#!/usr/bin/env node import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url); var KU=Object.create;var Dm=Object.defineProperty;var zU=Object.getOwnPropertyDescriptor;var jU=Object.getOwnPropertyNames;var XU=Object.getPrototypeOf,WU=Object.prototype.hasOwnProperty;var At=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Te=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var q=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Tr=(e,t)=>{for(var n in t)Dm(e,n,{get:t[n],enumerable:!0})},c8=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jU(t))!WU.call(e,i)&&i!==n&&Dm(e,i,{get:()=>t[i],enumerable:!(r=zU(t,i))||r.enumerable});return e};var jr=(e,t,n)=>(n=e!=null?KU(XU(e)):{},c8(t||!e||!e.__esModule?Dm(n,"default",{value:e,enumerable:!0}):n,e)),Ji=e=>c8(Dm({},"__esModule",{value:!0}),e);var y=Te(()=>{});var rv=q((dfe,nv)=>{"use strict";y();var ZU=Object.prototype.hasOwnProperty,cr="~";function Cp(){}Object.create&&(Cp.prototype=Object.create(null),new Cp().__proto__||(cr=!1));function JU(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function d8(e,t,n,r,i){if(typeof n!="function")throw new TypeError("The listener must be a function");var o=new JU(n,r||e,i),a=cr?cr+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],o]:e._events[a].push(o):(e._events[a]=o,e._eventsCount++),e}function Nm(e,t){--e._eventsCount===0?e._events=new Cp:delete e._events[t]}function Jn(){this._events=new Cp,this._eventsCount=0}Jn.prototype.eventNames=function(){var t=[],n,r;if(this._eventsCount===0)return t;for(r in n=this._events)ZU.call(n,r)&&t.push(cr?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(n)):t};Jn.prototype.listeners=function(t){var n=cr?cr+t:t,r=this._events[n];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,o=r.length,a=new Array(o);i{"use strict";y();Object.defineProperty(Nt,"__esModule",{value:!0});Nt.XRPLFaucetError=Nt.NotFoundError=Nt.ValidationError=Nt.ResponseFormatError=Nt.TimeoutError=Nt.RippledNotInitializedError=Nt.DisconnectedError=Nt.NotConnectedError=Nt.RippledError=Nt.ConnectionError=Nt.UnexpectedError=Nt.XrplError=void 0;var ba=class extends Error{constructor(t="",n){super(t),this.name=this.constructor.name,this.message=t,this.data=n,Error.captureStackTrace!=null&&Error.captureStackTrace(this,this.constructor)}toString(){let t=`[${this.name}(${this.message}`;return this.data&&(t+=`, ${JSON.stringify(this.data)}`),t+=")]",t}inspect(){return this.toString()}};Nt.XrplError=ba;var iv=class extends ba{};Nt.RippledError=iv;var ov=class extends ba{};Nt.UnexpectedError=ov;var ls=class extends ba{};Nt.ConnectionError=ls;var av=class extends ls{};Nt.NotConnectedError=av;var sv=class extends ls{};Nt.DisconnectedError=sv;var cv=class extends ls{};Nt.RippledNotInitializedError=cv;var lv=class extends ls{};Nt.TimeoutError=lv;var uv=class extends ls{};Nt.ResponseFormatError=uv;var dv=class extends ba{};Nt.ValidationError=dv;var fv=class extends ba{};Nt.XRPLFaucetError=fv;var pv=class extends ba{constructor(t="Not found"){super(t)}};Nt.NotFoundError=pv});var yv=q(Ca=>{"use strict";y();Object.defineProperty(Ca,"__esModule",{value:!0});Ca.DEFAULT_API_VERSION=Ca.RIPPLED_API_V2=Ca.RIPPLED_API_V1=void 0;Ca.RIPPLED_API_V1=1;Ca.RIPPLED_API_V2=2;Ca.DEFAULT_API_VERSION=Ca.RIPPLED_API_V2});var hv=q(Lm=>{"use strict";y();Object.defineProperty(Lm,"__esModule",{value:!0});Lm.AccountRootFlags=void 0;var f8;(function(e){e[e.lsfPasswordSpent=65536]="lsfPasswordSpent",e[e.lsfRequireDestTag=131072]="lsfRequireDestTag",e[e.lsfRequireAuth=262144]="lsfRequireAuth",e[e.lsfDisallowXRP=524288]="lsfDisallowXRP",e[e.lsfDisableMaster=1048576]="lsfDisableMaster",e[e.lsfNoFreeze=2097152]="lsfNoFreeze",e[e.lsfGlobalFreeze=4194304]="lsfGlobalFreeze",e[e.lsfDefaultRipple=8388608]="lsfDefaultRipple",e[e.lsfDepositAuth=16777216]="lsfDepositAuth",e[e.lsfAMM=33554432]="lsfAMM",e[e.lsfDisallowIncomingNFTokenOffer=67108864]="lsfDisallowIncomingNFTokenOffer",e[e.lsfDisallowIncomingCheck=134217728]="lsfDisallowIncomingCheck",e[e.lsfDisallowIncomingPayChan=268435456]="lsfDisallowIncomingPayChan",e[e.lsfDisallowIncomingTrustline=536870912]="lsfDisallowIncomingTrustline",e[e.lsfAllowTrustLineClawback=2147483648]="lsfAllowTrustLineClawback",e[e.lsfAllowTrustLineLocking=1073741824]="lsfAllowTrustLineLocking"})(f8||(Lm.AccountRootFlags=f8={}))});var mv=q(yu=>{"use strict";y();Object.defineProperty(yu,"__esModule",{value:!0});yu.MPTokenIssuanceImmutableFlags=yu.MPTokenIssuanceFlags=void 0;var p8;(function(e){e[e.lsfMPTLocked=1]="lsfMPTLocked",e[e.lsfMPTCanLock=2]="lsfMPTCanLock",e[e.lsfMPTRequireAuth=4]="lsfMPTRequireAuth",e[e.lsfMPTCanEscrow=8]="lsfMPTCanEscrow",e[e.lsfMPTCanTrade=16]="lsfMPTCanTrade",e[e.lsfMPTCanTransfer=32]="lsfMPTCanTransfer",e[e.lsfMPTCanClawback=64]="lsfMPTCanClawback",e[e.lsfMPTCanHoldConfidentialBalance=128]="lsfMPTCanHoldConfidentialBalance"})(p8||(yu.MPTokenIssuanceFlags=p8={}));var y8;(function(e){e[e.lsifMPTCanLock=2]="lsifMPTCanLock",e[e.lsifMPTRequireAuth=4]="lsifMPTRequireAuth",e[e.lsifMPTCanEscrow=8]="lsifMPTCanEscrow",e[e.lsifMPTCanTrade=16]="lsifMPTCanTrade",e[e.lsifMPTCanTransfer=32]="lsifMPTCanTransfer",e[e.lsifMPTCanClawback=64]="lsifMPTCanClawback",e[e.lsifMPTCanHoldConfidentialBalance=128]="lsifMPTCanHoldConfidentialBalance",e[e.lsifMPTMetadata=65536]="lsifMPTMetadata",e[e.lsifMPTTransferFee=131072]="lsifMPTTransferFee"})(y8||(yu.MPTokenIssuanceImmutableFlags=y8={}))});var vv={};Tr(vv,{abool:()=>QU,abytes:()=>St,aexists:()=>Ec,ahash:()=>va,anumber:()=>pn,aoutput:()=>Ap,asyncLoop:()=>Cv,byteSwap:()=>bv,byteSwap32:()=>g8,bytesToHex:()=>kc,checkOpts:()=>mu,clean:()=>yn,concatBytes:()=>Io,copyBytes:()=>gv,createHasher:()=>gu,createView:()=>Qi,hexToBytes:()=>_c,isBytes:()=>vp,isLE:()=>wv,kdfInputToBytes:()=>Ic,nextTick:()=>b8,oidNist:()=>Um,randomBytes:()=>us,rotl:()=>hu,rotr:()=>fi,swap32IfBE:()=>r$,swap8IfBE:()=>n$,u32:()=>t$,u8:()=>e$,utf8ToBytes:()=>Xr,validateObject:()=>o$});function vp(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function pn(e,t=""){if(typeof e!="number")throw new TypeError(Fm(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Fm(t)+"expected integer >= 0, got "+e);return e}function QU(e,t=""){if(typeof e!="boolean")throw new TypeError(Fm(t)+"expected boolean, got type="+typeof e);return e}function St(e,t,n=""){if(vp(e)&&(t===void 0||e.length===t))return e;t!==void 0&&pn(t,"length");let r=vp(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=Fm(n)+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)}function gv(e){return Uint8Array.from(St(e))}function va(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(pn(e.outputLen),pn(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function Ec(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Ap(e,t){St(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function e$(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function t$(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function yn(...e){for(let t=0;t>>t}function hu(e,t){return e<>>32-t>>>0}function bv(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function g8(e){for(let t=0;t=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function _c(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(w8)try{return Uint8Array.fromHex(e)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let i=0,o=0;it.setTimeout(n,0))}async function Cv(e,t,n,r){if(pn(e,"iters"),pn(t,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let i=Date.now();for(let o=0;o=0&&a{y();Ht=e=>Object.freeze(e());b$=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();T8=(()=>{try{let e=new TextDecoder;return e.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?e:void 0}catch{return}})(),Sv=8192;C$=Ht(()=>pi(Gr(4),kr("0123456789ABCDEF"))),v$=Ht(()=>pi(Gr(5),kr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Hm(5))),A$=Ht(()=>pi(Gr(5),kr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"))),S$=Ht(()=>pi(Gr(5),kr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Hm(5))),T$=Ht(()=>pi(Gr(5),kr("0123456789ABCDEFGHIJKLMNOPQRSTUV"))),E$=/^[\x00-\x7f]*$/,k$=Ht(()=>pi(Gr(5),kr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),O8(e=>{Wr("base32crockford.decode",e);let t=e.toUpperCase();if(e!==t&&!E$.test(e))throw new Error("base32crockford.decode: ASCII expected");return t.replace(/O/g,"0").replace(/[IL]/g,"1")}))),N8=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",_$=/[\t\n\f\r ]/,L8=(e,t)=>{Wr("base64",e);let n=t?"base64url":"base64";if(e.length>0&&_$.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:n,lastChunkHandling:"strict"})},B8=Ht(()=>pi(Gr(6),kr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Hm(6))),F8=Ht(()=>pi(Gr(6),kr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Hm(6))),I$=Ht(()=>N8?{encode(e){return Er(e),e.toBase64()},decode(e){return L8(e,!1)}}:B8),P$=Ht(()=>pi(Gr(6),kr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"))),x$=Ht(()=>N8?{encode(e){return Er(e),e.toBase64({alphabet:"base64url"})},decode(e){return L8(e,!0)}}:F8),M$=Ht(()=>pi(Gr(6),kr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"))),O$=656356768,D$=60466176,k8=65536,R$=2048,N$=4096,U8=(e,t)=>({encode:n=>{Er(n);let r=n.length;if(r===0)return new Uint8Array(0);if(r>=k8)throw new Error("invalid length");let i=0;for(;i=i;g=Math.floor(g/e))p[h--]=g%e;return p},decode:n=>{Er(n);let r=n.length;if(r===0)return new Uint8Array(0);if(r>=k8)throw new Error("invalid length");let i=0;for(;i=e)throw new Error(`invalid integer: ${T}`);p=p*e+T,h*=e}c=5;let g=p;for(let w=0;w0;g=Math.floor(g/65536))o[a++]=g%65536}let l=a===0?1:a*2-(o[a-1]<256?1:0),u=new Uint8Array(i+l),d=u.length-1;for(let p=0;p=i&&(u[d--]=h>>8)}return u}}),$8=(e,t)=>{let n=kr(t);return{encode(r){if(Er(r),r.length>R$)throw new Error("invalid length");return n.encode(e.encode(r))},decode(r){if(Wr("baseN.decode",r),r.length>N$)throw new Error("invalid length");return e.decode(n.decode(r))}}},q8=U8(58,O$),L$=Ht(()=>$8(U8(36,D$),"0123456789abcdefghijklmnopqrstuvwxyz")),kv=e=>$8(q8,e),$m=Ht(()=>kv("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),B$=Ht(()=>kv("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),F$=Ht(()=>kv("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")),_8=[0,2,3,5,6,7,9,10,11],U$=Ht(()=>({encode(e){Er(e);let t="";for(let n=0;n{qm(e);let t=e;return pi(R8(4,n=>t(t(n))),$m)},$$=Vm,Tv=kr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),q$=/^[\x21-\x60\x7b-\x7e]+$/;P8=[996825010,642813549,513874426,1027748829,705979059];V$=Ht(()=>H8("bech32")),K$=Ht(()=>H8("bech32m")),z$=Ht(()=>({encode(e){Er(e);for(let t=0;t127)throw new RangeError(`non-ASCII byte ${n} at ${t}`)}return D8(e)},decode(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);let t=new Uint8Array(e.length);for(let n=0;n127)throw new RangeError(`non-ASCII char "${e[n]}" (${r}) at ${n}`);t[n]=r}return t}})),V8=e=>{try{return encodeURI(e)!==null}catch{return!1}},K8=typeof"".isWellFormed=="function"?e=>e.isWellFormed():V8,wu=e=>new TypeError(`invalid utf8 at byte ${e}`),Ev=Ht(()=>({encode(e){Er(e);let t="";for(let n=0;n=e.length)throw wu(n-1);let i=e[n++];if((i&192)!==128)throw wu(n-1);let o=(r&31)<<6|i&63;if(r>=224){if(n>=e.length)throw wu(n-1);let a=e[n++];if((a&192)!==128||r===224&&i<160||r===237&&i>=160)throw wu(n-1);if(o=(r&15)<<12|(i&63)<<6|a&63,r>=240){if(n>=e.length)throw wu(n-1);let s=e[n++];if(r>244||(s&192)!==128||r===240&&i<144||r===244&&i>=144)throw wu(n-1);o=(r&7)<<18|(i&63)<<12|(a&63)<<6|s&63}}o<65536?t+=String.fromCharCode(o):(o-=65536,t+=String.fromCharCode((o>>10)+55296,(o&1023)+56320))}return t},decode(e){if(Wr("utf8",e),!K8(e))throw new TypeError("utf8 expected well-formed string");let t=new Uint8Array(e.length*3),n=0;for(let r=0;r=55296&&i<=57343){let o=e.charCodeAt(++r);i=65536+(i-55296<<10)+o-56320}i>=65536?(t[n++]=i>>18|240,t[n++]=i>>12&63|128):i>=2048?t[n++]=i>>12|224:t[n++]=i>>6|192,i>=2048&&(t[n++]=i>>6&63|128),t[n++]=i&63|128}return t.subarray(0,n)}})),j$=Ht(()=>{let e,t,n={encode(r){return Er(r),(t||(t=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}))).decode(r)},decode(r){if(Wr("utf8",r),!K8(r))throw new TypeError("utf8 expected well-formed string");return(e||(e=new TextEncoder)).encode(r)}};return{encode:typeof TextDecoder=="function"?n.encode:Ev.encode,decode:typeof TextEncoder=="function"?n.decode:Ev.decode}}),z8=Ht(()=>pi(Gr(4),kr("0123456789abcdef",{A:"a",B:"b",C:"c",D:"d",E:"e",F:"f"}),O8(e=>{if(Wr("hex",e),e.length%2!==0)throw new TypeError(`hex.decode: odd-length string (${e.length})`);return e}))),X$=Ht(()=>({alphabet:kr,base64Fallback:B8,base64urlFallback:F8,hexFallback:z8,radix2:Gr,radix58:q8,checksum:R8,utf8Fallback:Ev,_isWellFormedShim:V8})),W$=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",G$={encode(e){return Er(e),e.toHex()},decode(e){return Wr("hex",e),Uint8Array.fromHex(e)}},Y$=Ht(()=>W$?G$:z8)});var X8=q(Iv=>{"use strict";y();Object.defineProperty(Iv,"__esModule",{value:!0});var Z$=(Hn(),Ji(vv));function J$(e){return Array.isArray(e)?new Uint8Array(e):typeof e=="string"?(0,Z$.utf8ToBytes)(e):e}Iv.default=J$});var Km=q(Ep=>{"use strict";y();var Q$=Ep&&Ep.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ep,"__esModule",{value:!0});var W8=Q$(X8());function eq(e,t){function n(r){return t(e).update((0,W8.default)(r)).digest()}return n.create=()=>{let r=t(e);return{update(i){return r.update((0,W8.default)(i)),this},digest(){return r.digest()}}},n}Ep.default=eq});var Pv=q(bu=>{"use strict";y();var tq=bu&&bu.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(bu,"__esModule",{value:!0});bu.sha256=void 0;var nq=At("crypto"),rq=tq(Km());bu.sha256=(0,rq.default)("sha256",nq.createHash)});var G8=q(Cu=>{"use strict";y();Object.defineProperty(Cu,"__esModule",{value:!0});Cu.concatArgs=Cu.arrayEqual=void 0;function iq(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;roq(t)?[t]:Array.from(t))}Cu.concatArgs=aq});var r5=q(Lt=>{"use strict";y();Object.defineProperty(Lt,"__esModule",{value:!0});Lt.isValidClassicAddress=Lt.decodeAccountPublic=Lt.encodeAccountPublic=Lt.encodeNodePublic=Lt.decodeNodePublic=Lt.decodeAddress=Lt.decodeAccountID=Lt.encodeAddress=Lt.encodeAccountID=Lt.decodeSeed=Lt.encodeSeed=Lt.codec=void 0;var sq=(_v(),Ji(j8)),cq=Pv(),zm=G8(),xv=class{constructor(t){this._sha256=t.sha256,this._codec=sq.base58xrp}encode(t,n){let r=n.versions;return this._encodeVersioned(t,r,n.expectedLength)}decode(t,n){var r;let i=n.versions,o=n.versionTypes,a=this.decodeChecked(t);if(i.length>1&&!n.expectedLength)throw new Error("expectedLength is required because there are >= 2 possible versions");let s=typeof i[0]=="number"?1:i[0].length,c=(r=n.expectedLength)!==null&&r!==void 0?r:a.length-s,l=a.slice(0,-c),u=a.slice(-c);for(let d=0;d= 5");if(!this._verifyCheckSum(n))throw new Error("checksum_invalid");return n.slice(0,-4)}_encodeVersioned(t,n,r){if(!n5(t,r))throw new Error("unexpected_payload_length: bytes.length does not match expectedLength. Ensure that the bytes are a Uint8Array.");return this.encodeChecked((0,zm.concatArgs)(n,t))}_encodeRaw(t){return this._codec.encode(Uint8Array.from(t))}_decodeRaw(t){return this._codec.decode(t)}_verifyCheckSum(t){let n=this._sha256(this._sha256(t.slice(0,-4))).slice(0,4),r=t.slice(-4);return(0,zm.arrayEqual)(n,r)}},Y8=0,Z8=35,J8=33,Q8=28,e5=[1,225,75],lq={sha256:cq.sha256},Aa=new xv(lq);Lt.codec=Aa;function uq(e,t){if(!n5(e,16))throw new Error("entropy must have length 16");let n={expectedLength:16,versions:t==="ed25519"?e5:[J8]};return Aa.encode(e,n)}Lt.encodeSeed=uq;function dq(e,t={versionTypes:["ed25519","secp256k1"],versions:[e5,J8],expectedLength:16}){return Aa.decode(e,t)}Lt.decodeSeed=dq;function t5(e){let t={versions:[Y8],expectedLength:20};return Aa.encode(e,t)}Lt.encodeAccountID=t5;Lt.encodeAddress=t5;function Mv(e){let t={versions:[Y8],expectedLength:20};return Aa.decode(e,t).bytes}Lt.decodeAccountID=Mv;Lt.decodeAddress=Mv;function fq(e){let t={versions:[Q8],expectedLength:33};return Aa.decode(e,t).bytes}Lt.decodeNodePublic=fq;function pq(e){let t={versions:[Q8],expectedLength:33};return Aa.encode(e,t)}Lt.encodeNodePublic=pq;function yq(e){let t={versions:[Z8],expectedLength:33};return Aa.encode(e,t)}Lt.encodeAccountPublic=yq;function hq(e){let t={versions:[Z8],expectedLength:33};return Aa.decode(e,t).bytes}Lt.decodeAccountPublic=hq;function mq(e){try{Mv(e)}catch{return!1}return!0}Lt.isValidClassicAddress=mq;function n5(e,t){return"byteLength"in e?e.byteLength===t:e.length===t}});var lr=q(ft=>{"use strict";y();Object.defineProperty(ft,"__esModule",{value:!0});ft.isValidXAddress=ft.decodeXAddress=ft.xAddressToClassicAddress=ft.encodeXAddress=ft.classicAddressToXAddress=ft.isValidClassicAddress=ft.decodeAccountPublic=ft.encodeAccountPublic=ft.decodeNodePublic=ft.encodeNodePublic=ft.decodeAccountID=ft.encodeAccountID=ft.decodeSeed=ft.encodeSeed=ft.codec=void 0;var kp=We(),_r=r5();Object.defineProperty(ft,"codec",{enumerable:!0,get:function(){return _r.codec}});Object.defineProperty(ft,"encodeSeed",{enumerable:!0,get:function(){return _r.encodeSeed}});Object.defineProperty(ft,"decodeSeed",{enumerable:!0,get:function(){return _r.decodeSeed}});Object.defineProperty(ft,"encodeAccountID",{enumerable:!0,get:function(){return _r.encodeAccountID}});Object.defineProperty(ft,"decodeAccountID",{enumerable:!0,get:function(){return _r.decodeAccountID}});Object.defineProperty(ft,"encodeNodePublic",{enumerable:!0,get:function(){return _r.encodeNodePublic}});Object.defineProperty(ft,"decodeNodePublic",{enumerable:!0,get:function(){return _r.decodeNodePublic}});Object.defineProperty(ft,"encodeAccountPublic",{enumerable:!0,get:function(){return _r.encodeAccountPublic}});Object.defineProperty(ft,"decodeAccountPublic",{enumerable:!0,get:function(){return _r.decodeAccountPublic}});Object.defineProperty(ft,"isValidClassicAddress",{enumerable:!0,get:function(){return _r.isValidClassicAddress}});var jm={main:Uint8Array.from([5,68]),test:Uint8Array.from([4,147])},gq=4294967295;function wq(e,t,n){let r=(0,_r.decodeAccountID)(e);return i5(r,t,n)}ft.classicAddressToXAddress=wq;function i5(e,t,n){if(e.length!==20)throw new Error("Account ID must be 20 bytes");if(t!==!1&&t>gq)throw new Error("Invalid tag");let r=t||0,i=t===!1||t==null?0:1,o=(0,kp.concat)([n?jm.test:jm.main,e,Uint8Array.from([i,r&255,r>>8&255,r>>16&255,r>>24&255,0,0,0,0])]);return _r.codec.encodeChecked(o)}ft.encodeXAddress=i5;function bq(e){let{accountId:t,tag:n,test:r}=Ov(e);return{classicAddress:(0,_r.encodeAccountID)(t),tag:n,test:r}}ft.xAddressToClassicAddress=bq;function Ov(e){let t=_r.codec.decodeChecked(e),n=Cq(t),r=t.slice(2,22),i=vq(t);return{accountId:r,tag:i,test:n}}ft.decodeXAddress=Ov;function Cq(e){let t=e.slice(0,2);if((0,kp.equal)(jm.main,t))return!1;if((0,kp.equal)(jm.test,t))return!0;throw new Error("Invalid X-address: bad prefix")}function vq(e){let t=e[22];if(t>=2)throw new Error("Unsupported X-address");if(t===1)return e[23]+e[24]*256+e[25]*65536+e[26]*16777216;if(t!==0)throw new Error("flag must be zero to indicate no tag");if(!(0,kp.equal)((0,kp.hexToBytes)("0000000000000000"),e.slice(23,31)))throw new Error("remaining bytes must be zero");return!1}function Aq(e){try{Ov(e)}catch{return!1}return!0}ft.isValidXAddress=Aq});var o5=q((Ufe,Sq)=>{Sq.exports={ACCOUNT_SET_FLAGS:{asfAccountTxnID:5,asfAllowTrustLineClawback:16,asfAllowTrustLineLocking:17,asfAuthorizedNFTokenMinter:10,asfDefaultRipple:8,asfDepositAuth:9,asfDisableMaster:4,asfDisallowIncomingCheck:13,asfDisallowIncomingNFTokenOffer:12,asfDisallowIncomingPayChan:14,asfDisallowIncomingTrustline:15,asfDisallowXRP:3,asfGlobalFreeze:7,asfNoFreeze:6,asfRequireAuth:2,asfRequireDest:1},FIELDS:[["Invalid",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:-1,type:"Unknown"}],["ObjectEndMarker",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"STObject"}],["ArrayEndMarker",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"STArray"}],["taker_gets_funded",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:258,type:"Amount"}],["taker_pays_funded",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:259,type:"Amount"}],["Generic",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:0,type:"Unknown"}],["LedgerEntryType",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"UInt16"}],["TransactionType",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"UInt16"}],["SignerWeight",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"UInt16"}],["TransferFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"UInt16"}],["TradingFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"UInt16"}],["DiscountedFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"UInt16"}],["Version",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"UInt16"}],["LedgerFixType",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:21,type:"UInt16"}],["ManagementFeeRate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:22,type:"UInt16"}],["NetworkID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"UInt32"}],["Flags",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"UInt32"}],["SourceTag",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"UInt32"}],["Sequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"UInt32"}],["PreviousTxnLgrSeq",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"UInt32"}],["LedgerSequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"UInt32"}],["CloseTime",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:7,type:"UInt32"}],["ParentCloseTime",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:8,type:"UInt32"}],["SigningTime",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:9,type:"UInt32"}],["Expiration",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:10,type:"UInt32"}],["TransferRate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:11,type:"UInt32"}],["WalletSize",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:12,type:"UInt32"}],["OwnerCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:13,type:"UInt32"}],["DestinationTag",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:14,type:"UInt32"}],["LastUpdateTime",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:15,type:"UInt32"}],["HighQualityIn",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"UInt32"}],["HighQualityOut",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:17,type:"UInt32"}],["LowQualityIn",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:18,type:"UInt32"}],["LowQualityOut",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:19,type:"UInt32"}],["QualityIn",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:20,type:"UInt32"}],["QualityOut",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:21,type:"UInt32"}],["StampEscrow",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:22,type:"UInt32"}],["BondAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:23,type:"UInt32"}],["LoadFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:24,type:"UInt32"}],["OfferSequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:25,type:"UInt32"}],["FirstLedgerSequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:26,type:"UInt32"}],["LastLedgerSequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:27,type:"UInt32"}],["TransactionIndex",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:28,type:"UInt32"}],["OperationLimit",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:29,type:"UInt32"}],["ReferenceFeeUnits",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:30,type:"UInt32"}],["ReserveBase",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:31,type:"UInt32"}],["ReserveIncrement",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:32,type:"UInt32"}],["SetFlag",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:33,type:"UInt32"}],["ClearFlag",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:34,type:"UInt32"}],["SignerQuorum",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:35,type:"UInt32"}],["CancelAfter",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:36,type:"UInt32"}],["FinishAfter",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:37,type:"UInt32"}],["SignerListID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:38,type:"UInt32"}],["SettleDelay",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:39,type:"UInt32"}],["TicketCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:40,type:"UInt32"}],["TicketSequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:41,type:"UInt32"}],["NFTokenTaxon",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:42,type:"UInt32"}],["MintedNFTokens",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:43,type:"UInt32"}],["BurnedNFTokens",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:44,type:"UInt32"}],["VoteWeight",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:48,type:"UInt32"}],["FirstNFTokenSequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:50,type:"UInt32"}],["OracleDocumentID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:51,type:"UInt32"}],["PermissionValue",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:52,type:"UInt32"}],["ImmutableFlags",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:53,type:"UInt32"}],["StartDate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:54,type:"UInt32"}],["PaymentInterval",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:55,type:"UInt32"}],["GracePeriod",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:56,type:"UInt32"}],["PreviousPaymentDueDate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:57,type:"UInt32"}],["NextPaymentDueDate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:58,type:"UInt32"}],["PaymentRemaining",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:59,type:"UInt32"}],["PaymentTotal",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:60,type:"UInt32"}],["LoanSequence",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:61,type:"UInt32"}],["CoverRateMinimum",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:62,type:"UInt32"}],["CoverRateLiquidation",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:63,type:"UInt32"}],["OverpaymentFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:64,type:"UInt32"}],["InterestRate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:65,type:"UInt32"}],["LateInterestRate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:66,type:"UInt32"}],["CloseInterestRate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:67,type:"UInt32"}],["OverpaymentInterestRate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:68,type:"UInt32"}],["ConfidentialBalanceVersion",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:69,type:"UInt32"}],["SponsoredOwnerCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:70,type:"UInt32"}],["SponsoringOwnerCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:71,type:"UInt32"}],["SponsoringAccountCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:72,type:"UInt32"}],["RemainingOwnerCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:73,type:"UInt32"}],["SponsorFlags",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:74,type:"UInt32"}],["SubscriptionDate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:75,type:"UInt32"}],["RedemptionDate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:76,type:"UInt32"}],["IssuerKeyEpoch",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:77,type:"UInt32"}],["AuditorKeyEpoch",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:78,type:"UInt32"}],["IssuerKeyMirrorEpoch",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:79,type:"UInt32"}],["AuditorKeyMirrorEpoch",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:80,type:"UInt32"}],["IndexNext",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"UInt64"}],["IndexPrevious",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"UInt64"}],["BookNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"UInt64"}],["OwnerNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"UInt64"}],["BaseFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"UInt64"}],["ExchangeRate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"UInt64"}],["LowNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:7,type:"UInt64"}],["HighNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:8,type:"UInt64"}],["DestinationNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:9,type:"UInt64"}],["Cookie",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:10,type:"UInt64"}],["ServerVersion",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:11,type:"UInt64"}],["NFTokenOfferNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:12,type:"UInt64"}],["EmitBurden",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:13,type:"UInt64"}],["ReferenceCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:19,type:"UInt64"}],["XChainClaimID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:20,type:"UInt64"}],["XChainAccountCreateCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:21,type:"UInt64"}],["XChainAccountClaimCount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:22,type:"UInt64"}],["AssetPrice",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:23,type:"UInt64"}],["MaximumAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:24,type:"UInt64"}],["OutstandingAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:25,type:"UInt64"}],["MPTAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:26,type:"UInt64"}],["IssuerNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:27,type:"UInt64"}],["SubjectNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:28,type:"UInt64"}],["LockedAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:29,type:"UInt64"}],["VaultNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:30,type:"UInt64"}],["LoanBrokerNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:31,type:"UInt64"}],["ConfidentialOutstandingAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:32,type:"UInt64"}],["SponseeNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:33,type:"UInt64"}],["EmailHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Hash128"}],["LedgerHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Hash256"}],["ParentHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Hash256"}],["TransactionHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"Hash256"}],["AccountHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"Hash256"}],["PreviousTxnID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"Hash256"}],["LedgerIndex",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"Hash256"}],["WalletLocator",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:7,type:"Hash256"}],["RootIndex",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:8,type:"Hash256"}],["AccountTxnID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:9,type:"Hash256"}],["NFTokenID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:10,type:"Hash256"}],["EmitParentTxnID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:11,type:"Hash256"}],["EmitNonce",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:12,type:"Hash256"}],["EmitHookHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:13,type:"Hash256"}],["AMMID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:14,type:"Hash256"}],["BookDirectory",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"Hash256"}],["InvoiceID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:17,type:"Hash256"}],["Nickname",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:18,type:"Hash256"}],["Amendment",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:19,type:"Hash256"}],["Digest",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:21,type:"Hash256"}],["Channel",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:22,type:"Hash256"}],["ConsensusHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:23,type:"Hash256"}],["CheckID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:24,type:"Hash256"}],["ValidatedHash",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:25,type:"Hash256"}],["PreviousPageMin",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:26,type:"Hash256"}],["NextPageMin",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:27,type:"Hash256"}],["NFTokenBuyOffer",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:28,type:"Hash256"}],["NFTokenSellOffer",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:29,type:"Hash256"}],["DomainID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:34,type:"Hash256"}],["VaultID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:35,type:"Hash256"}],["ParentBatchID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:36,type:"Hash256"}],["LoanBrokerID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:37,type:"Hash256"}],["LoanID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:38,type:"Hash256"}],["ReferenceHolding",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:39,type:"Hash256"}],["BlindingFactor",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:40,type:"Hash256"}],["ObjectID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:41,type:"Hash256"}],["hash",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:257,type:"Hash256"}],["index",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:258,type:"Hash256"}],["Amount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Amount"}],["Balance",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Amount"}],["LimitAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"Amount"}],["TakerPays",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"Amount"}],["TakerGets",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"Amount"}],["LowLimit",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"Amount"}],["HighLimit",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:7,type:"Amount"}],["Fee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:8,type:"Amount"}],["SendMax",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:9,type:"Amount"}],["DeliverMin",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:10,type:"Amount"}],["Amount2",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:11,type:"Amount"}],["BidMin",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:12,type:"Amount"}],["BidMax",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:13,type:"Amount"}],["MinimumOffer",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"Amount"}],["RippleEscrow",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:17,type:"Amount"}],["DeliveredAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:18,type:"Amount"}],["NFTokenBrokerFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:19,type:"Amount"}],["BaseFeeDrops",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:22,type:"Amount"}],["ReserveBaseDrops",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:23,type:"Amount"}],["ReserveIncrementDrops",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:24,type:"Amount"}],["LPTokenOut",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:25,type:"Amount"}],["LPTokenIn",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:26,type:"Amount"}],["EPrice",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:27,type:"Amount"}],["Price",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:28,type:"Amount"}],["SignatureReward",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:29,type:"Amount"}],["MinAccountCreateAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:30,type:"Amount"}],["LPTokenBalance",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:31,type:"Amount"}],["FeeAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:32,type:"Amount"}],["MaxFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:33,type:"Amount"}],["FeeAmountDelta",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:34,type:"Amount"}],["PublicKey",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:1,type:"Blob"}],["MessageKey",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:2,type:"Blob"}],["SigningPubKey",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:3,type:"Blob"}],["TxnSignature",{isSerialized:!0,isSigningField:!1,isVLEncoded:!0,nth:4,type:"Blob"}],["URI",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:5,type:"Blob"}],["Signature",{isSerialized:!0,isSigningField:!1,isVLEncoded:!0,nth:6,type:"Blob"}],["Domain",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:7,type:"Blob"}],["FundCode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:8,type:"Blob"}],["RemoveCode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:9,type:"Blob"}],["ExpireCode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:10,type:"Blob"}],["CreateCode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:11,type:"Blob"}],["MemoType",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:12,type:"Blob"}],["MemoData",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:13,type:"Blob"}],["MemoFormat",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:14,type:"Blob"}],["Fulfillment",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:16,type:"Blob"}],["Condition",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:17,type:"Blob"}],["MasterSignature",{isSerialized:!0,isSigningField:!1,isVLEncoded:!0,nth:18,type:"Blob"}],["UNLModifyValidator",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:19,type:"Blob"}],["ValidatorToDisable",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:20,type:"Blob"}],["ValidatorToReEnable",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:21,type:"Blob"}],["DIDDocument",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:26,type:"Blob"}],["Data",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:27,type:"Blob"}],["AssetClass",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:28,type:"Blob"}],["Provider",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:29,type:"Blob"}],["MPTokenMetadata",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:30,type:"Blob"}],["CredentialType",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:31,type:"Blob"}],["ConfidentialBalanceInbox",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:32,type:"Blob"}],["ConfidentialBalanceSpending",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:33,type:"Blob"}],["IssuerEncryptedBalance",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:34,type:"Blob"}],["IssuerEncryptionKey",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:35,type:"Blob"}],["HolderEncryptionKey",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:36,type:"Blob"}],["ZKProof",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:37,type:"Blob"}],["HolderEncryptedAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:38,type:"Blob"}],["IssuerEncryptedAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:39,type:"Blob"}],["SenderEncryptedAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:40,type:"Blob"}],["DestinationEncryptedAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:41,type:"Blob"}],["AuditorEncryptedBalance",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:42,type:"Blob"}],["AuditorEncryptedAmount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:43,type:"Blob"}],["AuditorEncryptionKey",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:44,type:"Blob"}],["AmountCommitment",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:45,type:"Blob"}],["BalanceCommitment",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:46,type:"Blob"}],["Account",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:1,type:"AccountID"}],["Owner",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:2,type:"AccountID"}],["Destination",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:3,type:"AccountID"}],["Issuer",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:4,type:"AccountID"}],["Authorize",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:5,type:"AccountID"}],["Unauthorize",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:6,type:"AccountID"}],["RegularKey",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:8,type:"AccountID"}],["NFTokenMinter",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:9,type:"AccountID"}],["EmitCallback",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:10,type:"AccountID"}],["Holder",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:11,type:"AccountID"}],["Delegate",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:12,type:"AccountID"}],["OtherChainSource",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:18,type:"AccountID"}],["OtherChainDestination",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:19,type:"AccountID"}],["AttestationSignerAccount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:20,type:"AccountID"}],["AttestationRewardAccount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:21,type:"AccountID"}],["LockingChainDoor",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:22,type:"AccountID"}],["IssuingChainDoor",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:23,type:"AccountID"}],["Subject",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:24,type:"AccountID"}],["Borrower",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:25,type:"AccountID"}],["Counterparty",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:26,type:"AccountID"}],["Sponsor",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:27,type:"AccountID"}],["HighSponsor",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:28,type:"AccountID"}],["LowSponsor",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:29,type:"AccountID"}],["CounterpartySponsor",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:30,type:"AccountID"}],["Sponsee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:31,type:"AccountID"}],["Number",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Number"}],["AssetsAvailable",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Number"}],["AssetsMaximum",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"Number"}],["AssetsTotal",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"Number"}],["LossUnrealized",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"Number"}],["DebtTotal",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"Number"}],["DebtMaximum",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:7,type:"Number"}],["CoverAvailable",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:8,type:"Number"}],["LoanOriginationFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:9,type:"Number"}],["LoanServiceFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:10,type:"Number"}],["LatePaymentFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:11,type:"Number"}],["ClosePaymentFee",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:12,type:"Number"}],["PrincipalOutstanding",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:13,type:"Number"}],["PrincipalRequested",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:14,type:"Number"}],["TotalValueOutstanding",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:15,type:"Number"}],["PeriodicPayment",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"Number"}],["ManagementFeeOutstanding",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:17,type:"Number"}],["LoanScale",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Int32"}],["RemainingOwnerCountDelta",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Int32"}],["TransactionMetaData",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"STObject"}],["CreatedNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"STObject"}],["DeletedNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"STObject"}],["ModifiedNode",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"STObject"}],["PreviousFields",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"STObject"}],["FinalFields",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:7,type:"STObject"}],["NewFields",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:8,type:"STObject"}],["TemplateEntry",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:9,type:"STObject"}],["Memo",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:10,type:"STObject"}],["SignerEntry",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:11,type:"STObject"}],["NFToken",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:12,type:"STObject"}],["EmitDetails",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:13,type:"STObject"}],["Permission",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:15,type:"STObject"}],["Signer",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"STObject"}],["Majority",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:18,type:"STObject"}],["DisabledValidator",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:19,type:"STObject"}],["VoteEntry",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:25,type:"STObject"}],["AuctionSlot",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:26,type:"STObject"}],["AuthAccount",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:27,type:"STObject"}],["XChainClaimProofSig",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:28,type:"STObject"}],["XChainCreateAccountProofSig",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:29,type:"STObject"}],["XChainClaimAttestationCollectionElement",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:30,type:"STObject"}],["XChainCreateAccountAttestationCollectionElement",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:31,type:"STObject"}],["PriceData",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:32,type:"STObject"}],["Credential",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:33,type:"STObject"}],["RawTransaction",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:34,type:"STObject"}],["BatchSigner",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:35,type:"STObject"}],["Book",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:36,type:"STObject"}],["CounterpartySignature",{isSerialized:!0,isSigningField:!1,isVLEncoded:!1,nth:37,type:"STObject"}],["SponsorSignature",{isSerialized:!0,isSigningField:!1,isVLEncoded:!1,nth:38,type:"STObject"}],["Signers",{isSerialized:!0,isSigningField:!1,isVLEncoded:!1,nth:3,type:"STArray"}],["SignerEntries",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"STArray"}],["Template",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"STArray"}],["Necessary",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"STArray"}],["Sufficient",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:7,type:"STArray"}],["AffectedNodes",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:8,type:"STArray"}],["Memos",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:9,type:"STArray"}],["NFTokens",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:10,type:"STArray"}],["VoteSlots",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:12,type:"STArray"}],["AdditionalBooks",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:13,type:"STArray"}],["Majorities",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"STArray"}],["DisabledValidators",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:17,type:"STArray"}],["XChainClaimAttestations",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:21,type:"STArray"}],["XChainCreateAccountAttestations",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:22,type:"STArray"}],["PriceDataSeries",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:24,type:"STArray"}],["AuthAccounts",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:25,type:"STArray"}],["AuthorizeCredentials",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:26,type:"STArray"}],["UnauthorizeCredentials",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:27,type:"STArray"}],["AcceptedCredentials",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:28,type:"STArray"}],["Permissions",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:29,type:"STArray"}],["RawTransactions",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:30,type:"STArray"}],["BatchSigners",{isSerialized:!0,isSigningField:!1,isVLEncoded:!1,nth:31,type:"STArray"}],["CloseResolution",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"UInt8"}],["Method",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"UInt8"}],["TransactionResult",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"UInt8"}],["Scale",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"UInt8"}],["AssetScale",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:5,type:"UInt8"}],["LEVersion",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:6,type:"UInt8"}],["TickSize",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:16,type:"UInt8"}],["UNLModifyDisabling",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:17,type:"UInt8"}],["WasLockingChainSend",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:19,type:"UInt8"}],["WithdrawalPolicy",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:20,type:"UInt8"}],["ContractResult",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:21,type:"UInt8"}],["VaultKind",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:22,type:"UInt8"}],["TakerPaysCurrency",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Hash160"}],["TakerPaysIssuer",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Hash160"}],["TakerGetsCurrency",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"Hash160"}],["TakerGetsIssuer",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"Hash160"}],["Paths",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"PathSet"}],["Indexes",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:1,type:"Vector256"}],["Hashes",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:2,type:"Vector256"}],["Amendments",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:3,type:"Vector256"}],["NFTokenOffers",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:4,type:"Vector256"}],["CredentialIDs",{isSerialized:!0,isSigningField:!0,isVLEncoded:!0,nth:5,type:"Vector256"}],["MPTokenIssuanceID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Hash192"}],["ShareMPTID",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Hash192"}],["TakerPaysMPT",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"Hash192"}],["TakerGetsMPT",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"Hash192"}],["LockingChainIssue",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Issue"}],["IssuingChainIssue",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Issue"}],["Asset",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:3,type:"Issue"}],["Asset2",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:4,type:"Issue"}],["XChainBridge",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"XChainBridge"}],["BaseAsset",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:1,type:"Currency"}],["QuoteAsset",{isSerialized:!0,isSigningField:!0,isVLEncoded:!1,nth:2,type:"Currency"}],["Transaction",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:257,type:"Transaction"}],["LedgerEntry",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:257,type:"LedgerEntry"}],["Validation",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:257,type:"Validation"}],["Metadata",{isSerialized:!1,isSigningField:!1,isVLEncoded:!1,nth:257,type:"Metadata"}]],LEDGER_ENTRY_FLAGS:{AccountRoot:{lsfAllowTrustLineClawback:2147483648,lsfAllowTrustLineLocking:1073741824,lsfDefaultRipple:8388608,lsfDepositAuth:16777216,lsfDisableMaster:1048576,lsfDisallowIncomingCheck:134217728,lsfDisallowIncomingNFTokenOffer:67108864,lsfDisallowIncomingPayChan:268435456,lsfDisallowIncomingTrustline:536870912,lsfDisallowXRP:524288,lsfGlobalFreeze:4194304,lsfNoFreeze:2097152,lsfPasswordSpent:65536,lsfRequireAuth:262144,lsfRequireDestTag:131072},Credential:{lsfAccepted:65536},DirNode:{lsfNFTokenBuyOffers:1,lsfNFTokenSellOffers:2},Loan:{lsfLoanDefault:65536,lsfLoanImpaired:131072,lsfLoanOverpayment:262144},MPToken:{lsfMPTAMM:4,lsfMPTAuthorized:2,lsfMPTLocked:1},MPTokenIssuance:{lsfMPTCanClawback:64,lsfMPTCanEscrow:8,lsfMPTCanHoldConfidentialBalance:128,lsfMPTCanLock:2,lsfMPTCanTrade:16,lsfMPTCanTransfer:32,lsfMPTLocked:1,lsfMPTRequireAuth:4},NFTokenOffer:{lsfSellNFToken:1},Offer:{lsfHybrid:262144,lsfPassive:65536,lsfSell:131072},RippleState:{lsfAMMNode:16777216,lsfHighAuth:524288,lsfHighDeepFreeze:67108864,lsfHighFreeze:8388608,lsfHighNoRipple:2097152,lsfHighReserve:131072,lsfLowAuth:262144,lsfLowDeepFreeze:33554432,lsfLowFreeze:4194304,lsfLowNoRipple:1048576,lsfLowReserve:65536},SignerList:{lsfOneOwnerCount:65536},Sponsorship:{lsfSponsorshipRequireSignForFee:65536,lsfSponsorshipRequireSignForReserve:131072},Vault:{lsfVaultPrivate:65536}},LEDGER_ENTRY_FORMATS:{AMM:[{name:"Account",optionality:0},{name:"TradingFee",optionality:2},{name:"VoteSlots",optionality:1},{name:"AuctionSlot",optionality:1},{name:"LPTokenBalance",optionality:0},{name:"Asset",optionality:0},{name:"Asset2",optionality:0},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:1},{name:"PreviousTxnLgrSeq",optionality:1}],AccountRoot:[{name:"Account",optionality:0},{name:"Sequence",optionality:0},{name:"Balance",optionality:0},{name:"OwnerCount",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"AccountTxnID",optionality:1},{name:"RegularKey",optionality:1},{name:"EmailHash",optionality:1},{name:"WalletLocator",optionality:1},{name:"WalletSize",optionality:1},{name:"MessageKey",optionality:1},{name:"TransferRate",optionality:1},{name:"Domain",optionality:1},{name:"TickSize",optionality:1},{name:"TicketCount",optionality:1},{name:"NFTokenMinter",optionality:1},{name:"MintedNFTokens",optionality:2},{name:"BurnedNFTokens",optionality:2},{name:"FirstNFTokenSequence",optionality:1},{name:"SponsoredOwnerCount",optionality:2},{name:"SponsoringOwnerCount",optionality:2},{name:"SponsoringAccountCount",optionality:2},{name:"AMMID",optionality:1},{name:"VaultID",optionality:1},{name:"LoanBrokerID",optionality:1}],Amendments:[{name:"Amendments",optionality:1},{name:"Majorities",optionality:1},{name:"PreviousTxnID",optionality:1},{name:"PreviousTxnLgrSeq",optionality:1}],Bridge:[{name:"Account",optionality:0},{name:"SignatureReward",optionality:0},{name:"MinAccountCreateAmount",optionality:1},{name:"XChainBridge",optionality:0},{name:"XChainClaimID",optionality:0},{name:"XChainAccountCreateCount",optionality:0},{name:"XChainAccountClaimCount",optionality:0},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],Check:[{name:"Account",optionality:0},{name:"Destination",optionality:0},{name:"SendMax",optionality:0},{name:"Sequence",optionality:0},{name:"OwnerNode",optionality:0},{name:"DestinationNode",optionality:0},{name:"Expiration",optionality:1},{name:"InvoiceID",optionality:1},{name:"SourceTag",optionality:1},{name:"DestinationTag",optionality:1},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],Credential:[{name:"Subject",optionality:0},{name:"Issuer",optionality:0},{name:"CredentialType",optionality:0},{name:"Expiration",optionality:1},{name:"URI",optionality:1},{name:"IssuerNode",optionality:0},{name:"SubjectNode",optionality:1},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],DID:[{name:"Account",optionality:0},{name:"DIDDocument",optionality:1},{name:"URI",optionality:1},{name:"Data",optionality:1},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],Delegate:[{name:"Account",optionality:0},{name:"Authorize",optionality:0},{name:"Permissions",optionality:0},{name:"OwnerNode",optionality:0},{name:"DestinationNode",optionality:1},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],DepositPreauth:[{name:"Account",optionality:0},{name:"Authorize",optionality:1},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"AuthorizeCredentials",optionality:1}],DirectoryNode:[{name:"Owner",optionality:1},{name:"TakerPaysCurrency",optionality:1},{name:"TakerPaysIssuer",optionality:1},{name:"TakerPaysMPT",optionality:1},{name:"TakerGetsCurrency",optionality:1},{name:"TakerGetsIssuer",optionality:1},{name:"TakerGetsMPT",optionality:1},{name:"ExchangeRate",optionality:1},{name:"Indexes",optionality:0},{name:"RootIndex",optionality:0},{name:"IndexNext",optionality:1},{name:"IndexPrevious",optionality:1},{name:"NFTokenID",optionality:1},{name:"PreviousTxnID",optionality:1},{name:"PreviousTxnLgrSeq",optionality:1},{name:"DomainID",optionality:1}],Escrow:[{name:"Account",optionality:0},{name:"Sequence",optionality:1},{name:"Destination",optionality:0},{name:"Amount",optionality:0},{name:"Condition",optionality:1},{name:"CancelAfter",optionality:1},{name:"FinishAfter",optionality:1},{name:"SourceTag",optionality:1},{name:"DestinationTag",optionality:1},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"DestinationNode",optionality:1},{name:"TransferRate",optionality:1},{name:"IssuerNode",optionality:1}],FeeSettings:[{name:"BaseFee",optionality:1},{name:"ReferenceFeeUnits",optionality:1},{name:"ReserveBase",optionality:1},{name:"ReserveIncrement",optionality:1},{name:"BaseFeeDrops",optionality:1},{name:"ReserveBaseDrops",optionality:1},{name:"ReserveIncrementDrops",optionality:1},{name:"PreviousTxnID",optionality:1},{name:"PreviousTxnLgrSeq",optionality:1}],LedgerHashes:[{name:"FirstLedgerSequence",optionality:1},{name:"LastLedgerSequence",optionality:1},{name:"Hashes",optionality:0}],Loan:[{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"OwnerNode",optionality:0},{name:"LoanBrokerNode",optionality:0},{name:"LoanBrokerID",optionality:0},{name:"LoanSequence",optionality:0},{name:"Borrower",optionality:0},{name:"LoanOriginationFee",optionality:2},{name:"LoanServiceFee",optionality:2},{name:"LatePaymentFee",optionality:2},{name:"ClosePaymentFee",optionality:2},{name:"OverpaymentFee",optionality:2},{name:"InterestRate",optionality:2},{name:"LateInterestRate",optionality:2},{name:"CloseInterestRate",optionality:2},{name:"OverpaymentInterestRate",optionality:2},{name:"StartDate",optionality:0},{name:"PaymentInterval",optionality:0},{name:"GracePeriod",optionality:2},{name:"PreviousPaymentDueDate",optionality:2},{name:"NextPaymentDueDate",optionality:2},{name:"PaymentRemaining",optionality:2},{name:"PeriodicPayment",optionality:0},{name:"PrincipalOutstanding",optionality:2},{name:"TotalValueOutstanding",optionality:2},{name:"ManagementFeeOutstanding",optionality:2},{name:"LoanScale",optionality:2}],LoanBroker:[{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"Sequence",optionality:0},{name:"OwnerNode",optionality:0},{name:"VaultNode",optionality:0},{name:"VaultID",optionality:0},{name:"Account",optionality:0},{name:"Owner",optionality:0},{name:"LoanSequence",optionality:0},{name:"Data",optionality:2},{name:"ManagementFeeRate",optionality:2},{name:"OwnerCount",optionality:2},{name:"DebtTotal",optionality:2},{name:"DebtMaximum",optionality:2},{name:"CoverAvailable",optionality:2},{name:"CoverRateMinimum",optionality:2},{name:"CoverRateLiquidation",optionality:2}],MPToken:[{name:"Account",optionality:0},{name:"MPTokenIssuanceID",optionality:0},{name:"MPTAmount",optionality:2},{name:"LockedAmount",optionality:1},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"ConfidentialBalanceInbox",optionality:1},{name:"ConfidentialBalanceSpending",optionality:1},{name:"ConfidentialBalanceVersion",optionality:2},{name:"IssuerEncryptedBalance",optionality:1},{name:"AuditorEncryptedBalance",optionality:1},{name:"HolderEncryptionKey",optionality:1}],MPTokenIssuance:[{name:"Issuer",optionality:0},{name:"Sequence",optionality:0},{name:"TransferFee",optionality:2},{name:"OwnerNode",optionality:0},{name:"AssetScale",optionality:2},{name:"MaximumAmount",optionality:1},{name:"OutstandingAmount",optionality:0},{name:"LockedAmount",optionality:1},{name:"MPTokenMetadata",optionality:1},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"DomainID",optionality:1},{name:"ImmutableFlags",optionality:2},{name:"ReferenceHolding",optionality:1},{name:"IssuerEncryptionKey",optionality:1},{name:"AuditorEncryptionKey",optionality:1},{name:"IssuerKeyEpoch",optionality:1},{name:"AuditorKeyEpoch",optionality:1},{name:"ConfidentialOutstandingAmount",optionality:2}],NFTokenOffer:[{name:"Owner",optionality:0},{name:"NFTokenID",optionality:0},{name:"Amount",optionality:0},{name:"OwnerNode",optionality:0},{name:"NFTokenOfferNode",optionality:0},{name:"Destination",optionality:1},{name:"Expiration",optionality:1},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],NFTokenPage:[{name:"PreviousPageMin",optionality:1},{name:"NextPageMin",optionality:1},{name:"NFTokens",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],NegativeUNL:[{name:"DisabledValidators",optionality:1},{name:"ValidatorToDisable",optionality:1},{name:"ValidatorToReEnable",optionality:1},{name:"PreviousTxnID",optionality:1},{name:"PreviousTxnLgrSeq",optionality:1}],Offer:[{name:"Account",optionality:0},{name:"Sequence",optionality:0},{name:"TakerPays",optionality:0},{name:"TakerGets",optionality:0},{name:"BookDirectory",optionality:0},{name:"BookNode",optionality:0},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"Expiration",optionality:1},{name:"DomainID",optionality:1},{name:"AdditionalBooks",optionality:1}],Oracle:[{name:"Owner",optionality:0},{name:"OracleDocumentID",optionality:1},{name:"Provider",optionality:0},{name:"PriceDataSeries",optionality:0},{name:"AssetClass",optionality:0},{name:"LastUpdateTime",optionality:0},{name:"URI",optionality:1},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],PayChannel:[{name:"Account",optionality:0},{name:"Destination",optionality:0},{name:"Sequence",optionality:1},{name:"Amount",optionality:0},{name:"Balance",optionality:0},{name:"PublicKey",optionality:0},{name:"SettleDelay",optionality:0},{name:"Expiration",optionality:1},{name:"CancelAfter",optionality:1},{name:"SourceTag",optionality:1},{name:"DestinationTag",optionality:1},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"DestinationNode",optionality:1}],PermissionedDomain:[{name:"Owner",optionality:0},{name:"Sequence",optionality:0},{name:"AcceptedCredentials",optionality:0},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],RippleState:[{name:"Balance",optionality:0},{name:"LowLimit",optionality:0},{name:"HighLimit",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"LowNode",optionality:1},{name:"LowQualityIn",optionality:1},{name:"LowQualityOut",optionality:1},{name:"HighNode",optionality:1},{name:"HighQualityIn",optionality:1},{name:"HighQualityOut",optionality:1},{name:"HighSponsor",optionality:1},{name:"LowSponsor",optionality:1}],SignerList:[{name:"Owner",optionality:1},{name:"OwnerNode",optionality:0},{name:"SignerQuorum",optionality:0},{name:"SignerEntries",optionality:0},{name:"SignerListID",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],Sponsorship:[{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"Owner",optionality:0},{name:"Sponsee",optionality:0},{name:"FeeAmount",optionality:1},{name:"MaxFee",optionality:1},{name:"RemainingOwnerCount",optionality:2},{name:"OwnerNode",optionality:0},{name:"SponseeNode",optionality:0}],Ticket:[{name:"Account",optionality:0},{name:"OwnerNode",optionality:0},{name:"TicketSequence",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],Vault:[{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0},{name:"Sequence",optionality:0},{name:"OwnerNode",optionality:0},{name:"Owner",optionality:0},{name:"Account",optionality:0},{name:"Data",optionality:1},{name:"Asset",optionality:0},{name:"AssetsTotal",optionality:2},{name:"AssetsAvailable",optionality:2},{name:"AssetsMaximum",optionality:2},{name:"LossUnrealized",optionality:2},{name:"ShareMPTID",optionality:0},{name:"WithdrawalPolicy",optionality:0},{name:"Scale",optionality:2},{name:"LEVersion",optionality:2},{name:"VaultKind",optionality:2},{name:"SubscriptionDate",optionality:1},{name:"RedemptionDate",optionality:1}],XChainOwnedClaimID:[{name:"Account",optionality:0},{name:"XChainBridge",optionality:0},{name:"XChainClaimID",optionality:0},{name:"OtherChainSource",optionality:0},{name:"XChainClaimAttestations",optionality:0},{name:"SignatureReward",optionality:0},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],XChainOwnedCreateAccountClaimID:[{name:"Account",optionality:0},{name:"XChainBridge",optionality:0},{name:"XChainAccountCreateCount",optionality:0},{name:"XChainCreateAccountAttestations",optionality:0},{name:"OwnerNode",optionality:0},{name:"PreviousTxnID",optionality:0},{name:"PreviousTxnLgrSeq",optionality:0}],common:[{name:"LedgerIndex",optionality:1},{name:"LedgerEntryType",optionality:0},{name:"Flags",optionality:0},{name:"Sponsor",optionality:1}]},LEDGER_ENTRY_TYPES:{AMM:121,AccountRoot:97,Amendments:102,Bridge:105,Check:67,Credential:129,DID:73,Delegate:131,DepositPreauth:112,DirectoryNode:100,Escrow:117,FeeSettings:115,Invalid:-1,LedgerHashes:104,Loan:137,LoanBroker:136,MPToken:127,MPTokenIssuance:126,NFTokenOffer:55,NFTokenPage:80,NegativeUNL:78,Offer:111,Oracle:128,PayChannel:120,PermissionedDomain:130,RippleState:114,SignerList:83,Sponsorship:144,Ticket:84,Vault:132,XChainOwnedClaimID:113,XChainOwnedCreateAccountClaimID:116},TRANSACTION_FLAGS:{AMMClawback:{tfClawTwoAssets:1},AMMDeposit:{tfLPToken:65536,tfLimitLPToken:4194304,tfOneAssetLPToken:2097152,tfSingleAsset:524288,tfTwoAsset:1048576,tfTwoAssetIfEmpty:8388608},AMMWithdraw:{tfLPToken:65536,tfLimitLPToken:4194304,tfOneAssetLPToken:2097152,tfOneAssetWithdrawAll:262144,tfSingleAsset:524288,tfTwoAsset:1048576,tfWithdrawAll:131072},AccountSet:{tfAllowXRP:2097152,tfDisallowXRP:1048576,tfOptionalAuth:524288,tfOptionalDestTag:131072,tfRequireAuth:262144,tfRequireDestTag:65536},Batch:{tfAllOrNothing:65536,tfIndependent:524288,tfOnlyOne:131072,tfUntilFailure:262144},EnableAmendment:{tfGotMajority:65536,tfLostMajority:131072},LoanManage:{tfLoanDefault:65536,tfLoanImpair:131072,tfLoanUnimpair:262144},LoanPay:{tfLoanFullPayment:131072,tfLoanLatePayment:262144,tfLoanOverpayment:65536},LoanSet:{tfLoanOverpayment:65536},MPTokenAuthorize:{tfMPTUnauthorize:1},MPTokenIssuanceCreate:{tfMPTCanClawback:64,tfMPTCanEscrow:8,tfMPTCanHoldConfidentialBalance:128,tfMPTCanLock:2,tfMPTCanTrade:16,tfMPTCanTransfer:32,tfMPTRequireAuth:4},MPTokenIssuanceSet:{tfMPTLock:1,tfMPTSetCanClawback:128,tfMPTSetCanEscrow:16,tfMPTSetCanHoldConfidentialBalance:256,tfMPTSetCanLock:4,tfMPTSetCanTrade:32,tfMPTSetCanTransfer:64,tfMPTSetRequireAuth:8,tfMPTUnlock:2},NFTokenCreateOffer:{tfSellNFToken:1},NFTokenMint:{tfBurnable:1,tfMutable:16,tfOnlyXRP:2,tfTransferable:8},OfferCreate:{tfFillOrKill:262144,tfHybrid:1048576,tfImmediateOrCancel:131072,tfPassive:65536,tfSell:524288},Payment:{tfLimitQuality:262144,tfNoRippleDirect:65536,tfPartialPayment:131072,tfSponsorCreatedAccount:524288},PaymentChannelClaim:{tfClose:131072,tfRenew:65536},SponsorshipSet:{tfDeleteObject:1048576,tfSponsorshipClearRequireSignForFee:131072,tfSponsorshipClearRequireSignForReserve:524288,tfSponsorshipSetRequireSignForFee:65536,tfSponsorshipSetRequireSignForReserve:262144},SponsorshipTransfer:{tfSponsorshipCreate:131072,tfSponsorshipEnd:65536,tfSponsorshipReassign:262144},TrustSet:{tfClearDeepFreeze:8388608,tfClearFreeze:2097152,tfClearNoRipple:262144,tfSetDeepFreeze:4194304,tfSetFreeze:1048576,tfSetNoRipple:131072,tfSetfAuth:65536},VaultCreate:{tfVaultPrivate:65536,tfVaultShareNonTransferable:131072},XChainModifyBridge:{tfClearAccountCreateAmount:65536},universal:{tfFullyCanonicalSig:2147483648,tfInnerBatchTxn:1073741824}},TRANSACTION_FORMATS:{AMMBid:[{name:"Asset",optionality:0},{name:"Asset2",optionality:0},{name:"BidMin",optionality:1},{name:"BidMax",optionality:1},{name:"AuthAccounts",optionality:1}],AMMClawback:[{name:"Holder",optionality:0},{name:"Asset",optionality:0},{name:"Asset2",optionality:0},{name:"Amount",optionality:1}],AMMCreate:[{name:"Amount",optionality:0},{name:"Amount2",optionality:0},{name:"TradingFee",optionality:0}],AMMDelete:[{name:"Asset",optionality:0},{name:"Asset2",optionality:0}],AMMDeposit:[{name:"Asset",optionality:0},{name:"Asset2",optionality:0},{name:"Amount",optionality:1},{name:"Amount2",optionality:1},{name:"EPrice",optionality:1},{name:"LPTokenOut",optionality:1},{name:"TradingFee",optionality:1}],AMMVote:[{name:"Asset",optionality:0},{name:"Asset2",optionality:0},{name:"TradingFee",optionality:0}],AMMWithdraw:[{name:"Asset",optionality:0},{name:"Asset2",optionality:0},{name:"Amount",optionality:1},{name:"Amount2",optionality:1},{name:"EPrice",optionality:1},{name:"LPTokenIn",optionality:1}],AccountDelete:[{name:"Destination",optionality:0},{name:"DestinationTag",optionality:1},{name:"CredentialIDs",optionality:1}],AccountSet:[{name:"EmailHash",optionality:1},{name:"WalletLocator",optionality:1},{name:"WalletSize",optionality:1},{name:"MessageKey",optionality:1},{name:"Domain",optionality:1},{name:"TransferRate",optionality:1},{name:"SetFlag",optionality:1},{name:"ClearFlag",optionality:1},{name:"TickSize",optionality:1},{name:"NFTokenMinter",optionality:1}],Batch:[{name:"RawTransactions",optionality:0},{name:"BatchSigners",optionality:1}],CheckCancel:[{name:"CheckID",optionality:0}],CheckCash:[{name:"CheckID",optionality:0},{name:"Amount",optionality:1},{name:"DeliverMin",optionality:1}],CheckCreate:[{name:"Destination",optionality:0},{name:"SendMax",optionality:0},{name:"Expiration",optionality:1},{name:"DestinationTag",optionality:1},{name:"InvoiceID",optionality:1}],Clawback:[{name:"Amount",optionality:0},{name:"Holder",optionality:1}],ConfidentialMPTClawback:[{name:"MPTokenIssuanceID",optionality:0},{name:"Holder",optionality:0},{name:"MPTAmount",optionality:0},{name:"ZKProof",optionality:0}],ConfidentialMPTConvert:[{name:"MPTokenIssuanceID",optionality:0},{name:"MPTAmount",optionality:0},{name:"HolderEncryptionKey",optionality:1},{name:"HolderEncryptedAmount",optionality:0},{name:"IssuerEncryptedAmount",optionality:0},{name:"AuditorEncryptedAmount",optionality:1},{name:"BlindingFactor",optionality:0},{name:"ZKProof",optionality:1}],ConfidentialMPTConvertBack:[{name:"MPTokenIssuanceID",optionality:0},{name:"MPTAmount",optionality:0},{name:"HolderEncryptedAmount",optionality:0},{name:"IssuerEncryptedAmount",optionality:0},{name:"AuditorEncryptedAmount",optionality:1},{name:"BlindingFactor",optionality:0},{name:"ZKProof",optionality:0},{name:"BalanceCommitment",optionality:0}],ConfidentialMPTMergeInbox:[{name:"MPTokenIssuanceID",optionality:0}],ConfidentialMPTSend:[{name:"MPTokenIssuanceID",optionality:0},{name:"Destination",optionality:0},{name:"DestinationTag",optionality:1},{name:"SenderEncryptedAmount",optionality:0},{name:"DestinationEncryptedAmount",optionality:0},{name:"IssuerEncryptedAmount",optionality:0},{name:"AuditorEncryptedAmount",optionality:1},{name:"ZKProof",optionality:0},{name:"AmountCommitment",optionality:0},{name:"BalanceCommitment",optionality:0},{name:"CredentialIDs",optionality:1}],CredentialAccept:[{name:"Issuer",optionality:0},{name:"CredentialType",optionality:0}],CredentialCreate:[{name:"Subject",optionality:0},{name:"CredentialType",optionality:0},{name:"Expiration",optionality:1},{name:"URI",optionality:1}],CredentialDelete:[{name:"Subject",optionality:1},{name:"Issuer",optionality:1},{name:"CredentialType",optionality:0}],DIDDelete:[],DIDSet:[{name:"DIDDocument",optionality:1},{name:"URI",optionality:1},{name:"Data",optionality:1}],DelegateSet:[{name:"Authorize",optionality:0},{name:"Permissions",optionality:0}],DepositPreauth:[{name:"Authorize",optionality:1},{name:"Unauthorize",optionality:1},{name:"AuthorizeCredentials",optionality:1},{name:"UnauthorizeCredentials",optionality:1}],EnableAmendment:[{name:"LedgerSequence",optionality:0},{name:"Amendment",optionality:0}],EscrowCancel:[{name:"Owner",optionality:0},{name:"OfferSequence",optionality:0}],EscrowCreate:[{name:"Destination",optionality:0},{name:"Amount",optionality:0},{name:"Condition",optionality:1},{name:"CancelAfter",optionality:1},{name:"FinishAfter",optionality:1},{name:"DestinationTag",optionality:1}],EscrowFinish:[{name:"Owner",optionality:0},{name:"OfferSequence",optionality:0},{name:"Fulfillment",optionality:1},{name:"Condition",optionality:1},{name:"CredentialIDs",optionality:1}],LedgerStateFix:[{name:"LedgerFixType",optionality:0},{name:"Owner",optionality:1},{name:"BookDirectory",optionality:1}],LoanBrokerCoverClawback:[{name:"LoanBrokerID",optionality:1},{name:"Amount",optionality:1}],LoanBrokerCoverDeposit:[{name:"LoanBrokerID",optionality:0},{name:"Amount",optionality:0}],LoanBrokerCoverWithdraw:[{name:"LoanBrokerID",optionality:0},{name:"Amount",optionality:0},{name:"Destination",optionality:1},{name:"DestinationTag",optionality:1},{name:"CredentialIDs",optionality:1}],LoanBrokerDelete:[{name:"LoanBrokerID",optionality:0}],LoanBrokerSet:[{name:"VaultID",optionality:0},{name:"LoanBrokerID",optionality:1},{name:"Data",optionality:1},{name:"ManagementFeeRate",optionality:1},{name:"DebtMaximum",optionality:1},{name:"CoverRateMinimum",optionality:1},{name:"CoverRateLiquidation",optionality:1}],LoanDelete:[{name:"LoanID",optionality:0}],LoanManage:[{name:"LoanID",optionality:0}],LoanPay:[{name:"LoanID",optionality:0},{name:"Amount",optionality:0}],LoanSet:[{name:"LoanBrokerID",optionality:0},{name:"Data",optionality:1},{name:"Counterparty",optionality:1},{name:"CounterpartySignature",optionality:1},{name:"LoanOriginationFee",optionality:1},{name:"LoanServiceFee",optionality:1},{name:"LatePaymentFee",optionality:1},{name:"ClosePaymentFee",optionality:1},{name:"OverpaymentFee",optionality:1},{name:"InterestRate",optionality:1},{name:"LateInterestRate",optionality:1},{name:"CloseInterestRate",optionality:1},{name:"OverpaymentInterestRate",optionality:1},{name:"PrincipalRequested",optionality:0},{name:"PaymentTotal",optionality:1},{name:"PaymentInterval",optionality:1},{name:"GracePeriod",optionality:1}],MPTokenAuthorize:[{name:"MPTokenIssuanceID",optionality:0},{name:"Holder",optionality:1}],MPTokenIssuanceCreate:[{name:"AssetScale",optionality:1},{name:"TransferFee",optionality:1},{name:"MaximumAmount",optionality:1},{name:"MPTokenMetadata",optionality:1},{name:"DomainID",optionality:1},{name:"ImmutableFlags",optionality:1}],MPTokenIssuanceDestroy:[{name:"MPTokenIssuanceID",optionality:0}],MPTokenIssuanceSet:[{name:"MPTokenIssuanceID",optionality:0},{name:"Holder",optionality:1},{name:"DomainID",optionality:1},{name:"MPTokenMetadata",optionality:1},{name:"TransferFee",optionality:1},{name:"ImmutableFlags",optionality:1},{name:"IssuerEncryptionKey",optionality:1},{name:"AuditorEncryptionKey",optionality:1}],NFTokenAcceptOffer:[{name:"NFTokenBuyOffer",optionality:1},{name:"NFTokenSellOffer",optionality:1},{name:"NFTokenBrokerFee",optionality:1}],NFTokenBurn:[{name:"NFTokenID",optionality:0},{name:"Owner",optionality:1}],NFTokenCancelOffer:[{name:"NFTokenOffers",optionality:0}],NFTokenCreateOffer:[{name:"NFTokenID",optionality:0},{name:"Amount",optionality:0},{name:"Destination",optionality:1},{name:"Owner",optionality:1},{name:"Expiration",optionality:1}],NFTokenMint:[{name:"NFTokenTaxon",optionality:0},{name:"TransferFee",optionality:1},{name:"Issuer",optionality:1},{name:"URI",optionality:1},{name:"Amount",optionality:1},{name:"Destination",optionality:1},{name:"Expiration",optionality:1}],NFTokenModify:[{name:"NFTokenID",optionality:0},{name:"Owner",optionality:1},{name:"URI",optionality:1}],OfferCancel:[{name:"OfferSequence",optionality:0}],OfferCreate:[{name:"TakerPays",optionality:0},{name:"TakerGets",optionality:0},{name:"Expiration",optionality:1},{name:"OfferSequence",optionality:1},{name:"DomainID",optionality:1}],OracleDelete:[{name:"OracleDocumentID",optionality:0}],OracleSet:[{name:"OracleDocumentID",optionality:0},{name:"Provider",optionality:1},{name:"URI",optionality:1},{name:"AssetClass",optionality:1},{name:"LastUpdateTime",optionality:0},{name:"PriceDataSeries",optionality:0}],Payment:[{name:"Destination",optionality:0},{name:"Amount",optionality:0},{name:"SendMax",optionality:1},{name:"Paths",optionality:2},{name:"InvoiceID",optionality:1},{name:"DestinationTag",optionality:1},{name:"DeliverMin",optionality:1},{name:"CredentialIDs",optionality:1},{name:"DomainID",optionality:1}],PaymentChannelClaim:[{name:"Channel",optionality:0},{name:"Amount",optionality:1},{name:"Balance",optionality:1},{name:"Signature",optionality:1},{name:"PublicKey",optionality:1},{name:"CredentialIDs",optionality:1}],PaymentChannelCreate:[{name:"Destination",optionality:0},{name:"Amount",optionality:0},{name:"SettleDelay",optionality:0},{name:"PublicKey",optionality:0},{name:"CancelAfter",optionality:1},{name:"DestinationTag",optionality:1}],PaymentChannelFund:[{name:"Channel",optionality:0},{name:"Amount",optionality:0},{name:"Expiration",optionality:1}],PermissionedDomainDelete:[{name:"DomainID",optionality:0}],PermissionedDomainSet:[{name:"DomainID",optionality:1},{name:"AcceptedCredentials",optionality:0}],SetFee:[{name:"LedgerSequence",optionality:1},{name:"BaseFee",optionality:1},{name:"ReferenceFeeUnits",optionality:1},{name:"ReserveBase",optionality:1},{name:"ReserveIncrement",optionality:1},{name:"BaseFeeDrops",optionality:1},{name:"ReserveBaseDrops",optionality:1},{name:"ReserveIncrementDrops",optionality:1}],SetRegularKey:[{name:"RegularKey",optionality:1}],SignerListSet:[{name:"SignerQuorum",optionality:0},{name:"SignerEntries",optionality:1}],SponsorshipSet:[{name:"CounterpartySponsor",optionality:1},{name:"Sponsee",optionality:1},{name:"FeeAmountDelta",optionality:1},{name:"MaxFee",optionality:1},{name:"RemainingOwnerCountDelta",optionality:1}],SponsorshipTransfer:[{name:"ObjectID",optionality:1},{name:"Sponsee",optionality:1}],TicketCreate:[{name:"TicketCount",optionality:0}],TrustSet:[{name:"LimitAmount",optionality:1},{name:"QualityIn",optionality:1},{name:"QualityOut",optionality:1}],UNLModify:[{name:"UNLModifyDisabling",optionality:0},{name:"LedgerSequence",optionality:0},{name:"UNLModifyValidator",optionality:0}],VaultClawback:[{name:"VaultID",optionality:0},{name:"Holder",optionality:0},{name:"Amount",optionality:1}],VaultCreate:[{name:"Asset",optionality:0},{name:"AssetsMaximum",optionality:1},{name:"MPTokenMetadata",optionality:1},{name:"DomainID",optionality:1},{name:"WithdrawalPolicy",optionality:1},{name:"Data",optionality:1},{name:"Scale",optionality:1},{name:"VaultKind",optionality:1},{name:"SubscriptionDate",optionality:1},{name:"RedemptionDate",optionality:1}],VaultDelete:[{name:"VaultID",optionality:0},{name:"MemoData",optionality:1}],VaultDeposit:[{name:"VaultID",optionality:0},{name:"Amount",optionality:0}],VaultSet:[{name:"VaultID",optionality:0},{name:"AssetsMaximum",optionality:1},{name:"DomainID",optionality:1},{name:"Data",optionality:1}],VaultWithdraw:[{name:"VaultID",optionality:0},{name:"Amount",optionality:0},{name:"Destination",optionality:1},{name:"DestinationTag",optionality:1},{name:"CredentialIDs",optionality:1}],XChainAccountCreateCommit:[{name:"XChainBridge",optionality:0},{name:"Destination",optionality:0},{name:"Amount",optionality:0},{name:"SignatureReward",optionality:0}],XChainAddAccountCreateAttestation:[{name:"XChainBridge",optionality:0},{name:"AttestationSignerAccount",optionality:0},{name:"PublicKey",optionality:0},{name:"Signature",optionality:0},{name:"OtherChainSource",optionality:0},{name:"Amount",optionality:0},{name:"AttestationRewardAccount",optionality:0},{name:"WasLockingChainSend",optionality:0},{name:"XChainAccountCreateCount",optionality:0},{name:"Destination",optionality:0},{name:"SignatureReward",optionality:0}],XChainAddClaimAttestation:[{name:"XChainBridge",optionality:0},{name:"AttestationSignerAccount",optionality:0},{name:"PublicKey",optionality:0},{name:"Signature",optionality:0},{name:"OtherChainSource",optionality:0},{name:"Amount",optionality:0},{name:"AttestationRewardAccount",optionality:0},{name:"WasLockingChainSend",optionality:0},{name:"XChainClaimID",optionality:0},{name:"Destination",optionality:1}],XChainClaim:[{name:"XChainBridge",optionality:0},{name:"XChainClaimID",optionality:0},{name:"Destination",optionality:0},{name:"DestinationTag",optionality:1},{name:"Amount",optionality:0}],XChainCommit:[{name:"XChainBridge",optionality:0},{name:"XChainClaimID",optionality:0},{name:"Amount",optionality:0},{name:"OtherChainDestination",optionality:1}],XChainCreateBridge:[{name:"XChainBridge",optionality:0},{name:"SignatureReward",optionality:0},{name:"MinAccountCreateAmount",optionality:1}],XChainCreateClaimID:[{name:"XChainBridge",optionality:0},{name:"SignatureReward",optionality:0},{name:"OtherChainSource",optionality:0}],XChainModifyBridge:[{name:"XChainBridge",optionality:0},{name:"SignatureReward",optionality:1},{name:"MinAccountCreateAmount",optionality:1}],common:[{name:"TransactionType",optionality:0},{name:"Flags",optionality:1},{name:"SourceTag",optionality:1},{name:"Account",optionality:0},{name:"Sequence",optionality:0},{name:"PreviousTxnID",optionality:1},{name:"LastLedgerSequence",optionality:1},{name:"AccountTxnID",optionality:1},{name:"Fee",optionality:0},{name:"OperationLimit",optionality:1},{name:"Memos",optionality:1},{name:"SigningPubKey",optionality:0},{name:"TicketSequence",optionality:1},{name:"TxnSignature",optionality:1},{name:"Signers",optionality:1},{name:"NetworkID",optionality:1},{name:"Delegate",optionality:1},{name:"Sponsor",optionality:1},{name:"SponsorFlags",optionality:1},{name:"SponsorSignature",optionality:1}]},TRANSACTION_RESULTS:{tecAMM_ACCOUNT:168,tecAMM_BALANCE:163,tecAMM_EMPTY:166,tecAMM_FAILED:164,tecAMM_INVALID_TOKENS:165,tecAMM_NOT_EMPTY:167,tecARRAY_EMPTY:190,tecARRAY_TOO_LARGE:191,tecBAD_CREDENTIALS:193,tecBAD_PROOF:199,tecCANT_ACCEPT_OWN_NFTOKEN_OFFER:158,tecCLAIM:100,tecCRYPTOCONDITION_ERROR:146,tecDIR_FULL:121,tecDST_TAG_NEEDED:143,tecDUPLICATE:149,tecEMPTY_DID:187,tecEXPIRED:148,tecFAILED_PROCESSING:105,tecFROZEN:137,tecHAS_OBLIGATIONS:151,tecINCOMPLETE:169,tecINSUFFICIENT_FUNDS:159,tecINSUFFICIENT_PAYMENT:161,tecINSUFFICIENT_RESERVE:141,tecINSUFF_FEE:136,tecINSUF_RESERVE_LINE:122,tecINSUF_RESERVE_OFFER:123,tecINTERNAL:144,tecINVALID_UPDATE_TIME:188,tecINVARIANT_FAILED:147,tecKILLED:150,tecLIMIT_EXCEEDED:195,tecLOCKED:192,tecMAX_SEQUENCE_REACHED:154,tecNEED_MASTER_KEY:142,tecNFTOKEN_BUY_SELL_MISMATCH:156,tecNFTOKEN_OFFER_TYPE_MISMATCH:157,tecNO_ALTERNATIVE_KEY:130,tecNO_AUTH:134,tecNO_DST:124,tecNO_DST_INSUF_XRP:125,tecNO_ENTRY:140,tecNO_ISSUER:133,tecNO_LINE:135,tecNO_LINE_INSUF_RESERVE:126,tecNO_LINE_REDUNDANT:127,tecNO_PERMISSION:139,tecNO_REGULAR_KEY:131,tecNO_SPONSOR_PERMISSION:200,tecNO_SUITABLE_NFTOKEN_PAGE:155,tecNO_TARGET:138,tecOBJECT_NOT_FOUND:160,tecOVERSIZE:145,tecOWNERS:132,tecPATH_DRY:128,tecPATH_PARTIAL:101,tecPRECISION_LOSS:197,tecPSEUDO_ACCOUNT:196,tecTOKEN_PAIR_NOT_FOUND:189,tecTOO_SOON:152,tecUNFUNDED:129,tecUNFUNDED_ADD:102,tecUNFUNDED_AMM:162,tecUNFUNDED_OFFER:103,tecUNFUNDED_PAYMENT:104,tecWRONG_ASSET:194,tecXCHAIN_ACCOUNT_CREATE_PAST:181,tecXCHAIN_ACCOUNT_CREATE_TOO_MANY:182,tecXCHAIN_BAD_CLAIM_ID:172,tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR:185,tecXCHAIN_BAD_TRANSFER_ISSUE:170,tecXCHAIN_CLAIM_NO_QUORUM:173,tecXCHAIN_CREATE_ACCOUNT_DISABLED:186,tecXCHAIN_CREATE_ACCOUNT_NONXRP_ISSUE:175,tecXCHAIN_INSUFF_CREATE_AMOUNT:180,tecXCHAIN_NO_CLAIM_ID:171,tecXCHAIN_NO_SIGNERS_LIST:178,tecXCHAIN_PAYMENT_FAILED:183,tecXCHAIN_PROOF_UNKNOWN_KEY:174,tecXCHAIN_REWARD_MISMATCH:177,tecXCHAIN_SELF_COMMIT:184,tecXCHAIN_SENDING_ACCOUNT_MISMATCH:179,tecXCHAIN_WRONG_CHAIN:176,tefALREADY:-198,tefBAD_ADD_AUTH:-197,tefBAD_AUTH:-196,tefBAD_AUTH_MASTER:-183,tefBAD_LEDGER:-195,tefBAD_PATH_COUNT:-176,tefBAD_QUORUM:-185,tefBAD_SIGNATURE:-186,tefCREATED:-194,tefEXCEPTION:-193,tefFAILURE:-199,tefINTERNAL:-192,tefINVALID_LEDGER_FIX_TYPE:-178,tefINVARIANT_FAILED:-182,tefMASTER_DISABLED:-188,tefMAX_LEDGER:-187,tefNFTOKEN_IS_NOT_TRANSFERABLE:-179,tefNOT_MULTI_SIGNING:-184,tefNO_AUTH_REQUIRED:-191,tefNO_DST_PARTIAL:-177,tefNO_TICKET:-180,tefPAST_SEQ:-190,tefTOO_BIG:-181,tefWRONG_PRIOR:-189,telBAD_DOMAIN:-398,telBAD_PATH_COUNT:-397,telBAD_PUBLIC_KEY:-396,telCAN_NOT_QUEUE:-392,telCAN_NOT_QUEUE_BALANCE:-391,telCAN_NOT_QUEUE_BLOCKED:-389,telCAN_NOT_QUEUE_BLOCKS:-390,telCAN_NOT_QUEUE_FEE:-388,telCAN_NOT_QUEUE_FULL:-387,telENV_RPC_FAILED:-383,telFAILED_PROCESSING:-395,telINSUF_FEE_P:-394,telLOCAL_ERROR:-399,telNETWORK_ID_MAKES_TX_NON_CANONICAL:-384,telNO_DST_PARTIAL:-393,telREQUIRES_NETWORK_ID:-385,telWRONG_NETWORK:-386,temARRAY_EMPTY:-253,temARRAY_TOO_LARGE:-252,temBAD_AMM_TOKENS:-261,temBAD_AMOUNT:-298,temBAD_CIPHERTEXT:-248,temBAD_CURRENCY:-297,temBAD_EXPIRATION:-296,temBAD_FEE:-295,temBAD_ISSUER:-294,temBAD_LIMIT:-293,temBAD_MPT:-249,temBAD_NFTOKEN_TRANSFER_FEE:-262,temBAD_OFFER:-292,temBAD_PATH:-291,temBAD_PATH_LOOP:-290,temBAD_QUORUM:-271,temBAD_REGKEY:-289,temBAD_SEND_XRP_LIMIT:-288,temBAD_SEND_XRP_MAX:-287,temBAD_SEND_XRP_NO_DIRECT:-286,temBAD_SEND_XRP_PARTIAL:-285,temBAD_SEND_XRP_PATHS:-284,temBAD_SEQUENCE:-283,temBAD_SIGNATURE:-282,temBAD_SIGNER:-272,temBAD_SRC_ACCOUNT:-281,temBAD_TICK_SIZE:-269,temBAD_TRANSFER_FEE:-251,temBAD_TRANSFER_RATE:-280,temBAD_WEIGHT:-270,temCANNOT_PREAUTH_SELF:-267,temDISABLED:-273,temDST_IS_SRC:-279,temDST_NEEDED:-278,temEMPTY_DID:-254,temINVALID:-277,temINVALID_ACCOUNT_ID:-268,temINVALID_COUNT:-266,temINVALID_FLAG:-276,temINVALID_INNER_BATCH:-250,temMALFORMED:-299,temREDUNDANT:-275,temRIPPLE_EMPTY:-274,temSEQ_AND_TICKET:-263,temUNCERTAIN:-265,temUNKNOWN:-264,temXCHAIN_BAD_PROOF:-259,temXCHAIN_BRIDGE_BAD_ISSUES:-258,temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT:-256,temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT:-255,temXCHAIN_BRIDGE_NONDOOR_OWNER:-257,temXCHAIN_EQUAL_DOOR_ACCOUNTS:-260,terADDRESS_COLLISION:-86,terFUNDS_SPENT:-98,terINSUF_FEE_B:-97,terLAST:-91,terLOCKED:-84,terNO_ACCOUNT:-96,terNO_AMM:-87,terNO_AUTH:-95,terNO_DELEGATE_PERMISSION:-85,terNO_LINE:-94,terNO_PERMISSION:-83,terNO_RIPPLE:-90,terOWNERS:-93,terPRE_SEQ:-92,terPRE_TICKET:-88,terQUEUED:-89,terRETRY:-99,tesSUCCESS:0},TRANSACTION_TYPES:{AMMBid:39,AMMClawback:31,AMMCreate:35,AMMDelete:40,AMMDeposit:36,AMMVote:38,AMMWithdraw:37,AccountDelete:21,AccountSet:3,Batch:71,CheckCancel:18,CheckCash:17,CheckCreate:16,Clawback:30,ConfidentialMPTClawback:89,ConfidentialMPTConvert:85,ConfidentialMPTConvertBack:87,ConfidentialMPTMergeInbox:86,ConfidentialMPTSend:88,CredentialAccept:59,CredentialCreate:58,CredentialDelete:60,DIDDelete:50,DIDSet:49,DelegateSet:64,DepositPreauth:19,EnableAmendment:100,EscrowCancel:4,EscrowCreate:1,EscrowFinish:2,Invalid:-1,LedgerStateFix:53,LoanBrokerCoverClawback:78,LoanBrokerCoverDeposit:76,LoanBrokerCoverWithdraw:77,LoanBrokerDelete:75,LoanBrokerSet:74,LoanDelete:81,LoanManage:82,LoanPay:84,LoanSet:80,MPTokenAuthorize:57,MPTokenIssuanceCreate:54,MPTokenIssuanceDestroy:55,MPTokenIssuanceSet:56,NFTokenAcceptOffer:29,NFTokenBurn:26,NFTokenCancelOffer:28,NFTokenCreateOffer:27,NFTokenMint:25,NFTokenModify:61,OfferCancel:8,OfferCreate:7,OracleDelete:52,OracleSet:51,Payment:0,PaymentChannelClaim:15,PaymentChannelCreate:13,PaymentChannelFund:14,PermissionedDomainDelete:63,PermissionedDomainSet:62,SetFee:101,SetRegularKey:5,SignerListSet:12,SponsorshipSet:91,SponsorshipTransfer:90,TicketCreate:10,TrustSet:20,UNLModify:102,VaultClawback:70,VaultCreate:65,VaultDelete:67,VaultDeposit:68,VaultSet:66,VaultWithdraw:69,XChainAccountCreateCommit:44,XChainAddAccountCreateAttestation:46,XChainAddClaimAttestation:45,XChainClaim:43,XChainCommit:42,XChainCreateBridge:48,XChainCreateClaimID:41,XChainModifyBridge:47},TYPES:{AccountID:8,Amount:6,Blob:7,Currency:26,Done:-1,Hash128:4,Hash160:17,Hash192:21,Hash256:5,Hash384:22,Hash512:23,Int32:10,Int64:11,Issue:24,LedgerEntry:10002,Metadata:10004,NotPresent:0,Number:9,PathSet:18,STArray:15,STObject:14,Transaction:10001,UInt16:1,UInt32:2,UInt64:3,UInt8:16,UInt96:20,Unknown:-2,Validation:10003,Vector256:19,XChainBridge:25},hash:"0F89957938A9185335A2ACD799EDDF3965F349E2E482A0CDD97094A1E4DB9FE7"}});var Rv=q(vu=>{"use strict";y();Object.defineProperty(vu,"__esModule",{value:!0});vu.BytesLookup=vu.Bytes=void 0;var _p=class{constructor(t,n,r){this.name=t,this.ordinal=n,this.ordinalWidth=r,this.bytes=new Uint8Array(r);for(let i=0;i>>i*8&255}toJSON(){return this.name}toBytesSink(t){t.put(this.bytes)}toBytes(){return this.bytes}};vu.Bytes=_p;var Dv=class{constructor(t,n){this.ordinalWidth=n,Object.entries(t).forEach(([r,i])=>{this.add(r,i)})}add(t,n){if(this[t])throw new SyntaxError(`Attempted to add a value with a duplicate name "${t}". This is not allowed because it is unclear how to decode.`);if(this[n.toString()])throw new SyntaxError(`Attempted to add a duplicate value under a different name (Given name: "${t}" and previous name: "${this[n.toString()]}. This is not allowed because it is unclear how to decode. Given value: ${n.toString()}`);this[t]=new _p(t,n,this.ordinalWidth),this[n.toString()]=this[t]}from(t){return t instanceof _p?t:this[t]}fromParser(t){return this.from(t.readUIntN(this.ordinalWidth).toString())}};vu.BytesLookup=Dv});var Su=q(Au=>{"use strict";y();Object.defineProperty(Au,"__esModule",{value:!0});Au.BinarySerializer=Au.BytesList=void 0;var Nv=We(),Ip=class{constructor(){this.bytesArray=[]}getLength(){return(0,Nv.concat)(this.bytesArray).byteLength}put(t){let n=Uint8Array.from(t);return this.bytesArray.push(n),this}toBytesSink(t){t.put(this.toBytes())}toBytes(){return(0,Nv.concat)(this.bytesArray)}toHex(){return(0,Nv.bytesToHex)(this.toBytes())}};Au.BytesList=Ip;var Lv=class{constructor(t){this.sink=new Ip,this.sink=t}write(t){t.toBytesSink(this.sink)}put(t){this.sink.put(t)}writeType(t,n){this.write(t.from(n))}writeBytesList(t){t.toBytesSink(this.sink)}encodeVariableLength(t){let n=new Uint8Array(3);if(t<=192)return n[0]=t,n.slice(0,1);if(t<=12480)return t-=193,n[0]=193+(t>>>8),n[1]=t&255,n.slice(0,2);if(t<=918744)return t-=12481,n[0]=241+(t>>>16),n[1]=t>>8&255,n[2]=t&255,n.slice(0,3);throw new Error("Overflow error")}writeFieldAndValue(t,n,r=!1){let i=t.associatedType.from(n);if(i.toBytesSink===void 0||t.name===void 0)throw new Error;this.sink.put(t.header),t.isVariableLengthEncoded?this.writeLengthEncoded(i,r):i.toBytesSink(this.sink)}writeLengthEncoded(t,n=!1){let r=new Ip;n||t.toBytesSink(r),this.put(this.encodeVariableLength(r.getLength())),this.writeBytesList(r)}};Au.BinarySerializer=Lv});var Ir=q(Tu=>{"use strict";y();Object.defineProperty(Tu,"__esModule",{value:!0});Tu.Comparable=Tu.SerializedType=void 0;var Tq=Su(),Eq=We(),Xm=class{constructor(t){this.bytes=new Uint8Array(0),this.bytes=t??new Uint8Array(0)}static fromParser(t,n){throw new Error("fromParser not implemented")}static from(t){throw new Error("from not implemented")}toBytesSink(t){t.put(this.bytes)}toHex(){return(0,Eq.bytesToHex)(this.toBytes())}toBytes(){if(this.bytes)return this.bytes;let t=new Tq.BytesList;return this.toBytesSink(t),t.toBytes()}toJSON(t,n){return this.toHex()}toString(){return this.toHex()}};Tu.SerializedType=Xm;var Bv=class extends Xm{lt(t){return this.compareTo(t)<0}eq(t){return this.compareTo(t)===0}gt(t){return this.compareTo(t)>0}gte(t){return this.compareTo(t)>-1}lte(t){return this.compareTo(t)<1}compareTo(t){throw new Error(`cannot compare ${this.toString()} and ${t.toString()}`)}};Tu.Comparable=Bv});var Fv=q(yi=>{"use strict";y();Object.defineProperty(yi,"__esModule",{value:!0});yi.DELEGATABLE_PERMISSIONS_WIDTH=yi.TRANSACTION_RESULT_WIDTH=yi.TRANSACTION_TYPE_WIDTH=yi.LEDGER_ENTRY_WIDTH=yi.TYPE_WIDTH=void 0;yi.TYPE_WIDTH=2;yi.LEDGER_ENTRY_WIDTH=2;yi.TRANSACTION_TYPE_WIDTH=2;yi.TRANSACTION_RESULT_WIDTH=1;yi.DELEGATABLE_PERMISSIONS_WIDTH=4});var a5=q(Wm=>{"use strict";y();Object.defineProperty(Wm,"__esModule",{value:!0});Wm.FieldLookup=void 0;var kq=Rv(),_q=Ir(),Iq=Fv();function Pq(e,t){let n=[];return e<16?t<16?n.push(e<<4|t):n.push(e<<4,t):t<16?n.push(t,e):n.push(0,e,t),Uint8Array.from(n)}function xq([e,t],n){let r=Pq(n,t.nth);return{name:e,nth:t.nth,isVariableLengthEncoded:t.isVLEncoded,isSerialized:t.isSerialized,isSigningField:t.isSigningField,ordinal:n<<16|t.nth,type:new kq.Bytes(t.type,n,Iq.TYPE_WIDTH),header:r,associatedType:_q.SerializedType}}var Uv=class{constructor(t,n){t.forEach(([r,i])=>{let o=n[i.type];this[r]=xq([r,i],o),this[this[r].ordinal.toString()]=this[r]})}fromString(t){return this[t]}};Wm.FieldLookup=Uv});var qv=q(Po=>{"use strict";y();Object.defineProperty(Po,"__esModule",{value:!0});Po.BytesLookup=Po.Bytes=Po.FieldLookup=Po.XrplDefinitionsBase=void 0;var Pc=Rv();Object.defineProperty(Po,"Bytes",{enumerable:!0,get:function(){return Pc.Bytes}});Object.defineProperty(Po,"BytesLookup",{enumerable:!0,get:function(){return Pc.BytesLookup}});var s5=a5();Object.defineProperty(Po,"FieldLookup",{enumerable:!0,get:function(){return s5.FieldLookup}});var Pp=Fv(),Mq=["FeeAmountDelta"],$v=class{constructor(t,n){this.type=new Pc.BytesLookup(t.TYPES,Pp.TYPE_WIDTH),this.ledgerEntryType=new Pc.BytesLookup(t.LEDGER_ENTRY_TYPES,Pp.LEDGER_ENTRY_WIDTH),this.transactionType=new Pc.BytesLookup(t.TRANSACTION_TYPES,Pp.TRANSACTION_TYPE_WIDTH),this.transactionResult=new Pc.BytesLookup(t.TRANSACTION_RESULTS,Pp.TRANSACTION_RESULT_WIDTH),this.field=new s5.FieldLookup(t.FIELDS,t.TYPES),this.transactionNames=Object.entries(t.TRANSACTION_TYPES).filter(([o,a])=>a>=0).map(([o,a])=>o),this.dataTypes={},this.associateTypes(n),this.granularPermissions={TrustlineAuthorize:65537,TrustlineFreeze:65538,TrustlineUnfreeze:65539,AccountDomainSet:65540,AccountEmailHashSet:65541,AccountMessageKeySet:65542,AccountTransferRateSet:65543,AccountTickSizeSet:65544,PaymentMint:65545,PaymentBurn:65546,MPTokenIssuanceLock:65547,MPTokenIssuanceUnlock:65548};let r=Object.fromEntries(Object.entries(t.TRANSACTION_TYPES).map(([o,a])=>[o,a+1])),i=Object.assign(Object.assign({},this.granularPermissions),r);this.delegatablePermissions=new Pc.BytesLookup(i,Pp.DELEGATABLE_PERMISSIONS_WIDTH)}associateTypes(t){this.dataTypes=Object.assign({},this.dataTypes,t),Object.values(this.field).forEach(n=>{n.associatedType=this.dataTypes[n.type.name]}),this.field.TransactionType.associatedType=this.transactionType,this.field.TransactionResult.associatedType=this.transactionResult,this.field.LedgerEntryType.associatedType=this.ledgerEntryType,this.field.PermissionValue&&(this.field.PermissionValue.associatedType=this.delegatablePermissions),Mq.forEach(n=>{this.field[n]&&this.dataTypes.SignedAmount&&(this.field[n].associatedType=this.dataTypes.SignedAmount)})}getAssociatedTypes(){return this.dataTypes}};Po.XrplDefinitionsBase=$v});var Sa=q(cn=>{"use strict";y();var Oq=cn&&cn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(cn,"__esModule",{value:!0});cn.TRANSACTION_TYPES=cn.TransactionType=cn.TransactionResult=cn.LedgerEntryType=cn.Type=cn.Field=cn.DEFAULT_DEFINITIONS=cn.XrplDefinitionsBase=cn.Bytes=void 0;var Dq=Oq(o5()),Hv=qv();Object.defineProperty(cn,"XrplDefinitionsBase",{enumerable:!0,get:function(){return Hv.XrplDefinitionsBase}});Object.defineProperty(cn,"Bytes",{enumerable:!0,get:function(){return Hv.Bytes}});var xc=new Hv.XrplDefinitionsBase(Dq.default,{});cn.DEFAULT_DEFINITIONS=xc;var Rq=xc.type;cn.Type=Rq;var Nq=xc.ledgerEntryType;cn.LedgerEntryType=Nq;var Lq=xc.transactionType;cn.TransactionType=Lq;var Bq=xc.transactionResult;cn.TransactionResult=Bq;var Fq=xc.field;cn.Field=Fq;var Uq=xc.transactionNames;cn.TRANSACTION_TYPES=Uq});var hi=q(Xt=>{"use strict";y();Object.defineProperty(Xt,"__esModule",{value:!0});Xt.compare=Xt.equal=Xt.readInt64BE=Xt.readInt32BE=Xt.readUInt32BE=Xt.readUInt16BE=Xt.writeInt64BE=Xt.writeInt32BE=Xt.writeUInt32BE=Xt.writeUInt16BE=Xt.writeUInt8=void 0;function $q(e,t,n){t=Number(t),e[n]=t}Xt.writeUInt8=$q;function qq(e,t,n){t=Number(t),e[n]=t>>>8,e[n+1]=t}Xt.writeUInt16BE=qq;function Hq(e,t,n){e[n]=t>>>24&255,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=t&255}Xt.writeUInt32BE=Hq;function Vq(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setInt32(n,t,!1)}Xt.writeInt32BE=Vq;function Kq(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setBigInt64(n,t,!1)}Xt.writeInt64BE=Kq;function zq(e,t){return new DataView(e.buffer).getUint16(t,!1).toString(10)}Xt.readUInt16BE=zq;function jq(e,t){return new DataView(e.buffer).getUint32(t,!1).toString(10)}Xt.readUInt32BE=jq;function Xq(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt32(t,!1)}Xt.readInt32BE=Xq;function Wq(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getBigInt64(t,!1)}Xt.readInt64BE=Wq;function Gq(e,t){let n=e instanceof ArrayBuffer?new Uint8Array(e,0):e,r=t instanceof ArrayBuffer?new Uint8Array(t,0):t;return n.byteLength!=r.byteLength?!1:l5(n)&&l5(r)?Jq(n,r)===0:c5(n)&&c5(r)?Zq(n,r)===0:Yq(n,r)===0}Xt.equal=Gq;function Yq(e,t){let n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return Gm(n,r)}function Zq(e,t){let n=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2);return Gm(n,r)}function Jq(e,t){let n=new Uint32Array(e.buffer,e.byteOffset,e.byteLength/4),r=new Uint32Array(t.buffer,t.byteOffset,t.byteLength/4);return Gm(n,r)}function Gm(e,t){if(e.byteLength!==t.byteLength)throw new Error("Cannot compare arrays of different length");for(let n=0;nt[n])return 1;if(e[n]{"use strict";y();Object.defineProperty(Ym,"__esModule",{value:!0});Ym.Hash=void 0;var Qq=Ir(),u5=We(),eH=hi(),Vv=class extends Qq.Comparable{constructor(t){if(super(t),this.bytes.length!==this.constructor.width)throw new Error(`Invalid Hash length ${this.bytes.byteLength}`)}static from(t){if(t instanceof this)return t;if(typeof t=="string"){if(!u5.HEX_REGEX.test(t))throw new Error(`Invalid hash string ${t}`);return new this((0,u5.hexToBytes)(t))}throw new Error("Cannot construct Hash from given value")}static fromParser(t,n){return new this(t.read(n??this.width))}compareTo(t){return(0,eH.compare)(this.bytes,this.constructor.from(t).bytes)}toString(){return this.toHex()}nibblet(t){let n=t>0?t/2|0:0,r=this.bytes[n];return t%2===0?r=(r&240)>>>4:r=r&15,r}};Ym.Hash=Vv});var Jm=q(Zm=>{"use strict";y();Object.defineProperty(Zm,"__esModule",{value:!0});Zm.Hash160=void 0;var tH=xp(),Mc=class e extends tH.Hash{constructor(t){t?.byteLength===0&&(t=e.ZERO_160.bytes),super(t??e.ZERO_160.bytes)}};Zm.Hash160=Mc;Mc.width=20;Mc.ZERO_160=new Mc(new Uint8Array(Mc.width))});var Eu=q(eg=>{"use strict";y();Object.defineProperty(eg,"__esModule",{value:!0});eg.AccountID=void 0;var Qm=lr(),nH=Jm(),rH=We(),iH=/^[A-F0-9]{40}$/,Mp=class e extends nH.Hash160{constructor(t){super(t??e.defaultAccountID.bytes)}static from(t){if(t instanceof e)return t;if(typeof t=="string")return t===""?new e:iH.test(t)?new e((0,rH.hexToBytes)(t)):this.fromBase58(t);throw new Error("Cannot construct AccountID from value given")}static fromBase58(t){if((0,Qm.isValidXAddress)(t)){let n=(0,Qm.xAddressToClassicAddress)(t);if(n.tag!==!1)throw new Error("Only allowed to have tag on Account or Destination");t=n.classicAddress}return new e(Uint8Array.from((0,Qm.decodeAccountID)(t)))}toJSON(){return this.toBase58()}toBase58(){return(0,Qm.encodeAccountID)(this.bytes)}};eg.AccountID=Mp;Mp.defaultAccountID=new Mp(new Uint8Array(20))});var Ta=q(tg=>{"use strict";y();Object.defineProperty(tg,"__esModule",{value:!0});tg.BinaryParser=void 0;var oH=Sa(),aH=We(),Kv=class{constructor(t,n=oH.DEFAULT_DEFINITIONS){this.bytes=(0,aH.hexToBytes)(t),this.definitions=n}peek(){if(this.bytes.byteLength===0)throw new Error;return this.bytes[0]}skip(t){if(t<0)throw new Error(`skip: negative length ${t}`);if(t>this.bytes.byteLength)throw new Error(`skip: requested ${t} bytes but only ${this.bytes.byteLength} available`);this.bytes=this.bytes.slice(t)}read(t){if(t<0)throw new Error(`read: negative length ${t}`);if(t>this.bytes.byteLength)throw new Error(`read: requested ${t} bytes but only ${this.bytes.byteLength} available`);let n=this.bytes.slice(0,t);return this.skip(t),n}readUIntN(t){if(0>=t||t>4)throw new Error("invalid n");return this.read(t).reduce((n,r)=>n<<8|r)>>>0}readUInt8(){return this.readUIntN(1)}readUInt16(){return this.readUIntN(2)}readUInt32(){return this.readUIntN(4)}size(){return this.bytes.byteLength}end(t){let n=this.bytes.byteLength;return n===0||t!==void 0&&n<=t}readVariableLength(){return this.read(this.readVariableLengthLength())}readVariableLengthLength(){let t=this.readUInt8();if(t<=192)return t;if(t<=240){let n=this.readUInt8();return 193+(t-193)*256+n}else if(t<=254){let n=this.readUInt8(),r=this.readUInt8();return 12481+(t-241)*65536+n*256+r}throw new Error("Invalid variable length indicator")}readFieldOrdinal(){let t=this.readUInt8(),n=t&15;if(t>>=4,t===0&&(t=this.readUInt8(),t===0||t<16))throw new Error(`Cannot read FieldOrdinal, type_code ${t} out of range`);if(n===0&&(n=this.readUInt8(),n===0||n<16))throw new Error(`Cannot read FieldOrdinal, field_code ${n} out of range`);return t<<16|n}readField(){return this.definitions.field.fromString(this.readFieldOrdinal().toString())}readType(t){return t.fromParser(this)}typeForField(t){return t.associatedType}readFieldValue(t){let n=this.typeForField(t);if(!n)throw new Error(`unsupported: (${t.name}, ${t.type.name})`);let r=t.isVariableLengthEncoded?this.readVariableLengthLength():void 0,i=n.fromParser(this,r);if(i===void 0)throw new Error(`fromParser for (${t.name}, ${t.type.name}) -> undefined `);return i}readFieldAndValue(){let t=this.readField();return[t,this.readFieldValue(t)]}};tg.BinaryParser=Kv});var Rp=q(ng=>{"use strict";y();Object.defineProperty(ng,"__esModule",{value:!0});ng.Currency=void 0;var sH=Jm(),Op=We(),cH=/^0{40}$/,lH=/^[A-Z0-9a-z?!@#$%^&*(){}[\]|]{3}$/,uH=/^[A-F0-9]{40}$/,dH=/^0{24}[\x00-\x7F]{6}0{10}$/;function fH(e){let t=new Uint8Array(20);if(e!=="XRP"){let n=e.split("").map(r=>r.charCodeAt(0));t.set(n,12)}return t}function pH(e){return lH.test(e)}function yH(e){let t=(0,Op.hexToString)((0,Op.bytesToHex)(e));return t==="XRP"?null:pH(t)?t:null}function hH(e){return uH.test(e)}function mH(e){return e.length===3||hH(e)}function gH(e){return e.byteLength===20}function wH(e){return e instanceof Uint8Array?gH(e):mH(e)}function bH(e){if(!wH(e))throw new Error(`Unsupported Currency representation: ${e}`);return e.length===3?fH(e):(0,Op.hexToBytes)(e)}var Dp=class e extends sH.Hash160{constructor(t){super(t??e.XRP.bytes);let n=(0,Op.bytesToHex)(this.bytes);cH.test(n)?this._iso="XRP":dH.test(n)?this._iso=yH(this.bytes.slice(12,15)):this._iso=null}iso(){return this._iso}static from(t){if(t instanceof e)return t;if(typeof t=="string")return new e(bH(t));throw new Error("Cannot construct Currency from value given")}toJSON(){let t=this.iso();return t!==null?t:(0,Op.bytesToHex)(this.bytes)}};ng.Currency=Dp;Dp.XRP=new Dp(new Uint8Array(20))});var Sn=q((fpe,p5)=>{y();var og=f5(),CH=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,zv=Math.ceil,no=Math.floor,Pr="[BigNumber Error] ",eo=1e14,Ue=14,d5=9007199254740991,jv=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],fs=1e7,Rn=1e9;function f5(e){var t,n,r,i=k.prototype={constructor:k,toString:null,valueOf:null},o=new k(1),a=20,s=4,c=-7,l=21,u=-1e7,d=1e7,p=!1,h=1,g=0,w={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},T="0123456789abcdefghijklmnopqrstuvwxyz";function k(b,C){var v,S,A,M,$,R,O,j,N=this;if(!(N instanceof k))return new k(b,C);if(j=typeof b,C==null){if(D(b)){N.s=b.s,!b.c||b.e>d?N.c=N.e=null:b.e=10;$/=10,M++);M>d?N.c=N.e=null:(N.e=M,N.c=[b]);return}O=String(b)}else{if(j=="string"){if(O=b,!CH.test(O))return r(N,O)}else if(j=="bigint")O=String(b);else throw Error(Pr+"Invalid argument: "+b);N.s=O.charCodeAt(0)==45?(O=O.slice(1),-1):1}(M=O.indexOf("."))>-1&&(O=O.replace(".","")),($=O.search(/e/i))>0?(M<0&&(M=$),M+=+O.slice($+1),O=O.substring(0,$)):M<0&&(M=O.length)}else{if(j!="string")throw Error(Pr+"String expected: "+b);for(Jt(C,2,T.length,"Base"),O=b,N.s=O.charCodeAt(0)===45?(O=O.slice(1),-1):1,v=T.slice(0,C),M=$=0,R=O.length;$M){M=R;continue}}else if(!A&&(O==O.toUpperCase()&&(O=O.toLowerCase())||O==O.toLowerCase()&&(O=O.toUpperCase()))){A=!0,$=-1,M=0;continue}return r(N,b,C)}O=n(O,C,10,N.s),(M=O.indexOf("."))>-1?O=O.replace(".",""):M=O.length}for($=0;O.charCodeAt($)===48;$++);for(R=O.length;O.charCodeAt(--R)===48;);if(O=O.slice($,++R))if(R-=$,M=M-$-1,M>d)N.c=N.e=null;else if(MRn||A!==no(A))return!1;if(S[0]===0)return A===0&&S.length===1;if(C=(A+1)%Ue,C<1&&(C+=Ue),String(S[0]).length!==C)return!1;for(C=0;C=eo||v!==no(v))return!1;return v!==0},k.maximum=k.max=function(){return P(arguments,-1)},k.minimum=k.min=function(){return P(arguments,1)},k.random=(function(){var b=9007199254740992,C=Math.random()*b&2097151?function(){return no(Math.random()*b)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(v){var S,A,M,$,R,O=0,j=[],N=new k(o);if(v==null?v=a:Jt(v,0,Rn),$=zv(v/Ue),p)if(crypto.getRandomValues){for(S=crypto.getRandomValues(new Uint32Array($*=2));O<$;)R=S[O]*131072+(S[O+1]>>>11),R>=9e15?(A=crypto.getRandomValues(new Uint32Array(2)),S[O]=A[0],S[O+1]=A[1]):(j.push(R%1e14),O+=2);O=$/2}else if(crypto.randomBytes){for(S=crypto.randomBytes($*=7);O<$;)R=(S[O]&31)*281474976710656+S[O+1]*1099511627776+S[O+2]*4294967296+S[O+3]*16777216+(S[O+4]<<16)+(S[O+5]<<8)+S[O+6],R>=9e15?crypto.randomBytes(7).copy(S,O):(j.push(R%1e14),O+=7);O=$/7}else throw p=!1,Error(Pr+"crypto unavailable");if(!p)for(;O<$;)R=C(),R<9e15&&(j[O++]=R%1e14);for($=j[--O],v%=Ue,$&&v&&(R=jv[Ue-v],j[O]=no($/R)*R);j[O]===0;j.pop(),O--);if(O<0)j=[M=0];else{for(M=-1;j[0]===0;j.splice(0,1),M-=Ue);for(O=1,R=j[0];R>=10;R/=10,O++);OA-1&&(R[$+1]==null&&(R[$+1]=0),R[$+1]+=R[$]/A|0,R[$]%=A)}return R.reverse()}return function(v,S,A,M,$){var R,O,j,N,V,G,L,X,Z=v.indexOf("."),ee=a,J=s;for(Z>=0&&(N=g,g=0,v=v.replace(".",""),X=new k(S),G=X.pow(v.length-Z),g=N,X.c=C(ps(to(G.c),G.e,"0"),10,A,b),X.e=X.c.length),L=C(v,S,A,$?(R=T,b):(R=b,T)),j=N=L.length;L[--N]==0;L.pop());if(!L[0])return R.charAt(0);if(Z<0?--j:(G.c=L,G.e=j,G.s=M,G=t(G,X,ee,J,A),L=G.c,V=G.r,j=G.e),O=j+ee+1,Z=L[O],N=A/2,V=V||O<0||L[O+1]!=null,V=J<4?(Z!=null||V)&&(J==0||J==(G.s<0?3:2)):Z>N||Z==N&&(J==4||V||J==6&&L[O-1]&1||J==(G.s<0?8:7)),O<1||!L[0])v=V?ps(R.charAt(1),-ee,R.charAt(0)):R.charAt(0);else{if(L.length=O,V)for(--A;++L[--O]>A;)L[O]=0,O||(++j,L=[1].concat(L));for(N=L.length;!L[--N];);for(Z=0,v="";Z<=N;v+=R.charAt(L[Z++]));v=ps(v,j,R.charAt(0))}return v}})(),t=(function(){function b(S,A,M){var $,R,O,j,N=0,V=S.length,G=A%fs,L=A/fs|0;for(S=S.slice();V--;)O=S[V]%fs,j=S[V]/fs|0,$=L*O+j*G,R=G*O+$%fs*fs+N,N=(R/M|0)+($/fs|0)+L*j,S[V]=R%M;return N&&(S=[N].concat(S)),S}function C(S,A,M,$){var R,O;if(M!=$)O=M>$?1:-1;else for(R=O=0;RA[R]?1:-1;break}return O}function v(S,A,M,$){for(var R=0;M--;)S[M]-=R,R=S[M]1;S.splice(0,1));}return function(S,A,M,$,R){var O,j,N,V,G,L,X,Z,ee,J,ie,se,me,pe,Pe,Ee,Ne,De=S.s==A.s?1:-1,qe=S.c,xe=A.c;if(!qe||!qe[0]||!xe||!xe[0])return new k(!S.s||!A.s||(qe?xe&&qe[0]==xe[0]:!xe)?NaN:qe&&qe[0]==0||!xe?De*0:De/0);for(Z=new k(De),ee=Z.c=[],j=S.e-A.e,De=M+j+1,R||(R=eo,j=mi(S.e/Ue)-mi(A.e/Ue),De=De/Ue|0),N=0;xe[N]==(qe[N]||0);N++);if(xe[N]>(qe[N]||0)&&j--,De<0)ee.push(1),V=!0;else{for(pe=qe.length,Ee=xe.length,N=0,De+=2,G=no(R/(xe[0]+1)),G>1&&(xe=b(xe,G,R),qe=b(qe,G,R),Ee=xe.length,pe=qe.length),me=Ee,J=qe.slice(0,Ee),ie=J.length;ie=R/2&&Pe++;do{if(G=0,O=C(xe,J,Ee,ie),O<0){if(se=J[0],Ee!=ie&&(se=se*R+(J[1]||0)),G=no(se/Pe),G>1)for(G>=R&&(G=R-1),L=b(xe,G,R),X=L.length,ie=J.length;C(L,J,X,ie)==1;)G--,v(L,Ee=10;De/=10,N++);F(Z,M+(Z.e=N+j*Ue-1)+1,$,V)}else Z.e=j,Z.r=+V;return Z}})();function B(b,C,v,S){var A,M,$,R,O;if(v==null?v=s:Jt(v,0,8),!b.c)return b.toString();if(A=b.c[0],$=b.e,C==null)O=to(b.c),O=S==1||S==2&&($<=c||$>=l)?ig(O,$):ps(O,$,"0");else if(b=F(new k(b),C,v),M=b.e,O=to(b.c),R=O.length,S==1||S==2&&(C<=M||M<=c)){for(;R$),O=ps(O,M,"0"),M+1>R){if(--C>0)for(O+=".";C--;O+="0");}else if(C+=M-R,C>0)for(M+1==R&&(O+=".");C--;O+="0");return b.s<0&&A?"-"+O:O}function D(b){return b instanceof k||!!b&&b._isBigNumber===!0}function P(b,C){for(var v,S,A=1,M=new k(b[0]);A=10;A/=10,S++);return(v=S+v*Ue-1)>d?b.c=b.e=null:v=10;R/=10,A++);if(M=C-A,M<0)M+=Ue,$=C,O=V[j=0],N=no(O/G[A-$-1]%10);else if(j=zv((M+1)/Ue),j>=V.length)if(S){for(;V.length<=j;V.push(0));O=N=0,A=1,M%=Ue,$=M-Ue+1}else break e;else{for(O=R=V[j],A=1;R>=10;R/=10,A++);M%=Ue,$=M-Ue+A,N=$<0?0:no(O/G[A-$-1]%10)}if(S=S||C<0||V[j+1]!=null||($<0?O:O%G[A-$-1]),S=v<4?(N||S)&&(v==0||v==(b.s<0?3:2)):N>5||N==5&&(v==4||S||v==6&&(M>0?$>0?O/G[A-$]:0:V[j-1])%10&1||v==(b.s<0?8:7)),C<1||!V[0])return V.length=0,S?(C-=b.e+1,V[0]=G[(Ue-C%Ue)%Ue],b.e=-C||0):V[0]=b.e=0,b;if(M==0?(V.length=j,R=1,j--):(V.length=j+1,R=G[Ue-M],V[j]=$>0?no(O/G[A-$]%G[$])*R:0),S)for(;;)if(j==0){for(M=1,$=V[0];$>=10;$/=10,M++);for($=V[0]+=R,R=1;$>=10;$/=10,R++);M!=R&&(b.e++,V[0]==eo&&(V[0]=1));break}else{if(V[j]+=R,V[j]!=eo)break;V[j--]=0,R=1}for(M=V.length;V[--M]===0;V.pop());}b.e>d?b.c=b.e=null:b.e=l?ig(C,v):ps(C,v,"0"),b.s<0?"-"+C:C)}return i.absoluteValue=i.abs=function(){var b=new k(this);return b.s<0&&(b.s=1),b},i.comparedTo=function(b,C){return Oc(this,new k(b,C))},i.decimalPlaces=i.dp=function(b,C){var v,S,A,M=this;if(b!=null)return Jt(b,0,Rn),C==null?C=s:Jt(C,0,8),F(new k(M),b+M.e+1,C);if(!(v=M.c))return null;if(S=((A=v.length-1)-mi(this.e/Ue))*Ue,A=v[A])for(;A%10==0;A/=10,S--);return S<0&&(S=0),S},i.dividedBy=i.div=function(b,C){return t(this,new k(b,C),a,s)},i.dividedToIntegerBy=i.idiv=function(b,C){return t(this,new k(b,C),0,1)},i.exponentiatedBy=i.pow=function(b,C){var v,S,A,M,$,R,O,j,N,V=this;if(b=new k(b),b.c&&!b.isInteger())throw Error(Pr+"Exponent not an integer: "+H(b));if(C!=null&&(C=new k(C)),R=b.e>14,!V.c||!V.c[0]||V.c[0]==1&&!V.e&&V.c.length==1||!b.c||!b.c[0])return N=new k(Math.pow(+H(V),R?b.s*(2-rg(b)):+H(b))),C?N.mod(C):N;if(O=b.s<0,C){if(C.c?!C.c[0]:!C.s)return new k(NaN);S=!O&&V.isInteger()&&C.isInteger(),S&&(V=V.mod(C))}else{if(b.e>9&&(V.e>0||V.e<-1||(V.e==0?V.c[0]>1||R&&V.c[1]>=24e7:V.c[0]<8e13||R&&V.c[0]<=9999975e7)))return M=V.s<0&&rg(b)?-0:0,V.e>-1&&(M=1/M),new k(O?1/M:M);g&&(M=zv(g/Ue+2))}for(R?(v=new k(.5),O&&(b.s=1),j=rg(b)):(A=Math.abs(+H(b)),j=A%2),N=new k(o);;){if(j){if(N=N.times(V),!N.c)break;M?N.c.length>M&&(N.c.length=M):S&&(N=N.mod(C))}if(A){if(A=no(A/2),A===0)break;j=A%2}else if(b=b.times(v),F(b,b.e+1,1),b.e>14)j=rg(b);else{if(A=+H(b),A===0)break;j=A%2}V=V.times(V),M?V.c&&V.c.length>M&&(V.c.length=M):S&&(V=V.mod(C))}return S?N:(O&&(N=o.div(N)),C?N.mod(C):M?F(N,g,s,$):N)},i.integerValue=function(b){var C=new k(this);return b==null?b=s:Jt(b,0,8),F(C,C.e+1,b)},i.isEqualTo=i.eq=function(b,C){return Oc(this,new k(b,C))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(b,C){return Oc(this,new k(b,C))>0},i.isGreaterThanOrEqualTo=i.gte=function(b,C){return(C=Oc(this,new k(b,C)))===1||C===0},i.isInteger=function(){return!!this.c&&mi(this.e/Ue)>this.c.length-2},i.isLessThan=i.lt=function(b,C){return Oc(this,new k(b,C))<0},i.isLessThanOrEqualTo=i.lte=function(b,C){return(C=Oc(this,new k(b,C)))===-1||C===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(b,C){var v,S,A,M,$=this,R=$.s;if(b=new k(b,C),C=b.s,!R||!C)return new k(NaN);if(R!=C)return b.s=-C,$.plus(b);var O=$.e/Ue,j=b.e/Ue,N=$.c,V=b.c;if(!O||!j){if(!N||!V)return N?(b.s=-C,b):new k(V?$:NaN);if(!N[0]||!V[0])return V[0]?(b.s=-C,b):new k(N[0]?$:s==3?-0:0)}if(O=mi(O),j=mi(j),N=N.slice(),R=O-j){for((M=R<0)?(R=-R,A=N):(j=O,A=V),A.reverse(),C=R;C--;A.push(0));A.reverse()}else for(S=(M=(R=N.length)<(C=V.length))?R:C,R=C=0;C0)for(;C--;N[v++]=0);for(C=eo-1;S>R;){if(N[--S]=0;){for(v=0,G=se[A]%ee,L=se[A]/ee|0,$=O,M=A+$;M>A;)j=ie[--$]%ee,N=ie[$]/ee|0,R=L*j+N*G,j=G*j+R%ee*ee+X[M]+v,v=(j/Z|0)+(R/ee|0)+L*N,X[M--]=j%Z;X[M]=v}return v?++S:X.splice(0,1),U(b,X,S)},i.negated=function(){var b=new k(this);return b.s=-b.s||null,b},i.plus=function(b,C){var v,S=this,A=S.s;if(b=new k(b,C),C=b.s,!A||!C)return new k(NaN);if(A!=C)return b.s=-C,S.minus(b);var M=S.e/Ue,$=b.e/Ue,R=S.c,O=b.c;if(!M||!$){if(!R||!O)return new k(A/0);if(!R[0]||!O[0])return O[0]?b:new k(R[0]?S:A*0)}if(M=mi(M),$=mi($),R=R.slice(),A=M-$){for(A>0?($=M,v=O):(A=-A,v=R),v.reverse();A--;v.push(0));v.reverse()}for(A=R.length,C=O.length,A-C<0&&(v=O,O=R,R=v,C=A),A=0;C;)A=(R[--C]=R[C]+O[C]+A)/eo|0,R[C]=eo===R[C]?0:R[C]%eo;return A&&(R=[A].concat(R),++$),U(b,R,$)},i.precision=i.sd=function(b,C){var v,S,A,M=this;if(b!=null&&b!==!!b)return Jt(b,1,Rn),C==null?C=s:Jt(C,0,8),F(new k(M),b,C);if(!(v=M.c))return null;if(A=v.length-1,S=A*Ue+1,A=v[A]){for(;A%10==0;A/=10,S--);for(A=v[0];A>=10;A/=10,S++);}return b&&M.e+1>S&&(S=M.e+1),S},i.shiftedBy=function(b){return Jt(b,-d5,d5),this.times("1e"+b)},i.squareRoot=i.sqrt=function(){var b,C,v,S,A,M=this,$=M.c,R=M.s,O=M.e,j=a+4,N=new k("0.5");if(R!==1||!$||!$[0])return new k(!R||R<0&&(!$||$[0])?NaN:$?M:1/0);if(R=Math.sqrt(+H(M)),R==0||R==1/0?(C=to($),(C.length+O)%2==0&&(C+="0"),R=Math.sqrt(+C),O=mi((O+1)/2)-(O<0||O%2),R==1/0?C="5e"+O:(C=R.toExponential(),C=C.slice(0,C.indexOf("e")+1)+O),v=new k(C)):v=new k(R+""),v.c[0]){for(O=v.e,R=O+j,R<3&&(R=0);;)if(A=v,v=N.times(A.plus(t(M,A,j,1))),to(A.c).slice(0,R)===(C=to(v.c)).slice(0,R))if(v.e0&&X>0){for(M=X%R||R,N=L.substr(0,M);M0&&(N+=j+L.slice(M)),G&&(N="-"+N)}S=V?N+(v.decimalSeparator||"")+((O=+v.fractionGroupSize)?V.replace(new RegExp("\\d{"+O+"}\\B","g"),"$&"+(v.fractionGroupSeparator||"")):V):N}return(v.prefix||"")+S+(v.suffix||"")},i.toFraction=function(b){var C,v,S,A,M,$,R,O,j,N,V,G,L=this,X=L.c;if(b!=null&&(R=new k(b),!R.isInteger()&&(R.c||R.s!==1)||R.lt(o)))throw Error(Pr+"Argument "+(R.isInteger()?"out of range: ":"not an integer: ")+H(R));if(!X)return new k(L);for(C=new k(o),j=v=new k(o),S=O=new k(o),G=to(X),M=C.e=G.length-L.e-1,C.c[0]=jv[($=M%Ue)<0?Ue+$:$],b=!b||R.comparedTo(C)>0?M>0?C:j:R,$=d,d=1/0,R=new k(G),O.c[0]=0;N=t(R,C,0,1),A=v.plus(N.times(S)),A.comparedTo(b)!=1;)v=S,S=A,j=O.plus(N.times(A=j)),O=A,C=R.minus(N.times(A=C)),R=A;return A=t(b.minus(v),S,0,1),O=O.plus(A.times(j)),v=v.plus(A.times(S)),O.s=j.s=L.s,M=M*2,V=t(j,S,M,s).minus(L).abs().comparedTo(t(O,v,M,s).minus(L).abs())<1?[j,S]:[O,v],d=$,V},i.toNumber=function(){return+H(this)},i.toObject=function(){var b=this;return{c:b.c?b.c.slice():null,e:b.e,s:b.s}},i.toPrecision=function(b,C){return b!=null&&Jt(b,1,Rn),B(this,b,C,2)},i.toString=function(b){var C,v=this,S=v.s,A=v.e;return A===null?S?(C="Infinity",S<0&&(C="-"+C)):C="NaN":(b==null?C=A<=c||A>=l?ig(to(v.c),A):ps(to(v.c),A,"0"):(Jt(b,2,T.length,"Base"),C=n(ps(to(v.c),A,"0"),10,b,S,!0)),S<0&&v.c[0]&&(C="-"+C)),C},i.valueOf=i.toJSON=function(){return H(this)},i._isBigNumber=!0,e!=null&&k.set(e),k}function mi(e){var t=e|0;return e>0||e===t?t:t-1}function to(e){for(var t,n,r=1,i=e.length,o=e[0]+"";rl^n?1:-1;for(s=(c=i.length)<(l=o.length)?c:l,a=0;ao[a]^n?1:-1;return c==l?0:c>l^n?1:-1}function Jt(e,t,n,r){if(en||e!==no(e))throw Error(Pr+(r||"Argument")+(typeof e=="number"?en?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function rg(e){var t=e.c.length-1;return mi(e.e/Ue)==t&&e.c[t]%2!=0}function ig(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function ps(e,t,n){var r,i;if(t<0){for(i=n+".";++t;i+=n);e=i+e}else if(r=e.length,++t>r){for(i=n,t-=r;--t;i+=n);e+=i}else t{"use strict";y();Object.defineProperty(ag,"__esModule",{value:!0});ag.Hash192=void 0;var vH=xp(),Dc=class e extends vH.Hash{constructor(t){t?.byteLength===0&&(t=e.ZERO_192.bytes),super(t??e.ZERO_192.bytes)}};ag.Hash192=Dc;Dc.width=24;Dc.ZERO_192=new Dc(new Uint8Array(Dc.width))});var Gv=q(ku=>{"use strict";y();var AH=ku&&ku.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ku,"__esModule",{value:!0});ku.Amount=void 0;var y5=Ta(),h5=Eu(),m5=Rp(),SH=Ir(),Ea=AH(Sn()),Rc=We(),xo=hi(),g5=sg(),w5=-96,b5=80,Wv=16,TH=new Ea.default("1e17"),EH=new Ea.default("1e-6"),Xv=BigInt(4294967295),kH=BigInt(9223372036854776e3);Ea.default.config({EXPONENTIAL_AT:[w5-Wv,b5+Wv]});function _H(e){let t=Object.keys(e).sort();return t.length===3&&t[0]==="currency"&&t[1]==="issuer"&&t[2]==="value"}function IH(e){let t=Object.keys(e).sort();return t.length===2&&t[0]==="mpt_issuance_id"&&t[1]==="value"}var Np=class e extends SH.SerializedType{constructor(t){super(t??e.defaultAmount.bytes)}static from(t){if(t instanceof e)return t;let n=new Uint8Array(8);if(typeof t=="string"){e.assertXrpIsValid(t);let r=BigInt(t),i=[new Uint8Array(4),new Uint8Array(4)];return(0,xo.writeUInt32BE)(i[0],Number(r>>BigInt(32)),0),(0,xo.writeUInt32BE)(i[1],Number(r&BigInt(Xv)),0),n=(0,Rc.concat)(i),n[0]|=64,new e(n)}if(_H(t)){let r;try{r=new Ea.default(t.value)}catch{throw new Error(`${t.value} is an illegal amount`)}if(e.assertIouIsValid(r),r.isZero())n[0]|=128;else{let a=r.times(`1e${-((r.e||0)-15)}`).abs().toString(),s=BigInt(a),c=[new Uint8Array(4),new Uint8Array(4)];(0,xo.writeUInt32BE)(c[0],Number(s>>BigInt(32)),0),(0,xo.writeUInt32BE)(c[1],Number(s&BigInt(Xv)),0),n=(0,Rc.concat)(c),n[0]|=128,r.gt(new Ea.default(0))&&(n[0]|=64);let u=97+((r.e||0)-15);n[0]|=u>>>2,n[1]|=(u&3)<<6}let i=m5.Currency.from(t.currency).toBytes(),o=h5.AccountID.from(t.issuer).toBytes();return new e((0,Rc.concat)([n,i,o]))}if(IH(t)){e.assertMptIsValid(t.value);let r=new Uint8Array(1);r[0]|=96;let i=BigInt(t.value),o=[new Uint8Array(4),new Uint8Array(4)];(0,xo.writeUInt32BE)(o[0],Number(i>>BigInt(32)),0),(0,xo.writeUInt32BE)(o[1],Number(i&BigInt(Xv)),0),n=(0,Rc.concat)(o);let a=g5.Hash192.from(t.mpt_issuance_id).toBytes();return new e((0,Rc.concat)([r,n,a]))}throw new Error("Invalid type to construct an Amount")}static fromParser(t){if(t.peek()&128)return new e(t.read(48));let i=t.peek()&32?33:8;return new e(t.read(i))}toJSON(){if(this.isNative()){let t=this.bytes.slice(),r=t[0]&64?"":"-";t[0]&=63;let i=BigInt((0,xo.readUInt32BE)(t.slice(0,4),0)),o=BigInt((0,xo.readUInt32BE)(t.slice(4),0)),a=i<>6)-97;n[0]=0,n[1]&=63;let u=new Ea.default(`${c}0x${(0,Rc.bytesToHex)(n)}`).times(`1e${l}`);return e.assertIouIsValid(u),{value:u.toString(),currency:r.toJSON(),issuer:i.toJSON()}}if(this.isMPT()){let t=new y5.BinaryParser(this.toString()),n=t.read(1),r=t.read(8),i=g5.Hash192.fromParser(t),a=n[0]&64?"":"-",s=BigInt((0,xo.readUInt32BE)(r.slice(0,4),0)),c=BigInt((0,xo.readUInt32BE)(r.slice(4),0)),l=s<Wv||r>b5||r{"use strict";y();Object.defineProperty(cg,"__esModule",{value:!0});cg.Blob=void 0;var PH=Ir(),xH=We(),Yv=class e extends PH.SerializedType{constructor(t){super(t)}static fromParser(t,n){return new e(t.read(n))}static from(t){if(t instanceof e)return t;if(typeof t=="string"){if(!/^[A-F0-9]*$/iu.test(t))throw new Error("Cannot construct Blob from a non-hex string");return new e((0,xH.hexToBytes)(t))}throw new Error("Cannot construct Blob from value given")}};cg.Blob=Yv});var v5=q(lg=>{"use strict";y();Object.defineProperty(lg,"__esModule",{value:!0});lg.Hash128=void 0;var MH=xp(),OH=We(),Nc=class e extends MH.Hash{constructor(t){t?.byteLength===0&&(t=e.ZERO_128.bytes),super(t??e.ZERO_128.bytes)}toHex(){let t=(0,OH.bytesToHex)(this.toBytes());return/^0+$/.exec(t)?"":t}};lg.Hash128=Nc;Nc.width=16;Nc.ZERO_128=new Nc(new Uint8Array(Nc.width))});var dg=q(ug=>{"use strict";y();Object.defineProperty(ug,"__esModule",{value:!0});ug.Hash256=void 0;var DH=xp(),Lc=class e extends DH.Hash{constructor(t){super(t??e.ZERO_256.bytes)}};ug.Hash256=Lc;Lc.width=32;Lc.ZERO_256=new Lc(new Uint8Array(Lc.width))});var A5=q(fg=>{"use strict";y();Object.defineProperty(fg,"__esModule",{value:!0});fg.Int=void 0;var RH=Ir();function NH(e,t){return ei)throw new Error(`Invalid ${t}: ${n} must be >= ${r} and <= ${i}`)}};fg.Int=Zv});var S5=q(pg=>{"use strict";y();Object.defineProperty(pg,"__esModule",{value:!0});pg.Int32=void 0;var LH=A5(),Jv=hi(),ka=class e extends LH.Int{constructor(t){super(t??e.defaultInt32.bytes)}static fromParser(t){return new e(t.read(e.width))}static from(t){if(t instanceof e)return t;let n=new Uint8Array(e.width);if(typeof t=="string"){let r=Number(t);if(!Number.isFinite(r)||!Number.isInteger(r))throw new Error(`Cannot construct Int32 from string: ${t}`);return e.checkIntRange("Int32",r,e.MIN_VALUE,e.MAX_VALUE),(0,Jv.writeInt32BE)(n,r,0),new e(n)}if(typeof t=="number"&&Number.isInteger(t))return e.checkIntRange("Int32",t,e.MIN_VALUE,e.MAX_VALUE),(0,Jv.writeInt32BE)(n,t,0),new e(n);throw new Error("Cannot construct Int32 from given value")}valueOf(){return(0,Jv.readInt32BE)(this.bytes,0)}};pg.Int32=ka;ka.width=32/8;ka.defaultInt32=new ka(new Uint8Array(ka.width));ka.MIN_VALUE=-2147483648;ka.MAX_VALUE=2147483647});var t2=q(hg=>{"use strict";y();Object.defineProperty(hg,"__esModule",{value:!0});hg.Issue=void 0;var _u=We(),BH=Ta(),yg=Eu(),Qv=Rp(),FH=Ir(),UH=sg(),T5=hi();function $H(e){let t=Object.keys(e).sort(),n=t.length===1&&t[0]==="currency",r=t.length===2&&t[0]==="currency"&&t[1]==="issuer",i=t.length===1&&t[0]==="mpt_issuance_id";return n||r||i}var qH=44,e2=yg.AccountID.from("0000000000000000000000000000000000000001"),Lp=class e extends FH.SerializedType{constructor(t){super(t??e.XRP_ISSUE.bytes)}static from(t){if(t instanceof e)return t;if($H(t)){if(t.currency){let n=Qv.Currency.from(t.currency.toString()).toBytes();if(t.issuer){let r=yg.AccountID.from(t.issuer.toString()).toBytes();return new e((0,_u.concat)([n,r]))}return new e(n)}if(t.mpt_issuance_id){let n=UH.Hash192.from(t.mpt_issuance_id.toString()).toBytes(),r=n.slice(4),i=Number((0,T5.readUInt32BE)(n.slice(0,4),0)),o=new Uint8Array(4);return new DataView(o.buffer).setUint32(0,i,!0),new e((0,_u.concat)([r,e2.toBytes(),o]))}}throw new Error("Invalid type to construct an Issue")}static fromParser(t){let n=t.read(20);if(new Qv.Currency(n).toJSON()==="XRP")return new e(n);let r=new yg.AccountID(t.read(20));if(e2.toHex()===r.toHex()){let i=t.read(4);return new e((0,_u.concat)([n,e2.toBytes(),i]))}return new e((0,_u.concat)([n,r.toBytes()]))}toJSON(){if(this.toBytes().length===qH){let i=this.toBytes().slice(0,20),o=new DataView(this.toBytes().slice(40).buffer).getUint32(0,!0),a=new Uint8Array(4);return(0,T5.writeUInt32BE)(a,o,0),{mpt_issuance_id:(0,_u.bytesToHex)((0,_u.concat)([a,i]))}}let t=new BH.BinaryParser(this.toString()),n=Qv.Currency.fromParser(t);if(n.toJSON()==="XRP")return{currency:n.toJSON()};let r=yg.AccountID.fromParser(t);return{currency:n.toJSON(),issuer:r.toJSON()}}};hg.Issue=Lp;Lp.XRP_ISSUE=new Lp(new Uint8Array(20))});var I5=q(wg=>{"use strict";y();Object.defineProperty(wg,"__esModule",{value:!0});wg.STNumber=void 0;var HH=Ir(),mg=hi(),n2=BigInt("1000000000000000000"),VH=BigInt("9999999999999999999"),E5=BigInt("9223372036854775807"),k5=-32768,Bp=32768,_5=-2147483648;function KH(e){let n=/^([-+]?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(e);if(!n)throw new Error(`Unable to parse number from string: ${e}`);let[,r,i,o,a]=n,c=i.replace(/^0+(?=\d)/,"")||"0",l=0;for(o&&(c+=o,l-=o.length),a&&(l+=parseInt(a,10));c.length>1&&c.endsWith("0");)c=c.slice(0,-1),l+=1;let u=BigInt(c);r==="-"&&(u=-u);let d=uk5;)t-=1,n*=BigInt(10);let i=null;for(;n>VH;){if(t>=Bp)throw new Error("Mantissa and exponent are too large");t+=1,i=n%BigInt(10),n/=BigInt(10)}if(tBp)throw new Error("Exponent overflow: value too large to represent");if(n>E5){if(t>=Bp)throw new Error("Exponent overflow: value too large to represent");t+=1,i=n%BigInt(10),n/=BigInt(10)}if(i!=null&&i>=BigInt(5)&&(n+=BigInt(1),n>E5)){if(t>=Bp)throw new Error("Exponent overflow: value too large to represent");i=n%BigInt(10),t+=1,n/=BigInt(10),i>=BigInt(5)&&(n+=BigInt(1))}return r&&(n=-n),{mantissa:n,exponent:t}}var gg=class e extends HH.SerializedType{constructor(t){let n=t??e.defaultBytes;if(!(n instanceof Uint8Array)||n.length!==12)throw new Error(`STNumber must be constructed from a 12-byte Uint8Array, got ${n?.length}`);super(n)}static from(t){if(t instanceof e)return t;if(typeof t=="string")return e.fromValue(t);throw new Error("STNumber.from: Only string or STNumber instance is supported")}static fromValue(t){let{mantissa:n,exponent:r}=KH(t),{mantissa:i,exponent:o}=zH(n,r),a=new Uint8Array(12);return(0,mg.writeInt64BE)(a,i,0),(0,mg.writeInt32BE)(a,o,8),new e(a)}static fromParser(t){return new e(t.read(12))}toJSON(){let t=this.bytes;if(!t||t?.length!==12)throw new Error("STNumber internal bytes not set or wrong length");let n=(0,mg.readInt64BE)(t,0),r=(0,mg.readInt32BE)(t,8);if(n===BigInt(0)&&r===_5)return"0";let i=n-(a-10))){let g=r;for(;o!==BigInt(0)&&o%BigInt(10)===BigInt(0)&&g{"use strict";y();Object.defineProperty(bg,"__esModule",{value:!0});bg.PathSet=void 0;var Iu=Eu(),r2=Rp(),l2=Ta(),u2=Ir(),Bc=We(),s2=0,P5=255,i2=1,o2=16,a2=32;function jH(e){return e.issuer!==void 0||e.account!==void 0||e.currency!==void 0}function XH(e){return Array.isArray(e)&&e.length===0||Array.isArray(e)&&Array.isArray(e[0])&&e[0].length===0||Array.isArray(e)&&Array.isArray(e[0])&&jH(e[0][0])}var Fp=class e extends u2.SerializedType{static from(t){if(t instanceof e)return t;let n=[Uint8Array.from([0])];return t.account&&(n.push(Iu.AccountID.from(t.account).toBytes()),n[0][0]|=i2),t.currency&&(n.push(r2.Currency.from(t.currency).toBytes()),n[0][0]|=o2),t.issuer&&(n.push(Iu.AccountID.from(t.issuer).toBytes()),n[0][0]|=a2),new e((0,Bc.concat)(n))}static fromParser(t){let n=t.readUInt8(),r=[Uint8Array.from([n])];return n&i2&&r.push(t.read(Iu.AccountID.width)),n&o2&&r.push(t.read(r2.Currency.width)),n&a2&&r.push(t.read(Iu.AccountID.width)),new e((0,Bc.concat)(r))}toJSON(){let t=new l2.BinaryParser((0,Bc.bytesToHex)(this.bytes)),n=t.readUInt8(),r,i,o;n&i2&&(r=Iu.AccountID.fromParser(t).toJSON()),n&o2&&(i=r2.Currency.fromParser(t).toJSON()),n&a2&&(o=Iu.AccountID.fromParser(t).toJSON());let a={};return r&&(a.account=r),o&&(a.issuer=o),i&&(a.currency=i),a}type(){return this.bytes[0]}},Up=class e extends u2.SerializedType{static from(t){if(t instanceof e)return t;let n=[];return t.forEach(r=>{n.push(Fp.from(r).toBytes())}),new e((0,Bc.concat)(n))}static fromParser(t){let n=[];for(;!t.end()&&(n.push(Fp.fromParser(t).toBytes()),!(t.peek()===s2||t.peek()===P5)););return new e((0,Bc.concat)(n))}toJSON(){let t=[],n=new l2.BinaryParser(this.toString());for(;!n.end();)t.push(Fp.fromParser(n).toJSON());return t}},c2=class e extends u2.SerializedType{static from(t){if(t instanceof e)return t;if(XH(t)){let n=[];return t.forEach(r=>{n.push(Up.from(r).toBytes()),n.push(Uint8Array.from([P5]))}),n[n.length-1]=Uint8Array.from([s2]),new e((0,Bc.concat)(n))}throw new Error("Cannot construct PathSet from given value")}static fromParser(t){let n=[];for(;!t.end()&&(n.push(Up.fromParser(t).toBytes()),n.push(t.read(1)),n[n.length-1][0]!=s2););return new e((0,Bc.concat)(n))}toJSON(){let t=[],n=new l2.BinaryParser(this.toString());for(;!n.end();)t.push(Up.fromParser(n).toJSON()),n.skip(1);return t}};bg.PathSet=c2});var $p=q(Cg=>{"use strict";y();Object.defineProperty(Cg,"__esModule",{value:!0});Cg.UInt=void 0;var WH=Ir();function GH(e,t){return er)throw new Error(`Invalid ${this.constructor.name}: ${t} must be >= ${n} and <= ${r}`)}};Cg.UInt=d2});var Sg=q(Ag=>{"use strict";y();Object.defineProperty(Ag,"__esModule",{value:!0});Ag.UInt64=void 0;var YH=$p(),vg=We(),Pu=hi(),ZH=Sa(),JH=/^[a-fA-F0-9]{1,16}$/,QH=/^[0-9]{1,20}$/,M5=BigInt(4294967295),eV=new Set(["MaximumAmount","OutstandingAmount","MPTAmount","LockedAmount","ConfidentialOutstandingAmount"]);function O5(e){return eV.has(e)}var Fc=class e extends YH.UInt{constructor(t){super(t??e.defaultUInt64.bytes)}static fromParser(t){return new e(t.read(e.width))}static from(t,n=""){if(t instanceof e)return t;let r=new Uint8Array(e.width);if(typeof t=="number"&&Number.isInteger(t)){if(t<0)throw new Error("value must be an unsigned integer");let i=BigInt(t),o=[new Uint8Array(4),new Uint8Array(4)];return(0,Pu.writeUInt32BE)(o[0],Number(i>>BigInt(32)),0),(0,Pu.writeUInt32BE)(o[1],Number(i&BigInt(M5)),0),new e((0,vg.concat)(o))}if(typeof t=="string"){if(O5(n)){if(!QH.test(t))throw new Error(`${n} ${t} is not a valid base 10 string`);t=BigInt(t).toString(16)}if(typeof t=="string"&&!JH.test(t))throw new Error(`${t} is not a valid hex-string`);let i=t.padStart(16,"0");return r=(0,vg.hexToBytes)(i),new e(r)}if(typeof t=="bigint"){let i=[new Uint8Array(4),new Uint8Array(4)];return(0,Pu.writeUInt32BE)(i[0],Number(Number(t>>BigInt(32))),0),(0,Pu.writeUInt32BE)(i[1],Number(t&BigInt(M5)),0),new e((0,vg.concat)(i))}throw new Error("Cannot construct UInt64 from given value")}toJSON(t=ZH.DEFAULT_DEFINITIONS,n=""){let r=(0,vg.bytesToHex)(this.bytes);return O5(n)?BigInt("0x"+r).toString(10):r}valueOf(){let t=BigInt((0,Pu.readUInt32BE)(this.bytes.slice(0,4),0)),n=BigInt((0,Pu.readUInt32BE)(this.bytes.slice(4),0));return t<{"use strict";y();Object.defineProperty(Eg,"__esModule",{value:!0});Eg.STObject=void 0;var tV=Sa(),nV=Ir(),N5=lr(),rV=Ta(),Tg=Su(),iV=m2(),oV=Sg(),D5=Uint8Array.from([225]),R5="ObjectEndMarker",f2="STObject",aV="Destination",sV="Account",p2="SourceTag",y2="DestinationTag";function cV(e,t){let n=(0,N5.xAddressToClassicAddress)(t),r;if(e===aV)r=y2;else if(e===sV)r=p2;else if(n.tag!==!1)throw new Error(`${e} cannot have an associated tag`);return n.tag!==!1?{[e]:n.classicAddress,[r]:n.tag}:{[e]:n.classicAddress}}function lV(e,t){if(!(e[p2]===void 0||t[p2]===void 0))throw new Error("Cannot have Account X-Address and SourceTag");if(!(e[y2]===void 0||t[y2]===void 0))throw new Error("Cannot have Destination X-Address and DestinationTag")}var h2=class e extends nV.SerializedType{static fromParser(t){let n=new Tg.BytesList,r=new Tg.BinarySerializer(n);for(;!t.end();){let i=t.readField();if(i.name===R5)break;let o=t.readFieldValue(i);r.writeFieldAndValue(i,o),i.type.name===f2&&r.put(D5)}return new e(n.toBytes())}static from(t,n,r=tV.DEFAULT_DEFINITIONS){if(t instanceof e)return t;let i=new Tg.BytesList,o=new Tg.BinarySerializer(i),a=!1,s=Object.entries(t).reduce((u,[d,p])=>{let h;return p&&(0,N5.isValidXAddress)(p.toString())&&(h=cV(d,p.toString()),lV(h,t)),Object.assign(u,h??{[d]:p})},{});function c(u){return u!==void 0&&s[u.name]!==void 0&&u.isSerialized}let l=Object.keys(s).map(u=>{if(!(u in r.field)){if(u[0]===u[0].toLowerCase())return;throw new Error(`Field ${u} is not defined in the definitions`)}return r.field[u]}).filter(c).sort((u,d)=>u.ordinal-d.ordinal);return n!==void 0&&(l=l.filter(n)),l.forEach(u=>{let d=u.type.name===f2?this.from(s[u.name],void 0,r):u.type.name==="STArray"?iV.STArray.from(s[u.name],r):u.type.name==="UInt64"?oV.UInt64.from(s[u.name],u.name):u.associatedType.from(s[u.name]);if(d==null)throw new TypeError(`Unable to interpret "${u.name}: ${s[u.name]}".`);d.name==="UNLModify"&&(a=!0);let p=u.name=="Account"&&a;o.writeFieldAndValue(u,d,p),u.type.name===f2&&o.put(D5)}),new e(i.toBytes())}toJSON(t){let n=new rV.BinaryParser(this.toString(),t),r={};for(;!n.end();){let i=n.readField();if(i.name===R5)break;r[i.name]=n.readFieldValue(i).toJSON(t,i.name)}return r}};Eg.STObject=h2});var m2=q(_g=>{"use strict";y();Object.defineProperty(_g,"__esModule",{value:!0});_g.STArray=void 0;var L5=Sa(),uV=Ir(),B5=kg(),dV=Ta(),F5=We(),U5=Uint8Array.from([241]),$5="ArrayEndMarker",fV=Uint8Array.from([225]);function pV(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&Object.keys(t).length===1&&typeof Object.values(t)[0]=="object")}var g2=class e extends uV.SerializedType{static fromParser(t){let n=[];for(;!t.end();){let r=t.readField();if(r.name===$5)break;n.push(r.header,t.readFieldValue(r).toBytes(),fV)}return n.push(U5),new e((0,F5.concat)(n))}static from(t,n=L5.DEFAULT_DEFINITIONS){if(t instanceof e)return t;if(pV(t)){let r=[];return t.forEach(i=>{r.push(B5.STObject.from(i,void 0,n).toBytes())}),r.push(U5),new e((0,F5.concat)(r))}throw new Error("Cannot construct STArray from value given")}toJSON(t=L5.DEFAULT_DEFINITIONS){let n=[],r=new dV.BinaryParser(this.toString(),t);for(;!r.end();){let i=r.readField();if(i.name===$5)break;let o={};o[i.name]=B5.STObject.fromParser(r).toJSON(t),n.push(o)}return n}};_g.STArray=g2});var V5=q(xu=>{"use strict";y();var yV=xu&&xu.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(xu,"__esModule",{value:!0});xu.SignedAmount=void 0;var b2=yV(Sn()),hV=We(),q5=hi(),H5=Gv(),mV=new b2.default("1e17"),gV=new b2.default("1e-6"),wV=BigInt(4294967295),w2=class e extends H5.Amount{static from(t){if(t instanceof H5.Amount)return t instanceof e?t:new e(t.toBytes());if(typeof t!="string")throw new Error("SignedAmount only supports native XRP string values");return e.fromString(t)}static fromString(t){if(t.indexOf(".")!==-1)throw new Error(`${t} is an illegal amount`);let n;try{n=new b2.default(t)}catch{throw new Error(`${t} is an illegal amount`)}if(n.isNaN())throw new Error(`${t} is an illegal amount`);if(!n.isZero()){let c=n.abs();if(c.lt(gV)||c.gt(mV))throw new Error(`${t} is an illegal amount`)}let r;try{r=BigInt(t)}catch{throw new Error(`${t} is an illegal amount`)}let i=r>BigInt(32)),0),(0,q5.writeUInt32BE)(a[1],Number(o&BigInt(wV)),0);let s=(0,hV.concat)(a);return i||(s[0]|=64),new e(s)}};xu.SignedAmount=w2});var z5=q(Ig=>{"use strict";y();Object.defineProperty(Ig,"__esModule",{value:!0});Ig.UInt16=void 0;var bV=$p(),K5=hi(),Uc=class e extends bV.UInt{constructor(t){super(t??e.defaultUInt16.bytes)}static fromParser(t){return new e(t.read(e.width))}static from(t){if(t instanceof e)return t;if(typeof t=="number"&&Number.isInteger(t)){e.checkUintRange(t,0,65535);let n=new Uint8Array(e.width);return(0,K5.writeUInt16BE)(n,t,0),new e(n)}throw new Error("Cannot construct UInt16 from given value")}valueOf(){return parseInt((0,K5.readUInt16BE)(this.bytes,0))}};Ig.UInt16=Uc;Uc.width=16/8;Uc.defaultUInt16=new Uc(new Uint8Array(Uc.width))});var v2=q(Pg=>{"use strict";y();Object.defineProperty(Pg,"__esModule",{value:!0});Pg.UInt32=void 0;var CV=$p(),C2=hi(),$c=class e extends CV.UInt{constructor(t){super(t??e.defaultUInt32.bytes)}static fromParser(t){return new e(t.read(e.width))}static from(t){if(t instanceof e)return t;let n=new Uint8Array(e.width);if(typeof t=="string"){let r=Number.parseInt(t);return(0,C2.writeUInt32BE)(n,r,0),new e(n)}if(typeof t=="number"&&Number.isInteger(t))return e.checkUintRange(t,0,4294967295),(0,C2.writeUInt32BE)(n,t,0),new e(n);throw new Error("Cannot construct UInt32 from given value")}valueOf(){return parseInt((0,C2.readUInt32BE)(this.bytes,0),10)}};Pg.UInt32=$c;$c.width=32/8;$c.defaultUInt32=new $c(new Uint8Array($c.width))});var A2=q(xg=>{"use strict";y();Object.defineProperty(xg,"__esModule",{value:!0});xg.UInt8=void 0;var vV=$p(),AV=We(),SV=hi(),qc=class e extends vV.UInt{constructor(t){super(t??e.defaultUInt8.bytes)}static fromParser(t){return new e(t.read(e.width))}static from(t){if(t instanceof e)return t;if(typeof t=="number"&&Number.isInteger(t)){e.checkUintRange(t,0,255);let n=new Uint8Array(e.width);return(0,SV.writeUInt8)(n,t,0),new e(n)}throw new Error("Cannot construct UInt8 from given value")}valueOf(){return parseInt((0,AV.bytesToHex)(this.bytes),16)}};xg.UInt8=qc;qc.width=8/8;qc.defaultUInt8=new qc(new Uint8Array(qc.width))});var W5=q(Mg=>{"use strict";y();Object.defineProperty(Mg,"__esModule",{value:!0});Mg.Vector256=void 0;var TV=Ir(),j5=dg(),X5=Su(),EV=We();function kV(e){return Array.isArray(e)&&(e.length===0||typeof e[0]=="string")}var S2=class e extends TV.SerializedType{constructor(t){super(t)}static fromParser(t,n){let r=new X5.BytesList,o=(n??t.size())/32;for(let a=0;a{j5.Hash256.from(r).toBytesSink(n)}),new e(n.toBytes())}throw new Error("Cannot construct Vector256 from given value")}toJSON(){if(this.bytes.byteLength%32!==0)throw new Error("Invalid bytes for Vector256");let t=[];for(let n=0;n{"use strict";y();Object.defineProperty(Og,"__esModule",{value:!0});Og.XChainBridge=void 0;var _V=Ta(),qp=Eu(),IV=Ir(),G5=t2(),T2=We();function PV(e){let t=Object.keys(e).sort();return t.length===4&&t[0]==="IssuingChainDoor"&&t[1]==="IssuingChainIssue"&&t[2]==="LockingChainDoor"&&t[3]==="LockingChainIssue"}var Mu=class e extends IV.SerializedType{constructor(t){super(t??e.ZERO_XCHAIN_BRIDGE.bytes)}static from(t){if(t instanceof e)return t;if(!PV(t))throw new Error("Invalid type to construct an XChainBridge");let n=[];return this.TYPE_ORDER.forEach(r=>{let{name:i,type:o}=r;o===qp.AccountID&&n.push(Uint8Array.from([20]));let a=o.from(t[i]);n.push(a.toBytes())}),new e((0,T2.concat)(n))}static fromParser(t){let n=[];return this.TYPE_ORDER.forEach(r=>{let{type:i}=r;i===qp.AccountID&&(t.skip(1),n.push(Uint8Array.from([20])));let o=i.fromParser(t);n.push(o.toBytes())}),new e((0,T2.concat)(n))}toJSON(){let t=new _V.BinaryParser(this.toString()),n={};return e.TYPE_ORDER.forEach(r=>{let{name:i,type:o}=r;o===qp.AccountID&&t.skip(1);let a=o.fromParser(t).toJSON();n[i]=a}),n}};Og.XChainBridge=Mu;Mu.ZERO_XCHAIN_BRIDGE=new Mu((0,T2.concat)([Uint8Array.from([20]),new Uint8Array(40),Uint8Array.from([20]),new Uint8Array(40)]));Mu.TYPE_ORDER=[{name:"LockingChainDoor",type:qp.AccountID},{name:"LockingChainIssue",type:G5.Issue},{name:"IssuingChainDoor",type:qp.AccountID},{name:"IssuingChainIssue",type:G5.Issue}]});var ys=q(Ke=>{"use strict";y();Object.defineProperty(Ke,"__esModule",{value:!0});Ke.Vector256=Ke.UInt64=Ke.UInt32=Ke.UInt16=Ke.UInt8=Ke.STObject=Ke.STArray=Ke.SignedAmount=Ke.PathSet=Ke.Int32=Ke.Hash256=Ke.Hash192=Ke.Hash160=Ke.Hash128=Ke.Currency=Ke.Blob=Ke.Amount=Ke.AccountID=Ke.coreTypes=void 0;var Z5=Eu();Object.defineProperty(Ke,"AccountID",{enumerable:!0,get:function(){return Z5.AccountID}});var J5=Gv();Object.defineProperty(Ke,"Amount",{enumerable:!0,get:function(){return J5.Amount}});var Q5=C5();Object.defineProperty(Ke,"Blob",{enumerable:!0,get:function(){return Q5.Blob}});var ek=Rp();Object.defineProperty(Ke,"Currency",{enumerable:!0,get:function(){return ek.Currency}});var tk=v5();Object.defineProperty(Ke,"Hash128",{enumerable:!0,get:function(){return tk.Hash128}});var nk=Jm();Object.defineProperty(Ke,"Hash160",{enumerable:!0,get:function(){return nk.Hash160}});var rk=sg();Object.defineProperty(Ke,"Hash192",{enumerable:!0,get:function(){return rk.Hash192}});var ik=dg();Object.defineProperty(Ke,"Hash256",{enumerable:!0,get:function(){return ik.Hash256}});var ok=S5();Object.defineProperty(Ke,"Int32",{enumerable:!0,get:function(){return ok.Int32}});var xV=t2(),MV=I5(),ak=x5();Object.defineProperty(Ke,"PathSet",{enumerable:!0,get:function(){return ak.PathSet}});var sk=m2();Object.defineProperty(Ke,"STArray",{enumerable:!0,get:function(){return sk.STArray}});var ck=V5();Object.defineProperty(Ke,"SignedAmount",{enumerable:!0,get:function(){return ck.SignedAmount}});var lk=kg();Object.defineProperty(Ke,"STObject",{enumerable:!0,get:function(){return lk.STObject}});var uk=z5();Object.defineProperty(Ke,"UInt16",{enumerable:!0,get:function(){return uk.UInt16}});var dk=v2();Object.defineProperty(Ke,"UInt32",{enumerable:!0,get:function(){return dk.UInt32}});var fk=Sg();Object.defineProperty(Ke,"UInt64",{enumerable:!0,get:function(){return fk.UInt64}});var pk=A2();Object.defineProperty(Ke,"UInt8",{enumerable:!0,get:function(){return pk.UInt8}});var yk=W5();Object.defineProperty(Ke,"Vector256",{enumerable:!0,get:function(){return yk.Vector256}});var OV=Y5(),DV=Sa(),hk={AccountID:Z5.AccountID,Amount:J5.Amount,Blob:Q5.Blob,Currency:ek.Currency,Hash128:tk.Hash128,Hash160:nk.Hash160,Hash192:rk.Hash192,Hash256:ik.Hash256,Int32:ok.Int32,Issue:xV.Issue,Number:MV.STNumber,PathSet:ak.PathSet,SignedAmount:ck.SignedAmount,STArray:sk.STArray,STObject:lk.STObject,UInt8:pk.UInt8,UInt16:uk.UInt16,UInt32:dk.UInt32,UInt64:fk.UInt64,Vector256:yk.Vector256,XChainBridge:OV.XChainBridge};Ke.coreTypes=hk;DV.DEFAULT_DEFINITIONS.associateTypes(hk)});var Ou=q(Dg=>{"use strict";y();Object.defineProperty(Dg,"__esModule",{value:!0});Dg.HashPrefix=void 0;var RV=hi();function ur(e){let t=new Uint8Array(4);return(0,RV.writeUInt32BE)(t,e,0),t}var NV={transactionID:ur(1415073280),transaction:ur(1397638144),accountStateEntry:ur(1296846336),innerNode:ur(1296649728),ledgerHeader:ur(1280791040),transactionSig:ur(1398036480),transactionMultiSig:ur(1397576704),counterpartyTransactionSig:ur(1129337856),counterpartyTransactionMultiSig:ur(1129336064),sponsorTransactionSig:ur(1397771776),sponsorTransactionMultiSig:ur(1397771520),validation:ur(1447119872),proposal:ur(1347571712),paymentChannelClaim:ur(1129073920),batch:ur(1111705600)};Dg.HashPrefix=NV});var Rg=q(Du=>{"use strict";y();var LV=Du&&Du.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Du,"__esModule",{value:!0});Du.sha512=void 0;var BV=At("crypto"),FV=LV(Km());Du.sha512=(0,FV.default)("sha512",BV.createHash)});var Hp=q(hs=>{"use strict";y();Object.defineProperty(hs,"__esModule",{value:!0});hs.transactionID=hs.sha512Half=hs.Sha512Half=void 0;var UV=Ou(),mk=ys(),$V=Su(),qV=Rg(),Ng=class e extends $V.BytesList{constructor(){super(...arguments),this.hash=qV.sha512.create()}static put(t){return new e().put(t)}put(t){return this.hash.update(t),this}finish256(){return Uint8Array.from(this.hash.digest().slice(0,32))}finish(){return new mk.Hash256(this.finish256())}};hs.Sha512Half=Ng;function gk(...e){let t=new Ng;return e.forEach(n=>t.put(n)),t.finish256()}hs.sha512Half=gk;function HV(e){return new mk.Hash256(gk(UV.HashPrefix.transactionID,e))}hs.transactionID=HV});var k2=q(kt=>{"use strict";y();Object.defineProperty(kt,"__esModule",{value:!0});kt.signingBatchData=kt.transactionID=kt.sha512Half=kt.binaryToJSON=kt.signingClaimData=kt.signingData=kt.multiSigningData=kt.readJSON=kt.serializeObject=kt.makeParser=kt.BytesList=kt.BinarySerializer=kt.BinaryParser=void 0;var VV=We(),gi=ys(),wk=Ta();Object.defineProperty(kt,"BinaryParser",{enumerable:!0,get:function(){return wk.BinaryParser}});var Lg=Ou(),Vp=Su();Object.defineProperty(kt,"BinarySerializer",{enumerable:!0,get:function(){return Vp.BinarySerializer}});Object.defineProperty(kt,"BytesList",{enumerable:!0,get:function(){return Vp.BytesList}});var bk=Hp();Object.defineProperty(kt,"sha512Half",{enumerable:!0,get:function(){return bk.sha512Half}});Object.defineProperty(kt,"transactionID",{enumerable:!0,get:function(){return bk.transactionID}});var Ck=Sa(),vk=(e,t)=>new wk.BinaryParser(e instanceof Uint8Array?(0,VV.bytesToHex)(e):e,t);kt.makeParser=vk;var Ak=(e,t=Ck.DEFAULT_DEFINITIONS)=>e.readType(gi.coreTypes.STObject).toJSON(t);kt.readJSON=Ak;var KV=(e,t)=>Ak(vk(e,t),t);kt.binaryToJSON=KV;function E2(e,t={}){let{prefix:n,suffix:r,signingFieldsOnly:i=!1,definitions:o}=t,a=new Vp.BytesList;n&&a.put(n);let s=i?c=>c.isSigningField:void 0;return gi.coreTypes.STObject.from(e,s,o).toBytesSink(a),r&&a.put(r),a.toBytes()}kt.serializeObject=E2;function zV(e,t=Lg.HashPrefix.transactionSig,n={}){return E2(e,{prefix:t,signingFieldsOnly:!0,definitions:n.definitions})}kt.signingData=zV;function jV(e){let t=BigInt(String(e.amount)),n=Lg.HashPrefix.paymentChannelClaim,r=gi.coreTypes.Hash256.from(e.channel).toBytes(),i=gi.coreTypes.UInt64.from(t).toBytes(),o=new Vp.BytesList;return o.put(n),o.put(r),o.put(i),o.toBytes()}kt.signingClaimData=jV;function XV(e,t,n={}){var r,i;let o=(r=n.prefix)!==null&&r!==void 0?r:Lg.HashPrefix.transactionMultiSig,a=gi.coreTypes.AccountID.from(t).toBytes();return E2(e,{prefix:o,suffix:a,signingFieldsOnly:!0,definitions:(i=n.definitions)!==null&&i!==void 0?i:Ck.DEFAULT_DEFINITIONS})}kt.multiSigningData=XV;function WV(e){if(e.account==null)throw Error("No field `account`");if(e.sequence==null)throw Error("No field `sequence`");if(e.flags==null)throw Error("No field `flags`");if(e.txIDs==null)throw Error("No field `txIDs`");let t=Lg.HashPrefix.batch,n=gi.coreTypes.AccountID.from(e.account).toBytes(),r=gi.coreTypes.UInt32.from(e.sequence).toBytes(),i=gi.coreTypes.UInt32.from(e.flags).toBytes(),o=gi.coreTypes.UInt32.from(e.txIDs.length).toBytes(),a=new Vp.BytesList;if(a.put(t),a.put(n),a.put(r),a.put(i),a.put(o),e.txIDs.forEach(s=>{a.put(gi.coreTypes.Hash256.from(s).toBytes())}),e.batchAccount!=null&&a.put(gi.coreTypes.AccountID.from(e.batchAccount).toBytes()),e.signerAccount!=null){if(e.batchAccount==null)throw Error("Field `signerAccount` requires `batchAccount`");a.put(gi.coreTypes.AccountID.from(e.signerAccount).toBytes())}return a.toBytes()}kt.signingBatchData=WV});var P2=q(ms=>{"use strict";y();Object.defineProperty(ms,"__esModule",{value:!0});ms.ShaMapLeaf=ms.ShaMapNode=ms.ShaMap=void 0;var Sk=ys(),GV=Ou(),Tk=Hp(),Kp=class{};ms.ShaMapNode=Kp;var zp=class extends Kp{constructor(t,n){super(),this.index=t,this.item=n}isLeaf(){return!0}isInner(){return!1}hashPrefix(){return this.item===void 0?new Uint8Array(0):this.item.hashPrefix()}hash(){let t=Tk.Sha512Half.put(this.hashPrefix());return this.toBytesSink(t),t.finish()}toBytesSink(t){this.item!==void 0&&this.item.toBytesSink(t),this.index.toBytesSink(t)}};ms.ShaMapLeaf=zp;var _2=class e extends Kp{constructor(t=0){super(),this.depth=t,this.slotBits=0,this.branches=Array(16)}isInner(){return!0}isLeaf(){return!1}hashPrefix(){return GV.HashPrefix.innerNode}setBranch(t,n){this.slotBits=this.slotBits|1<{"use strict";y();Object.defineProperty(Mo,"__esModule",{value:!0});Mo.decodeLedgerData=Mo.ledgerHash=Mo.transactionTreeHash=Mo.accountStateHash=void 0;var YV=P2(),M2=Ou(),ZV=Hp(),_k=k2(),gs=dg(),Ek=kg(),Ik=Sg(),x2=v2(),kk=A2(),JV=Ta();function Pk(e,t){let n=new YV.ShaMap;return t.forEach(r=>n.addItem(...e(r))),n.hash()}function QV(e){if(!e.hash)throw new Error;return[gs.Hash256.from(e.hash),{hashPrefix(){return M2.HashPrefix.transaction},toBytesSink(r){let i=new _k.BinarySerializer(r);i.writeLengthEncoded(Ek.STObject.from(e)),i.writeLengthEncoded(Ek.STObject.from(e.metaData))}},void 0]}function eK(e){let t=gs.Hash256.from(e.index),n=(0,_k.serializeObject)(e);return[t,{hashPrefix(){return M2.HashPrefix.accountStateEntry},toBytesSink(i){i.put(n)}},void 0]}function tK(e){return Pk(QV,e)}Mo.transactionTreeHash=tK;function nK(e){return Pk(eK,e)}Mo.accountStateHash=nK;function rK(e){let t=new ZV.Sha512Half;if(t.put(M2.HashPrefix.ledgerHeader),e.parent_close_time===void 0||e.close_flags===void 0)throw new Error;return x2.UInt32.from(e.ledger_index).toBytesSink(t),Ik.UInt64.from(BigInt(String(e.total_coins))).toBytesSink(t),gs.Hash256.from(e.parent_hash).toBytesSink(t),gs.Hash256.from(e.transaction_hash).toBytesSink(t),gs.Hash256.from(e.account_hash).toBytesSink(t),x2.UInt32.from(e.parent_close_time).toBytesSink(t),x2.UInt32.from(e.close_time).toBytesSink(t),kk.UInt8.from(e.close_time_resolution).toBytesSink(t),kk.UInt8.from(e.close_flags).toBytesSink(t),t.finish()}Mo.ledgerHash=rK;function iK(e,t){if(typeof e!="string")throw new Error("binary must be a hex string");let n=new JV.BinaryParser(e,t);return{ledger_index:n.readUInt32(),total_coins:n.readType(Ik.UInt64).valueOf().toString(),parent_hash:n.readType(gs.Hash256).toHex(),transaction_hash:n.readType(gs.Hash256).toHex(),account_hash:n.readType(gs.Hash256).toHex(),parent_close_time:n.readUInt32(),close_time:n.readUInt32(),close_time_resolution:n.readUInt8(),close_flags:n.readUInt8()}}Mo.decodeLedgerData=iK});var Ok=q(Ru=>{"use strict";y();var oK=Ru&&Ru.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ru,"__esModule",{value:!0});Ru.quality=void 0;var aK=ys(),xk=oK(Sn()),Mk=We(),D2=class{static encode(t){let n;try{n=new xk.default(t)}catch{throw new Error(`${t} is not a valid quality`)}let r=(n.e||0)-15,i=n.times(`1e${-r}`).abs().toString(),o=aK.coreTypes.UInt64.from(BigInt(i)).toBytes();return o[0]=r+100,o}static decode(t){let n=(0,Mk.hexToBytes)(t).slice(-8),r=n[0]-100,i;try{i=new xk.default(`0x${(0,Mk.bytesToHex)(n.slice(1))}`)}catch{throw new Error(`${t} is not a valid quality`)}return i.times(`1e${r}`)}};Ru.quality=D2});var Dk=q(ct=>{"use strict";y();var sK=ct&&ct.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),cK=ct&&ct.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Bg=ct&&ct.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&sK(t,e,n);return cK(t,e),t};Object.defineProperty(ct,"__esModule",{value:!0});ct.types=ct.ShaMap=ct.HashPrefix=ct.quality=ct.TransactionResult=ct.Type=ct.LedgerEntryType=ct.TransactionType=ct.Field=ct.DEFAULT_DEFINITIONS=ct.ledgerHashes=ct.binary=ct.hashes=void 0;var Nu=Sa();Object.defineProperty(ct,"DEFAULT_DEFINITIONS",{enumerable:!0,get:function(){return Nu.DEFAULT_DEFINITIONS}});Object.defineProperty(ct,"Field",{enumerable:!0,get:function(){return Nu.Field}});Object.defineProperty(ct,"TransactionType",{enumerable:!0,get:function(){return Nu.TransactionType}});Object.defineProperty(ct,"LedgerEntryType",{enumerable:!0,get:function(){return Nu.LedgerEntryType}});Object.defineProperty(ct,"Type",{enumerable:!0,get:function(){return Nu.Type}});Object.defineProperty(ct,"TransactionResult",{enumerable:!0,get:function(){return Nu.TransactionResult}});var lK=Bg(ys());ct.types=lK;var uK=Bg(k2());ct.binary=uK;var dK=P2();Object.defineProperty(ct,"ShaMap",{enumerable:!0,get:function(){return dK.ShaMap}});var fK=Bg(O2());ct.ledgerHashes=fK;var pK=Bg(Hp());ct.hashes=pK;var yK=Ok();Object.defineProperty(ct,"quality",{enumerable:!0,get:function(){return yK.quality}});var hK=Ou();Object.defineProperty(ct,"HashPrefix",{enumerable:!0,get:function(){return hK.HashPrefix}})});var Rk=q(Fg=>{"use strict";y();Object.defineProperty(Fg,"__esModule",{value:!0});Fg.XrplDefinitions=void 0;var mK=qv(),gK=ys(),R2=class extends mK.XrplDefinitionsBase{constructor(t,n){let r=Object.assign({},gK.coreTypes,n);super(t,r)}};Fg.XrplDefinitions=R2});var Qn=q(Ze=>{"use strict";y();Object.defineProperty(Ze,"__esModule",{value:!0});Ze.coreTypes=Ze.DEFAULT_DEFINITIONS=Ze.XrplDefinitionsBase=Ze.XrplDefinitions=Ze.TRANSACTION_TYPES=Ze.decodeLedgerData=Ze.decodeQuality=Ze.encodeQuality=Ze.encodeForSigningBatch=Ze.encodeForMultisigningSponsor=Ze.encodeForSigningSponsor=Ze.encodeForMultisigningCounterparty=Ze.encodeForSigningCounterparty=Ze.encodeForMultisigning=Ze.encodeForSigningClaim=Ze.encodeForSigning=Ze.encode=Ze.decode=void 0;var ws=Dk(),wK=O2();Object.defineProperty(Ze,"decodeLedgerData",{enumerable:!0,get:function(){return wK.decodeLedgerData}});var N2=Sa();Object.defineProperty(Ze,"XrplDefinitionsBase",{enumerable:!0,get:function(){return N2.XrplDefinitionsBase}});Object.defineProperty(Ze,"TRANSACTION_TYPES",{enumerable:!0,get:function(){return N2.TRANSACTION_TYPES}});Object.defineProperty(Ze,"DEFAULT_DEFINITIONS",{enumerable:!0,get:function(){return N2.DEFAULT_DEFINITIONS}});var bK=Rk();Object.defineProperty(Ze,"XrplDefinitions",{enumerable:!0,get:function(){return bK.XrplDefinitions}});var CK=ys();Object.defineProperty(Ze,"coreTypes",{enumerable:!0,get:function(){return CK.coreTypes}});var Oo=We(),{signingData:L2,signingClaimData:vK,multiSigningData:B2,signingBatchData:AK,binaryToJSON:SK,serializeObject:TK}=ws.binary;function EK(e,t){if(typeof e!="string")throw new Error("binary must be a hex string");return SK(e,t)}Ze.decode=EK;function kK(e,t){if(typeof e!="object")throw new Error;return(0,Oo.bytesToHex)(TK(e,{definitions:t}))}Ze.encode=kK;function _K(e,t){if(typeof e!="object")throw new Error;return(0,Oo.bytesToHex)(L2(e,ws.HashPrefix.transactionSig,{definitions:t}))}Ze.encodeForSigning=_K;function IK(e){if(typeof e!="object")throw new Error;return(0,Oo.bytesToHex)(vK(e))}Ze.encodeForSigningClaim=IK;function PK(e,t,n){if(typeof e!="object")throw new Error;let r=n?{definitions:n}:void 0;return(0,Oo.bytesToHex)(B2(e,t,r))}Ze.encodeForMultisigning=PK;function xK(e,t){if(typeof e!="object")throw new Error;return(0,Oo.bytesToHex)(L2(e,ws.HashPrefix.counterpartyTransactionSig,{definitions:t}))}Ze.encodeForSigningCounterparty=xK;function MK(e,t,n){if(typeof e!="object")throw new Error;return(0,Oo.bytesToHex)(B2(e,t,{prefix:ws.HashPrefix.counterpartyTransactionMultiSig,definitions:n}))}Ze.encodeForMultisigningCounterparty=MK;function OK(e,t){if(typeof e!="object")throw new Error;return(0,Oo.bytesToHex)(L2(e,ws.HashPrefix.sponsorTransactionSig,{definitions:t}))}Ze.encodeForSigningSponsor=OK;function DK(e,t,n){if(typeof e!="object")throw new Error;return(0,Oo.bytesToHex)(B2(e,t,{prefix:ws.HashPrefix.sponsorTransactionMultiSig,definitions:n}))}Ze.encodeForMultisigningSponsor=DK;function RK(e){if(typeof e!="object")throw new Error("Need an object to encode a Batch transaction");return(0,Oo.bytesToHex)(AK(e))}Ze.encodeForSigningBatch=RK;function NK(e){if(typeof e!="string")throw new Error;return(0,Oo.bytesToHex)(ws.quality.encode(e))}Ze.encodeQuality=NK;function LK(e){if(typeof e!="string")throw new Error;return ws.quality.decode(e).toString()}Ze.decodeQuality=LK});var hn=q(wi=>{"use strict";y();Object.defineProperty(wi,"__esModule",{value:!0});wi.isHex=wi.hasFlag=wi.isFlagEnabled=wi.onlyHasFields=wi.INTEGER_SANITY_CHECK=void 0;var BK=/^[0-9A-Fa-f]+$/u;wi.INTEGER_SANITY_CHECK=/^[0-9]+$/u;function FK(e,t){return Object.keys(e).every(n=>t.includes(n))}wi.onlyHasFields=FK;function Nk(e,t){return(BigInt(t)&BigInt(e))===BigInt(t)}wi.isFlagEnabled=Nk;function UK(e,t,n){return e.Flags==null?!1:typeof e.Flags=="number"?Nk(e.Flags,t):e.Flags[n]===!0}wi.hasFlag=UK;function $K(e){return BK.test(e)}wi.isHex=$K});var de=q(ue=>{"use strict";y();Object.defineProperty(ue,"__esModule",{value:!0});ue.isDomainID=ue.containsDuplicates=ue.validateCredentialsList=ue.validateCredentialType=ue.parseAmountValue=ue.validateBaseTransaction=ue.validateSponsorFields=ue.SponsorFlags=ue.GlobalFlags=ue.isMPTIssuer=ue.validateConfidentialMPTAmount=ue.validateOptionalField=ue.validateRequiredField=ue.isHexWithByteLength=ue.validateHexMetadata=ue.isLedgerEntryId=ue.isArray=ue.isXChainBridge=ue.isTokenAmount=ue.isAmount=ue.areAddressesEqual=ue.isAccount=ue.isClawbackAmount=ue.isMPTAmount=ue.isAuthorizeCredential=ue.isIssuedCurrencyAmount=ue.isIssuedCurrency=ue.isCurrency=ue.isXRPLNumber=ue.isValue=ue.isNull=ue.isNumber=ue.isString=ue.isRecord=ue.VAULT_DATA_MAX_BYTE_LENGTH=ue.MAX_MPT_AMOUNT=ue.CONFIDENTIAL_SEND_PROOF_BYTES=ue.CONFIDENTIAL_CONVERT_BACK_PROOF_BYTES=ue.CONFIDENTIAL_CLAWBACK_PROOF_BYTES=ue.CONFIDENTIAL_CONVERT_PROOF_BYTES=ue.CONFIDENTIAL_BLINDING_FACTOR_BYTES=ue.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES=ue.CONFIDENTIAL_EC_POINT_BYTES=ue.MAX_AUTHORIZED_CREDENTIALS=void 0;var Uk=We(),bs=lr(),qK=Qn(),ot=fe(),_a=hn(),HK=3;ue.MAX_AUTHORIZED_CREDENTIALS=8;var VK=64,Lk=VK*2,KK=64;ue.CONFIDENTIAL_EC_POINT_BYTES=33;ue.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES=66;ue.CONFIDENTIAL_BLINDING_FACTOR_BYTES=32;ue.CONFIDENTIAL_CONVERT_PROOF_BYTES=64;ue.CONFIDENTIAL_CLAWBACK_PROOF_BYTES=64;ue.CONFIDENTIAL_CONVERT_BACK_PROOF_BYTES=816;ue.CONFIDENTIAL_SEND_PROOF_BYTES=946;ue.MAX_MPT_AMOUNT=BigInt("9223372036854775807");ue.VAULT_DATA_MAX_BYTE_LENGTH=256;function zK(e){if(!dr(e))return!1;let t=e.Memo;if(!dr(t))return!1;let n=Object.keys(t).length,r=t.MemoData==null||nt(t.MemoData)&&(0,_a.isHex)(t.MemoData),i=t.MemoFormat==null||nt(t.MemoFormat)&&(0,_a.isHex)(t.MemoFormat),o=t.MemoType==null||nt(t.MemoType)&&(0,_a.isHex)(t.MemoType);return n>=1&&n<=HK&&r&&i&&o&&(0,_a.onlyHasFields)(t,["MemoFormat","MemoData","MemoType"])}var jK=3;function $k(e){if(!dr(e))return!1;let t=e.Signer;return dr(t)?Object.keys(t).length===jK&&nt(t.Account)&&nt(t.TxnSignature)&&nt(t.SigningPubKey):!1}function XK(e,t){if(!dr(e))return!1;if(t)return e.SigningPubKey===""&&e.TxnSignature===void 0&&e.Signers===void 0;let n=e.SigningPubKey!==void 0,r=e.TxnSignature!==void 0,i=e.Signers!==void 0,o=n&&r,a=i;return!(o&&a||!o&&!a||o&&(!nt(e.SigningPubKey)||!nt(e.TxnSignature))||a&&(!jp(e.Signers)||!e.Signers.every($k)))}var qk=1,WK=1,Hk=2,GK=2,YK=3,ZK=4,JK=1;function dr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}ue.isRecord=dr;function nt(e){return typeof e=="string"}ue.isString=nt;function Hc(e){return typeof e=="number"}ue.isNumber=Hc;function QK(e){return e==null}ue.isNull=QK;function ez(e){return n=>n===e}ue.isValue=ez;function tz(e){return typeof e=="string"&&/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/u.test(e.trim())}ue.isXRPLNumber=tz;function nz(e){return dr(e)&&(Object.keys(e).length===Hk&&nt(e.issuer)&&nt(e.currency)||Object.keys(e).length===qk&&e.currency==="XRP"||Object.keys(e).length===WK&&nt(e.mpt_issuance_id))}ue.isCurrency=nz;function F2(e){return dr(e)&&(Object.keys(e).length===Hk&&nt(e.issuer)&&nt(e.currency)||Object.keys(e).length===qk&&e.currency==="XRP")}ue.isIssuedCurrency=F2;function Ug(e){return dr(e)&&Object.keys(e).length===YK&&nt(e.value)&&nt(e.issuer)&&nt(e.currency)}ue.isIssuedCurrencyAmount=Ug;function Vk(e){return dr(e)&&dr(e.Credential)&&Object.keys(e).length===JK&&typeof e.Credential.CredentialType=="string"&&typeof e.Credential.Issuer=="string"}ue.isAuthorizeCredential=Vk;function $g(e){return dr(e)&&Object.keys(e).length===GK&&typeof e.value=="string"&&typeof e.mpt_issuance_id=="string"}ue.isMPTAmount=$g;function rz(e){return Ug(e)||$g(e)}ue.isClawbackAmount=rz;function $2(e){return typeof e=="string"&&((0,bs.isValidClassicAddress)(e)||(0,bs.isValidXAddress)(e))}ue.isAccount=$2;function Bk(e){return(0,bs.isValidXAddress)(e)?(0,bs.xAddressToClassicAddress)(e).classicAddress:e}function q2(e,t){return Bk(e)===Bk(t)}ue.areAddressesEqual=q2;function Kk(e){return typeof e=="string"||Ug(e)||$g(e)}ue.isAmount=Kk;function iz(e){return Ug(e)||$g(e)}ue.isTokenAmount=iz;function oz(e){return dr(e)&&Object.keys(e).length===ZK&&typeof e.LockingChainDoor=="string"&&F2(e.LockingChainIssue)&&typeof e.IssuingChainDoor=="string"&&F2(e.IssuingChainIssue)}ue.isXChainBridge=oz;function jp(e){return e!=null&&Array.isArray(e)}ue.isArray=jp;function az(e){return nt(e)&&(0,_a.isHex)(e)&&e.length===KK}ue.isLedgerEntryId=az;function sz(e,t){return nt(e)&&(0,_a.isHex)(e)&&e.length>0&&e.length<=t}ue.validateHexMetadata=sz;function cz(e){return n=>nt(n)&&(0,_a.isHex)(n)&&n.length===e*2}ue.isHexWithByteLength=cz;function H2(e,t,n,r={}){var i,o;let a=(i=r.paramName)!==null&&i!==void 0?i:t,s=(o=r.txType)!==null&&o!==void 0?o:e.TransactionType;if(e[t]==null)throw new ot.ValidationError(`${s}: missing field ${String(a)}`);if(!n(e[t]))throw new ot.ValidationError(`${s}: invalid field ${String(a)}`)}ue.validateRequiredField=H2;function ro(e,t,n,r={}){var i,o;let a=(i=r.paramName)!==null&&i!==void 0?i:t,s=(o=r.txType)!==null&&o!==void 0?o:e.TransactionType;if(e[t]!==void 0&&!n(e[t]))throw new ot.ValidationError(`${s}: invalid field ${String(a)}`)}ue.validateOptionalField=ro;function lz(e,t){if(H2(e,"MPTAmount",nt),!_a.INTEGER_SANITY_CHECK.exec(e.MPTAmount))throw new ot.ValidationError(`${e.TransactionType}: Invalid MPTAmount`);let n=BigInt(e.MPTAmount);if(n>ue.MAX_MPT_AMOUNT||!t&&n===BigInt(0))throw new ot.ValidationError(`${e.TransactionType}: MPTAmount out of range`)}ue.validateConfidentialMPTAmount=lz;var uz=8;function dz(e,t){if(!nt(e)||!nt(t))return!1;let n=(0,bs.isValidXAddress)(e)?(0,bs.xAddressToClassicAddress)(e).classicAddress:e;return(0,bs.isValidClassicAddress)(n)?(0,Uk.bytesToHex)((0,bs.decodeAccountID)(n)).toUpperCase()===t.slice(uz).toUpperCase():!1}ue.isMPTIssuer=dz;var U2;(function(e){e[e.tfInnerBatchTxn=1073741824]="tfInnerBatchTxn"})(U2||(ue.GlobalFlags=U2={}));var Lu;(function(e){e[e.spfSponsorFee=1]="spfSponsorFee",e[e.spfSponsorReserve=2]="spfSponsorReserve"})(Lu||(ue.SponsorFlags=Lu={}));var fz=new Set(["DelegateSet","DepositPreauth","Payment","SignerListSet","CheckCancel","CheckCash","CheckCreate","EscrowCancel","EscrowCreate","EscrowFinish","PaymentChannelClaim","PaymentChannelCreate","PaymentChannelFund","Clawback","MPTokenAuthorize","MPTokenIssuanceCreate","MPTokenIssuanceDestroy","MPTokenIssuanceSet","TrustSet","CredentialAccept","CredentialCreate","CredentialDelete","AccountSet","SetRegularKey","SponsorshipTransfer"]);function pz(e){return typeof e.Flags=="number"?(e.Flags&U2.tfInnerBatchTxn)!==0:dr(e.Flags)?e.Flags.tfInnerBatchTxn===!0:!1}function yz(e,t,n,r){let i=Lu.spfSponsorFee|Lu.spfSponsorReserve;if((e&~i)!==0)throw new ot.ValidationError("Transaction: SponsorFlags contains invalid flags");if(e===0)throw new ot.ValidationError("Transaction: SponsorFlags must have at least one flag set");let o=(e&Lu.spfSponsorReserve)!==0,a=(e&Lu.spfSponsorFee)!==0;if(o&&t&&!fz.has(t))throw new ot.ValidationError(`Transaction: ${t} cannot use spfSponsorReserve flag (does not create ledger objects)`);if(o&&n)throw new ot.ValidationError("Transaction: SponsorFlags.spfSponsorReserve cannot be combined with Delegate (reserve sponsorship under permissioned delegation is disallowed)");if(a&&r)throw new ot.ValidationError("Transaction: SponsorFlags.spfSponsorFee is not allowed on inner Batch transactions")}function zk(e){let t=String(e.TransactionType),n=pz(e),r=e.Sponsor,i=e.SponsorFlags,o=e.SponsorSignature,a=r!==void 0,s=i!==void 0,c=o!==void 0;if((a||s||c)&&(!a||!s))throw new ot.ValidationError("Transaction: Sponsor and SponsorFlags must both be present for sponsored transactions");if(a){if(!nt(r))throw new ot.ValidationError("Transaction: Sponsor must be a string");if(!$2(r))throw new ot.ValidationError("Transaction: Sponsor must be a valid account address")}if(s){if(!Hc(i))throw new ot.ValidationError("Transaction: SponsorFlags must be a number");yz(i,t,e.Delegate!==void 0,n)}if(c&&!XK(o,n))throw new ot.ValidationError("Transaction: invalid SponsorSignature");if(a&&nt(r)&&nt(e.Account)&&q2(r,e.Account))throw new ot.ValidationError("Transaction: Sponsor and Account cannot be the same (self-sponsorship not allowed)")}ue.validateSponsorFields=zk;function hz(e){if(!dr(e))throw new ot.ValidationError("BaseTransaction: invalid, expected a valid object");if(e.TransactionType===void 0)throw new ot.ValidationError("BaseTransaction: missing field TransactionType");if(typeof e.TransactionType!="string")throw new ot.ValidationError("BaseTransaction: TransactionType not string");if(!qK.TRANSACTION_TYPES.includes(e.TransactionType))throw new ot.ValidationError(`BaseTransaction: Unknown TransactionType ${e.TransactionType}`);H2(e,"Account",nt),ro(e,"Fee",nt),ro(e,"Sequence",Hc),ro(e,"AccountTxnID",nt),ro(e,"LastLedgerSequence",Hc);let t=e.Memos;if(t!=null&&(!jp(t)||!t.every(zK)))throw new ot.ValidationError("BaseTransaction: invalid Memos");let n=e.Signers;if(n!=null&&(!jp(n)||n.length===0||!n.every($k)))throw new ot.ValidationError("BaseTransaction: invalid Signers");ro(e,"SourceTag",Hc),ro(e,"SigningPubKey",nt),ro(e,"TicketSequence",Hc),ro(e,"TxnSignature",nt),ro(e,"NetworkID",Hc),ro(e,"Delegate",$2);let r=e.Delegate;if(r!=null&&nt(r)&&nt(e.Account)&&q2(r,e.Account))throw new ot.ValidationError("BaseTransaction: Account and Delegate addresses cannot be the same");zk(e)}ue.validateBaseTransaction=hz;function mz(e){return Kk(e)?parseFloat(typeof e=="string"?e:e.value):NaN}ue.parseAmountValue=mz;function gz(e){if(typeof e.TransactionType!="string")throw new ot.ValidationError("Invalid TransactionType");if(e.CredentialType===void 0)throw new ot.ValidationError(`${e.TransactionType}: missing field CredentialType`);if(!nt(e.CredentialType))throw new ot.ValidationError(`${e.TransactionType}: CredentialType must be a string`);if(e.CredentialType.length===0)throw new ot.ValidationError(`${e.TransactionType}: CredentialType cannot be an empty string`);if(e.CredentialType.length>Lk)throw new ot.ValidationError(`${e.TransactionType}: CredentialType length cannot be > ${Lk}`);if(!Uk.HEX_REGEX.test(e.CredentialType))throw new ot.ValidationError(`${e.TransactionType}: CredentialType must be encoded in hex`)}ue.validateCredentialType=gz;function wz(e,t,n,r){if(e!=null){if(!jp(e))throw new ot.ValidationError(`${t}: Credentials must be an array`);if(e.length>r)throw new ot.ValidationError(`${t}: Credentials length cannot exceed ${r} elements`);if(e.length===0)throw new ot.ValidationError(`${t}: Credentials cannot be an empty array`);if(e.forEach(i=>{if(n){if(!nt(i))throw new ot.ValidationError(`${t}: Invalid Credentials ID list format`)}else if(!Vk(i))throw new ot.ValidationError(`${t}: Invalid Credentials format`)}),jk(e))throw new ot.ValidationError(`${t}: Credentials cannot contain duplicate elements`)}}ue.validateCredentialsList=wz;function bz(e){return typeof e[0]!="string"}function jk(e){if(typeof e[0]=="string")return new Set(e.map(r=>JSON.stringify(r))).size!==e.length;let t=new Set;if(bz(e))for(let n of e){let r=`${n.Credential.Issuer}-${n.Credential.CredentialType}`;if(t.has(r))return!0;t.add(r)}return!1}ue.containsDuplicates=jk;var Fk=64;function Cz(e){return nt(e)&&e.length===Fk&&(0,_a.isHex)(e)&&e!=="0".repeat(Fk)}ue.isDomainID=Cz});var Hg=q(Cs=>{"use strict";y();Object.defineProperty(Cs,"__esModule",{value:!0});Cs.validateAccountSet=Cs.AccountSetTfFlags=Cs.AccountSetAsfFlags=void 0;var Do=fe(),V2=de(),qg;(function(e){e[e.asfRequireDest=1]="asfRequireDest",e[e.asfRequireAuth=2]="asfRequireAuth",e[e.asfDisallowXRP=3]="asfDisallowXRP",e[e.asfDisableMaster=4]="asfDisableMaster",e[e.asfAccountTxnID=5]="asfAccountTxnID",e[e.asfNoFreeze=6]="asfNoFreeze",e[e.asfGlobalFreeze=7]="asfGlobalFreeze",e[e.asfDefaultRipple=8]="asfDefaultRipple",e[e.asfDepositAuth=9]="asfDepositAuth",e[e.asfAuthorizedNFTokenMinter=10]="asfAuthorizedNFTokenMinter",e[e.asfDisallowIncomingNFTokenOffer=12]="asfDisallowIncomingNFTokenOffer",e[e.asfDisallowIncomingCheck=13]="asfDisallowIncomingCheck",e[e.asfDisallowIncomingPayChan=14]="asfDisallowIncomingPayChan",e[e.asfDisallowIncomingTrustline=15]="asfDisallowIncomingTrustline",e[e.asfAllowTrustLineClawback=16]="asfAllowTrustLineClawback",e[e.asfAllowTrustLineLocking=17]="asfAllowTrustLineLocking"})(qg||(Cs.AccountSetAsfFlags=qg={}));var Xk;(function(e){e[e.tfRequireDestTag=65536]="tfRequireDestTag",e[e.tfOptionalDestTag=131072]="tfOptionalDestTag",e[e.tfRequireAuth=262144]="tfRequireAuth",e[e.tfOptionalAuth=524288]="tfOptionalAuth",e[e.tfDisallowXRP=1048576]="tfDisallowXRP",e[e.tfAllowXRP=2097152]="tfAllowXRP"})(Xk||(Cs.AccountSetTfFlags=Xk={}));var vz=3,Az=15;function Sz(e){if((0,V2.validateBaseTransaction)(e),(0,V2.validateOptionalField)(e,"NFTokenMinter",V2.isAccount),e.ClearFlag!==void 0){if(typeof e.ClearFlag!="number")throw new Do.ValidationError("AccountSet: invalid ClearFlag");if(!Object.values(qg).includes(e.ClearFlag))throw new Do.ValidationError("AccountSet: invalid ClearFlag")}if(e.Domain!==void 0&&typeof e.Domain!="string")throw new Do.ValidationError("AccountSet: invalid Domain");if(e.EmailHash!==void 0&&typeof e.EmailHash!="string")throw new Do.ValidationError("AccountSet: invalid EmailHash");if(e.MessageKey!==void 0&&typeof e.MessageKey!="string")throw new Do.ValidationError("AccountSet: invalid MessageKey");if(e.SetFlag!==void 0){if(typeof e.SetFlag!="number")throw new Do.ValidationError("AccountSet: invalid SetFlag");if(!Object.values(qg).includes(e.SetFlag))throw new Do.ValidationError("AccountSet: invalid SetFlag")}if(e.TransferRate!==void 0&&typeof e.TransferRate!="number")throw new Do.ValidationError("AccountSet: invalid TransferRate");if(e.TickSize!==void 0){if(typeof e.TickSize!="number")throw new Do.ValidationError("AccountSet: invalid TickSize");if(e.TickSize!==0&&(e.TickSizeAz))throw new Do.ValidationError("AccountSet: invalid TickSize")}}Cs.validateAccountSet=Sz});var Kg=q(Bu=>{"use strict";y();Object.defineProperty(Bu,"__esModule",{value:!0});Bu.validateAMMClawback=Bu.AMMClawbackFlags=void 0;var Vg=fe(),Ia=de(),Wk;(function(e){e[e.tfClawTwoAssets=1]="tfClawTwoAssets"})(Wk||(Bu.AMMClawbackFlags=Wk={}));function Tz(e){(0,Ia.validateBaseTransaction)(e),(0,Ia.validateRequiredField)(e,"Holder",Ia.isAccount),(0,Ia.validateRequiredField)(e,"Asset",Ia.isIssuedCurrency);let t=e.Asset;if(e.Holder===t.issuer)throw new Vg.ValidationError("AMMClawback: Holder and Asset.issuer must be distinct");if(e.Account!==t.issuer)throw new Vg.ValidationError("AMMClawback: Account must be the same as Asset.issuer");if((0,Ia.validateRequiredField)(e,"Asset2",Ia.isIssuedCurrency),(0,Ia.validateOptionalField)(e,"Amount",Ia.isIssuedCurrencyAmount),e.Amount!=null){if(e.Amount.currency!==t.currency)throw new Vg.ValidationError("AMMClawback: Amount.currency must match Asset.currency");if(e.Amount.issuer!==t.issuer)throw new Vg.ValidationError("AMMClawback: Amount.issuer must match Amount.issuer")}}Bu.validateAMMClawback=Tz});var zg=q(Fu=>{"use strict";y();Object.defineProperty(Fu,"__esModule",{value:!0});Fu.validateAMMDeposit=Fu.AMMDepositFlags=void 0;var io=fe(),Vc=de(),Gk;(function(e){e[e.tfLPToken=65536]="tfLPToken",e[e.tfSingleAsset=524288]="tfSingleAsset",e[e.tfTwoAsset=1048576]="tfTwoAsset",e[e.tfOneAssetLPToken=2097152]="tfOneAssetLPToken",e[e.tfLimitLPToken=4194304]="tfLimitLPToken",e[e.tfTwoAssetIfEmpty=8388608]="tfTwoAssetIfEmpty"})(Gk||(Fu.AMMDepositFlags=Gk={}));function Ez(e){if((0,Vc.validateBaseTransaction)(e),e.Asset==null)throw new io.ValidationError("AMMDeposit: missing field Asset");if(!(0,Vc.isIssuedCurrency)(e.Asset))throw new io.ValidationError("AMMDeposit: Asset must be a Currency");if(e.Asset2==null)throw new io.ValidationError("AMMDeposit: missing field Asset2");if(!(0,Vc.isIssuedCurrency)(e.Asset2))throw new io.ValidationError("AMMDeposit: Asset2 must be a Currency");if(e.Amount2!=null&&e.Amount==null)throw new io.ValidationError("AMMDeposit: must set Amount with Amount2");if(e.EPrice!=null&&e.Amount==null)throw new io.ValidationError("AMMDeposit: must set Amount with EPrice");if(e.LPTokenOut==null&&e.Amount==null)throw new io.ValidationError("AMMDeposit: must set at least LPTokenOut or Amount");if(e.LPTokenOut!=null&&!(0,Vc.isIssuedCurrencyAmount)(e.LPTokenOut))throw new io.ValidationError("AMMDeposit: LPTokenOut must be an IssuedCurrencyAmount");if(e.Amount!=null&&!(0,Vc.isAmount)(e.Amount))throw new io.ValidationError("AMMDeposit: Amount must be an Amount");if(e.Amount2!=null&&!(0,Vc.isAmount)(e.Amount2))throw new io.ValidationError("AMMDeposit: Amount2 must be an Amount");if(e.EPrice!=null&&!(0,Vc.isAmount)(e.EPrice))throw new io.ValidationError("AMMDeposit: EPrice must be an Amount")}Fu.validateAMMDeposit=Ez});var jg=q(Uu=>{"use strict";y();Object.defineProperty(Uu,"__esModule",{value:!0});Uu.validateAMMWithdraw=Uu.AMMWithdrawFlags=void 0;var Ro=fe(),Kc=de(),Yk;(function(e){e[e.tfLPToken=65536]="tfLPToken",e[e.tfWithdrawAll=131072]="tfWithdrawAll",e[e.tfOneAssetWithdrawAll=262144]="tfOneAssetWithdrawAll",e[e.tfSingleAsset=524288]="tfSingleAsset",e[e.tfTwoAsset=1048576]="tfTwoAsset",e[e.tfOneAssetLPToken=2097152]="tfOneAssetLPToken",e[e.tfLimitLPToken=4194304]="tfLimitLPToken"})(Yk||(Uu.AMMWithdrawFlags=Yk={}));function kz(e){if((0,Kc.validateBaseTransaction)(e),e.Asset==null)throw new Ro.ValidationError("AMMWithdraw: missing field Asset");if(!(0,Kc.isIssuedCurrency)(e.Asset))throw new Ro.ValidationError("AMMWithdraw: Asset must be a Currency");if(e.Asset2==null)throw new Ro.ValidationError("AMMWithdraw: missing field Asset2");if(!(0,Kc.isIssuedCurrency)(e.Asset2))throw new Ro.ValidationError("AMMWithdraw: Asset2 must be a Currency");if(e.Amount2!=null&&e.Amount==null)throw new Ro.ValidationError("AMMWithdraw: must set Amount with Amount2");if(e.EPrice!=null&&e.Amount==null)throw new Ro.ValidationError("AMMWithdraw: must set Amount with EPrice");if(e.LPTokenIn!=null&&!(0,Kc.isIssuedCurrencyAmount)(e.LPTokenIn))throw new Ro.ValidationError("AMMWithdraw: LPTokenIn must be an IssuedCurrencyAmount");if(e.Amount!=null&&!(0,Kc.isAmount)(e.Amount))throw new Ro.ValidationError("AMMWithdraw: Amount must be an Amount");if(e.Amount2!=null&&!(0,Kc.isAmount)(e.Amount2))throw new Ro.ValidationError("AMMWithdraw: Amount2 must be an Amount");if(e.EPrice!=null&&!(0,Kc.isAmount)(e.EPrice))throw new Ro.ValidationError("AMMWithdraw: EPrice must be an Amount")}Uu.validateAMMWithdraw=kz});var Xp=q($u=>{"use strict";y();Object.defineProperty($u,"__esModule",{value:!0});$u.validateBatch=$u.BatchFlags=void 0;var Xg=fe(),_z=hn(),bt=de(),Zk;(function(e){e[e.tfAllOrNothing=65536]="tfAllOrNothing",e[e.tfOnlyOne=131072]="tfOnlyOne",e[e.tfUntilFailure=262144]="tfUntilFailure",e[e.tfIndependent=524288]="tfIndependent"})(Zk||($u.BatchFlags=Zk={}));function Iz(e,t){if(e.TransactionType==="Batch")throw new Xg.ValidationError(`Batch: RawTransactions[${t}] is a Batch transaction. Cannot nest Batch transactions.`);if(!(0,_z.hasFlag)(e,bt.GlobalFlags.tfInnerBatchTxn,"tfInnerBatchTxn"))throw new Xg.ValidationError(`Batch: RawTransactions[${t}] must contain the \`tfInnerBatchTxn\` flag.`);(0,bt.validateOptionalField)(e,"Fee",(0,bt.isValue)("0"),{paramName:`RawTransactions[${t}].RawTransaction.Fee`,txType:"Batch"}),(0,bt.validateOptionalField)(e,"SigningPubKey",(0,bt.isValue)(""),{paramName:`RawTransactions[${t}].RawTransaction.SigningPubKey`,txType:"Batch"}),(0,bt.validateOptionalField)(e,"TxnSignature",bt.isNull,{paramName:`RawTransactions[${t}].RawTransaction.TxnSignature`,txType:"Batch"}),(0,bt.validateOptionalField)(e,"Signers",bt.isNull,{paramName:`RawTransactions[${t}].RawTransaction.Signers`,txType:"Batch"}),(0,bt.validateOptionalField)(e,"LastLedgerSequence",bt.isNull,{paramName:`RawTransactions[${t}].RawTransaction.LastLedgerSequence`,txType:"Batch"})}function Pz(e){var t;(0,bt.validateBaseTransaction)(e),(0,bt.validateRequiredField)(e,"RawTransactions",bt.isArray),e.RawTransactions.forEach((n,r)=>{if(!(0,bt.isRecord)(n))throw new Xg.ValidationError(`Batch: RawTransactions[${r}] is not object.`);(0,bt.validateRequiredField)(n,"RawTransaction",bt.isRecord,{paramName:`RawTransactions[${r}].RawTransaction`,txType:"Batch"});let i=n.RawTransaction;Iz(i,r)}),(0,bt.validateOptionalField)(e,"BatchSigners",bt.isArray),(t=e.BatchSigners)===null||t===void 0||t.forEach((n,r)=>{if(!(0,bt.isRecord)(n))throw new Xg.ValidationError(`Batch: BatchSigners[${r}] is not object.`);let i=n;(0,bt.validateRequiredField)(i,"BatchSigner",bt.isRecord,{paramName:`BatchSigners[${r}].BatchSigner`,txType:"Batch"});let o=i.BatchSigner;(0,bt.validateRequiredField)(o,"Account",bt.isString,{paramName:`BatchSigners[${r}].BatchSigner.Account`,txType:"Batch"}),(0,bt.validateOptionalField)(o,"SigningPubKey",bt.isString,{paramName:`BatchSigners[${r}].BatchSigner.SigningPubKey`,txType:"Batch"}),(0,bt.validateOptionalField)(o,"TxnSignature",bt.isString,{paramName:`BatchSigners[${r}].BatchSigner.TxnSignature`,txType:"Batch"}),(0,bt.validateOptionalField)(o,"Signers",bt.isArray,{paramName:`BatchSigners[${r}].BatchSigner.Signers`,txType:"Batch"})})}$u.validateBatch=Pz});var Gg=q(qu=>{"use strict";y();Object.defineProperty(qu,"__esModule",{value:!0});qu.validateLoanManage=qu.LoanManageFlags=void 0;var Jk=fe(),Wg=de(),vs;(function(e){e[e.tfLoanDefault=65536]="tfLoanDefault",e[e.tfLoanImpair=131072]="tfLoanImpair",e[e.tfLoanUnimpair=262144]="tfLoanUnimpair"})(vs||(qu.LoanManageFlags=vs={}));function xz(e){if((0,Wg.validateBaseTransaction)(e),(0,Wg.validateRequiredField)(e,"LoanID",Wg.isString),!(0,Wg.isLedgerEntryId)(e.LoanID))throw new Jk.ValidationError("LoanManage: LoanID must be 64 characters hexadecimal string");let t=e.Flags;if(t==null)return;let n=0;if(typeof t=="number"?n=t:(t.tfLoanImpair&&(n|=vs.tfLoanImpair),t.tfLoanUnimpair&&(n|=vs.tfLoanUnimpair)),(n&vs.tfLoanImpair)===vs.tfLoanImpair&&(n&vs.tfLoanUnimpair)===vs.tfLoanUnimpair)throw new Jk.ValidationError("LoanManage: tfLoanImpair and tfLoanUnimpair cannot both be present")}qu.validateLoanManage=xz});var Yg=q(Vu=>{"use strict";y();Object.defineProperty(Vu,"__esModule",{value:!0});Vu.validateLoanPay=Vu.LoanPayFlags=void 0;var K2=fe(),z2=hn(),Hu=de(),Wp;(function(e){e[e.tfLoanOverpayment=65536]="tfLoanOverpayment",e[e.tfLoanFullPayment=131072]="tfLoanFullPayment",e[e.tfLoanLatePayment=262144]="tfLoanLatePayment"})(Wp||(Vu.LoanPayFlags=Wp={}));function Mz(e){if((0,Hu.validateBaseTransaction)(e),(0,Hu.validateRequiredField)(e,"LoanID",Hu.isString),(0,Hu.validateRequiredField)(e,"Amount",Hu.isAmount),!(0,Hu.isLedgerEntryId)(e.LoanID))throw new K2.ValidationError("LoanPay: LoanID must be 64 characters hexadecimal string");if(typeof e.Flags=="number"){if([(0,z2.isFlagEnabled)(e.Flags,Wp.tfLoanLatePayment),(0,z2.isFlagEnabled)(e.Flags,Wp.tfLoanFullPayment),(0,z2.isFlagEnabled)(e.Flags,Wp.tfLoanOverpayment)].filter(Boolean).length>1)throw new K2.ValidationError("LoanPay: Only one of tfLoanLatePayment, tfLoanFullPayment, or tfLoanOverpayment flags can be set")}else if(e.Flags!=null&&typeof e.Flags=="object"){let t=e.Flags;if([t.tfLoanLatePayment,t.tfLoanFullPayment,t.tfLoanOverpayment].filter(Boolean).length>1)throw new K2.ValidationError("LoanPay: Only one of tfLoanLatePayment, tfLoanFullPayment, or tfLoanOverpayment flags can be set")}}Vu.validateLoanPay=Mz});var Zg=q(Ku=>{"use strict";y();Object.defineProperty(Ku,"__esModule",{value:!0});Ku.validateMPTokenAuthorize=Ku.MPTokenAuthorizeFlags=void 0;var Gp=de(),Qk;(function(e){e[e.tfMPTUnauthorize=1]="tfMPTUnauthorize"})(Qk||(Ku.MPTokenAuthorizeFlags=Qk={}));function Oz(e){(0,Gp.validateBaseTransaction)(e),(0,Gp.validateRequiredField)(e,"MPTokenIssuanceID",Gp.isString),(0,Gp.validateOptionalField)(e,"Holder",Gp.isAccount)}Ku.validateMPTokenAuthorize=Oz});var Jg=q((Hye,e_)=>{"use strict";y();e_.exports=function(e,t){t||(t={}),typeof t=="function"&&(t={cmp:t});var n=typeof t.cycles=="boolean"?t.cycles:!1,r=t.cmp&&(function(o){return function(a){return function(s,c){var l={key:s,value:a[s]},u={key:c,value:a[c]};return o(l,u)}}})(t.cmp),i=[];return(function o(a){if(a&&a.toJSON&&typeof a.toJSON=="function"&&(a=a.toJSON()),a!==void 0){if(typeof a=="number")return isFinite(a)?""+a:"null";if(typeof a!="object")return JSON.stringify(a);var s,c;if(Array.isArray(a)){for(c="[",s=0;s{"use strict";y();var Dz=er&&er.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(er,"__esModule",{value:!0});er.validateMPTokenMetadata=er.decodeMPTokenMetadata=er.encodeMPTokenMetadata=er.MPT_META_WARNING_HEADER=er.MAX_MPT_META_BYTE_LENGTH=void 0;var W2=We(),Rz=Dz(Jg()),bn=de(),t_=hn();er.MAX_MPT_META_BYTE_LENGTH=1024;er.MPT_META_WARNING_HEADER="MPTokenMetadata is not properly formatted as JSON as per the XLS-89 standard. While adherence to this standard is not mandatory, such non-compliant MPToken's might not be discoverable by Explorers and Indexers in the XRPL ecosystem.";var zu=[{long:"uri",compact:"u"},{long:"category",compact:"c"},{long:"title",compact:"t"}],Yp=[{long:"ticker",compact:"t",validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];return!(0,bn.isString)(n)||!/^[A-Z0-9]{1,6}$/u.test(n)?[`${this.long}/${this.compact}: should have uppercase letters (A-Z) and digits (0-9) only. Max 6 characters recommended.`]:[]}},{long:"name",compact:"n",validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];return!(0,bn.isString)(n)||n.length===0?[`${this.long}/${this.compact}: should be a non-empty string.`]:[]}},{long:"icon",compact:"i",validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];return!(0,bn.isString)(n)||n.length===0?[`${this.long}/${this.compact}: should be a non-empty string.`]:[]}},{long:"asset_class",compact:"ac",validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact],r=["rwa","memes","wrapped","gaming","defi","other"];return!(0,bn.isString)(n)||!r.includes(n)?[`${this.long}/${this.compact}: should be one of ${r.join(", ")}.`]:[]}},{long:"issuer_name",compact:"in",validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];return!(0,bn.isString)(n)||n.length===0?[`${this.long}/${this.compact}: should be a non-empty string.`]:[]}},{long:"desc",compact:"d",validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];if(e[this.long]===void 0&&e[this.compact]===void 0)return[];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];return!(0,bn.isString)(n)||n.length===0?[`${this.long}/${this.compact}: should be a non-empty string.`]:[]}},{long:"asset_subclass",compact:"as",required:!1,validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];if((e.asset_class==="rwa"||e.ac==="rwa")&&n===void 0)return[`${this.long}/${this.compact}: required when asset_class is rwa.`];if(e[this.long]===void 0&&e[this.compact]===void 0)return[];let r=["stablecoin","commodity","real_estate","private_credit","equity","treasury","other"];return!(0,bn.isString)(n)||!r.includes(n)?[`${this.long}/${this.compact}: should be one of ${r.join(", ")}.`]:[]}},{long:"uris",compact:"us",required:!1,validate(e){var t,n,r,i;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];if(e[this.long]===void 0&&e[this.compact]===void 0)return[];let o=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];if(!Array.isArray(o)||o.length===0)return[`${this.long}/${this.compact}: should be a non-empty array.`];let a=[];for(let s of o){if(!(0,bn.isRecord)(s)||Object.keys(s).length!==zu.length){a.push(`${this.long}/${this.compact}: should be an array of objects each with uri/u, category/c, and title/t properties.`);continue}for(let d of zu)if(s[d.long]!=null&&s[d.compact]!=null){a.push(`${this.long}/${this.compact}: should not have both ${d.long} and ${d.compact} fields.`);break}let c=(n=s.uri)!==null&&n!==void 0?n:s.u,l=(r=s.category)!==null&&r!==void 0?r:s.c,u=(i=s.title)!==null&&i!==void 0?i:s.t;(!(0,bn.isString)(c)||!(0,bn.isString)(l)||!(0,bn.isString)(u))&&a.push(`${this.long}/${this.compact}: should be an array of objects each with uri/u, category/c, and title/t properties.`)}return a}},{long:"additional_info",compact:"ai",required:!1,validate(e){var t;if(e[this.long]!=null&&e[this.compact]!=null)return[`${this.long}/${this.compact}: both long and compact forms present. expected only one.`];if(e[this.long]===void 0&&e[this.compact]===void 0)return[];let n=(t=e[this.long])!==null&&t!==void 0?t:e[this.compact];return!(0,bn.isString)(n)&&!(0,bn.isRecord)(n)?[`${this.long}/${this.compact}: should be a string or JSON object.`]:[]}}];function j2(e,t){let n={};for(let[r,i]of Object.entries(e)){let o=t.find(({long:a,compact:s})=>a===r||s===r);if(o===void 0){n[r]=i;continue}if(e[o.long]!==void 0&&e[o.compact]!==void 0){n[r]=i;continue}n[o.compact]=i}return n}function Nz(e){let t=e;if(!(0,bn.isRecord)(t))throw new Error("MPTokenMetadata must be JSON object.");return t=j2(t,Yp),Array.isArray(t.uris)&&(t.uris=t.uris.map(n=>(0,bn.isRecord)(n)?j2(n,zu):n)),Array.isArray(t.us)&&(t.us=t.us.map(n=>(0,bn.isRecord)(n)?j2(n,zu):n)),(0,W2.stringToHex)((0,Rz.default)(t)).toUpperCase()}er.encodeMPTokenMetadata=Nz;function X2(e,t){let n={};for(let[r,i]of Object.entries(e)){let o=t.find(({long:a,compact:s})=>a===r||s===r);if(o===void 0){n[r]=i;continue}if(e[o.long]!==void 0&&e[o.compact]!==void 0){n[r]=i;continue}n[o.long]=i}return n}function Lz(e){if(!(0,t_.isHex)(e))throw new Error("MPTokenMetadata must be in hex format.");let t;try{t=JSON.parse((0,W2.hexToString)(e))}catch(r){throw new Error(`MPTokenMetadata is not properly formatted as JSON - ${String(r)}`)}if(!(0,bn.isRecord)(t))throw new Error("MPTokenMetadata must be a JSON object.");let n=t;return n=X2(n,Yp),Array.isArray(n.uris)&&(n.uris=n.uris.map(r=>(0,bn.isRecord)(r)?X2(r,zu):r)),Array.isArray(n.us)&&(n.us=n.us.map(r=>(0,bn.isRecord)(r)?X2(r,zu):r)),n}er.decodeMPTokenMetadata=Lz;function Bz(e){let t=[];if(!(0,t_.isHex)(e))return t.push("MPTokenMetadata must be in hex format."),t;if(e.length/2>er.MAX_MPT_META_BYTE_LENGTH)return t.push(`MPTokenMetadata must be max ${er.MAX_MPT_META_BYTE_LENGTH} bytes.`),t;let n;try{n=JSON.parse((0,W2.hexToString)(e))}catch(i){return t.push(`MPTokenMetadata is not properly formatted as JSON - ${String(i)}`),t}if(!(0,bn.isRecord)(n))return t.push("MPTokenMetadata is not properly formatted JSON object as per XLS-89."),t;Object.keys(n).length>Yp.length&&t.push(`MPTokenMetadata must not contain more than ${Yp.length} top-level fields (found ${Object.keys(n).length}).`);let r=n;for(let i of Yp)t.push(...i.validate(r));return t}er.validateMPTokenMetadata=Bz});var ey=q(fr=>{"use strict";y();Object.defineProperty(fr,"__esModule",{value:!0});fr.validateMPTokenIssuanceCreate=fr.tifMPTokenIssuanceImmutableMask=fr.MPTokenIssuanceCreateImmutableFlags=fr.MPTokenIssuanceCreateFlags=fr.MAX_TRANSFER_FEE=void 0;var As=fe(),Jp=hn(),Qg=Zp(),Yr=de(),Fz="9223372036854775807";fr.MAX_TRANSFER_FEE=5e4;var Qp;(function(e){e[e.tfMPTCanLock=2]="tfMPTCanLock",e[e.tfMPTRequireAuth=4]="tfMPTRequireAuth",e[e.tfMPTCanEscrow=8]="tfMPTCanEscrow",e[e.tfMPTCanTrade=16]="tfMPTCanTrade",e[e.tfMPTCanTransfer=32]="tfMPTCanTransfer",e[e.tfMPTCanClawback=64]="tfMPTCanClawback",e[e.tfMPTCanHoldConfidentialBalance=128]="tfMPTCanHoldConfidentialBalance"})(Qp||(fr.MPTokenIssuanceCreateFlags=Qp={}));var oo;(function(e){e[e.tifMPTCanLock=2]="tifMPTCanLock",e[e.tifMPTRequireAuth=4]="tifMPTRequireAuth",e[e.tifMPTCanEscrow=8]="tifMPTCanEscrow",e[e.tifMPTCanTrade=16]="tifMPTCanTrade",e[e.tifMPTCanTransfer=32]="tifMPTCanTransfer",e[e.tifMPTCanClawback=64]="tifMPTCanClawback",e[e.tifMPTCanHoldConfidentialBalance=128]="tifMPTCanHoldConfidentialBalance",e[e.tifMPTMetadata=65536]="tifMPTMetadata",e[e.tifMPTTransferFee=131072]="tifMPTTransferFee"})(oo||(fr.MPTokenIssuanceCreateImmutableFlags=oo={}));fr.tifMPTokenIssuanceImmutableMask=~(oo.tifMPTCanLock|oo.tifMPTRequireAuth|oo.tifMPTCanEscrow|oo.tifMPTCanTrade|oo.tifMPTCanTransfer|oo.tifMPTCanClawback|oo.tifMPTCanHoldConfidentialBalance|oo.tifMPTMetadata|oo.tifMPTTransferFee);function Uz(e){var t,n,r;if((0,Yr.validateBaseTransaction)(e),(0,Yr.validateOptionalField)(e,"MaximumAmount",Yr.isString),(0,Yr.validateOptionalField)(e,"MPTokenMetadata",Yr.isString),(0,Yr.validateOptionalField)(e,"TransferFee",Yr.isNumber),(0,Yr.validateOptionalField)(e,"AssetScale",Yr.isNumber),(0,Yr.validateOptionalField)(e,"ImmutableFlags",Yr.isNumber),(0,Yr.validateOptionalField)(e,"DomainID",Yr.isDomainID),e.DomainID!=null&&!(0,Jp.hasFlag)(e,Qp.tfMPTRequireAuth,"tfMPTRequireAuth"))throw new As.ValidationError("MPTokenIssuanceCreate: Cannot set DomainID unless tfMPTRequireAuth flag is set.");if(typeof e.ImmutableFlags=="number"){let i=e.ImmutableFlags&fr.tifMPTokenIssuanceImmutableMask;if(e.ImmutableFlags===0||i!==0)throw new As.ValidationError("MPTokenIssuanceCreate: Invalid ImmutableFlags value")}if(typeof e.MPTokenMetadata=="string"&&(!(0,Jp.isHex)(e.MPTokenMetadata)||e.MPTokenMetadata.length/2>Qg.MAX_MPT_META_BYTE_LENGTH))throw new As.ValidationError(`MPTokenIssuanceCreate: MPTokenMetadata (hex format) must be non-empty and no more than ${Qg.MAX_MPT_META_BYTE_LENGTH} bytes.`);if(typeof e.MaximumAmount=="string")if(Jp.INTEGER_SANITY_CHECK.exec(e.MaximumAmount)){if(BigInt(e.MaximumAmount)>BigInt(Fz)||BigInt(e.MaximumAmount)<=BigInt("0"))throw new As.ValidationError("MPTokenIssuanceCreate: MaximumAmount out of range")}else throw new As.ValidationError("MPTokenIssuanceCreate: Invalid MaximumAmount");if(typeof e.TransferFee=="number"){let i=(t=e.Flags)!==null&&t!==void 0?t:0,o=typeof i=="number"?(0,Jp.isFlagEnabled)(i,Qp.tfMPTCanTransfer):(n=i.tfMPTCanTransfer)!==null&&n!==void 0?n:!1,a=typeof i=="number"?(0,Jp.isFlagEnabled)(i,Qp.tfMPTCanHoldConfidentialBalance):(r=i.tfMPTCanHoldConfidentialBalance)!==null&&r!==void 0?r:!1;if(e.TransferFee<0||e.TransferFee>fr.MAX_TRANSFER_FEE)throw new As.ValidationError(`MPTokenIssuanceCreate: TransferFee must be between 0 and ${fr.MAX_TRANSFER_FEE}`);if(e.TransferFee&&!o)throw new As.ValidationError("MPTokenIssuanceCreate: TransferFee cannot be provided without enabling tfMPTCanTransfer flag");if(e.TransferFee&&a)throw new As.ValidationError("MPTokenIssuanceCreate: TransferFee cannot be provided together with the tfMPTCanHoldConfidentialBalance flag")}if(e.MPTokenMetadata!=null){let i=(0,Qg.validateMPTokenMetadata)(e.MPTokenMetadata);if(i.length>0){let o=[Qg.MPT_META_WARNING_HEADER,...i.map(a=>`- ${a}`)].join(` `);console.warn(o)}}}fr.validateMPTokenIssuanceCreate=Uz});var n0=q(Pa=>{"use strict";y();Object.defineProperty(Pa,"__esModule",{value:!0});Pa.validateMPTokenIssuanceSet=Pa.tfMPTokenIssuanceSetEnableFlagMask=Pa.MPTokenIssuanceSetFlags=void 0;var bi=fe(),e0=hn(),$z=ju(),t0=Zp(),Tn=de(),G2=ey(),Ci;(function(e){e[e.tfMPTLock=1]="tfMPTLock",e[e.tfMPTUnlock=2]="tfMPTUnlock",e[e.tfMPTSetCanLock=4]="tfMPTSetCanLock",e[e.tfMPTSetRequireAuth=8]="tfMPTSetRequireAuth",e[e.tfMPTSetCanEscrow=16]="tfMPTSetCanEscrow",e[e.tfMPTSetCanTrade=32]="tfMPTSetCanTrade",e[e.tfMPTSetCanTransfer=64]="tfMPTSetCanTransfer",e[e.tfMPTSetCanClawback=128]="tfMPTSetCanClawback",e[e.tfMPTSetCanHoldConfidentialBalance=256]="tfMPTSetCanHoldConfidentialBalance"})(Ci||(Pa.MPTokenIssuanceSetFlags=Ci={}));Pa.tfMPTokenIssuanceSetEnableFlagMask=Ci.tfMPTSetCanLock|Ci.tfMPTSetRequireAuth|Ci.tfMPTSetCanEscrow|Ci.tfMPTSetCanTrade|Ci.tfMPTSetCanTransfer|Ci.tfMPTSetCanClawback|Ci.tfMPTSetCanHoldConfidentialBalance;function qz(e){if((0,Tn.validateBaseTransaction)(e),(0,Tn.validateRequiredField)(e,"MPTokenIssuanceID",Tn.isString),(0,Tn.validateOptionalField)(e,"Holder",Tn.isAccount),(0,Tn.validateOptionalField)(e,"IssuerEncryptionKey",(0,Tn.isHexWithByteLength)(Tn.CONFIDENTIAL_EC_POINT_BYTES)),(0,Tn.validateOptionalField)(e,"AuditorEncryptionKey",(0,Tn.isHexWithByteLength)(Tn.CONFIDENTIAL_EC_POINT_BYTES)),e.AuditorEncryptionKey!=null&&e.IssuerEncryptionKey==null)throw new bi.ValidationError("MPTokenIssuanceSet: AuditorEncryptionKey requires IssuerEncryptionKey");if((0,Tn.validateOptionalField)(e,"MPTokenMetadata",Tn.isString),(0,Tn.validateOptionalField)(e,"TransferFee",Tn.isNumber),(0,Tn.validateOptionalField)(e,"ImmutableFlags",Tn.isNumber),(0,Tn.validateOptionalField)(e,"DomainID",Tn.isDomainID),e.DomainID!=null&&e.Holder!=null)throw new bi.ValidationError("MPTokenIssuanceSet: Cannot set both DomainID and Holder fields.");if(typeof e.ImmutableFlags=="number"){let s=e.ImmutableFlags&G2.tifMPTokenIssuanceImmutableMask;if(e.ImmutableFlags===0||s!==0)throw new bi.ValidationError("MPTokenIssuanceSet: Invalid ImmutableFlags value")}let t=(0,$z.convertTxFlagsToNumber)(e),n=(0,e0.isFlagEnabled)(t,Ci.tfMPTLock),r=(0,e0.isFlagEnabled)(t,Ci.tfMPTUnlock),i=(t&Pa.tfMPTokenIssuanceSetEnableFlagMask)!==0;if(n&&r)throw new bi.ValidationError("MPTokenIssuanceSet: flag conflict");if(e.Holder!=null&&e.Holder===e.Account)throw new bi.ValidationError("MPTokenIssuanceSet: Holder cannot be the same as the Account.");let o=i||e.MPTokenMetadata!=null||e.TransferFee!=null||e.ImmutableFlags!=null,a=e.IssuerEncryptionKey!=null||e.AuditorEncryptionKey!=null;if(t===0&&e.DomainID==null&&!o&&!a)throw new bi.ValidationError("MPTokenIssuanceSet: Transaction does not change the state of the MPTokenIssuance ledger object.");if(o&&e.Holder!=null)throw new bi.ValidationError("MPTokenIssuanceSet: Holder field is not allowed when mutating MPTokenIssuance.");if(a&&e.Holder!=null)throw new bi.ValidationError("MPTokenIssuanceSet: Holder field is not allowed when registering confidential encryption keys.");if(o&&(n||r))throw new bi.ValidationError("MPTokenIssuanceSet: Can not lock/unlock while mutating MPTokenIssuance.");if(typeof e.TransferFee=="number"){if(e.TransferFee<0||e.TransferFee>G2.MAX_TRANSFER_FEE)throw new bi.ValidationError(`MPTokenIssuanceSet: TransferFee must be between 0 and ${G2.MAX_TRANSFER_FEE}`);if(e.TransferFee>0&&(0,e0.isFlagEnabled)(t,Ci.tfMPTSetCanHoldConfidentialBalance))throw new bi.ValidationError("MPTokenIssuanceSet: TransferFee cannot be provided together with the tfMPTSetCanHoldConfidentialBalance flag")}if(typeof e.MPTokenMetadata=="string"&&e.MPTokenMetadata.length>0){if(!(0,e0.isHex)(e.MPTokenMetadata)||e.MPTokenMetadata.length/2>t0.MAX_MPT_META_BYTE_LENGTH)throw new bi.ValidationError(`MPTokenIssuanceSet: MPTokenMetadata must be a valid hex string no more than ${t0.MAX_MPT_META_BYTE_LENGTH} bytes (an empty string clears the field).`);let s=(0,t0.validateMPTokenMetadata)(e.MPTokenMetadata);if(s.length>0){let c=[t0.MPT_META_WARNING_HEADER,...s.map(l=>`- ${l}`)].join(` `);console.warn(c)}}}Pa.validateMPTokenIssuanceSet=qz});var r0=q(Xu=>{"use strict";y();Object.defineProperty(Xu,"__esModule",{value:!0});Xu.validateNFTokenCreateOffer=Xu.NFTokenCreateOfferFlags=void 0;var zc=fe(),Hz=hn(),Zr=de(),Y2;(function(e){e[e.tfSellNFToken=1]="tfSellNFToken"})(Y2||(Xu.NFTokenCreateOfferFlags=Y2={}));function Vz(e){if(e.Owner!=null)throw new zc.ValidationError("NFTokenCreateOffer: Owner must not be present for sell offers")}function Kz(e){if(e.Owner==null)throw new zc.ValidationError("NFTokenCreateOffer: Owner must be present for buy offers");if((0,Zr.parseAmountValue)(e.Amount)<=0)throw new zc.ValidationError("NFTokenCreateOffer: Amount must be greater than 0 for buy offers")}function zz(e){var t,n;if((0,Zr.validateBaseTransaction)(e),(0,Zr.isString)(e.Account)&&(0,Zr.isString)(e.Owner)&&(0,Zr.areAddressesEqual)(e.Account,e.Owner))throw new zc.ValidationError("NFTokenCreateOffer: Owner and Account must not be equal");if((0,Zr.isString)(e.Account)&&(0,Zr.isString)(e.Destination)&&(0,Zr.areAddressesEqual)(e.Account,e.Destination))throw new zc.ValidationError("NFTokenCreateOffer: Destination and Account must not be equal");if((0,Zr.validateOptionalField)(e,"Destination",Zr.isAccount),(0,Zr.validateOptionalField)(e,"Owner",Zr.isAccount),e.NFTokenID==null)throw new zc.ValidationError("NFTokenCreateOffer: missing field NFTokenID");if(!(0,Zr.isAmount)(e.Amount))throw new zc.ValidationError("NFTokenCreateOffer: invalid Amount");let r=(t=e.Flags)!==null&&t!==void 0?t:0;(typeof r=="number"?(0,Hz.isFlagEnabled)(r,Y2.tfSellNFToken):(n=r.tfSellNFToken)!==null&&n!==void 0?n:!1)?Vz(e):Kz(e)}Xu.validateNFTokenCreateOffer=zz});var i0=q(Wu=>{"use strict";y();Object.defineProperty(Wu,"__esModule",{value:!0});Wu.validateNFTokenMint=Wu.NFTokenMintFlags=void 0;var ty=fe(),jz=hn(),xa=de(),n_;(function(e){e[e.tfBurnable=1]="tfBurnable",e[e.tfOnlyXRP=2]="tfOnlyXRP",e[e.tfTrustLine=4]="tfTrustLine",e[e.tfTransferable=8]="tfTransferable",e[e.tfMutable=16]="tfMutable"})(n_||(Wu.NFTokenMintFlags=n_={}));function Xz(e){if((0,xa.validateBaseTransaction)(e),e.Account===e.Issuer)throw new ty.ValidationError("NFTokenMint: Issuer must not be equal to Account");if((0,xa.validateOptionalField)(e,"Issuer",xa.isAccount),typeof e.URI=="string"&&e.URI==="")throw new ty.ValidationError("NFTokenMint: URI must not be empty string");if(typeof e.URI=="string"&&!(0,jz.isHex)(e.URI))throw new ty.ValidationError("NFTokenMint: URI must be in hex format");if(e.NFTokenTaxon==null)throw new ty.ValidationError("NFTokenMint: missing field NFTokenTaxon");if(e.Amount==null&&(e.Expiration!=null||e.Destination!=null))throw new ty.ValidationError("NFTokenMint: Amount is required when Expiration or Destination is present");(0,xa.validateOptionalField)(e,"Amount",xa.isAmount),(0,xa.validateOptionalField)(e,"Expiration",xa.isNumber),(0,xa.validateOptionalField)(e,"Destination",xa.isAccount)}Wu.validateNFTokenMint=Xz});var o0=q(Gu=>{"use strict";y();Object.defineProperty(Gu,"__esModule",{value:!0});Gu.validateOfferCreate=Gu.OfferCreateFlags=void 0;var jc=fe(),Wz=hn(),ny=de(),Z2;(function(e){e[e.tfPassive=65536]="tfPassive",e[e.tfImmediateOrCancel=131072]="tfImmediateOrCancel",e[e.tfFillOrKill=262144]="tfFillOrKill",e[e.tfSell=524288]="tfSell",e[e.tfHybrid=1048576]="tfHybrid"})(Z2||(Gu.OfferCreateFlags=Z2={}));function Gz(e){if((0,ny.validateBaseTransaction)(e),e.TakerGets===void 0)throw new jc.ValidationError("OfferCreate: missing field TakerGets");if(e.TakerPays===void 0)throw new jc.ValidationError("OfferCreate: missing field TakerPays");if(typeof e.TakerGets!="string"&&!(0,ny.isAmount)(e.TakerGets))throw new jc.ValidationError("OfferCreate: invalid TakerGets");if(typeof e.TakerPays!="string"&&!(0,ny.isAmount)(e.TakerPays))throw new jc.ValidationError("OfferCreate: invalid TakerPays");if(e.Expiration!==void 0&&typeof e.Expiration!="number")throw new jc.ValidationError("OfferCreate: invalid Expiration");if(e.OfferSequence!==void 0&&typeof e.OfferSequence!="number")throw new jc.ValidationError("OfferCreate: invalid OfferSequence");if((0,ny.validateOptionalField)(e,"DomainID",ny.isDomainID,{txType:"OfferCreate",paramName:"DomainID"}),e.DomainID==null&&(0,Wz.hasFlag)(e,Z2.tfHybrid,"tfHybrid"))throw new jc.ValidationError("OfferCreate: tfHybrid flag cannot be set if DomainID is not present")}Gu.validateOfferCreate=Gz});var a0=q(Yu=>{"use strict";y();Object.defineProperty(Yu,"__esModule",{value:!0});Yu.validatePayment=Yu.PaymentFlags=void 0;var ao=fe(),ry=hn(),xr=de(),Xc;(function(e){e[e.tfNoRippleDirect=65536]="tfNoRippleDirect",e[e.tfPartialPayment=131072]="tfPartialPayment",e[e.tfLimitQuality=262144]="tfLimitQuality",e[e.tfSponsorCreatedAccount=524288]="tfSponsorCreatedAccount"})(Xc||(Yu.PaymentFlags=Xc={}));function Yz(e){if((0,xr.validateBaseTransaction)(e),e.Amount===void 0)throw new ao.ValidationError("PaymentTransaction: missing field Amount");if(!(0,xr.isAmount)(e.Amount))throw new ao.ValidationError("PaymentTransaction: invalid Amount");if((0,xr.validateRequiredField)(e,"Destination",xr.isAccount),(0,xr.validateOptionalField)(e,"DestinationTag",xr.isNumber),(0,xr.validateCredentialsList)(e.CredentialIDs,e.TransactionType,!0,xr.MAX_AUTHORIZED_CREDENTIALS),e.InvoiceID!==void 0&&typeof e.InvoiceID!="string")throw new ao.ValidationError("PaymentTransaction: InvoiceID must be a string");if((0,xr.validateOptionalField)(e,"DomainID",xr.isDomainID,{txType:"PaymentTransaction",paramName:"DomainID"}),e.Paths!==void 0&&!tj(e.Paths))throw new ao.ValidationError("PaymentTransaction: invalid Paths");if(e.SendMax!==void 0&&!(0,xr.isAmount)(e.SendMax))throw new ao.ValidationError("PaymentTransaction: invalid SendMax");Jz(e),Zz(e)}Yu.validatePayment=Yz;function Zz(e){var t,n,r,i,o;let a=(t=e.Flags)!==null&&t!==void 0?t:0;if(!(typeof a=="number"?(0,ry.isFlagEnabled)(a,Xc.tfSponsorCreatedAccount):(n=a.tfSponsorCreatedAccount)!==null&&n!==void 0?n:!1))return;let c=typeof a=="number"?(0,ry.isFlagEnabled)(a,Xc.tfNoRippleDirect):(r=a.tfNoRippleDirect)!==null&&r!==void 0?r:!1,l=typeof a=="number"?(0,ry.isFlagEnabled)(a,Xc.tfPartialPayment):(i=a.tfPartialPayment)!==null&&i!==void 0?i:!1,u=typeof a=="number"?(0,ry.isFlagEnabled)(a,Xc.tfLimitQuality):(o=a.tfLimitQuality)!==null&&o!==void 0?o:!1;if(c||l||u)throw new ao.ValidationError("PaymentTransaction: tfSponsorCreatedAccount cannot be combined with tfNoRippleDirect, tfPartialPayment, or tfLimitQuality");if(e.SendMax!==void 0||e.Paths!==void 0)throw new ao.ValidationError("PaymentTransaction: tfSponsorCreatedAccount cannot be combined with SendMax or Paths");if(typeof e.Amount!="string")throw new ao.ValidationError("PaymentTransaction: tfSponsorCreatedAccount requires a native XRP Amount")}function Jz(e){var t;if(e.DeliverMin!=null){if(e.Flags==null)throw new ao.ValidationError("PaymentTransaction: tfPartialPayment flag required with DeliverMin");let n=e.Flags;if(!(typeof n=="number"?(0,ry.isFlagEnabled)(n,Xc.tfPartialPayment):(t=n.tfPartialPayment)!==null&&t!==void 0?t:!1))throw new ao.ValidationError("PaymentTransaction: tfPartialPayment flag required with DeliverMin");if(!(0,xr.isAmount)(e.DeliverMin))throw new ao.ValidationError("PaymentTransaction: invalid DeliverMin")}}function Qz(e){return e.account!==void 0&&typeof e.account!="string"||e.currency!==void 0&&typeof e.currency!="string"||e.issuer!==void 0&&typeof e.issuer!="string"?!1:e.account!==void 0&&e.currency===void 0&&e.issuer===void 0||e.currency!==void 0||e.issuer!==void 0}function ej(e){if(!Array.isArray(e)||e.length===0)return!1;for(let t of e)if(!Qz(t))return!1;return!0}function tj(e){if(!(0,xr.isArray)(e)||e.length===0)return!1;for(let t of e)if(!(0,xr.isArray)(t)||t.length===0||!ej(t))return!1;return!0}});var s0=q(Ju=>{"use strict";y();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.validatePaymentChannelClaim=Ju.PaymentChannelClaimFlags=void 0;var Zu=fe(),J2=de(),r_;(function(e){e[e.tfRenew=65536]="tfRenew",e[e.tfClose=131072]="tfClose"})(r_||(Ju.PaymentChannelClaimFlags=r_={}));function nj(e){if((0,J2.validateBaseTransaction)(e),(0,J2.validateCredentialsList)(e.CredentialIDs,e.TransactionType,!0,J2.MAX_AUTHORIZED_CREDENTIALS),e.Channel===void 0)throw new Zu.ValidationError("PaymentChannelClaim: missing Channel");if(typeof e.Channel!="string")throw new Zu.ValidationError("PaymentChannelClaim: Channel must be a string");if(e.Balance!==void 0&&typeof e.Balance!="string")throw new Zu.ValidationError("PaymentChannelClaim: Balance must be a string");if(e.Amount!==void 0&&typeof e.Amount!="string")throw new Zu.ValidationError("PaymentChannelClaim: Amount must be a string");if(e.Signature!==void 0&&typeof e.Signature!="string")throw new Zu.ValidationError("PaymentChannelClaim: Signature must be a string");if(e.PublicKey!==void 0&&typeof e.PublicKey!="string")throw new Zu.ValidationError("PaymentChannelClaim: PublicKey must be a string")}Ju.validatePaymentChannelClaim=nj});var c0=q(Qu=>{"use strict";y();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.validateSponsorshipSet=Qu.SponsorshipSetFlags=void 0;var Qt=fe(),rj=hn(),vi=de(),ij=/^-?(?:0|[1-9][0-9]*)$/u,Ai;(function(e){e[e.tfSponsorshipSetRequireSignForFee=65536]="tfSponsorshipSetRequireSignForFee",e[e.tfSponsorshipClearRequireSignForFee=131072]="tfSponsorshipClearRequireSignForFee",e[e.tfSponsorshipSetRequireSignForReserve=262144]="tfSponsorshipSetRequireSignForReserve",e[e.tfSponsorshipClearRequireSignForReserve=524288]="tfSponsorshipClearRequireSignForReserve",e[e.tfDeleteObject=1048576]="tfDeleteObject"})(Ai||(Qu.SponsorshipSetFlags=Ai={}));var oj=Ai.tfSponsorshipSetRequireSignForFee|Ai.tfSponsorshipClearRequireSignForFee|Ai.tfSponsorshipSetRequireSignForReserve|Ai.tfSponsorshipClearRequireSignForReserve;function aj(e){let t=0,n=!1,r=!1,i=!1;if(typeof e.Flags=="number")t=e.Flags,n=(e.Flags&oj)!==0,r=(e.Flags&Ai.tfSponsorshipSetRequireSignForFee)!==0&&(e.Flags&Ai.tfSponsorshipClearRequireSignForFee)!==0,i=(e.Flags&Ai.tfSponsorshipSetRequireSignForReserve)!==0&&(e.Flags&Ai.tfSponsorshipClearRequireSignForReserve)!==0;else if((0,vi.isRecord)(e.Flags)){let a=e.Flags;a.tfDeleteObject&&(t=Ai.tfDeleteObject),n=!!(a.tfSponsorshipSetRequireSignForFee||a.tfSponsorshipClearRequireSignForFee||a.tfSponsorshipSetRequireSignForReserve||a.tfSponsorshipClearRequireSignForReserve),r=!!(a.tfSponsorshipSetRequireSignForFee&&a.tfSponsorshipClearRequireSignForFee),i=!!(a.tfSponsorshipSetRequireSignForReserve&&a.tfSponsorshipClearRequireSignForReserve)}return{isDelete:(t&Ai.tfDeleteObject)!==0,hasModifyFlag:n,hasFeeSignConflict:r,hasReserveSignConflict:i}}function sj(e){(0,vi.validateBaseTransaction)(e);let t=e.Sponsee!==void 0,n=e.CounterpartySponsor!==void 0;if(!t&&!n)throw new Qt.ValidationError("SponsorshipSet: must have either Sponsee or CounterpartySponsor");if(t&&n)throw new Qt.ValidationError("SponsorshipSet: cannot have both Sponsee and CounterpartySponsor");if(t){if(!(0,vi.isString)(e.Sponsee))throw new Qt.ValidationError("SponsorshipSet: Sponsee must be a string");if((0,vi.isString)(e.Account)&&(0,vi.areAddressesEqual)(e.Account,e.Sponsee))throw new Qt.ValidationError("SponsorshipSet: Account and Sponsee cannot be the same");if(!(0,vi.isAccount)(e.Sponsee))throw new Qt.ValidationError("SponsorshipSet: Sponsee must be a valid account address")}if(n){if(!(0,vi.isString)(e.CounterpartySponsor))throw new Qt.ValidationError("SponsorshipSet: CounterpartySponsor must be a string");if((0,vi.isString)(e.Account)&&(0,vi.areAddressesEqual)(e.Account,e.CounterpartySponsor))throw new Qt.ValidationError("SponsorshipSet: Account and CounterpartySponsor cannot be the same");if(!(0,vi.isAccount)(e.CounterpartySponsor))throw new Qt.ValidationError("SponsorshipSet: CounterpartySponsor must be a valid account address")}let{isDelete:r,hasModifyFlag:i,hasFeeSignConflict:o,hasReserveSignConflict:a}=aj(e);if(o)throw new Qt.ValidationError("SponsorshipSet: cannot set both tfSponsorshipSetRequireSignForFee and tfSponsorshipClearRequireSignForFee");if(a)throw new Qt.ValidationError("SponsorshipSet: cannot set both tfSponsorshipSetRequireSignForReserve and tfSponsorshipClearRequireSignForReserve");if(n&&!r)throw new Qt.ValidationError("SponsorshipSet: CounterpartySponsor can only be used with tfDeleteObject (only the sponsor can create or modify a Sponsorship)");if(r){if(i)throw new Qt.ValidationError("SponsorshipSet: cannot set RequireSignForFee/RequireSignForReserve flags together with tfDeleteObject");if(e.FeeAmountDelta!==void 0||e.RemainingOwnerCountDelta!==void 0||e.MaxFee!==void 0)throw new Qt.ValidationError("SponsorshipSet: cannot include FeeAmountDelta, RemainingOwnerCountDelta, or MaxFee together with tfDeleteObject")}if(e.FeeAmountDelta!==void 0){if(!(0,vi.isString)(e.FeeAmountDelta))throw new Qt.ValidationError("SponsorshipSet: FeeAmountDelta must be a string");if(!ij.exec(e.FeeAmountDelta))throw new Qt.ValidationError("SponsorshipSet: FeeAmountDelta must be a numeric string");if(BigInt(e.FeeAmountDelta)===BigInt(0))throw new Qt.ValidationError("SponsorshipSet: FeeAmountDelta must not be zero")}if(e.MaxFee!==void 0){if(!(0,vi.isString)(e.MaxFee))throw new Qt.ValidationError("SponsorshipSet: MaxFee must be a string");if(!rj.INTEGER_SANITY_CHECK.exec(e.MaxFee))throw new Qt.ValidationError("SponsorshipSet: MaxFee must be a non-negative numeric string")}if(e.RemainingOwnerCountDelta!==void 0){if(typeof e.RemainingOwnerCountDelta!="number")throw new Qt.ValidationError("SponsorshipSet: RemainingOwnerCountDelta must be a number");if(!Number.isInteger(e.RemainingOwnerCountDelta))throw new Qt.ValidationError("SponsorshipSet: RemainingOwnerCountDelta must be an integer");if(e.RemainingOwnerCountDelta===0)throw new Qt.ValidationError("SponsorshipSet: RemainingOwnerCountDelta must be non-zero when present");let s=-2147483648,c=2147483647;if(e.RemainingOwnerCountDelta>c||e.RemainingOwnerCountDelta{"use strict";y();Object.defineProperty(ed,"__esModule",{value:!0});ed.validateSponsorshipTransfer=ed.SponsorshipTransferFlags=void 0;var pr=fe(),Si=de(),iy;(function(e){e[e.tfSponsorshipEnd=65536]="tfSponsorshipEnd",e[e.tfSponsorshipCreate=131072]="tfSponsorshipCreate",e[e.tfSponsorshipReassign=262144]="tfSponsorshipReassign"})(iy||(ed.SponsorshipTransferFlags=iy={}));function cj(e){(0,Si.validateBaseTransaction)(e);let t=!1,n=!1,r=!1;if(typeof e.Flags=="number")t=(e.Flags&iy.tfSponsorshipEnd)!==0,n=(e.Flags&iy.tfSponsorshipCreate)!==0,r=(e.Flags&iy.tfSponsorshipReassign)!==0;else if((0,Si.isRecord)(e.Flags)){let c=e.Flags;t=c.tfSponsorshipEnd===!0,n=c.tfSponsorshipCreate===!0,r=c.tfSponsorshipReassign===!0}let i=(t?1:0)+(n?1:0)+(r?1:0);if(i===0)throw new pr.ValidationError("SponsorshipTransfer: must specify exactly one scenario flag (tfSponsorshipEnd, tfSponsorshipCreate, or tfSponsorshipReassign)");if(i>1)throw new pr.ValidationError("SponsorshipTransfer: cannot specify multiple scenario flags (tfSponsorshipEnd, tfSponsorshipCreate, tfSponsorshipReassign are mutually exclusive)");if(e.ObjectID!==void 0){if(!(0,Si.isString)(e.ObjectID))throw new pr.ValidationError("SponsorshipTransfer: ObjectID must be a string");if(!/^[0-9A-Fa-f]{64}$/u.test(e.ObjectID))throw new pr.ValidationError("SponsorshipTransfer: ObjectID must be a 64-character hexadecimal string")}let o=e.Sponsor!==void 0;if(t&&o)throw new pr.ValidationError("SponsorshipTransfer: Sponsor field must not be present for tfSponsorshipEnd scenario");if((n||r)&&!o)throw new pr.ValidationError("SponsorshipTransfer: Sponsor field is required for tfSponsorshipCreate and tfSponsorshipReassign scenarios");if(e.Sponsor!==void 0){if(!(0,Si.isString)(e.Sponsor))throw new pr.ValidationError("SponsorshipTransfer: Sponsor must be a string");if((0,Si.isString)(e.Account)&&(0,Si.areAddressesEqual)(e.Account,e.Sponsor))throw new pr.ValidationError("SponsorshipTransfer: Account and Sponsor cannot be the same");if(!(0,Si.isAccount)(e.Sponsor))throw new pr.ValidationError("SponsorshipTransfer: Sponsor must be a valid account address")}if((n||r)&&!(typeof e.SponsorFlags=="number"&&(e.SponsorFlags&Si.SponsorFlags.spfSponsorReserve)!==0))throw new pr.ValidationError("SponsorshipTransfer: SponsorFlags must be present with the spfSponsorReserve bit set for tfSponsorshipCreate and tfSponsorshipReassign scenarios");if((n||r)&&e.ObjectID===void 0&&e.SponsorSignature===void 0)throw new pr.ValidationError("SponsorshipTransfer: SponsorSignature is required for account-level tfSponsorshipCreate or tfSponsorshipReassign (no ObjectID)");let s=e.Sponsee!==void 0;if((n||r)&&s)throw new pr.ValidationError("SponsorshipTransfer: Sponsee field must not be present for tfSponsorshipCreate or tfSponsorshipReassign scenarios");if(e.Sponsee!==void 0){if(!(0,Si.isString)(e.Sponsee))throw new pr.ValidationError("SponsorshipTransfer: Sponsee must be a string");if((0,Si.isString)(e.Account)&&(0,Si.areAddressesEqual)(e.Account,e.Sponsee))throw new pr.ValidationError("SponsorshipTransfer: Account and Sponsee cannot be the same");if(!(0,Si.isAccount)(e.Sponsee))throw new pr.ValidationError("SponsorshipTransfer: Sponsee must be a valid account address")}}ed.validateSponsorshipTransfer=cj});var d0=q(td=>{"use strict";y();Object.defineProperty(td,"__esModule",{value:!0});td.validateTrustSet=td.TrustSetFlags=void 0;var u0=fe(),i_=de(),o_;(function(e){e[e.tfSetfAuth=65536]="tfSetfAuth",e[e.tfSetNoRipple=131072]="tfSetNoRipple",e[e.tfClearNoRipple=262144]="tfClearNoRipple",e[e.tfSetFreeze=1048576]="tfSetFreeze",e[e.tfClearFreeze=2097152]="tfClearFreeze",e[e.tfSetDeepFreeze=4194304]="tfSetDeepFreeze",e[e.tfClearDeepFreeze=8388608]="tfClearDeepFreeze"})(o_||(td.TrustSetFlags=o_={}));function lj(e){(0,i_.validateBaseTransaction)(e);let{LimitAmount:t,QualityIn:n,QualityOut:r}=e;if(t===void 0)throw new u0.ValidationError("TrustSet: missing field LimitAmount");if(!(0,i_.isAmount)(t))throw new u0.ValidationError("TrustSet: invalid LimitAmount");if(n!==void 0&&typeof n!="number")throw new u0.ValidationError("TrustSet: QualityIn must be a number");if(r!==void 0&&typeof r!="number")throw new u0.ValidationError("TrustSet: QualityOut must be a number")}td.validateTrustSet=lj});var p0=q(No=>{"use strict";y();Object.defineProperty(No,"__esModule",{value:!0});No.validateVaultCreate=No.VaultCreateFlags=No.VaultKind=No.VaultWithdrawalPolicy=void 0;var Jr=fe(),Q2=hn(),f0=Zp(),en=de(),a_=18,s_=180,c_=946708560,l_;(function(e){e[e.vaultStrategyFirstComeFirstServe=1]="vaultStrategyFirstComeFirstServe"})(l_||(No.VaultWithdrawalPolicy=l_={}));var Wc;(function(e){e[e.vaultKindOpen=0]="vaultKindOpen",e[e.vaultKindClosed=1]="vaultKindClosed"})(Wc||(No.VaultKind=Wc={}));var eA;(function(e){e[e.tfVaultPrivate=65536]="tfVaultPrivate",e[e.tfVaultShareNonTransferable=131072]="tfVaultShareNonTransferable"})(eA||(No.VaultCreateFlags=eA={}));function uj(e){if((0,en.validateBaseTransaction)(e),(0,en.validateRequiredField)(e,"Asset",en.isCurrency),(0,en.validateOptionalField)(e,"Data",en.isString),(0,en.validateOptionalField)(e,"AssetsMaximum",en.isXRPLNumber),(0,en.validateOptionalField)(e,"MPTokenMetadata",en.isString),(0,en.validateOptionalField)(e,"WithdrawalPolicy",en.isNumber),(0,en.validateOptionalField)(e,"DomainID",en.isString),(0,en.validateOptionalField)(e,"Scale",en.isNumber),(0,en.validateOptionalField)(e,"VaultKind",en.isNumber),(0,en.validateOptionalField)(e,"SubscriptionDate",en.isNumber),(0,en.validateOptionalField)(e,"RedemptionDate",en.isNumber),e.VaultKind!==void 0&&e.VaultKind!==Wc.vaultKindOpen&&e.VaultKind!==Wc.vaultKindClosed)throw new Jr.ValidationError(`VaultCreate: VaultKind must be ${Wc.vaultKindOpen} (open-ended) or ${Wc.vaultKindClosed} (close-ended)`);if(e.SubscriptionDate!==void 0&&!Number.isInteger(e.SubscriptionDate))throw new Jr.ValidationError("VaultCreate: SubscriptionDate must be an integer number of seconds since the Ripple Epoch");if(e.RedemptionDate!==void 0&&!Number.isInteger(e.RedemptionDate))throw new Jr.ValidationError("VaultCreate: RedemptionDate must be an integer number of seconds since the Ripple Epoch");if(e.Data!==void 0){let c=e.Data;if(!(0,Q2.isHex)(c)||c.length%2!==0)throw new Jr.ValidationError("VaultCreate: Data must be a hex string with an even number of characters");let l=c.length/2;if(l>en.VAULT_DATA_MAX_BYTE_LENGTH)throw new Jr.ValidationError(`VaultCreate: Data exceeds ${en.VAULT_DATA_MAX_BYTE_LENGTH} bytes (actual: ${l})`)}if(e.MPTokenMetadata!==void 0){let c=e.MPTokenMetadata;if(!(0,Q2.isHex)(c))throw new Jr.ValidationError("VaultCreate: MPTokenMetadata must be a valid non-empty hex string");let l=c.length/2;if(l>f0.MAX_MPT_META_BYTE_LENGTH)throw new Jr.ValidationError(`VaultCreate: MPTokenMetadata exceeds ${f0.MAX_MPT_META_BYTE_LENGTH} bytes (actual: ${l})`)}if(e.DomainID!==void 0&&!(0,Q2.hasFlag)(e,eA.tfVaultPrivate,"tfVaultPrivate"))throw new Jr.ValidationError("VaultCreate: Cannot set DomainID unless tfVaultPrivate flag is set.");let t=e.Asset,n=t.currency==="XRP",r="mpt_issuance_id"in t,i=!n&&!r;if(e.Scale!==void 0){if(n||r)throw new Jr.ValidationError("VaultCreate: Scale parameter must not be provided for XRP or MPT assets");if(i&&(!Number.isInteger(e.Scale)||e.Scale<0||e.Scale>a_))throw new Jr.ValidationError(`VaultCreate: Scale must be a number between 0 and ${a_} inclusive for IOU assets`)}let o=e.VaultKind===Wc.vaultKindClosed,a=e.SubscriptionDate!==void 0,s=e.RedemptionDate!==void 0;if(o){if(typeof e.SubscriptionDate!="number"||typeof e.RedemptionDate!="number")throw new Jr.ValidationError("VaultCreate: A close-ended vault requires both SubscriptionDate and RedemptionDate");let c=e.RedemptionDate-e.SubscriptionDate;if(c=c_)throw new Jr.ValidationError(`VaultCreate: RedemptionDate - SubscriptionDate must be within [${s_}, ${c_}) seconds`)}else if(a||s)throw new Jr.ValidationError("VaultCreate: SubscriptionDate and RedemptionDate can only be set on a close-ended vault (VaultKind=1)");if(e.MPTokenMetadata!=null){let c=(0,f0.validateMPTokenMetadata)(e.MPTokenMetadata);if(c.length>0){let l=[f0.MPT_META_WARNING_HEADER,...c.map(u=>`- ${u}`)].join(` `);console.warn(l)}}}No.validateVaultCreate=uj});var y0=q(nd=>{"use strict";y();Object.defineProperty(nd,"__esModule",{value:!0});nd.validateXChainModifyBridge=nd.XChainModifyBridgeFlags=void 0;var Gc=de(),u_;(function(e){e[e.tfClearAccountCreateAmount=65536]="tfClearAccountCreateAmount"})(u_||(nd.XChainModifyBridgeFlags=u_={}));function dj(e){(0,Gc.validateBaseTransaction)(e),(0,Gc.validateRequiredField)(e,"XChainBridge",Gc.isXChainBridge),(0,Gc.validateOptionalField)(e,"SignatureReward",Gc.isAmount),(0,Gc.validateOptionalField)(e,"MinAccountCreateAmount",Gc.isAmount)}nd.validateXChainModifyBridge=dj});var ju=q(Mr=>{"use strict";y();Object.defineProperty(Mr,"__esModule",{value:!0});Mr.parseTransactionFlags=Mr.convertTxFlagsToNumber=Mr.setTransactionFlagsToNumber=Mr.parseMPTokenIssuanceImmutableFlags=Mr.parseMPTokenIssuanceFlags=Mr.parseAccountRootFlags=void 0;var d_=fe(),f_=hv(),h0=mv(),fj=Hg(),pj=Kg(),yj=zg(),hj=jg(),mj=Xp(),Yc=de(),gj=Gg(),wj=Yg(),bj=Zg(),Cj=ey(),vj=n0(),Aj=r0(),Sj=i0(),Tj=o0(),Ej=a0(),kj=s0(),_j=c0(),Ij=l0(),Pj=d0(),xj=p0(),Mj=y0(),oy=hn();function Oj(e){let t={};return Object.values(f_.AccountRootFlags).forEach(n=>{typeof n=="string"&&(0,oy.isFlagEnabled)(e,f_.AccountRootFlags[n])&&(t[n]=!0)}),t}Mr.parseAccountRootFlags=Oj;function Dj(e){let t={};return Object.values(h0.MPTokenIssuanceFlags).forEach(n=>{typeof n=="string"&&(0,oy.isFlagEnabled)(e,h0.MPTokenIssuanceFlags[n])&&(t[n]=!0)}),t}Mr.parseMPTokenIssuanceFlags=Dj;function Rj(e){let t={};return e==null||Object.values(h0.MPTokenIssuanceImmutableFlags).forEach(n=>{typeof n=="string"&&(0,oy.isFlagEnabled)(e,h0.MPTokenIssuanceImmutableFlags[n])&&(t[n]=!0)}),t}Mr.parseMPTokenIssuanceImmutableFlags=Rj;var tA={AccountSet:fj.AccountSetTfFlags,AMMClawback:pj.AMMClawbackFlags,AMMDeposit:yj.AMMDepositFlags,AMMWithdraw:hj.AMMWithdrawFlags,Batch:mj.BatchFlags,LoanManage:gj.LoanManageFlags,LoanPay:wj.LoanPayFlags,MPTokenAuthorize:bj.MPTokenAuthorizeFlags,MPTokenIssuanceCreate:Cj.MPTokenIssuanceCreateFlags,MPTokenIssuanceSet:vj.MPTokenIssuanceSetFlags,NFTokenCreateOffer:Aj.NFTokenCreateOfferFlags,NFTokenMint:Sj.NFTokenMintFlags,OfferCreate:Tj.OfferCreateFlags,PaymentChannelClaim:kj.PaymentChannelClaimFlags,Payment:Ej.PaymentFlags,SponsorshipSet:_j.SponsorshipSetFlags,SponsorshipTransfer:Ij.SponsorshipTransferFlags,TrustSet:Pj.TrustSetFlags,VaultCreate:xj.VaultCreateFlags,XChainModifyBridge:Mj.XChainModifyBridgeFlags};function p_(e){return e in tA}function Nj(e){console.warn("This function is deprecated. Use convertTxFlagsToNumber() instead and use the returned value to modify the Transaction.Flags from the caller."),e.Flags&&(e.Flags=nA(e))}Mr.setTransactionFlagsToNumber=Nj;function nA(e){let t=e.Flags;if(t==null)return 0;if(typeof t=="number")return t;if(p_(e.TransactionType)){let n=tA[e.TransactionType];return Object.keys(t).reduce((r,i)=>{var o;if(n[i]==null&&Yc.GlobalFlags[i]==null)throw new d_.ValidationError(`Invalid flag ${i}.`);return t[i]?r|((o=n[i])!==null&&o!==void 0?o:Yc.GlobalFlags[i]):r},0)}return Object.keys(t).reduce((n,r)=>{if(Yc.GlobalFlags[r]==null)throw new d_.ValidationError(`Invalid flag ${r}. Valid flags are ${JSON.stringify(Yc.GlobalFlags)}`);return t[r]?n|Yc.GlobalFlags[r]:n},0)}Mr.convertTxFlagsToNumber=nA;function Lj(e){let t=nA(e);if(t===0)return{};let n={};if(p_(e.TransactionType)){let r=tA[e.TransactionType];Object.values(r).forEach(i=>{typeof i=="string"&&(0,oy.isFlagEnabled)(t,r[i])&&(n[i]=!0)})}return Object.values(Yc.GlobalFlags).forEach(r=>{typeof r=="string"&&(0,oy.isFlagEnabled)(t,Yc.GlobalFlags[r])&&(n[r]=!0)}),n}Mr.parseTransactionFlags=Lj});var y_=q(rd=>{"use strict";y();var Bj=rd&&rd.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rd,"__esModule",{value:!0});rd.ripemd160=void 0;var Fj=At("crypto"),Uj=Bj(Km());rd.ripemd160=(0,Uj.default)("ripemd160",Fj.createHash)});function $j(e,t=!1){return t?{h:Number(e&m0),l:Number(e>>h_&m0)}:{h:Number(e>>h_&m0)|0,l:Number(e&m0)|0}}function m_(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var m0,h_,qj,Hj,rA,iA,Zc,Jc,ay,sy,w_,b_,C_,v_,A_,S_,oA=Te(()=>{y();m0=BigInt(4294967295),h_=BigInt(32);qj=e=>e/2**32|0,Hj=e=>e>>>0;rA=(e,t,n)=>e>>>n,iA=(e,t,n)=>e<<32-n|t>>>n,Zc=(e,t,n)=>e>>>n|t<<32-n,Jc=(e,t,n)=>e<<32-n|t>>>n,ay=(e,t,n)=>e<<64-n|t>>>n-32,sy=(e,t,n)=>e>>>n-32|t<<64-n;w_=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),b_=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,C_=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),v_=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,A_=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),S_=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0});function aA(e,t,n){return e&t^~e&n}function sA(e,t,n){return e&t^e&n^t&n}var Qc,T_,E_,cA=Te(()=>{y();oA();Hn();Qc=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,i){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Qi(this.buffer)}update(t){Ec(this),St(t);let{view:n,buffer:r,blockLen:i}=this,o=t.length,a=!1;for(let s=0;si-a&&(this.process(r,0),n.fill(0)),g_(r,i-8,this.length*8,o),this.process(r,0),this.roundClean();let s=t===n?r:Qi(t),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d{y();cA();oA();Hn();Kj=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ss=new Uint32Array(64),lA=class extends Qc{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:i,E:o,F:a,G:s,H:c}=this;return[t,n,r,i,o,a,s,c]}set(t,n,r,i,o,a,s,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=a|0,this.G=s|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let d=0;d<16;d++,n+=4)Ss[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){let p=Ss[d-15],h=Ss[d-2],g=fi(p,7)^fi(p,18)^p>>>3,w=fi(h,17)^fi(h,19)^h>>>10;Ss[d]=w+Ss[d-7]+g+Ss[d-16]|0}let{A:r,B:i,C:o,D:a,E:s,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=fi(s,6)^fi(s,11)^fi(s,25),h=u+p+aA(s,c,l)+Kj[d]+Ss[d]|0,w=(fi(r,2)^fi(r,13)^fi(r,22))+sA(r,i,o)|0;u=l,l=c,c=s,s=a+h|0,a=o,o=i,i=r,r=h+w|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,a=a+this.D|0,s=s+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,o,a,s,c,l,u)}roundClean(){yn(Ss)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),yn(this.buffer)}},uA=class extends lA{constructor(){super(32,T_)}},k_=m_(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),zj=k_[0],jj=k_[1],Ts=new Uint32Array(80),Es=new Uint32Array(80),dA=class extends Qc{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(t,n){super(128,t,16,!1),this.Ah=n[0]|0,this.Al=n[1]|0,this.Bh=n[2]|0,this.Bl=n[3]|0,this.Ch=n[4]|0,this.Cl=n[5]|0,this.Dh=n[6]|0,this.Dl=n[7]|0,this.Eh=n[8]|0,this.El=n[9]|0,this.Fh=n[10]|0,this.Fl=n[11]|0,this.Gh=n[12]|0,this.Gl=n[13]|0,this.Hh=n[14]|0,this.Hl=n[15]|0}get(){let{Ah:t,Al:n,Bh:r,Bl:i,Ch:o,Cl:a,Dh:s,Dl:c,Eh:l,El:u,Fh:d,Fl:p,Gh:h,Gl:g,Hh:w,Hl:T}=this;return[t,n,r,i,o,a,s,c,l,u,d,p,h,g,w,T]}set(t,n,r,i,o,a,s,c,l,u,d,p,h,g,w,T){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=o|0,this.Cl=a|0,this.Dh=s|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=h|0,this.Gl=g|0,this.Hh=w|0,this.Hl=T|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let D=0;D<16;D++,n+=4)Ts[D]=t.getUint32(n),Es[D]=t.getUint32(n+=4);for(let D=16;D<80;D++){let P=Ts[D-15]|0,U=Es[D-15]|0,F=Zc(P,U,1)^Zc(P,U,8)^rA(P,U,7),H=Jc(P,U,1)^Jc(P,U,8)^iA(P,U,7),b=Ts[D-2]|0,C=Es[D-2]|0,v=Zc(b,C,19)^ay(b,C,61)^rA(b,C,6),S=Jc(b,C,19)^sy(b,C,61)^iA(b,C,6),A=C_(H,S,Es[D-7],Es[D-16]),M=v_(A,F,v,Ts[D-7],Ts[D-16]);Ts[D]=M|0,Es[D]=A|0}let{Ah:r,Al:i,Bh:o,Bl:a,Ch:s,Cl:c,Dh:l,Dl:u,Eh:d,El:p,Fh:h,Fl:g,Gh:w,Gl:T,Hh:k,Hl:B}=this;for(let D=0;D<80;D++){let P=Zc(d,p,14)^Zc(d,p,18)^ay(d,p,41),U=Jc(d,p,14)^Jc(d,p,18)^sy(d,p,41),F=d&h^~d&w,H=p&g^~p&T,b=A_(B,U,H,jj[D],Es[D]),C=S_(b,k,P,F,zj[D],Ts[D]),v=b|0,S=Zc(r,i,28)^ay(r,i,34)^ay(r,i,39),A=Jc(r,i,28)^sy(r,i,34)^sy(r,i,39),M=r&o^r&s^o&s,$=i&a^i&c^a&c;k=w|0,B=T|0,w=h|0,T=g|0,h=d|0,g=p|0,{h:d,l:p}=Lo(l|0,u|0,C|0,v|0),l=s|0,u=c|0,s=o|0,c=a|0,o=r|0,a=i|0;let R=w_(v,A,$);r=b_(R,C,S,M),i=R|0}({h:r,l:i}=Lo(this.Ah|0,this.Al|0,r|0,i|0)),{h:o,l:a}=Lo(this.Bh|0,this.Bl|0,o|0,a|0),{h:s,l:c}=Lo(this.Ch|0,this.Cl|0,s|0,c|0),{h:l,l:u}=Lo(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Lo(this.Eh|0,this.El|0,d|0,p|0),{h,l:g}=Lo(this.Fh|0,this.Fl|0,h|0,g|0),{h:w,l:T}=Lo(this.Gh|0,this.Gl|0,w|0,T|0),{h:k,l:B}=Lo(this.Hh|0,this.Hl|0,k|0,B|0),this.set(r,i,o,a,s,c,l,u,d,p,h,g,w,T,k,B)}roundClean(){yn(Ts,Es)}destroy(){this.destroyed=!0,yn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},fA=class extends dA{constructor(){super(64,E_)}},_t=gu(()=>new uA,Um(1)),tr=gu(()=>new fA,Um(3))});var hA={};Tr(hA,{aInRange:()=>so,aarray:()=>ln,abignumber:()=>od,abool:()=>nr,abytes:()=>Ae,afunction:()=>ks,anumber:()=>b0,aobject:()=>Ma,asafenumber:()=>Pt,asciiToBytes:()=>Vn,astring:()=>id,bitGet:()=>Gj,bitLen:()=>tl,bitMask:()=>cd,bitSet:()=>Yj,bytesToHex:()=>Qr,bytesToNumberBE:()=>un,bytesToNumberLE:()=>En,concatBytes:()=>Fe,copyBytes:()=>kn,createHmacDrbg:()=>yA,equalBytes:()=>sd,hexToBytes:()=>Da,hexToNumber:()=>pA,inRange:()=>C0,isBytes:()=>ei,isPosBig:()=>Oa,notImplemented:()=>v0,numberToBytesBE:()=>_s,numberToBytesLE:()=>ad,numberToHexUnpadded:()=>el,numberToVarBytesBE:()=>Wj,randomBytes:()=>pt,validateObject:()=>Ge});function ln(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;rn)throw new RangeError("number is too large");return _c(r.padStart(n,"0"))}function ad(e,t){return _s(e,t).reverse()}function Wj(e){return _c(el(od(e)))}function sd(e,t){if(e=Ae(e),t=Ae(t),e.length!==t.length)return!1;let n=0;for(let r=0;r{let r=t.charCodeAt(0);if(t.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${e[n]}" with code ${r} at position ${n}`);return r})}function Oa(e){return typeof e=="bigint"&&g0<=e}function C0(e,t,n){return Oa(e)&&Oa(t)&&Oa(n)&&t<=e&&e 0");if(e.ORDER<=Ct)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Ps(e,t,n=!1){ti(e),ln(t,"nums"),nr(n,"passZero");let r=e,i=new Array(t.length).fill(n?r.ZERO:void 0),o=t.reduce((s,c,l)=>r.is0(c)?s:(i[l]=s,r.mul(s,c)),r.ONE),a=r.inv(o);return t.reduceRight((s,c,l)=>r.is0(c)?s:(i[l]=r.mul(s,i[l]),r.mul(s,c)),a),i}function ld(e,t){ti(e);let n=e;wA(n.ORDER,"FpLegendre");let r=(n.ORDER-Ct)/Is,i=n.pow(t,r),o=n.eql(i,n.ONE),a=n.eql(i,n.ZERO),s=n.eql(i,n.neg(n.ONE));if(!o&&!a&&!s)throw new Error("invalid Legendre symbol result");return o?1:a?0:-1}function bA(e,t){return ld(e,t)!==-1}function oX(e,t){if(t!==void 0&&b0(t),e<=_n)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let n=tl(e);if(t!==void 0&&t= bitLen(n) (${n})`);let r=t!==void 0?t:n,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function ud(e,t={}){return Object.freeze(A0.prototype),new A0(e,t)}function B_(e,t){ti(e);let n=e;if(!n.isOdd)throw new Error("Field doesn't have isOdd");let r=n.sqrt(t);return n.isOdd(r)?n.neg(r):r}function F_(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=Ct)throw new Error("field order must be greater than 1");let t=tl(e-Ct);return Math.ceil(t/8)}function xs(e){let t=F_(e);return t+Math.ceil(t/2)}function Ra(e,t,n=!1){Ae(e);let r=e.length,i=F_(t),o=Math.max(xs(t),16);if(r1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let a=n?En(e):un(e),s=yt(a,t-Ct)+Ct;return n?ad(s,i):_s(s,i)}var _n,Ct,Is,P_,mA,x_,Zj,M_,Jj,Qj,O_,eX,L_,iX,I_,A0,co=Te(()=>{y();Or();_n=BigInt(0),Ct=BigInt(1),Is=BigInt(2),P_=BigInt(3),mA=BigInt(4),x_=BigInt(5),Zj=BigInt(7),M_=BigInt(8),Jj=BigInt(9),Qj=BigInt(15),O_=BigInt(16),eX=BigInt("0x10000000000000000");L_=(e,t)=>(yt(e,t)&Ct)===Ct,iX=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];I_=new WeakMap,A0=class{ORDER;BITS;BYTES;isLE;ZERO=_n;ONE=Ct;_lengths;_mod;constructor(t,n={}){if(t<=Ct)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:i,nByteLength:o}=oX(t,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=i,this.BYTES=o,Object.freeze(this)}create(t){return yt(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return _n<=t&&ti)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);let l=new Uint8Array(i);l.set(t,o?0:l.length-t.length),t=l}if(t.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+t.length);let c=o?En(t):un(t);if(s&&(c=yt(c,a)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ps(this,t,!0)}cmov(t,n,r){return nr(r,"condition"),r?n:t}}});function Ti(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);ks(t.fromAffine,"Point.fromAffine"),ks(t.fromBytes,"Point.fromBytes"),ks(t.fromHex,"Point.fromHex"),Ma(t.BASE,"Point.BASE"),Ma(t.ZERO,"Point.ZERO"),ti(t.Fp),ti(t.Fn)}function T0(e,t){Ti(e),H_(t,e);let n=Ps(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function cX(e,t,n=1){if(!Number.isSafeInteger(e)||et)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function lX(e,t){let n=e*(4*t+128);if(n>$_)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+$_/2**20+" MiB")}function SA(e,t){if(e!==void 0){ks(e,"randomBytes");try{let n=e(t);if(!ei(n)||n.length!==t)return}catch{return}return e}}function H_(e,t){ln(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function uX(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,i)=>{if(!(n===void 0?t.isValid(r):Oa(r)&&rAA;){let a=0;e&cy&&(a=Number(e&i),a>=r&&(a-=n),e-=BigInt(a)),o.push(a),e>>=cy}return o}function pX(e,t,n){let r=2**t,i=r/2,o=BigInt(r-1),a=BigInt(t),s=[];for(let c=0;c>=a,l>i&&(l-=r,e+=cy),s.push(l)}if(e!==AA)throw new Error("invalid wnaf");return s}function yX(e,t,n){let r=0;for(let o of n)r=Math.max(r,o.length);let i=e;for(let o=r-1;o>=0;o--){o!==r-1&&(i=i.double());for(let a=0;a>1];i=i.add(s<0?c.negate():c)}}}return i}function Ms(e,t,n,r=!1){if(Ti(e),H_(t,e),nr(r,"allowOversized"),uX(n,e.Fn,r?e.Fn.ORDER**aX:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let i=t.map(a=>dX(a,4)),o=n.map(a=>fX(a,4));return yX(e.ZERO,i,o)}function q_(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ti(t),t}else return ud(e,{isLE:n})}function E0(e,t,n={},r){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);Ge(n);for(let c of["p","n","h"]){let l=t[c];if(!(Oa(l)&&l!==AA))throw new Error(`CURVE.${c} must be positive bigint`)}let i=q_(t.p,n.Fp,r),o=q_(t.n,n.Fn,r),s=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of s)if(!i.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:o}}function Os(e,t){return function(r){let i=e(r);return{secretKey:i,publicKey:t(i)}}}var AA,cy,aX,CA,U_,sX,$_,V_,dd,nl=Te(()=>{y();Or();co();AA=BigInt(0),cy=BigInt(1),aX=BigInt(4),CA=16,U_=128,sX=5,$_=2**31;V_=new WeakMap;dd=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){Ti(t),this.randomBytes=SA(n,CA),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,r){let i=Math.ceil(r/n)+1,o=2**(n-1),a=[],s=t;for(let c=0;cs.W===t&&s.bits===r);return a||(a=this.buildWnafTable(n,t,r),typeof i=="function"&&(a={...a,comp:i(a.comp)}),o||(o=[],this.wnafPrecomputes.set(n,o)),o.push(a)),a}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!C0(n,cy,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,i){let o=vA(t);return o===1?this.fixedWindowCT(t,n,r):this.wnafCachedCT(this.getWnafPrecomputes(o,t,r,i),n)}mulCT(t,n,r){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,r)}mulCTBlinded(t,n,r){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let i=this.Point.Fn.BITS+U_,o=this.randomBytes(CA);if(!ei(o)||o.length!==CA)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let a=n+un(o)*this.Point.Fn.ORDER;return this.runCT(t,a,i,r)}fixedWindowCT(t,n,r){let i=sX,o=1<=0;u--){if(u!==c-1)for(let h=0;h>BigInt(u*i)&a),p=s[0];for(let h=1;h=this.Point.Fn.ORDER)return Ms(this.Point,[t],[n],!0);let o=this.getWnafPrecomputes(i,t,this.bits,r);return this.wnafCachedCT(o,n).p}setWindowSize(t,n){this.assertPoint(t),cX(n,this.bits);let r=Math.ceil((this.bits+U_)/n)+1;lX(r*2**(n-1),this.Point.Fp.BYTES),V_.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return vA(t)!==1}}});function TA(e,t="n"){if(typeof e!="number")throw new TypeError(`wrong u32 integer "${t}": expected number, got type=${typeof e}`);if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new RangeError(`wrong u32 integer "${t}": expected 0..4294967295, got ${e}`);return e}function K_(e){return TA(e,"x"),(e&e-1)===0&&e!==0}function hX(e){if(TA(e),e<=1)return 1;if(e>2147483648)throw new Error("nextPowerOfTwo overflow: result does not fit u32");return 1<>>0}function k0(e){return TA(e),31-Math.clz32(e)}function z_(e,t,n,r,i){ti(e);let o=e,a=n||((d,p)=>new Array(d).fill(p??o.ZERO)),s=d=>{if(Array.isArray(d))return!0;if(!ArrayBuffer.isView(d))return!1;let p=d;return typeof p.length=="number"&&typeof p.slice=="function"&&typeof p[Symbol.iterator]=="function"},c=(d,p)=>{if(!s(p))throw new TypeError(`"${d}" expected polynomial, got type=${typeof p}`)},l=(d,p)=>{c("a",d);let h=d.length;if(p!==void 0&&(c("b",p),p.length!==h))throw new Error(`poly: mismatched lengths ${h} vs ${p.length}`);if(i!==void 0&&h!==i)throw new Error(`poly: expected fixed length ${i}, got ${h}`);return h};function u(d,p,h=!1,g){if(!K_(p))throw new Error("poly.lagrange: expected power of two length, got "+p);let w=g||(h?t.brp(k0(p)):t.roots(k0(p)));for(let T=0;T{l(d);let h=a(p,o.ZERO);for(let g=0;g{l(d);for(let p=d.length-1;p>=0;p--)if(!o.is0(d[p]))return p;return-1},add:(d,p)=>{let h=l(d,p),g=a(h);for(let w=0;w{let h=l(d,p),g=a(h);for(let w=0;w{let h=l(d,p),g=a(h);for(let w=0;w{if(s(p)){let h=l(d,p);if(r){let g=r.direct(d,!1,!0),w=r.direct(p,!1,!0);for(let T=0;T{l(d);let p=a(d.length);for(let h=0;h{l(d,p);let h=o.ZERO;for(let g=0;g{let h=a(p),g=o.ONE;for(let w=0;w{l(d);let h=o.ZERO;for(let g=d.length-1;g>=0;g--)h=o.add(o.mul(h,p),d[g]);return h}},lagrange:{basis:(d,p,h=!1,g)=>{if(!K_(p))throw new Error("poly.lagrange: expected power of two length, got "+p);let w=k0(p),T=g||(h?t.brp(w):t.roots(w)),k=a(p),B=u(d,p,h,g);if(B!==-1)return k[B]=o.ONE,k;let D=o.pow(d,BigInt(p)),P=o.mul(o.sub(D,o.ONE),o.inv(BigInt(p))),U=a(p);for(let H=0;H0;w--)p[w]=o.add(o.mul(p[w],g),p[w-1]);p[0]=o.mul(p[0],g)}return p}}}var j_=Te(()=>{y();co()});function rl(e,t){if(Pt(e),Pt(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw new Error("invalid I2OSP input: "+e);let n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function gX(e,t){let n=new Uint8Array(e.length);for(let r=0;r255&&(t=r(Fe(Vn("H2C-OVERSIZE-DST-"),t)));let{outputLen:i,blockLen:o}=r,a=Math.ceil(n/i);if(n>65535||a>255)throw new Error("expand_message_xmd: invalid lenInBytes");let s=Fe(t,rl(t.length,1)),c=new Uint8Array(o),l=rl(n,2),u=new Array(a),d=r(Fe(c,e,l,rl(0,1),s));u[0]=r(Fe(d,rl(1,1),s));for(let h=1;h65535)throw new Error("expand_message_xof: invalid lenInBytes");if(t.length>255){let o=Math.ceil(2*r/8);t=i.create({dkLen:o}).update(Vn("H2C-OVERSIZE-DST-")).update(t).digest()}if(t.length>255)throw new Error("expand_message_xof: invalid DST");return i.create({dkLen:n}).update(e).update(rl(n,2)).update(t).update(rl(t.length,1)).digest()}function EA(e,t,n){Ge(n,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:a,expand:s,DST:c}=n;if(Pt(a.outputLen,"valid hash"),Ae(e),Pt(t),Pt(o,"m"),Pt(i,"k"),r<=BigInt(1))throw new Error("hash_to_field: expected valid field characteristic");if(t<1)throw new Error("hash_to_field: expected count >= 1");if(o<1)throw new Error("hash_to_field: expected m >= 1");if(i<0)throw new Error("hash_to_field: invalid k");let l=r.toString(2).length,u=Math.ceil((l+i)/8),d=t*o*u,p;if(s==="xmd")p=_0(e,c,d,a);else if(s==="xof")p=wX(e,c,d,i,a);else if(s==="_internal_pass")p=e;else throw new Error('expand must be "xmd" or "xof"');let h=new Array(t);for(let g=0;g{if(ln(r,"map["+i+"]"),r.length<1)throw new Error("isogenyMap: expected non-empty coefficients");return Array.from(r).reverse()});return(r,i)=>{let[o,a,s,c]=n.map(p=>p.reduce((h,g)=>e.add(e.mul(h,r),g))),l=e.is0(a)||e.is0(c),[u,d]=Ps(e,[a,c],!0);return r=e.mul(o,u),i=e.mul(i,e.mul(s,d)),l?{x:e.ZERO,y:e.ZERO}:{x:r,y:i}}}function I0(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");Ge(n);let r=c=>Object.freeze({...c,DST:ei(c.DST)?kn(c.DST):c.DST,...c.encodeDST===void 0?{}:{encodeDST:ei(c.encodeDST)?kn(c.encodeDST):c.encodeDST}}),i=r(n),o=c=>c&&c.DST!==void 0?{DST:c.DST}:void 0;function a(c){return e.fromAffine(t(c))}function s(c){let l=c.clearCofactor();return l.equals(e.ZERO)?e.ZERO:(l.assertValidity(),l)}return Object.freeze({get defaults(){return r(i)},Point:e,hashToCurve(c,l){let u=Object.assign({},i,o(l)),d=EA(c,2,u),p=a(d[0]),h=a(d[1]);return s(p.add(h))},encodeToCurve(c,l){let u=i.encodeDST===void 0?{}:{DST:i.encodeDST},d=Object.assign({},i,u,o(l)),p=EA(c,1,d),h=a(p[0]);return s(h)},mapToCurve(c){if(i.m===1){if(typeof c!="bigint")throw new Error("expected bigint (m=1)");return s(a([c]))}if(!Array.isArray(c))throw new Error("expected array of bigints");if(c.length!==i.m)throw new Error(`expected array of ${i.m} bigints`);for(let l of c)if(typeof l!="bigint")throw new Error("expected array of bigints");return s(a(c))},hashToScalar(c,l){let u=e.Fn.ORDER,d=Object.assign({},i,{DST:ly},o(l),{p:u,m:1});return EA(c,1,d)[0][0]}})}function bX(e,t){let n=ti(e),r=n.ORDER,i=X_;for(let w=r-Fo;w%Ds===X_;w/=Ds)i+=Fo;let o=i,a=Ds<{let k=p,B=n.pow(T,u),D=n.sqr(B);D=n.mul(D,T);let P=n.mul(w,D);P=n.pow(P,l),P=n.mul(P,B),B=n.mul(P,T),D=n.mul(P,w);let U=n.mul(D,B);P=n.pow(U,d);let F=n.eql(P,n.ONE);B=n.mul(D,h),P=n.mul(U,k),D=n.cmov(B,D,F),U=n.cmov(P,U,F);for(let H=o;H>Fo;H--){let b=H-Ds;b=Ds<{let D=n.sqr(B),P=n.mul(k,B);D=n.mul(D,P);let U=n.pow(D,w);U=n.mul(U,P);let F=n.mul(U,T),H=n.mul(n.sqr(U),B),b=n.eql(H,k),C=n.cmov(F,U,b);return{isValid:!n.is0(B)&&b,value:C}}}return g}function J_(e,t){let n=ti(e);Ge(t,{},{},"opts");let{A:r,B:i,Z:o}=t;if(!n.isValidNot0(r)||!n.isValidNot0(i)||!n.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");if(n.eql(o,n.neg(n.ONE))||bA(n,o))throw new Error("mapToCurveSimpleSWU: invalid opts");let a=n.mul(i,n.inv(n.mul(o,r))),s=n.add(n.add(n.mul(n.sqr(a),a),n.mul(r,a)),i);if(!bA(n,s))throw new Error("mapToCurveSimpleSWU: invalid opts");let c=bX(n,o);if(!n.isOdd)throw new Error("Field does not have .isOdd()");return l=>{let u,d,p,h,g,w,T,k;u=n.sqr(l),u=n.mul(u,o),d=n.sqr(u),d=n.add(d,u),p=n.add(d,n.ONE),p=n.mul(p,i),h=n.cmov(o,n.neg(d),!n.eql(d,n.ZERO)),h=n.mul(h,r),d=n.sqr(p),w=n.sqr(h),g=n.mul(w,r),d=n.add(d,g),d=n.mul(d,p),w=n.mul(w,h),g=n.mul(w,i),d=n.add(d,g),T=n.mul(u,p);let{isValid:B,value:D}=c(d,w);k=n.mul(u,l),k=n.mul(k,D),T=n.cmov(T,p,B),k=n.cmov(k,D,B);let P=n.isOdd(l)===n.isOdd(k);k=n.cmov(n.neg(k),k,P);let U=Ps(n,[h],!0)[0];return T=n.mul(T,U),{x:T,y:k}}}var X_,Fo,Ds,W_,G_,mX,ly,P0=Te(()=>{y();Or();co();X_=BigInt(0),Fo=BigInt(1),Ds=BigInt(2),W_=BigInt(3),G_=BigInt(4),mX=un;ly="HashToScalar-"});function fd(e){Ge(e,{name:"string",hash:"function"},{hashToScalar:"function",validatePoint:"function",parsePublicKey:"function",adjustScalar:"function",adjustPoint:"function",challenge:"function",adjustNonces:"function",adjustSecret:"function",adjustPublic:"function",adjustGroupCommitmentShare:"function",adjustTx:"object",adjustDKG:"function"}),Ti(e.Point);let{Point:t,validatePoint:n,parsePublicKey:r,adjustScalar:i,adjustPoint:o,challenge:a,adjustNonces:s,adjustSecret:c,adjustPublic:l,adjustGroupCommitmentShare:u,adjustDKG:d}=e,p=e.Fn===void 0?t.Fn:e.Fn,h=e.adjustTx===void 0?void 0:{encode:e.adjustTx.encode,decode:e.adjustTx.decode};h&&Ge(h,{encode:"function",decode:"function"});let g=e.hash,w=e.hashToScalar===void 0?(K,re={DST:new Uint8Array})=>{let ce=g(Fe(re.DST,K));return p.create(p.isLE?En(ce):un(ce))}:e.hashToScalar,T=Xr(e.H1!==void 0?e.H1:e.name+"rho"),k=Xr(e.H2!==void 0?e.H2:e.name+"chal"),B=Xr(e.H3!==void 0?e.H3:e.name+"nonce"),D=Xr(e.H4!==void 0?e.H4:e.name+"msg"),P=Xr(e.H5!==void 0?e.H5:e.name+"com"),U=Xr(e.HDKG!==void 0?e.HDKG:e.name+"dkg"),F=Xr(e.HID!==void 0?e.HID:e.name+"id"),H=K=>w(K,{DST:T}),b=K=>w(K,{DST:k}),C=K=>w(K,{DST:B}),v=K=>g(Fe(D,K)),S=K=>g(Fe(P,K)),A=K=>w(K,{DST:U}),M=K=>w(K,{DST:F}),$=(K=pt)=>{if(typeof K!="function")throw new TypeError('"rng" expected function, got type='+typeof K);let re=Ra(K(xs(p.ORDER)),p.ORDER,p.isLE);return p.isLE?En(re):un(re)},R=K=>K.toBytes(),O=K=>{if(K.assertValidity(),K.is0())throw new Error("invalid point: identity");if(!K.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return n&&n(K),K},j=K=>O(t.fromBytes(K)),N=(K,re)=>({identifier:K,hiding:R(t.BASE.multiply(p.fromBytes(re.hiding))),binding:R(t.BASE.multiply(p.fromBytes(re.binding)))}),V=o===void 0?K=>K:o,G=K=>{if(!p.isValid(K)||p.is0(K))throw new Error("Invalid identifier "+K);return K},L=K=>Qr(p.toBytes(G(K))),X=(K,re="identifier")=>{id(K,re);let ce=G(p.fromBytes(Da(K)));if(L(ce)!==K)throw new Error("expected canonical identifier hex");return ce},Z=K=>({identifier:L(X(K.identifier)),commitment:K.commitment.map(re=>kn(re)),proofOfKnowledge:kn(K.proofOfKnowledge)}),ee=K=>{let re=K.map(Z);return re.sort((ce,he)=>{let ge=X(ce.identifier),we=X(he.identifier);return gewe?1:0}),re},J=(K,re)=>{if(K.length!==re.length)return!1;for(let ce=0;ce{let ce=Fe(R(K),p.toBytes(re));return h&&(ce=h.encode(ce)),ce},decode:K=>{h&&(K=h.decode(K));let re=K.subarray(0,-p.BYTES),ce=j(re);if(R(ce).length!==re.length)throw new Error("invalid signature encoding");let he=p.fromBytes(K.subarray(-p.BYTES));return{R:ce,z:he}}},se=(K=pt)=>{let re=$(K);i&&(re=i(re));let ce=t.BASE.multiply(re);return{scalar:re,point:ce}},me="roots are unavailable in FROST polynomial mode",pe={info:{G:p.ZERO,oddFactor:p.ZERO,powerOfTwo:0},roots(){throw new Error(me)},brp(){throw new Error(me)},inverse(){throw new Error(me)},omega(){throw new Error(me)},clear(){}},Pe=z_(p,pe),Ee=(K,re)=>Ms(t,K,re),Ne=(K,re)=>{if(!re.length)throw new Error("empty coefficients");return Pe.monomial.eval(re,K)},De=(K,re)=>{let ce="invalid parameters";if(!K.some(Me=>p.eql(Me,re)))throw new Error(ce);let he=new Set(K);if(he.size!==K.length)throw new Error(ce);if(!he.has(re))throw new Error(ce);let ge=p.ONE,we=p.ONE;for(let Me of K)p.eql(Me,re)||(ge=p.mul(ge,Me),we=p.mul(we,p.sub(Me,re)));return p.div(ge,we)},qe=(K,re)=>{let ce=Pe.monomial.basis(K,re.length);return Ee(re,ce)},xe=(K,re,ce,he=pt)=>{if(Uo(K),re!==void 0&&Ae(re,p.BYTES,"secret"),ce!==void 0&&ln(ce,"coeffs"),typeof he!="function")throw new TypeError('"rng" expected function, got type='+typeof he);let ge=re===void 0?$(he):p.fromBytes(re);if(!ce){ce=[];for(let Re=0;Ret.BASE.multiply(Re));return{coefficients:we,commitment:Me,secret:ge}},vt={challenge:(K,re,ce)=>A(Fe(p.toBytes(K),R(re),R(ce))),compute(K,re,ce,he=pt){if(re.length<1)throw new Error("coefficients should have at least one element");let{point:ge,scalar:we}=se(he),Me=ce[0],Re=this.challenge(K,Me,ge),gt=p.add(we,p.mul(re[0],Re));return ie.encode(ge,gt)},validate(K,re,ce){if(re.length<1)throw new Error("commitment should have at least one element");let{R:he,z:ge}=ie.decode(ce),we=j(re[0]),Me=this.challenge(K,we,he);if(!he.equals(t.BASE.multiplyUnsafe(ge).subtract(we.multiplyUnsafe(Me))))throw new Error("invalid proof of knowledge")}},Kr={challenge:(K,re,ce)=>a?a(K,re,ce):b(Fe(R(K),R(re),ce)),sign(K,re,ce=pt){let{point:he,scalar:ge}=se(ce),we=t.BASE.multiply(re),Me=this.challenge(he,we,K),Re=p.add(ge,p.mul(Me,re));return[he,Re]},verify(K,re,ce,he){o&&(he=o(he)),o&&(re=o(re));let ge=this.challenge(re,he,K),we=t.BASE.multiplyUnsafe(ce),Me=he.multiplyUnsafe(ge),Re=we.subtract(Me).subtract(re);return Re.clearCofactor&&(Re=Re.clearCofactor()),t.ZERO.equals(Re)}},Xi=(K,re,ce)=>{if(!t.BASE.multiply(ce).equals(qe(K,re)))throw new Error("invalid secret share")},Sr={fromNumber(K){if(!Number.isSafeInteger(K))throw new Error("expected safe interger");return L(BigInt(K))},derive(K){return id(K,"s"),L(M(Xr(K)))}},uu=(K,re=pt)=>C(Fe(re(32),p.toBytes(K))),lt=(K,re,ce)=>{let he=re.map(Rt=>[Rt.identifier,X(Rt.identifier),j(Rt.hiding),j(Rt.binding)]);he.sort((Rt,wn)=>Rt[1]wn[1]?1:0);let ge=[];for(let[Rt,wn,Qe,sn]of he)ge.push(p.toBytes(wn),R(Qe),R(sn));let we=S(Fe(...ge)),Me=Fe(R(K),v(ce),we),Re={};for(let[Rt,wn]of he)Re[Rt]=H(Fe(Me,p.toBytes(wn)));let gt=t.ZERO,He=[],Je=[];for(let[Rt,wn,Qe,sn]of he){if(t.ZERO.equals(Qe)||t.ZERO.equals(sn))throw new Error("infinity commitment");gt=gt.add(Qe),He.push(sn),Je.push(Re[Rt])}let Se=gt.add(Ee(He,Je));return{identifiers:he.map(Rt=>Rt[1]),groupCommitment:Se,bindingFactors:Re}},du=(K,re,ce,he)=>{let ge=V(j(K)),we=X(he),{identifiers:Me,groupCommitment:Re,bindingFactors:gt}=lt(ge,re,ce),He=gt[he],Je=De(Me,we),Se=Kr.challenge(Re,ge,ce);return{lambda:Je,challenge:Se,bindingFactor:He,groupCommitment:Re}};Object.freeze(Sr);let Mm={Identifier:Sr,DKG:Object.freeze({round1:(K,re,ce,he=pt)=>{let ge=X(K,"id");Uo(re);let{coefficients:we,commitment:Me}=xe(re,ce,void 0,he),Re=vt.compute(ge,we,Me,he),gt=Me.map(R),He={identifier:L(ge),commitment:gt,proofOfKnowledge:Re},Je={identifier:ge,coefficients:we,commitment:Me.map(R),signers:{min:re.min,max:re.max},step:1};return{public:He,secret:Je}},round2:(K,re)=>{if(Ge(K,{identifier:"bigint",commitment:"object",signers:"object"},{coefficients:"object",round1Cache:"object",round2Cache:"object",step:"number"},"secret"),Uo(K.signers,"secret.signers"),ln(re,"others"),re.length!==K.signers.max-1)throw new Error("wrong number of round1 packages");if(!K.coefficients||K.step===3)throw new Error("round3 package used in round2");let ce=ee(re);if(K.round2Cache!==void 0){if(K.round1Cache===void 0||!J(K.round1Cache,ce))throw new Error("round1 packages do not match authenticated transcript");return K.round2Cache}let he={};for(let ge of ce){if(ge.commitment.length!==K.signers.min)throw new Error("wrong number of commitments");let we=X(ge.identifier);if(we===K.identifier)throw new Error("duplicate id="+L(we));vt.validate(we,ge.commitment,ge.proofOfKnowledge);for(let Re of ge.commitment)j(Re);if(he[ge.identifier])throw new Error("Duplicate id="+we);let Me=p.toBytes(Ne(we,K.coefficients));he[ge.identifier]={identifier:L(K.identifier),signingShare:Me}}return K.round1Cache=ce,K.round2Cache=he,K.step=2,he},round3:(K,re,ce)=>{if(Ge(K,{identifier:"bigint",commitment:"object",signers:"object"},{coefficients:"object",round1Cache:"object",round2Cache:"object",step:"number"},"secret"),Uo(K.signers,"secret.signers"),ln(re,"round1"),ln(ce,"round2"),re.length!==K.signers.max-1)throw new Error("wrong length of round1 packages");if(!K.coefficients||K.step!==2||!K.round1Cache)throw new Error("round2 package used in round3");let he=ee(re),ge=K.round1Cache;if(!J(ge,he))throw new Error("round1 packages do not match authenticated transcript");if(ce.length!==ge.length)throw new Error("wrong length of round2 packages");let we={};for(let Qe of ge){if(!Qe.identifier||!Qe.commitment)throw new Error("wrong round1 share");we[Qe.identifier]={...Qe}}for(let Qe of ce){if(!Qe.identifier||!Qe.signingShare)throw new Error("wrong round2 share");if(!we[Qe.identifier])throw new Error("round1 share for "+Qe.identifier+" is missing");we[Qe.identifier].signingShare=Qe.signingShare}if(Object.keys(we).length!==ge.length)throw new Error("mismatch identifiers between rounds");let Me=p.ZERO;if(K.commitment.length!==K.signers.min)throw new Error("wrong commitments length");let Re=K.commitment.map(j),gt=Ne(K.identifier,K.coefficients);Xi(K.identifier,Re,gt);let He=Re.map(R),Je={[L(K.identifier)]:He};for(let Qe in we){let sn=we[Qe];if(!sn.signingShare||!sn.commitment)throw new Error("mismatch identifiers");let Wi=X(Qe),wa=p.fromBytes(sn.signingShare),hp=sn.commitment.map(j);Xi(K.identifier,hp,wa),Me=p.add(Me,wa);let zr=L(Wi);if(Je[zr])throw new Error("duplicated id="+zr);Je[zr]=sn.commitment}Me=p.add(Me,gt);let Se=new Array(K.signers.min).fill(t.ZERO);for(let Qe in Je){let sn=Je[Qe];if(sn.length!==K.signers.min)throw new Error("wrong commitments length");for(let Wi=0;Wi[Qe,sn.slice()]))},secret:{identifier:L(K.identifier),signingShare:p.toBytes(Me)}};d&&(wn=d(wn));for(let Qe=0;Qe[...G])}:void 0,T=o6(r,i);function k(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function B(G,L,X){if(L.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:Z,y:ee}=L.toAffine(),J=r.toBytes(Z);if(nr(X,"isCompressed"),X){k();let ie=!r.isOdd(ee);return Fe(i6(ie),J)}else return Fe(Uint8Array.of(4),J,r.toBytes(ee))}function D(G){Ae(G,void 0,"Point");let{publicKey:L,publicKeyUncompressed:X}=T,Z=G.length,ee=G[0],J=G.subarray(1);if(l&&Z===1&&ee===0)return{x:r.ZERO,y:r.ZERO};if(Z===L&&(ee===2||ee===3)){let ie=r.fromBytes(J);if(!r.isValid(ie))throw new Error("bad point: is not on curve, wrong x");let se=b(ie),me;try{me=r.sqrt(se)}catch(Ee){let Ne=Ee instanceof Error?": "+Ee.message:"";throw new Error("bad point: is not on curve, sqrt error"+Ne)}k();let pe=r.isOdd(me);return(ee&1)===1!==pe&&(me=r.neg(me)),{x:ie,y:me}}else if(Z===X&&ee===4){let ie=r.BYTES,se=r.fromBytes(J.subarray(0,ie)),me=r.fromBytes(J.subarray(ie,ie*2));if(!C(se,me))throw new Error("bad point: is not on curve");return{x:se,y:me}}else throw new Error(`bad point: got length ${Z}, expected compressed=${L} or uncompressed=${X}`)}let P=h===void 0?B:h,U=p===void 0?D:p,F=r.mul(o.b,PA),H=r.is0(o.a)?G=>r.ZERO:G=>r.mul(o.a,G);function b(G){let L=r.sqr(G),X=r.mul(L,G);return r.add(r.add(X,r.mul(G,o.a)),o.b)}function C(G,L){let X=r.sqr(L),Z=b(G);return r.eql(X,Z)}if(!C(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let v=r.mul(r.pow(o.a,PA),AX),S=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(v,S)))throw new Error("bad curve params: a or b");function A(G,L,X=!1){if(!r.isValid(L)||X&&r.is0(L))throw new Error(`bad point coordinate ${G}`);return typeof L=="object"&&L!==null?r.create(L):L}function M(G){if(!(G instanceof j))throw new Error("Weierstrass Point expected")}function $(G){if(!w||!w.basises)throw new Error("no endo");return vX(G,w.basises,i.ORDER)}function R(G,L,X,Z){if(!i.isValid(Z))throw new RangeError("invalid scalar: out of range");if(w){let{k1neg:ee,k1:J,k2neg:ie,k2:se}=$(Z),me=new j(r.mul(X.X,w.beta),X.Y,X.Z);G.push(ee?X.negate():X,ie?me.negate():me),L.push(J,se)}else G.push(X),L.push(Z)}let O=new WeakSet;class j{static BASE=new j(o.Gx,o.Gy,r.ONE);static ZERO=new j(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=i;X;Y;Z;constructor(L,X,Z){this.X=A("x",L),this.Y=A("y",X,!0),this.Z=A("z",Z),Object.freeze(this)}static CURVE(){return o}static fromAffine(L){let{x:X,y:Z}=L||{};if(!L||!r.isValid(X)||!r.isValid(Z))throw new Error("invalid affine point");if(L instanceof j)throw new Error("projective point not allowed");return r.is0(X)&&r.is0(Z)?j.ZERO:new j(X,Z,r.ONE)}static fromBytes(L){let X=j.fromAffine(U(Ae(L,void 0,"point")));return X.assertValidity(),X}static fromHex(L){return j.fromBytes(Da(L))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(L=6,X=!0){return V.setWindowSize(this,L),X||this.multiply(PA),this}assertValidity(){let L=this;if(L.is0()){if(l&&r.is0(L.X)&&r.eql(L.Y,r.ONE)&&r.is0(L.Z))return;throw new Error("bad point: ZERO")}if(O.has(L))return;let{x:X,y:Z}=L.toAffine();if(!r.isValid(X)||!r.isValid(Z))throw new Error("bad point: x or y not field elements");if(!C(X,Z))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");O.add(L)}hasEvenY(){let{y:L}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(L)}equals(L){M(L);let{X,Y:Z,Z:ee}=this,{X:J,Y:ie,Z:se}=L,me=r.eql(r.mul(X,se),r.mul(J,ee)),pe=r.eql(r.mul(Z,se),r.mul(ie,ee));return me&&pe}negate(){return new j(this.X,r.neg(this.Y),this.Z)}double(){let{X:L,Y:X,Z}=this,ee=r.ZERO,J=r.ZERO,ie=r.ZERO,se=r.mul(L,L),me=r.mul(X,X),pe=r.mul(Z,Z),Pe=r.mul(L,X);return Pe=r.add(Pe,Pe),ie=r.mul(L,Z),ie=r.add(ie,ie),ee=H(ie),J=r.mul(F,pe),J=r.add(ee,J),ee=r.sub(me,J),J=r.add(me,J),J=r.mul(ee,J),ee=r.mul(Pe,ee),ie=r.mul(F,ie),pe=H(pe),Pe=r.sub(se,pe),Pe=H(Pe),Pe=r.add(Pe,ie),ie=r.add(se,se),se=r.add(ie,se),se=r.add(se,pe),se=r.mul(se,Pe),J=r.add(J,se),pe=r.mul(X,Z),pe=r.add(pe,pe),se=r.mul(pe,Pe),ee=r.sub(ee,se),ie=r.mul(pe,me),ie=r.add(ie,ie),ie=r.add(ie,ie),new j(ee,J,ie)}add(L){M(L);let{X,Y:Z,Z:ee}=this,{X:J,Y:ie,Z:se}=L,me=r.ZERO,pe=r.ZERO,Pe=r.ZERO,Ee=r.mul(X,J),Ne=r.mul(Z,ie),De=r.mul(ee,se),qe=r.add(X,Z),xe=r.add(J,ie);qe=r.mul(qe,xe),xe=r.add(Ee,Ne),qe=r.sub(qe,xe),xe=r.add(X,ee);let vt=r.add(J,se);return xe=r.mul(xe,vt),vt=r.add(Ee,De),xe=r.sub(xe,vt),vt=r.add(Z,ee),me=r.add(ie,se),vt=r.mul(vt,me),me=r.add(Ne,De),vt=r.sub(vt,me),Pe=H(xe),me=r.mul(F,De),Pe=r.add(me,Pe),me=r.sub(Ne,Pe),Pe=r.add(Ne,Pe),pe=r.mul(me,Pe),Ne=r.add(Ee,Ee),Ne=r.add(Ne,Ee),De=H(De),xe=r.mul(F,xe),Ne=r.add(Ne,De),De=r.sub(Ee,De),De=H(De),xe=r.add(xe,De),Ee=r.mul(Ne,xe),pe=r.add(pe,Ee),Ee=r.mul(vt,xe),me=r.mul(qe,me),me=r.sub(me,Ee),Ee=r.mul(qe,Ne),Pe=r.mul(vt,Pe),Pe=r.add(Pe,Ee),new j(me,pe,Pe)}subtract(L){return M(L),this.add(L.negate())}is0(){return this.equals(j.ZERO)}multiply(L){if(!i.isValidNot0(L))throw new RangeError("invalid scalar: out of range");let{p:X,f:Z}=V.mulSecret(this,L,a,N);return N([X,Z])[0]}multiplyUnsafe(L){let X=this,Z=L;if(!i.isValid(Z))throw new RangeError("invalid scalar: out of range");if(Z===Ba||X.is0())return j.ZERO;if(Z===ol)return X;if(V.hasWindowSize(this))return V.mulUnsafe(X,Z,N);let ee=[],J=[];return R(ee,J,X,Z),Ms(j,ee,J)}mulAddUnsafe(L,X,Z){M(X);let ee=[],J=[];return R(ee,J,this,L),R(ee,J,X,Z),Ms(j,ee,J)}toAffine(L){let X=this,Z=L;if(Z!=null&&!r.isValid(Z))throw new RangeError('"invertedZ" expected valid field element');let{X:ee,Y:J,Z:ie}=X;if(r.eql(ie,r.ONE))return{x:ee,y:J};let se=X.is0();Z==null&&(Z=se?r.ONE:r.inv(ie));let me=r.mul(ee,Z),pe=r.mul(J,Z),Pe=r.mul(ie,Z);if(se)return{x:r.ZERO,y:r.ZERO};if(!r.eql(Pe,r.ONE))throw new Error("invZ was invalid");return{x:me,y:pe}}isTorsionFree(){return a===ol?!0:d?d(j,this):V.mulUnsafe(this,s).is0()}clearCofactor(){return a===ol?this:u?u(j,this):this.multiplyUnsafe(a)}isSmallOrder(){return a===ol?this.is0():this.clearCofactor().is0()}toBytes(L=!0){return nr(L,"isCompressed"),this.assertValidity(),P(j,this,L)}toHex(L=!0){return Qr(this.toBytes(L))}toString(){return``}}let N=G=>T0(j,G),V=new dd(j,g);return V.bits>=6&&j.BASE.precompute(6),Object.freeze(j.prototype),Object.freeze(j),j}function i6(e){return Uint8Array.of(e?2:3)}function o6(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function SX(e,t={}){Ti(e);let{Fn:n}=e,r=t.randomBytes===void 0?pt:t.randomBytes,i=Object.assign(o6(e.Fp,n),{seed:Math.max(xs(n.ORDER),16)});function o(h){try{let g=n.fromBytes(h);return n.isValidNot0(g)}catch{return!1}}function a(h,g){let{publicKey:w,publicKeyUncompressed:T}=i;try{let k=h.length;return g===!0&&k!==w||g===!1&&k!==T?!1:!e.fromBytes(h).is0()}catch{return!1}}function s(h){return h=h===void 0?r(i.seed):h,Ra(Ae(h,i.seed,"seed"),n.ORDER)}function c(h,g=!0){return e.BASE.multiply(n.fromBytes(h)).toBytes(g)}function l(h){let{secretKey:g,publicKey:w,publicKeyUncompressed:T}=i,k=n._lengths;if(!ei(h))return;let B=Ae(h,void 0,"key").length,D=B===w||B===T,P=B===g||!!k?.includes(B);if(!(D&&P))return D}function u(h,g,w=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");let T=n.fromBytes(h),k=e.fromBytes(g);if(k.is0())throw new Error("invalid public key: point at infinity");return k.multiply(T).toBytes(w)}let d={isValidSecretKey:o,isValidPublicKey:a,randomSecretKey:s},p=Os(s,c);return Object.freeze(d),Object.freeze(i),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:d,lengths:i})}function a6(e,t,n={}){Ti(e);let r=t;va(r),Ge(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let i=Object.assign({},n),o=i.randomBytes===void 0?pt:i.randomBytes,a=i.hmac===void 0?(G,L)=>Na(r,G,L):i.hmac,{Fp:s,Fn:c}=e,{ORDER:l,BITS:u}=c,d=xs(l),p=SA(o,d),{keygen:h,getPublicKey:g,getSharedSecret:w,utils:T,lengths:k}=SX(e,i),B={prehash:!0,lowS:typeof i.lowS=="boolean"?i.lowS:!0,format:"compact",extraEntropy:!1},D=l*n6+ol>ol;return G>L}function U(G,L){if(!c.isValidNot0(L))throw new Error(`invalid signature ${G}: out of range 1..Point.Fn.ORDER`);return L}function F(){if(!s.isOdd)throw new Error("Field doesn't support isOdd")}function H(G,L,X){return F(),(G===X?0:2)|Number(s.isOdd(L))}function b(){if(D)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function C(G,L){xA(L);let X=k.signature,Z=L==="compact"?X:L==="recovered"?X+1:void 0;return Ae(G,Z)}class v{r;s;recovery;constructor(L,X,Z){if(this.r=U("r",L),this.s=U("s",X),Z!=null){if(b(),![0,1,2,3].includes(Z))throw new Error("invalid recovery id");this.recovery=Z}Object.freeze(this)}static fromBytes(L,X=B.format){C(L,X);let Z;if(X==="der"){if(L.length>2*c.BYTES+16)throw new M0.Err("invalid signature: DER signature too long");let{r:se,s:me}=M0.toSig(Ae(L),c.BYTES+1);return new v(se,me)}X==="recovered"&&(Z=L[0],X="compact",L=L.subarray(1));let ee=k.signature/2,J=L.subarray(0,ee),ie=L.subarray(ee,ee*2);return new v(c.fromBytes(J),c.fromBytes(ie),Z)}static fromHex(L,X){return this.fromBytes(Da(L),X)}assertRecovery(){let{recovery:L}=this;if(L==null)throw new Error("invalid recovery id: must be present");return L}addRecoveryBit(L){return new v(this.r,this.s,L)}recoverPublicKey(L){let{r:X,s:Z}=this,ee=this.assertRecovery(),J=ee===2||ee===3?X+l:X;if(!s.isValid(J))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let ie=s.toBytes(J),se=e.fromBytes(Fe(i6((ee&1)===0),ie)),me=c.inv(J),pe=A(Ae(L,void 0,"msgHash")),Pe=c.create(-pe*me),Ee=c.create(Z*me),Ne=e.BASE.mulAddUnsafe(Pe,se,Ee);if(Ne.is0())throw new Error("invalid recovery: point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return P(this.s)}toBytes(L=B.format){if(xA(L),L==="der")return Da(M0.hexFromSig(this));let{r:X,s:Z}=this,ee=c.toBytes(X),J=c.toBytes(Z);return L==="recovered"?(b(),Fe(Uint8Array.of(this.assertRecovery()),ee,J)):Fe(ee,J)}toHex(L){return Qr(this.toBytes(L))}}Object.freeze(v.prototype),Object.freeze(v);let S=i.bits2int===void 0?function(L){if(L.length>8192)throw new Error("input is too large");let X=un(L),Z=L.length*8-u;return Z>0?X>>BigInt(Z):X}:i.bits2int,A=i.bits2int_modN===void 0?function(L){return c.create(S(L))}:i.bits2int_modN,M=cd(u);function $(G){return so("num < 2^"+u,G,Ba,M),c.toBytes(G)}function R(G,L){return Ae(G,void 0,"message"),L?Ae(r(G),void 0,"prehashed message"):G}function O(G,L,X){let{lowS:Z,prehash:ee,extraEntropy:J}=IA(X,B);G=R(G,ee);let ie=A(G),se=c.fromBytes(L);if(!c.isValidNot0(se))throw new Error("invalid private key");let me=[$(se),$(ie)];if(J!=null&&J!==!1){let Ne=J===!0?o(k.secretKey):J;me.push(Ae(Ne,void 0,"extraEntropy"))}let pe=Fe(...me),Pe=ie;function Ee(Ne){let De=S(Ne);if(!c.isValidNot0(De))return;let qe=e.BASE.multiply(De).toAffine(),xe=c.create(qe.x);if(xe===Ba)return;let vt;if(p!==void 0){let Sr=un(Ra(p(d),l)),uu=c.inv(c.mul(Sr,De)),lt=c.mul(Sr,Pe),du=c.mul(Sr,se);vt=c.create(uu*c.create(lt+du*xe))}else{let Sr=S0(De,l);vt=c.create(Sr*c.create(Pe+xe*se))}if(vt===Ba)return;let Kr=H(qe.x,qe.y,xe),Xi=vt;return Z&&P(vt)&&(Xi=c.neg(vt),Kr^=1),new v(xe,Xi,D?void 0:Kr)}return{seed:pe,k2sig:Ee}}function j(G,L,X={}){let{seed:Z,k2sig:ee}=O(G,L,X);return yA(r.outputLen,c.BYTES,a)(Z,ee).toBytes(X.format)}function N(G,L,X,Z={}){let{lowS:ee,prehash:J,format:ie}=IA(Z,B);if(X=Ae(X,void 0,"publicKey"),L=R(L,J),!ei(G)){let se=G instanceof v?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+se)}C(G,ie);try{let se=v.fromBytes(G,ie),me=e.fromBytes(X);if(me.is0()||ee&&se.hasHighS())return!1;let{r:pe,s:Pe}=se,Ee=A(L),Ne=c.inv(Pe),De=c.create(Ee*Ne),qe=c.create(pe*Ne),xe=e.BASE.mulAddUnsafe(De,me,qe);if(xe.is0())return!1;let vt=xe.toAffine();return!(c.create(vt.x)!==pe||ie==="recovered"&&se.recovery!==H(vt.x,vt.y,pe))}catch{return!1}}function V(G,L,X={}){let{prehash:Z}=IA(X,B);return L=R(L,Z),v.fromBytes(G,"recovered").recoverPublicKey(L).toBytes()}return Object.freeze({keygen:h,getPublicKey:g,getSharedSecret:w,utils:T,lengths:k,Point:e,sign:j,verify:N,recoverPublicKey:V,Signature:v,hash:r})}var t6,Ba,ol,n6,PA,AX,s6=Te(()=>{y();uy();Hn();Or();nl();e6();co();t6=(e,t)=>(e+(e>=0?t:-t)/n6)/t;Ba=BigInt(0),ol=BigInt(1),n6=BigInt(2),PA=BigInt(3),AX=BigInt(4)});var NA={};Tr(NA,{__TEST:()=>_X,schnorr:()=>IX,schnorr_FROST:()=>DX,secp256k1:()=>al,secp256k1_FROST:()=>MX,secp256k1_hasher:()=>DA});function EX(e){let t=O0.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),o=BigInt(22),a=BigInt(23),s=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Vt(u,n,t)*u%t,p=Vt(d,n,t)*u%t,h=Vt(p,c6,t)*l%t,g=Vt(h,i,t)*h%t,w=Vt(g,o,t)*g%t,T=Vt(w,s,t)*w%t,k=Vt(T,c,t)*T%t,B=Vt(k,s,t)*w%t,D=Vt(B,n,t)*u%t,P=Vt(D,a,t)*g%t,U=Vt(P,r,t)*l%t,F=Vt(U,c6,t);if(!lo.eql(lo.sqr(F),e))throw new Error("Cannot find square root");return F}function dy(e,...t){let n=l6[e];if(n===void 0){let r=_t(Vn(e));n=Fe(r,r),l6[e]=n}return _t(Fe(n,...t))}function p6(e){let{Fn:t,BASE:n}=xt,r=t.fromBytes(Ae(e,32,"secretKey")),o=n.multiply(r).toAffine();return{scalar:$o(o.y)?r:t.neg(r),bytes:f6(o)}}function D0(e){let t=lo;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x \u2265 p");let n=t.sqr(e),r=t.add(t.mulN(n,e),BigInt(7)),i=t.sqrt(r);$o(i)||(i=t.neg(i));let o=xt.fromAffine({x:e,y:i});return o.assertValidity(),o}function OA(...e){return xt.Fn.create(pd(dy("BIP0340/challenge",...e)))}function u6(e){return p6(e).bytes}function kX(e,t,n=us(32)){let{Fn:r,BASE:i}=xt,o=kn(Ae(e,void 0,"message")),{bytes:a,scalar:s}=p6(t),c=Ae(n,32,"auxRand"),l=r.toBytes(s^pd(dy("BIP0340/aux",c))),u=dy("BIP0340/nonce",l,a,o),d=r.create(pd(u));if(d===MA)throw new Error("sign failed: k is zero");let h=i.multiply(d).toAffine(),g=$o(h.y)?d:r.neg(d),w=f6(h),T=OA(w,a,o),k=new Uint8Array(64);if(k.set(w,0),k.set(r.toBytes(r.create(g+T*s)),32),!y6(k,o,a))throw new Error("sign: Invalid signature produced");return k}function y6(e,t,n){let{Fp:r,Fn:i,BASE:o}=xt,a=Ae(e,64,"signature"),s=Ae(t,void 0,"message"),c=Ae(n,32,"publicKey");try{let l=D0(pd(c)),u=a.subarray(0,32),d=pd(u);if(!r.isValidNot0(d))return!1;let p=pd(a.subarray(32,64));if(!i.isValidNot0(p))return!1;let h=OA(u,fy(l),s),g=o.mulAddUnsafe(p,l,i.neg(h)),{x:w,y:T}=g.toAffine();return!(g.is0()||!$o(T)||!r.eql(w,d))}catch{return!1}}function h6(e,t){if(t===void 0)return MA;let n=fy(e),r=un(dy("TapTweak",n,t));if(!xt.Fn.isValid(r))throw new Error("invalid TapTweak hash");return r}function RA(e){let t=xt.fromBytes(e.commitments[0]);return $o(t.y)?e:{signers:{min:e.signers.min,max:e.signers.max},commitments:e.commitments.map(n=>xt.fromBytes(n).negate().toBytes()),verifyingShares:Object.fromEntries(Object.entries(e.verifyingShares).map(([n,r])=>[n,xt.fromBytes(r).negate().toBytes()]))}}function m6(e,t){let n=xt.fromBytes(t.commitments[0]);if($o(n.y))return e;let r=xt.Fn;return{...e,signingShare:r.toBytes(r.neg(r.fromBytes(e.signingShare)))}}function OX(e,t){if($o(e.y))return t;let n=xt.Fn;return{binding:n.toBytes(n.neg(n.fromBytes(t.binding))),hiding:n.toBytes(n.neg(n.fromBytes(t.hiding)))}}function g6(e,t,n){let r=xt.Fn,i=m6(e,t),o=RA(t),a=h6(xt.fromBytes(o.commitments[0]),n),s=r.toBytes(r.add(r.fromBytes(i.signingShare),a));return{identifier:i.identifier,signingShare:s}}function w6(e,t){let n=RA(e),r=h6(xt.fromBytes(n.commitments[0]),t);if(r===MA)return n;let i=xt.BASE.multiply(r),o=n.commitments.map((s,c)=>(c===0?xt.fromBytes(s).add(i):xt.fromBytes(s)).toBytes()),a={};for(let s in n.verifyingShares)a[s]=xt.fromBytes(n.verifyingShares[s]).add(i).toBytes();return{signers:{min:n.signers.min,max:n.signers.max},commitments:o,verifyingShares:a}}var O0,TX,MA,c6,lo,xt,al,l6,fy,f6,$o,pd,_X,IX,PX,d6,xX,DA,MX,DX,R0=Te(()=>{y();Bo();Hn();nl();kA();P0();co();s6();Or();O0={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},TX={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},MA=BigInt(0),c6=BigInt(2);lo=ud(O0.p,{sqrt:EX}),xt=r6(O0,{Fp:lo,endo:TX}),al=a6(xt,_t),l6=Object.create(null);fy=e=>e.toBytes(!0).slice(1),f6=({x:e})=>lo.toBytes(e),$o=e=>!lo.isOdd(e);pd=un;_X=Object.freeze({lift_x:D0,frostTweakPublic:w6,frostTweakSecret:g6}),IX=(()=>{let n=r=>(r=r===void 0?us(48):r,Ra(Ae(r,48,"seed"),O0.n));return Object.freeze({keygen:Os(n,u6),getPublicKey:u6,sign:kX,verify:y6,Point:xt,utils:Object.freeze({randomSecretKey:n,taggedHash:dy,lift_x:D0,pointToBytes:fy}),lengths:Object.freeze({secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48})})})(),PX=Z_(lo,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),xX=()=>d6||(d6=J_(lo,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:lo.create(BigInt("-11"))})),DA=I0(xt,e=>{let{x:t,y:n}=xX()(lo.create(e[0]));return PX(t,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:lo.ORDER,m:1,k:128,expand:"xmd",hash:_t}),MX=fd({name:"FROST-secp256k1-SHA256-v1",Point:xt,hashToScalar:DA.hashToScalar,hash:_t});DX=fd({name:"FROST-secp256k1-SHA256-TR-v1",Point:xt,hashToScalar:DA.hashToScalar,hash:_t,parsePublicKey(e){if(e.length===32)return D0(un(e));if(e.length===33)return xt.fromBytes(e);throw new Error(`expected x-only or compressed public key, got length=${e.length}`)},adjustScalar(e){let t=xt.BASE.multiply(e);return $o(t.y)?e:xt.Fn.neg(e)},adjustPoint:e=>$o(e.y)?e:e.negate(),challenge(e,t,n){return OA(fy(e),fy(t),n)},adjustNonces:OX,adjustGroupCommitmentShare:(e,t)=>$o(e.y)?t:t.negate(),adjustPublic:RA,adjustSecret:m6,adjustTx:{encode:e=>e.subarray(1),decode:e=>Fe(Uint8Array.of(2),e)},adjustDKG:e=>{let t=new Uint8Array(0);return{public:w6(e.public,t),secret:g6(e.secret,e.public,t)}}})});var py=q(BA=>{"use strict";y();Object.defineProperty(BA,"__esModule",{value:!0});var RX=Rg(),NX=(Or(),Ji(hA)),LA=class e{constructor(){this.hash=RX.sha512.create()}static half(t){return new e().add(t).first256()}add(t){return this.hash.update(t),this}addU32(t){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),this.add(n)}finish(){return this.hash.digest()}first256(){return this.finish().slice(0,32)}first256BigInt(){return(0,NX.bytesToNumberBE)(this.first256())}};BA.default=LA});var UA=q(Rs=>{"use strict";y();var LX=Rs&&Rs.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Rs,"__esModule",{value:!0});Rs.accountPublicFromPublicGenerator=Rs.derivePrivateKey=void 0;var yy=(R0(),Ji(NA)),BX=LX(py()),FX=BigInt(0);function FA(e,t){let n=yy.secp256k1.Point.CURVE().n;for(let r=0;r<=4294967295;r++){let i=new BX.default().add(e);t!==void 0&&i.addU32(t),i.addU32(r);let o=i.first256BigInt();if(o>FX&&o{"use strict";y();Object.defineProperty($A,"__esModule",{value:!0});var qX={ok(e,t){if(!e)throw new Error(t)}};$A.default=qX});var v6=q(Ns=>{"use strict";y();Object.defineProperty(Ns,"__esModule",{value:!0});Ns.getAlgorithmFromPrivateKey=Ns.getAlgorithmFromPublicKey=Ns.getAlgorithmFromKey=void 0;var Ei;(function(e){e[e.NONE=-1]="NONE",e[e.ED25519=237]="ED25519",e[e.SECP256K1_PUB_X=2]="SECP256K1_PUB_X",e[e.SECP256K1_PUB_X_ODD_Y=3]="SECP256K1_PUB_X_ODD_Y",e[e.SECP256K1_PUB_XY=4]="SECP256K1_PUB_XY",e[e.SECP256K1_PRIVATE=0]="SECP256K1_PRIVATE"})(Ei||(Ei={}));var b6={[`private_${Ei.NONE}_32`]:"ecdsa-secp256k1",[`private_${Ei.SECP256K1_PRIVATE}_33`]:"ecdsa-secp256k1",[`private_${Ei.ED25519}_33`]:"ed25519",[`public_${Ei.ED25519}_33`]:"ed25519",[`public_${Ei.SECP256K1_PUB_X}_33`]:"ecdsa-secp256k1",[`public_${Ei.SECP256K1_PUB_X_ODD_Y}_33`]:"ecdsa-secp256k1",[`public_${Ei.SECP256K1_PUB_XY}_65`]:"ecdsa-secp256k1"};function HX(e){return{prefix:e.length<2?Ei.NONE:parseInt(e.slice(0,2),16),len:e.length/2}}function C6(e){return e===Ei.NONE?"None":`0x${e.toString(16).padStart(2,"0")}`}function VX(e){let n={algorithm:17,prefix:6};return Object.entries(b6).filter(([r])=>r.startsWith(e)).map(([r,i])=>{let[,o,a]=r.split("_"),s=i.padEnd(n.algorithm),c=C6(Number(o)).padEnd(n.prefix);return`${s} - Prefix: ${c} Length: ${a} bytes`}).join(` `)}function KX({key:e,type:t,prefix:n,len:r}){let i=VX(t),o=t==="private"?"[redacted]":e,a=t==="private"?"[redacted]":C6(n);return`invalid_key: Type: ${t} Key: ${o} Prefix: ${a} Length: ${r} bytes Acceptable ${t} formats are: ${i} `}function qA(e,t){let{prefix:n,len:r}=HX(e),i=t==="private"&&r===32?Ei.NONE:n,o=b6[`${t}_${i}_${r}`];if(!o)throw new Error(KX({key:e,type:t,len:r,prefix:i}));return o}Ns.getAlgorithmFromKey=qA;function zX(e){return qA(e,"public")}Ns.getAlgorithmFromPublicKey=zX;function jX(e){return qA(e,"private")}Ns.getAlgorithmFromPrivateKey=jX});var k6=q(my=>{"use strict";y();var E6=my&&my.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(my,"__esModule",{value:!0});var A6=(Or(),Ji(hA)),L0=(R0(),Ji(NA)),hy=We(),XX=UA(),WX=E6(N0()),S6=E6(py()),T6="00",GX={deriveKeypair(e,t){let n=(0,XX.derivePrivateKey)(e,t),r=T6+(0,hy.bytesToHex)((0,A6.numberToBytesBE)(n,32)),i=(0,hy.bytesToHex)(L0.secp256k1.getPublicKey((0,A6.numberToBytesBE)(n,32),!0));return{privateKey:r,publicKey:i}},sign(e,t){WX.default.ok(t.length===66&&t.startsWith(T6)||t.length===64);let n=t.length===66?t.slice(2):t;return(0,hy.bytesToHex)(L0.secp256k1.sign(S6.default.half(e),(0,hy.hexToBytes)(n),{lowS:!0,extraEntropy:void 0,format:"der",prehash:!1})).toUpperCase()},verify(e,t,n){let r=L0.secp256k1.Signature.fromHex(t,"der");return L0.secp256k1.verify(r.toBytes("compact"),S6.default.half(e),(0,hy.hexToBytes)(n),{prehash:!1})}};my.default=GX});function ZX(e,t,n,r){let i=e.sqr(n),o=e.sqr(r),a=e.add(e.mul(t.a,i),o),s=e.add(e.ONE,e.mul(t.d,e.mul(i,o)));return e.eql(a,s)}function I6(e,t={}){Ge(t,{},{},"extraOpts");let n=t,r=E0("edwards",e,n,n.FpFnLE),{Fp:i,Fn:o}=r,a=r.CURVE,{h:s}=a;if(ld(i,a.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ld(i,a.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ge(n,{},{uvRatio:"function",randomBytes:"function"});let c=n.randomBytes===void 0?pt:n.randomBytes,l=U0<{try{return{isValid:!0,value:i.sqrt(i.div(B,D))}}catch{return{isValid:!1,value:B0}}}:n.uvRatio;if(!ZX(i,a,a.Gx,a.Gy))throw new Error("bad curve params: generator point");let p=i.eql(a.a,i.neg(i.ONE))?B=>i.neg(B):i.eql(a.a,i.ONE)?B=>B:B=>i.mul(a.a,B);function h(B,D,P=!1){let U=P?F0:B0;return so("coordinate "+B,D,U,l),D}function g(B){if(!(B instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(a.Gx,a.Gy,i.ONE,i.mul(a.Gx,a.Gy));static ZERO=new w(i.ZERO,i.ONE,i.ONE,i.ZERO);static Fp=i;static Fn=o;X;Y;Z;T;constructor(D,P,U,F){this.X=h("x",D),this.Y=h("y",P),this.Z=h("z",U,!0),this.T=h("t",F),Object.freeze(this)}static CURVE(){return a}static fromAffine(D){if(D instanceof w)throw new Error("extended point not allowed");let{x:P,y:U}=D||{};return h("x",P),h("y",U),new w(P,U,i.ONE,i.mul(P,U))}static fromBytes(D,P=!1){let U=i.BYTES,{a:F,d:H}=a;D=kn(Ae(D,U,"point")),nr(P,"zip215");let b=kn(D),C=D[U-1];b[U-1]=C&-129;let v=En(b),S=P?l:i.ORDER;so("point.y",v,B0,S);let A=i.sqr(v),M=i.sub(A,i.ONE),$=i.sub(i.mulN(H,A),F),{isValid:R,value:O}=d(M,$);if(!R)throw new Error("bad point: invalid y coordinate");let j=u(O),N=(C&128)!==0;if(!P&&i.is0(O)&&N)throw new Error("bad point: x=0 and x_0=1");return N!==j&&(O=i.neg(O)),w.fromAffine({x:O,y:v})}static fromHex(D,P=!1){return w.fromBytes(Da(D),P)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(D=6,P=!0){return k.setWindowSize(this,D),P||this.multiply(U0),this}assertValidity(){let D=this,{a:P,d:U}=a;if(D.is0())throw new Error("bad point: ZERO");let{X:F,Y:H,Z:b,T:C}=D,v=i.sqr(F),S=i.sqr(H),A=i.sqr(b),M=i.sqr(A),$=i.mul(v,P),R=i.mul(i.add($,S),A),O=i.add(M,i.mul(U,i.mul(v,S)));if(!i.eql(R,O))throw new Error("bad point: equation left != right (1)");let j=i.mul(F,H),N=i.mul(b,C);if(!i.eql(j,N))throw new Error("bad point: equation left != right (2)")}equals(D){g(D);let{X:P,Y:U,Z:F}=this,{X:H,Y:b,Z:C}=D,v=i.mul(P,C),S=i.mul(H,F),A=i.mul(U,C),M=i.mul(b,F);return i.eql(v,S)&&i.eql(A,M)}is0(){return this.equals(w.ZERO)}negate(){return new w(i.neg(this.X),this.Y,this.Z,i.neg(this.T))}double(){let{X:D,Y:P,Z:U}=this,F=i.sqr(D),H=i.sqr(P),b=i.mul(i.sqr(U),U0),C=p(F),v=i.addN(D,P),S=i.sub(i.subN(i.sqr(v),F),H),A=i.addN(C,H),M=i.subN(A,b),$=i.subN(C,H),R=i.mul(S,M),O=i.mul(A,$),j=i.mul(S,$),N=i.mul(M,A);return new w(R,O,N,j)}add(D){g(D);let{d:P}=a,{X:U,Y:F,Z:H,T:b}=this,{X:C,Y:v,Z:S,T:A}=D,M=i.mul(U,C),$=i.mul(F,v),R=i.mul(i.mulN(b,P),A),O=i.mul(H,S),j=i.sub(i.subN(i.mulN(i.addN(U,F),i.addN(C,v)),M),$),N=i.subN(O,R),V=i.addN(O,R),G=i.sub($,p(M)),L=i.mul(j,N),X=i.mul(V,G),Z=i.mul(j,G),ee=i.mul(N,V);return new w(L,X,ee,Z)}subtract(D){return g(D),this.add(D.negate())}multiply(D){if(!o.isValidNot0(D))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:P,f:U}=k.mulSecret(this,D,s,T);return T([P,U])[0]}multiplyUnsafe(D){if(!o.isValid(D))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return D===B0?w.ZERO:this.is0()||D===F0?this:k.mulUnsafe(this,D,T)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return k.mulUnsafe(this,a.n).is0()}toAffine(D){let P=this,U=D;if(U!=null&&typeof U!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof U);let{X:F,Y:H,Z:b}=P,C=P.is0();U==null&&(U=C?i.create(_6):i.inv(b));let v=i.mul(F,U),S=i.mul(H,U),A=i.mul(b,U);if(C)return{x:i.ZERO,y:i.ONE};if(!i.eql(A,i.ONE))throw new Error("invZ was invalid");return{x:v,y:S}}clearCofactor(){return s===F0?this:s===U0?this.double():s===YX?this.double().double():s===_6?this.double().double().double():this.multiplyUnsafe(s)}toBytes(){let{x:D,y:P}=this.toAffine(),U=i.toBytes(P);return U[U.length-1]|=u(D)?128:0,U}toHex(){return Qr(this.toBytes())}toString(){return``}}let T=B=>T0(w,B),k=new dd(w,c);return k.bits>=6&&w.BASE.precompute(6),Object.freeze(w.prototype),Object.freeze(w),w}function P6(e,t,n={}){if(Ti(e),typeof t!="function")throw new Error('"hash" function param is required');let r=t,i=n;Ge(i,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:o}=i,{BASE:a,Fp:s,Fn:c}=e,l=r.outputLen,u=2*s.BYTES;if(l!==void 0&&(Pt(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=i.randomBytes===void 0?pt:i.randomBytes,p=i.toMontgomery,h=i.toMontgomerySecret,g=i.adjustScalarBytes===void 0?$=>$:i.adjustScalarBytes,w=i.domain===void 0?($,R,O)=>{if(nr(O,"phflag"),R.length||O)throw new Error("Contexts/pre-hash are not supported");return $}:i.domain;function T($){return c.create(En($))}function k($){let R=C.secretKey;Ae($,C.secretKey,"secretKey");let O=Ae(r($),2*R,"hashedSecretKey"),j=g(O.slice(0,R)),N=O.slice(R,2*R),V=T(j);return{head:j,prefix:N,scalar:V}}function B($){let{head:R,prefix:O,scalar:j}=k($),N=a.multiply(j),V=N.toBytes();return{head:R,prefix:O,scalar:j,point:N,pointBytes:V}}function D($){return B($).pointBytes}function P($=Uint8Array.of(),...R){let O=Fe(...R);return T(r(w(O,Ae($,void 0,"context"),!!o)))}function U($,R,O={}){Ge(O,{},{},"options"),$=kn(Ae($,void 0,"message")),o&&($=o($));let{prefix:j,scalar:N,pointBytes:V}=B(R),G=P(O.context,j,$),L=a.multiply(G).toBytes(),X=P(O.context,L,V,$),Z=c.create(G+X*N);if(!c.isValid(Z))throw new Error("sign failed: invalid s");let ee=Fe(L,c.toBytes(Z));return Ae(ee,C.signature,"result")}let F={zip215:i.zip215};function H($,R,O,j=F){Ge(j);let{context:N}=j,V=j.zip215===void 0?!!F.zip215:j.zip215,G=C.signature;$=Ae($,G,"signature"),R=Ae(R,void 0,"message"),O=Ae(O,C.publicKey,"publicKey"),V!==void 0&&nr(V,"zip215"),o&&(R=o(R));let L=G/2,X=$.subarray(0,L),Z=En($.subarray(L,G)),ee,J,ie;try{ee=e.fromBytes(O,V),J=e.fromBytes(X,V),ie=a.multiplyUnsafe(Z)}catch{return!1}if(!V&&ee.isSmallOrder())return!1;let se=P(N,X,O,R);return J.add(ee.multiplyUnsafe(se)).subtract(ie).clearCofactor().is0()}let b=s.BYTES,C={secretKey:b,publicKey:b,signature:2*b,seed:b};function v($){return $=$===void 0?d(C.seed):$,Ae($,C.seed,"seed")}function S($){return ei($)&&$.length===C.secretKey}function A($,R){try{return!!e.fromBytes($,R===void 0?F.zip215:R)}catch{return!1}}let M={getExtendedPublicKey:B,randomSecretKey:v,isValidSecretKey:S,isValidPublicKey:A,toMontgomery($){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(e.fromBytes($))},toMontgomerySecret($){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h($)}};return Object.freeze(C),Object.freeze(M),Object.freeze({keygen:Os(v,D),getPublicKey:D,sign:U,verify:H,utils:M,Point:e,lengths:C})}var B0,F0,U0,YX,_6,$0,x6=Te(()=>{y();Or();nl();co();B0=BigInt(0),F0=BigInt(1),U0=BigInt(2),YX=BigInt(4),_6=BigInt(8);$0=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){v0()}static fromHex(t){v0()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Qr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}}});function M6(e,t){return e+t-(t>>ki<{let o=r+i,s=((t+i-r)*n+r)%e;return{x_2:s,x_3:o-s}}}function QX(e){return Ge(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...e})}function O6(e){let t=QX(e),{P:n,type:r,adjustScalarBytes:i,powPminus2:o,randomBytes:a}=t,s=t.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");let l=a===void 0?pt:a,u=c?255:448,d=JX(n),p=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),w=c?q0**BigInt(254):q0**BigInt(447),T=c?BigInt(8)*(q0**BigInt(251)-ki):BigInt(4)*(q0**BigInt(445)-ki),k=w+T+ki,B=O=>yt(O,n),D=P(h);function P(O){return ad(B(O),p)}function U(O){let j=kn(Ae(O,p,"uCoordinate"));return c&&(j[31]&=127),B(En(j))}function F(O){return En(i(kn(Ae(O,p,"scalar"))))}let H=new Set(c?[sl,ki,n-ki,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[sl,ki,n-ki]);function b(O,j){let N=U(j);if(H.has(N))throw new Error("invalid private or public key received");let V=A(N,F(O));if(V===sl)throw new Error("invalid private or public key received");return P(V)}function C(O){if(s===void 0)return b(O,D);let j=F(O);so("scalar",j,w,k);let N=B(s(j));if(N===sl)throw new Error("invalid private or public key received");return P(N)}let v=C,S=b;function A(O,j){so("u",O,sl,n),so("scalar",j,w,k);let N=j,V=O,G=ki,L=sl,X=O,Z=ki,ee=N^N>>ki;for(let se=BigInt(u-1);se>=sl;se--){let me=M6(n,ee>>se);({x_2:G,x_3:X}=d(me,G,X)),{x_2:L,x_3:Z}=d(me,L,Z);let pe=G+L,Pe=B(pe*pe),Ee=G-L,Ne=B(Ee*Ee),De=Pe-Ne,qe=X+Z,xe=X-Z,vt=B(xe*pe),Kr=B(qe*Ee),Xi=vt+Kr,Sr=vt-Kr;X=B(Xi*Xi),Z=B(V*B(Sr*Sr)),G=B(Pe*Ne),L=B(De*(Pe+B(g*De)))}let J=M6(n,N);({x_2:G,x_3:X}=d(J,G,X)),{x_2:L,x_3:Z}=d(J,L,Z);let ie=o(L);return B(G*ie)}let M={secretKey:p,publicKey:p,seed:p},$=O=>(O=O===void 0?l(p):O,Ae(O,M.seed,"seed"),O),R={randomSecretKey:$};return Object.freeze(M),Object.freeze(R),Object.freeze({keygen:Os($,v),getSharedSecret:S,getPublicKey:v,scalarMult:b,scalarMultBase:C,utils:R,GuBytes:D.slice(),lengths:M})}var sl,ki,q0,D6=Te(()=>{y();Or();nl();co();sl=BigInt(0),ki=BigInt(1),q0=BigInt(2)});function R6(e){Ge(e,{name:"string",hash:"function",hashToScalar:"function",hashToGroup:"function"}),Ti(e.Point);let{name:t,Point:n,hash:r,hashToGroup:i,hashToScalar:o}=e,{Fn:a}=n,s=N=>S0(N,a.ORDER),c=(N,V)=>i(N,{DST:Fe(Vn("HashToGroup-"),V)}),l=(N,V)=>o(N,{DST:Fe(eW,V)}),u=(N=pt)=>{if(typeof N!="function")throw new TypeError('"rng" expected function, got type='+typeof N);let V=Ra(N(xs(a.ORDER)),a.ORDER,a.isLE);return a.isLE?En(V):un(V)},d=(N,V)=>Ms(n,N,V),p=N=>Fe(Vn("OPRFV1-"),new Uint8Array([N]),Vn("-"+t)),h=p(0),g=p(1),w=p(2);function T(...N){let V=[];for(let G of N)typeof G=="number"?V.push(_s(G,2)):typeof G=="string"?V.push(Vn(G)):(Ae(G),V.push(_s(G.length,2),G));return Fe(...V)}let k=(N,V)=>{if(Ae(V,void 0,N),V.length>65535)throw new Error(`"${N}" expected Uint8Array of length <= 65535, got length=${V.length}`);return V},B=(...N)=>r(T(...N,"Finalize"));function D(N,V,G,L){let X=N.toBytes(),Z=r(T(X,Fe(Vn("Seed-"),L))),ee=[];for(let J=0;Jpe.toBytes());return l(T(ee,J,ie,se,me,"Challenge"),Z)}function H(N,V,G,L,X,Z){let{M:ee,Z:J}=U(V,G,L,X,N),ie=u(Z),se=n.BASE.multiply(ie),me=ee.multiply(ie),pe=F(G,ee,J,se,me,N),Pe=a.sub(ie,a.mul(pe,V));return Fe(...[pe,Pe].map(Ee=>a.toBytes(Ee)))}function b(N,V,G,L,X){Ae(X,2*a.BYTES);let{M:Z,Z:ee}=P(V,G,L,N),[J,ie]=[X.subarray(0,a.BYTES),X.subarray(a.BYTES)].map(Pe=>a.fromBytes(Pe)),se=d([n.BASE,V],[ie,J]),me=d([Z,ee],[ie,J]),pe=F(V,Z,ee,se,me,N);if(!a.eql(J,pe))throw new Error("proof verification failed")}function C(){let N=u(),V=n.BASE.multiply(N);return{secretKey:a.toBytes(N),publicKey:V.toBytes()}}function v(N,V,G){Ae(V,32,"seed"),G=k("keyInfo",G);let L=Fe(Vn("DeriveKeyPair"),N),X=Fe(V,T(G),Uint8Array.of(0));for(let Z=0;Z<=255;Z++){X[X.length-1]=Z;let ee=o(X,{DST:L});if(!a.is0(ee))return{secretKey:a.toBytes(ee),publicKey:n.BASE.multiply(ee).toBytes()}}throw new Error("Cannot derive key")}let S=(N,V)=>{let G=n.fromBytes(V);if(G.equals(n.ZERO))throw new Error(N+" point at infinity");return G};function A(N,V,G=pt){V=k("input",V);let L=u(G),X=c(V,N);if(X.equals(n.ZERO))throw new Error("Input point at infinity");let Z=X.multiply(L);return{blind:a.toBytes(L),blinded:Z.toBytes()}}function M(N,V,G){G=k("input",G);let L=a.fromBytes(V),X=c(G,N);if(X.equals(n.ZERO))throw new Error("Input point at infinity");let Z=X.multiply(L).toBytes();return B(G,Z)}let $=Object.freeze({generateKeyPair:C,deriveKeyPair:(N,V)=>v(h,N,V),blind:(N,V=pt)=>A(h,N,V),blindEvaluate(N,V){let G=a.fromBytes(N);return S("blinded",V).multiply(G).toBytes()},finalize(N,V,G){N=k("input",N);let L=a.fromBytes(V),Z=S("evaluated",G).multiply(a.inv(L)).toBytes();return B(N,Z)},evaluate:(N,V)=>M(h,N,V)}),R=Object.freeze({generateKeyPair:C,deriveKeyPair:(N,V)=>v(g,N,V),blind:(N,V=pt)=>A(g,N,V),blindEvaluateBatch(N,V,G,L=pt){if(!Array.isArray(G))throw new Error("expected array");let X=a.fromBytes(N),Z=S("public key",V),ee=G.map(se=>S("blinded",se)),J=ee.map(se=>se.multiply(X)),ie=H(g,X,Z,ee,J,L);return{evaluated:J.map(se=>se.toBytes()),proof:ie}},blindEvaluate(N,V,G,L=pt){let X=this.blindEvaluateBatch(N,V,[G],L);return{evaluated:X.evaluated[0],proof:X.proof}},finalizeBatch(N,V,G){if(!Array.isArray(N))throw new Error("expected array");let L=S("public key",V),X=N.map(ee=>S("blinded",ee.blinded)),Z=N.map(ee=>S("evaluated",ee.evaluated));return b(g,L,X,Z,G),N.map((ee,J)=>{let ie=k("input",ee.input),se=a.fromBytes(ee.blind),me=Z[J].multiply(a.inv(se)).toBytes();return B(ie,me)})},finalize(N,V,G,L,X,Z){return this.finalizeBatch([{input:N,blind:V,evaluated:G,blinded:L}],X,Z)[0]},evaluate:(N,V)=>M(g,N,V)}),j={name:t,oprf:$,voprf:R,poprf:N=>{N=kn(k("info",N));let V=l(T("Info",N),w),G=n.BASE.multiply(V);return Object.freeze({generateKeyPair:C,deriveKeyPair:(L,X)=>v(w,L,X),blind(L,X,Z=pt){L=k("input",L);let ee=S("public key",X),J=G.add(ee);if(J.equals(n.ZERO))throw new Error("tweakedKey point at infinity");let ie=u(Z),se=c(L,w);if(se.equals(n.ZERO))throw new Error("Input point at infinity");let me=se.multiply(ie);return{blind:a.toBytes(ie),blinded:me.toBytes(),tweakedKey:J.toBytes()}},blindEvaluateBatch(L,X,Z=pt){if(!Array.isArray(X))throw new Error("expected array");let ee=a.fromBytes(L),J=a.add(ee,V),ie=s(J),se=X.map(Ee=>S("blinded",Ee)),me=se.map(Ee=>Ee.multiply(ie)),pe=n.BASE.multiply(J),Pe=H(w,J,pe,me,se,Z);return{evaluated:me.map(Ee=>Ee.toBytes()),proof:Pe}},blindEvaluate(L,X,Z=pt){let ee=this.blindEvaluateBatch(L,[X],Z);return{evaluated:ee.evaluated[0],proof:ee.proof}},finalizeBatch(L,X,Z){if(!Array.isArray(L))throw new Error("expected array");let ee=L.map(ie=>k("input",ie.input)),J=L.map(ie=>S("evaluated",ie.evaluated));return b(w,S("tweakedKey",Z),J,L.map(ie=>S("blinded",ie.blinded)),X),L.map((ie,se)=>{let me=a.fromBytes(ie.blind),pe=J[se].multiply(a.inv(me)).toBytes();return B(ee[se],N,pe)})},finalize(L,X,Z,ee,J,ie){return this.finalizeBatch([{input:L,blind:X,evaluated:Z,blinded:ee}],J,ie)[0]},evaluate(L,X){X=k("input",X);let Z=a.fromBytes(L),ee=c(X,w);if(ee.equals(n.ZERO))throw new Error("Input point at infinity");let J=a.add(Z,V),ie=s(J),se=ee.multiply(ie).toBytes();return B(X,N,se)}})},__tests:Object.freeze({Fn:a,invertSecret:s})};return Object.freeze(j)}var eW,N6=Te(()=>{y();Or();nl();P0();co();eW=Vn(ly)});var j6={};Tr(j6,{ED25519_TORSION_SUBGROUP:()=>vW,_map_to_curve_elligator2_curve25519:()=>z6,ed25519:()=>Kn,ed25519_FROST:()=>aW,ed25519_hasher:()=>fW,ed25519ctx:()=>iW,ed25519ph:()=>oW,ristretto255:()=>wW,ristretto255_FROST:()=>CW,ristretto255_hasher:()=>V0,ristretto255_oprf:()=>bW,x25519:()=>sW});function jA(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=yd,s=e*e%o*e%o,c=Vt(s,H0,o)*s%o,l=Vt(c,fo,o)*e%o,u=Vt(l,tW,o)*l%o,d=Vt(u,t,o)*u%o,p=Vt(d,n,o)*d%o,h=Vt(p,r,o)*p%o,g=Vt(h,i,o)*h%o,w=Vt(g,i,o)*h%o,T=Vt(w,t,o)*u%o;return{pow_p_5_8:Vt(T,H0,o)*e%o,b2:s}}function XA(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function WA(e,t){let n=yd,r=yt(t*t*t,n),i=yt(r*r*t,n),o=jA(e*i).pow_p_5_8,a=yt(e*r*o,n),s=yt(t*a*a,n),c=a,l=yt(a*HA,n),u=s===e,d=s===yt(-e,n),p=s===yt(-e*HA,n);return u&&(a=c),(d||p)&&(a=l),L_(a,n)&&(a=yt(-a,n)),{isValid:u||d,value:a}}function nW(e){let{y:t}=e;return ne.toBytes(ne.div(fo+t,fo-t))}function rW(e){let t=ni.Fp.BYTES;return St(e,t),XA(tr(e.subarray(0,t))).subarray(0,t)}function K6(e,t,n){if(t.length>255)throw new Error("Context is too big");return Io(Vn("SigEd25519 no Ed25519 collisions"),new Uint8Array([n?1:0,t.length]),t,e)}function GA(e){return P6(ni,tr,Object.assign({adjustScalarBytes:XA,toMontgomery:nW,toMontgomerySecret:rW,zip215:!0},e))}function z6(e){let t=ne.sqr(e);t=ne.mul(t,H0);let n=ne.add(t,ne.ONE),r=ne.neg(F6),i=ne.sqr(n),o=ne.mul(i,n),a=ne.mul(t,F6);a=ne.mul(a,r),a=ne.add(a,i),a=ne.mul(a,r);let s=ne.sqr(o);i=ne.sqr(s),s=ne.mul(s,o),s=ne.mul(s,a),i=ne.mul(i,s);let c=jA(i).pow_p_5_8;c=ne.mul(c,s);let l=ne.mul(c,B6);i=ne.sqr(c),i=ne.mul(i,o);let u=ne.eql(i,a),d=ne.cmov(l,c,u),p=ne.mul(r,t),h=ne.mul(c,e);h=ne.mul(h,lW);let g=ne.mul(h,B6),w=ne.mul(a,t);i=ne.sqr(h),i=ne.mul(i,o);let T=ne.eql(i,w),k=ne.cmov(g,h,T);i=ne.sqr(d),i=ne.mul(i,o);let B=ne.eql(i,a),D=ne.cmov(p,r,B),P=ne.cmov(k,d,B),U=ne.isOdd(P);return P=ne.cmov(P,ne.neg(P),B!==U),{xMn:D,xMd:n,yMn:P,yMd:fo}}function dW(e){let{xMn:t,xMd:n,yMn:r,yMd:i}=z6(e),o=ne.mul(t,i);o=ne.mul(o,uW);let a=ne.mul(n,r),s=ne.sub(t,n),c=ne.add(t,n),l=ne.mul(a,c),u=ne.eql(l,ne.ZERO);o=ne.cmov(o,ne.ZERO,u),a=ne.cmov(a,ne.ONE,u),s=ne.cmov(s,ne.ONE,u),c=ne.cmov(c,ne.ONE,u);let[d,p]=Ps(ne,[a,c],!0);return{x:ne.mul(o,d),y:ne.mul(s,p)}}function $6(e){let{d:t}=zA,n=ne.mul(ne.mulN(VA,e),e),r=ne.mul(ne.addN(n,fo),hW),i=BigInt(-1),o=ne.mul(ne.subN(i,ne.mulN(t,n)),ne.add(n,t)),{isValid:a,value:s}=WA(r,o),c=ne.mul(s,e);ne.isOdd(c)||(c=ne.neg(c)),a||(s=c),a||(i=n);let l=ne.sub(ne.mulN(ne.mulN(i,ne.subN(n,fo)),mW),o),u=ne.sqrN(s),d=ne.mul(ne.addN(s,s),o),p=ne.mul(l,pW),h=ne.sub(fo,u),g=ne.add(fo,u);return new ni(ne.mul(d,g),ne.mul(h,p),ne.mul(p,g),ne.mul(d,h))}var L6,fo,H0,q6,tW,H6,yd,zA,HA,ni,ne,V6,Kn,iW,oW,aW,sW,cW,lW,B6,F6,uW,fW,VA,pW,yW,hW,mW,U6,gW,KA,uo,wW,V0,bW,CW,vW,qo=Te(()=>{y();Bo();Hn();x6();kA();P0();co();D6();N6();Or();L6=BigInt(0),fo=BigInt(1),H0=BigInt(2),q6=BigInt(3),tW=BigInt(5),H6=BigInt(8),yd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),zA={p:yd,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:H6,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};HA=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");ni=I6(zA,{uvRatio:WA}),ne=ni.Fp;V6=ni.Fn;Kn=GA({}),iW=GA({domain:K6}),oW=GA({domain:K6,prehash:tr}),aW=fd({name:"FROST-ED25519-SHA512-v1",Point:ni,validatePoint:e=>{if(e.assertValidity(),!e.isTorsionFree())throw new Error("bad point: not torsion-free")},hash:tr,H2:""}),sW=(()=>{let e=yd,t=n=>{let{pow_p_5_8:r,b2:i}=jA(n);return yt(Vt(r,q6,e)*i,e)};return O6({P:e,type:"x25519",powPminus2:t,adjustScalarBytes:XA,scalarMultBase:n=>{let r=yt(n,ni.Fn.ORDER);if(r===L6)return L6;let i=ni.BASE.multiply(r);return yt((i.Z+i.Y)*t(yt(i.Z-i.Y,e)),e)}})})(),cW=(yd+q6)/H6,lW=ne.pow(H0,cW),B6=ne.sqrt(ne.neg(ne.ONE)),F6=BigInt(486662);uW=B_(ne,ne.neg(BigInt(486664)));fW=I0(ni,e=>dW(e[0]),{DST:"edwards25519_XMD:SHA-512_ELL2_RO_",encodeDST:"edwards25519_XMD:SHA-512_ELL2_NU_",p:yd,m:1,k:128,expand:"xmd",hash:tr}),VA=HA,pW=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),yW=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),hW=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),mW=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),U6=e=>WA(fo,e),gW=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),KA=e=>ne.create(En(e)&gW);uo=class e extends $0{static BASE=new e(ni.BASE);static ZERO=new e(ni.ZERO);static Fp=ne;static Fn=V6;constructor(t){super(t)}static fromAffine(t){return new e(ni.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static fromBytes(t){St(t,32);let{a:n,d:r}=zA,i=KA(t);if(!sd(ne.toBytes(i),t)||ne.isOdd(i))throw new Error("invalid ristretto255 encoding 1");let o=ne.sqr(i),a=ne.add(fo,ne.mulN(n,o)),s=ne.sub(fo,ne.mulN(n,o)),c=ne.sqr(a),l=ne.sqr(s),u=ne.sub(ne.mulN(ne.mulN(n,r),c),l),{isValid:d,value:p}=U6(ne.mul(u,l)),h=ne.mul(p,s),g=ne.mul(ne.mulN(p,h),u),w=ne.mul(ne.addN(i,i),h);ne.isOdd(w)&&(w=ne.neg(w));let T=ne.mul(a,g),k=ne.mul(w,T);if(!d||ne.isOdd(k)||ne.is0(T))throw new Error("invalid ristretto255 encoding 2");return new e(new ni(w,T,ne.ONE,k))}static fromHex(t){return e.fromBytes(_c(t))}toBytes(){let{X:t,Y:n,Z:r,T:i}=this.ep,o=ne.mul(ne.add(r,n),ne.sub(r,n)),a=ne.mul(t,n),s=ne.sqr(a),{value:c}=U6(ne.mul(o,s)),l=ne.mul(c,o),u=ne.mul(c,a),d=ne.mul(ne.mulN(l,u),i),p;if(ne.isOdd(ne.mul(i,d))){let g=ne.mul(n,VA),w=ne.mul(t,VA);t=g,n=w,p=ne.mul(l,yW)}else p=u;ne.isOdd(ne.mul(t,d))&&(n=ne.neg(n));let h=ne.mul(ne.subN(r,n),p);return ne.isOdd(h)&&(h=ne.neg(h)),ne.toBytes(h)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:i,Y:o}=t.ep,a=ne.eql(ne.mul(n,o),ne.mul(r,i)),s=ne.eql(ne.mul(r,o),ne.mul(n,i));return a||s}is0(){return this.equals(e.ZERO)}},wW=(Object.freeze(uo.BASE),Object.freeze(uo.ZERO),Object.freeze(uo.prototype),Object.freeze(uo),Object.freeze({Point:uo})),V0=Object.freeze({Point:uo,hashToCurve(e,t){let n=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,r=_0(e,n,64,tr);return V0.deriveToCurve(r)},hashToScalar(e,t){let n=t?.DST===void 0?ly:t.DST,r=_0(e,n,64,tr);return V6.create(En(r))},deriveToCurve(e){St(e,64);let t=KA(e.subarray(0,32)),n=$6(t),r=KA(e.subarray(32,64)),i=$6(r);return new uo(n.add(i))}}),bW=R6({name:"ristretto255-SHA512",Point:uo,hash:tr,hashToGroup:V0.hashToCurve,hashToScalar:V0.hashToScalar}),CW=fd({name:"FROST-RISTRETTO255-SHA512-v1",Point:uo,validatePoint:e=>{e.assertValidity()},hash:tr}),vW=Object.freeze(["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"])});var G6=q(gy=>{"use strict";y();var W6=gy&&gy.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(gy,"__esModule",{value:!0});var YA=(qo(),Ji(j6)),hd=We(),ZA=W6(N0()),AW=W6(py()),X6="ED",SW={deriveKeypair(e){let t=AW.default.half(e),n=X6+(0,hd.bytesToHex)(t),r=X6+(0,hd.bytesToHex)(YA.ed25519.getPublicKey(t));return{privateKey:n,publicKey:r}},sign(e,t){return ZA.default.ok(e instanceof Uint8Array,"message must be array of octets"),ZA.default.ok(t.length===66,"private key must be 33 bytes including prefix"),(0,hd.bytesToHex)(YA.ed25519.sign(e,(0,hd.hexToBytes)(t.slice(2))))},verify(e,t,n){return ZA.default.ok(n.length===66,"public key must be 33 bytes including prefix"),YA.ed25519.verify((0,hd.hexToBytes)(t),e,(0,hd.hexToBytes)(n.slice(2)),{zip215:!1})}};gy.default=SW});var _i=q(Nn=>{"use strict";y();var K0=Nn&&Nn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Nn,"__esModule",{value:!0});Nn.decodeSeed=Nn.deriveNodeAddress=Nn.deriveAddress=Nn.verify=Nn.sign=Nn.deriveKeypair=Nn.generateSeed=void 0;var wy=lr();Object.defineProperty(Nn,"decodeSeed",{enumerable:!0,get:function(){return wy.decodeSeed}});var TW=y_(),EW=Pv(),z0=We(),kW=UA(),_W=K0(py()),JA=K0(N0()),Y6=v6(),IW=K0(k6()),PW=K0(G6()),QA=16;function xW(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1&&Object.prototype.toString.call(e)==="[object Uint8Array]"}function e3(e){return{"ecdsa-secp256k1":IW.default,ed25519:PW.default}[e]}function MW(e={}){let t=["ecdsa-secp256k1","ed25519"];JA.default.ok(!e.algorithm||t.includes(e.algorithm),`Unsupported algorithm: ${e.algorithm}. Use one of: ${t.join(", ")}`);let n=e.entropy;JA.default.ok(n===void 0||xW(n),"entropy must be a Uint8Array"),JA.default.ok(n===void 0||n.length===QA,`entropy must be exactly ${QA} bytes`);let r=n??(0,z0.randomBytes)(QA),i=e.algorithm==="ecdsa-secp256k1"?"secp256k1":"ed25519";return(0,wy.encodeSeed)(r,i)}Nn.generateSeed=MW;function OW(e,t){var n;let r=(0,wy.decodeSeed)(e),o=((n=t?.algorithm)!==null&&n!==void 0?n:r.type)==="ed25519"?"ed25519":"ecdsa-secp256k1",a=e3(o),s=a.deriveKeypair(r.bytes,t),c=_W.default.half("This test message should verify."),l=a.sign(c,s.privateKey);if(!a.verify(c,l,s.publicKey))throw new Error("derived keypair did not generate verifiable signature");return s}Nn.deriveKeypair=OW;function DW(e,t){let n=(0,Y6.getAlgorithmFromPrivateKey)(t);return e3(n).sign((0,z0.hexToBytes)(e),t)}Nn.sign=DW;function RW(e,t,n){let r=(0,Y6.getAlgorithmFromPublicKey)(n);return e3(r).verify((0,z0.hexToBytes)(e),t,n)}Nn.verify=RW;function NW(e){return(0,TW.ripemd160)((0,EW.sha256)(e))}function Z6(e){return(0,wy.encodeAccountID)(NW(e))}function LW(e){return Z6((0,z0.hexToBytes)(e))}Nn.deriveAddress=LW;function BW(e){let t=(0,wy.decodeNodePublic)(e),n=(0,kW.accountPublicFromPublicGenerator)(t);return Z6(n)}Nn.deriveNodeAddress=BW});var J6=q(Ls=>{"use strict";y();Object.defineProperty(Ls,"__esModule",{value:!0});Ls.deriveXAddress=Ls.deriveAddress=Ls.deriveKeypair=void 0;var FW=lr(),t3=_i();Object.defineProperty(Ls,"deriveKeypair",{enumerable:!0,get:function(){return t3.deriveKeypair}});Object.defineProperty(Ls,"deriveAddress",{enumerable:!0,get:function(){return t3.deriveAddress}});function UW(e){let t=(0,t3.deriveAddress)(e.publicKey);return(0,FW.classicAddressToXAddress)(t,e.tag,e.test)}Ls.deriveXAddress=UW});var n3=q(md=>{"use strict";y();Object.defineProperty(md,"__esModule",{value:!0});md.omitBy=md.groupBy=void 0;function $W(e,t){function n(r,i,o,a){let s=t(i,o,a)||0,c=r[s]||[];return c.push(i),r[s]=c,r}return e.reduce(n,{})}md.groupBy=$W;function qW(e,t){return Object.keys(e).filter(i=>!t(e[i],i)).reduce((i,o)=>(i[o]=e[o],i),{})}md.omitBy=qW});var Cy=q(Bs=>{"use strict";y();var HW=Bs&&Bs.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Bs,"__esModule",{value:!0});Bs.xrpToDrops=Bs.dropsToXrp=void 0;var by=HW(Sn()),cl=fe(),Q6=1e6,VW=6,r3=10,e9=/^-?[0-9.]+$/u;function KW(e){let t;try{t=new by.default(e).toString(r3)}catch{throw new cl.ValidationError(`dropsToXrp: invalid value '${typeof e=="string"?e:JSON.stringify(e)}', should be a BigNumber or string-encoded number.`)}if(t.includes("."))throw new cl.ValidationError(`dropsToXrp: value '${t}' has too many decimal places.`);if(!e9.exec(t))throw new cl.ValidationError(`dropsToXrp: failed sanity check - value '${t}', does not match (^-?[0-9]+$).`);return new by.default(t).dividedBy(Q6).toNumber()}Bs.dropsToXrp=KW;function zW(e){let t;try{t=new by.default(e).toString(r3)}catch{throw new cl.ValidationError(`xrpToDrops: invalid value '${typeof e=="string"?e:JSON.stringify(e)}', should be a BigNumber or string-encoded number.`)}if(!e9.exec(t))throw new cl.ValidationError(`xrpToDrops: failed sanity check - value '${t}', does not match (^-?[0-9.]+$).`);let n=t.split(".");if(n.length>2)throw new cl.ValidationError(`xrpToDrops: failed sanity check - value '${t}' has too many decimal points.`);if((n[1]||"0").length>VW)throw new cl.ValidationError(`xrpToDrops: value '${t}' has too many decimal places.`);return new by.default(t).times(Q6).integerValue(by.default.ROUND_FLOOR).toString(r3)}Bs.xrpToDrops=zW});var n9=q(vy=>{"use strict";y();var jW=vy&&vy.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(vy,"__esModule",{value:!0});var o3=jW(Sn()),XW=n3(),WW=Cy();function GW(e){let t=Object.keys(e)[0],n=e[t];return Object.assign(Object.assign({},n),{NodeType:t,LedgerEntryType:n.LedgerEntryType,LedgerIndex:n.LedgerIndex,NewFields:n.NewFields,FinalFields:n.FinalFields,PreviousFields:n.PreviousFields})}function YW(e){return e.AffectedNodes.length===0?[]:e.AffectedNodes.map(GW)}function ZW(e){let t=(0,XW.groupBy)(e,n=>n.account);return Object.entries(t).map(([n,r])=>({account:n,balances:r.map(i=>i.balance)}))}function i3(e){return typeof e=="string"?new o3.default(e):new o3.default(e.value)}function t9(e){var t,n,r;let i=null;return!((t=e.NewFields)===null||t===void 0)&&t.Balance?i=i3(e.NewFields.Balance):!((n=e.PreviousFields)===null||n===void 0)&&n.Balance&&(!((r=e.FinalFields)===null||r===void 0)&&r.Balance)&&(i=i3(e.FinalFields.Balance).minus(i3(e.PreviousFields.Balance))),i===null||i.isZero()?null:i}function JW(e){var t,n,r;let i=t9(e);return i===null?null:{account:(n=(t=e.FinalFields)===null||t===void 0?void 0:t.Account)!==null&&n!==void 0?n:(r=e.NewFields)===null||r===void 0?void 0:r.Account,balance:{currency:"XRP",value:(0,WW.dropsToXrp)(i).toString()}}}function QW(e){let t=new o3.default(e.balance.value).negated();return{account:e.balance.issuer,balance:{issuer:e.account,currency:e.balance.currency,value:t.toString()}}}function eG(e){var t,n,r;let i=t9(e);if(i===null)return null;let o=(t=e.NewFields)!==null&&t!==void 0?t:e.FinalFields,a={account:(n=o?.LowLimit)===null||n===void 0?void 0:n.issuer,balance:{issuer:(r=o?.HighLimit)===null||r===void 0?void 0:r.issuer,currency:(o?.Balance).currency,value:i.toString()}};return[a,QW(a)]}function tG(e){let t=YW(e).map(n=>{if(n.LedgerEntryType==="AccountRoot"){let r=JW(n);return r==null?[]:[r]}if(n.LedgerEntryType==="RippleState"){let r=eG(n);return r??[]}return[]});return ZW(t.flat())}vy.default=tG});var j0=q(Fs=>{"use strict";y();Object.defineProperty(Fs,"__esModule",{value:!0});Fs.isDeletedNode=Fs.isModifiedNode=Fs.isCreatedNode=void 0;function nG(e){return Object.prototype.hasOwnProperty.call(e,"CreatedNode")}Fs.isCreatedNode=nG;function rG(e){return Object.prototype.hasOwnProperty.call(e,"ModifiedNode")}Fs.isModifiedNode=rG;function iG(e){return Object.prototype.hasOwnProperty.call(e,"DeletedNode")}Fs.isDeletedNode=iG});var r9=q(s3=>{"use strict";y();Object.defineProperty(s3,"__esModule",{value:!0});var oG=Qn(),a3=j0();function aG(e){return typeof e=="string"?(0,oG.decode)(e):e}function sG(e){if(typeof e!="string"&&e?.AffectedNodes===void 0)throw new TypeError(`Unable to parse the parameter given to getNFTokenID. 'meta' must be the metadata from an NFTokenMint transaction. Received ${JSON.stringify(e)} instead.`);let n=aG(e).AffectedNodes.filter(a=>{var s;return(0,a3.isCreatedNode)(a)?a.CreatedNode.LedgerEntryType==="NFTokenPage":(0,a3.isModifiedNode)(a)?a.ModifiedNode.LedgerEntryType==="NFTokenPage"&&!!(!((s=a.ModifiedNode.PreviousFields)===null||s===void 0)&&s.NFTokens):!1}),r=new Set(n.flatMap(a=>{var s;return((0,a3.isModifiedNode)(a)?(s=a.ModifiedNode.PreviousFields)===null||s===void 0?void 0:s.NFTokens:[]).map(l=>l.NFToken.NFTokenID)}).filter(a=>!!a));return n.flatMap(a=>{var s,c,l,u,d,p;return((p=(l=(c=(s=a.ModifiedNode)===null||s===void 0?void 0:s.FinalFields)===null||c===void 0?void 0:c.NFTokens)!==null&&l!==void 0?l:(d=(u=a.CreatedNode)===null||u===void 0?void 0:u.NewFields)===null||d===void 0?void 0:d.NFTokens)!==null&&p!==void 0?p:[]).map(h=>h.NFToken.NFTokenID)}).filter(a=>!!a).find(a=>!r.has(a))}s3.default=sG});var i9=q(c3=>{"use strict";y();Object.defineProperty(c3,"__esModule",{value:!0});var cG=Qn(),lG=j0();function uG(e){return typeof e=="string"?(0,cG.decode)(e):e}function dG(e){if(typeof e!="string"&&e?.AffectedNodes===void 0)throw new TypeError(`Unable to parse the parameter given to getXChainClaimID. 'meta' must be the metadata from an XChainCreateClaimID transaction. Received ${JSON.stringify(e)} instead.`);let t=uG(e);if(!t.TransactionResult)throw new TypeError("Cannot get XChainClaimID from un-validated transaction");return t.TransactionResult!=="tesSUCCESS"?void 0:t.AffectedNodes.find(r=>(0,lG.isCreatedNode)(r)&&r.CreatedNode.LedgerEntryType==="XChainOwnedClaimID").CreatedNode.NewFields.XChainClaimID}c3.default=dG});var Ay=q(u3=>{"use strict";y();Object.defineProperty(u3,"__esModule",{value:!0});var l3;(function(e){e[e.TRANSACTION_ID=1415073280]="TRANSACTION_ID",e[e.TRANSACTION_NODE=1397638144]="TRANSACTION_NODE",e[e.INNER_NODE=1296649728]="INNER_NODE",e[e.LEAF_NODE=1296846336]="LEAF_NODE",e[e.TRANSACTION_SIGN=1398036480]="TRANSACTION_SIGN",e[e.TRANSACTION_SIGN_TESTNET=1937012736]="TRANSACTION_SIGN_TESTNET",e[e.TRANSACTION_MULTISIGN=1397576704]="TRANSACTION_MULTISIGN",e[e.LEDGER=1280791040]="LEDGER"})(l3||(l3={}));u3.default=l3});var Sy=q(d3=>{"use strict";y();Object.defineProperty(d3,"__esModule",{value:!0});var fG=Rg(),o9=We(),pG=32;function yG(e){return(0,o9.bytesToHex)((0,fG.sha512)((0,o9.hexToBytes)(e)).slice(0,pG))}d3.default=yG});var X0=q(gd=>{"use strict";y();Object.defineProperty(gd,"__esModule",{value:!0});gd.Node=gd.NodeType=void 0;var a9;(function(e){e[e.INNER=1]="INNER",e[e.TRANSACTION_NO_METADATA=2]="TRANSACTION_NO_METADATA",e[e.TRANSACTION_METADATA=3]="TRANSACTION_METADATA",e[e.ACCOUNT_STATE=4]="ACCOUNT_STATE"})(a9||(gd.NodeType=a9={}));var f3=class{};gd.Node=f3});var g3=q(Ty=>{"use strict";y();var c9=Ty&&Ty.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ty,"__esModule",{value:!0});var s9=fe(),p3=c9(Ay()),y3=c9(Sy()),W0=X0(),h3=16,m3=class extends W0.Node{constructor(t,n,r){super(),this.tag=t,this.type=r,this.data=n}get hash(){switch(this.type){case W0.NodeType.ACCOUNT_STATE:{let t=p3.default.LEAF_NODE.toString(h3);return(0,y3.default)(t+this.data+this.tag)}case W0.NodeType.TRANSACTION_NO_METADATA:{let t=p3.default.TRANSACTION_ID.toString(h3);return(0,y3.default)(t+this.data)}case W0.NodeType.TRANSACTION_METADATA:{let t=p3.default.TRANSACTION_NODE.toString(h3);return(0,y3.default)(t+this.data+this.tag)}default:throw new s9.XrplError("Tried to hash a SHAMap node of unknown type.")}}addItem(t,n){throw new s9.XrplError("Cannot call addItem on a LeafNode")}};Ty.default=m3});var d9=q(Ey=>{"use strict";y();var v3=Ey&&Ey.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ey,"__esModule",{value:!0});var w3=fe(),hG=v3(Ay()),mG=v3(Sy()),gG=v3(g3()),l9=X0(),u9="0000000000000000000000000000000000000000000000000000000000000000",b3=15,G0=16,C3=class e extends l9.Node{constructor(t=0){super(),this.leaves={},this.type=l9.NodeType.INNER,this.depth=t,this.empty=!0}get hash(){if(this.empty)return u9;let t="";for(let r=0;r<=b3;r++){let i=this.leaves[r],o=i==null?u9:i.hash;t+=o}let n=hG.default.INNER_NODE.toString(G0);return(0,mG.default)(n+t)}addItem(t,n){let r=this.getNode(parseInt(t[this.depth],G0));if(r===void 0){this.setNode(parseInt(t[this.depth],G0),n);return}if(r instanceof e)r.addItem(t,n);else if(r instanceof gG.default){if(r.tag===t)throw new w3.XrplError("Tried to add a node to a SHAMap that was already in there.");{let i=new e(this.depth+1);i.addItem(r.tag,r),i.addItem(t,n),this.setNode(parseInt(t[this.depth],G0),i)}}}setNode(t,n){if(t<0||t>b3)throw new w3.XrplError("Invalid slot: slot must be between 0-15.");this.leaves[t]=n,this.empty=!1}getNode(t){if(t<0||t>b3)throw new w3.XrplError("Invalid slot: slot must be between 0-15.");return this.leaves[t]}};Ey.default=C3});var p9=q(Ho=>{"use strict";y();var wG=Ho&&Ho.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),bG=Ho&&Ho.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&wG(t,e,n)},f9=Ho&&Ho.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ho,"__esModule",{value:!0});var CG=f9(d9()),vG=f9(g3()),A3=class{constructor(){this.root=new CG.default(0)}get hash(){return this.root.hash}addItem(t,n,r){this.root.addItem(t,new vG.default(t,n,r))}};bG(X0(),Ho);Ho.default=A3});var k3=q(In=>{"use strict";y();var AG=In&&In.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),SG=In&&In.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),TG=In&&In.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&AG(t,e,n);return SG(t,e),t},T3=In&&In.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(In,"__esModule",{value:!0});In.hashStateTree=In.hashTxTree=In.hashLedgerHeader=In.hashSignedTx=void 0;var S3=We(),EG=T3(Sn()),_y=Qn(),wd=fe(),kG=de(),_G=hn(),h9=T3(Ay()),m9=T3(Sy()),Y0=TG(p9()),E3=16;function ky(e,t){return Number(e).toString(E3).padStart(t*2,"0")}function IG(e,t){return new EG.default(e).toString(E3).padStart(t*2,"0")}function y9(e){let t=e.length/2;if(t<=192)return(0,S3.bytesToHex)([t])+e;if(t<=12480){let n=t-193;return(0,S3.bytesToHex)([193+(n>>>8),n&255])+e}if(t<=918744){let n=t-12481;return(0,S3.bytesToHex)([241+(n>>>16),n>>>8&255,n&255])+e}throw new wd.XrplError("Variable integer overflow.")}function g9(e){let t,n;if(typeof e=="string"?(t=e,n=(0,_y.decode)(e)):(t=(0,_y.encode)(e),n=e),n.TxnSignature===void 0&&n.Signers===void 0&&n.SigningPubKey===void 0&&!(0,_G.hasFlag)(n,kG.GlobalFlags.tfInnerBatchTxn,"tfInnerBatchTxn"))throw new wd.ValidationError("The transaction must be signed to hash it.");let r=h9.default.TRANSACTION_ID.toString(16).toUpperCase();return(0,m9.default)(r.concat(t))}In.hashSignedTx=g9;function w9(e){let n=h9.default.LEDGER.toString(E3).toUpperCase()+ky(Number(e.ledger_index),4)+IG(e.total_coins,8)+e.parent_hash+e.transaction_hash+e.account_hash+ky(e.parent_close_time,4)+ky(e.close_time,4)+ky(e.close_time_resolution,1)+ky(e.close_flags,1);return(0,m9.default)(n)}In.hashLedgerHeader=w9;function b9(e){var t;let n=new Y0.default;for(let r of e){let i=(0,_y.encode)(r),o=(0,_y.encode)((t=r.metaData)!==null&&t!==void 0?t:{}),a=g9(i),s=y9(i)+y9(o);n.addItem(a,s,Y0.NodeType.TRANSACTION_METADATA)}return n.hash}In.hashTxTree=b9;function C9(e){let t=new Y0.default;return e.forEach(n=>{let r=(0,_y.encode)(n);t.addItem(n.index,r,Y0.NodeType.ACCOUNT_STATE)}),t.hash}In.hashStateTree=C9;function PG(e,t){let{transaction_hash:n}=e;if(!t.computeTreeHashes)return n;if(e.transactions==null)throw new wd.ValidationError("transactions is missing from the ledger");let r=b9(e.transactions);if(n!==r)throw new wd.ValidationError("transactionHash in header does not match computed hash of transactions",{transactionHashInHeader:n,computedHashOfTransactions:r});return r}function xG(e,t){let{account_hash:n}=e;if(!t.computeTreeHashes)return n;if(e.accountState==null)throw new wd.ValidationError("accountState is missing from the ledger");let r=C9(e.accountState);if(n!==r)throw new wd.ValidationError("stateHash in header does not match computed hash of state");return r}function MG(e,t={}){let n={transaction_hash:PG(e,t),account_hash:xG(e,t)};return w9(Object.assign(Object.assign({},e),n))}In.default=MG});var v9=q(_3=>{"use strict";y();Object.defineProperty(_3,"__esModule",{value:!0});var OG={account:"a",dirNode:"d",generatorMap:"g",rippleState:"r",offer:"o",ownerDir:"O",bookDir:"B",contract:"c",skipList:"s",escrow:"u",amendment:"f",feeSettings:"e",ticket:"T",signerList:"S",paychan:"x",check:"C",depositPreauth:"p",vault:"V",loanBroker:"l",loan:"L"};_3.default=OG});var xy=q(ze=>{"use strict";y();var DG=ze&&ze.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),RG=ze&&ze.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),NG=ze&&ze.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&DG(t,e,n);return RG(t,e),t},Z0=ze&&ze.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ze,"__esModule",{value:!0});ze.hashTxTree=ze.hashStateTree=ze.hashLedger=ze.hashSignedTx=ze.hashLedgerHeader=ze.hashLoan=ze.hashLoanBroker=ze.hashVault=ze.hashPaymentChannel=ze.hashEscrow=ze.hashTrustline=ze.hashOfferId=ze.hashSignerListId=ze.hashAccountRoot=ze.hashTx=void 0;var S9=We(),A9=Z0(Sn()),LG=lr(),Iy=NG(k3());ze.hashLedger=Iy.default;Object.defineProperty(ze,"hashLedgerHeader",{enumerable:!0,get:function(){return Iy.hashLedgerHeader}});Object.defineProperty(ze,"hashSignedTx",{enumerable:!0,get:function(){return Iy.hashSignedTx}});Object.defineProperty(ze,"hashTxTree",{enumerable:!0,get:function(){return Iy.hashTxTree}});Object.defineProperty(ze,"hashStateTree",{enumerable:!0,get:function(){return Iy.hashStateTree}});var BG=Z0(Ay()),T9=Z0(v9()),Ko=Z0(Sy()),Fa=16,Py=4;function Vo(e){return(0,S9.bytesToHex)((0,LG.decodeAccountID)(e))}function Us(e){return T9.default[e].charCodeAt(0).toString(Fa).padStart(4,"0")}var I3=255;function FG(e){if(e.length!==3)return e;let t=Array(20).fill(0);return t[12]=e.charCodeAt(0)&I3,t[13]=e.charCodeAt(1)&I3,t[14]=e.charCodeAt(2)&I3,(0,S9.bytesToHex)(Uint8Array.from(t))}function UG(e){let t=BG.default.TRANSACTION_SIGN.toString(Fa).toUpperCase();return(0,Ko.default)(t+e)}ze.hashTx=UG;function $G(e){return(0,Ko.default)(Us("account")+Vo(e))}ze.hashAccountRoot=$G;function qG(e){return(0,Ko.default)(`${Us("signerList")+Vo(e)}00000000`)}ze.hashSignerListId=qG;function HG(e,t){let n=T9.default.offer.charCodeAt(0).toString(Fa).padStart(2,"0"),r=t.toString(Fa).padStart(8,"0"),i=`00${n}`;return(0,Ko.default)(i+Vo(e)+r)}ze.hashOfferId=HG;function VG(e,t,n){let r=Vo(e),i=Vo(t),o=new A9.default(r,16).isGreaterThan(new A9.default(i,16)),a=o?i:r,s=o?r:i,c=Us("rippleState");return(0,Ko.default)(c+a+s+FG(n))}ze.hashTrustline=VG;function KG(e,t){return(0,Ko.default)(Us("escrow")+Vo(e)+t.toString(Fa).padStart(Py*2,"0"))}ze.hashEscrow=KG;function zG(e,t,n){return(0,Ko.default)(Us("paychan")+Vo(e)+Vo(t)+n.toString(Fa).padStart(Py*2,"0"))}ze.hashPaymentChannel=zG;function jG(e,t){return(0,Ko.default)(Us("vault")+Vo(e)+t.toString(Fa).padStart(Py*2,"0"))}ze.hashVault=jG;function XG(e,t){return(0,Ko.default)(Us("loanBroker")+Vo(e)+t.toString(Fa).padStart(Py*2,"0"))}ze.hashLoanBroker=XG;function WG(e,t){return(0,Ko.default)(Us("loan")+e+t.toString(Fa).padStart(Py*2,"0"))}ze.hashLoan=WG});var E9=q(Oy=>{"use strict";y();var GG=Oy&&Oy.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Oy,"__esModule",{value:!0});var YG=We(),My=GG(Sn()),ZG=lr(),JG=fe();function QG(e,t){let o=new My.default(384160001).multipliedBy(t).modulo(4294967296).plus(2459).modulo(4294967296).toNumber();return(e^o)>>>0}function eY(e){if(e.length!==64)throw new JG.XrplError(`Attempting to parse a nftokenID with length ${e.length} , but expected a token with length 64`);let n=new My.default(e.substring(48,56),16).toNumber(),r=new My.default(e.substring(56,64),16).toNumber();return{NFTokenID:e,Flags:new My.default(e.substring(0,4),16).toNumber(),TransferFee:new My.default(e.substring(4,8),16).toNumber(),Issuer:(0,ZG.encodeAccountID)((0,YG.hexToBytes)(e.substring(8,48))),Taxon:QG(n,r),Sequence:r}}Oy.default=eY});var P9=q(rr=>{"use strict";y();var tY=rr&&rr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rr,"__esModule",{value:!0});rr.percentToQuality=rr.transferRateToDecimal=rr.qualityToDecimal=rr.decimalToQuality=rr.percentToTransferRate=rr.decimalToTransferRate=void 0;var Dy=tY(Sn()),ri=fe(),Ry=10,Ua="1000000000",nY="2000000000";function k9(e){if(!e.endsWith("%"))throw new ri.ValidationError(`Value ${e} must end with %`);let t=e.split("%").filter(n=>n!=="");if(t.length!==1)throw new ri.ValidationError(`Value ${e} contains too many % signs`);try{return new Dy.default(t[0]).dividedBy("100").toString(Ry)}catch{throw new ri.ValidationError("Value is not a number")}}function _9(e){let t;try{t=new Dy.default(e).times(Ua).plus(Ua)}catch{throw new ri.ValidationError("Value is not a number")}if(t.isLessThan(Ua)||t.isGreaterThan(nY))throw new ri.ValidationError("Decimal value must be between 0 and 1.00.");let n=t.toString(Ry);if(n===Ua)return 0;if(n.includes("."))throw new ri.ValidationError("Decimal exceeds maximum precision.");return Number(n)}rr.decimalToTransferRate=_9;function rY(e){return _9(k9(e))}rr.percentToTransferRate=rY;function I9(e){let t;try{t=new Dy.default(e).times(Ua)}catch{throw new ri.ValidationError("Value is not a number")}let n=t.toString(Ry);if(n.includes("-"))throw new ri.ValidationError("Cannot have negative Quality");if(n===Ua)return 0;if(n.includes("."))throw new ri.ValidationError("Decimal exceeds maximum precision.");return Number(n)}rr.decimalToQuality=I9;function iY(e){if(!Number.isInteger(e))throw new ri.ValidationError("Quality must be an integer");if(e<0)throw new ri.ValidationError("Negative quality not allowed");return e===0?"1":new Dy.default(e).dividedBy(Ua).toString(Ry)}rr.qualityToDecimal=iY;function oY(e){if(!Number.isInteger(e))throw new ri.ValidationError("Error decoding, transfer Rate must be an integer");if(e===0)return"0";let t=new Dy.default(e).minus(Ua).dividedBy(Ua);if(t.isLessThan(0))throw new ri.ValidationError("Error decoding, negative transfer rate");return t.toString(Ry)}rr.transferRateToDecimal=oY;function aY(e){return I9(k9(e))}rr.percentToQuality=aY});var x9=q(P3=>{"use strict";y();Object.defineProperty(P3,"__esModule",{value:!0});var sY=Qn(),cY=_i(),lY=Cy();function uY(e,t,n){let r=(0,sY.encodeForSigningClaim)({channel:e,amount:(0,lY.xrpToDrops)(t)});return(0,cY.sign)(r,n)}P3.default=uY});var O9=q(bd=>{"use strict";y();Object.defineProperty(bd,"__esModule",{value:!0});bd.convertStringToHex=bd.convertHexToString=void 0;var M9=We();function dY(e){return(0,M9.stringToHex)(e)}bd.convertStringToHex=dY;function fY(e,t="utf8"){return(0,M9.hexToString)(e,t)}bd.convertHexToString=fY});var L9=q(zo=>{"use strict";y();Object.defineProperty(zo,"__esModule",{value:!0});zo.isoTimeToRippleTime=zo.rippleTimeToISOTime=zo.unixTimeToRippleTime=zo.rippleTimeToUnixTime=void 0;var D9=946684800;function R9(e){return(e+D9)*1e3}zo.rippleTimeToUnixTime=R9;function N9(e){return Math.round(e/1e3)-D9}zo.unixTimeToRippleTime=N9;function pY(e){return new Date(R9(e)).toISOString()}zo.rippleTimeToISOTime=pY;function yY(e){let t=typeof e=="string"?new Date(e):e;return N9(t.getTime())}zo.isoTimeToRippleTime=yY});var B9=q(x3=>{"use strict";y();Object.defineProperty(x3,"__esModule",{value:!0});var hY=Qn(),mY=_i(),gY=Cy();function wY(e,t,n,r){let i=(0,hY.encodeForSigningClaim)({channel:e,amount:(0,gY.xrpToDrops)(t)});return(0,mY.verify)(i,n,r)}x3.default=wY});var Ny=q(le=>{"use strict";y();var Cd=le&&le.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(le,"__esModule",{value:!0});le.getXChainClaimID=le.parseNFTokenID=le.getNFTokenID=le.encodeForSigningClaim=le.encodeForSigningBatch=le.encodeForSigning=le.encodeForMultiSigning=le.decode=le.encode=le.decodeXAddress=le.encodeXAddress=le.decodeAccountPublic=le.encodeAccountPublic=le.decodeNodePublic=le.encodeNodePublic=le.decodeAccountID=le.encodeAccountID=le.decodeSeed=le.encodeSeed=le.isValidClassicAddress=le.isValidXAddress=le.xAddressToClassicAddress=le.classicAddressToXAddress=le.convertHexToString=le.convertStringToHex=le.verifyPaymentChannelClaim=le.verifyKeypairSignature=le.signPaymentChannelClaim=le.deriveXAddress=le.deriveAddress=le.deriveKeypair=le.hashes=le.isValidAddress=le.isValidSecret=le.qualityToDecimal=le.transferRateToDecimal=le.decimalToTransferRate=le.percentToTransferRate=le.decimalToQuality=le.percentToQuality=le.unixTimeToRippleTime=le.rippleTimeToUnixTime=le.isoTimeToRippleTime=le.rippleTimeToISOTime=le.hasNextPage=le.xrpToDrops=le.dropsToXrp=le.getBalanceChanges=void 0;var ir=lr();Object.defineProperty(le,"classicAddressToXAddress",{enumerable:!0,get:function(){return ir.classicAddressToXAddress}});Object.defineProperty(le,"decodeAccountID",{enumerable:!0,get:function(){return ir.decodeAccountID}});Object.defineProperty(le,"decodeAccountPublic",{enumerable:!0,get:function(){return ir.decodeAccountPublic}});Object.defineProperty(le,"decodeNodePublic",{enumerable:!0,get:function(){return ir.decodeNodePublic}});Object.defineProperty(le,"decodeSeed",{enumerable:!0,get:function(){return ir.decodeSeed}});Object.defineProperty(le,"decodeXAddress",{enumerable:!0,get:function(){return ir.decodeXAddress}});Object.defineProperty(le,"encodeAccountID",{enumerable:!0,get:function(){return ir.encodeAccountID}});Object.defineProperty(le,"encodeAccountPublic",{enumerable:!0,get:function(){return ir.encodeAccountPublic}});Object.defineProperty(le,"encodeNodePublic",{enumerable:!0,get:function(){return ir.encodeNodePublic}});Object.defineProperty(le,"encodeSeed",{enumerable:!0,get:function(){return ir.encodeSeed}});Object.defineProperty(le,"encodeXAddress",{enumerable:!0,get:function(){return ir.encodeXAddress}});Object.defineProperty(le,"isValidClassicAddress",{enumerable:!0,get:function(){return ir.isValidClassicAddress}});Object.defineProperty(le,"isValidXAddress",{enumerable:!0,get:function(){return ir.isValidXAddress}});Object.defineProperty(le,"xAddressToClassicAddress",{enumerable:!0,get:function(){return ir.xAddressToClassicAddress}});var vd=Qn(),bY=_i();Object.defineProperty(le,"verifyKeypairSignature",{enumerable:!0,get:function(){return bY.verify}});var J0=J6();Object.defineProperty(le,"deriveKeypair",{enumerable:!0,get:function(){return J0.deriveKeypair}});Object.defineProperty(le,"deriveAddress",{enumerable:!0,get:function(){return J0.deriveAddress}});Object.defineProperty(le,"deriveXAddress",{enumerable:!0,get:function(){return J0.deriveXAddress}});var CY=Cd(n9());le.getBalanceChanges=CY.default;var vY=Cd(r9());le.getNFTokenID=vY.default;var AY=Cd(i9());le.getXChainClaimID=AY.default;var yr=xy(),SY=Cd(E9());le.parseNFTokenID=SY.default;var Ad=P9();Object.defineProperty(le,"percentToTransferRate",{enumerable:!0,get:function(){return Ad.percentToTransferRate}});Object.defineProperty(le,"decimalToTransferRate",{enumerable:!0,get:function(){return Ad.decimalToTransferRate}});Object.defineProperty(le,"transferRateToDecimal",{enumerable:!0,get:function(){return Ad.transferRateToDecimal}});Object.defineProperty(le,"percentToQuality",{enumerable:!0,get:function(){return Ad.percentToQuality}});Object.defineProperty(le,"decimalToQuality",{enumerable:!0,get:function(){return Ad.decimalToQuality}});Object.defineProperty(le,"qualityToDecimal",{enumerable:!0,get:function(){return Ad.qualityToDecimal}});var TY=Cd(x9());le.signPaymentChannelClaim=TY.default;var F9=O9();Object.defineProperty(le,"convertHexToString",{enumerable:!0,get:function(){return F9.convertHexToString}});Object.defineProperty(le,"convertStringToHex",{enumerable:!0,get:function(){return F9.convertStringToHex}});var Q0=L9();Object.defineProperty(le,"rippleTimeToISOTime",{enumerable:!0,get:function(){return Q0.rippleTimeToISOTime}});Object.defineProperty(le,"isoTimeToRippleTime",{enumerable:!0,get:function(){return Q0.isoTimeToRippleTime}});Object.defineProperty(le,"rippleTimeToUnixTime",{enumerable:!0,get:function(){return Q0.rippleTimeToUnixTime}});Object.defineProperty(le,"unixTimeToRippleTime",{enumerable:!0,get:function(){return Q0.unixTimeToRippleTime}});var EY=Cd(B9());le.verifyPaymentChannelClaim=EY.default;var U9=Cy();Object.defineProperty(le,"xrpToDrops",{enumerable:!0,get:function(){return U9.xrpToDrops}});Object.defineProperty(le,"dropsToXrp",{enumerable:!0,get:function(){return U9.dropsToXrp}});function kY(e){try{return(0,J0.deriveKeypair)(e),!0}catch{return!1}}le.isValidSecret=kY;function _Y(e){return(0,vd.encode)(e)}le.encode=_Y;function IY(e){return(0,vd.encodeForSigning)(e)}le.encodeForSigning=IY;function PY(e){return(0,vd.encodeForSigningClaim)(e)}le.encodeForSigningClaim=PY;function xY(e,t){return(0,vd.encodeForMultisigning)(e,t)}le.encodeForMultiSigning=xY;function MY(e){return(0,vd.encodeForSigningBatch)(e)}le.encodeForSigningBatch=MY;function OY(e){return(0,vd.decode)(e)}le.decode=OY;function DY(e){return(0,ir.isValidXAddress)(e)||(0,ir.isValidClassicAddress)(e)}le.isValidAddress=DY;function RY(e){return!!e.result.marker}le.hasNextPage=RY;var NY={hashSignedTx:yr.hashSignedTx,hashTx:yr.hashTx,hashAccountRoot:yr.hashAccountRoot,hashSignerListId:yr.hashSignerListId,hashOfferId:yr.hashOfferId,hashTrustline:yr.hashTrustline,hashTxTree:yr.hashTxTree,hashStateTree:yr.hashStateTree,hashLedger:yr.hashLedger,hashLedgerHeader:yr.hashLedgerHeader,hashEscrow:yr.hashEscrow,hashPaymentChannel:yr.hashPaymentChannel,hashVault:yr.hashVault,hashLoanBroker:yr.hashLoanBroker,hashLoan:yr.hashLoan};le.hashes=NY});var q9=q(Ii=>{"use strict";y();var Ly=Ii&&Ii.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(Ii,"__esModule",{value:!0});Ii.getLastLedgerSequence=Ii.getSignedTx=Ii.waitForFinalTransactionOutcome=Ii.submitRequest=void 0;var O3=fe(),By=Ny(),LY=1e3;function BY(e){return Ly(this,void 0,void 0,function*(){return new Promise(t=>{setTimeout(t,e)})})}function FY(e,t,n=!1){return Ly(this,void 0,void 0,function*(){if(!$9(t))throw new O3.ValidationError("Transaction must be signed.");let i={command:"submit",tx_blob:typeof t=="string"?t:(0,By.encode)(t),fail_hard:qY(t)||n};return e.request(i)})}Ii.submitRequest=FY;function M3(e,t,n,r){return Ly(this,void 0,void 0,function*(){yield BY(LY);let i=yield e.getLedgerIndex();if(nLy(this,void 0,void 0,function*(){var s;let c=(s=a?.data)===null||s===void 0?void 0:s.error;if(c==="txnNotFound")return M3(e,t,n,r);throw new Error(`${c} Preliminary result: ${r}. Full error details: ${String(a)}`)}));return o.result.validated?o:M3(e,t,n,r)})}Ii.waitForFinalTransactionOutcome=M3;function $9(e){let t=typeof e=="string"?(0,By.decode)(e):e;if(typeof t=="string")return!1;if(t.Signers!=null){let n=t.Signers;for(let r of n)if(r.Signer.SigningPubKey==null||r.Signer.TxnSignature==null)return!1;return!0}return t.SigningPubKey!=null&&t.TxnSignature!=null}function UY(e,t,{autofill:n=!0,wallet:r}={}){return Ly(this,void 0,void 0,function*(){if($9(t))return t;if(!r)throw new O3.ValidationError("Wallet must be provided when submitting an unsigned transaction");let i=typeof t=="string"?(0,By.decode)(t):t;return n&&(i=yield e.autofill(i)),r.sign(i).tx_blob})}Ii.getSignedTx=UY;function $Y(e){return(typeof e=="string"?(0,By.decode)(e):e).LastLedgerSequence}Ii.getLastLedgerSequence=$Y;function qY(e){return(typeof e=="string"?(0,By.decode)(e):e).TransactionType==="AccountDelete"}});var D3=q(e1=>{"use strict";y();Object.defineProperty(e1,"__esModule",{value:!0});e1.ensureClassicAddress=void 0;var H9=lr();function HY(e){if((0,H9.isValidXAddress)(e)){let{classicAddress:t,tag:n}=(0,H9.xAddressToClassicAddress)(e);if(n!==!1)throw new Error("This command does not support the use of a tag. Use an address without a tag.");return t}return e}e1.ensureClassicAddress=HY});var R3=q(t1=>{"use strict";y();Object.defineProperty(t1,"__esModule",{value:!0});t1.SponsorshipFlags=void 0;var V9;(function(e){e[e.lsfSponsorshipRequireSignForFee=65536]="lsfSponsorshipRequireSignForFee",e[e.lsfSponsorshipRequireSignForReserve=131072]="lsfSponsorshipRequireSignForReserve"})(V9||(t1.SponsorshipFlags=V9={}))});var N3=q($s=>{"use strict";y();var j9=$s&&$s.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})},VY=$s&&$s.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty($s,"__esModule",{value:!0});$s.validateSponsorship=void 0;var n1=VY(Sn()),KY=fe(),K9=R3(),z9=de();function zY(e,t,n){var r,i;return j9(this,void 0,void 0,function*(){if(!t.Sponsor||!t.SponsorFlags)return{valid:!1,error:"Transaction does not have Sponsor and SponsorFlags fields"};if(!n&&!t.Fee)return{valid:!1,error:"No fee available to validate -- pass estimatedFee or set tx.Fee"};let o=(r=n??t.Fee)!==null&&r!==void 0?r:"0",a=t.SponsorSignature!=null,s=(i=t.Delegate)!==null&&i!==void 0?i:t.Account;try{let c=yield jY(e,t.Sponsor,s);if(!c)return a?{valid:!0,estimatedFee:o}:{valid:!1,error:`No Sponsorship ledger entry found for sponsor ${t.Sponsor} and sponsee ${s}`};let l=(t.SponsorFlags&z9.SponsorFlags.spfSponsorFee)!==0,u=(t.SponsorFlags&z9.SponsorFlags.spfSponsorReserve)!==0;if(!a){let d=(c.Flags&K9.SponsorshipFlags.lsfSponsorshipRequireSignForFee)!==0,p=(c.Flags&K9.SponsorshipFlags.lsfSponsorshipRequireSignForReserve)!==0;if(l&&d)return{valid:!1,error:"Sponsorship requires the sponsee to sign for fee sponsorship (lsfSponsorshipRequireSignForFee is set)",sponsorship:c,estimatedFee:o};if(u&&p)return{valid:!1,error:"Sponsorship requires the sponsee to sign for reserve sponsorship (lsfSponsorshipRequireSignForReserve is set)",sponsorship:c,estimatedFee:o}}if(u&&(c.RemainingOwnerCount==null||c.RemainingOwnerCount<1))return{valid:!1,error:`Sponsorship RemainingOwnerCount (${String(c.RemainingOwnerCount)}) is insufficient to cover this reserve-sponsored transaction`,sponsorship:c,estimatedFee:o};if(!l)return{valid:!0,sponsorship:c,estimatedFee:o};if(c.FeeAmount==null)return{valid:!1,error:"Sponsorship FeeAmount is required when spfSponsorFee flag is set",sponsorship:c,estimatedFee:o};if(c.FeeAmount){let d=new n1.default(c.FeeAmount),p=new n1.default(o);if(d.isLessThan(p))return{valid:!1,error:`Sponsorship FeeAmount (${c.FeeAmount} drops) is insufficient for transaction fee (${o} drops)`,sponsorship:c,estimatedFee:o}}if(c.MaxFee){let d=new n1.default(c.MaxFee);if(new n1.default(o).isGreaterThan(d))return{valid:!1,error:`Transaction fee (${o} drops) exceeds sponsorship MaxFee (${c.MaxFee} drops)`,sponsorship:c,estimatedFee:o}}return{valid:!0,sponsorship:c,estimatedFee:o}}catch(c){return{valid:!1,error:c instanceof Error?c.message:String(c)}}})}$s.validateSponsorship=zY;function jY(e,t,n){return j9(this,void 0,void 0,function*(){try{let r={command:"ledger_entry",sponsorship:{sponsor:t,sponsee:n}},o=(yield e.request(r)).result.node;return o?.LedgerEntryType==="Sponsorship"?o:null}catch(r){if(r instanceof KY.XrplError&&typeof r.data=="object"&&r.data!==null&&"error"in r.data&&r.data.error==="entryNotFound")return null;throw r}})}});var X9=q($a=>{"use strict";y();var XY=$a&&$a.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),L3=$a&&$a.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&XY(t,e,n)};Object.defineProperty($a,"__esModule",{value:!0});L3(q9(),$a);L3(D3(),$a);L3(N3(),$a)});var W9=q(ll=>{"use strict";y();var WY=ll&&ll.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})},GY=ll&&ll.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ll,"__esModule",{value:!0});var B3=GY(Sn()),YY=fe(),ZY=6,JY=10;function QY(e,t){var n,r;return WY(this,void 0,void 0,function*(){let i=t??e.feeCushion,o=(yield e.request({command:"server_info"})).result.info,a=(n=o.validated_ledger)===null||n===void 0?void 0:n.base_fee_xrp;if(a==null)throw new YY.XrplError("getFeeXrp: Could not get base_fee_xrp from server_info");let s=new B3.default(a);(r=o.load_factor)!==null&&r!==void 0||(o.load_factor=1);let c=s.times(o.load_factor).times(i);return c=B3.default.min(c,e.maxFeeXRP),new B3.default(c.toFixed(ZY)).toString(JY)})}ll.default=QY});var rI=q(dn=>{"use strict";y();var jo=dn&&dn.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})},J9=dn&&dn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(dn,"__esModule",{value:!0});dn.autofillBatchTxn=dn.handleDeliverMax=dn.checkAccountDeleteBlockers=dn.setLatestValidatedLedgerSequence=dn.getTransactionFee=dn.setNextValidSequenceNumber=dn.setValidAddresses=dn.txNeedsNetworkID=void 0;var hr=J9(Sn()),G9=lr(),po=fe(),eZ=de(),Y9=Ny(),tZ=J9(W9()),nZ=20,rZ=1024,iZ="1.11.0",oZ=9,aZ=["ConfidentialMPTConvert","ConfidentialMPTConvertBack","ConfidentialMPTSend","ConfidentialMPTClawback","ConfidentialMPTMergeInbox"];function sZ(e,t){if(e===t)return!0;let n=e.split("."),r=t.split("."),i=parseInt(n[0],10),o=parseInt(n[1],10),a=parseInt(r[0],10),s=parseInt(r[1],10);if(i!==a)return il.length:c.length===2?c[1][0].startsWith(l[1][0])?c[1].startsWith("b")?parseInt(c[1].slice(1),10)rZ&&e.buildVersion&&sZ(iZ,e.buildVersion))}dn.txNeedsNetworkID=Q9;function cZ(e){Z9(e,"Account","SourceTag"),e.Destination!=null&&Z9(e,"Destination","DestinationTag"),ul(e,"Authorize"),ul(e,"Unauthorize"),ul(e,"Owner"),ul(e,"RegularKey"),ul(e,"Sponsor"),ul(e,"Sponsee"),ul(e,"CounterpartySponsor")}dn.setValidAddresses=cZ;function Z9(e,t,n){let{classicAccount:r,tag:i}=eI(e[t]);if(e[t]=r,i!=null&&i!==!1){if(e[n]&&e[n]!==i)throw new po.ValidationError(`The ${n}, if present, must match the tag of the ${t} X-address`);e[n]=i}}function eI(e,t){if((0,G9.isValidXAddress)(e)){let n=(0,G9.xAddressToClassicAddress)(e);if(t!=null&&n.tag!==t)throw new po.ValidationError("address includes a tag that does not match the tag specified in the transaction");return{classicAccount:n.classicAddress,tag:n.tag}}return{classicAccount:e,tag:t}}function ul(e,t){let n=e[t];if(typeof n=="string"){let{classicAccount:r}=eI(n);e[t]=r}}function tI(e,t){return jo(this,void 0,void 0,function*(){let n={command:"account_info",account:t,ledger_index:"current"};return(yield e.request(n)).result.account_data.Sequence})}function lZ(e,t){return jo(this,void 0,void 0,function*(){t.Sequence=yield tI(e,t.Account)})}dn.setNextValidSequenceNumber=lZ;function uZ(e){var t;return jo(this,void 0,void 0,function*(){let r=(t=(yield e.request({command:"server_state"})).result.state.validated_ledger)===null||t===void 0?void 0:t.reserve_inc;return r==null?Promise.reject(new Error("Could not fetch Owner Reserve.")):new hr.default(r)})}function dZ(e,t){var n,r;return jo(this,void 0,void 0,function*(){let i=t.Counterparty;if(i==null){if(t.LoanBrokerID==null)throw new po.ValidationError("LoanBrokerID is required for LoanSet transaction");i=(yield e.request({command:"ledger_entry",index:t.LoanBrokerID,ledger_index:"validated"})).result.node.Owner}let o={command:"account_info",account:i,ledger_index:"validated",signer_lists:!0},s=(n=(yield e.request(o)).result.signer_lists)===null||n===void 0?void 0:n[0];return(r=s?.SignerEntries.length)!==null&&r!==void 0?r:1})}function fZ(e,t=0){return t<=0?new hr.default(0):(console.warn("For sponsored transaction the auto calculated Fee accounts for sponsor signers to avoid transaction failure."),new hr.default(Fy(e,t)))}function nI(e,t,n=0,r=0){return jo(this,void 0,void 0,function*(){let i=yield(0,tZ.default)(e),o=(0,Y9.xrpToDrops)(i),a=new hr.default(o),s=["AccountDelete","AMMCreate","VaultCreate"].includes(t.TransactionType);if(t.TransactionType==="EscrowFinish"&&t.Fulfillment!=null){let d=Math.ceil(t.Fulfillment.length/2);a=new hr.default(Fy(o,33+d/16))}else if(s)a=yield uZ(e);else if(t.TransactionType==="Batch"){let d=yield t.RawTransactions.reduce((p,h)=>jo(this,void 0,void 0,function*(){let g=yield p,w=yield nI(e,h.RawTransaction);return hr.default.sum(g,w)}),Promise.resolve(new hr.default(0)));a=hr.default.sum(a.times(2),d)}else aZ.includes(t.TransactionType)&&(a=hr.default.sum(a,Fy(o,oZ)));if(n>0&&(a=hr.default.sum(a,Fy(o,n))),t.TransactionType==="LoanSet"){let d=yield dZ(e,t);a=hr.default.sum(a,Fy(o,d)),console.warn("For LoanSet transaction the auto calculated Fee accounts for total number of signers the counterparty has to avoid transaction failure.")}let c=fZ(o,r);a=hr.default.sum(a,c);let l=(0,Y9.xrpToDrops)(e.maxFeeXRP);return(s?a:hr.default.min(a,l)).dp(0,hr.default.ROUND_CEIL)})}function pZ(e,t,n=0,r=0){return jo(this,void 0,void 0,function*(){let i=yield nI(e,t,n,r);t.Fee=i.toString(10)})}dn.getTransactionFee=pZ;function Fy(e,t){return new hr.default(e).times(t).toString()}function yZ(e,t){return jo(this,void 0,void 0,function*(){let n=yield e.getLedgerIndex();t.LastLedgerSequence=n+nZ})}dn.setLatestValidatedLedgerSequence=yZ;function hZ(e,t){return jo(this,void 0,void 0,function*(){let n={command:"account_objects",account:t.Account,ledger_index:"validated",deletion_blockers_only:!0},r={command:"account_info",account:t.Account,ledger_index:"validated"},[i,o]=yield Promise.all([e.request(n),e.request(r)]);if(i.result.account_objects.length>0)throw new po.XrplError(`Account ${t.Account} cannot be deleted; there are Escrows, PayChannels, RippleStates, Checks, or Sponsorships associated with the account.`,i.result.account_objects);let a=o.result.account_data;if(a.SponsoringOwnerCount!=null||a.SponsoringAccountCount!=null)throw new po.XrplError(`Account ${t.Account} cannot be deleted; it has outstanding sponsorship obligations (SponsoringOwnerCount/SponsoringAccountCount).`);if(a.Sponsor!=null&&"Destination"in t&&typeof t.Destination=="string"&&!(0,eZ.areAddressesEqual)(a.Sponsor,t.Destination))throw new po.XrplError(`Account ${t.Account} cannot be deleted; its Sponsor (${a.Sponsor}) does not match the AccountDelete Destination (${t.Destination}).`)})}dn.checkAccountDeleteBlockers=hZ;function mZ(e){var t;if(e.DeliverMax!=null){if((t=e.Amount)!==null&&t!==void 0||(e.Amount=e.DeliverMax),e.Amount!=null&&e.Amount!==e.DeliverMax)throw new po.ValidationError("PaymentTransaction: Amount and DeliverMax fields must be identical when both are provided");delete e.DeliverMax}}dn.handleDeliverMax=mZ;function gZ(e,t){return jo(this,void 0,void 0,function*(){let n={};for(let r of t.RawTransactions){let i=r.RawTransaction;if(i.Sequence==null&&i.TicketSequence==null)if(i.Account in n)i.Sequence=n[i.Account],n[i.Account]+=1;else{let o=yield tI(e,i.Account),a=i.Account===t.Account?o+1:o;n[i.Account]=a+1,i.Sequence=a}if(i.Fee==null)i.Fee="0";else if(i.Fee!=="0")throw new po.XrplError('Must have `Fee of "0" in inner Batch transaction.');if(i.SigningPubKey==null)i.SigningPubKey="";else if(i.SigningPubKey!=="")throw new po.XrplError('Must have `SigningPubKey` of "" in inner Batch transaction.');if(i.TxnSignature!=null)throw new po.XrplError("Must not have `TxnSignature` in inner Batch transaction.");if(i.Signers!=null)throw new po.XrplError("Must not have `Signers` in inner Batch transaction.");i.NetworkID==null&&Q9(e)&&(i.NetworkID=e.networkID)}})}dn.autofillBatchTxn=gZ});var iI=q(r1=>{"use strict";y();Object.defineProperty(r1,"__esModule",{value:!0});r1.formatBalances=void 0;function wZ(e){return e.map(t=>({value:t.balance,currency:t.currency,issuer:t.account}))}r1.formatBalances=wZ});var F3=q(i1=>{"use strict";y();Object.defineProperty(i1,"__esModule",{value:!0});i1.OfferFlags=void 0;var oI;(function(e){e[e.lsfPassive=65536]="lsfPassive",e[e.lsfSell=131072]="lsfSell",e[e.lsfHybrid=262144]="lsfHybrid"})(oI||(i1.OfferFlags=oI={}))});var aI=q(fn=>{"use strict";y();var bZ=fn&&fn.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})},CZ=fn&&fn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(fn,"__esModule",{value:!0});fn.sortAndLimitOffers=fn.separateBuySellOrders=fn.combineOrders=fn.extractOffers=fn.reverseRequest=fn.requestAllOffers=fn.createBookOffersRequest=fn.validateOrderbookOptions=void 0;var vZ=CZ(Sn()),Uy=fe(),AZ=F3(),SZ=20;function TZ(e){return e.sort((t,n)=>{var r,i,o;let a=(r=t.quality)!==null&&r!==void 0?r:0,s=(i=n.quality)!==null&&i!==void 0?i:0;return(o=new vZ.default(a).comparedTo(s))!==null&&o!==void 0?o:0})}var EZ=new Set(["limit","ledger_index","ledger_hash","taker"]);function kZ(e){for(let t of Object.keys(e))if(!EZ.has(t))throw new Uy.ValidationError(`Unexpected option: ${t}`,e);if(e.limit&&typeof e.limit!="number")throw new Uy.ValidationError("limit must be a number",e.limit);if(e.ledger_index&&!(typeof e.ledger_index=="number"||typeof e.ledger_index=="string"&&["validated","closed","current"].includes(e.ledger_index)))throw new Uy.ValidationError('ledger_index must be a number or a string of "validated", "closed", or "current"',e.ledger_index);if(e.ledger_hash!==void 0&&e.ledger_hash!==null&&typeof e.ledger_hash!="string")throw new Uy.ValidationError("ledger_hash must be a string",e.ledger_hash);if(e.taker!==void 0&&typeof e.taker!="string")throw new Uy.ValidationError("taker must be a string",e.taker)}fn.validateOrderbookOptions=kZ;function _Z(e,t,n){var r,i,o;return{command:"book_offers",taker_pays:e,taker_gets:t,ledger_index:(r=n.ledger_index)!==null&&r!==void 0?r:"validated",ledger_hash:n.ledger_hash===null?void 0:n.ledger_hash,limit:(i=n.limit)!==null&&i!==void 0?i:SZ,taker:(o=n.taker)!==null&&o!==void 0?o:void 0}}fn.createBookOffersRequest=_Z;function IZ(e,t){return bZ(this,void 0,void 0,function*(){return(yield e.requestAll(t)).map(r=>r.result.offers)})}fn.requestAllOffers=IZ;function PZ(e){return Object.assign(Object.assign({},e),{taker_pays:e.taker_gets,taker_gets:e.taker_pays})}fn.reverseRequest=PZ;function xZ(e){return e.flatMap(t=>t)}fn.extractOffers=xZ;function MZ(e,t){return[...e,...t]}fn.combineOrders=MZ;function OZ(e){let t=[],n=[];return e.forEach(r=>{(r.Flags&AZ.OfferFlags.lsfSell)===0?t.push(r):n.push(r)}),{buy:t,sell:n}}fn.separateBuySellOrders=OZ;function DZ(e,t){return TZ(e).slice(0,t)}fn.sortAndLimitOffers=DZ});function sI(e,t,n,r){return e===0?t^n^r:e===1?t&n|~t&r:e===2?(t|~n)^r:e===3?t&r|n&~r:t^(n|~r)}var RZ,cI,NZ,lI,uI,dI,fI,LZ,BZ,FZ,UZ,o1,U3,pI,yI=Te(()=>{y();cA();Hn();RZ=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),cI=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),NZ=cI.map(e=>(9*e+5)%16),lI=(()=>{let n=[[cI],[NZ]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(o=>RZ[o]));return n})(),uI=lI[0],dI=lI[1],fI=[[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)),LZ=uI.map((e,t)=>e.map(n=>fI[t][n])),BZ=dI.map((e,t)=>e.map(n=>fI[t][n])),FZ=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),UZ=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);o1=new Uint32Array(16),U3=class extends Qc{h0=1732584193;h1=-271733879;h2=-1732584194;h3=271733878;h4=-1009589776;constructor(){super(64,20,8,!0)}get(){let{h0:t,h1:n,h2:r,h3:i,h4:o}=this;return[t,n,r,i,o]}set(t,n,r,i,o){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=i|0,this.h4=o|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let h=0;h<16;h++,n+=4)o1[h]=t.getUint32(n,!0);let r=this.h0|0,i=r,o=this.h1|0,a=o,s=this.h2|0,c=s,l=this.h3|0,u=l,d=this.h4|0,p=d;for(let h=0;h<5;h++){let g=4-h,w=FZ[h],T=UZ[h],k=uI[h],B=dI[h],D=LZ[h],P=BZ[h];for(let U=0;U<16;U++){let F=hu(r+sI(h,o,s,l)+o1[k[U]]+w,D[U])+d|0;r=d,d=l,l=hu(s,10)|0,s=o,o=F}for(let U=0;U<16;U++){let F=hu(i+sI(g,a,c,u)+o1[B[U]]+T,P[U])+p|0;i=p,p=u,u=hu(c,10)|0,c=a,a=F}}this.set(this.h1+s+u|0,this.h2+l+p|0,this.h3+d+i|0,this.h4+r+a|0,this.h0+o+c|0)}roundClean(){yn(o1)}destroy(){this.destroyed=!0,yn(this.buffer),this.set(0,0,0,0,0)}},pI=gu(()=>new U3)});var hI={};Tr(hI,{HARDENED_OFFSET:()=>qy,HDKey:()=>K3});var $y,Sd,$3,$Z,q3,qy,H3,qZ,HZ,qs,V3,K3,mI=Te(()=>{y();R0();uy();yI();Bo();Hn();_v();$y=al.Point,Sd=$y.Fn,$3=Vm(_t),$Z=Uint8Array.from("Bitcoin seed".split(""),e=>e.charCodeAt(0)),q3={private:76066276,public:76067358},qy=2147483648,H3=255,qZ=e=>pI(_t(e)),HZ=e=>Qi(e).getUint32(0,!1),qs=(e,t="number")=>{if(typeof e!="number")throw new TypeError(`"${t}" expected number, got type=${typeof e}`);if(!Number.isSafeInteger(e)||e<0||e>2**32-1)throw new RangeError(`"${t}" expected integer in range 0..2**32-1, got ${e}`);let n=new Uint8Array(4);return Qi(n).setUint32(0,e,!1),n},V3=(e,t="versions")=>{if(!(typeof e=="object"&&e!==null))throw new Error("versions must be an object");return qs(e.private,`${t}.private`),qs(e.public,`${t}.public`),e},K3=class e{get fingerprint(){if(!this._pubHash)throw new Error("No publicKey set!");return HZ(this._pubHash)}get identifier(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get pubKeyHash(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get privateKey(){return this._privateKey?Uint8Array.from(this._privateKey):null}get publicKey(){return this._publicKey?Uint8Array.from(this._publicKey):null}get chainCode(){return this._chainCode?Uint8Array.from(this._chainCode):null}get privateExtendedKey(){let t=this._privateKey;if(!t)throw new Error("No private key");return $3.encode(this.serialize(this.versions.private,Io(Uint8Array.of(0),t)))}get publicExtendedKey(){if(!this._publicKey)throw new Error("No public key");return $3.encode(this.serialize(this.versions.public,this._publicKey))}static fromMasterSeed(t,n=q3){if(St(t),n=V3(n),8*t.length<128||8*t.length>512)throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+t.length);let r=Na(tr,$Z,t),i=r.slice(0,32),o=r.slice(32);return new e({versions:n,chainCode:o,privateKey:i})}static fromExtendedKey(t,n=q3){n=V3(n);let r=$3.decode(t);if(r.length!==78)throw new Error(`HDKey: invalid extended key length: expected 78 bytes, got ${r.length}`);let i=Qi(r),o=i.getUint32(0,!1),a={versions:n,depth:r[4],parentFingerprint:i.getUint32(5,!1),index:i.getUint32(9,!1),chainCode:r.slice(13,45)},s=r.slice(45),c=s[0]===0;if(o!==n[c?"private":"public"])throw new Error("Version mismatch");return c?new e({...a,privateKey:s.slice(1)}):new e({...a,publicKey:s})}static fromJSON(t){return e.fromExtendedKey("xpriv"in t?t.xpriv:t.xpub)}versions;depth=0;index=0;parentFingerprint=0;_chainCode=null;_privateKey;_publicKey;_pubHash;constructor(t){if(!t||typeof t!="object")throw new Error("HDKey.constructor must not be called directly");let n=t.depth??0,r=t.index??0,i=t.parentFingerprint??0;if(!Number.isSafeInteger(n)||n<0||n>H3)throw new RangeError("HDKey: depth must be an integer in range 0..255");if(qs(r,"index"),qs(i,"parentFingerprint"),n===0&&(r!==0||i!==0))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(this.versions=t.versions?V3(t.versions):q3,this.depth=n,t.chainCode&&St(t.chainCode,32),this._chainCode=t.chainCode?Uint8Array.from(t.chainCode):null,this.index=r,this.parentFingerprint=i,t.publicKey&&t.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(t.privateKey){if(!al.utils.isValidSecretKey(t.privateKey))throw new Error("Invalid private key");this._privateKey=Uint8Array.from(t.privateKey),this._publicKey=al.getPublicKey(this._privateKey,!0)}else if(t.publicKey)this._publicKey=$y.fromBytes(t.publicKey).toBytes(!0);else throw new Error("HDKey: no public or private key provided");this._pubHash=qZ(this._publicKey)}derive(t){if(!/^[mM]'?/.test(t))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(t))return this;let n=t.replace(/^[mM]'?\//,"").split("/");if(n.length>H3-this.depth)throw new Error("HDKey: path exceeds the serializable depth 255");let r=this;for(let i of n){let o=/^(\d+)('?)$/.exec(i),a=o&&o[1];if(!o||o.length!==3||typeof a!="string")throw new Error("invalid child index: "+i);let s=+a;if(!Number.isSafeInteger(s)||s>=qy)throw new Error("Invalid index");o[2]==="'"&&(s+=qy),r=r.deriveChild(s)}return r}deriveChild(t){return this._deriveChild(t)}_deriveChild(t,n){if(!this._publicKey||!this._chainCode)throw new Error("No publicKey or chainCode set");let r=qs(t,"index");if(t>=qy){let u=this._privateKey;if(!u)throw new Error("Could not derive hardened child key");r=Io(Uint8Array.of(0),u,r)}else r=Io(this._publicKey,r);let i=n||Na(tr,this._chainCode,r);St(i,64);let o=i.slice(0,32),a=i.slice(32),s={versions:this.versions,chainCode:a,depth:this.depth+1,parentFingerprint:this.fingerprint,index:t};if(s.depth>H3)throw new Error("HDKey: depth exceeds the serializable value 255");let c=()=>{let u=this._privateKey?4294967295:qy-1;if(t>=u)throw new Error(`HDKey: cannot retry child derivation at index ${t}`);return this.deriveChild(t+1)},l=Sd.fromBytes(o,!0);if(!Sd.isValid(l))return c();if(this._privateKey){let u=Sd.create(Sd.fromBytes(this._privateKey)+l);if(!Sd.isValidNot0(u))return c();s.privateKey=Sd.toBytes(u)}else{let u=$y.fromBytes(this._publicKey),d=l===0n?u:u.add($y.BASE.multiply(l));if(d.equals($y.ZERO))return c();s.publicKey=d.toBytes(!0)}return new e(s)}sign(t){if(!this._privateKey)throw new Error("No privateKey set!");return St(t,32),al.sign(t,this._privateKey,{prehash:!1})}verify(t,n){if(St(t,32),St(n,64),!this._publicKey)throw new Error("No publicKey set!");return al.verify(n,t,this._publicKey,{prehash:!1})}wipePrivateData(){return this._privateKey&&(this._privateKey.fill(0),this._privateKey=void 0),this}toJSON(){return this.toPrivateJSON()}toPrivateJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(t,n){if(!this._chainCode)throw new Error("No chainCode set");return St(n,33),Io(qs(t,"version"),new Uint8Array([this.depth]),qs(this.parentFingerprint,"parentFingerprint"),qs(this.index,"index"),this._chainCode,n)}}});function gI(e,t,n,r){va(e);let i=mu({dkLen:32,asyncTick:10},r),{c:o,dkLen:a,asyncTick:s}=i;if(pn(o,"c"),pn(a,"dkLen"),pn(s,"asyncTick"),o<1)throw new Error('"c" (iterations) must be >= 1');if(a<1)throw new Error('"dkLen" must be >= 1');if(a>(2**32-1)*e.outputLen)throw new Error("derived key too long");let c=Ic(t,"password");try{let l=Ic(n,"salt");try{let u=new Uint8Array(a),{iHash:d,oHash:p,outputLen:h}=Na.create(e,c),g=new Uint8Array(h),w=VZ(d,p,l,g);return{c:o,dkLen:a,asyncTick:s,DK:u,outputLen:h,eng:w}}finally{typeof n=="string"&&yn(l)}}finally{typeof t=="string"&&yn(c)}}function VZ(e,t,n,r){let i=new Uint8Array(4),o=Qi(i),a=e._cloneInto().update(n),s=t._cloneInto(),c=e._cloneInto,l=t._cloneInto;return{u1:(u,d)=>{o.setInt32(0,u,!1),a._cloneInto(s).update(i).digestInto(r),t._cloneInto(s).update(r).digestInto(r),d.set(r.subarray(0,d.length))},rounds:(u,d)=>{for(let p=1;p(e.destroy(),t.destroy(),a.destroy(),s.destroy(),yn(r),u)}}function wI(e,t,n,r){let{c:i,dkLen:o,DK:a,outputLen:s,eng:c}=gI(e,t,n,r);for(let l=1,u=0;u{l.output(s),yn(s)};for(let d=1,p=0;p{l.rounds(2,h)},u)}return l.output(s)}var CI=Te(()=>{y();uy();Hn()});function vI(){let t=(typeof globalThis=="object"?globalThis.crypto:null)?.subtle;if(typeof t=="object"&&t!=null)return t;throw new Error("crypto.subtle must be defined")}function KZ(e,t,n){let r=async i=>{St(i);let o=vI();return new Uint8Array(await o.digest(e,i))};return r.webCryptoName=e,r.outputLen=n,r.blockLen=t,r.create=()=>{throw new Error("not implemented")},Object.freeze(r)}function zZ(e){va(e);let t=e.webCryptoName;if(typeof t!="string")throw new Error("non-web hash");return t}async function SI(e,t,n,r){let i=vI(),o=zZ(e),a=mu({dkLen:32},r),{c:s,dkLen:c}=a;if(pn(s,"c"),pn(c,"dkLen"),s>2147483647)throw new Error('"c" exceeds WebCrypto backend limit');if(c<1)throw new Error('"dkLen" must be >= 1');if(c>=2**29)throw new Error("derived key too long");let l=Ic(t,"password");try{let u=Ic(n,"salt"),d=typeof n=="string"?u:gv(u);try{let p=await i.importKey("raw",l,"PBKDF2",!1,["deriveBits"]),h={name:"PBKDF2",salt:d,iterations:s,hash:o},g=new Uint8Array(await i.deriveBits(h,p,8*c));if(g.length!==c)throw yn(g),new Error("WebCrypto returned an invalid derived key length");return g}finally{yn(d)}}finally{typeof t=="string"&&yn(l)}}var AI,TI=Te(()=>{y();Hn();AI=KZ("SHA-512",128,64)});var OI={};Tr(OI,{entropyToMnemonic:()=>MI,generateMnemonic:()=>XZ,mnemonicToEntropy:()=>xI,mnemonicToSeed:()=>ZZ,mnemonicToSeedSync:()=>JZ,mnemonicToSeedWebcrypto:()=>QZ,validateMnemonic:()=>YZ});function EI(e){for(let t=0;t=55296&&n<=56319){if(t+1>=e.length)return!1;let r=e.charCodeAt(++t);if(r<56320||r>57343)return!1}else if(n>=56320&&n<=57343)return!1}return!0}function kI(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);if(!EI(e))throw new TypeError("expected well-formed Unicode string");return e.normalize("NFKD")}function a1(e){let t=kI(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function _I(e){if(St(e),![16,20,24,28,32].includes(e.length))throw new RangeError("invalid entropy length")}function XZ(e,t=128){if(pn(t),t%32!==0||t>256)throw new RangeError("Invalid entropy");return MI(us(t/8),e)}function PI(e){if(!Array.isArray(e)||e.length!==2048||typeof e[0]!="string")throw new TypeError("Wordlist: expected array of 2048 strings");e.forEach(t=>{if(typeof t!="string")throw new TypeError("wordlist: non-string element: "+t);if(!EI(t))throw new TypeError("wordlist: expected well-formed Unicode string")})}function WZ(e,t){PI(t);let n=new Uint8Array(e.length+1);n.set(e),n[e.length]=II(e);let r=[],i=0,o=0;for(let a of n)i=i<<8|a,o+=8,o>=11&&(o-=11,r.push(t[i>>>o&2047]),i&=(1<=8;)o-=8,r[a++]=i>>>o&255;i&=(1<0&&(r[a]=i<<8-o);let s=r.subarray(0,n);if(r[n]!==II(s))throw new Error("Invalid checksum");return Uint8Array.from(s)}function xI(e,t){let{words:n}=a1(e),r=GZ(n,t);return _I(r),r}function MI(e,t){return _I(e),WZ(e,t).join(jZ(t)?"\u3000":" ")}function YZ(e,t){try{xI(e,t)}catch{return!1}return!0}function ZZ(e,t=""){return bI(tr,a1(e).nfkd,z3(t),{c:2048,dkLen:64})}function JZ(e,t=""){return wI(tr,a1(e).nfkd,z3(t),{c:2048,dkLen:64})}function QZ(e,t=""){return SI(AI,a1(e).nfkd,z3(t),{c:2048,dkLen:64})}var jZ,II,z3,DI=Te(()=>{y();CI();Bo();Hn();TI();jZ=e=>e[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";II=e=>{let t=8-e.length/4;return _t(e)[0]>>t<{if(typeof e!="string")throw new TypeError("invalid passphrase type: "+typeof e);return kI("mnemonic"+e)}});var RI={};Tr(RI,{wordlist:()=>eJ});var eJ,NI=Te(()=>{y();eJ=Object.freeze(`abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo`.split(` `))});var Hy=q(X3=>{"use strict";y();Object.defineProperty(X3,"__esModule",{value:!0});var j3;(function(e){e.ed25519="ed25519",e.secp256k1="ecdsa-secp256k1"})(j3||(j3={}));X3.default=j3});var LI=q(s1=>{"use strict";y();Object.defineProperty(s1,"__esModule",{value:!0});s1.validateAccountDelete=void 0;var dl=de();function tJ(e){(0,dl.validateBaseTransaction)(e),(0,dl.validateRequiredField)(e,"Destination",dl.isAccount),(0,dl.validateOptionalField)(e,"DestinationTag",dl.isNumber),(0,dl.validateCredentialsList)(e.CredentialIDs,e.TransactionType,!0,dl.MAX_AUTHORIZED_CREDENTIALS)}s1.validateAccountDelete=tJ});var FI=q(c1=>{"use strict";y();Object.defineProperty(c1,"__esModule",{value:!0});c1.validateAMMBid=void 0;var ii=fe(),Hs=de(),BI=4;function nJ(e){if((0,Hs.validateBaseTransaction)(e),e.Asset==null)throw new ii.ValidationError("AMMBid: missing field Asset");if(!(0,Hs.isIssuedCurrency)(e.Asset))throw new ii.ValidationError("AMMBid: Asset must be a Currency");if(e.Asset2==null)throw new ii.ValidationError("AMMBid: missing field Asset2");if(!(0,Hs.isIssuedCurrency)(e.Asset2))throw new ii.ValidationError("AMMBid: Asset2 must be a Currency");if(e.BidMin!=null&&!(0,Hs.isAmount)(e.BidMin))throw new ii.ValidationError("AMMBid: BidMin must be an Amount");if(e.BidMax!=null&&!(0,Hs.isAmount)(e.BidMax))throw new ii.ValidationError("AMMBid: BidMax must be an Amount");if(e.AuthAccounts!=null){if(!(0,Hs.isArray)(e.AuthAccounts))throw new ii.ValidationError("AMMBid: AuthAccounts must be an AuthAccount array");if(e.AuthAccounts.length>BI)throw new ii.ValidationError(`AMMBid: AuthAccounts length must not be greater than ${BI}`);rJ(e.Account,e.AuthAccounts)}}c1.validateAMMBid=nJ;function rJ(e,t){for(let n of t){if(!(0,Hs.isRecord)(n))throw new ii.ValidationError("AMMBid: invalid AuthAccounts");if(!(0,Hs.isRecord)(n.AuthAccount))throw new ii.ValidationError("AMMBid: invalid AuthAccounts");if(n.AuthAccount.Account==null)throw new ii.ValidationError("AMMBid: invalid AuthAccounts");if(typeof n.AuthAccount.Account!="string")throw new ii.ValidationError("AMMBid: invalid AuthAccounts");if(n.AuthAccount.Account===e)throw new ii.ValidationError("AMMBid: AuthAccounts must not include sender's address")}return!0}});var G3=q(Vs=>{"use strict";y();Object.defineProperty(Vs,"__esModule",{value:!0});Vs.validateAMMCreate=Vs.AMM_MAX_TRADING_FEE=void 0;var fl=fe(),W3=de();Vs.AMM_MAX_TRADING_FEE=1e3;function iJ(e){if((0,W3.validateBaseTransaction)(e),e.Amount==null)throw new fl.ValidationError("AMMCreate: missing field Amount");if(!(0,W3.isAmount)(e.Amount))throw new fl.ValidationError("AMMCreate: Amount must be an Amount");if(e.Amount2==null)throw new fl.ValidationError("AMMCreate: missing field Amount2");if(!(0,W3.isAmount)(e.Amount2))throw new fl.ValidationError("AMMCreate: Amount2 must be an Amount");if(e.TradingFee==null)throw new fl.ValidationError("AMMCreate: missing field TradingFee");if(typeof e.TradingFee!="number")throw new fl.ValidationError("AMMCreate: TradingFee must be a number");if(e.TradingFee<0||e.TradingFee>Vs.AMM_MAX_TRADING_FEE)throw new fl.ValidationError(`AMMCreate: TradingFee must be between 0 and ${Vs.AMM_MAX_TRADING_FEE}`)}Vs.validateAMMCreate=iJ});var UI=q(u1=>{"use strict";y();Object.defineProperty(u1,"__esModule",{value:!0});u1.validateAMMDelete=void 0;var l1=fe(),Y3=de();function oJ(e){if((0,Y3.validateBaseTransaction)(e),e.Asset==null)throw new l1.ValidationError("AMMDelete: missing field Asset");if(!(0,Y3.isIssuedCurrency)(e.Asset))throw new l1.ValidationError("AMMDelete: Asset must be a Currency");if(e.Asset2==null)throw new l1.ValidationError("AMMDelete: missing field Asset2");if(!(0,Y3.isIssuedCurrency)(e.Asset2))throw new l1.ValidationError("AMMDelete: Asset2 must be a Currency")}u1.validateAMMDelete=oJ});var qI=q(d1=>{"use strict";y();Object.defineProperty(d1,"__esModule",{value:!0});d1.validateAMMVote=void 0;var pl=fe(),$I=G3(),Z3=de();function aJ(e){if((0,Z3.validateBaseTransaction)(e),e.Asset==null)throw new pl.ValidationError("AMMVote: missing field Asset");if(!(0,Z3.isIssuedCurrency)(e.Asset))throw new pl.ValidationError("AMMVote: Asset must be a Currency");if(e.Asset2==null)throw new pl.ValidationError("AMMVote: missing field Asset2");if(!(0,Z3.isIssuedCurrency)(e.Asset2))throw new pl.ValidationError("AMMVote: Asset2 must be a Currency");if(e.TradingFee==null)throw new pl.ValidationError("AMMVote: missing field TradingFee");if(typeof e.TradingFee!="number")throw new pl.ValidationError("AMMVote: TradingFee must be a number");if(e.TradingFee<0||e.TradingFee>$I.AMM_MAX_TRADING_FEE)throw new pl.ValidationError(`AMMVote: TradingFee must be between 0 and ${$I.AMM_MAX_TRADING_FEE}`)}d1.validateAMMVote=aJ});var HI=q(f1=>{"use strict";y();Object.defineProperty(f1,"__esModule",{value:!0});f1.validateCheckCancel=void 0;var sJ=fe(),cJ=de();function lJ(e){if((0,cJ.validateBaseTransaction)(e),e.CheckID!==void 0&&typeof e.CheckID!="string")throw new sJ.ValidationError("CheckCancel: invalid CheckID")}f1.validateCheckCancel=lJ});var VI=q(p1=>{"use strict";y();Object.defineProperty(p1,"__esModule",{value:!0});p1.validateCheckCash=void 0;var Vy=fe(),J3=de();function uJ(e){if((0,J3.validateBaseTransaction)(e),e.Amount==null&&e.DeliverMin==null)throw new Vy.ValidationError("CheckCash: must have either Amount or DeliverMin");if(e.Amount!=null&&e.DeliverMin!=null)throw new Vy.ValidationError("CheckCash: cannot have both Amount and DeliverMin");if(e.Amount!=null&&e.Amount!==void 0&&!(0,J3.isAmount)(e.Amount))throw new Vy.ValidationError("CheckCash: invalid Amount");if(e.DeliverMin!=null&&e.DeliverMin!==void 0&&!(0,J3.isAmount)(e.DeliverMin))throw new Vy.ValidationError("CheckCash: invalid DeliverMin");if(e.CheckID!==void 0&&typeof e.CheckID!="string")throw new Vy.ValidationError("CheckCash: invalid CheckID")}p1.validateCheckCash=uJ});var KI=q(h1=>{"use strict";y();Object.defineProperty(h1,"__esModule",{value:!0});h1.validateCheckCreate=void 0;var y1=fe(),Td=de();function dJ(e){if((0,Td.validateBaseTransaction)(e),e.SendMax===void 0)throw new y1.ValidationError("CheckCreate: missing field SendMax");if((0,Td.validateRequiredField)(e,"Destination",Td.isAccount),(0,Td.validateOptionalField)(e,"DestinationTag",Td.isNumber),typeof e.SendMax!="string"&&!(0,Td.isIssuedCurrencyAmount)(e.SendMax))throw new y1.ValidationError("CheckCreate: invalid SendMax");if(e.Expiration!==void 0&&typeof e.Expiration!="number")throw new y1.ValidationError("CheckCreate: invalid Expiration");if(e.InvoiceID!==void 0&&typeof e.InvoiceID!="string")throw new y1.ValidationError("CheckCreate: invalid InvoiceID")}h1.validateCheckCreate=dJ});var zI=q(m1=>{"use strict";y();Object.defineProperty(m1,"__esModule",{value:!0});m1.validateClawback=void 0;var Ky=fe(),yo=de();function fJ(e){if((0,yo.validateBaseTransaction)(e),(0,yo.validateRequiredField)(e,"Amount",yo.isClawbackAmount),(0,yo.validateOptionalField)(e,"Holder",yo.isAccount),!(0,yo.isIssuedCurrencyAmount)(e.Amount)&&!(0,yo.isMPTAmount)(e.Amount))throw new Ky.ValidationError("Clawback: invalid Amount");if((0,yo.isIssuedCurrencyAmount)(e.Amount)&&e.Account===e.Amount.issuer)throw new Ky.ValidationError("Clawback: invalid holder Account");if((0,yo.isMPTAmount)(e.Amount)&&e.Account===e.Holder)throw new Ky.ValidationError("Clawback: invalid holder Account");if((0,yo.isIssuedCurrencyAmount)(e.Amount)&&e.Holder)throw new Ky.ValidationError("Clawback: cannot have Holder for currency");if((0,yo.isMPTAmount)(e.Amount)&&!e.Holder)throw new Ky.ValidationError("Clawback: missing Holder")}m1.validateClawback=fJ});var XI=q(g1=>{"use strict";y();Object.defineProperty(g1,"__esModule",{value:!0});g1.validateConfidentialMPTClawback=void 0;var jI=fe(),Xo=de();function pJ(e){if((0,Xo.validateBaseTransaction)(e),(0,Xo.validateRequiredField)(e,"MPTokenIssuanceID",Xo.isString),!(0,Xo.isMPTIssuer)(e.Account,e.MPTokenIssuanceID))throw new jI.ValidationError("ConfidentialMPTClawback: Account must be the issuer of the MPTokenIssuanceID");if((0,Xo.validateRequiredField)(e,"Holder",Xo.isAccount),e.Account===e.Holder)throw new jI.ValidationError("ConfidentialMPTClawback: Holder and Account must be different");(0,Xo.validateConfidentialMPTAmount)(e,!1),(0,Xo.validateRequiredField)(e,"ZKProof",(0,Xo.isHexWithByteLength)(Xo.CONFIDENTIAL_CLAWBACK_PROOF_BYTES))}g1.validateConfidentialMPTClawback=pJ});var GI=q(w1=>{"use strict";y();Object.defineProperty(w1,"__esModule",{value:!0});w1.validateConfidentialMPTConvert=void 0;var WI=fe(),tn=de();function yJ(e){if(e.HolderEncryptionKey==null!=(e.ZKProof==null))throw new WI.ValidationError("ConfidentialMPTConvert: set HolderEncryptionKey and ZKProof together")}function hJ(e){if((0,tn.validateBaseTransaction)(e),(0,tn.validateRequiredField)(e,"MPTokenIssuanceID",tn.isString),(0,tn.isMPTIssuer)(e.Account,e.MPTokenIssuanceID))throw new WI.ValidationError("ConfidentialMPTConvert: the issuer cannot convert its own issuance");(0,tn.validateConfidentialMPTAmount)(e,!0),(0,tn.validateOptionalField)(e,"HolderEncryptionKey",(0,tn.isHexWithByteLength)(tn.CONFIDENTIAL_EC_POINT_BYTES)),(0,tn.validateRequiredField)(e,"HolderEncryptedAmount",(0,tn.isHexWithByteLength)(tn.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES)),(0,tn.validateRequiredField)(e,"IssuerEncryptedAmount",(0,tn.isHexWithByteLength)(tn.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES)),(0,tn.validateOptionalField)(e,"AuditorEncryptedAmount",(0,tn.isHexWithByteLength)(tn.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES)),(0,tn.validateRequiredField)(e,"BlindingFactor",(0,tn.isHexWithByteLength)(tn.CONFIDENTIAL_BLINDING_FACTOR_BYTES)),(0,tn.validateOptionalField)(e,"ZKProof",(0,tn.isHexWithByteLength)(tn.CONFIDENTIAL_CONVERT_PROOF_BYTES)),yJ(e)}w1.validateConfidentialMPTConvert=hJ});var YI=q(b1=>{"use strict";y();Object.defineProperty(b1,"__esModule",{value:!0});b1.validateConfidentialMPTConvertBack=void 0;var mJ=fe(),nn=de();function gJ(e){if((0,nn.validateBaseTransaction)(e),(0,nn.validateRequiredField)(e,"MPTokenIssuanceID",nn.isString),(0,nn.isMPTIssuer)(e.Account,e.MPTokenIssuanceID))throw new mJ.ValidationError("ConfidentialMPTConvertBack: the issuer cannot convert back its own issuance");(0,nn.validateConfidentialMPTAmount)(e,!1),(0,nn.validateRequiredField)(e,"HolderEncryptedAmount",(0,nn.isHexWithByteLength)(nn.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES)),(0,nn.validateRequiredField)(e,"IssuerEncryptedAmount",(0,nn.isHexWithByteLength)(nn.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES)),(0,nn.validateOptionalField)(e,"AuditorEncryptedAmount",(0,nn.isHexWithByteLength)(nn.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES)),(0,nn.validateRequiredField)(e,"BlindingFactor",(0,nn.isHexWithByteLength)(nn.CONFIDENTIAL_BLINDING_FACTOR_BYTES)),(0,nn.validateRequiredField)(e,"ZKProof",(0,nn.isHexWithByteLength)(nn.CONFIDENTIAL_CONVERT_BACK_PROOF_BYTES)),(0,nn.validateRequiredField)(e,"BalanceCommitment",(0,nn.isHexWithByteLength)(nn.CONFIDENTIAL_EC_POINT_BYTES))}b1.validateConfidentialMPTConvertBack=gJ});var ZI=q(v1=>{"use strict";y();Object.defineProperty(v1,"__esModule",{value:!0});v1.validateConfidentialMPTMergeInbox=void 0;var wJ=fe(),C1=de();function bJ(e){if((0,C1.validateBaseTransaction)(e),(0,C1.validateRequiredField)(e,"MPTokenIssuanceID",C1.isString),(0,C1.isMPTIssuer)(e.Account,e.MPTokenIssuanceID))throw new wJ.ValidationError("ConfidentialMPTMergeInbox: the issuer cannot merge its own issuance")}v1.validateConfidentialMPTMergeInbox=bJ});var JI=q(A1=>{"use strict";y();Object.defineProperty(A1,"__esModule",{value:!0});A1.validateConfidentialMPTSend=void 0;var Q3=fe(),Wt=de();function CJ(e){let t=(0,Wt.isHexWithByteLength)(Wt.CONFIDENTIAL_ELGAMAL_CIPHERTEXT_BYTES),n=(0,Wt.isHexWithByteLength)(Wt.CONFIDENTIAL_EC_POINT_BYTES);if((0,Wt.validateBaseTransaction)(e),(0,Wt.validateRequiredField)(e,"MPTokenIssuanceID",Wt.isString),(0,Wt.validateRequiredField)(e,"Destination",Wt.isAccount),e.Account===e.Destination)throw new Q3.ValidationError("ConfidentialMPTSend: Destination and Account must be different");if((0,Wt.isMPTIssuer)(e.Account,e.MPTokenIssuanceID))throw new Q3.ValidationError("ConfidentialMPTSend: the issuer cannot be the sender");if((0,Wt.isMPTIssuer)(e.Destination,e.MPTokenIssuanceID))throw new Q3.ValidationError("ConfidentialMPTSend: the issuer cannot be the destination");(0,Wt.validateOptionalField)(e,"DestinationTag",Wt.isNumber),(0,Wt.validateRequiredField)(e,"SenderEncryptedAmount",t),(0,Wt.validateRequiredField)(e,"DestinationEncryptedAmount",t),(0,Wt.validateRequiredField)(e,"IssuerEncryptedAmount",t),(0,Wt.validateOptionalField)(e,"AuditorEncryptedAmount",t),(0,Wt.validateRequiredField)(e,"ZKProof",(0,Wt.isHexWithByteLength)(Wt.CONFIDENTIAL_SEND_PROOF_BYTES)),(0,Wt.validateRequiredField)(e,"AmountCommitment",n),(0,Wt.validateRequiredField)(e,"BalanceCommitment",n),(0,Wt.validateCredentialsList)(e.CredentialIDs,e.TransactionType,!0,Wt.MAX_AUTHORIZED_CREDENTIALS)}A1.validateConfidentialMPTSend=CJ});var QI=q(S1=>{"use strict";y();Object.defineProperty(S1,"__esModule",{value:!0});S1.validateCredentialAccept=void 0;var Ed=de();function vJ(e){(0,Ed.validateBaseTransaction)(e),(0,Ed.validateRequiredField)(e,"Account",Ed.isString),(0,Ed.validateRequiredField)(e,"Issuer",Ed.isString),(0,Ed.validateCredentialType)(e)}S1.validateCredentialAccept=vJ});var tP=q(E1=>{"use strict";y();Object.defineProperty(E1,"__esModule",{value:!0});E1.validateCredentialCreate=void 0;var AJ=We(),T1=fe(),Ks=de(),eP=256;function SJ(e){(0,Ks.validateBaseTransaction)(e),(0,Ks.validateRequiredField)(e,"Account",Ks.isString),(0,Ks.validateRequiredField)(e,"Subject",Ks.isString),(0,Ks.validateCredentialType)(e),(0,Ks.validateOptionalField)(e,"Expiration",Ks.isNumber),TJ(e.URI)}E1.validateCredentialCreate=SJ;function TJ(e){if(e!==void 0){if(typeof e!="string")throw new T1.ValidationError("CredentialCreate: invalid field URI");if(e.length===0)throw new T1.ValidationError("CredentialCreate: URI cannot be an empty string");if(e.length>eP)throw new T1.ValidationError(`CredentialCreate: URI length must be <= ${eP}`);if(!AJ.HEX_REGEX.test(e))throw new T1.ValidationError("CredentialCreate: URI must be encoded in hex")}}});var nP=q(k1=>{"use strict";y();Object.defineProperty(k1,"__esModule",{value:!0});k1.validateCredentialDelete=void 0;var EJ=fe(),zs=de();function kJ(e){if((0,zs.validateBaseTransaction)(e),!e.Subject&&!e.Issuer)throw new EJ.ValidationError("CredentialDelete: either `Issuer` or `Subject` must be provided");(0,zs.validateRequiredField)(e,"Account",zs.isString),(0,zs.validateCredentialType)(e),(0,zs.validateOptionalField)(e,"Subject",zs.isString),(0,zs.validateOptionalField)(e,"Issuer",zs.isString)}k1.validateCredentialDelete=kJ});var iP=q(I1=>{"use strict";y();Object.defineProperty(I1,"__esModule",{value:!0});I1.validateDelegateSet=void 0;var yl=fe(),_1=de(),rP=10,_J=new Set(["AccountSet","SetRegularKey","SignerListSet","DelegateSet","AccountDelete","Batch","EnableAmendment","SetFee","UNLModify"]);function IJ(e){if((0,_1.validateBaseTransaction)(e),(0,_1.validateRequiredField)(e,"Authorize",_1.isAccount),e.Authorize===e.Account)throw new yl.ValidationError("DelegateSet: Authorize and Account must be different.");(0,_1.validateRequiredField)(e,"Permissions",Array.isArray);let t=e.Permissions;if(t.length>rP)throw new yl.ValidationError(`DelegateSet: Permissions array length cannot be greater than ${rP}.`);let n=new Set;if(t.forEach(r=>{if(r==null||Object.keys(r).length!==1||r.Permission==null||Object.keys(r.Permission).length!==1)throw new yl.ValidationError("DelegateSet: Permissions array element is malformed");let i=r.Permission.PermissionValue;if(i==null)throw new yl.ValidationError("DelegateSet: PermissionValue must be defined");if(typeof i!="string")throw new yl.ValidationError("DelegateSet: PermissionValue must be a string");if(_J.has(i))throw new yl.ValidationError(`DelegateSet: PermissionValue contains a non-delegatable transaction ${i}`);n.add(i)}),t.length!==n.size)throw new yl.ValidationError("DelegateSet: Permissions array cannot contain duplicate values")}I1.validateDelegateSet=IJ});var aP=q(P1=>{"use strict";y();Object.defineProperty(P1,"__esModule",{value:!0});P1.validateDepositPreauth=void 0;var eS=fe(),js=de();function oP(e,t){let n=e[t];if(!(0,js.isString)(n))throw new eS.ValidationError(`DepositPreauth: ${t} must be a string`);if((0,js.isString)(e.Account)&&(0,js.areAddressesEqual)(e.Account,n)){let r=t==="Authorize"?"preauthorize":"unauthorize";throw new eS.ValidationError(`DepositPreauth: Account can't ${r} its own address`)}}function PJ(e){(0,js.validateBaseTransaction)(e),xJ(e),e.Authorize!==void 0?oP(e,"Authorize"):e.Unauthorize!==void 0?oP(e,"Unauthorize"):e.AuthorizeCredentials!==void 0?(0,js.validateCredentialsList)(e.AuthorizeCredentials,e.TransactionType,!1,js.MAX_AUTHORIZED_CREDENTIALS):e.UnauthorizeCredentials!==void 0&&(0,js.validateCredentialsList)(e.UnauthorizeCredentials,e.TransactionType,!1,js.MAX_AUTHORIZED_CREDENTIALS)}P1.validateDepositPreauth=PJ;function xJ(e){if(["Authorize","Unauthorize","AuthorizeCredentials","UnauthorizeCredentials"].filter(r=>e[r]!==void 0).length!==1)throw new eS.ValidationError("DepositPreauth: Requires exactly one field of the following: Authorize, Unauthorize, AuthorizeCredentials, UnauthorizeCredentials.")}});var sP=q(x1=>{"use strict";y();Object.defineProperty(x1,"__esModule",{value:!0});x1.validateDIDDelete=void 0;var MJ=de();function OJ(e){(0,MJ.validateBaseTransaction)(e)}x1.validateDIDDelete=OJ});var cP=q(M1=>{"use strict";y();Object.defineProperty(M1,"__esModule",{value:!0});M1.validateDIDSet=void 0;var DJ=fe(),hl=de();function RJ(e){if((0,hl.validateBaseTransaction)(e),(0,hl.validateOptionalField)(e,"Data",hl.isString),(0,hl.validateOptionalField)(e,"DIDDocument",hl.isString),(0,hl.validateOptionalField)(e,"URI",hl.isString),e.Data===void 0&&e.DIDDocument===void 0&&e.URI===void 0)throw new DJ.ValidationError("DIDSet: Must have at least one of `Data`, `DIDDocument`, and `URI`")}M1.validateDIDSet=RJ});var uP=q(O1=>{"use strict";y();Object.defineProperty(O1,"__esModule",{value:!0});O1.validateEscrowCancel=void 0;var lP=fe(),tS=de();function NJ(e){if((0,tS.validateBaseTransaction)(e),(0,tS.validateRequiredField)(e,"Owner",tS.isAccount),e.OfferSequence==null)throw new lP.ValidationError("EscrowCancel: missing OfferSequence");if(typeof e.OfferSequence!="number"&&typeof e.OfferSequence!="string"||Number.isNaN(Number(e.OfferSequence)))throw new lP.ValidationError("EscrowCancel: OfferSequence must be a number")}O1.validateEscrowCancel=NJ});var dP=q(D1=>{"use strict";y();Object.defineProperty(D1,"__esModule",{value:!0});D1.validateEscrowCreate=void 0;var zy=fe(),ml=de();function LJ(e){if((0,ml.validateBaseTransaction)(e),(0,ml.validateRequiredField)(e,"Amount",ml.isAmount),(0,ml.validateRequiredField)(e,"Destination",ml.isAccount),(0,ml.validateOptionalField)(e,"DestinationTag",ml.isNumber),e.CancelAfter===void 0&&e.FinishAfter===void 0)throw new zy.ValidationError("EscrowCreate: Either CancelAfter or FinishAfter must be specified");if(e.FinishAfter===void 0&&e.Condition===void 0)throw new zy.ValidationError("EscrowCreate: Either Condition or FinishAfter must be specified");if(e.CancelAfter!==void 0&&typeof e.CancelAfter!="number")throw new zy.ValidationError("EscrowCreate: CancelAfter must be a number");if(e.FinishAfter!==void 0&&typeof e.FinishAfter!="number")throw new zy.ValidationError("EscrowCreate: FinishAfter must be a number");if(e.Condition!==void 0&&typeof e.Condition!="string")throw new zy.ValidationError("EscrowCreate: Condition must be a string")}D1.validateEscrowCreate=LJ});var fP=q(N1=>{"use strict";y();Object.defineProperty(N1,"__esModule",{value:!0});N1.validateEscrowFinish=void 0;var R1=fe(),jy=de();function BJ(e){if((0,jy.validateBaseTransaction)(e),(0,jy.validateRequiredField)(e,"Owner",jy.isAccount),(0,jy.validateCredentialsList)(e.CredentialIDs,e.TransactionType,!0,jy.MAX_AUTHORIZED_CREDENTIALS),e.OfferSequence==null)throw new R1.ValidationError("EscrowFinish: missing field OfferSequence");if(typeof e.OfferSequence!="number"&&typeof e.OfferSequence!="string"||Number.isNaN(Number(e.OfferSequence)))throw new R1.ValidationError("EscrowFinish: OfferSequence must be a number");if(e.Condition!==void 0&&typeof e.Condition!="string")throw new R1.ValidationError("EscrowFinish: Condition must be a string");if(e.Fulfillment!==void 0&&typeof e.Fulfillment!="string")throw new R1.ValidationError("EscrowFinish: Fulfillment must be a string")}N1.validateEscrowFinish=BJ});var pP=q(_d=>{"use strict";y();var FJ=_d&&_d.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_d,"__esModule",{value:!0});_d.validateLoanBrokerCoverClawback=void 0;var UJ=FJ(Sn()),nS=fe(),kd=de();function $J(e){if((0,kd.validateBaseTransaction)(e),(0,kd.validateOptionalField)(e,"LoanBrokerID",kd.isString),(0,kd.validateOptionalField)(e,"Amount",kd.isTokenAmount),e.LoanBrokerID!=null&&!(0,kd.isLedgerEntryId)(e.LoanBrokerID))throw new nS.ValidationError("LoanBrokerCoverClawback: LoanBrokerID must be 64 characters hexadecimal string");if(e.Amount!=null&&new UJ.default(e.Amount.value).isLessThan(0))throw new nS.ValidationError("LoanBrokerCoverClawback: Amount must be >= 0");if(e.LoanBrokerID==null&&e.Amount==null)throw new nS.ValidationError("LoanBrokerCoverClawback: Either LoanBrokerID or Amount is required")}_d.validateLoanBrokerCoverClawback=$J});var yP=q(L1=>{"use strict";y();Object.defineProperty(L1,"__esModule",{value:!0});L1.validateLoanBrokerCoverDeposit=void 0;var qJ=fe(),Id=de();function HJ(e){if((0,Id.validateBaseTransaction)(e),(0,Id.validateRequiredField)(e,"LoanBrokerID",Id.isString),(0,Id.validateRequiredField)(e,"Amount",Id.isAmount),!(0,Id.isLedgerEntryId)(e.LoanBrokerID))throw new qJ.ValidationError("LoanBrokerCoverDeposit: LoanBrokerID must be 64 characters hexadecimal string")}L1.validateLoanBrokerCoverDeposit=HJ});var hP=q(B1=>{"use strict";y();Object.defineProperty(B1,"__esModule",{value:!0});B1.validateLoanBrokerCoverWithdraw=void 0;var VJ=fe(),Pi=de();function KJ(e){if((0,Pi.validateBaseTransaction)(e),(0,Pi.validateRequiredField)(e,"LoanBrokerID",Pi.isString),(0,Pi.validateRequiredField)(e,"Amount",Pi.isAmount),(0,Pi.validateOptionalField)(e,"Destination",Pi.isAccount),(0,Pi.validateOptionalField)(e,"DestinationTag",Pi.isNumber),(0,Pi.validateCredentialsList)(e.CredentialIDs,e.TransactionType,!0,Pi.MAX_AUTHORIZED_CREDENTIALS),!(0,Pi.isLedgerEntryId)(e.LoanBrokerID))throw new VJ.ValidationError("LoanBrokerCoverWithdraw: LoanBrokerID must be 64 characters hexadecimal string")}B1.validateLoanBrokerCoverWithdraw=KJ});var mP=q(U1=>{"use strict";y();Object.defineProperty(U1,"__esModule",{value:!0});U1.validateLoanBrokerDelete=void 0;var zJ=fe(),F1=de();function jJ(e){if((0,F1.validateBaseTransaction)(e),(0,F1.validateRequiredField)(e,"LoanBrokerID",F1.isString),!(0,F1.isLedgerEntryId)(e.LoanBrokerID))throw new zJ.ValidationError("LoanBrokerDelete: LoanBrokerID must be 64 characters hexadecimal string")}U1.validateLoanBrokerDelete=jJ});var vP=q(Pd=>{"use strict";y();var XJ=Pd&&Pd.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Pd,"__esModule",{value:!0});Pd.validateLoanBrokerSet=void 0;var WJ=XJ(Sn()),Xs=fe(),Ln=de(),gP=512,wP=1e4,bP=1e5,CP=1e5;function GJ(e){var t,n;if((0,Ln.validateBaseTransaction)(e),(0,Ln.validateRequiredField)(e,"VaultID",Ln.isString),(0,Ln.validateOptionalField)(e,"LoanBrokerID",Ln.isString),(0,Ln.validateOptionalField)(e,"Data",Ln.isString),(0,Ln.validateOptionalField)(e,"ManagementFeeRate",Ln.isNumber),(0,Ln.validateOptionalField)(e,"DebtMaximum",Ln.isXRPLNumber),(0,Ln.validateOptionalField)(e,"CoverRateMinimum",Ln.isNumber),(0,Ln.validateOptionalField)(e,"CoverRateLiquidation",Ln.isNumber),!(0,Ln.isLedgerEntryId)(e.VaultID))throw new Xs.ValidationError("LoanBrokerSet: VaultID must be 64 characters hexadecimal string");if(e.LoanBrokerID!=null&&!(0,Ln.isLedgerEntryId)(e.LoanBrokerID))throw new Xs.ValidationError("LoanBrokerSet: LoanBrokerID must be 64 characters hexadecimal string");if(e.Data!=null&&!(0,Ln.validateHexMetadata)(e.Data,gP))throw new Xs.ValidationError(`LoanBrokerSet: Data must be a valid non-empty hex string up to ${gP} characters`);if(e.ManagementFeeRate!=null&&(e.ManagementFeeRate<0||e.ManagementFeeRate>wP))throw new Xs.ValidationError(`LoanBrokerSet: ManagementFeeRate must be between 0 and ${wP} inclusive`);if(e.DebtMaximum!=null&&new WJ.default(e.DebtMaximum).isLessThan(0))throw new Xs.ValidationError("LoanBrokerSet: DebtMaximum must be a non-negative value");if(e.CoverRateMinimum!=null&&(e.CoverRateMinimum<0||e.CoverRateMinimum>bP))throw new Xs.ValidationError(`LoanBrokerSet: CoverRateMinimum must be between 0 and ${bP} inclusive`);if(e.CoverRateLiquidation!=null&&(e.CoverRateLiquidation<0||e.CoverRateLiquidation>CP))throw new Xs.ValidationError(`LoanBrokerSet: CoverRateLiquidation must be between 0 and ${CP} inclusive`);let r=(t=e.CoverRateMinimum)!==null&&t!==void 0?t:0,i=(n=e.CoverRateLiquidation)!==null&&n!==void 0?n:0;if(r===0&&i!==0||r!==0&&i===0)throw new Xs.ValidationError("LoanBrokerSet: CoverRateMinimum and CoverRateLiquidation must both be zero or both be non-zero")}Pd.validateLoanBrokerSet=GJ});var AP=q(q1=>{"use strict";y();Object.defineProperty(q1,"__esModule",{value:!0});q1.validateLoanDelete=void 0;var YJ=fe(),$1=de();function ZJ(e){if((0,$1.validateBaseTransaction)(e),(0,$1.validateRequiredField)(e,"LoanID",$1.isString),!(0,$1.isLedgerEntryId)(e.LoanID))throw new YJ.ValidationError("LoanDelete: LoanID must be 64 characters hexadecimal string")}q1.validateLoanDelete=ZJ});var rS=q(xd=>{"use strict";y();Object.defineProperty(xd,"__esModule",{value:!0});xd.validateLoanSet=xd.LoanSetFlags=void 0;var qa=fe(),et=de(),SP=512,TP=1e5,EP=1e5,kP=1e5,_P=1e5,IP=1e5,PP=60,xP;(function(e){e[e.tfLoanOverpayment=65536]="tfLoanOverpayment"})(xP||(xd.LoanSetFlags=xP={}));function JJ(e){if((0,et.validateBaseTransaction)(e),(0,et.validateRequiredField)(e,"LoanBrokerID",et.isString),(0,et.validateRequiredField)(e,"PrincipalRequested",et.isXRPLNumber),(0,et.validateOptionalField)(e,"CounterpartySignature",et.isRecord),(0,et.validateOptionalField)(e,"Data",et.isString),(0,et.validateOptionalField)(e,"Counterparty",et.isAccount),(0,et.validateOptionalField)(e,"LoanOriginationFee",et.isXRPLNumber),(0,et.validateOptionalField)(e,"LoanServiceFee",et.isXRPLNumber),(0,et.validateOptionalField)(e,"LatePaymentFee",et.isXRPLNumber),(0,et.validateOptionalField)(e,"ClosePaymentFee",et.isXRPLNumber),(0,et.validateOptionalField)(e,"OverpaymentFee",et.isNumber),(0,et.validateOptionalField)(e,"InterestRate",et.isNumber),(0,et.validateOptionalField)(e,"LateInterestRate",et.isNumber),(0,et.validateOptionalField)(e,"CloseInterestRate",et.isNumber),(0,et.validateOptionalField)(e,"OverpaymentInterestRate",et.isNumber),(0,et.validateOptionalField)(e,"PaymentTotal",et.isNumber),(0,et.validateOptionalField)(e,"PaymentInterval",et.isNumber),(0,et.validateOptionalField)(e,"GracePeriod",et.isNumber),!(0,et.isLedgerEntryId)(e.LoanBrokerID))throw new qa.ValidationError("LoanSet: LoanBrokerID must be 64 characters hexadecimal string");if(e.Data!=null&&!(0,et.validateHexMetadata)(e.Data,SP))throw new qa.ValidationError(`LoanSet: Data must be a valid non-empty hex string up to ${SP} characters`);if(e.OverpaymentFee!=null&&(e.OverpaymentFee<0||e.OverpaymentFee>TP))throw new qa.ValidationError(`LoanSet: OverpaymentFee must be between 0 and ${TP} inclusive`);if(e.InterestRate!=null&&(e.InterestRate<0||e.InterestRate>EP))throw new qa.ValidationError(`LoanSet: InterestRate must be between 0 and ${EP} inclusive`);if(e.LateInterestRate!=null&&(e.LateInterestRate<0||e.LateInterestRate>kP))throw new qa.ValidationError(`LoanSet: LateInterestRate must be between 0 and ${kP} inclusive`);if(e.CloseInterestRate!=null&&(e.CloseInterestRate<0||e.CloseInterestRate>_P))throw new qa.ValidationError(`LoanSet: CloseInterestRate must be between 0 and ${_P} inclusive`);if(e.OverpaymentInterestRate!=null&&(e.OverpaymentInterestRate<0||e.OverpaymentInterestRate>IP))throw new qa.ValidationError(`LoanSet: OverpaymentInterestRate must be between 0 and ${IP} inclusive`);if(e.PaymentInterval!=null&&e.PaymentIntervale.PaymentInterval)throw new qa.ValidationError("LoanSet: GracePeriod must not be greater than PaymentInterval")}xd.validateLoanSet=JJ});var MP=q(H1=>{"use strict";y();Object.defineProperty(H1,"__esModule",{value:!0});H1.validateMPTokenIssuanceDestroy=void 0;var iS=de();function QJ(e){(0,iS.validateBaseTransaction)(e),(0,iS.validateRequiredField)(e,"MPTokenIssuanceID",iS.isString)}H1.validateMPTokenIssuanceDestroy=QJ});var DP=q(K1=>{"use strict";y();Object.defineProperty(K1,"__esModule",{value:!0});K1.validateNFTokenAcceptOffer=void 0;var V1=fe(),OP=de();function eQ(e){let t=(0,OP.parseAmountValue)(e.NFTokenBrokerFee);if(Number.isNaN(t))throw new V1.ValidationError("NFTokenAcceptOffer: invalid NFTokenBrokerFee");if(t<=0)throw new V1.ValidationError("NFTokenAcceptOffer: NFTokenBrokerFee must be greater than 0; omit if there is no fee");if(e.NFTokenSellOffer==null||e.NFTokenBuyOffer==null)throw new V1.ValidationError("NFTokenAcceptOffer: both NFTokenSellOffer and NFTokenBuyOffer must be set if using brokered mode")}function tQ(e){if((0,OP.validateBaseTransaction)(e),e.NFTokenBrokerFee!=null&&eQ(e),e.NFTokenSellOffer==null&&e.NFTokenBuyOffer==null)throw new V1.ValidationError("NFTokenAcceptOffer: must set either NFTokenSellOffer or NFTokenBuyOffer")}K1.validateNFTokenAcceptOffer=tQ});var RP=q(z1=>{"use strict";y();Object.defineProperty(z1,"__esModule",{value:!0});z1.validateNFTokenBurn=void 0;var Xy=de();function nQ(e){(0,Xy.validateBaseTransaction)(e),(0,Xy.validateRequiredField)(e,"NFTokenID",Xy.isString),(0,Xy.validateOptionalField)(e,"Owner",Xy.isAccount)}z1.validateNFTokenBurn=nQ});var BP=q(j1=>{"use strict";y();Object.defineProperty(j1,"__esModule",{value:!0});j1.validateNFTokenCancelOffer=void 0;var NP=fe(),LP=de();function rQ(e){if((0,LP.validateBaseTransaction)(e),!(0,LP.isArray)(e.NFTokenOffers))throw new NP.ValidationError("NFTokenCancelOffer: missing field NFTokenOffers");if(e.NFTokenOffers.length<1)throw new NP.ValidationError("NFTokenCancelOffer: empty field NFTokenOffers")}j1.validateNFTokenCancelOffer=rQ});var oS=q(X1=>{"use strict";y();Object.defineProperty(X1,"__esModule",{value:!0});X1.validateNFTokenModify=void 0;var FP=fe(),iQ=hn(),gl=de();function oQ(e){if((0,gl.validateBaseTransaction)(e),(0,gl.validateRequiredField)(e,"NFTokenID",gl.isString),(0,gl.validateOptionalField)(e,"Owner",gl.isAccount),(0,gl.validateOptionalField)(e,"URI",gl.isString),e.URI!==void 0&&typeof e.URI=="string"){if(e.URI==="")throw new FP.ValidationError("NFTokenModify: URI must not be empty string");if(!(0,iQ.isHex)(e.URI))throw new FP.ValidationError("NFTokenModify: URI must be in hex format")}}X1.validateNFTokenModify=oQ});var $P=q(W1=>{"use strict";y();Object.defineProperty(W1,"__esModule",{value:!0});W1.validateOfferCancel=void 0;var UP=fe(),aQ=de();function sQ(e){if((0,aQ.validateBaseTransaction)(e),e.OfferSequence===void 0)throw new UP.ValidationError("OfferCancel: missing field OfferSequence");if(typeof e.OfferSequence!="number")throw new UP.ValidationError("OfferCancel: OfferSequence must be a number")}W1.validateOfferCancel=sQ});var qP=q(G1=>{"use strict";y();Object.defineProperty(G1,"__esModule",{value:!0});G1.validateOracleDelete=void 0;var aS=de();function cQ(e){(0,aS.validateBaseTransaction)(e),(0,aS.validateRequiredField)(e,"OracleDocumentID",aS.isNumber)}G1.validateOracleDelete=cQ});var jP=q(Y1=>{"use strict";y();Object.defineProperty(Y1,"__esModule",{value:!0});Y1.validateOracleSet=void 0;var oi=fe(),lQ=hn(),zn=de(),HP=10,VP=10,KP=1,zP=16;function uQ(e){(0,zn.validateBaseTransaction)(e),(0,zn.validateRequiredField)(e,"OracleDocumentID",zn.isNumber),(0,zn.validateRequiredField)(e,"LastUpdateTime",zn.isNumber),(0,zn.validateOptionalField)(e,"Provider",zn.isString),(0,zn.validateOptionalField)(e,"URI",zn.isString),(0,zn.validateOptionalField)(e,"AssetClass",zn.isString),(0,zn.validateRequiredField)(e,"PriceDataSeries",t=>{if(!(0,zn.isArray)(t))throw new oi.ValidationError("OracleSet: PriceDataSeries must be an array");if(t.length>HP)throw new oi.ValidationError(`OracleSet: PriceDataSeries must have at most ${HP} PriceData objects`);for(let n of t){if(!(0,zn.isRecord)(n))throw new oi.ValidationError("OracleSet: PriceDataSeries must be an array of objects");let r=n.PriceData;if(!(0,zn.isRecord)(r))throw new oi.ValidationError("OracleSet: PriceDataSeries must have a `PriceData` object");if(Object.keys(n).length!==1)throw new oi.ValidationError("OracleSet: PriceDataSeries must only have a single PriceData object");if(r.BaseAsset==null||typeof r.BaseAsset!="string")throw new oi.ValidationError("OracleSet: PriceDataSeries must have a `BaseAsset` string");if(typeof r.QuoteAsset!="string")throw new oi.ValidationError("OracleSet: PriceDataSeries must have a `QuoteAsset` string");if(r.AssetPrice==null!=(r.Scale==null))throw new oi.ValidationError("OracleSet: PriceDataSeries must have both `AssetPrice` and `Scale` if any are present");if("AssetPrice"in r&&!(0,zn.isNumber)(r.AssetPrice)){if(typeof r.AssetPrice!="string")throw new oi.ValidationError("OracleSet: Field AssetPrice must be a string or a number");if(!(0,lQ.isHex)(r.AssetPrice))throw new oi.ValidationError("OracleSet: Field AssetPrice must be a valid hex string");if(r.AssetPrice.lengthzP)throw new oi.ValidationError(`OracleSet: Length of AssetPrice field must be between ${KP} and ${zP} characters long`)}if("Scale"in r){if(!(0,zn.isNumber)(r.Scale))throw new oi.ValidationError("OracleSet: invalid field Scale");if(r.Scale<0||r.Scale>VP)throw new oi.ValidationError(`OracleSet: Scale must be in range 0-${VP}`)}}return!0})}Y1.validateOracleSet=uQ});var XP=q(Z1=>{"use strict";y();Object.defineProperty(Z1,"__esModule",{value:!0});Z1.validatePaymentChannelCreate=void 0;var wl=fe(),Wy=de();function dQ(e){if((0,Wy.validateBaseTransaction)(e),e.Amount===void 0)throw new wl.ValidationError("PaymentChannelCreate: missing Amount");if(typeof e.Amount!="string")throw new wl.ValidationError("PaymentChannelCreate: Amount must be a string");if((0,Wy.validateRequiredField)(e,"Destination",Wy.isAccount),(0,Wy.validateOptionalField)(e,"DestinationTag",Wy.isNumber),e.SettleDelay===void 0)throw new wl.ValidationError("PaymentChannelCreate: missing SettleDelay");if(typeof e.SettleDelay!="number")throw new wl.ValidationError("PaymentChannelCreate: SettleDelay must be a number");if(e.PublicKey===void 0)throw new wl.ValidationError("PaymentChannelCreate: missing PublicKey");if(typeof e.PublicKey!="string")throw new wl.ValidationError("PaymentChannelCreate: PublicKey must be a string");if(e.CancelAfter!==void 0&&typeof e.CancelAfter!="number")throw new wl.ValidationError("PaymentChannelCreate: CancelAfter must be a number")}Z1.validatePaymentChannelCreate=dQ});var WP=q(J1=>{"use strict";y();Object.defineProperty(J1,"__esModule",{value:!0});J1.validatePaymentChannelFund=void 0;var Gy=fe(),fQ=de();function pQ(e){if((0,fQ.validateBaseTransaction)(e),e.Channel===void 0)throw new Gy.ValidationError("PaymentChannelFund: missing Channel");if(typeof e.Channel!="string")throw new Gy.ValidationError("PaymentChannelFund: Channel must be a string");if(e.Amount===void 0)throw new Gy.ValidationError("PaymentChannelFund: missing Amount");if(typeof e.Amount!="string")throw new Gy.ValidationError("PaymentChannelFund: Amount must be a string");if(e.Expiration!==void 0&&typeof e.Expiration!="number")throw new Gy.ValidationError("PaymentChannelFund: Expiration must be a number")}J1.validatePaymentChannelFund=pQ});var GP=q(Q1=>{"use strict";y();Object.defineProperty(Q1,"__esModule",{value:!0});Q1.validatePermissionedDomainDelete=void 0;var sS=de();function yQ(e){(0,sS.validateBaseTransaction)(e),(0,sS.validateRequiredField)(e,"DomainID",sS.isString)}Q1.validatePermissionedDomainDelete=yQ});var YP=q(ew=>{"use strict";y();Object.defineProperty(ew,"__esModule",{value:!0});ew.validatePermissionedDomainSet=void 0;var Md=de(),hQ=10;function mQ(e){(0,Md.validateBaseTransaction)(e),(0,Md.validateOptionalField)(e,"DomainID",Md.isString),(0,Md.validateRequiredField)(e,"AcceptedCredentials",Md.isArray),(0,Md.validateCredentialsList)(e.AcceptedCredentials,e.TransactionType,!1,hQ)}ew.validatePermissionedDomainSet=mQ});var ZP=q(tw=>{"use strict";y();Object.defineProperty(tw,"__esModule",{value:!0});tw.validateSetRegularKey=void 0;var gQ=fe(),wQ=de();function bQ(e){if((0,wQ.validateBaseTransaction)(e),e.RegularKey!==void 0&&typeof e.RegularKey!="string")throw new gQ.ValidationError("SetRegularKey: RegularKey must be a string")}tw.validateSetRegularKey=bQ});var QP=q(rw=>{"use strict";y();Object.defineProperty(rw,"__esModule",{value:!0});rw.validateSignerListSet=void 0;var nw=fe(),Ws=de(),JP=32,CQ=/^[0-9A-Fa-f]{64}$/u;function vQ(e){if((0,Ws.validateBaseTransaction)(e),(0,Ws.validateRequiredField)(e,"SignerQuorum",Ws.isNumber),e.SignerQuorum!==0){if((0,Ws.validateRequiredField)(e,"SignerEntries",Ws.isArray),e.SignerEntries.length===0)throw new nw.ValidationError("SignerListSet: need at least 1 member in SignerEntries");if(e.SignerEntries.length>JP)throw new nw.ValidationError(`SignerListSet: maximum of ${JP} members allowed in SignerEntries`);for(let t of e.SignerEntries){if(!(0,Ws.isRecord)(t)||!(0,Ws.isRecord)(t.SignerEntry))throw new nw.ValidationError("SignerListSet: SignerEntries must be an array of SignerEntry objects");let n=t.SignerEntry,{WalletLocator:r}=n;if(r!=null&&(!(0,Ws.isString)(r)||!CQ.test(r)))throw new nw.ValidationError("SignerListSet: WalletLocator in SignerEntry must be a 256-bit (32-byte) hexadecimal value")}}}rw.validateSignerListSet=vQ});var e7=q(iw=>{"use strict";y();Object.defineProperty(iw,"__esModule",{value:!0});iw.validateTicketCreate=void 0;var cS=fe(),AQ=de(),SQ=250;function TQ(e){(0,AQ.validateBaseTransaction)(e);let{TicketCount:t}=e;if(t===void 0)throw new cS.ValidationError("TicketCreate: missing field TicketCount");if(typeof t!="number")throw new cS.ValidationError("TicketCreate: TicketCount must be a number");if(!Number.isInteger(t)||t<1||t>SQ)throw new cS.ValidationError("TicketCreate: TicketCount must be an integer from 1 to 250")}iw.validateTicketCreate=TQ});var t7=q(ow=>{"use strict";y();Object.defineProperty(ow,"__esModule",{value:!0});ow.validateVaultClawback=void 0;var bl=de();function EQ(e){(0,bl.validateBaseTransaction)(e),(0,bl.validateRequiredField)(e,"VaultID",bl.isString),(0,bl.validateRequiredField)(e,"Holder",bl.isAccount),(0,bl.validateOptionalField)(e,"Amount",bl.isClawbackAmount)}ow.validateVaultClawback=EQ});var r7=q(aw=>{"use strict";y();Object.defineProperty(aw,"__esModule",{value:!0});aw.validateVaultDelete=void 0;var n7=fe(),kQ=hn(),Cl=de();function _Q(e){if((0,Cl.validateBaseTransaction)(e),(0,Cl.validateRequiredField)(e,"VaultID",Cl.isString),(0,Cl.validateOptionalField)(e,"MemoData",Cl.isString),e.MemoData!==void 0){let t=e.MemoData;if(!(0,kQ.isHex)(t)||t.length%2!==0)throw new n7.ValidationError("VaultDelete: MemoData must be a hex string with an even number of characters");if(t.length/2>Cl.VAULT_DATA_MAX_BYTE_LENGTH)throw new n7.ValidationError(`VaultDelete: MemoData must not exceed ${Cl.VAULT_DATA_MAX_BYTE_LENGTH} bytes`)}}aw.validateVaultDelete=_Q});var i7=q(sw=>{"use strict";y();Object.defineProperty(sw,"__esModule",{value:!0});sw.validateVaultDeposit=void 0;var Yy=de();function IQ(e){(0,Yy.validateBaseTransaction)(e),(0,Yy.validateRequiredField)(e,"VaultID",Yy.isString),(0,Yy.validateRequiredField)(e,"Amount",Yy.isAmount)}sw.validateVaultDeposit=IQ});var a7=q(cw=>{"use strict";y();Object.defineProperty(cw,"__esModule",{value:!0});cw.validateVaultSet=void 0;var o7=fe(),PQ=hn(),ho=de();function xQ(e){if((0,ho.validateBaseTransaction)(e),(0,ho.validateRequiredField)(e,"VaultID",ho.isString),(0,ho.validateOptionalField)(e,"Data",ho.isString),(0,ho.validateOptionalField)(e,"AssetsMaximum",ho.isXRPLNumber),(0,ho.validateOptionalField)(e,"DomainID",ho.isString),e.Data!==void 0){let t=e.Data;if(!(0,PQ.isHex)(t))throw new o7.ValidationError("VaultSet: Data must be a valid hex string");let n=t.length/2;if(n>ho.VAULT_DATA_MAX_BYTE_LENGTH)throw new o7.ValidationError(`VaultSet: Data exceeds ${ho.VAULT_DATA_MAX_BYTE_LENGTH} bytes (actual: ${n})`)}}cw.validateVaultSet=xQ});var s7=q(lw=>{"use strict";y();Object.defineProperty(lw,"__esModule",{value:!0});lw.validateVaultWithdraw=void 0;var mo=de();function MQ(e){(0,mo.validateBaseTransaction)(e),(0,mo.validateRequiredField)(e,"VaultID",mo.isString),(0,mo.validateRequiredField)(e,"Amount",mo.isAmount),(0,mo.validateOptionalField)(e,"Destination",mo.isAccount),(0,mo.validateOptionalField)(e,"DestinationTag",mo.isNumber),(0,mo.validateCredentialsList)(e.CredentialIDs,e.TransactionType,!0,mo.MAX_AUTHORIZED_CREDENTIALS)}lw.validateVaultWithdraw=MQ});var c7=q(uw=>{"use strict";y();Object.defineProperty(uw,"__esModule",{value:!0});uw.validateXChainAccountCreateCommit=void 0;var Ha=de();function OQ(e){(0,Ha.validateBaseTransaction)(e),(0,Ha.validateRequiredField)(e,"XChainBridge",Ha.isXChainBridge),(0,Ha.validateRequiredField)(e,"SignatureReward",Ha.isAmount),(0,Ha.validateRequiredField)(e,"Destination",Ha.isAccount),(0,Ha.validateRequiredField)(e,"Amount",Ha.isAmount)}uw.validateXChainAccountCreateCommit=OQ});var l7=q(dw=>{"use strict";y();Object.defineProperty(dw,"__esModule",{value:!0});dw.validateXChainAddAccountCreateAttestation=void 0;var rn=de();function DQ(e){(0,rn.validateBaseTransaction)(e),(0,rn.validateRequiredField)(e,"Amount",rn.isAmount),(0,rn.validateRequiredField)(e,"AttestationRewardAccount",rn.isAccount),(0,rn.validateRequiredField)(e,"AttestationSignerAccount",rn.isAccount),(0,rn.validateRequiredField)(e,"Destination",rn.isAccount),(0,rn.validateRequiredField)(e,"OtherChainSource",rn.isAccount),(0,rn.validateRequiredField)(e,"PublicKey",rn.isString),(0,rn.validateRequiredField)(e,"Signature",rn.isString),(0,rn.validateRequiredField)(e,"SignatureReward",rn.isAmount),(0,rn.validateRequiredField)(e,"WasLockingChainSend",t=>t===0||t===1),(0,rn.validateRequiredField)(e,"XChainAccountCreateCount",t=>(0,rn.isNumber)(t)||(0,rn.isString)(t)),(0,rn.validateRequiredField)(e,"XChainBridge",rn.isXChainBridge)}dw.validateXChainAddAccountCreateAttestation=DQ});var u7=q(fw=>{"use strict";y();Object.defineProperty(fw,"__esModule",{value:!0});fw.validateXChainAddClaimAttestation=void 0;var mn=de();function RQ(e){(0,mn.validateBaseTransaction)(e),(0,mn.validateRequiredField)(e,"Amount",mn.isAmount),(0,mn.validateRequiredField)(e,"AttestationRewardAccount",mn.isAccount),(0,mn.validateRequiredField)(e,"AttestationSignerAccount",mn.isAccount),(0,mn.validateOptionalField)(e,"Destination",mn.isAccount),(0,mn.validateRequiredField)(e,"OtherChainSource",mn.isAccount),(0,mn.validateRequiredField)(e,"PublicKey",mn.isString),(0,mn.validateRequiredField)(e,"Signature",mn.isString),(0,mn.validateRequiredField)(e,"WasLockingChainSend",t=>t===0||t===1),(0,mn.validateRequiredField)(e,"XChainBridge",mn.isXChainBridge),(0,mn.validateRequiredField)(e,"XChainClaimID",t=>(0,mn.isNumber)(t)||(0,mn.isString)(t))}fw.validateXChainAddClaimAttestation=RQ});var d7=q(pw=>{"use strict";y();Object.defineProperty(pw,"__esModule",{value:!0});pw.validateXChainClaim=void 0;var xi=de();function NQ(e){(0,xi.validateBaseTransaction)(e),(0,xi.validateRequiredField)(e,"XChainBridge",xi.isXChainBridge),(0,xi.validateRequiredField)(e,"XChainClaimID",t=>(0,xi.isNumber)(t)||(0,xi.isString)(t)),(0,xi.validateRequiredField)(e,"Destination",xi.isAccount),(0,xi.validateOptionalField)(e,"DestinationTag",xi.isNumber),(0,xi.validateRequiredField)(e,"Amount",xi.isAmount)}pw.validateXChainClaim=NQ});var f7=q(yw=>{"use strict";y();Object.defineProperty(yw,"__esModule",{value:!0});yw.validateXChainCommit=void 0;var Wo=de();function LQ(e){(0,Wo.validateBaseTransaction)(e),(0,Wo.validateRequiredField)(e,"XChainBridge",Wo.isXChainBridge),(0,Wo.validateRequiredField)(e,"XChainClaimID",t=>(0,Wo.isNumber)(t)||(0,Wo.isString)(t)),(0,Wo.validateOptionalField)(e,"OtherChainDestination",Wo.isAccount),(0,Wo.validateRequiredField)(e,"Amount",Wo.isAmount)}yw.validateXChainCommit=LQ});var p7=q(hw=>{"use strict";y();Object.defineProperty(hw,"__esModule",{value:!0});hw.validateXChainCreateBridge=void 0;var vl=de();function BQ(e){(0,vl.validateBaseTransaction)(e),(0,vl.validateRequiredField)(e,"XChainBridge",vl.isXChainBridge),(0,vl.validateRequiredField)(e,"SignatureReward",vl.isAmount),(0,vl.validateOptionalField)(e,"MinAccountCreateAmount",vl.isAmount)}hw.validateXChainCreateBridge=BQ});var y7=q(mw=>{"use strict";y();Object.defineProperty(mw,"__esModule",{value:!0});mw.validateXChainCreateClaimID=void 0;var Al=de();function FQ(e){(0,Al.validateBaseTransaction)(e),(0,Al.validateRequiredField)(e,"XChainBridge",Al.isXChainBridge),(0,Al.validateRequiredField)(e,"SignatureReward",Al.isAmount),(0,Al.validateRequiredField)(e,"OtherChainSource",Al.isAccount)}mw.validateXChainCreateClaimID=FQ});var w7=q(gw=>{"use strict";y();Object.defineProperty(gw,"__esModule",{value:!0});gw.validate=void 0;var h7=fe(),UQ=ju(),$Q=LI(),qQ=Hg(),HQ=FI(),VQ=Kg(),KQ=G3(),zQ=UI(),jQ=zg(),XQ=qI(),WQ=jg(),GQ=Xp(),YQ=HI(),ZQ=VI(),JQ=KI(),QQ=zI(),m7=de(),eee=XI(),tee=GI(),nee=YI(),ree=ZI(),iee=JI(),oee=QI(),aee=tP(),see=nP(),cee=iP(),lee=aP(),uee=sP(),dee=cP(),fee=uP(),pee=dP(),yee=fP(),hee=pP(),mee=yP(),gee=hP(),wee=mP(),bee=vP(),Cee=AP(),vee=Gg(),Aee=Yg(),See=rS(),Tee=Zg(),Eee=ey(),kee=MP(),_ee=n0(),Iee=DP(),Pee=RP(),xee=BP(),Mee=r0(),Oee=i0(),Dee=oS(),Ree=$P(),Nee=o0(),Lee=qP(),Bee=jP(),Fee=a0(),Uee=s0(),$ee=XP(),qee=WP(),Hee=GP(),Vee=YP(),Kee=ZP(),zee=QP(),jee=c0(),Xee=l0(),Wee=e7(),Gee=d0(),Yee=t7(),Zee=p0(),Jee=r7(),Qee=i7(),ete=a7(),tte=s7(),nte=c7(),rte=l7(),ite=u7(),ote=d7(),ate=f7(),ste=p7(),cte=y7(),lte=y0();function g7(e){let t=Object.assign({},e);switch((0,m7.validateBaseTransaction)(t),Object.keys(t).forEach(n=>{let i=t[n];if(i&&(0,m7.isIssuedCurrencyAmount)(i)){let o=i.currency;if(o.length===3&&o.toUpperCase()==="XRP")throw new h7.ValidationError(`Cannot have an issued currency with a similar standard code to XRP (received '${o}'). XRP is not an issued currency.`)}}),t.Flags=(0,UQ.convertTxFlagsToNumber)(t),t.TransactionType){case"AMMBid":(0,HQ.validateAMMBid)(t);break;case"AMMClawback":(0,VQ.validateAMMClawback)(t);break;case"AMMCreate":(0,KQ.validateAMMCreate)(t);break;case"AMMDelete":(0,zQ.validateAMMDelete)(t);break;case"AMMDeposit":(0,jQ.validateAMMDeposit)(t);break;case"AMMVote":(0,XQ.validateAMMVote)(t);break;case"AMMWithdraw":(0,WQ.validateAMMWithdraw)(t);break;case"AccountDelete":(0,$Q.validateAccountDelete)(t);break;case"AccountSet":(0,qQ.validateAccountSet)(t);break;case"Batch":(0,GQ.validateBatch)(t),t.RawTransactions.forEach(n=>{g7(n.RawTransaction)});break;case"CheckCancel":(0,YQ.validateCheckCancel)(t);break;case"CheckCash":(0,ZQ.validateCheckCash)(t);break;case"CheckCreate":(0,JQ.validateCheckCreate)(t);break;case"Clawback":(0,QQ.validateClawback)(t);break;case"ConfidentialMPTClawback":(0,eee.validateConfidentialMPTClawback)(t);break;case"ConfidentialMPTConvert":(0,tee.validateConfidentialMPTConvert)(t);break;case"ConfidentialMPTConvertBack":(0,nee.validateConfidentialMPTConvertBack)(t);break;case"ConfidentialMPTMergeInbox":(0,ree.validateConfidentialMPTMergeInbox)(t);break;case"ConfidentialMPTSend":(0,iee.validateConfidentialMPTSend)(t);break;case"CredentialAccept":(0,oee.validateCredentialAccept)(t);break;case"CredentialCreate":(0,aee.validateCredentialCreate)(t);break;case"CredentialDelete":(0,see.validateCredentialDelete)(t);break;case"DIDDelete":(0,uee.validateDIDDelete)(t);break;case"DIDSet":(0,dee.validateDIDSet)(t);break;case"DelegateSet":(0,cee.validateDelegateSet)(t);break;case"DepositPreauth":(0,lee.validateDepositPreauth)(t);break;case"EscrowCancel":(0,fee.validateEscrowCancel)(t);break;case"EscrowCreate":(0,pee.validateEscrowCreate)(t);break;case"EscrowFinish":(0,yee.validateEscrowFinish)(t);break;case"LoanBrokerCoverClawback":(0,hee.validateLoanBrokerCoverClawback)(t);break;case"LoanBrokerCoverDeposit":(0,mee.validateLoanBrokerCoverDeposit)(t);break;case"LoanBrokerCoverWithdraw":(0,gee.validateLoanBrokerCoverWithdraw)(t);break;case"LoanBrokerDelete":(0,wee.validateLoanBrokerDelete)(t);break;case"LoanBrokerSet":(0,bee.validateLoanBrokerSet)(t);break;case"LoanSet":(0,See.validateLoanSet)(t);break;case"LoanManage":(0,vee.validateLoanManage)(t);break;case"LoanDelete":(0,Cee.validateLoanDelete)(t);break;case"LoanPay":(0,Aee.validateLoanPay)(t);break;case"MPTokenAuthorize":(0,Tee.validateMPTokenAuthorize)(t);break;case"MPTokenIssuanceCreate":(0,Eee.validateMPTokenIssuanceCreate)(t);break;case"MPTokenIssuanceDestroy":(0,kee.validateMPTokenIssuanceDestroy)(t);break;case"MPTokenIssuanceSet":(0,_ee.validateMPTokenIssuanceSet)(t);break;case"NFTokenAcceptOffer":(0,Iee.validateNFTokenAcceptOffer)(t);break;case"NFTokenBurn":(0,Pee.validateNFTokenBurn)(t);break;case"NFTokenCancelOffer":(0,xee.validateNFTokenCancelOffer)(t);break;case"NFTokenCreateOffer":(0,Mee.validateNFTokenCreateOffer)(t);break;case"NFTokenMint":(0,Oee.validateNFTokenMint)(t);break;case"NFTokenModify":(0,Dee.validateNFTokenModify)(t);break;case"OfferCancel":(0,Ree.validateOfferCancel)(t);break;case"OfferCreate":(0,Nee.validateOfferCreate)(t);break;case"OracleDelete":(0,Lee.validateOracleDelete)(t);break;case"OracleSet":(0,Bee.validateOracleSet)(t);break;case"Payment":(0,Fee.validatePayment)(t);break;case"PaymentChannelClaim":(0,Uee.validatePaymentChannelClaim)(t);break;case"PaymentChannelCreate":(0,$ee.validatePaymentChannelCreate)(t);break;case"PaymentChannelFund":(0,qee.validatePaymentChannelFund)(t);break;case"PermissionedDomainSet":(0,Vee.validatePermissionedDomainSet)(t);break;case"PermissionedDomainDelete":(0,Hee.validatePermissionedDomainDelete)(t);break;case"SetRegularKey":(0,Kee.validateSetRegularKey)(t);break;case"SignerListSet":(0,zee.validateSignerListSet)(t);break;case"SponsorshipSet":(0,jee.validateSponsorshipSet)(t);break;case"SponsorshipTransfer":(0,Xee.validateSponsorshipTransfer)(t);break;case"TicketCreate":(0,Wee.validateTicketCreate)(t);break;case"TrustSet":(0,Gee.validateTrustSet)(t);break;case"VaultClawback":(0,Yee.validateVaultClawback)(t);break;case"VaultCreate":(0,Zee.validateVaultCreate)(t);break;case"VaultDelete":(0,Jee.validateVaultDelete)(t);break;case"VaultDeposit":(0,Qee.validateVaultDeposit)(t);break;case"VaultSet":(0,ete.validateVaultSet)(t);break;case"VaultWithdraw":(0,tte.validateVaultWithdraw)(t);break;case"XChainAccountCreateCommit":(0,nte.validateXChainAccountCreateCommit)(t);break;case"XChainAddAccountCreateAttestation":(0,rte.validateXChainAddAccountCreateAttestation)(t);break;case"XChainAddClaimAttestation":(0,ite.validateXChainAddClaimAttestation)(t);break;case"XChainClaim":(0,ote.validateXChainClaim)(t);break;case"XChainCommit":(0,ate.validateXChainCommit)(t);break;case"XChainCreateBridge":(0,ste.validateXChainCreateBridge)(t);break;case"XChainCreateClaimID":(0,cte.validateXChainCreateClaimID)(t);break;case"XChainModifyBridge":(0,lte.validateXChainModifyBridge)(t);break;default:throw new h7.ValidationError(`Invalid field TransactionType: ${t.TransactionType}`)}}gw.validate=g7});var C7=q(ww=>{"use strict";y();Object.defineProperty(ww,"__esModule",{value:!0});ww.EnableAmendmentFlags=void 0;var b7;(function(e){e[e.tfGotMajority=65536]="tfGotMajority",e[e.tfLostMajority=131072]="tfLostMajority"})(b7||(ww.EnableAmendmentFlags=b7={}))});var Od=q(Ce=>{"use strict";y();var ute=Ce&&Ce.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),dte=Ce&&Ce.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&ute(t,e,n)};Object.defineProperty(Ce,"__esModule",{value:!0});Ce.XChainModifyBridgeFlags=Ce.VaultWithdrawalPolicy=Ce.VaultKind=Ce.VaultCreateFlags=Ce.TrustSetFlags=Ce.SponsorshipTransferFlags=Ce.SponsorshipSetFlags=Ce.PaymentChannelClaimFlags=Ce.PaymentFlags=Ce.OfferCreateFlags=Ce.validateNFTokenModify=Ce.NFTokenMintFlags=Ce.NFTokenCreateOfferFlags=Ce.MPTokenIssuanceSetFlags=Ce.MPTokenIssuanceCreateImmutableFlags=Ce.MPTokenIssuanceCreateFlags=Ce.MPTokenAuthorizeFlags=Ce.LoanPayFlags=Ce.LoanManageFlags=Ce.LoanSetFlags=Ce.EnableAmendmentFlags=Ce.BatchFlags=Ce.AMMWithdrawFlags=Ce.AMMDepositFlags=Ce.AMMClawbackFlags=Ce.AccountSetTfFlags=Ce.AccountSetAsfFlags=Ce.validate=Ce.SponsorFlags=Ce.isMPTAmount=Ce.GlobalFlags=void 0;var lS=de();Object.defineProperty(Ce,"GlobalFlags",{enumerable:!0,get:function(){return lS.GlobalFlags}});Object.defineProperty(Ce,"isMPTAmount",{enumerable:!0,get:function(){return lS.isMPTAmount}});Object.defineProperty(Ce,"SponsorFlags",{enumerable:!0,get:function(){return lS.SponsorFlags}});var fte=w7();Object.defineProperty(Ce,"validate",{enumerable:!0,get:function(){return fte.validate}});dte(j0(),Ce);var v7=Hg();Object.defineProperty(Ce,"AccountSetAsfFlags",{enumerable:!0,get:function(){return v7.AccountSetAsfFlags}});Object.defineProperty(Ce,"AccountSetTfFlags",{enumerable:!0,get:function(){return v7.AccountSetTfFlags}});var pte=Kg();Object.defineProperty(Ce,"AMMClawbackFlags",{enumerable:!0,get:function(){return pte.AMMClawbackFlags}});var yte=zg();Object.defineProperty(Ce,"AMMDepositFlags",{enumerable:!0,get:function(){return yte.AMMDepositFlags}});var hte=jg();Object.defineProperty(Ce,"AMMWithdrawFlags",{enumerable:!0,get:function(){return hte.AMMWithdrawFlags}});var mte=Xp();Object.defineProperty(Ce,"BatchFlags",{enumerable:!0,get:function(){return mte.BatchFlags}});var gte=C7();Object.defineProperty(Ce,"EnableAmendmentFlags",{enumerable:!0,get:function(){return gte.EnableAmendmentFlags}});var wte=rS();Object.defineProperty(Ce,"LoanSetFlags",{enumerable:!0,get:function(){return wte.LoanSetFlags}});var bte=Gg();Object.defineProperty(Ce,"LoanManageFlags",{enumerable:!0,get:function(){return bte.LoanManageFlags}});var Cte=Yg();Object.defineProperty(Ce,"LoanPayFlags",{enumerable:!0,get:function(){return Cte.LoanPayFlags}});var vte=Zg();Object.defineProperty(Ce,"MPTokenAuthorizeFlags",{enumerable:!0,get:function(){return vte.MPTokenAuthorizeFlags}});var A7=ey();Object.defineProperty(Ce,"MPTokenIssuanceCreateFlags",{enumerable:!0,get:function(){return A7.MPTokenIssuanceCreateFlags}});Object.defineProperty(Ce,"MPTokenIssuanceCreateImmutableFlags",{enumerable:!0,get:function(){return A7.MPTokenIssuanceCreateImmutableFlags}});var Ate=n0();Object.defineProperty(Ce,"MPTokenIssuanceSetFlags",{enumerable:!0,get:function(){return Ate.MPTokenIssuanceSetFlags}});var Ste=r0();Object.defineProperty(Ce,"NFTokenCreateOfferFlags",{enumerable:!0,get:function(){return Ste.NFTokenCreateOfferFlags}});var Tte=i0();Object.defineProperty(Ce,"NFTokenMintFlags",{enumerable:!0,get:function(){return Tte.NFTokenMintFlags}});var Ete=oS();Object.defineProperty(Ce,"validateNFTokenModify",{enumerable:!0,get:function(){return Ete.validateNFTokenModify}});var kte=o0();Object.defineProperty(Ce,"OfferCreateFlags",{enumerable:!0,get:function(){return kte.OfferCreateFlags}});var _te=a0();Object.defineProperty(Ce,"PaymentFlags",{enumerable:!0,get:function(){return _te.PaymentFlags}});var Ite=s0();Object.defineProperty(Ce,"PaymentChannelClaimFlags",{enumerable:!0,get:function(){return Ite.PaymentChannelClaimFlags}});var Pte=c0();Object.defineProperty(Ce,"SponsorshipSetFlags",{enumerable:!0,get:function(){return Pte.SponsorshipSetFlags}});var xte=l0();Object.defineProperty(Ce,"SponsorshipTransferFlags",{enumerable:!0,get:function(){return xte.SponsorshipTransferFlags}});var Mte=d0();Object.defineProperty(Ce,"TrustSetFlags",{enumerable:!0,get:function(){return Mte.TrustSetFlags}});var uS=p0();Object.defineProperty(Ce,"VaultCreateFlags",{enumerable:!0,get:function(){return uS.VaultCreateFlags}});Object.defineProperty(Ce,"VaultKind",{enumerable:!0,get:function(){return uS.VaultKind}});Object.defineProperty(Ce,"VaultWithdrawalPolicy",{enumerable:!0,get:function(){return uS.VaultWithdrawalPolicy}});var Ote=y0();Object.defineProperty(Ce,"XChainModifyBridgeFlags",{enumerable:!0,get:function(){return Ote.XChainModifyBridgeFlags}})});var S7=q((sbe,Dte)=>{Dte.exports=["A","ABE","ACE","ACT","AD","ADA","ADD","AGO","AID","AIM","AIR","ALL","ALP","AM","AMY","AN","ANA","AND","ANN","ANT","ANY","APE","APS","APT","ARC","ARE","ARK","ARM","ART","AS","ASH","ASK","AT","ATE","AUG","AUK","AVE","AWE","AWK","AWL","AWN","AX","AYE","BAD","BAG","BAH","BAM","BAN","BAR","BAT","BAY","BE","BED","BEE","BEG","BEN","BET","BEY","BIB","BID","BIG","BIN","BIT","BOB","BOG","BON","BOO","BOP","BOW","BOY","BUB","BUD","BUG","BUM","BUN","BUS","BUT","BUY","BY","BYE","CAB","CAL","CAM","CAN","CAP","CAR","CAT","CAW","COD","COG","COL","CON","COO","COP","COT","COW","COY","CRY","CUB","CUE","CUP","CUR","CUT","DAB","DAD","DAM","DAN","DAR","DAY","DEE","DEL","DEN","DES","DEW","DID","DIE","DIG","DIN","DIP","DO","DOE","DOG","DON","DOT","DOW","DRY","DUB","DUD","DUE","DUG","DUN","EAR","EAT","ED","EEL","EGG","EGO","ELI","ELK","ELM","ELY","EM","END","EST","ETC","EVA","EVE","EWE","EYE","FAD","FAN","FAR","FAT","FAY","FED","FEE","FEW","FIB","FIG","FIN","FIR","FIT","FLO","FLY","FOE","FOG","FOR","FRY","FUM","FUN","FUR","GAB","GAD","GAG","GAL","GAM","GAP","GAS","GAY","GEE","GEL","GEM","GET","GIG","GIL","GIN","GO","GOT","GUM","GUN","GUS","GUT","GUY","GYM","GYP","HA","HAD","HAL","HAM","HAN","HAP","HAS","HAT","HAW","HAY","HE","HEM","HEN","HER","HEW","HEY","HI","HID","HIM","HIP","HIS","HIT","HO","HOB","HOC","HOE","HOG","HOP","HOT","HOW","HUB","HUE","HUG","HUH","HUM","HUT","I","ICY","IDA","IF","IKE","ILL","INK","INN","IO","ION","IQ","IRA","IRE","IRK","IS","IT","ITS","IVY","JAB","JAG","JAM","JAN","JAR","JAW","JAY","JET","JIG","JIM","JO","JOB","JOE","JOG","JOT","JOY","JUG","JUT","KAY","KEG","KEN","KEY","KID","KIM","KIN","KIT","LA","LAB","LAC","LAD","LAG","LAM","LAP","LAW","LAY","LEA","LED","LEE","LEG","LEN","LEO","LET","LEW","LID","LIE","LIN","LIP","LIT","LO","LOB","LOG","LOP","LOS","LOT","LOU","LOW","LOY","LUG","LYE","MA","MAC","MAD","MAE","MAN","MAO","MAP","MAT","MAW","MAY","ME","MEG","MEL","MEN","MET","MEW","MID","MIN","MIT","MOB","MOD","MOE","MOO","MOP","MOS","MOT","MOW","MUD","MUG","MUM","MY","NAB","NAG","NAN","NAP","NAT","NAY","NE","NED","NEE","NET","NEW","NIB","NIL","NIP","NIT","NO","NOB","NOD","NON","NOR","NOT","NOV","NOW","NU","NUN","NUT","O","OAF","OAK","OAR","OAT","ODD","ODE","OF","OFF","OFT","OH","OIL","OK","OLD","ON","ONE","OR","ORB","ORE","ORR","OS","OTT","OUR","OUT","OVA","OW","OWE","OWL","OWN","OX","PA","PAD","PAL","PAM","PAN","PAP","PAR","PAT","PAW","PAY","PEA","PEG","PEN","PEP","PER","PET","PEW","PHI","PI","PIE","PIN","PIT","PLY","PO","POD","POE","POP","POT","POW","PRO","PRY","PUB","PUG","PUN","PUP","PUT","QUO","RAG","RAM","RAN","RAP","RAT","RAW","RAY","REB","RED","REP","RET","RIB","RID","RIG","RIM","RIO","RIP","ROB","ROD","ROE","RON","ROT","ROW","ROY","RUB","RUE","RUG","RUM","RUN","RYE","SAC","SAD","SAG","SAL","SAM","SAN","SAP","SAT","SAW","SAY","SEA","SEC","SEE","SEN","SET","SEW","SHE","SHY","SIN","SIP","SIR","SIS","SIT","SKI","SKY","SLY","SO","SOB","SOD","SON","SOP","SOW","SOY","SPA","SPY","SUB","SUD","SUE","SUM","SUN","SUP","TAB","TAD","TAG","TAN","TAP","TAR","TEA","TED","TEE","TEN","THE","THY","TIC","TIE","TIM","TIN","TIP","TO","TOE","TOG","TOM","TON","TOO","TOP","TOW","TOY","TRY","TUB","TUG","TUM","TUN","TWO","UN","UP","US","USE","VAN","VAT","VET","VIE","WAD","WAG","WAR","WAS","WAY","WE","WEB","WED","WEE","WET","WHO","WHY","WIN","WIT","WOK","WON","WOO","WOW","WRY","WU","YAM","YAP","YAW","YE","YEA","YES","YET","YOU","ABED","ABEL","ABET","ABLE","ABUT","ACHE","ACID","ACME","ACRE","ACTA","ACTS","ADAM","ADDS","ADEN","AFAR","AFRO","AGEE","AHEM","AHOY","AIDA","AIDE","AIDS","AIRY","AJAR","AKIN","ALAN","ALEC","ALGA","ALIA","ALLY","ALMA","ALOE","ALSO","ALTO","ALUM","ALVA","AMEN","AMES","AMID","AMMO","AMOK","AMOS","AMRA","ANDY","ANEW","ANNA","ANNE","ANTE","ANTI","AQUA","ARAB","ARCH","AREA","ARGO","ARID","ARMY","ARTS","ARTY","ASIA","ASKS","ATOM","AUNT","AURA","AUTO","AVER","AVID","AVIS","AVON","AVOW","AWAY","AWRY","BABE","BABY","BACH","BACK","BADE","BAIL","BAIT","BAKE","BALD","BALE","BALI","BALK","BALL","BALM","BAND","BANE","BANG","BANK","BARB","BARD","BARE","BARK","BARN","BARR","BASE","BASH","BASK","BASS","BATE","BATH","BAWD","BAWL","BEAD","BEAK","BEAM","BEAN","BEAR","BEAT","BEAU","BECK","BEEF","BEEN","BEER","BEET","BELA","BELL","BELT","BEND","BENT","BERG","BERN","BERT","BESS","BEST","BETA","BETH","BHOY","BIAS","BIDE","BIEN","BILE","BILK","BILL","BIND","BING","BIRD","BITE","BITS","BLAB","BLAT","BLED","BLEW","BLOB","BLOC","BLOT","BLOW","BLUE","BLUM","BLUR","BOAR","BOAT","BOCA","BOCK","BODE","BODY","BOGY","BOHR","BOIL","BOLD","BOLO","BOLT","BOMB","BONA","BOND","BONE","BONG","BONN","BONY","BOOK","BOOM","BOON","BOOT","BORE","BORG","BORN","BOSE","BOSS","BOTH","BOUT","BOWL","BOYD","BRAD","BRAE","BRAG","BRAN","BRAY","BRED","BREW","BRIG","BRIM","BROW","BUCK","BUDD","BUFF","BULB","BULK","BULL","BUNK","BUNT","BUOY","BURG","BURL","BURN","BURR","BURT","BURY","BUSH","BUSS","BUST","BUSY","BYTE","CADY","CAFE","CAGE","CAIN","CAKE","CALF","CALL","CALM","CAME","CANE","CANT","CARD","CARE","CARL","CARR","CART","CASE","CASH","CASK","CAST","CAVE","CEIL","CELL","CENT","CERN","CHAD","CHAR","CHAT","CHAW","CHEF","CHEN","CHEW","CHIC","CHIN","CHOU","CHOW","CHUB","CHUG","CHUM","CITE","CITY","CLAD","CLAM","CLAN","CLAW","CLAY","CLOD","CLOG","CLOT","CLUB","CLUE","COAL","COAT","COCA","COCK","COCO","CODA","CODE","CODY","COED","COIL","COIN","COKE","COLA","COLD","COLT","COMA","COMB","COME","COOK","COOL","COON","COOT","CORD","CORE","CORK","CORN","COST","COVE","COWL","CRAB","CRAG","CRAM","CRAY","CREW","CRIB","CROW","CRUD","CUBA","CUBE","CUFF","CULL","CULT","CUNY","CURB","CURD","CURE","CURL","CURT","CUTS","DADE","DALE","DAME","DANA","DANE","DANG","DANK","DARE","DARK","DARN","DART","DASH","DATA","DATE","DAVE","DAVY","DAWN","DAYS","DEAD","DEAF","DEAL","DEAN","DEAR","DEBT","DECK","DEED","DEEM","DEER","DEFT","DEFY","DELL","DENT","DENY","DESK","DIAL","DICE","DIED","DIET","DIME","DINE","DING","DINT","DIRE","DIRT","DISC","DISH","DISK","DIVE","DOCK","DOES","DOLE","DOLL","DOLT","DOME","DONE","DOOM","DOOR","DORA","DOSE","DOTE","DOUG","DOUR","DOVE","DOWN","DRAB","DRAG","DRAM","DRAW","DREW","DRUB","DRUG","DRUM","DUAL","DUCK","DUCT","DUEL","DUET","DUKE","DULL","DUMB","DUNE","DUNK","DUSK","DUST","DUTY","EACH","EARL","EARN","EASE","EAST","EASY","EBEN","ECHO","EDDY","EDEN","EDGE","EDGY","EDIT","EDNA","EGAN","ELAN","ELBA","ELLA","ELSE","EMIL","EMIT","EMMA","ENDS","ERIC","EROS","EVEN","EVER","EVIL","EYED","FACE","FACT","FADE","FAIL","FAIN","FAIR","FAKE","FALL","FAME","FANG","FARM","FAST","FATE","FAWN","FEAR","FEAT","FEED","FEEL","FEET","FELL","FELT","FEND","FERN","FEST","FEUD","FIEF","FIGS","FILE","FILL","FILM","FIND","FINE","FINK","FIRE","FIRM","FISH","FISK","FIST","FITS","FIVE","FLAG","FLAK","FLAM","FLAT","FLAW","FLEA","FLED","FLEW","FLIT","FLOC","FLOG","FLOW","FLUB","FLUE","FOAL","FOAM","FOGY","FOIL","FOLD","FOLK","FOND","FONT","FOOD","FOOL","FOOT","FORD","FORE","FORK","FORM","FORT","FOSS","FOUL","FOUR","FOWL","FRAU","FRAY","FRED","FREE","FRET","FREY","FROG","FROM","FUEL","FULL","FUME","FUND","FUNK","FURY","FUSE","FUSS","GAFF","GAGE","GAIL","GAIN","GAIT","GALA","GALE","GALL","GALT","GAME","GANG","GARB","GARY","GASH","GATE","GAUL","GAUR","GAVE","GAWK","GEAR","GELD","GENE","GENT","GERM","GETS","GIBE","GIFT","GILD","GILL","GILT","GINA","GIRD","GIRL","GIST","GIVE","GLAD","GLEE","GLEN","GLIB","GLOB","GLOM","GLOW","GLUE","GLUM","GLUT","GOAD","GOAL","GOAT","GOER","GOES","GOLD","GOLF","GONE","GONG","GOOD","GOOF","GORE","GORY","GOSH","GOUT","GOWN","GRAB","GRAD","GRAY","GREG","GREW","GREY","GRID","GRIM","GRIN","GRIT","GROW","GRUB","GULF","GULL","GUNK","GURU","GUSH","GUST","GWEN","GWYN","HAAG","HAAS","HACK","HAIL","HAIR","HALE","HALF","HALL","HALO","HALT","HAND","HANG","HANK","HANS","HARD","HARK","HARM","HART","HASH","HAST","HATE","HATH","HAUL","HAVE","HAWK","HAYS","HEAD","HEAL","HEAR","HEAT","HEBE","HECK","HEED","HEEL","HEFT","HELD","HELL","HELM","HERB","HERD","HERE","HERO","HERS","HESS","HEWN","HICK","HIDE","HIGH","HIKE","HILL","HILT","HIND","HINT","HIRE","HISS","HIVE","HOBO","HOCK","HOFF","HOLD","HOLE","HOLM","HOLT","HOME","HONE","HONK","HOOD","HOOF","HOOK","HOOT","HORN","HOSE","HOST","HOUR","HOVE","HOWE","HOWL","HOYT","HUCK","HUED","HUFF","HUGE","HUGH","HUGO","HULK","HULL","HUNK","HUNT","HURD","HURL","HURT","HUSH","HYDE","HYMN","IBIS","ICON","IDEA","IDLE","IFFY","INCA","INCH","INTO","IONS","IOTA","IOWA","IRIS","IRMA","IRON","ISLE","ITCH","ITEM","IVAN","JACK","JADE","JAIL","JAKE","JANE","JAVA","JEAN","JEFF","JERK","JESS","JEST","JIBE","JILL","JILT","JIVE","JOAN","JOBS","JOCK","JOEL","JOEY","JOHN","JOIN","JOKE","JOLT","JOVE","JUDD","JUDE","JUDO","JUDY","JUJU","JUKE","JULY","JUNE","JUNK","JUNO","JURY","JUST","JUTE","KAHN","KALE","KANE","KANT","KARL","KATE","KEEL","KEEN","KENO","KENT","KERN","KERR","KEYS","KICK","KILL","KIND","KING","KIRK","KISS","KITE","KLAN","KNEE","KNEW","KNIT","KNOB","KNOT","KNOW","KOCH","KONG","KUDO","KURD","KURT","KYLE","LACE","LACK","LACY","LADY","LAID","LAIN","LAIR","LAKE","LAMB","LAME","LAND","LANE","LANG","LARD","LARK","LASS","LAST","LATE","LAUD","LAVA","LAWN","LAWS","LAYS","LEAD","LEAF","LEAK","LEAN","LEAR","LEEK","LEER","LEFT","LEND","LENS","LENT","LEON","LESK","LESS","LEST","LETS","LIAR","LICE","LICK","LIED","LIEN","LIES","LIEU","LIFE","LIFT","LIKE","LILA","LILT","LILY","LIMA","LIMB","LIME","LIND","LINE","LINK","LINT","LION","LISA","LIST","LIVE","LOAD","LOAF","LOAM","LOAN","LOCK","LOFT","LOGE","LOIS","LOLA","LONE","LONG","LOOK","LOON","LOOT","LORD","LORE","LOSE","LOSS","LOST","LOUD","LOVE","LOWE","LUCK","LUCY","LUGE","LUKE","LULU","LUND","LUNG","LURA","LURE","LURK","LUSH","LUST","LYLE","LYNN","LYON","LYRA","MACE","MADE","MAGI","MAID","MAIL","MAIN","MAKE","MALE","MALI","MALL","MALT","MANA","MANN","MANY","MARC","MARE","MARK","MARS","MART","MARY","MASH","MASK","MASS","MAST","MATE","MATH","MAUL","MAYO","MEAD","MEAL","MEAN","MEAT","MEEK","MEET","MELD","MELT","MEMO","MEND","MENU","MERT","MESH","MESS","MICE","MIKE","MILD","MILE","MILK","MILL","MILT","MIMI","MIND","MINE","MINI","MINK","MINT","MIRE","MISS","MIST","MITE","MITT","MOAN","MOAT","MOCK","MODE","MOLD","MOLE","MOLL","MOLT","MONA","MONK","MONT","MOOD","MOON","MOOR","MOOT","MORE","MORN","MORT","MOSS","MOST","MOTH","MOVE","MUCH","MUCK","MUDD","MUFF","MULE","MULL","MURK","MUSH","MUST","MUTE","MUTT","MYRA","MYTH","NAGY","NAIL","NAIR","NAME","NARY","NASH","NAVE","NAVY","NEAL","NEAR","NEAT","NECK","NEED","NEIL","NELL","NEON","NERO","NESS","NEST","NEWS","NEWT","NIBS","NICE","NICK","NILE","NINA","NINE","NOAH","NODE","NOEL","NOLL","NONE","NOOK","NOON","NORM","NOSE","NOTE","NOUN","NOVA","NUDE","NULL","NUMB","OATH","OBEY","OBOE","ODIN","OHIO","OILY","OINT","OKAY","OLAF","OLDY","OLGA","OLIN","OMAN","OMEN","OMIT","ONCE","ONES","ONLY","ONTO","ONUS","ORAL","ORGY","OSLO","OTIS","OTTO","OUCH","OUST","OUTS","OVAL","OVEN","OVER","OWLY","OWNS","QUAD","QUIT","QUOD","RACE","RACK","RACY","RAFT","RAGE","RAID","RAIL","RAIN","RAKE","RANK","RANT","RARE","RASH","RATE","RAVE","RAYS","READ","REAL","REAM","REAR","RECK","REED","REEF","REEK","REEL","REID","REIN","RENA","REND","RENT","REST","RICE","RICH","RICK","RIDE","RIFT","RILL","RIME","RING","RINK","RISE","RISK","RITE","ROAD","ROAM","ROAR","ROBE","ROCK","RODE","ROIL","ROLL","ROME","ROOD","ROOF","ROOK","ROOM","ROOT","ROSA","ROSE","ROSS","ROSY","ROTH","ROUT","ROVE","ROWE","ROWS","RUBE","RUBY","RUDE","RUDY","RUIN","RULE","RUNG","RUNS","RUNT","RUSE","RUSH","RUSK","RUSS","RUST","RUTH","SACK","SAFE","SAGE","SAID","SAIL","SALE","SALK","SALT","SAME","SAND","SANE","SANG","SANK","SARA","SAUL","SAVE","SAYS","SCAN","SCAR","SCAT","SCOT","SEAL","SEAM","SEAR","SEAT","SEED","SEEK","SEEM","SEEN","SEES","SELF","SELL","SEND","SENT","SETS","SEWN","SHAG","SHAM","SHAW","SHAY","SHED","SHIM","SHIN","SHOD","SHOE","SHOT","SHOW","SHUN","SHUT","SICK","SIDE","SIFT","SIGH","SIGN","SILK","SILL","SILO","SILT","SINE","SING","SINK","SIRE","SITE","SITS","SITU","SKAT","SKEW","SKID","SKIM","SKIN","SKIT","SLAB","SLAM","SLAT","SLAY","SLED","SLEW","SLID","SLIM","SLIT","SLOB","SLOG","SLOT","SLOW","SLUG","SLUM","SLUR","SMOG","SMUG","SNAG","SNOB","SNOW","SNUB","SNUG","SOAK","SOAR","SOCK","SODA","SOFA","SOFT","SOIL","SOLD","SOME","SONG","SOON","SOOT","SORE","SORT","SOUL","SOUR","SOWN","STAB","STAG","STAN","STAR","STAY","STEM","STEW","STIR","STOW","STUB","STUN","SUCH","SUDS","SUIT","SULK","SUMS","SUNG","SUNK","SURE","SURF","SWAB","SWAG","SWAM","SWAN","SWAT","SWAY","SWIM","SWUM","TACK","TACT","TAIL","TAKE","TALE","TALK","TALL","TANK","TASK","TATE","TAUT","TEAL","TEAM","TEAR","TECH","TEEM","TEEN","TEET","TELL","TEND","TENT","TERM","TERN","TESS","TEST","THAN","THAT","THEE","THEM","THEN","THEY","THIN","THIS","THUD","THUG","TICK","TIDE","TIDY","TIED","TIER","TILE","TILL","TILT","TIME","TINA","TINE","TINT","TINY","TIRE","TOAD","TOGO","TOIL","TOLD","TOLL","TONE","TONG","TONY","TOOK","TOOL","TOOT","TORE","TORN","TOTE","TOUR","TOUT","TOWN","TRAG","TRAM","TRAY","TREE","TREK","TRIG","TRIM","TRIO","TROD","TROT","TROY","TRUE","TUBA","TUBE","TUCK","TUFT","TUNA","TUNE","TUNG","TURF","TURN","TUSK","TWIG","TWIN","TWIT","ULAN","UNIT","URGE","USED","USER","USES","UTAH","VAIL","VAIN","VALE","VARY","VASE","VAST","VEAL","VEDA","VEIL","VEIN","VEND","VENT","VERB","VERY","VETO","VICE","VIEW","VINE","VISE","VOID","VOLT","VOTE","WACK","WADE","WAGE","WAIL","WAIT","WAKE","WALE","WALK","WALL","WALT","WAND","WANE","WANG","WANT","WARD","WARM","WARN","WART","WASH","WAST","WATS","WATT","WAVE","WAVY","WAYS","WEAK","WEAL","WEAN","WEAR","WEED","WEEK","WEIR","WELD","WELL","WELT","WENT","WERE","WERT","WEST","WHAM","WHAT","WHEE","WHEN","WHET","WHOA","WHOM","WICK","WIFE","WILD","WILL","WIND","WINE","WING","WINK","WINO","WIRE","WISE","WISH","WITH","WOLF","WONT","WOOD","WOOL","WORD","WORE","WORK","WORM","WORN","WOVE","WRIT","WYNN","YALE","YANG","YANK","YARD","YARN","YAWL","YAWN","YEAH","YEAR","YELL","YOGA","YOKE"]});var fS=q(Gs=>{"use strict";y();var Rte=Gs&&Gs.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Gs,"__esModule",{value:!0});Gs.keyToRFC1751Mnemonic=Gs.rfc1751MnemonicToKey=void 0;var E7=We(),Nte=Rte(S7()),k7=Nte.default,T7=["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"];function dS(e){let t="";for(let n of e)t+=T7[n>>4]+T7[n&15];return t}function Cw(e,t,n){let r=e.substring(t,t+n),i=0;for(let o=0;o>16,d=l>>8&255,p=l&255,h=Math.floor(r/8);c>5?(i[h]|=u,i[h+1]|=d,i[h+2]|=p):c>-3?(i[h]|=d,i[h+1]|=p):i[h]|=p,r+=11}return{subKey:i.slice(),word:o}}function Ute(e){return Array.prototype.slice.call(e)}function bw(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function $te(e){let t=e.length;for(let n=0;n{"use strict";y();var qte=Pn&&Pn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Pn,"__esModule",{value:!0});Pn.validateEntropy=Pn.isUint8Array=Pn.computeSignature=Pn.getDecodedTransaction=Pn.addressToBigNumber=Pn.NUM_BITS_IN_HEX=Pn.compareSigners=void 0;var Hte=We(),Vte=qte(Sn()),pS=lr(),Va=Qn(),I7=_i(),yS=fe();function Kte(e,t){if(!e.Account||!t.Account)throw new Error("compareSigners: Account cannot be null or undefined");let n=hS(e.Account).comparedTo(hS(t.Account));if(n===null)throw new Error("compareSigners: Invalid account address comparison resulted in NaN");return n}Pn.compareSigners=Kte;Pn.NUM_BITS_IN_HEX=16;function hS(e){let t=(0,Hte.bytesToHex)((0,pS.decodeAccountID)(e));return new Vte.default(t,Pn.NUM_BITS_IN_HEX)}Pn.addressToBigNumber=hS;function zte(e){return typeof e=="object"?(0,Va.decode)((0,Va.encode)(e)):(0,Va.decode)(e)}Pn.getDecodedTransaction=zte;var jte={transaction:{single:e=>(0,Va.encodeForSigning)(e),multi:(e,t)=>(0,Va.encodeForMultisigning)(e,t)},counterparty:{single:e=>(0,Va.encodeForSigningCounterparty)(e),multi:(e,t)=>(0,Va.encodeForMultisigningCounterparty)(e,t)},sponsor:{single:e=>(0,Va.encodeForSigningSponsor)(e),multi:(e,t)=>(0,Va.encodeForMultisigningSponsor)(e,t)}};function Xte(e,t,n,r="transaction"){let i=jte[r];if(n){let o=(0,pS.isValidXAddress)(n)?(0,pS.xAddressToClassicAddress)(n).classicAddress:n;return(0,I7.sign)(i.multi(e,o),t)}return(0,I7.sign)(i.single(e),t)}Pn.computeSignature=Xte;var Sl=16,P7=255;function M7(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1&&Object.prototype.toString.call(e)==="[object Uint8Array]"}Pn.isUint8Array=M7;function x7(e){return new yS.ValidationError(`entropy must be exactly ${Sl} bytes, received ${e}. A seed holds ${Sl} bytes, so extra bytes cannot be stored. If all of your input is meaningful, hash it down to ${Sl} bytes rather than truncating, which would discard the difference between inputs that share their first ${Sl} bytes.`)}function Wte(e){if(M7(e)){let n=new Uint8Array(e);if(n.length!==Sl)throw x7(n.length);return n}if(!Array.isArray(e))throw new yS.ValidationError(`entropy must be a Uint8Array or an array of byte values, received ${typeof e}. If you have a hex string, convert it to bytes first (for example with hexToBytes) rather than passing the string directly.`);if(e.length!==Sl)throw x7(e.length);let t=Array.from({length:Sl},(n,r)=>e[r]);if(!t.every(n=>Number.isInteger(n)&&n>=0&&n<=P7))throw new yS.ValidationError(`entropy must contain only integers between 0 and ${P7}, with no missing or empty positions.`);return Uint8Array.from(t)}Pn.validateEntropy=Wte});var gS=q(Rd=>{"use strict";y();Object.defineProperty(Rd,"__esModule",{value:!0});Rd.multisign=Rd.verifySignature=void 0;var O7=Qn(),Gte=_i(),vw=fe(),Yte=Od(),mS=Dd();function Zte(e){if(e.length===0)throw new vw.ValidationError("There were 0 transactions to multisign");let t=e.map(n=>(0,mS.getDecodedTransaction)(n));return t.forEach(n=>{if((0,Yte.validate)(n),n.Signers==null||n.Signers.length===0)throw new vw.ValidationError("For multisigning all transactions must include a Signers field containing an array of signatures. You may have forgotten to pass the 'forMultisign' parameter when signing.");if(n.SigningPubKey!=="")throw new vw.ValidationError("SigningPubKey must be an empty string for all transactions when multisigning.")}),Qte(t),(0,O7.encode)(ene(t))}Rd.multisign=Zte;function Jte(e,t){let n=(0,mS.getDecodedTransaction)(e),r=t;if(typeof n.TxnSignature!="string"||!n.TxnSignature)throw new Error("Transaction is missing a signature, TxnSignature");if(!r){if(typeof n.SigningPubKey!="string"||!n.SigningPubKey)throw new Error("Transaction is missing a public key, SigningPubKey");r=n.SigningPubKey}return(0,Gte.verify)((0,O7.encodeForSigning)(n),n.TxnSignature,r)}Rd.verifySignature=Jte;function Qte(e){let t=JSON.stringify(Object.assign(Object.assign({},e[0]),{Signers:null}));if(e.slice(1).some(n=>JSON.stringify(Object.assign(Object.assign({},n),{Signers:null}))!==t))throw new vw.ValidationError("txJSON is not the same for all signedTransactions")}function ene(e){let t=e.flatMap(n=>{var r;return(r=n.Signers)!==null&&r!==void 0?r:[]}).sort((n,r)=>(0,mS.compareSigners)(n.Signer,r.Signer));return Object.assign(Object.assign({},e[0]),{Signers:t})}});var D7=q(Aw=>{"use strict";y();Object.defineProperty(Aw,"__esModule",{value:!0});Aw.AMENDMENTS_ID=void 0;Aw.AMENDMENTS_ID="7DB0788C020F02780A673DC74757F23823FA3014C1866E72CC4CD8B226CD6EF4"});var R7=q(Sw=>{"use strict";y();Object.defineProperty(Sw,"__esModule",{value:!0});Sw.FEE_SETTINGS_ID=void 0;Sw.FEE_SETTINGS_ID="4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A651"});var L7=q(Tw=>{"use strict";y();Object.defineProperty(Tw,"__esModule",{value:!0});Tw.LoanFlags=void 0;var N7;(function(e){e[e.lsfLoanDefault=65536]="lsfLoanDefault",e[e.lsfLoanImpaired=131072]="lsfLoanImpaired",e[e.lsfLoanOverpayment=262144]="lsfLoanOverpayment"})(N7||(Tw.LoanFlags=N7={}))});var B7=q(Ew=>{"use strict";y();Object.defineProperty(Ew,"__esModule",{value:!0});Ew.NEGATIVE_UNL_ID=void 0;Ew.NEGATIVE_UNL_ID="2E8A59AA9D3B5B186B0B9E0F62E6C02587CA74A4D778938E957B6357D364B244"});var U7=q(kw=>{"use strict";y();Object.defineProperty(kw,"__esModule",{value:!0});kw.RippleStateFlags=void 0;var F7;(function(e){e[e.lsfLowReserve=65536]="lsfLowReserve",e[e.lsfHighReserve=131072]="lsfHighReserve",e[e.lsfLowAuth=262144]="lsfLowAuth",e[e.lsfHighAuth=524288]="lsfHighAuth",e[e.lsfLowNoRipple=1048576]="lsfLowNoRipple",e[e.lsfHighNoRipple=2097152]="lsfHighNoRipple",e[e.lsfLowFreeze=4194304]="lsfLowFreeze",e[e.lsfHighFreeze=8388608]="lsfHighFreeze",e[e.lsfAMMNode=16777216]="lsfAMMNode",e[e.lsfLowDeepFreeze=33554432]="lsfLowDeepFreeze",e[e.lsfHighDeepFreeze=67108864]="lsfHighDeepFreeze"})(F7||(kw.RippleStateFlags=F7={}))});var q7=q(_w=>{"use strict";y();Object.defineProperty(_w,"__esModule",{value:!0});_w.SignerListFlags=void 0;var $7;(function(e){e[e.lsfOneOwnerCount=65536]="lsfOneOwnerCount"})($7||(_w.SignerListFlags=$7={}))});var V7=q(Iw=>{"use strict";y();Object.defineProperty(Iw,"__esModule",{value:!0});Iw.VaultFlags=void 0;var H7;(function(e){e[e.lsfVaultPrivate=65536]="lsfVaultPrivate"})(H7||(Iw.VaultFlags=H7={}))});var z7=q(Bt=>{"use strict";y();Object.defineProperty(Bt,"__esModule",{value:!0});Bt.VaultFlags=Bt.SponsorshipFlags=Bt.SignerListFlags=Bt.RippleStateFlags=Bt.OfferFlags=Bt.MPTokenIssuanceImmutableFlags=Bt.MPTokenIssuanceFlags=Bt.NEGATIVE_UNL_ID=Bt.LoanFlags=Bt.FEE_SETTINGS_ID=Bt.AMENDMENTS_ID=Bt.AccountRootFlags=void 0;var tne=hv();Object.defineProperty(Bt,"AccountRootFlags",{enumerable:!0,get:function(){return tne.AccountRootFlags}});var nne=D7();Object.defineProperty(Bt,"AMENDMENTS_ID",{enumerable:!0,get:function(){return nne.AMENDMENTS_ID}});var rne=R7();Object.defineProperty(Bt,"FEE_SETTINGS_ID",{enumerable:!0,get:function(){return rne.FEE_SETTINGS_ID}});var ine=L7();Object.defineProperty(Bt,"LoanFlags",{enumerable:!0,get:function(){return ine.LoanFlags}});var K7=mv();Object.defineProperty(Bt,"MPTokenIssuanceFlags",{enumerable:!0,get:function(){return K7.MPTokenIssuanceFlags}});Object.defineProperty(Bt,"MPTokenIssuanceImmutableFlags",{enumerable:!0,get:function(){return K7.MPTokenIssuanceImmutableFlags}});var one=B7();Object.defineProperty(Bt,"NEGATIVE_UNL_ID",{enumerable:!0,get:function(){return one.NEGATIVE_UNL_ID}});var ane=F3();Object.defineProperty(Bt,"OfferFlags",{enumerable:!0,get:function(){return ane.OfferFlags}});var sne=U7();Object.defineProperty(Bt,"RippleStateFlags",{enumerable:!0,get:function(){return sne.RippleStateFlags}});var cne=q7();Object.defineProperty(Bt,"SignerListFlags",{enumerable:!0,get:function(){return cne.SignerListFlags}});var lne=R3();Object.defineProperty(Bt,"SponsorshipFlags",{enumerable:!0,get:function(){return lne.SponsorshipFlags}});var une=V7();Object.defineProperty(Bt,"VaultFlags",{enumerable:!0,get:function(){return une.VaultFlags}})});var X7=q(j7=>{"use strict";y();Object.defineProperty(j7,"__esModule",{value:!0})});var Zy=q(ut=>{"use strict";y();var W7=ut&&ut.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),dne=ut&&ut.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),fne=ut&&ut.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&W7(t,e,n);return dne(t,e),t},wS=ut&&ut.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&W7(t,e,n)};Object.defineProperty(ut,"__esModule",{value:!0});ut.encodeMPTokenMetadata=ut.decodeMPTokenMetadata=ut.validateMPTokenMetadata=ut.parseTransactionFlags=ut.convertTxFlagsToNumber=ut.setTransactionFlagsToNumber=ut.parseMPTokenIssuanceImmutableFlags=ut.parseMPTokenIssuanceFlags=ut.parseAccountRootFlags=ut.LedgerEntry=void 0;ut.LedgerEntry=fne(z7());var Nd=ju();Object.defineProperty(ut,"parseAccountRootFlags",{enumerable:!0,get:function(){return Nd.parseAccountRootFlags}});Object.defineProperty(ut,"parseMPTokenIssuanceFlags",{enumerable:!0,get:function(){return Nd.parseMPTokenIssuanceFlags}});Object.defineProperty(ut,"parseMPTokenIssuanceImmutableFlags",{enumerable:!0,get:function(){return Nd.parseMPTokenIssuanceImmutableFlags}});Object.defineProperty(ut,"setTransactionFlagsToNumber",{enumerable:!0,get:function(){return Nd.setTransactionFlagsToNumber}});Object.defineProperty(ut,"convertTxFlagsToNumber",{enumerable:!0,get:function(){return Nd.convertTxFlagsToNumber}});Object.defineProperty(ut,"parseTransactionFlags",{enumerable:!0,get:function(){return Nd.parseTransactionFlags}});var bS=Zp();Object.defineProperty(ut,"validateMPTokenMetadata",{enumerable:!0,get:function(){return bS.validateMPTokenMetadata}});Object.defineProperty(ut,"decodeMPTokenMetadata",{enumerable:!0,get:function(){return bS.decodeMPTokenMetadata}});Object.defineProperty(ut,"encodeMPTokenMetadata",{enumerable:!0,get:function(){return bS.encodeMPTokenMetadata}});wS(X7(),ut);wS(Od(),ut);wS(yv(),ut)});var ex=q(Ld=>{"use strict";y();Object.defineProperty(Ld,"__esModule",{value:!0});Ld.combineBatchSigners=Ld.signMultiBatch=void 0;var Y7=Qn(),pne=_i(),Tl=fe(),yne=Zy(),hne=Xp(),Z7=xy(),J7=Dd();function mne(e,t,n,r=!1){let i;return r?i={BatchSigner:{Account:e,Signers:[{Signer:{Account:r,SigningPubKey:t.publicKey,TxnSignature:n}}]}}:i={BatchSigner:{Account:e,SigningPubKey:t.publicKey,TxnSignature:n}},i}function Q7(e){var t,n;let r=(t=e.Sequence)!==null&&t!==void 0?t:0;return r!==0?r:(n=e.TicketSequence)!==null&&n!==void 0?n:0}function gne(e,t,n={}){var r;let i=(r=n.batchAccount)!==null&&r!==void 0?r:e.classicAddress,o=!1;if(typeof n.multisign=="string"?o=n.multisign:n.multisign&&(o=e.classicAddress),t.TransactionType!=="Batch")throw new Tl.ValidationError("Must be a Batch transaction.");(0,yne.validate)(t);let a=new Set;if(t.RawTransactions.forEach(l=>{var u;a.add((u=l.RawTransaction.Delegate)!==null&&u!==void 0?u:l.RawTransaction.Account);let d=l.RawTransaction.Counterparty;typeof d=="string"&&a.add(d)}),!a.has(i))throw new Tl.ValidationError("Must be signing for an address submitting a transaction in the Batch.");let s=Object.assign({account:t.Account,sequence:Q7(t),flags:t.Flags,txIDs:t.RawTransactions.map(l=>(0,Z7.hashSignedTx)(l.RawTransaction)),batchAccount:i},o?{signerAccount:o}:{}),c=(0,pne.sign)((0,Y7.encodeForSigningBatch)(s),e.privateKey);t.BatchSigners=[mne(i,e,c,o)]}Ld.signMultiBatch=gne;function wne(e){if(e.length===0)throw new Tl.ValidationError("There are 0 transactions to combine.");let t=e.map(r=>(0,J7.getDecodedTransaction)(r));t.forEach(r=>{if(r.TransactionType!=="Batch")throw new Tl.ValidationError("TransactionType must be `Batch`.");if((0,hne.validateBatch)(r),r.BatchSigners==null||r.BatchSigners.length===0)throw new Tl.ValidationError("For combining Batch transaction signatures, all transactions must include a BatchSigners field containing an array of signatures.");if(r.TxnSignature!=null||r.Signers!=null)throw new Tl.ValidationError("Batch transaction must be unsigned.")});let n=t;return bne(n),(0,Y7.encode)(Cne(n))}Ld.combineBatchSigners=wne;function G7(e){return JSON.stringify({account:e.Account,sequence:Q7(e),flags:e.Flags,transactionIDs:e.RawTransactions.map(t=>(0,Z7.hashSignedTx)(t.RawTransaction))})}function bne(e){let t=G7(e[0]);if(e.slice(1).some(n=>G7(n)!==t))throw new Tl.ValidationError("Account, sequence, flags, and transaction hashes must be the same for all provided transactions.")}function Cne(e){let t=e[0].Account,n=e.flatMap(o=>{var a;return(a=o.BatchSigners)!==null&&a!==void 0?a:[]}).filter(o=>o.BatchSigner.Account!==t).sort((o,a)=>(0,J7.compareSigners)(o.BatchSigner,a.BatchSigner)),r=[],i="";for(let o of n){let a=o.BatchSigner.Account;a!==i&&(r.push(o),i=a)}return Object.assign(Object.assign({},e[0]),{BatchSigners:r})}});var tx=q(Pw=>{"use strict";y();Object.defineProperty(Pw,"__esModule",{value:!0});Pw.authorizeChannel=void 0;var vne=Qn(),Ane=_i();function Sne(e,t,n){let r=(0,vne.encodeForSigningClaim)({channel:t,amount:n});return(0,Ane.sign)(r,e.privateKey)}Pw.authorizeChannel=Sne});var ox=q(Zs=>{"use strict";y();var Tne=Zs&&Zs.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Zs,"__esModule",{value:!0});Zs.combineLoanSetCounterpartySigners=Zs.signLoanSetByCounterparty=void 0;var nx=Tne(Jg()),rx=Qn(),Ys=fe(),ix=Zy(),Ene=xy(),Jy=Dd();function kne(e,t,n={}){let r=(0,Jy.getDecodedTransaction)(t);if(r.TransactionType!=="LoanSet")throw new Ys.ValidationError("Transaction must be a LoanSet transaction.");if(r.CounterpartySignature)throw new Ys.ValidationError("Transaction is already signed by the counterparty.");if(r.TxnSignature==null||r.SigningPubKey==null)throw new Ys.ValidationError("Transaction must be first signed by first party.");(0,ix.validate)(r);let i=!1;typeof n.multisign=="string"?i=n.multisign:n.multisign&&(i=e.classicAddress),i?r.CounterpartySignature={Signers:[{Signer:{Account:i,SigningPubKey:e.publicKey,TxnSignature:(0,Jy.computeSignature)(r,e.privateKey,i,"counterparty")}}]}:r.CounterpartySignature={SigningPubKey:e.publicKey,TxnSignature:(0,Jy.computeSignature)(r,e.privateKey,void 0,"counterparty")};let o=(0,rx.encode)(r);return{tx:r,tx_blob:o,hash:(0,Ene.hashSignedTx)(o)}}Zs.signLoanSetByCounterparty=kne;function _ne(e){if(e.length===0)throw new Ys.ValidationError("There are 0 transactions to combine.");let t=e.map(i=>(0,Jy.getDecodedTransaction)(i));t.forEach(i=>{var o;if((0,ix.validate)(i),i.TransactionType!=="LoanSet")throw new Ys.ValidationError("Transaction must be a LoanSet transaction.");if(((o=i.CounterpartySignature)===null||o===void 0?void 0:o.Signers)==null||i.CounterpartySignature.Signers.length===0)throw new Ys.ValidationError("CounterpartySignature must have Signers.");if(i.TxnSignature==null||i.SigningPubKey==null)throw new Ys.ValidationError("Transaction must be first signed by first party.")});let n=t;Ine(n);let r=Pne(n);return{tx:r,tx_blob:(0,rx.encode)(r)}}Zs.combineLoanSetCounterpartySigners=_ne;function Ine(e){let t=(0,nx.default)(Object.assign(Object.assign({},e[0]),{CounterpartySignature:Object.assign(Object.assign({},e[0].CounterpartySignature),{Signers:null})}));if(e.slice(1).some(n=>(0,nx.default)(Object.assign(Object.assign({},n),{CounterpartySignature:Object.assign(Object.assign({},n.CounterpartySignature),{Signers:null})}))!==t))throw new Ys.ValidationError("LoanSet transactions are not the same.")}function Pne(e){let t=e.flatMap(n=>{var r,i;return(i=(r=n.CounterpartySignature)===null||r===void 0?void 0:r.Signers)!==null&&i!==void 0?i:[]}).sort((n,r)=>(0,Jy.compareSigners)(n.Signer,r.Signer));return Object.assign(Object.assign({},e[0]),{CounterpartySignature:{Signers:t}})}});var lx=q(Go=>{"use strict";y();var xne=Go&&Go.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Go,"__esModule",{value:!0});Go.addPreFundedSponsor=Go.combineSponsorSigners=Go.signAsSponsor=void 0;var ax=xne(Jg()),sx=Qn(),Dr=fe(),cx=Zy(),Qy=de(),Mne=xy(),eh=Dd();function One(e,t,n={}){let r=(0,eh.getDecodedTransaction)(t);if(r.SponsorSignature)throw new Dr.ValidationError("Transaction is already signed by the sponsor.");if((r.TxnSignature==null||r.SigningPubKey==null)&&(r.Signers==null||r.Signers.length===0))throw new Dr.ValidationError("Transaction must be first signed by the account.");if(r.SponsorFlags===void 0)throw new Dr.ValidationError("Transaction must have SponsorFlags field set before sponsor can sign.");if(r.Sponsor===void 0)throw new Dr.ValidationError("Transaction must have Sponsor field set before sponsor can sign.");let i=!1;if(typeof n.multisign=="string"?i=n.multisign:n.multisign&&(i=e.classicAddress),!i&&!(0,Qy.areAddressesEqual)(r.Sponsor,e.classicAddress))throw new Dr.ValidationError(`Transaction Sponsor field (${r.Sponsor}) does not match the signing wallet address (${e.classicAddress}).`);if((0,Qy.areAddressesEqual)(r.Account,r.Sponsor))throw new Dr.ValidationError("signAsSponsor: Sponsor cannot be the same as the transaction Account (self-sponsorship not allowed).");i?r.SponsorSignature={Signers:[{Signer:{Account:i,SigningPubKey:e.publicKey,TxnSignature:(0,eh.computeSignature)(r,e.privateKey,i,"sponsor")}}]}:r.SponsorSignature={SigningPubKey:e.publicKey,TxnSignature:(0,eh.computeSignature)(r,e.privateKey,void 0,"sponsor")},(0,cx.validate)(r);let o=(0,sx.encode)(r);return{tx:r,tx_blob:o,hash:(0,Mne.hashSignedTx)(o)}}Go.signAsSponsor=One;function Dne(e){if(e.length===0)throw new Dr.ValidationError("There are 0 transactions to combine.");let t=e.map(r=>(0,eh.getDecodedTransaction)(r));t.forEach(r=>{var i;if((0,cx.validate)(r),((i=r.SponsorSignature)===null||i===void 0?void 0:i.Signers)==null||r.SponsorSignature.Signers.length===0)throw new Dr.ValidationError("SponsorSignature must have Signers.");if((r.TxnSignature==null||r.SigningPubKey==null)&&(r.Signers==null||r.Signers.length===0))throw new Dr.ValidationError("Transaction must be first signed by the account.")}),Rne(t);let n=Nne(t);return{tx:n,tx_blob:(0,sx.encode)(n)}}Go.combineSponsorSigners=Dne;function Rne(e){let t=(0,ax.default)(Object.assign(Object.assign({},e[0]),{SponsorSignature:Object.assign(Object.assign({},e[0].SponsorSignature),{Signers:null})}));if(e.slice(1).some(n=>(0,ax.default)(Object.assign(Object.assign({},n),{SponsorSignature:Object.assign(Object.assign({},n.SponsorSignature),{Signers:null})}))!==t))throw new Dr.ValidationError("Sponsor transactions are not the same.")}function Nne(e){let t=e.flatMap(i=>{var o,a;return(a=(o=i.SponsorSignature)===null||o===void 0?void 0:o.Signers)!==null&&a!==void 0?a:[]}).sort((i,o)=>(0,eh.compareSigners)(i.Signer,o.Signer)),n=new Set,r=[];for(let i of t)n.has(i.Signer.Account)||(n.add(i.Signer.Account),r.push(i));return Object.assign(Object.assign({},e[0]),{SponsorSignature:{Signers:r}})}function Lne(e,t,n){if((0,Qy.areAddressesEqual)(e.Account,t))throw new Dr.ValidationError("addPreFundedSponsor: Sponsor and Account cannot be the same (self-sponsorship not allowed)");if(!Number.isInteger(n))throw new Dr.ValidationError("addPreFundedSponsor: SponsorFlags must be a valid integer");let r=Qy.SponsorFlags.spfSponsorFee|Qy.SponsorFlags.spfSponsorReserve;if((n&~r)!==0)throw new Dr.ValidationError("addPreFundedSponsor: SponsorFlags contains invalid flags");if(n===0)throw new Dr.ValidationError("addPreFundedSponsor: SponsorFlags must have at least one flag set");return Object.assign(Object.assign({},e),{Sponsor:t,SponsorFlags:n})}Go.addPreFundedSponsor=Lne});var nh=q(Ft=>{"use strict";y();var px=Ft&&Ft.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.addPreFundedSponsor=Ft.combineSponsorSigners=Ft.signAsSponsor=Ft.combineLoanSetCounterpartySigners=Ft.signLoanSetByCounterparty=Ft.authorizeChannel=Ft.verifySignature=Ft.multisign=Ft.combineBatchSigners=Ft.signMultiBatch=Ft.Wallet=void 0;var Bne=(mI(),Ji(hI)),ux=(DI(),Ji(OI)),Fne=(NI(),Ji(RI)),dx=We(),Une=px(Sn()),fx=lr(),$ne=Qn(),xw=_i(),AS=px(Hy()),Bd=fe(),qne=Od(),Hne=de(),Vne=hn(),Kne=D3(),zne=n3(),jne=k3(),Xne=fS(),Wne=gS(),CS=Dd(),vS=AS.default.ed25519,Gne="m/44'/144'/0'/0/0";function Yne(e){if(!(e.privateKey instanceof Uint8Array))throw new Bd.ValidationError("Unable to derive privateKey from mnemonic input");if(!(e.publicKey instanceof Uint8Array))throw new Bd.ValidationError("Unable to derive publicKey from mnemonic input")}var th=class e{constructor(t,n,r={}){this.publicKey=t,this.privateKey=n,this.classicAddress=r.masterAddress?(0,Kne.ensureClassicAddress)(r.masterAddress):(0,xw.deriveAddress)(t),this.seed=r.seed}get address(){return this.classicAddress}static generate(t=vS){if(!Object.values(AS.default).includes(t))throw new Bd.ValidationError("Invalid cryptographic signing algorithm");let n=(0,xw.generateSeed)({algorithm:t});return e.fromSeed(n,{algorithm:t})}static fromSeed(t,n={}){return e.deriveWallet(t,{algorithm:n.algorithm,masterAddress:n.masterAddress})}static fromEntropy(t,n={}){var r;let i=(r=n.algorithm)!==null&&r!==void 0?r:vS,o={entropy:(0,CS.validateEntropy)(t),algorithm:i},a=(0,xw.generateSeed)(o);return e.deriveWallet(a,{algorithm:i,masterAddress:n.masterAddress})}static fromMnemonic(t,n={}){var r,i;if(n.mnemonicEncoding==="rfc1751")return e.fromRFC1751Mnemonic(t,{masterAddress:n.masterAddress,algorithm:(r=n.algorithm)!==null&&r!==void 0?r:vS});if(!(0,ux.validateMnemonic)(t,Fne.wordlist))throw new Bd.ValidationError("Unable to parse the given mnemonic using bip39 encoding");let o=(0,ux.mnemonicToSeedSync)(t),s=Bne.HDKey.fromMasterSeed(o).derive((i=n.derivationPath)!==null&&i!==void 0?i:Gne);Yne(s);let c=(0,dx.bytesToHex)(s.publicKey),l=(0,dx.bytesToHex)(s.privateKey);return new e(c,`00${l}`,{masterAddress:n.masterAddress})}static fromRFC1751Mnemonic(t,n){let r=(0,Xne.rfc1751MnemonicToKey)(t),i;n.algorithm===AS.default.secp256k1?i="secp256k1":i="ed25519";let o=(0,fx.encodeSeed)(r,i);return e.fromSeed(o,{masterAddress:n.masterAddress,algorithm:n.algorithm})}static deriveWallet(t,n={}){let{publicKey:r,privateKey:i}=(0,xw.deriveKeypair)(t,{algorithm:n.algorithm});return new e(r,i,{seed:t,masterAddress:n.masterAddress})}sign(t,n){let r=!1;typeof n=="string"?r=n:n&&(r=this.classicAddress);let i=(0,zne.omitBy)(Object.assign({},t),s=>s==null);if(i.TxnSignature||i.Signers)throw new Bd.ValidationError('txJSON must not contain "TxnSignature" or "Signers" properties');if(Zne(i),(0,qne.validate)(i),(0,Vne.hasFlag)(i,Hne.GlobalFlags.tfInnerBatchTxn,"tfInnerBatchTxn"))throw new Bd.ValidationError("Cannot sign a Batch inner transaction.");let o=Object.assign({},i);if(r){o.SigningPubKey="";let s={Account:r,SigningPubKey:this.publicKey,TxnSignature:(0,CS.computeSignature)(o,this.privateKey,r)};o.Signers=[{Signer:s}]}else o.SigningPubKey=this.publicKey,o.TxnSignature=(0,CS.computeSignature)(o,this.privateKey);let a=(0,$ne.encode)(o);return{tx_blob:a,hash:(0,jne.hashSignedTx)(a)}}verifyTransaction(t){return(0,Wne.verifySignature)(t,this.publicKey)}getXAddress(t=!1,n=!1){return(0,fx.classicAddressToXAddress)(this.classicAddress,t,n)}};Ft.Wallet=th;th.fromSecret=th.fromSeed;function Zne(e){e.TransactionType==="Payment"&&typeof e.Amount!="string"&&e.Amount.value.includes(".")&&e.Amount.value.endsWith("0")&&(e.Amount=Object.assign({},e.Amount),e.Amount.value=new Une.default(e.Amount.value).toString())}var yx=ex();Object.defineProperty(Ft,"signMultiBatch",{enumerable:!0,get:function(){return yx.signMultiBatch}});Object.defineProperty(Ft,"combineBatchSigners",{enumerable:!0,get:function(){return yx.combineBatchSigners}});var hx=gS();Object.defineProperty(Ft,"multisign",{enumerable:!0,get:function(){return hx.multisign}});Object.defineProperty(Ft,"verifySignature",{enumerable:!0,get:function(){return hx.verifySignature}});var Jne=tx();Object.defineProperty(Ft,"authorizeChannel",{enumerable:!0,get:function(){return Jne.authorizeChannel}});var mx=ox();Object.defineProperty(Ft,"signLoanSetByCounterparty",{enumerable:!0,get:function(){return mx.signLoanSetByCounterparty}});Object.defineProperty(Ft,"combineLoanSetCounterpartySigners",{enumerable:!0,get:function(){return mx.combineLoanSetCounterpartySigners}});var SS=lx();Object.defineProperty(Ft,"signAsSponsor",{enumerable:!0,get:function(){return SS.signAsSponsor}});Object.defineProperty(Ft,"combineSponsorSigners",{enumerable:!0,get:function(){return SS.combineSponsorSigners}});Object.defineProperty(Ft,"addPreFundedSponsor",{enumerable:!0,get:function(){return SS.addPreFundedSponsor}})});var gx=q(mr=>{"use strict";y();Object.defineProperty(mr,"__esModule",{value:!0});mr.getFaucetPath=mr.getFaucetHost=mr.faucetNetworkIDs=mr.faucetNetworkPaths=mr.FaucetNetwork=void 0;var TS=fe(),Fd;(function(e){e.Testnet="faucet.altnet.rippletest.net",e.Devnet="faucet.devnet.rippletest.net"})(Fd||(mr.FaucetNetwork=Fd={}));mr.faucetNetworkPaths={[Fd.Testnet]:"/accounts",[Fd.Devnet]:"/accounts"};mr.faucetNetworkIDs=new Map([[1,Fd.Testnet],[2,Fd.Devnet]]);function Qne(e){if(e.networkID==null)throw new TS.XRPLFaucetError("Cannot create faucet URL without networkID or the faucetHost information");if(mr.faucetNetworkIDs.has(e.networkID))return mr.faucetNetworkIDs.get(e.networkID);throw e.networkID===0?new TS.XRPLFaucetError("Faucet is not available for mainnet."):new TS.XRPLFaucetError("Faucet URL is not defined or inferrable.")}mr.getFaucetHost=Qne;function ere(e){return e===void 0?"/accounts":mr.faucetNetworkPaths[e]||"/accounts"}mr.getFaucetPath=ere});var vx=q(Yo=>{"use strict";y();var Ud=Yo&&Yo.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(Yo,"__esModule",{value:!0});Yo.requestFunding=Yo.getStartingBalance=Yo.generateWalletToFund=void 0;var tre=lr(),rh=fe(),wx=gx(),nre=nh(),bx=1,Cx=20;function rre(e){return e&&(0,tre.isValidClassicAddress)(e.classicAddress)?e:nre.Wallet.generate()}Yo.generateWalletToFund=rre;function ire(e,t){return Ud(this,void 0,void 0,function*(){let n=0;try{n=Number(yield e.getXrpBalance(t))}catch{}return n})}Yo.getStartingBalance=ire;function ore(e,t,n,r,i){var o,a,s,c;return Ud(this,void 0,void 0,function*(){let l=(o=e.faucetHost)!==null&&o!==void 0?o:(0,wx.getFaucetHost)(t);if(!l)throw new rh.XRPLFaucetError("No faucet hostname could be derived");let u=(a=e.faucetPath)!==null&&a!==void 0?a:(0,wx.getFaucetPath)(l),d=(s=e.faucetProtocol)!==null&&s!==void 0?s:"https",p=yield fetch(`${d}://${l}${u}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(p.ok&&(!((c=p.headers.get("Content-Type"))===null||c===void 0)&&c.startsWith("application/json"))){let g=(yield p.json()).account.classicAddress;return are(t,g,r,n)}return sre(p)})}Yo.requestFunding=ore;function are(e,t,n,r){return Ud(this,void 0,void 0,function*(){if(!t)return Promise.reject(new rh.XRPLFaucetError("The faucet account is undefined"));let i=yield cre(e,t,r);if(i>r)return{wallet:n,balance:i};throw new rh.XRPLFaucetError(`Unable to fund address with faucet after waiting ${bx*Cx} seconds`)})}function sre(e){var t;return Ud(this,void 0,void 0,function*(){let n={contentType:(t=e.headers.get("Content-Type"))!==null&&t!==void 0?t:void 0,statusCode:e.status},r=e.clone();try{let i=yield e.json();n.body=i}catch{n.body=yield r.text()}return Promise.reject(new rh.XRPLFaucetError(`Request failed: ${JSON.stringify(n)}`))})}function cre(e,t,n){return Ud(this,void 0,void 0,function*(){return new Promise((r,i)=>{let o=Cx,a=setInterval(()=>Ud(this,void 0,void 0,function*(){o<0?(clearInterval(a),r(n)):o-=1;try{let s;try{s=Number(yield e.getXrpBalance(t))}catch{}s>n&&(clearInterval(a),r(s))}catch(s){clearInterval(a),s instanceof Error&&i(new rh.XRPLFaucetError(`Unable to check if the address ${t} balance has increased. Error: ${s.message}`)),i(s)}}),bx*1e3)})})}});var Ka=q((Wbe,Tx)=>{"use strict";y();var Ax=["nodebuffer","arraybuffer","fragments"],Sx=typeof Blob<"u";Sx&&Ax.push("blob");Tx.exports={BINARY_TYPES:Ax,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Sx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ih=q((Ybe,$d)=>{"use strict";y();var{websocketMask:Ex,websocketUnmask:lre}=At("http"),{EMPTY_BUFFER:ure}=Ka(),ES=Buffer[Symbol.species];function dre(e,t){if(e.length===0)return ure;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),r=0;for(let i=0;i{"use strict";y();var kx=Symbol("kDone"),PS=Symbol("kRun"),xS=class{constructor(t){this[kx]=()=>{this.pending--,this[PS]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[PS]()}[PS](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[kx])}}};_x.exports=xS});var Vd=q((eCe,Ox)=>{"use strict";y();var oh=At("zlib"),Px=ih(),pre=Ix(),{kStatusCode:xx}=Ka(),yre=Buffer[Symbol.species],hre=Buffer.from([0,0,255,255]),Ow=Symbol("permessage-deflate"),za=Symbol("total-length"),qd=Symbol("callback"),Js=Symbol("buffers"),Hd=Symbol("error"),Mw,MS=class{constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Mw){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Mw=new pre(n)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[qd];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let n=this._options,r=t.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&(typeof i.client_max_window_bits=="number"?n.clientMaxWindowBits>i.client_max_window_bits:!i.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(t){let n=t[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(t){return t.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),t}decompress(t,n,r){Mw.add(i=>{this._decompress(t,n,(o,a)=>{i(),r(o,a)})})}compress(t,n,r){Mw.add(i=>{this._compress(t,n,(o,a)=>{i(),r(o,a)})})}_decompress(t,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?oh.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=oh.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Ow]=this,this._inflate[za]=0,this._inflate[Js]=[],this._inflate.on("error",gre),this._inflate.on("data",Mx)}this._inflate[qd]=r,this._inflate.write(t),n&&this._inflate.write(hre),this._inflate.flush(()=>{let o=this._inflate[Hd];if(o){this._inflate.close(),this._inflate=null,r(o);return}let a=Px.concat(this._inflate[Js],this._inflate[za]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[za]=0,this._inflate[Js]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,a)})}_compress(t,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?oh.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=oh.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[za]=0,this._deflate[Js]=[],this._deflate.on("data",mre)}this._deflate[qd]=r,this._deflate.write(t),this._deflate.flush(oh.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Px.concat(this._deflate[Js],this._deflate[za]);n&&(o=new yre(o.buffer,o.byteOffset,o.length-4)),this._deflate[qd]=null,this._deflate[za]=0,this._deflate[Js]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};Ox.exports=MS;function mre(e){this[Js].push(e),this[za]+=e.length}function Mx(e){if(this[za]+=e.length,this[Ow]._maxPayload<1||this[za]<=this[Ow]._maxPayload){this[Js].push(e);return}this[Hd]=new RangeError("Max payload size exceeded"),this[Hd].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hd][xx]=1009,this.removeListener("data",Mx),this.reset()}function gre(e){if(this[Ow]._inflate=null,this[Hd]){this[qd](this[Hd]);return}e[xx]=1007,this[qd](e)}});var Kd=q((nCe,Dw)=>{"use strict";y();var{isUtf8:Dx}=At("buffer"),{hasBlob:wre}=Ka(),bre=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Cre(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function OS(e){let t=e.length,n=0;for(;n=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||e[n]===224&&(e[n+1]&224)===128||e[n]===237&&(e[n+1]&224)===160)return!1;n+=3}else if((e[n]&248)===240){if(n+3>=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||(e[n+3]&192)!==128||e[n]===240&&(e[n+1]&240)===128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function vre(e){return wre&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}Dw.exports={isBlob:vre,isValidStatusCode:Cre,isValidUTF8:OS,tokenChars:bre};if(Dx)Dw.exports.isValidUTF8=function(e){return e.length<24?OS(e):Dx(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=At("utf-8-validate");Dw.exports.isValidUTF8=function(t){return t.length<32?OS(t):e(t)}}catch{}});var BS=q((iCe,$x)=>{"use strict";y();var{Writable:Are}=At("stream"),Rx=Vd(),{BINARY_TYPES:Sre,EMPTY_BUFFER:Nx,kStatusCode:Tre,kWebSocket:Ere}=Ka(),{concat:DS,toArrayBuffer:kre,unmask:_re}=ih(),{isValidStatusCode:Ire,isValidUTF8:Lx}=Kd(),Rw=Buffer[Symbol.species],Mi=0,Bx=1,Fx=2,Ux=3,RS=4,NS=5,Nw=6,LS=class extends Are{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||Sre[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[Ere]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Mi}_write(t,n,r){if(this._opcode===8&&this._state==Mi)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(r)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,t),i),this._buffers[0]=new Rw(r.buffer,r.byteOffset+t,r.length-t)),t-=r.length}while(t>0);return n}startLoop(t){this._loop=!0;do switch(this._state){case Mi:this.getInfo(t);break;case Bx:this.getPayloadLength16(t);break;case Fx:this.getPayloadLength64(t);break;case Ux:this.getMask();break;case RS:this.getData(t);break;case NS:case Nw:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Rx.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(i);return}this._payloadLength===126?this._state=Bx:this._payloadLength===127?this._state=Fx:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(n);return}this._masked?this._state=Ux:this._state=RS}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=RS}getData(t){let n=Nx;if(this._payloadLength){if(this._bufferedBytes7){this.controlMessage(n,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(r);return}if(this._compressed){this._state=NS,this.decompress(n,t);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(t)}decompress(t,n){this._extensions[Rx.extensionName].decompress(t,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(a);return}this._fragments.push(o)}this.dataMessage(n),this._state===Mi&&this.startLoop(n)})}dataMessage(t){if(!this._fin){this._state=Mi;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=DS(r,n):this._binaryType==="arraybuffer"?i=kre(DS(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Mi):(this._state=Nw,setImmediate(()=>{this.emit("message",i,!0),this._state=Mi,this.startLoop(t)}))}else{let i=DS(r,n);if(!this._skipUTF8Validation&&!Lx(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._state===NS||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Mi):(this._state=Nw,setImmediate(()=>{this.emit("message",i,!1),this._state=Mi,this.startLoop(t)}))}}controlMessage(t,n){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,Nx),this.end();else{let r=t.readUInt16BE(0);if(!Ire(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new Rw(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Lx(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=Mi;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=Mi):(this._state=Nw,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=Mi,this.startLoop(n)}))}createError(t,n,r,i,o){this._loop=!1,this._errored=!0;let a=new t(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(a,this.createError),a.code=o,a[Tre]=i,a}};$x.exports=LS});var $S=q((sCe,Vx)=>{"use strict";y();var{Duplex:aCe}=At("stream"),{randomFillSync:Pre}=At("crypto"),{types:{isUint8Array:xre}}=At("util"),qx=Vd(),{EMPTY_BUFFER:Mre,kWebSocket:Ore,NOOP:Dre}=Ka(),{isBlob:zd,isValidStatusCode:Rre}=Kd(),{mask:Hx,toBuffer:El}=ih(),Oi=Symbol("kByteLength"),Nre=Buffer.alloc(4),Lw=8*1024,kl,jd=Lw,go=0,Lre=1,Bre=2,FS=class e{constructor(t,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=go,this.onerror=Dre,this[Ore]=void 0}static frame(t,n){let r,i=!1,o=2,a=!1;n.mask&&(r=n.maskBuffer||Nre,n.generateMask?n.generateMask(r):(jd===Lw&&(kl===void 0&&(kl=Buffer.alloc(Lw)),Pre(kl,0,Lw),jd=0),r[0]=kl[jd++],r[1]=kl[jd++],r[2]=kl[jd++],r[3]=kl[jd++]),a=(r[0]|r[1]|r[2]|r[3])===0,o=6);let s;typeof t=="string"?(!n.mask||a)&&n[Oi]!==void 0?s=n[Oi]:(t=Buffer.from(t),s=t.length):(s=t.length,i=n.mask&&n.readOnly&&!a);let c=s;s>=65536?(o+=8,c=127):s>125&&(o+=2,c=126);let l=Buffer.allocUnsafe(i?s+o:o);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),n.mask?(l[1]|=128,l[o-4]=r[0],l[o-3]=r[1],l[o-2]=r[2],l[o-1]=r[3],s?a?[l,t]:i?(Hx(t,r,l,o,s),[l]):(Hx(t,r,t,0,s),[l,t]):[l]):s?[l,t]:[l]}close(t,n,r,i){let o;if(t===void 0)o=Mre;else{if(typeof t!="number"||!Rre(t))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let s=Buffer.byteLength(n);if(s>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+s),o.writeUInt16BE(t,0),typeof n=="string")o.write(n,2);else if(xre(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[Oi]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==go?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(e.frame(o,a),i)}ping(t,n,r){let i,o;if(typeof t=="string"?(i=Buffer.byteLength(t),o=!1):zd(t)?(i=t.size,o=!1):(t=El(t),i=t.length,o=El.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Oi]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};zd(t)?this._state!==go?this.enqueue([this.getBlobData,t,!1,a,r]):this.getBlobData(t,!1,a,r):this._state!==go?this.enqueue([this.dispatch,t,!1,a,r]):this.sendFrame(e.frame(t,a),r)}pong(t,n,r){let i,o;if(typeof t=="string"?(i=Buffer.byteLength(t),o=!1):zd(t)?(i=t.size,o=!1):(t=El(t),i=t.length,o=El.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Oi]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};zd(t)?this._state!==go?this.enqueue([this.getBlobData,t,!1,a,r]):this.getBlobData(t,!1,a,r):this._state!==go?this.enqueue([this.dispatch,t,!1,a,r]):this.sendFrame(e.frame(t,a),r)}send(t,n,r){let i=this._extensions[qx.extensionName],o=n.binary?2:1,a=n.compress,s,c;typeof t=="string"?(s=Buffer.byteLength(t),c=!1):zd(t)?(s=t.size,c=!1):(t=El(t),s=t.length,c=El.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=i._threshold),this._compress=a):(a=!1,o=0),n.fin&&(this._firstFragment=!0);let l={[Oi]:s,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:a};zd(t)?this._state!==go?this.enqueue([this.getBlobData,t,this._compress,l,r]):this.getBlobData(t,this._compress,l,r):this._state!==go?this.enqueue([this.dispatch,t,this._compress,l,r]):this.dispatch(t,this._compress,l,r)}getBlobData(t,n,r,i){this._bufferedBytes+=r[Oi],this._state=Bre,t.arrayBuffer().then(o=>{if(this._socket.destroyed){let s=new Error("The socket was closed while the blob was being read");process.nextTick(US,this,s,i);return}this._bufferedBytes-=r[Oi];let a=El(o);n?this.dispatch(a,n,r,i):(this._state=go,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(o=>{process.nextTick(Fre,this,o,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let o=this._extensions[qx.extensionName];this._bufferedBytes+=r[Oi],this._state=Lre,o.compress(t,r.fin,(a,s)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");US(this,c,i);return}this._bufferedBytes-=r[Oi],this._state=go,r.readOnly=!1,this.sendFrame(e.frame(s,r),i),this.dequeue()})}dequeue(){for(;this._state===go&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][Oi],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][Oi],this._queue.push(t)}sendFrame(t,n){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],n),this._socket.uncork()):this._socket.write(t[0],n)}};Vx.exports=FS;function US(e,t,n){typeof n=="function"&&n(t);for(let r=0;r{"use strict";y();var{kForOnEventAttribute:ah,kListener:qS}=Ka(),Kx=Symbol("kCode"),zx=Symbol("kData"),jx=Symbol("kError"),Xx=Symbol("kMessage"),Wx=Symbol("kReason"),Xd=Symbol("kTarget"),Gx=Symbol("kType"),Yx=Symbol("kWasClean"),ja=class{constructor(t){this[Xd]=null,this[Gx]=t}get target(){return this[Xd]}get type(){return this[Gx]}};Object.defineProperty(ja.prototype,"target",{enumerable:!0});Object.defineProperty(ja.prototype,"type",{enumerable:!0});var _l=class extends ja{constructor(t,n={}){super(t),this[Kx]=n.code===void 0?0:n.code,this[Wx]=n.reason===void 0?"":n.reason,this[Yx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Kx]}get reason(){return this[Wx]}get wasClean(){return this[Yx]}};Object.defineProperty(_l.prototype,"code",{enumerable:!0});Object.defineProperty(_l.prototype,"reason",{enumerable:!0});Object.defineProperty(_l.prototype,"wasClean",{enumerable:!0});var Wd=class extends ja{constructor(t,n={}){super(t),this[jx]=n.error===void 0?null:n.error,this[Xx]=n.message===void 0?"":n.message}get error(){return this[jx]}get message(){return this[Xx]}};Object.defineProperty(Wd.prototype,"error",{enumerable:!0});Object.defineProperty(Wd.prototype,"message",{enumerable:!0});var sh=class extends ja{constructor(t,n={}){super(t),this[zx]=n.data===void 0?null:n.data}get data(){return this[zx]}};Object.defineProperty(sh.prototype,"data",{enumerable:!0});var Ure={addEventListener(e,t,n={}){for(let i of this.listeners(e))if(!n[ah]&&i[qS]===t&&!i[ah])return;let r;if(e==="message")r=function(o,a){let s=new sh("message",{data:a?o:o.toString()});s[Xd]=this,Bw(t,this,s)};else if(e==="close")r=function(o,a){let s=new _l("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Xd]=this,Bw(t,this,s)};else if(e==="error")r=function(o){let a=new Wd("error",{error:o,message:o.message});a[Xd]=this,Bw(t,this,a)};else if(e==="open")r=function(){let o=new ja("open");o[Xd]=this,Bw(t,this,o)};else return;r[ah]=!!n[ah],r[qS]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(let n of this.listeners(e))if(n[qS]===t&&!n[ah]){this.removeListener(e,n);break}}};Zx.exports={CloseEvent:_l,ErrorEvent:Wd,Event:ja,EventTarget:Ure,MessageEvent:sh};function Bw(e,t,n){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}});var Fw=q((dCe,Qx)=>{"use strict";y();var{tokenChars:ch}=Kd();function Zo(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function $re(e){let t=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,a,s,c=-1,l=-1,u=-1,d=0;for(;d{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(r=>[t].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Qx.exports={format:qre,parse:$re}});var Hw=q((hCe,dM)=>{"use strict";y();var Hre=At("events"),Vre=At("https"),Kre=At("http"),rM=At("net"),eM=At("querystring"),zre=At("tls"),{randomBytes:jre,createHash:Xre}=At("crypto"),{Duplex:pCe,Readable:yCe}=At("stream"),{URL:Uw}=At("url"),Qs=Vd(),Wre=BS(),Gre=$S(),{isBlob:Yre}=Kd(),{BINARY_TYPES:tM,CLOSE_TIMEOUT:Zre,EMPTY_BUFFER:lh,GUID:Jre,kForOnEventAttribute:HS,kListener:Qre,kStatusCode:eie,kWebSocket:Bn,NOOP:tie}=Ka(),{EventTarget:{addEventListener:nie,removeEventListener:rie}}=Jx(),{format:iie,parse:oie}=Fw(),{toBuffer:aie}=ih(),iM=Symbol("kAborted"),VS=[8,13],Xa=["CONNECTING","OPEN","CLOSING","CLOSED"],sie=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Kt=class e extends Hre{constructor(t,n,r){super(),this._binaryType=tM[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=lh,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?!r||r.protocols===void 0?n=[]:Array.isArray(r.protocols)?n=r.protocols:n=[r.protocols]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,r.protocols===void 0?n=[]:Array.isArray(r.protocols)?n=r.protocols:n=[r.protocols]):n=[n]),r=oM(this,t,n,r)):this._isServer=!0,r.autoPong&&(this._autoPong=!0,this._autoPongComplete=()=>hie(this),this._pendingAutoPongs=0,this._maxPendingAutoPongs=r.maxPendingAutoPongs|0),this._closeTimeout=r.closeTimeout}get binaryType(){return this._binaryType}set binaryType(t){tM.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new Wre({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new Gre(t,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[Bn]=this,o[Bn]=this,t[Bn]=this,i.on("conclude",uie),i.on("drain",die),i.on("error",fie),i.on("message",pie),i.on("ping",yie),i.on("pong",mie),o.onerror=gie,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",cM),t.on("data",qw),t.on("end",lM),t.on("error",uM),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Qs.extensionName]&&this._extensions[Qs.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){ai(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(t,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=e.CLOSING,sM(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(r=t,t=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){KS(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||lh,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(r=t,t=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){KS(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||lh,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){KS(this,t,r);return}let i={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Qs.extensionName]||(i.compress=!1),this._sender.send(t||lh,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){ai(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(Kt,"CONNECTING",{enumerable:!0,value:Xa.indexOf("CONNECTING")});Object.defineProperty(Kt.prototype,"CONNECTING",{enumerable:!0,value:Xa.indexOf("CONNECTING")});Object.defineProperty(Kt,"OPEN",{enumerable:!0,value:Xa.indexOf("OPEN")});Object.defineProperty(Kt.prototype,"OPEN",{enumerable:!0,value:Xa.indexOf("OPEN")});Object.defineProperty(Kt,"CLOSING",{enumerable:!0,value:Xa.indexOf("CLOSING")});Object.defineProperty(Kt.prototype,"CLOSING",{enumerable:!0,value:Xa.indexOf("CLOSING")});Object.defineProperty(Kt,"CLOSED",{enumerable:!0,value:Xa.indexOf("CLOSED")});Object.defineProperty(Kt.prototype,"CLOSED",{enumerable:!0,value:Xa.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(Kt.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(Kt.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[HS])return t[Qre];return null},set(t){for(let n of this.listeners(e))if(n[HS]){this.removeListener(e,n);break}typeof t=="function"&&this.addEventListener(e,t,{[HS]:!0})}})});Kt.prototype.addEventListener=nie;Kt.prototype.removeEventListener=rie;dM.exports=Kt;function oM(e,t,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Zre,protocolVersion:VS[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,maxPendingAutoPongs:60,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!VS.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${VS.join(", ")})`);let o;if(t instanceof Uw)o=t;else try{o=new Uw(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}(o.protocol==="http:"||o.protocol==="https:")&&(o=new Uw(o),o.protocol=o.protocol==="http:"?"ws:":"wss:"),e._url=o.href;let a=o.protocol==="wss:",s=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!a&&!s?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:s&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let w=new SyntaxError(c);if(e._redirects===0)throw w;$w(e,w);return}let l=a?443:80,u=jre(16).toString("base64"),d=a?Vre.request:Kre.request,p=new Set,h;if(i.createConnection=i.createConnection||(a?lie:cie),i.defaultPort=i.defaultPort||l,i.port=o.port||l,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new Qs({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=iie({[Qs.extensionName]:h.offer()})),n.length){for(let w of n){if(typeof w!="string"||!sie.test(w)||p.has(w))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(w)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),o.username||o.password){let w=eM.unescape(o.username),T=eM.unescape(o.password);i.auth=`${w}:${T}`}if(s){let w=i.path.indexOf(":");w===-1?(i.socketPath=i.path,i.path=""):(i.socketPath=i.path.slice(0,w),i.path=i.path.slice(w+1))}let g;if(i.followRedirects){if(e._redirects===0){e._originalIpc=s,e._originalSecure=a,e._originalHostOrSocketPath=s?i.socketPath:o.host;let w=r&&r.headers;if(r={...r,headers:{}},w)for(let[T,k]of Object.entries(w))r.headers[T.toLowerCase()]=k}else if(e.listenerCount("redirect")===0){let w=s?e._originalIpc?i.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:o.host===e._originalHostOrSocketPath;(!w||e._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,w||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),g=e._req=d(i),e._redirects&&e.emit("redirect",e.url,g)}else g=e._req=d(i);return i.timeout&&g.on("timeout",()=>{ai(e,g,"Opening handshake has timed out")}),g.on("error",w=>{g===null||g[iM]||(g=e._req=null,$w(e,w))}),g.on("response",w=>{let T=w.headers.location,k=w.statusCode;if(T&&i.followRedirects&&k>=300&&k<400){if(++e._redirects>i.maxRedirects){ai(e,g,"Maximum redirects exceeded");return}g.abort();let B;try{B=new Uw(T,t)}catch{let P=new SyntaxError(`Invalid URL: ${T}`);$w(e,P);return}oM(e,B,n,r)}else e.emit("unexpected-response",g,w)||ai(e,g,`Unexpected server response: ${w.statusCode}`)}),g.on("upgrade",(w,T,k)=>{if(e.emit("upgrade",w),e.readyState!==Kt.CONNECTING)return;g=e._req=null;let B=w.headers.upgrade;if(B===void 0||B.toLowerCase()!=="websocket"){ai(e,T,"Invalid Upgrade header");return}let D=Xre("sha1").update(u+Jre).digest("base64");if(w.headers["sec-websocket-accept"]!==D){ai(e,T,"Invalid Sec-WebSocket-Accept header");return}let P=w.headers["sec-websocket-protocol"],U;if(P!==void 0?p.size?p.has(P)||(U="Server sent an invalid subprotocol"):U="Server sent a subprotocol but none was requested":p.size&&(U="Server sent no subprotocol"),U){ai(e,T,U);return}P&&(e._protocol=P);let F=w.headers["sec-websocket-extensions"];if(F!==void 0){if(!h){ai(e,T,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let H;try{H=oie(F)}catch{ai(e,T,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(H);if(b.length!==1||b[0]!==Qs.extensionName){ai(e,T,"Server indicated an extension that was not requested");return}try{h.accept(H[Qs.extensionName])}catch{ai(e,T,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[Qs.extensionName]=h}e.setSocket(T,k,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,e):g.end(),i}function $w(e,t){e._readyState=Kt.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function cie(e){return e.path=e.socketPath,rM.connect(e)}function lie(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=rM.isIP(e.host)?"":e.host),zre.connect(e)}function ai(e,t,n){e._readyState=Kt.CLOSING;let r=new Error(n);Error.captureStackTrace(r,ai),t.setHeader?(t[iM]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick($w,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function KS(e,t,n){if(t){let r=Yre(t)?t.size:aie(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${e.readyState} (${Xa[e.readyState]})`);process.nextTick(n,r)}}function uie(e,t){let n=this[Bn];n._closeFrameReceived=!0,n._closeCode=e,t.length===0?n._closeMessage=lh:(n._closeMessage=Buffer.allocUnsafeSlow(t.length),n._closeMessage.set(t)),n._socket[Bn]!==void 0&&(n._socket.removeListener("data",qw),process.nextTick(aM,n._socket),e===1005?n.close():n.close(e,t))}function die(){let e=this[Bn];e.isPaused||e._socket.resume()}function fie(e){let t=this[Bn];t._socket[Bn]!==void 0&&(t._socket.removeListener("data",qw),process.nextTick(aM,t._socket),t.close(e[eie])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function nM(){this[Bn].emitClose()}function pie(e,t){this[Bn].emit("message",e,t)}function yie(e){let t=this[Bn];t._autoPong&&t.readyState===Kt.OPEN&&(t._maxPendingAutoPongs>0&&t._pendingAutoPongs>=t._maxPendingAutoPongs?t.terminate():(t._pendingAutoPongs++,t.pong(e,!this._isServer,t._autoPongComplete))),t.emit("ping",e)}function hie(e){e._pendingAutoPongs--}function mie(e){this[Bn].emit("pong",e)}function aM(e){e.resume()}function gie(e){let t=this[Bn];t.readyState!==Kt.CLOSED&&(t.readyState===Kt.OPEN&&(t._readyState=Kt.CLOSING,sM(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function sM(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function cM(){let e=this[Bn];if(this.removeListener("close",cM),this.removeListener("data",qw),this.removeListener("end",lM),e._readyState=Kt.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[Bn]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",nM),e._receiver.on("finish",nM))}function qw(e){this[Bn]._receiver.write(e)||this.pause()}function lM(){let e=this[Bn];e._readyState=Kt.CLOSING,e._receiver.end(),this.end()}function uM(){let e=this[Bn];this.removeListener("error",uM),this.on("error",tie),e&&(e._readyState=Kt.CLOSING,this.destroy())}});var hM=q((wCe,yM)=>{"use strict";y();var gCe=Hw(),{Duplex:wie}=At("stream");function fM(e){e.emit("close")}function bie(){!this.destroyed&&this._writableState.finished&&this.destroy()}function pM(e){this.removeListener("error",pM),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Cie(e,t){let n=!0,r=new wie({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(o,a){let s=!a&&r._readableState.objectMode?o.toString():o;r.push(s)||e.pause()}),e.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),e.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(e.readyState===e.CLOSED){o(i),process.nextTick(fM,r);return}let a=!1;e.once("error",function(c){a=!0,o(c)}),e.once("close",function(){a||o(i),process.nextTick(fM,r)}),n&&e.terminate()},r._final=function(i){if(e.readyState===e.CONNECTING){e.once("open",function(){r._final(i)});return}e._socket!==null&&(e._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(e._socket.once("finish",function(){i()}),e.close()))},r._read=function(){e.isPaused&&e.resume()},r._write=function(i,o,a){if(e.readyState===e.CONNECTING){e.once("open",function(){r._write(i,o,a)});return}e.send(i,a)},r.on("end",bie),r.on("error",pM),r}yM.exports=Cie});var zS=q((CCe,mM)=>{"use strict";y();var{tokenChars:vie}=Kd();function Aie(e){let t=new Set,n=-1,r=-1,i=0;for(i;i{"use strict";y();var Sie=At("events"),Vw=At("http"),{Duplex:ACe}=At("stream"),{createHash:Tie}=At("crypto"),gM=Fw(),Il=Vd(),Eie=zS(),kie=Hw(),{CLOSE_TIMEOUT:_ie,GUID:Iie,kWebSocket:Pie}=Ka(),xie=/^[+/0-9A-Za-z]{22}==$/,wM=0,bM=1,vM=2,jS=class extends Sie{constructor(t,n){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:_ie,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:kie,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=Vw.createServer((r,i)=>{let o=Vw.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(t.port,t.host,t.backlog,n)):t.server&&(this._server=t.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Mie(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,r)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=wM}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===vM){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(uh,this);return}if(t&&this.once("close",t),this._state!==bM)if(this._state=bM,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(uh,this):process.nextTick(uh,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{uh(this)})}}shouldHandle(t){if(this.options.path){let n=t.url.indexOf("?");if((n!==-1?t.url.slice(0,n):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,n,r,i){n.on("error",CM);let o=t.headers["sec-websocket-key"],a=t.headers.upgrade,s=+t.headers["sec-websocket-version"];if(t.method!=="GET"){Pl(this,t,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Pl(this,t,n,400,"Invalid Upgrade header");return}if(o===void 0||!xie.test(o)){Pl(this,t,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(s!==13&&s!==8){Pl(this,t,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){dh(n,400);return}let c=t.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Eie.parse(c)}catch{Pl(this,t,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=t.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let p=new Il({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=gM.parse(u);h[Il.extensionName]&&(p.accept(h[Il.extensionName]),d[Il.extensionName]=p)}catch{Pl(this,t,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:t.headers[`${s===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,g,w,T)=>{if(!h)return dh(n,g||401,w,T);this.completeUpgrade(d,o,l,t,n,r,i)});return}if(!this.options.verifyClient(p))return dh(n,401)}this.completeUpgrade(d,o,l,t,n,r,i)}completeUpgrade(t,n,r,i,o,a,s){if(!o.readable||!o.writable)return o.destroy();if(o[Pie])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>wM)return dh(o,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Tie("sha1").update(n+Iie).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(t[Il.extensionName]){let d=t[Il.extensionName].params,p=gM.format({[Il.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${p}`),u._extensions=t}this.emit("headers",l,i),o.write(l.concat(`\r `).join(`\r `)),o.removeListener("error",CM),u.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(uh,this)})),s(u,i)}};AM.exports=jS;function Mie(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let r of Object.keys(t))e.removeListener(r,t[r])}}function uh(e){e._state=vM,e.emit("close")}function CM(){this.destroy()}function dh(e,t,n,r){n=n||Vw.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Vw.STATUS_CODES[t]}\r `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r `)+`\r \r `+n)}function Pl(e,t,n,r,i,o){if(e.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,Pl),e.emit("wsClientError",a,n,t)}else dh(n,r,i,o)}});var kM=q((ECe,EM)=>{"use strict";y();var Oie=hM(),Die=Fw(),Rie=Vd(),Nie=BS(),Lie=$S(),Bie=zS(),wo=Hw(),TM=SM();wo.createWebSocketStream=Oie;wo.extension=Die;wo.PerMessageDeflate=Rie;wo.Receiver=Nie;wo.Sender=Lie;wo.Server=TM;wo.subprotocol=Bie;wo.WebSocket=wo;wo.WebSocketServer=TM;EM.exports=wo});var _M=q(fh=>{"use strict";y();var Fie=fh&&fh.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(fh,"__esModule",{value:!0});var Uie=Fie(kM()),XS=class extends Uie.default{constructor(...t){super(t[0],t[1],t[2]),this.setMaxListeners(1/0)}};fh.default=XS});var IM=q(ph=>{"use strict";y();var $ie=ph&&ph.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(ph,"__esModule",{value:!0});var WS=class{constructor(){this.promisesAwaitingConnection=[]}resolveAllAwaiting(){this.promisesAwaitingConnection.map(({resolve:t})=>t()),this.promisesAwaitingConnection=[]}rejectAllAwaiting(t){this.promisesAwaitingConnection.map(({reject:n})=>n(t)),this.promisesAwaitingConnection=[]}awaitConnection(){return $ie(this,void 0,void 0,function*(){return new Promise((t,n)=>{this.promisesAwaitingConnection.push({resolve:t,reject:n})})})}};ph.default=WS});var PM=q(YS=>{"use strict";y();Object.defineProperty(YS,"__esModule",{value:!0});var qie=100,Hie=1e3,GS=class{constructor(t={}){var n,r;this.factor=2,this.numAttempts=0,this.ms=(n=t.min)!==null&&n!==void 0?n:qie,this.max=(r=t.max)!==null&&r!==void 0?r:Hie}get attempts(){return this.numAttempts}duration(){let t=this.ms*Math.pow(this.factor,this.numAttempts);return this.numAttempts+=1,Math.floor(Math.min(t,this.max))}reset(){this.numAttempts=0}};YS.default=GS});var xM=q(yh=>{"use strict";y();var Vie=yh&&yh.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(yh,"__esModule",{value:!0});var ec=fe(),ZS=class{constructor(){this.nextId=0,this.promisesAwaitingResponse=new Map}addPromise(t,n){return Vie(this,void 0,void 0,function*(){return new Promise((r,i)=>{this.promisesAwaitingResponse.set(t,{resolve:r,reject:i,timer:n})})})}resolve(t,n){let r=this.promisesAwaitingResponse.get(t);if(r==null)throw new ec.XrplError(`No existing promise with id ${t}`,{type:"resolve",response:n});clearTimeout(r.timer),r.resolve(n),this.deletePromise(t)}reject(t,n){let r=this.promisesAwaitingResponse.get(t);if(r==null)throw new ec.XrplError(`No existing promise with id ${t}`,{type:"reject",error:n});clearTimeout(r.timer),r.reject(n),this.deletePromise(t)}rejectAll(t){this.promisesAwaitingResponse.forEach((n,r,i)=>{this.reject(r,t),this.deletePromise(r)})}createRequest(t,n){let r;t.id==null?(r=this.nextId,this.nextId+=1):r=t.id;let i=JSON.stringify(Object.assign(Object.assign({},t),{id:r})),o=setTimeout(()=>{this.reject(r,new ec.TimeoutError(`Timeout for request: ${JSON.stringify(t)} with id ${r}`,t))},n);if(o.unref&&o.unref(),this.promisesAwaitingResponse.has(r))throw clearTimeout(o),new ec.XrplError(`Response with id '${r}' is already pending`,t);let a=new Promise((s,c)=>{this.promisesAwaitingResponse.set(r,{resolve:s,reject:c,timer:o})});return[r,i,a]}handleResponse(t){var n,r,i;if(t.id==null||!(typeof t.id=="string"||typeof t.id=="number"))throw new ec.ResponseFormatError("valid id not found in response",t);if(this.promisesAwaitingResponse.has(t.id)){if(t.status==null){let o=new ec.ResponseFormatError("Response has no status");this.reject(t.id,o)}if(t.status==="error"){let o=t,a=new ec.RippledError((r=(n=o.error_message)!==null&&n!==void 0?n:o.error_exception)!==null&&r!==void 0?r:o.error,o);this.reject(t.id,a);return}if(t.status!=="success"){let o=new ec.ResponseFormatError(`unrecognized response.status: ${(i=t.status)!==null&&i!==void 0?i:""}`,t);this.reject(t.id,o);return}delete t.status,this.resolve(t.id,t)}}deletePromise(t){this.promisesAwaitingResponse.delete(t)}};yh.default=ZS});var OM=q(Di=>{"use strict";y();var tc=Di&&Di.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})},Kw=Di&&Di.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Di,"__esModule",{value:!0});Di.Connection=Di.INTENTIONAL_DISCONNECT_CODE=void 0;var MM=We(),Gd=Kw(_M()),Kie=rv(),si=fe(),zie=Kw(IM()),jie=Kw(PM()),Xie=Kw(xM()),Wie=60,Gie=20,Yie=5;Di.INTENTIONAL_DISCONNECT_CODE=4e3;function Zie(e,t){let n={agent:t.agent};t.headers&&(n.headers=t.headers),t.authorization!=null&&(n.headers=Object.assign(Object.assign({},n.headers),{Authorization:`Basic ${btoa(t.authorization)}`}));let r=Object.assign({},n);return new Gd.default(e,r)}function Jie(e,t){return tc(this,void 0,void 0,function*(){return new Promise((n,r)=>{e.send(t,i=>{i?r(new si.DisconnectedError(i.message,i)):n()})})})}var JS=class extends Kie.EventEmitter{constructor(t,n={}){super(),this.ws=null,this.reconnectTimeoutID=null,this.heartbeatIntervalID=null,this.retryConnectionBackoff=new jie.default({min:100,max:Wie*1e3}),this.requestManager=new Xie.default,this.connectionManager=new zie.default,this.trace=()=>{},this.url=t,this.config=Object.assign({timeout:Gie*1e3,connectionTimeout:Yie*1e3},n),typeof n.trace=="function"?this.trace=n.trace:n.trace&&(this.trace=console.log)}get state(){return this.ws?this.ws.readyState:Gd.default.CLOSED}get shouldBeConnected(){return this.ws!==null}isConnected(){return this.state===Gd.default.OPEN}connect(){return tc(this,void 0,void 0,function*(){if(this.isConnected())return Promise.resolve();if(this.state===Gd.default.CONNECTING)return this.connectionManager.awaitConnection();if(!this.url)return Promise.reject(new si.ConnectionError("Cannot connect because no server was specified"));if(this.ws!=null)return Promise.reject(new si.XrplError("Websocket connection never cleaned up.",{state:this.state}));let t=setTimeout(()=>{this.onConnectionFailed(new si.ConnectionError(`Error: connect() timed out after ${this.config.connectionTimeout} ms. If your internet connection is working, the rippled server may be blocked or inaccessible. You can also try setting the 'connectionTimeout' option in the Client constructor.`))},this.config.connectionTimeout);if(this.ws=Zie(this.url,this.config),this.ws==null)throw new si.XrplError("Connect: created null websocket");return this.ws.on("error",n=>this.onConnectionFailed(n)),this.ws.on("error",()=>clearTimeout(t)),this.ws.on("close",n=>this.onConnectionFailed(n)),this.ws.on("close",()=>clearTimeout(t)),this.ws.once("open",()=>{this.onceOpen(t)}),this.connectionManager.awaitConnection()})}disconnect(){return tc(this,void 0,void 0,function*(){return this.clearHeartbeatInterval(),this.reconnectTimeoutID!==null&&(clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null),this.state===Gd.default.CLOSED||this.ws==null?Promise.resolve(void 0):new Promise(t=>{this.ws==null&&t(void 0),this.ws!=null&&this.ws.once("close",n=>t(n)),this.ws!=null&&this.state!==Gd.default.CLOSING&&this.ws.close(Di.INTENTIONAL_DISCONNECT_CODE)})})}reconnect(){return tc(this,void 0,void 0,function*(){this.emit("reconnect"),yield this.disconnect(),yield this.connect()})}request(t,n){return tc(this,void 0,void 0,function*(){if(!this.shouldBeConnected||this.ws==null)throw new si.NotConnectedError(JSON.stringify(t),t);let[r,i,o]=this.requestManager.createRequest(t,n??this.config.timeout);return this.trace("send",i),Jie(this.ws,i).catch(a=>{try{this.requestManager.reject(r,a)}catch(s){s instanceof si.XrplError?this.trace("send",`send errored after connection was closed: ${s.toString()}`):this.trace("send",String(s))}}),o})}getUrl(){var t;return(t=this.url)!==null&&t!==void 0?t:""}onMessage(t){this.trace("receive",t);let n;try{n=JSON.parse(t)}catch(r){r instanceof Error&&this.emit("error","badMessage",r.message,t);return}if(n.type==null&&n.error){this.emit("error",n.error,n.error_message,n);return}if(n.type&&this.emit(n.type,n),n.type==="response")try{this.requestManager.handleResponse(n)}catch(r){r instanceof Error?this.emit("error","badMessage",r.message,t):this.emit("error","badMessage",r,r)}}onceOpen(t){return tc(this,void 0,void 0,function*(){if(this.ws==null)throw new si.XrplError("onceOpen: ws is null");this.ws.removeAllListeners(),clearTimeout(t),this.ws.on("message",n=>this.onMessage(n)),this.ws.on("error",n=>this.emit("error","websocket",n.message,n)),this.ws.once("close",(n,r)=>{if(this.ws==null)throw new si.XrplError("onceClose: ws is null");this.clearHeartbeatInterval(),this.requestManager.rejectAll(new si.DisconnectedError(`websocket was closed, ${r?(0,MM.hexToString)((0,MM.bytesToHex)(r)):""}`)),this.ws.removeAllListeners(),this.ws=null,n===void 0?this.emit("disconnected",1011):this.emit("disconnected",n),n!==Di.INTENTIONAL_DISCONNECT_CODE&&n!==void 0&&this.intentionalDisconnect()});try{this.retryConnectionBackoff.reset(),this.startHeartbeatInterval(),this.connectionManager.resolveAllAwaiting(),this.emit("connected")}catch(n){n instanceof Error&&(this.connectionManager.rejectAllAwaiting(n),yield this.disconnect().catch(()=>{}))}})}intentionalDisconnect(){let t=this.retryConnectionBackoff.duration();this.trace("reconnect",`Retrying connection in ${t}ms.`),this.emit("reconnecting",this.retryConnectionBackoff.attempts),this.reconnectTimeoutID=setTimeout(()=>{this.reconnect().catch(n=>{this.emit("error","reconnect",n.message,n)})},t)}clearHeartbeatInterval(){this.heartbeatIntervalID&&clearInterval(this.heartbeatIntervalID)}startHeartbeatInterval(){this.clearHeartbeatInterval(),this.heartbeatIntervalID=setInterval(()=>{this.heartbeat()},this.config.timeout)}heartbeat(){return tc(this,void 0,void 0,function*(){this.request({command:"ping"}).catch(()=>tc(this,void 0,void 0,function*(){return this.reconnect().catch(t=>{this.emit("error","reconnect",t.message,t)})}))})}onConnectionFailed(t){this.ws&&(this.ws.removeAllListeners(),this.ws.on("error",()=>{}),this.ws.close(),this.ws=null),typeof t=="number"?this.connectionManager.rejectAllAwaiting(new si.NotConnectedError(`Connection failed with code ${t}.`,{code:t})):t?.message?this.connectionManager.rejectAllAwaiting(new si.NotConnectedError(t.message,t)):this.connectionManager.rejectAllAwaiting(new si.NotConnectedError("Connection failed."))}};Di.Connection=JS});var RM=q(nc=>{"use strict";y();var Qie=nc&&nc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nc,"__esModule",{value:!0});nc.handleStreamPartialPayment=nc.handlePartialPayment=void 0;var zw=Qie(Sn()),eoe=Qn(),hh=Od(),toe=hn(),DM=2001;function noe(e,t){if(typeof e=="string"&&typeof t=="string")return e===t;if(typeof e=="string"||typeof t=="string")return!1;if((0,hh.isMPTAmount)(e)&&(0,hh.isMPTAmount)(t)){let i=new zw.default(e.value),o=new zw.default(t.value);return e.mpt_issuance_id===t.mpt_issuance_id&&i.isEqualTo(o)}if((0,hh.isMPTAmount)(e)||(0,hh.isMPTAmount)(t))return!1;let n=new zw.default(e.value),r=new zw.default(t.value);return e.currency===t.currency&&e.issuer===t.issuer&&n.isEqualTo(r)}function mh(e,t){var n,r;if(e==null||t==null||e.TransactionType!=="Payment")return!1;let i=t;if(typeof i=="string"){if(i==="unavailable")return!1;i=(0,eoe.decode)(i)}if(!(typeof e.Flags=="number"?(0,toe.isFlagEnabled)(e.Flags,hh.PaymentFlags.tfPartialPayment):(n=e.Flags)===null||n===void 0?void 0:n.tfPartialPayment))return!1;let a=i.delivered_amount,s=(r=e.DeliverMax)!==null&&r!==void 0?r:e.Amount;return a===void 0?!1:!noe(a,s)}function roe(e){return mh(e.result.tx_json,e.result.meta)}function ioe(e){return mh(e.result.tx_json,e.result.metadata)}function ooe(e){let{transactions:t}=e.result;return t.some(r=>{if(r.tx_json!=null){let o=r;return mh(o.tx_json,o.meta)}let i=r;return mh(i.tx,i.meta)})}function aoe(e,t){switch(e){case"tx":return roe(t);case"transaction_entry":return ioe(t);case"account_tx":return ooe(t);default:return!1}}function soe(e,t){var n;if(aoe(e,t)){let r=(n=t.warnings)!==null&&n!==void 0?n:[],i={id:DM,message:"This response contains a Partial Payment"};r.push(i),t.warnings=r}}nc.handlePartialPayment=soe;function coe(e,t){var n,r;if(mh((n=e.tx_json)!==null&&n!==void 0?n:e.transaction,e.meta)){let i=(r=e.warnings)!==null&&r!==void 0?r:[],o={id:DM,message:"This response contains a Partial Payment"};i.push(o),e.warnings=i,t("Partial payment received",JSON.stringify(e))}}nc.handleStreamPartialPayment=coe});var BM=q(Yd=>{"use strict";y();var jn=Yd&&Yd.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(Yd,"__esModule",{value:!0});Yd.Client=void 0;var loe=rv(),rc=fe(),uoe=yv(),doe=ju(),xl=X9(),ic=rI(),foe=iI(),bo=aI(),QS=Ny(),poe=nh(),yoe=vx(),NM=OM(),LM=RM();function hoe(e){switch(e){case"account_channels":return"channels";case"account_lines":return"lines";case"account_objects":return"account_objects";case"account_tx":return"transactions";case"account_offers":case"book_offers":return"offers";case"ledger_data":return"state";default:return null}}function moe(e,t,n){if(t>n)throw new Error("Illegal clamp bounds");return Math.min(Math.max(e,t),n)}var goe=1.2,woe="2",boe=10,Coe=400,voe=1e3,eT=class extends loe.EventEmitter{constructor(t,n={}){var r,i;if(super(),this.apiVersion=uoe.DEFAULT_API_VERSION,typeof t!="string"||!/wss?(?:\+unix)?:\/\//u.exec(t))throw new rc.ValidationError("server URI must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.");if(n.authorization!=null&&!t.startsWith("wss://")&&!t.startsWith("wss+unix://"))throw new rc.ValidationError("Authorization Credentials cannot be sent over an unencrypted connection. Use wss:// or wss+unix:// instead.");this.feeCushion=(r=n.feeCushion)!==null&&r!==void 0?r:goe,this.maxFeeXRP=(i=n.maxFeeXRP)!==null&&i!==void 0?i:woe,this.connection=new NM.Connection(t,n),this.connection.on("error",(o,a,s)=>{this.emit("error",o,a,s)}),this.connection.on("reconnect",()=>{this.connection.removeAllListeners("connected"),this.connection.once("connected",()=>this.emit("connected"))}),this.connection.on("disconnected",o=>{let a=o;a===NM.INTENTIONAL_DISCONNECT_CODE&&(a=voe),this.emit("disconnected",a)}),this.connection.on("ledgerClosed",o=>{this.emit("ledgerClosed",o)}),this.connection.on("transaction",o=>{(0,LM.handleStreamPartialPayment)(o,this.connection.trace),this.emit("transaction",o)}),this.connection.on("validationReceived",o=>{this.emit("validationReceived",o)}),this.connection.on("manifestReceived",o=>{this.emit("manifestReceived",o)}),this.connection.on("peerStatusChange",o=>{this.emit("peerStatusChange",o)}),this.connection.on("consensusPhase",o=>{this.emit("consensusPhase",o)}),this.connection.on("path_find",o=>{this.emit("path_find",o)})}get url(){return this.connection.getUrl()}request(t){var n;return jn(this,void 0,void 0,function*(){let r=Object.assign(Object.assign({},t),{account:typeof t.account=="string"?(0,xl.ensureClassicAddress)(t.account):void 0,api_version:(n=t.api_version)!==null&&n!==void 0?n:this.apiVersion}),i=yield this.connection.request(r);return(0,LM.handlePartialPayment)(t.command,i),i})}requestNextPage(t,n){return jn(this,void 0,void 0,function*(){if(!n.result.marker)return Promise.reject(new rc.NotFoundError("response does not have a next page"));let r=Object.assign(Object.assign({},t),{marker:n.result.marker});return this.request(r)})}on(t,n){return super.on(t,n)}requestAll(t,n){var r;return jn(this,void 0,void 0,function*(){let i=n??hoe(t.command);if(!i)throw new rc.ValidationError(`no collect key for command ${t.command}`);let o=(r=t.limit)!==null&&r!==void 0?r:1/0,a=0,s=t.marker,c=[];do{let l=moe(o-a,boe,Coe),u=Object.assign(Object.assign({},t),{limit:l,marker:s}),d=yield this.connection.request(u),p=d.result;if(!(i in p))throw new rc.XrplError(`${i} not in result`);let h=p[i];s=p.marker,c.push(d),Array.isArray(h)&&(a+=h.length)}while(s&&ajn(this,void 0,void 0,function*(){yield this.getServerInfo(),this.emit("connected")}))})}disconnect(){return jn(this,void 0,void 0,function*(){yield this.connection.disconnect()})}isConnected(){return this.connection.isConnected()}autofill(t,n,r){var i;return jn(this,void 0,void 0,function*(){let o=Object.assign({},t);(0,ic.setValidAddresses)(o),o.Flags=(0,doe.convertTxFlagsToNumber)(o);let a=[];return(i=o.NetworkID)!==null&&i!==void 0||(o.NetworkID=(0,ic.txNeedsNetworkID)(this)?this.networkID:void 0),o.Sequence==null&&a.push((0,ic.setNextValidSequenceNumber)(this,o)),o.Fee==null&&a.push((0,ic.getTransactionFee)(this,o,n,r)),o.LastLedgerSequence==null&&a.push((0,ic.setLatestValidatedLedgerSequence)(this,o)),o.TransactionType==="AccountDelete"&&a.push((0,ic.checkAccountDeleteBlockers)(this,o)),o.TransactionType==="Batch"&&a.push((0,ic.autofillBatchTxn)(this,o)),o.TransactionType==="Payment"&&o.DeliverMax!=null&&(0,ic.handleDeliverMax)(o),Promise.all(a).then(()=>o)})}simulate(t,n){var r;return jn(this,void 0,void 0,function*(){let i=(r=n?.binary)!==null&&r!==void 0?r:!1,o=typeof t=="string"?{command:"simulate",tx_blob:t,binary:i}:{command:"simulate",tx_json:t,binary:i};return this.request(o)})}submit(t,n){return jn(this,void 0,void 0,function*(){let r=yield(0,xl.getSignedTx)(this,t,n);return(0,xl.submitRequest)(this,r,n?.failHard)})}submitAndWait(t,n){return jn(this,void 0,void 0,function*(){let r=yield(0,xl.getSignedTx)(this,t,n),i=(0,xl.getLastLedgerSequence)(r);if(i==null)throw new rc.ValidationError("Transaction must contain a LastLedgerSequence value for reliable submission.");let o=yield(0,xl.submitRequest)(this,r,n?.failHard);if(o.result.engine_result.startsWith("tem"))throw new rc.XrplError(`Transaction failed, ${o.result.engine_result}: ${o.result.engine_result_message}`);let a=QS.hashes.hashSignedTx(r);return(0,xl.waitForFinalTransactionOutcome)(this,a,i,o.result.engine_result)})}prepareTransaction(t,n,r){return jn(this,void 0,void 0,function*(){return this.autofill(t,n,r)})}getXrpBalance(t,n={}){var r;return jn(this,void 0,void 0,function*(){let i={command:"account_info",account:t,ledger_index:(r=n.ledger_index)!==null&&r!==void 0?r:"validated",ledger_hash:n.ledger_hash},o=yield this.request(i);return(0,QS.dropsToXrp)(o.result.account_data.Balance)})}getBalances(t,n={}){var r;return jn(this,void 0,void 0,function*(){let i=[],o=Promise.resolve(0);n.peer||(o=this.getXrpBalance(t,{ledger_hash:n.ledger_hash,ledger_index:n.ledger_index}));let a={command:"account_lines",account:t,ledger_index:(r=n.ledger_index)!==null&&r!==void 0?r:"validated",ledger_hash:n.ledger_hash,peer:n.peer,limit:n.limit},s=this.requestAll(a);return yield Promise.all([o,s]).then(([c,l])=>{let u=l.flatMap(d=>(0,foe.formatBalances)(d.result.lines));c!==0&&i.push({currency:"XRP",value:c.toString()}),i.push(...u)}),i.slice(0,n.limit)})}getOrderbook(t,n,r={}){return jn(this,void 0,void 0,function*(){(0,bo.validateOrderbookOptions)(r);let i=(0,bo.createBookOffersRequest)(t,n,r),o=yield(0,bo.requestAllOffers)(this,i),a=yield(0,bo.requestAllOffers)(this,(0,bo.reverseRequest)(i)),s=(0,bo.extractOffers)(o),c=(0,bo.extractOffers)(a),l=(0,bo.combineOrders)(s,c),{buy:u,sell:d}=(0,bo.separateBuySellOrders)(l);return{buy:(0,bo.sortAndLimitOffers)(u,r.limit),sell:(0,bo.sortAndLimitOffers)(d,r.limit)}})}getLedgerIndex(){return jn(this,void 0,void 0,function*(){return(yield this.request({command:"ledger",ledger_index:"validated"})).result.ledger_index})}fundWallet(t,n={}){return jn(this,void 0,void 0,function*(){if(!this.isConnected())throw new rc.RippledError("Client not connected, cannot call faucet");let r=!!t,i=t&&(0,QS.isValidClassicAddress)(t.classicAddress)?t:poe.Wallet.generate(),o={destination:i.classicAddress,xrpAmount:n.amount,usageContext:n.usageContext,userAgent:"xrpl.js"},a=0;if(r)try{a=Number(yield this.getXrpBalance(i.classicAddress))}catch{}return(0,yoe.requestFunding)(n,this,a,i,o)})}};Yd.Client=eT});var tT=q(or=>{"use strict";y();Object.defineProperty(or,"__esModule",{value:!0});or.parseSecretString=or.checkChecksum=or.calculateChecksum=or.secretToEntropy=or.entropyToSecret=or.randomSecret=or.randomEntropy=void 0;var jw=We();function FM(){return(0,jw.randomBytes)(16)}or.randomEntropy=FM;function UM(e,t){return t*(e*2+1)%9}or.calculateChecksum=UM;function $M(e,t,n){let r,i;if(typeof t=="string"){if(t.length!==6)throw new Error("value must have a length of 6");r=parseInt(t.slice(5),10),i=parseInt(t.slice(0,5),10)}else{if(typeof n!="number")throw new Error("checksum must be a number when value is a number");r=n,i=t}return i*(e*2+1)%9===r}or.checkChecksum=$M;function qM(e){let t=new Array(Math.ceil(e.length/2)),n=Array.from(t,(r,i)=>{let o=e.slice(i*2,(i+1)*2),a=parseInt((0,jw.bytesToHex)(o),16);return"0".repeat(5-String(a).length)+String(a)+String(UM(i,a))});if(n.length!==8)throw new Error("Chucks must have 8 digits");return n}or.entropyToSecret=qM;function Aoe(){return qM(FM())}or.randomSecret=Aoe;function Soe(e){return(0,jw.concat)(e.map((t,n)=>{let r=Number(t.slice(0,5)),i=Number(t.slice(5));if(t.length!==6)throw new Error("Invalid secret: number invalid");if(!$M(n,r,i))throw new Error("Invalid secret part: checksum invalid");let o=`0000${r.toString(16)}`.slice(-4);return(0,jw.hexToBytes)(o)}))}or.secretToEntropy=Soe;function Toe(e){let t=e.replace(/[^0-9]/gu,"");if(t.length!==48)throw new Error("Invalid secret string (should contain 8 blocks of 6 digits");return Array.from(new Array(8),(n,r)=>t.slice(r*6,(r+1)*6))}or.parseSecretString=Toe});var HM=q(Ww=>{"use strict";y();Object.defineProperty(Ww,"__esModule",{value:!0});Ww.Account=void 0;var nT=_i(),Xw=tT(),rT=class{constructor(t,n="ed25519"){this._account={familySeed:"",address:"",keypair:{publicKey:"",privateKey:""}},this._algorithm=n,typeof t=="string"?this._secret=(0,Xw.parseSecretString)(t):Array.isArray(t)?this._secret=t:t instanceof Uint8Array?this._secret=(0,Xw.entropyToSecret)(t):this._secret=(0,Xw.randomSecret)(),Eoe(this._secret),this.derive()}getSecret(){return this._secret}getSecretString(){return this._secret.join(" ")}getAddress(){return this._account.address}getFamilySeed(){return this._account.familySeed}getKeypair(){return this._account.keypair}toString(){return this.getSecretString()}derive(){try{let t=(0,Xw.secretToEntropy)(this._secret);this._account.familySeed=(0,nT.generateSeed)({entropy:t,algorithm:this._algorithm}),this._account.keypair=(0,nT.deriveKeypair)(this._account.familySeed),this._account.address=(0,nT.deriveAddress)(this._account.keypair.publicKey)}catch(t){let n="Unknown Error";throw t instanceof Error&&(n=t.message),new Error(n)}}};Ww.Account=rT;function Eoe(e){if(e.length!==8)throw new Error("Secret must have 8 numbers");e.forEach(t=>{if(t.length!==6)throw new Error("Each secret number must be 6 digits")})}});var KM=q(oc=>{"use strict";y();var koe=oc&&oc.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),VM=oc&&oc.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&koe(t,e,n)};Object.defineProperty(oc,"__esModule",{value:!0});VM(HM(),oc);VM(tT(),oc)});var jM=q(Zd=>{"use strict";y();var _oe=Zd&&Zd.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Zd,"__esModule",{value:!0});Zd.walletFromSecretNumbers=void 0;var Ioe=KM(),zM=_oe(Hy()),Poe=nh();function xoe(e,t){var n;let r=new Ioe.Account(e).getFamilySeed(),i={masterAddress:void 0,algorithm:void 0};return t===void 0?i.algorithm=zM.default.secp256k1:(i.masterAddress=t.masterAddress,i.algorithm=(n=t.algorithm)!==null&&n!==void 0?n:zM.default.secp256k1),Poe.Wallet.fromSecret(r,i)}Zd.walletFromSecretNumbers=xoe});var ac=q(Be=>{"use strict";y();Object.defineProperty(Be,"__esModule",{value:!0});Be.PEDERSEN_PARAMS_STRUCT_SIZE=Be.PEDERSEN_PARAMS_BLINDING_OFFSET=Be.PEDERSEN_PARAMS_CIPHERTEXT_OFFSET=Be.PEDERSEN_PARAMS_AMOUNT_OFFSET=Be.PEDERSEN_PARAMS_COMMITMENT_OFFSET=Be.PARTICIPANT_STRUCT_SIZE=Be.PARTICIPANT_CIPHERTEXT_OFFSET=Be.PARTICIPANT_PUBKEY_OFFSET=Be.SEND_PROOF_SIZE=Be.CONVERT_BACK_PROOF_SIZE=Be.CLAWBACK_PROOF_SIZE=Be.CONVERT_PROOF_SIZE=Be.ISSUANCE_ID_SIZE=Be.ACCOUNT_ID_SIZE=Be.CONTEXT_HASH_SIZE=Be.PEDERSEN_COMMIT_SIZE=Be.ELGAMAL_TOTAL_SIZE=Be.BLINDING_FACTOR_SIZE=Be.PRIVKEY_SIZE=Be.PUBKEY_SIZE=void 0;Be.PUBKEY_SIZE=33;Be.PRIVKEY_SIZE=32;Be.BLINDING_FACTOR_SIZE=32;Be.ELGAMAL_TOTAL_SIZE=66;Be.PEDERSEN_COMMIT_SIZE=33;Be.CONTEXT_HASH_SIZE=32;Be.ACCOUNT_ID_SIZE=20;Be.ISSUANCE_ID_SIZE=24;Be.CONVERT_PROOF_SIZE=64;Be.CLAWBACK_PROOF_SIZE=64;Be.CONVERT_BACK_PROOF_SIZE=816;Be.SEND_PROOF_SIZE=946;Be.PARTICIPANT_PUBKEY_OFFSET=0;Be.PARTICIPANT_CIPHERTEXT_OFFSET=Be.PUBKEY_SIZE;Be.PARTICIPANT_STRUCT_SIZE=Be.PUBKEY_SIZE+Be.ELGAMAL_TOTAL_SIZE;Be.PEDERSEN_PARAMS_COMMITMENT_OFFSET=0;Be.PEDERSEN_PARAMS_AMOUNT_OFFSET=40;Be.PEDERSEN_PARAMS_CIPHERTEXT_OFFSET=48;Be.PEDERSEN_PARAMS_BLINDING_OFFSET=114;Be.PEDERSEN_PARAMS_STRUCT_SIZE=152});var Ml=q(Jd=>{"use strict";y();Object.defineProperty(Jd,"__esModule",{value:!0});Jd.bytesToHex=Jd.hexToBytes=void 0;var Moe=/^[0-9a-fA-F]*$/u;function Ooe(e,t,n){if(typeof e!="string"||e.length%2!==0||!Moe.test(e))throw new Error(`${t} must be an even-length hex string`);let r=new Uint8Array(e.length/2);for(let i=0;i{y();var iT=(()=>{var e=globalThis.document?.currentScript?.src;return async function(t={}){var n=t,r=!!globalThis.window,i=!!globalThis.WorkerGlobalScope,o=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",a=[],s="./this.program",c=(f,m)=>{throw m};typeof __filename<"u"&&(e=__filename);var l="";function u(f){return n.locateFile?n.locateFile(f,l):l+f}var d,p;if(o){var h=At("node:fs");l=__dirname+"/",p=f=>{f=D(f)?new URL(f):f;var m=h.readFileSync(f);return m},d=async(f,m=!0)=>{f=D(f)?new URL(f):f;var E=h.readFileSync(f,m?void 0:"utf8");return E},process.argv.length>1&&(s=process.argv[1].replace(/\\/g,"/")),a=process.argv.slice(2),c=(f,m)=>{throw process.exitCode=f,m}}else if(r||i){try{l=new URL(".",e).href}catch{}d=async f=>{var m=await fetch(f,{credentials:"same-origin"});if(m.ok)return m.arrayBuffer();throw new Error(m.status+" : "+m.url)}}var g=console.log.bind(console),w=console.error.bind(console),T,k=!1,B,D=f=>f.startsWith("file://");class P{}class U extends P{}var F=!1;function H(){return Om.buffer}function b(){if(!J?.buffer?.resizable){var f=H();J=new Int8Array(f),X=new Int16Array(f),n.HEAPU8=Ee=new Uint8Array(f),me=new Uint16Array(f),Z=new Int32Array(f),pe=new Uint32Array(f),ie=new Float32Array(f),se=new Float64Array(f),ee=new BigInt64Array(f),Pe=new BigUint64Array(f)}}function C(){var f=n.preRun;f&&(typeof f=="function"&&(f=[f]),qe.push(...f)),Ne(qe)}function v(){F=!0,!n.noFSInit&&!_.initialized&&_.init(),He.init(),wp.u(),_.ignorePermissions=!1}function S(){var f=n.postRun;f&&(typeof f=="function"&&(f=[f]),De.push(...f)),Ne(De)}function A(f){n.onAbort?.(f),f=`Aborted(${f})`,w(f),k=!0,f+=". Build with -sASSERTIONS for more info.";var m=new WebAssembly.RuntimeError(f);throw m}var M;function $(){return u("mpt_crypto.wasm")}function R(f){if(p)return p(f);throw"both async and sync fetching of the wasm failed"}async function O(f){if(!T)try{var m=await d(f);return new Uint8Array(m)}catch{}return R(f)}async function j(f,m){try{var E=await O(f),x=await WebAssembly.instantiate(E,m);return x}catch(z){w(`failed to asynchronously prepare wasm: ${z}`),A(z)}}async function N(f,m,E){if(!f&&!o)try{var x=fetch(m,{credentials:"same-origin"}),z=await WebAssembly.instantiateStreaming(x,E);return z}catch(Q){w(`wasm streaming compile failed: ${Q}`),w("falling back to ArrayBuffer instantiation")}return j(m,E)}function V(){var f={a:HU};return f}async function G(){function f(oe){return wp=oe.exports,qU(wp),b(),wp}function m(oe){return f(oe.instance)}var E=V(),x=n.instantiateWasm;if(x)return new Promise(oe=>{x(E,ae=>oe(f(ae)))});M??=$();var z=await N(T,M,E),Q=m(z);return Q}class L{name="ExitStatus";constructor(m){this.message=`Program terminated with exit(${m})`,this.status=m}}var X,Z,ee,J,ie,se,me,pe,Pe,Ee,Ne=f=>{for(;f.length>0;)f.shift()(n)},De=[],qe=[],xe=!0,vt=f=>o8(f),Kr=()=>s8();class Xi{constructor(m){this.excPtr=m,this.ptr=m-24}set_type(m){pe[this.ptr+4>>2]=m}get_type(){return pe[this.ptr+4>>2]}set_destructor(m){pe[this.ptr+8>>2]=m}get_destructor(){return pe[this.ptr+8>>2]}set_caught(m){m=m?1:0,J[this.ptr+12]=m}get_caught(){return J[this.ptr+12]!=0}set_rethrown(m){m=m?1:0,J[this.ptr+13]=m}get_rethrown(){return J[this.ptr+13]!=0}init(m,E){this.set_adjusted_ptr(0),this.set_type(m),this.set_destructor(E)}set_adjusted_ptr(m){pe[this.ptr+16>>2]=m}get_adjusted_ptr(){return pe[this.ptr+16>>2]}}var Sr=0,uu=(f,m,E)=>{var x=new Xi(f);x.init(m,E),Sr++,A()},lt={isAbs:f=>f.charAt(0)==="/",splitPath:f=>{var m=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return m.exec(f).slice(1)},normalizeArray:(f,m)=>{for(var E=0,x=f.length-1;x>=0;x--){var z=f[x];z==="."?f.splice(x,1):z===".."?(f.splice(x,1),E++):E&&(f.splice(x,1),E--)}if(m)for(;E;E--)f.unshift("..");return f},normalize:f=>{var m=lt.isAbs(f),E=f.slice(-1)==="/";return f=lt.normalizeArray(f.split("/").filter(x=>!!x),!m).join("/"),!f&&!m&&(f="."),f&&E&&(f+="/"),(m?"/":"")+f},dirname:f=>{var m=lt.splitPath(f),E=m[0],x=m[1];return!E&&!x?".":(x&&(x=x.slice(0,-1)),E+x)},basename:f=>f&&f.match(/([^\/]+|\/)\/*$/)[1],join:(...f)=>lt.normalize(f.join("/")),join2:(f,m)=>lt.normalize(f+"/"+m)},du=()=>{if(o){var f=At("node:crypto");return m=>(f.randomFillSync(m),0)}return m=>(crypto.getRandomValues(m),0)},Mm=f=>(Mm=du())(f),K={resolve:(...f)=>{for(var m="",E=!1,x=f.length-1;x>=-1&&!E;x--){var z=x>=0?f[x]:_.cwd();if(typeof z!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!z)return"";m=z+"/"+m,E=lt.isAbs(z)}return m=lt.normalizeArray(m.split("/").filter(Q=>!!Q),!E).join("/"),(E?"/":"")+m||"."},relative:(f,m)=>{f=K.resolve(f).slice(1),m=K.resolve(m).slice(1);function E(Le){for(var tt=0;tt=0&&Le[wt]==="";wt--);return tt>wt?[]:Le.slice(tt,wt-tt+1)}for(var x=E(f.split("/")),z=E(m.split("/")),Q=Math.min(x.length,z.length),oe=Q,ae=0;ae{var z=m+E;if(x)return z;for(;f[m]&&!(m>=z);)++m;return m},he=(f,m=0,E,x)=>{var z=ce(f,m,E,x);return re.decode(f.buffer?f.subarray(m,z):new Uint8Array(f.slice(m,z)))},ge=[],we=f=>{for(var m=0,E=0;E=55296&&x<=57343?(m+=4,++E):m+=3}return m},Me=(f,m,E,x)=>{if(!(x>0))return 0;for(var z=E,Q=E+x-1,oe=0;oe=Q)break;m[E++]=ae}else if(ae<=2047){if(E+1>=Q)break;m[E++]=192|ae>>6,m[E++]=128|ae&63}else if(ae<=65535){if(E+2>=Q)break;m[E++]=224|ae>>12,m[E++]=128|ae>>6&63,m[E++]=128|ae&63}else{if(E+3>=Q)break;m[E++]=240|ae>>18,m[E++]=128|ae>>12&63,m[E++]=128|ae>>6&63,m[E++]=128|ae&63,oe++}}return m[E]=0,E-z},Re=(f,m,E)=>{var x=E>0?E:we(f)+1,z=new Array(x),Q=Me(f,z,0,z.length);return m&&(z.length=Q),z},gt=()=>{if(!ge.length){var f=null;if(o){var m=256,E=Buffer.alloc(m),x=0,z=process.stdin.fd;try{x=h.readSync(z,E,0,m)}catch(Q){if(Q.toString().includes("EOF"))x=0;else throw Q}x>0&&(f=E.slice(0,x).toString("utf-8"))}else globalThis.window?.prompt&&(f=window.prompt("Input: "),f!==null&&(f+=` `));if(!f)return null;ge=Re(f,!0)}return ge.shift()},He={ttys:[],init(){},shutdown(){},register(f,m){He.ttys[f]={input:[],output:[],ops:m},_.registerDevice(f,He.stream_ops)},stream_ops:{open(f){var m=He.ttys[f.node.rdev];if(!m)throw new _.ErrnoError(43);f.tty=m,f.seekable=!1},close(f){f.tty.ops.fsync(f.tty)},fsync(f){f.tty.ops.fsync(f.tty)},read(f,m,E,x,z){if(!f.tty||!f.tty.ops.get_char)throw new _.ErrnoError(60);for(var Q=0,oe=0;oe0&&(g(he(f.output)),f.output=[])},ioctl_tcgets(f){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(f,m,E){return 0},ioctl_tiocgwinsz(f){return[24,80]}},default_tty1_ops:{put_char(f,m){m===null||m===10?(w(he(f.output)),f.output=[]):m!=0&&f.output.push(m)},fsync(f){f.output?.length>0&&(w(he(f.output)),f.output=[])}}},Je=f=>{A()},Se={ops_table:null,mount(f){return Se.createNode(null,"/",16895,0)},createNode(f,m,E,x){if(_.isBlkdev(E)||_.isFIFO(E))throw new _.ErrnoError(63);Se.ops_table||={dir:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr,lookup:Se.node_ops.lookup,mknod:Se.node_ops.mknod,rename:Se.node_ops.rename,unlink:Se.node_ops.unlink,rmdir:Se.node_ops.rmdir,readdir:Se.node_ops.readdir,symlink:Se.node_ops.symlink},stream:{llseek:Se.stream_ops.llseek}},file:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr},stream:{llseek:Se.stream_ops.llseek,read:Se.stream_ops.read,write:Se.stream_ops.write,mmap:Se.stream_ops.mmap,msync:Se.stream_ops.msync}},link:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr,readlink:Se.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr},stream:_.chrdev_stream_ops}};var z=_.createNode(f,m,E,x);return _.isDir(z.mode)?(z.node_ops=Se.ops_table.dir.node,z.stream_ops=Se.ops_table.dir.stream,z.contents={}):_.isFile(z.mode)?(z.node_ops=Se.ops_table.file.node,z.stream_ops=Se.ops_table.file.stream,z.usedBytes=0,z.contents=Se.emptyFileContents??=new Uint8Array(0)):_.isLink(z.mode)?(z.node_ops=Se.ops_table.link.node,z.stream_ops=Se.ops_table.link.stream):_.isChrdev(z.mode)&&(z.node_ops=Se.ops_table.chrdev.node,z.stream_ops=Se.ops_table.chrdev.stream),z.atime=z.mtime=z.ctime=Date.now(),f&&(f.contents[m]=z,f.atime=f.mtime=f.ctime=z.atime),z},getFileDataAsTypedArray(f){return f.contents.subarray(0,f.usedBytes)},expandFileStorage(f,m){var E=f.contents.length;if(!(E>=m)){var x=1024*1024;m=Math.max(m,E*(E>>0),E&&(m=Math.max(m,256));var z=Se.getFileDataAsTypedArray(f);f.contents=new Uint8Array(m),f.contents.set(z)}},resizeFileStorage(f,m){if(f.usedBytes!=m){var E=f.contents;f.contents=new Uint8Array(m),f.contents.set(E.subarray(0,Math.min(m,f.usedBytes))),f.usedBytes=m}},node_ops:{getattr(f){var m={};return m.dev=_.isChrdev(f.mode)?f.id:1,m.ino=f.id,m.mode=f.mode,m.nlink=1,m.uid=0,m.gid=0,m.rdev=f.rdev,_.isDir(f.mode)?m.size=4096:_.isFile(f.mode)?m.size=f.usedBytes:_.isLink(f.mode)?m.size=f.link.length:m.size=0,m.atime=new Date(f.atime),m.mtime=new Date(f.mtime),m.ctime=new Date(f.ctime),m.blksize=4096,m.blocks=Math.ceil(m.size/m.blksize),m},setattr(f,m){for(let E of["mode","atime","mtime","ctime"])m[E]!=null&&(f[E]=m[E]);m.size!==void 0&&Se.resizeFileStorage(f,m.size)},lookup(f,m){throw Se.doesNotExistError||(Se.doesNotExistError=new _.ErrnoError(44),Se.doesNotExistError.stack=""),Se.doesNotExistError},mknod(f,m,E,x){return Se.createNode(f,m,E,x)},rename(f,m,E){var x;try{x=_.lookupNode(m,E)}catch{}if(x){if(_.isDir(f.mode))for(var z in x.contents)throw new _.ErrnoError(55);_.hashRemoveNode(x)}delete f.parent.contents[f.name],m.contents[E]=f,f.name=E,m.ctime=m.mtime=f.parent.ctime=f.parent.mtime=Date.now()},unlink(f,m){delete f.contents[m],f.ctime=f.mtime=Date.now()},rmdir(f,m){var E=_.lookupNode(f,m);for(var x in E.contents)throw new _.ErrnoError(55);delete f.contents[m],f.ctime=f.mtime=Date.now()},readdir(f){return[".","..",...Object.keys(f.contents)]},symlink(f,m,E){var x=Se.createNode(f,m,41471,0);return x.link=E,x},readlink(f){if(!_.isLink(f.mode))throw new _.ErrnoError(28);return f.link}},stream_ops:{read(f,m,E,x,z){var Q=f.node.contents;if(z>=f.node.usedBytes)return 0;var oe=Math.min(f.node.usedBytes-z,x);return m.set(Q.subarray(z,z+oe),E),oe},write(f,m,E,x,z,Q){if(m.buffer===J.buffer&&(Q=!1),!x)return 0;var oe=f.node;return oe.mtime=oe.ctime=Date.now(),Q?(oe.contents=m.subarray(E,E+x),oe.usedBytes=x):oe.usedBytes===0&&z===0?(oe.contents=m.slice(E,E+x),oe.usedBytes=x):(Se.expandFileStorage(oe,z+x),oe.contents.set(m.subarray(E,E+x),z),oe.usedBytes=Math.max(oe.usedBytes,z+x)),x},llseek(f,m,E){var x=m;if(E===1?x+=f.position:E===2&&_.isFile(f.node.mode)&&(x+=f.node.usedBytes),x<0)throw new _.ErrnoError(28);return x},mmap(f,m,E,x,z){if(!_.isFile(f.node.mode))throw new _.ErrnoError(43);var Q,oe,ae=f.node.contents;if(!(z&2)&&ae.buffer===J.buffer)oe=!1,Q=ae.byteOffset;else{if(oe=!0,Q=Je(m),!Q)throw new _.ErrnoError(48);ae&&((E>0||E+m{if(typeof f!="string")return f;var m={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},E=m[f];if(typeof E>"u")throw new Error(`Unknown file open mode: ${f}`);return E},Rt=f=>(typeof f=="string"&&(f=Re(f,!0)),f.subarray||(f=new Uint8Array(f)),f),wn=(f,m)=>{var E=0;return f&&(E|=365),m&&(E|=146),E},Qe=async f=>{var m=await d(f);return new Uint8Array(m)},sn=(...f)=>_.createDataFile(...f),Wi=f=>f,wa=null,hp=async()=>wa,zr=0,kF=f=>{zr--,n.monitorRunDependencies?.(zr),zr||wa.resolve()},_F=f=>{if(!zr){var m;wa=new Promise(E=>m=E),wa.resolve=m}zr++,n.monitorRunDependencies?.(zr)},IF=[],PF=async(f,m)=>{typeof Browser<"u"&&Browser.init();for(var E of IF)if(E.canHandle(m))return E.handle(f,m);return f},XE=async(f,m,E,x,z,Q,oe,ae)=>{var be=m?K.resolve(lt.join2(f,m)):f,Le=Wi(`cp ${be}`);_F(Le);try{var tt=E;typeof E=="string"&&(tt=await Qe(E)),tt=await PF(tt,be),ae?.(),Q||sn(f,m,tt,x,z,oe)}finally{kF(Le)}},xF=(f,m,E,x,z,Q,oe,ae,be,Le)=>{XE(f,m,E,x,z,ae,be,Le).then(Q).catch(oe)},_={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(f){this.errno=f}},FSStream:class{shared={};get object(){return this.node}set object(f){this.node=f}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(f){this.shared.flags=f}get position(){return this.shared.position}set position(f){this.shared.position=f}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(f,m,E,x){f||(f=this),this.parent=f,this.mount=f.mount,this.id=_.nextInode++,this.name=m,this.mode=E,this.rdev=x,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(f){f?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(f){f?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return _.isDir(this.mode)}get isDevice(){return _.isChrdev(this.mode)}},lookupPath(f,m={}){if(!f)throw new _.ErrnoError(44);m.follow_mount??=!0,lt.isAbs(f)||(f=_.cwd()+"/"+f);e:for(var E=0;E<40;E++){for(var x=f.split("/").filter(Le=>!!Le),z=_.root,Q="/",oe=0;oe>>0)%_.nameTable.length},hashAddNode(f){var m=_.hashName(f.parent.id,f.name);f.name_next=_.nameTable[m],_.nameTable[m]=f},hashRemoveNode(f){var m=_.hashName(f.parent.id,f.name);if(_.nameTable[m]===f)_.nameTable[m]=f.name_next;else for(var E=_.nameTable[m];E;){if(E.name_next===f){E.name_next=f.name_next;break}E=E.name_next}},lookupNode(f,m){var E=_.mayLookup(f);if(E)throw new _.ErrnoError(E);for(var x=_.hashName(f.id,m),z=_.nameTable[x];z;z=z.name_next){var Q=z.name;if(z.parent.id===f.id&&Q===m)return z}return _.lookup(f,m)},createNode(f,m,E,x){var z=new _.FSNode(f,m,E,x);return _.hashAddNode(z),z},destroyNode(f){_.hashRemoveNode(f)},isRoot(f){return f===f.parent},isMountpoint(f){return!!f.mounted},isFile(f){return(f&61440)===32768},isDir(f){return(f&61440)===16384},isLink(f){return(f&61440)===40960},isChrdev(f){return(f&61440)===8192},isBlkdev(f){return(f&61440)===24576},isFIFO(f){return(f&61440)===4096},isSocket(f){return(f&49152)===49152},flagsToPermissionString(f){var m=["r","w","rw"][f&3];return f&512&&(m+="w"),m},nodePermissions(f,m){return _.ignorePermissions?0:m.includes("r")&&!(f.mode&292)||m.includes("w")&&!(f.mode&146)||m.includes("x")&&!(f.mode&73)?2:0},mayLookup(f){if(!_.isDir(f.mode))return 54;var m=_.nodePermissions(f,"x");return m||(f.node_ops.lookup?0:2)},mayCreate(f,m){if(!_.isDir(f.mode))return 54;try{var E=_.lookupNode(f,m);return 20}catch{}return _.nodePermissions(f,"wx")},mayDelete(f,m,E){var x;try{x=_.lookupNode(f,m)}catch(Q){return Q.errno}var z=_.nodePermissions(f,"wx");if(z)return z;if(E){if(!_.isDir(x.mode))return 54;if(_.isRoot(x)||_.getPath(x)===_.cwd())return 10}else if(_.isDir(x.mode))return 31;return 0},mayOpen(f,m){if(!f)return 44;if(_.isLink(f.mode))return 32;var E=_.flagsToPermissionString(m);return _.isDir(f.mode)&&(E!=="r"||m&576)?31:_.nodePermissions(f,E)},checkOpExists(f,m){if(!f)throw new _.ErrnoError(m);return f},MAX_OPEN_FDS:4096,nextfd(){for(var f=0;f<=_.MAX_OPEN_FDS;f++)if(!_.streams[f])return f;throw new _.ErrnoError(33)},getStreamChecked(f){var m=_.getStream(f);if(!m)throw new _.ErrnoError(8);return m},getStream:f=>_.streams[f],createStream(f,m=-1){return f=Object.assign(new _.FSStream,f),m==-1&&(m=_.nextfd()),f.fd=m,_.streams[m]=f,f},closeStream(f){_.streams[f]=null},dupStream(f,m=-1){var E=_.createStream(f,m);return E.stream_ops?.dup?.(E),E},doSetAttr(f,m,E){var x=f?.stream_ops.setattr,z=x?f:m;x??=m.node_ops.setattr,_.checkOpExists(x,63);try{x(z,E)}catch(Q){throw Q instanceof RangeError?new _.ErrnoError(22):Q}},chrdev_stream_ops:{open(f){var m=_.getDevice(f.node.rdev);f.stream_ops=m.stream_ops,f.stream_ops.open?.(f)},llseek(){throw new _.ErrnoError(70)}},major:f=>f>>8,minor:f=>f&255,makedev:(f,m)=>f<<8|m,registerDevice(f,m){_.devices[f]={stream_ops:m}},getDevice:f=>_.devices[f],getMounts(f){for(var m=[],E=[f];E.length;){var x=E.pop();m.push(x),E.push(...x.mounts)}return m},syncfs(f,m){typeof f=="function"&&(m=f,f=!1),_.syncFSRequests++,_.syncFSRequests>1&&w(`warning: ${_.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var E=_.getMounts(_.root.mount),x=0;function z(ae){return _.syncFSRequests--,m(ae)}function Q(ae){if(ae)return Q.errored?void 0:(Q.errored=!0,z(ae));++x>=E.length&&z(null)}for(var oe of E)oe.type.syncfs?oe.type.syncfs(oe,f,Q):Q(null)},mount(f,m,E){var x=E==="/",z=!E,Q;if(x&&_.root)throw new _.ErrnoError(10);if(!x&&!z){var oe=_.lookupPath(E,{follow_mount:!1});if(E=oe.path,Q=oe.node,_.isMountpoint(Q))throw new _.ErrnoError(10);if(!_.isDir(Q.mode))throw new _.ErrnoError(54)}var ae={type:f,opts:m,mountpoint:E,mounts:[]},be=f.mount(ae);return be.mount=ae,ae.root=be,x?_.root=be:Q&&(Q.mounted=ae,Q.mount&&Q.mount.mounts.push(ae)),be},unmount(f){var m=_.lookupPath(f,{follow_mount:!1});if(!_.isMountpoint(m.node))throw new _.ErrnoError(28);var E=m.node,x=E.mounted,z=_.getMounts(x);for(var[Q,oe]of Object.entries(_.nameTable))for(;oe;){var ae=oe.name_next;z.includes(oe.mount)&&_.destroyNode(oe),oe=ae}E.mounted=null;var be=E.mount.mounts.indexOf(x);E.mount.mounts.splice(be,1)},lookup(f,m){return f.node_ops.lookup(f,m)},mknod(f,m,E){var x=_.lookupPath(f,{parent:!0}),z=x.node,Q=lt.basename(f);if(!Q)throw new _.ErrnoError(28);if(Q==="."||Q==="..")throw new _.ErrnoError(20);var oe=_.mayCreate(z,Q);if(oe)throw new _.ErrnoError(oe);if(!z.node_ops.mknod)throw new _.ErrnoError(63);return z.node_ops.mknod(z,Q,m,E)},statfs(f){return _.statfsNode(_.lookupPath(f,{follow:!0}).node)},statfsStream(f){return _.statfsNode(f.node)},statfsNode(f){var m={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:_.nextInode,ffree:_.nextInode-1,fsid:42,flags:2,namelen:255};return f.node_ops.statfs&&Object.assign(m,f.node_ops.statfs(f.mount.opts.root)),m},create(f,m=438){return m&=4095,m|=32768,_.mknod(f,m,0)},mkdir(f,m=511){return m&=1023,m|=16384,_.mknod(f,m,0)},mkdirTree(f,m){var E=f.split("/"),x="";for(var z of E)if(z){(x||lt.isAbs(f))&&(x+="/"),x+=z;try{_.mkdir(x,m)}catch(Q){if(Q.errno!=20)throw Q}}},mkdev(f,m,E){return typeof E>"u"&&(E=m,m=438),m|=8192,_.mknod(f,m,E)},symlink(f,m){if(!K.resolve(f))throw new _.ErrnoError(44);var E=_.lookupPath(m,{parent:!0}),x=E.node;if(!x)throw new _.ErrnoError(44);var z=lt.basename(m),Q=_.mayCreate(x,z);if(Q)throw new _.ErrnoError(Q);if(!x.node_ops.symlink)throw new _.ErrnoError(63);return x.node_ops.symlink(x,z,f)},rename(f,m){var E=lt.dirname(f),x=lt.dirname(m),z=lt.basename(f),Q=lt.basename(m),oe,ae,be;if(oe=_.lookupPath(f,{parent:!0}),ae=oe.node,oe=_.lookupPath(m,{parent:!0}),be=oe.node,!ae||!be)throw new _.ErrnoError(44);if(ae.mount!==be.mount)throw new _.ErrnoError(75);var Le=_.lookupNode(ae,z),tt=K.relative(f,x);if(tt.charAt(0)!==".")throw new _.ErrnoError(28);if(tt=K.relative(m,E),tt.charAt(0)!==".")throw new _.ErrnoError(55);var wt;try{wt=_.lookupNode(be,Q)}catch{}if(Le!==wt){var Oe=_.isDir(Le.mode),Xe=_.mayDelete(ae,z,Oe);if(Xe)throw new _.ErrnoError(Xe);if(Xe=wt?_.mayDelete(be,Q,Oe):_.mayCreate(be,Q),Xe)throw new _.ErrnoError(Xe);if(!ae.node_ops.rename)throw new _.ErrnoError(63);if(_.isMountpoint(Le)||wt&&_.isMountpoint(wt))throw new _.ErrnoError(10);if(be!==ae&&(Xe=_.nodePermissions(ae,"w"),Xe))throw new _.ErrnoError(Xe);_.hashRemoveNode(Le);try{ae.node_ops.rename(Le,be,Q),Le.parent=be}catch(Ve){throw Ve}finally{_.hashAddNode(Le)}}},rmdir(f){var m=_.lookupPath(f,{parent:!0}),E=m.node,x=lt.basename(f),z=_.lookupNode(E,x),Q=_.mayDelete(E,x,!0);if(Q)throw new _.ErrnoError(Q);if(!E.node_ops.rmdir)throw new _.ErrnoError(63);if(_.isMountpoint(z))throw new _.ErrnoError(10);E.node_ops.rmdir(E,x),_.destroyNode(z)},readdir(f){var m=_.lookupPath(f,{follow:!0}),E=m.node,x=_.checkOpExists(E.node_ops.readdir,54);return x(E)},unlink(f){var m=_.lookupPath(f,{parent:!0}),E=m.node;if(!E)throw new _.ErrnoError(44);var x=lt.basename(f),z=_.lookupNode(E,x),Q=_.mayDelete(E,x,!1);if(Q)throw new _.ErrnoError(Q);if(!E.node_ops.unlink)throw new _.ErrnoError(63);if(_.isMountpoint(z))throw new _.ErrnoError(10);E.node_ops.unlink(E,x),_.destroyNode(z)},readlink(f){var m=_.lookupPath(f),E=m.node;if(!E)throw new _.ErrnoError(44);if(!E.node_ops.readlink)throw new _.ErrnoError(28);return E.node_ops.readlink(E)},stat(f,m){var E=_.lookupPath(f,{follow:!m}),x=E.node,z=_.checkOpExists(x.node_ops.getattr,63);return z(x)},fstat(f){var m=_.getStreamChecked(f),E=m.node,x=m.stream_ops.getattr,z=x?m:E;return x??=E.node_ops.getattr,_.checkOpExists(x,63),x(z)},lstat(f){return _.stat(f,!0)},doChmod(f,m,E,x){_.doSetAttr(f,m,{mode:E&4095|m.mode&-4096,ctime:Date.now(),dontFollow:x})},chmod(f,m,E){var x;if(typeof f=="string"){var z=_.lookupPath(f,{follow:!E});x=z.node}else x=f;_.doChmod(null,x,m,E)},lchmod(f,m){_.chmod(f,m,!0)},fchmod(f,m){var E=_.getStreamChecked(f);_.doChmod(E,E.node,m,!1)},doChown(f,m,E){_.doSetAttr(f,m,{timestamp:Date.now(),dontFollow:E})},chown(f,m,E,x){var z;if(typeof f=="string"){var Q=_.lookupPath(f,{follow:!x});z=Q.node}else z=f;_.doChown(null,z,x)},lchown(f,m,E){_.chown(f,m,E,!0)},fchown(f,m,E){var x=_.getStreamChecked(f);_.doChown(x,x.node,!1)},doTruncate(f,m,E){if(_.isDir(m.mode))throw new _.ErrnoError(31);if(!_.isFile(m.mode))throw new _.ErrnoError(28);var x=_.nodePermissions(m,"w");if(x)throw new _.ErrnoError(x);_.doSetAttr(f,m,{size:E,timestamp:Date.now()})},truncate(f,m){if(m<0)throw new _.ErrnoError(28);var E;if(typeof f=="string"){var x=_.lookupPath(f,{follow:!0});E=x.node}else E=f;_.doTruncate(null,E,m)},ftruncate(f,m){var E=_.getStreamChecked(f);if(m<0||(E.flags&2097155)===0)throw new _.ErrnoError(28);_.doTruncate(E,E.node,m)},utime(f,m,E){var x=_.lookupPath(f,{follow:!0}),z=x.node,Q=_.checkOpExists(z.node_ops.setattr,63);Q(z,{atime:m,mtime:E})},open(f,m,E=438){if(f==="")throw new _.ErrnoError(44);m=cs(m),m&64?E=E&4095|32768:E=0;var x,z;if(typeof f=="object")x=f;else{z=f.endsWith("/");var Q=_.lookupPath(f,{follow:!(m&131072),noent_okay:!0});x=Q.node,f=Q.path}var oe=!1;if(m&64)if(x){if(m&128)throw new _.ErrnoError(20)}else{if(z)throw new _.ErrnoError(31);x=_.mknod(f,E|511,0),oe=!0}if(!x)throw new _.ErrnoError(44);if(_.isChrdev(x.mode)&&(m&=-513),m&65536&&!_.isDir(x.mode))throw new _.ErrnoError(54);if(!oe){var ae=_.mayOpen(x,m);if(ae)throw new _.ErrnoError(ae)}m&512&&!oe&&_.truncate(x,0),m&=-131713;var be=_.createStream({node:x,path:_.getPath(x),flags:m,seekable:!0,position:0,stream_ops:x.stream_ops,ungotten:[],error:!1});return be.stream_ops.open&&be.stream_ops.open(be),oe&&_.chmod(x,E&511),be},close(f){if(_.isClosed(f))throw new _.ErrnoError(8);f.getdents&&(f.getdents=null);try{f.stream_ops.close&&f.stream_ops.close(f)}catch(m){throw m}finally{_.closeStream(f.fd)}f.fd=null},isClosed(f){return f.fd===null},llseek(f,m,E){if(_.isClosed(f))throw new _.ErrnoError(8);if(!f.seekable||!f.stream_ops.llseek)throw new _.ErrnoError(70);if(E!=0&&E!=1&&E!=2)throw new _.ErrnoError(28);return f.position=f.stream_ops.llseek(f,m,E),f.ungotten=[],f.position},read(f,m,E,x,z){if(x<0||z<0)throw new _.ErrnoError(28);if(_.isClosed(f))throw new _.ErrnoError(8);if((f.flags&2097155)===1)throw new _.ErrnoError(8);if(_.isDir(f.node.mode))throw new _.ErrnoError(31);if(!f.stream_ops.read)throw new _.ErrnoError(28);var Q=typeof z<"u";if(!Q)z=f.position;else if(!f.seekable)throw new _.ErrnoError(70);var oe=f.stream_ops.read(f,m,E,x,z);return Q||(f.position+=oe),oe},write(f,m,E,x,z,Q){if(x<0||z<0)throw new _.ErrnoError(28);if(_.isClosed(f))throw new _.ErrnoError(8);if((f.flags&2097155)===0)throw new _.ErrnoError(8);if(_.isDir(f.node.mode))throw new _.ErrnoError(31);if(!f.stream_ops.write)throw new _.ErrnoError(28);f.seekable&&f.flags&1024&&_.llseek(f,0,2);var oe=typeof z<"u";if(!oe)z=f.position;else if(!f.seekable)throw new _.ErrnoError(70);var ae=f.stream_ops.write(f,m,E,x,z,Q);return oe||(f.position+=ae),ae},mmap(f,m,E,x,z){if((x&2)!==0&&(z&2)===0&&(f.flags&2097155)!==2)throw new _.ErrnoError(2);if((f.flags&2097155)===1)throw new _.ErrnoError(2);if(!f.stream_ops.mmap)throw new _.ErrnoError(43);if(!m)throw new _.ErrnoError(28);return f.stream_ops.mmap(f,m,E,x,z)},msync(f,m,E,x,z){return f.stream_ops.msync?f.stream_ops.msync(f,m,E,x,z):0},ioctl(f,m,E){if(!f.stream_ops.ioctl)throw new _.ErrnoError(59);return f.stream_ops.ioctl(f,m,E)},readFile(f,m={}){m.flags=m.flags??0,m.encoding=m.encoding??"binary",m.encoding!=="utf8"&&m.encoding!=="binary"&&A(`Invalid encoding type "${m.encoding}"`);var E=_.open(f,m.flags),x=_.stat(f),z=x.size,Q=new Uint8Array(z);return _.read(E,Q,0,z,0),m.encoding==="utf8"&&(Q=he(Q)),_.close(E),Q},writeFile(f,m,E={}){E.flags=E.flags??577;var x=_.open(f,E.flags,E.mode);m=Rt(m),_.write(x,m,0,m.byteLength,void 0,E.canOwn),_.close(x)},cwd:()=>_.currentPath,chdir(f){var m=_.lookupPath(f,{follow:!0});if(m.node===null)throw new _.ErrnoError(44);if(!_.isDir(m.node.mode))throw new _.ErrnoError(54);var E=_.nodePermissions(m.node,"x");if(E)throw new _.ErrnoError(E);_.currentPath=m.path},createDefaultDirectories(){_.mkdir("/tmp"),_.mkdir("/home"),_.mkdir("/home/web_user")},createDefaultDevices(){_.mkdir("/dev"),_.registerDevice(_.makedev(1,3),{read:()=>0,write:(x,z,Q,oe,ae)=>oe,llseek:()=>0}),_.mkdev("/dev/null",_.makedev(1,3)),He.register(_.makedev(5,0),He.default_tty_ops),He.register(_.makedev(6,0),He.default_tty1_ops),_.mkdev("/dev/tty",_.makedev(5,0)),_.mkdev("/dev/tty1",_.makedev(6,0));var f=new Uint8Array(1024),m=0,E=()=>(m===0&&(Mm(f),m=f.byteLength),f[--m]);_.createDevice("/dev","random",E),_.createDevice("/dev","urandom",E),_.mkdir("/dev/shm"),_.mkdir("/dev/shm/tmp")},createSpecialDirectories(){_.mkdir("/proc");var f=_.mkdir("/proc/self");_.mkdir("/proc/self/fd"),_.mount({mount(){var m=_.createNode(f,"fd",16895,73);return m.stream_ops={llseek:Se.stream_ops.llseek},m.node_ops={lookup(E,x){var z=+x,Q=_.getStreamChecked(z),oe={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>Q.path},id:z+1};return oe.parent=oe,oe},readdir(){return Array.from(_.streams.entries()).filter(([E,x])=>x).map(([E,x])=>E.toString())}},m}},{},"/proc/self/fd")},createStandardStreams(f,m,E){f?_.createDevice("/dev","stdin",f):_.symlink("/dev/tty","/dev/stdin"),m?_.createDevice("/dev","stdout",null,m):_.symlink("/dev/tty","/dev/stdout"),E?_.createDevice("/dev","stderr",null,E):_.symlink("/dev/tty1","/dev/stderr");var x=_.open("/dev/stdin",0),z=_.open("/dev/stdout",1),Q=_.open("/dev/stderr",1)},staticInit(){_.nameTable=new Array(4096),_.mount(Se,{},"/"),_.createDefaultDirectories(),_.createDefaultDevices(),_.createSpecialDirectories(),_.filesystems={MEMFS:Se}},init(f,m,E){_.initialized=!0,f??=n.stdin,m??=n.stdout,E??=n.stderr,_.createStandardStreams(f,m,E)},quit(){_.initialized=!1;for(var f of _.streams)f&&_.close(f)},findObject(f,m){var E=_.analyzePath(f,m);return E.exists?E.object:null},analyzePath(f,m){try{var E=_.lookupPath(f,{follow:!m});f=E.path}catch{}var x={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var E=_.lookupPath(f,{parent:!0});x.parentExists=!0,x.parentPath=E.path,x.parentObject=E.node,x.name=lt.basename(f),E=_.lookupPath(f,{follow:!m}),x.exists=!0,x.path=E.path,x.object=E.node,x.name=E.node.name,x.isRoot=E.path==="/"}catch(z){x.error=z.errno}return x},createPath(f,m,E,x){f=typeof f=="string"?f:_.getPath(f);for(var z=m.split("/").reverse();z.length;){var Q=z.pop();if(Q){var oe=lt.join2(f,Q);try{_.mkdir(oe)}catch(ae){if(ae.errno!=20)throw ae}f=oe}}return oe},createFile(f,m,E,x,z){var Q=lt.join2(typeof f=="string"?f:_.getPath(f),m),oe=wn(x,z);return _.create(Q,oe)},createDataFile(f,m,E,x,z,Q){var oe=m;f&&(f=typeof f=="string"?f:_.getPath(f),oe=m?lt.join2(f,m):f);var ae=wn(x,z),be=_.create(oe,ae);if(E){E=Rt(E),_.chmod(be,ae|146);var Le=_.open(be,577);_.write(Le,E,0,E.length,0,Q),_.close(Le),_.chmod(be,ae)}},createDevice(f,m,E,x){var z=lt.join2(typeof f=="string"?f:_.getPath(f),m),Q=wn(!!E,!!x);_.createDevice.major??=64;var oe=_.makedev(_.createDevice.major++,0);return _.registerDevice(oe,{open(ae){ae.seekable=!1},close(ae){x?.buffer?.length&&x(10)},read(ae,be,Le,tt,wt){for(var Oe=0,Xe=0;Xethis.length-1||Oe<0)){var Xe=Oe%this.chunkSize,Ve=Oe/this.chunkSize|0;return this.getter(Ve)[Xe]}}setDataGetter(Oe){this.getter=Oe}cacheLength(){var Oe=new XMLHttpRequest;Oe.open("HEAD",E,!1),Oe.send(null),Oe.status>=200&&Oe.status<300||Oe.status===304||A("Couldn't load "+E+". Status: "+Oe.status);var Xe=Number(Oe.getResponseHeader("Content-length")),Ve,Zt=(Ve=Oe.getResponseHeader("Accept-Ranges"))&&Ve==="bytes",Gi=(Ve=Oe.getResponseHeader("Content-Encoding"))&&Ve==="gzip",Yi=1024*1024;Zt||(Yi=Xe);var Zi=(_o,pu)=>{_o>pu&&A(`invalid range (${_o}, ${pu}) or no bytes requested!`),pu>Xe-1&&A(`only ${Xe} bytes available! programmer error!`);var qn=new XMLHttpRequest;return qn.open("GET",E,!1),Xe!==Yi&&qn.setRequestHeader("Range","bytes="+_o+"-"+pu),qn.responseType="arraybuffer",qn.overrideMimeType&&qn.overrideMimeType("text/plain; charset=x-user-defined"),qn.send(null),qn.status>=200&&qn.status<300||qn.status===304||A("Couldn't load "+E+". Status: "+qn.status),qn.response!==void 0?new Uint8Array(qn.response||[]):Re(qn.responseText??"",!0)},bp=this;bp.setDataGetter(_o=>{var pu=_o*Yi,qn=(_o+1)*Yi-1;return qn=Math.min(qn,Xe-1),typeof bp.chunks[_o]>"u"&&(bp.chunks[_o]=Zi(pu,qn)),typeof bp.chunks[_o]>"u"&&A("doXHR failed!"),bp.chunks[_o]}),(Gi||!Xe)&&(Yi=Xe=1,Xe=this.getter(0).length,Yi=Xe,g("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=Xe,this._chunkSize=Yi,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(globalThis.XMLHttpRequest){i||A("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var oe=new Q,ae={isDevice:!1,contents:oe}}else var ae={isDevice:!1,url:E};var be=_.createFile(f,m,ae,x,z);ae.contents?be.contents=ae.contents:ae.url&&(be.contents=null,be.url=ae.url),Object.defineProperties(be,{usedBytes:{get:function(){return this.contents.length}}});var Le={};for(let[wt,Oe]of Object.entries(be.stream_ops))Le[wt]=(...Xe)=>(_.forceLoadFile(be),Oe(...Xe));function tt(wt,Oe,Xe,Ve,Zt){var Gi=wt.node.contents;if(Zt>=Gi.length)return 0;var Yi=Math.min(Gi.length-Zt,Ve);if(Gi.slice)for(var Zi=0;Zi(_.forceLoadFile(be),tt(wt,Oe,Xe,Ve,Zt)),Le.mmap=(wt,Oe,Xe,Ve,Zt)=>{_.forceLoadFile(be);var Gi=Je(Oe);if(!Gi)throw new _.ErrnoError(48);return tt(wt,J,Gi,Oe,Xe),{ptr:Gi,allocated:!0}},be.stream_ops=Le,be}},WE=(f,m,E)=>{if(!f)return"";var x=ce(Ee,f,m,E);return re.decode(Ee.subarray(f,x))},vn={currentUmask:18,calculateAt(f,m,E){if(lt.isAbs(m))return m;var x;if(f===-100)x=_.cwd();else{var z=vn.getStreamFromFD(f);x=z.path}if(m.length==0){if(!E)throw new _.ErrnoError(44);return x}return x+"/"+m},writeStat(f,m){pe[f>>2]=m.dev,pe[f+4>>2]=m.mode,pe[f+8>>2]=m.nlink,pe[f+12>>2]=m.uid,pe[f+16>>2]=m.gid,pe[f+20>>2]=m.rdev,ee[f+24>>3]=BigInt(m.size),Z[f+32>>2]=4096,Z[f+36>>2]=m.blocks;var E=m.atime.getTime(),x=m.mtime.getTime(),z=m.ctime.getTime();return ee[f+40>>3]=BigInt(Math.floor(E/1e3)),pe[f+48>>2]=E%1e3*1e3*1e3,ee[f+56>>3]=BigInt(Math.floor(x/1e3)),pe[f+64>>2]=x%1e3*1e3*1e3,ee[f+72>>3]=BigInt(Math.floor(z/1e3)),pe[f+80>>2]=z%1e3*1e3*1e3,ee[f+88>>3]=BigInt(m.ino),0},writeStatFs(f,m){pe[f+4>>2]=m.bsize,pe[f+60>>2]=m.bsize,ee[f+8>>3]=BigInt(m.blocks),ee[f+16>>3]=BigInt(m.bfree),ee[f+24>>3]=BigInt(m.bavail),ee[f+32>>3]=BigInt(m.files),ee[f+40>>3]=BigInt(m.ffree),pe[f+48>>2]=m.fsid,pe[f+64>>2]=m.flags,pe[f+56>>2]=m.namelen},doMsync(f,m,E,x,z){if(!_.isFile(m.node.mode))throw new _.ErrnoError(43);if(x&2)return 0;var Q=Ee.subarray(f,f+E);_.msync(m,Q,z,E,x)},getStreamFromFD(f){var m=_.getStreamChecked(f);return m},varargs:void 0,getStr(f){var m=WE(f);return m}};function MF(f,m){try{return vn.writeStat(m,_.fstat(f))}catch(E){if(typeof _>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}var QC=(f,m,E)=>Me(f,Ee,m,E);function OF(f,m,E){try{var x=vn.getStreamFromFD(f);x.getdents||=_.readdir(x.path);for(var z=280,Q=0,oe=_.llseek(x,0,1),ae=Math.floor(oe/z),be=Math.min(x.getdents.length,ae+Math.floor(E/z)),Le=ae;Le>3]=BigInt(tt),ee[m+Q+8>>3]=BigInt((Le+1)*z),X[m+Q+16>>1]=280,J[m+Q+18]=wt,QC(Oe,m+Q+19,256),Q+=z}return _.llseek(x,Le*z,0),Q}catch(Zt){if(typeof _>"u"||Zt.name!=="ErrnoError")throw Zt;return-Zt.errno}}function DF(f,m){try{return f=vn.getStr(f),vn.writeStat(m,_.lstat(f))}catch(E){if(typeof _>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}function RF(f,m,E,x){try{m=vn.getStr(m);var z=x&256,Q=x&4096;return x=x&-6401,m=vn.calculateAt(f,m,Q),vn.writeStat(E,z?_.lstat(m):_.stat(m))}catch(oe){if(typeof _>"u"||oe.name!=="ErrnoError")throw oe;return-oe.errno}}var NF=()=>{var f=Z[+vn.varargs>>2];return vn.varargs+=4,f};function LF(f,m,E,x){vn.varargs=x;try{m=vn.getStr(m),m=vn.calculateAt(f,m);var z=x?NF():0;return E&64&&(z&=~vn.currentUmask),_.open(m,E,z).fd}catch(Q){if(typeof _>"u"||Q.name!=="ErrnoError")throw Q;return-Q.errno}}function BF(f,m){try{return f=vn.getStr(f),vn.writeStat(m,_.stat(f))}catch(E){if(typeof _>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}var FF=()=>A(""),GE=0,UF=()=>{xe=!1,GE=0},mp={},YE=f=>{if(f instanceof L||f=="unwind")return B;c(1,f)},ZE=()=>xe||GE>0,JE=f=>{B=f,ZE()||(n.onExit?.(f),k=!0),c(f,new L(f))},$F=(f,m)=>{B=f,JE(f)},qF=$F,HF=()=>{if(!ZE())try{qF(B)}catch(f){YE(f)}},VF=f=>{if(!k)try{return f()}catch(m){YE(m)}finally{HF()}},QE=()=>performance.now(),KF=(f,m)=>{if(mp[f]&&(clearTimeout(mp[f].id),delete mp[f]),!m)return 0;var E=setTimeout(()=>{delete mp[f],VF(()=>i8(f,QE()))},m);return mp[f]={id:E,timeout_ms:m},0},e8=()=>Date.now(),zF=1,jF=f=>f>=0&&f<=3,XF=9007199254740992,WF=-9007199254740992,GF=f=>fXF?NaN:Number(f);function YF(f,m,E){if(m=GF(m),!jF(f))return 28;var x;if(f===0)x=e8();else if(zF)x=QE();else return 52;var z=Math.round(x*1e3*1e3);return ee[E>>3]=BigInt(z),0}var ZF=()=>134217728,JF=(f,m)=>Math.ceil(f/m)*m,QF=f=>{var m=Om.buffer.byteLength,E=(f-m+65535)/65536|0;try{return Om.grow(E),b(),1}catch{}},eU=f=>{var m=Ee.length;f>>>=0;var E=ZF();if(f>E)return!1;for(var x=1;x<=4;x*=2){var z=m*(1+.2/x);z=Math.min(z,f+100663296);var Q=Math.min(E,JF(Math.max(f,z),65536)),oe=QF(Q);if(oe)return!0}return!1},ev={},tU=()=>s,gp=()=>{if(!gp.strings){var f=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:f,_:tU()};for(var E in ev)ev[E]===void 0?delete m[E]:m[E]=ev[E];var x=[];for(var E in m)x.push(`${E}=${m[E]}`);gp.strings=x}return gp.strings},nU=(f,m)=>{var E=0,x=0;for(var z of gp()){var Q=m+E;pe[f+x>>2]=Q,E+=QC(z,Q,1/0)+1,x+=4}return 0},rU=(f,m)=>{var E=gp();pe[f>>2]=E.length;var x=0;for(var z of E)x+=we(z)+1;return pe[m>>2]=x,0};function iU(f){try{var m=vn.getStreamFromFD(f);return _.close(m),0}catch(E){if(typeof _>"u"||E.name!=="ErrnoError")throw E;return E.errno}}var oU=(f,m,E,x)=>{for(var z=0,Q=0;Q>2],ae=pe[m+4>>2];m+=8;var be=_.read(f,J,oe,ae,x);if(be<0)return-1;if(z+=be,be>2]=Q,0}catch(oe){if(typeof _>"u"||oe.name!=="ErrnoError")throw oe;return oe.errno}}var sU=(f,m,E,x)=>{for(var z=0,Q=0;Q>2],ae=pe[m+4>>2];m+=8;var be=_.write(f,J,oe,ae,x);if(be<0)return-1;if(z+=be,be>2]=Q,0}catch(oe){if(typeof _>"u"||oe.name!=="ErrnoError")throw oe;return oe.errno}}var t8=f=>{var m=n["_"+f];return m},lU=(f,m)=>{J.set(f,m)},n8=f=>a8(f),uU=f=>{var m=we(f)+1,E=n8(m);return QC(f,E,m),E},r8=(f,m,E,x,z)=>{var Q={string:Ve=>{var Zt=0;return Ve!=null&&Ve!==0&&(Zt=uU(Ve)),Zt},array:Ve=>{var Zt=n8(Ve.length);return lU(Ve,Zt),Zt}};function oe(Ve){return m==="string"?WE(Ve):m==="boolean"?!!Ve:Ve}var ae=t8(f),be=[],Le=0;if(x)for(var tt=0;tt{var z=!E||E.every(oe=>oe==="number"||oe==="boolean"),Q=m!=="string";return Q&&z&&!x?t8(f):(...oe)=>r8(f,m,E,oe,x)};_.createPreloadedFile=xF,_.preloadFile=XE,_.staticInit();{n.noExitRuntime&&(xe=n.noExitRuntime),n.print&&(g=n.print),n.printErr&&(w=n.printErr),n.arguments&&(a=n.arguments),n.thisProgram&&(s=n.thisProgram);var fu=n.preInit;if(fu)for(typeof fu=="function"&&(n.preInit=fu=[fu]);fu.length>0;)fu.shift()()}n.ccall=r8,n.cwrap=dU;var fU,pU,yU,hU,mU,gU,wU,bU,CU,vU,AU,SU,TU,EU,kU,_U,IU,PU,xU,MU,OU,DU,RU,NU,LU,BU,FU,i8,o8,a8,s8,UU,$U,Om;function qU(f){fU=n._free=f.v,pU=n._malloc=f.w,yU=n._secp256k1_elgamal_add=f.x,hU=n._secp256k1_elgamal_subtract=f.y,mU=n._mpt_secp256k1_context=f.z,gU=n._mpt_make_ec_pair=f.A,wU=n._mpt_serialize_ec_pair=f.B,bU=n._mpt_get_convert_context_hash=f.C,CU=n._mpt_get_convert_back_context_hash=f.D,vU=n._mpt_get_send_context_hash=f.E,AU=n._mpt_get_clawback_context_hash=f.F,SU=n._mpt_generate_blinding_factor=f.G,TU=n._mpt_encrypt_amount=f.H,EU=n._mpt_decrypt_amount=f.I,kU=n._mpt_verify_revealed_amount=f.J,_U=n._mpt_get_convert_proof=f.K,IU=n._mpt_get_pedersen_commitment=f.L,PU=n._mpt_get_confidential_send_proof=f.M,xU=n._mpt_get_convert_back_proof=f.N,MU=n._mpt_get_clawback_proof=f.O,OU=n._mpt_verify_convert_proof=f.P,DU=n._mpt_compute_convert_back_remainder=f.Q,RU=n._mpt_verify_aggregated_bulletproof=f.R,NU=n._mpt_verify_convert_back_proof=f.S,LU=n._mpt_verify_send_range_proof=f.T,BU=n._mpt_verify_send_proof=f.U,FU=n._mpt_verify_clawback_proof=f.V,i8=f.W,o8=f.X,a8=f.Y,s8=f.Z,UU=Om=f.t,$U=f.__indirect_function_table}var HU={s:uu,d:MF,k:OF,q:DF,p:RF,g:LF,c:BF,r:FF,m:UF,i:KF,h:YF,b:e8,j:eU,n:nU,o:rU,a:iU,f:aU,e:cU,l:JE};async function VU(){C(),zr&&await hp();var f=n.setStatus;f&&(f("Running..."),await new Promise(m=>setTimeout(m,1)),setTimeout(f,1,"")),!k&&(v(),n.onRuntimeInitialized?.(),S())}var wp;return wp=await G(),await VU(),n}})();typeof XM=="object"&&typeof Gw=="object"?(Gw.exports=iT,Gw.exports.default=iT):typeof define=="function"&&define.amd&&define([],()=>iT)});var aT=q(Ri=>{"use strict";y();var Roe=Ri&&Ri.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Noe=Ri&&Ri.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Loe=Ri&&Ri.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&Roe(t,e,n);return Noe(t,e),t};Object.defineProperty(Ri,"__esModule",{value:!0});Ri.loadWasmModule=Ri.loadWithRetry=void 0;var Yw,Boe=3,Foe=100;async function Uoe(){let{default:e}=await Promise.resolve().then(()=>Loe(WM())),t=await e();if(t._mpt_secp256k1_context()===0)throw new Error("mpt-crypto: failed to initialize the secp256k1 context");return t}async function oT(e=Uoe,t=1){try{return await e()}catch(n){if(t>=Boe)throw n;return await new Promise(r=>{setTimeout(r,t*Foe)}),oT(e,t+1)}}Ri.loadWithRetry=oT;async function $oe(){return Yw??(Yw=oT().catch(e=>{throw Yw=void 0,e})),Yw}Ri.loadWasmModule=$oe});var Zw=q(Xn=>{"use strict";y();Object.defineProperty(Xn,"__esModule",{value:!0});Xn.rawPedersenParams=Xn.rawParticipant=Xn.assertUint32=Xn.U32_MAX=Xn.assertUint64=Xn.U64_MAX=void 0;var gh=ac(),wh=Ml();Xn.U64_MAX=2n**64n-1n;function GM(e,t,n=Xn.U64_MAX){if(e<0n||e>n)throw new Error(`${t} must be an integer in [0, ${n}] (got ${e})`)}Xn.assertUint64=GM;Xn.U32_MAX=4294967295;function qoe(e,t){if(!Number.isInteger(e)||e<0||e>Xn.U32_MAX)throw new Error(`${t} must be an integer in [0, ${Xn.U32_MAX}] (got ${e})`)}Xn.assertUint32=qoe;function Hoe(e,t){return{publicKey:(0,wh.hexToBytes)(e.publicKey,`${t}.publicKey`,gh.PUBKEY_SIZE),ciphertext:(0,wh.hexToBytes)(e.ciphertext,`${t}.ciphertext`,gh.ELGAMAL_TOTAL_SIZE)}}Xn.rawParticipant=Hoe;function Voe(e,t){return GM(e.amount,`${t}.amount`),{commitment:(0,wh.hexToBytes)(e.commitment,`${t}.commitment`,gh.PEDERSEN_COMMIT_SIZE),amount:e.amount,ciphertext:(0,wh.hexToBytes)(e.ciphertext,`${t}.ciphertext`,gh.ELGAMAL_TOTAL_SIZE),blindingFactor:(0,wh.hexToBytes)(e.blindingFactor,`${t}.blindingFactor`,gh.BLINDING_FACTOR_SIZE)}}Xn.rawPedersenParams=Voe});var YM=q(Jw=>{"use strict";y();Object.defineProperty(Jw,"__esModule",{value:!0});Jw.Marshaller=void 0;var Wa=ac(),sT=class{constructor(t){this.ptrs=[],this.mod=t}alloc(t){let n=this.mod._malloc(t);if(n===0)throw new Error(`mpt-crypto: failed to allocate ${t} bytes`);return this.mod.HEAPU8.fill(0,n,n+t),this.ptrs.push({ptr:n,size:t}),n}allocBytes(t){let n=this.mod._malloc(t.length);if(n===0)throw new Error(`mpt-crypto: failed to allocate ${t.length} bytes`);return this.mod.HEAPU8.set(t,n),this.ptrs.push({ptr:n,size:t.length}),n}readBytes(t,n){return this.mod.HEAPU8.slice(t,t+n)}view(){return new DataView(this.mod.HEAPU8.buffer)}writeU32(t,n){this.view().setUint32(t,n,!0)}readU32(t){return this.view().getUint32(t,!0)}readU64(t){return this.view().getBigUint64(t,!0)}allocPedersenParams(t){let n=this.alloc(Wa.PEDERSEN_PARAMS_STRUCT_SIZE);return this.mod.HEAPU8.set(t.commitment,n+Wa.PEDERSEN_PARAMS_COMMITMENT_OFFSET),this.view().setBigUint64(n+Wa.PEDERSEN_PARAMS_AMOUNT_OFFSET,t.amount,!0),this.mod.HEAPU8.set(t.ciphertext,n+Wa.PEDERSEN_PARAMS_CIPHERTEXT_OFFSET),this.mod.HEAPU8.set(t.blindingFactor,n+Wa.PEDERSEN_PARAMS_BLINDING_OFFSET),n}allocParticipants(t){let n=this.alloc(Wa.PARTICIPANT_STRUCT_SIZE*t.length);return t.forEach((r,i)=>{let o=n+i*Wa.PARTICIPANT_STRUCT_SIZE;this.mod.HEAPU8.set(r.publicKey,o+Wa.PARTICIPANT_PUBKEY_OFFSET),this.mod.HEAPU8.set(r.ciphertext,o+Wa.PARTICIPANT_CIPHERTEXT_OFFSET)}),n}dispose(){for(let{ptr:t,size:n}of this.ptrs)this.mod.HEAPU8.fill(0,t,t+n),this.mod._free(t);this.ptrs.length=0}};Jw.Marshaller=sT});var bh=q(Qw=>{"use strict";y();Object.defineProperty(Qw,"__esModule",{value:!0});Qw.withModule=void 0;var Koe=YM(),zoe=aT();async function joe(e){let t=await(0,zoe.loadWasmModule)(),n=new Koe.Marshaller(t);try{return e(t,n)}finally{n.dispose()}}Qw.withModule=joe});var ZM=q(Jo=>{"use strict";y();Object.defineProperty(Jo,"__esModule",{value:!0});Jo.getPedersenCommitment=Jo.decryptAmount=Jo.encryptAmount=Jo.generateBlindingFactor=void 0;var Co=ac(),sc=Ml(),eb=Zw(),tb=bh(),Xoe=8,Woe=eb.U64_MAX-1n,Goe=0n;async function Yoe(){return(0,tb.withModule)((e,t)=>{let n=t.alloc(Co.BLINDING_FACTOR_SIZE);if(e._mpt_generate_blinding_factor(n)!==0)throw new Error("mpt_generate_blinding_factor failed");return(0,sc.bytesToHex)(t.readBytes(n,Co.BLINDING_FACTOR_SIZE))})}Jo.generateBlindingFactor=Yoe;async function Zoe(e,t,n){(0,eb.assertUint64)(e,"amount");let r=(0,sc.hexToBytes)(t,"publicKey",Co.PUBKEY_SIZE),i=(0,sc.hexToBytes)(n,"blindingFactor",Co.BLINDING_FACTOR_SIZE);return(0,tb.withModule)((o,a)=>{let s=a.allocBytes(r),c=a.allocBytes(i);i.fill(0);let l=a.alloc(Co.ELGAMAL_TOTAL_SIZE);if(o._mpt_encrypt_amount(e,s,c,l)!==0)throw new Error("mpt_encrypt_amount failed");return(0,sc.bytesToHex)(a.readBytes(l,Co.ELGAMAL_TOTAL_SIZE))})}Jo.encryptAmount=Zoe;async function Joe(e,t,n){(0,eb.assertUint64)(n,"rangeHigh",Woe);let r=(0,sc.hexToBytes)(e,"ciphertext",Co.ELGAMAL_TOTAL_SIZE),i=(0,sc.hexToBytes)(t,"privateKey",Co.PRIVKEY_SIZE);return(0,tb.withModule)((o,a)=>{let s=a.allocBytes(r),c=a.allocBytes(i);i.fill(0);let l=a.alloc(Xoe);if(o._mpt_decrypt_amount(s,c,l,Goe,n)!==0)throw new Error("mpt_decrypt_amount failed");return a.readU64(l)})}Jo.decryptAmount=Joe;async function Qoe(e,t){(0,eb.assertUint64)(e,"amount");let n=(0,sc.hexToBytes)(t,"blindingFactor",Co.BLINDING_FACTOR_SIZE);return(0,tb.withModule)((r,i)=>{let o=i.allocBytes(n);n.fill(0);let a=i.alloc(Co.PEDERSEN_COMMIT_SIZE);if(r._mpt_get_pedersen_commitment(e,o,a)!==0)throw new Error("mpt_get_pedersen_commitment failed");return(0,sc.bytesToHex)(i.readBytes(a,Co.PEDERSEN_COMMIT_SIZE))})}Jo.getPedersenCommitment=Qoe});var QM=q(ef=>{"use strict";y();Object.defineProperty(ef,"__esModule",{value:!0});ef.subtractCiphertexts=ef.addCiphertexts=void 0;var nb=ac(),cT=Ml(),eae=bh(),Qd=64,rb=1;async function JM(e,t,n){let r=(0,cT.hexToBytes)(e,"a",nb.ELGAMAL_TOTAL_SIZE),i=(0,cT.hexToBytes)(t,"b",nb.ELGAMAL_TOTAL_SIZE);return(0,eae.withModule)((o,a)=>{let s=o._mpt_secp256k1_context();if(s===0)throw new Error("mpt-crypto: secp256k1 context unavailable");let c=a.allocBytes(r),l=a.allocBytes(i),u=a.alloc(Qd),d=a.alloc(Qd),p=a.alloc(Qd),h=a.alloc(Qd),g=a.alloc(Qd),w=a.alloc(Qd);if(o._mpt_make_ec_pair(c,u,d)!==rb)throw new Error("mpt-crypto: failed to parse ciphertext a");if(o._mpt_make_ec_pair(l,p,h)!==rb)throw new Error("mpt-crypto: failed to parse ciphertext b");if((n==="add"?o._secp256k1_elgamal_add(s,g,w,u,d,p,h):o._secp256k1_elgamal_subtract(s,g,w,u,d,p,h))!==rb)throw new Error(`mpt-crypto: elgamal ${n} failed`);let k=a.alloc(nb.ELGAMAL_TOTAL_SIZE);if(o._mpt_serialize_ec_pair(g,w,k)!==rb)throw new Error("mpt-crypto: failed to serialize combined ciphertext");return(0,cT.bytesToHex)(a.readBytes(k,nb.ELGAMAL_TOTAL_SIZE))})}async function tae(e,t){return JM(e,t,"add")}ef.addCiphertexts=tae;async function nae(e,t){return JM(e,t,"subtract")}ef.subtractCiphertexts=nae});var eO=q(Qo=>{"use strict";y();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.getClawbackContextHash=Qo.getSendContextHash=Qo.getConvertBackContextHash=Qo.getConvertContextHash=void 0;var Fn=ac(),Rr=Ml(),tf=Zw(),ib=bh();async function rae(e,t,n){(0,tf.assertUint32)(n,"sequence");let r=(0,Rr.hexToBytes)(e,"account",Fn.ACCOUNT_ID_SIZE),i=(0,Rr.hexToBytes)(t,"issuance",Fn.ISSUANCE_ID_SIZE);return(0,ib.withModule)((o,a)=>{let s=a.allocBytes(r),c=a.allocBytes(i),l=a.alloc(Fn.CONTEXT_HASH_SIZE);if(o._mpt_get_convert_context_hash(s,c,n,l)!==0)throw new Error("mpt_get_convert_context_hash failed");return(0,Rr.bytesToHex)(a.readBytes(l,Fn.CONTEXT_HASH_SIZE))})}Qo.getConvertContextHash=rae;async function iae(e,t,n,r){(0,tf.assertUint32)(n,"sequence"),(0,tf.assertUint32)(r,"version");let i=(0,Rr.hexToBytes)(e,"account",Fn.ACCOUNT_ID_SIZE),o=(0,Rr.hexToBytes)(t,"issuance",Fn.ISSUANCE_ID_SIZE);return(0,ib.withModule)((a,s)=>{let c=s.allocBytes(i),l=s.allocBytes(o),u=s.alloc(Fn.CONTEXT_HASH_SIZE);if(a._mpt_get_convert_back_context_hash(c,l,n,r,u)!==0)throw new Error("mpt_get_convert_back_context_hash failed");return(0,Rr.bytesToHex)(s.readBytes(u,Fn.CONTEXT_HASH_SIZE))})}Qo.getConvertBackContextHash=iae;async function oae(e,t,n,r,i){(0,tf.assertUint32)(n,"sequence"),(0,tf.assertUint32)(i,"version");let o=(0,Rr.hexToBytes)(e,"account",Fn.ACCOUNT_ID_SIZE),a=(0,Rr.hexToBytes)(t,"issuance",Fn.ISSUANCE_ID_SIZE),s=(0,Rr.hexToBytes)(r,"destination",Fn.ACCOUNT_ID_SIZE);return(0,ib.withModule)((c,l)=>{let u=l.allocBytes(o),d=l.allocBytes(a),p=l.allocBytes(s),h=l.alloc(Fn.CONTEXT_HASH_SIZE);if(c._mpt_get_send_context_hash(u,d,n,p,i,h)!==0)throw new Error("mpt_get_send_context_hash failed");return(0,Rr.bytesToHex)(l.readBytes(h,Fn.CONTEXT_HASH_SIZE))})}Qo.getSendContextHash=oae;async function aae(e,t,n,r){(0,tf.assertUint32)(n,"sequence");let i=(0,Rr.hexToBytes)(e,"account",Fn.ACCOUNT_ID_SIZE),o=(0,Rr.hexToBytes)(t,"issuance",Fn.ISSUANCE_ID_SIZE),a=(0,Rr.hexToBytes)(r,"holder",Fn.ACCOUNT_ID_SIZE);return(0,ib.withModule)((s,c)=>{let l=c.allocBytes(i),u=c.allocBytes(o),d=c.allocBytes(a),p=c.alloc(Fn.CONTEXT_HASH_SIZE);if(s._mpt_get_clawback_context_hash(l,u,n,d,p)!==0)throw new Error("mpt_get_clawback_context_hash failed");return(0,Rr.bytesToHex)(c.readBytes(p,Fn.CONTEXT_HASH_SIZE))})}Qo.getClawbackContextHash=aae});var tO=q(ea=>{"use strict";y();Object.defineProperty(ea,"__esModule",{value:!0});ea.getConfidentialSendProof=ea.getConvertBackProof=ea.getClawbackProof=ea.getConvertProof=void 0;var Gt=ac(),xn=Ml(),nf=Zw(),ob=bh(),sae=4;async function cae(e,t,n){let r=(0,xn.hexToBytes)(e,"publicKey",Gt.PUBKEY_SIZE),i=(0,xn.hexToBytes)(t,"privateKey",Gt.PRIVKEY_SIZE),o=(0,xn.hexToBytes)(n,"contextHash",Gt.CONTEXT_HASH_SIZE);return(0,ob.withModule)((a,s)=>{let c=s.allocBytes(r),l=s.allocBytes(i);i.fill(0);let u=s.allocBytes(o),d=s.alloc(Gt.CONVERT_PROOF_SIZE);if(a._mpt_get_convert_proof(c,l,u,d)!==0)throw new Error("mpt_get_convert_proof failed");return(0,xn.bytesToHex)(s.readBytes(d,Gt.CONVERT_PROOF_SIZE))})}ea.getConvertProof=cae;async function lae(e,t,n,r,i){(0,nf.assertUint64)(r,"amount");let o=(0,xn.hexToBytes)(e,"privateKey",Gt.PRIVKEY_SIZE),a=(0,xn.hexToBytes)(t,"publicKey",Gt.PUBKEY_SIZE),s=(0,xn.hexToBytes)(n,"contextHash",Gt.CONTEXT_HASH_SIZE),c=(0,xn.hexToBytes)(i,"ciphertext",Gt.ELGAMAL_TOTAL_SIZE);return(0,ob.withModule)((l,u)=>{let d=u.allocBytes(o);o.fill(0);let p=u.allocBytes(a),h=u.allocBytes(s),g=u.allocBytes(c),w=u.alloc(Gt.CLAWBACK_PROOF_SIZE);if(l._mpt_get_clawback_proof(d,p,h,r,g,w)!==0)throw new Error("mpt_get_clawback_proof failed");return(0,xn.bytesToHex)(u.readBytes(w,Gt.CLAWBACK_PROOF_SIZE))})}ea.getClawbackProof=lae;async function uae(e,t,n,r,i){(0,nf.assertUint64)(r,"amount");let o=(0,xn.hexToBytes)(e,"privateKey",Gt.PRIVKEY_SIZE),a=(0,xn.hexToBytes)(t,"publicKey",Gt.PUBKEY_SIZE),s=(0,xn.hexToBytes)(n,"contextHash",Gt.CONTEXT_HASH_SIZE),c=(0,nf.rawPedersenParams)(i,"params");return(0,ob.withModule)((l,u)=>{let d=u.allocBytes(o);o.fill(0);let p=u.allocBytes(a),h=u.allocBytes(s),g=u.allocPedersenParams(c);c.blindingFactor.fill(0);let w=u.alloc(Gt.CONVERT_BACK_PROOF_SIZE);if(l._mpt_get_convert_back_proof(d,p,h,r,g,w)!==0)throw new Error("mpt_get_convert_back_proof failed");return(0,xn.bytesToHex)(u.readBytes(w,Gt.CONVERT_BACK_PROOF_SIZE))})}ea.getConvertBackProof=uae;async function dae(e){if((0,nf.assertUint64)(e.amount,"amount"),e.participants.length===0)throw new Error("getConfidentialSendProof: participants must not be empty");let t=(0,xn.hexToBytes)(e.privateKey,"privateKey",Gt.PRIVKEY_SIZE),n=(0,xn.hexToBytes)(e.publicKey,"publicKey",Gt.PUBKEY_SIZE),r=(0,xn.hexToBytes)(e.txBlindingFactor,"txBlindingFactor",Gt.BLINDING_FACTOR_SIZE),i=(0,xn.hexToBytes)(e.contextHash,"contextHash",Gt.CONTEXT_HASH_SIZE),o=(0,xn.hexToBytes)(e.amountCommitment,"amountCommitment",Gt.PEDERSEN_COMMIT_SIZE),a=e.participants.map((c,l)=>(0,nf.rawParticipant)(c,`participants[${l}]`)),s=(0,nf.rawPedersenParams)(e.balanceParams,"balanceParams");return(0,ob.withModule)((c,l)=>{let u=l.allocBytes(t);t.fill(0);let d=l.allocBytes(n),p=l.allocParticipants(a),h=l.allocBytes(r);r.fill(0);let g=l.allocBytes(i),w=l.allocBytes(o),T=l.allocPedersenParams(s);s.blindingFactor.fill(0);let k=l.alloc(Gt.SEND_PROOF_SIZE),B=l.alloc(sae);if(l.writeU32(B,Gt.SEND_PROOF_SIZE),c._mpt_get_confidential_send_proof(u,d,e.amount,p,a.length,h,g,w,T,k,B)!==0)throw new Error("mpt_get_confidential_send_proof failed");let D=l.readU32(B);if(D>Gt.SEND_PROOF_SIZE)throw new Error("mpt_get_confidential_send_proof wrote more than the allocated buffer");return(0,xn.bytesToHex)(l.readBytes(k,D))})}ea.getConfidentialSendProof=dae});var iO=q(ke=>{"use strict";y();Object.defineProperty(ke,"__esModule",{value:!0});ke.getConfidentialSendProof=ke.getConvertBackProof=ke.getClawbackProof=ke.getConvertProof=ke.getClawbackContextHash=ke.getSendContextHash=ke.getConvertBackContextHash=ke.getConvertContextHash=ke.subtractCiphertexts=ke.addCiphertexts=ke.getPedersenCommitment=ke.decryptAmount=ke.encryptAmount=ke.generateBlindingFactor=ke.loadWasmModule=ke.hexToBytes=ke.bytesToHex=ke.SEND_PROOF_SIZE=ke.CONVERT_BACK_PROOF_SIZE=ke.CLAWBACK_PROOF_SIZE=ke.CONVERT_PROOF_SIZE=ke.ISSUANCE_ID_SIZE=ke.ACCOUNT_ID_SIZE=ke.CONTEXT_HASH_SIZE=ke.PEDERSEN_COMMIT_SIZE=ke.ELGAMAL_TOTAL_SIZE=ke.BLINDING_FACTOR_SIZE=ke.PRIVKEY_SIZE=ke.PUBKEY_SIZE=void 0;var Ni=ac();Object.defineProperty(ke,"PUBKEY_SIZE",{enumerable:!0,get:function(){return Ni.PUBKEY_SIZE}});Object.defineProperty(ke,"PRIVKEY_SIZE",{enumerable:!0,get:function(){return Ni.PRIVKEY_SIZE}});Object.defineProperty(ke,"BLINDING_FACTOR_SIZE",{enumerable:!0,get:function(){return Ni.BLINDING_FACTOR_SIZE}});Object.defineProperty(ke,"ELGAMAL_TOTAL_SIZE",{enumerable:!0,get:function(){return Ni.ELGAMAL_TOTAL_SIZE}});Object.defineProperty(ke,"PEDERSEN_COMMIT_SIZE",{enumerable:!0,get:function(){return Ni.PEDERSEN_COMMIT_SIZE}});Object.defineProperty(ke,"CONTEXT_HASH_SIZE",{enumerable:!0,get:function(){return Ni.CONTEXT_HASH_SIZE}});Object.defineProperty(ke,"ACCOUNT_ID_SIZE",{enumerable:!0,get:function(){return Ni.ACCOUNT_ID_SIZE}});Object.defineProperty(ke,"ISSUANCE_ID_SIZE",{enumerable:!0,get:function(){return Ni.ISSUANCE_ID_SIZE}});Object.defineProperty(ke,"CONVERT_PROOF_SIZE",{enumerable:!0,get:function(){return Ni.CONVERT_PROOF_SIZE}});Object.defineProperty(ke,"CLAWBACK_PROOF_SIZE",{enumerable:!0,get:function(){return Ni.CLAWBACK_PROOF_SIZE}});Object.defineProperty(ke,"CONVERT_BACK_PROOF_SIZE",{enumerable:!0,get:function(){return Ni.CONVERT_BACK_PROOF_SIZE}});Object.defineProperty(ke,"SEND_PROOF_SIZE",{enumerable:!0,get:function(){return Ni.SEND_PROOF_SIZE}});var nO=Ml();Object.defineProperty(ke,"bytesToHex",{enumerable:!0,get:function(){return nO.bytesToHex}});Object.defineProperty(ke,"hexToBytes",{enumerable:!0,get:function(){return nO.hexToBytes}});var fae=aT();Object.defineProperty(ke,"loadWasmModule",{enumerable:!0,get:function(){return fae.loadWasmModule}});var ab=ZM();Object.defineProperty(ke,"generateBlindingFactor",{enumerable:!0,get:function(){return ab.generateBlindingFactor}});Object.defineProperty(ke,"encryptAmount",{enumerable:!0,get:function(){return ab.encryptAmount}});Object.defineProperty(ke,"decryptAmount",{enumerable:!0,get:function(){return ab.decryptAmount}});Object.defineProperty(ke,"getPedersenCommitment",{enumerable:!0,get:function(){return ab.getPedersenCommitment}});var rO=QM();Object.defineProperty(ke,"addCiphertexts",{enumerable:!0,get:function(){return rO.addCiphertexts}});Object.defineProperty(ke,"subtractCiphertexts",{enumerable:!0,get:function(){return rO.subtractCiphertexts}});var sb=eO();Object.defineProperty(ke,"getConvertContextHash",{enumerable:!0,get:function(){return sb.getConvertContextHash}});Object.defineProperty(ke,"getConvertBackContextHash",{enumerable:!0,get:function(){return sb.getConvertBackContextHash}});Object.defineProperty(ke,"getSendContextHash",{enumerable:!0,get:function(){return sb.getSendContextHash}});Object.defineProperty(ke,"getClawbackContextHash",{enumerable:!0,get:function(){return sb.getClawbackContextHash}});var cb=tO();Object.defineProperty(ke,"getConvertProof",{enumerable:!0,get:function(){return cb.getConvertProof}});Object.defineProperty(ke,"getClawbackProof",{enumerable:!0,get:function(){return cb.getClawbackProof}});Object.defineProperty(ke,"getConvertBackProof",{enumerable:!0,get:function(){return cb.getConvertBackProof}});Object.defineProperty(ke,"getConfidentialSendProof",{enumerable:!0,get:function(){return cb.getConfidentialSendProof}})});var of=q(Li=>{"use strict";y();var pae=Li&&Li.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),yae=Li&&Li.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),hae=Li&&Li.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&pae(t,e,n);return yae(t,e),t},mae=Li&&Li.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(Li,"__esModule",{value:!0});Li.loadMptCrypto=void 0;var gae=fe(),rf;function wae(){return mae(this,void 0,void 0,function*(){return rf??(rf=Promise.resolve().then(()=>hae(iO())).catch(e=>{throw rf=void 0,new gae.XrplError('Failed to load the "@xrplf/mpt-crypto" module required for Confidential MPT operations.',e)})),rf})}Li.loadMptCrypto=wae});var sO=q(af=>{"use strict";y();var bae=af&&af.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(af,"__esModule",{value:!0});af.deriveConfidentialKeypair=void 0;var oO=_i(),aO=bae(Hy());function Cae(e){let t=e??(0,oO.generateSeed)({algorithm:aO.default.secp256k1}),{publicKey:n,privateKey:r}=(0,oO.deriveKeypair)(t,{algorithm:aO.default.secp256k1});return{publicKey:n,privateKey:r.slice(2)}}af.deriveConfidentialKeypair=Cae});var Ch=q(Ut=>{"use strict";y();var sf=Ut&&Ut.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.resolveSpendingState=Ut.requireIssuerKey=Ut.getConfidentialBalance=Ut.decryptBound=Ut.fetchMPTokenIssuance=Ut.fetchMPToken=Ut.resolveLedgerIndex=Ut.resolveSequence=Ut.getAccountSequence=Ut.accountIdHex=Ut.assertConfidentialAmount=void 0;var vae=We(),Aae=lr(),lT=fe(),cO=de(),Sae=of();function Tae(e,t){if(ecO.MAX_MPT_AMOUNT||!t&&e===BigInt(0)){let n=t?"0":"1";throw new lT.XrplError(`Confidential MPT amount out of range [${n}, ${cO.MAX_MPT_AMOUNT.toString()}]: ${e.toString()}`)}}Ut.assertConfidentialAmount=Tae;function Eae(e){return(0,vae.bytesToHex)((0,Aae.decodeAccountID)(e))}Ut.accountIdHex=Eae;function lO(e,t){return sf(this,void 0,void 0,function*(){return(yield e.request({command:"account_info",account:t})).result.account_data.Sequence})}Ut.getAccountSequence=lO;function kae(e,t,n){return sf(this,void 0,void 0,function*(){return n??(yield lO(e,t))})}Ut.resolveSequence=kae;function _ae(e,t){return sf(this,void 0,void 0,function*(){return t??(yield e.getLedgerIndex())})}Ut.resolveLedgerIndex=_ae;function uO(e,t,n,r){return sf(this,void 0,void 0,function*(){return(yield e.request({command:"ledger_entry",mptoken:{mpt_issuance_id:n,account:t},ledger_index:r})).result.node})}Ut.fetchMPToken=uO;function dO(e,t,n){return sf(this,void 0,void 0,function*(){return(yield e.request({command:"ledger_entry",mpt_issuance:t,ledger_index:n})).result.node})}Ut.fetchMPTokenIssuance=dO;function fO(e,t=BigInt(0)){var n;return BigInt((n=e.ConfidentialOutstandingAmount)!==null&&n!==void 0?n:0)+t}Ut.decryptBound=fO;function Iae(e,t,n,r){return sf(this,void 0,void 0,function*(){let i=yield e.getLedgerIndex(),o=yield uO(e,t,n,i);if(o.ConfidentialBalanceSpending==null)return BigInt(0);let[a,s]=yield Promise.all([dO(e,n,i),(0,Sae.loadMptCrypto)()]);return s.decryptAmount(o.ConfidentialBalanceSpending,r,fO(a))})}Ut.getConfidentialBalance=Iae;function Pae(e,t){if(e.IssuerEncryptionKey==null)throw new lT.XrplError(`Issuance ${t} has no registered IssuerEncryptionKey`);return e.IssuerEncryptionKey}Ut.requireIssuerKey=Pae;function xae(e,t,n){var r,i,o;let a=(r=n?.spending)!==null&&r!==void 0?r:e.ConfidentialBalanceSpending;if(a==null)throw new lT.XrplError(`Account ${t} has no confidential spending balance`);return{spending:a,version:(o=(i=n?.version)!==null&&i!==void 0?i:e.ConfidentialBalanceVersion)!==null&&o!==void 0?o:0}}Ut.resolveSpendingState=xae});var dT=q(ta=>{"use strict";y();var uT=ta&&ta.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(ta,"__esModule",{value:!0});ta.prepareConfidentialMergeInbox=ta.prepareConfidentialConvertBack=ta.prepareConfidentialConvert=void 0;var Wn=Ch(),pO=of();function Mae(e,t){var n;return uT(this,void 0,void 0,function*(){(0,Wn.assertConfidentialAmount)(t.amount,!0);let[r,i]=yield Promise.all([(0,pO.loadMptCrypto)(),(0,Wn.resolveLedgerIndex)(e,t.ledgerIndex)]),[o,a,s]=yield Promise.all([(0,Wn.fetchMPTokenIssuance)(e,t.mptIssuanceID,i),(0,Wn.fetchMPToken)(e,t.account,t.mptIssuanceID,i),(0,Wn.resolveSequence)(e,t.account,t.sequence)]),c=(0,Wn.requireIssuerKey)(o,t.mptIssuanceID),{amount:l,holderKeypair:u}=t,d=(n=t.registerKey)!==null&&n!==void 0?n:a.HolderEncryptionKey==null,p=yield r.generateBlindingFactor(),[h,g]=yield Promise.all([r.encryptAmount(l,u.publicKey,p),r.encryptAmount(l,c,p)]),w={TransactionType:"ConfidentialMPTConvert",Account:t.account,Sequence:s,MPTokenIssuanceID:t.mptIssuanceID,MPTAmount:l.toString(),HolderEncryptedAmount:h,IssuerEncryptedAmount:g,BlindingFactor:p};if(o.AuditorEncryptionKey!=null&&(w.AuditorEncryptedAmount=yield r.encryptAmount(l,o.AuditorEncryptionKey,p)),d){let T=yield r.getConvertContextHash((0,Wn.accountIdHex)(t.account),t.mptIssuanceID,s);w.HolderEncryptionKey=u.publicKey,w.ZKProof=yield r.getConvertProof(u.publicKey,u.privateKey,T)}return w})}ta.prepareConfidentialConvert=Mae;function Oae(e,t){return uT(this,void 0,void 0,function*(){(0,Wn.assertConfidentialAmount)(t.amount,!1);let[n,r]=yield Promise.all([(0,pO.loadMptCrypto)(),(0,Wn.resolveLedgerIndex)(e,t.ledgerIndex)]),[i,o,a]=yield Promise.all([(0,Wn.fetchMPTokenIssuance)(e,t.mptIssuanceID,r),(0,Wn.fetchMPToken)(e,t.account,t.mptIssuanceID,r),(0,Wn.resolveSequence)(e,t.account,t.sequence)]),s=(0,Wn.requireIssuerKey)(i,t.mptIssuanceID),{amount:c,holderKeypair:l}=t,{spending:u,version:d}=(0,Wn.resolveSpendingState)(o,t.account,t.confidentialState),[p,h,g,w]=yield Promise.all([n.decryptAmount(u,l.privateKey,(0,Wn.decryptBound)(i,t.outstandingDelta)),n.generateBlindingFactor(),n.generateBlindingFactor(),n.getConvertBackContextHash((0,Wn.accountIdHex)(t.account),t.mptIssuanceID,a,d)]),T=yield n.getPedersenCommitment(p,g),[k,B,D]=yield Promise.all([n.encryptAmount(c,l.publicKey,h),n.encryptAmount(c,s,h),n.getConvertBackProof(l.privateKey,l.publicKey,w,c,{commitment:T,amount:p,ciphertext:u,blindingFactor:g})]),P={TransactionType:"ConfidentialMPTConvertBack",Account:t.account,Sequence:a,MPTokenIssuanceID:t.mptIssuanceID,MPTAmount:c.toString(),HolderEncryptedAmount:k,IssuerEncryptedAmount:B,BlindingFactor:h,BalanceCommitment:T,ZKProof:D};return i.AuditorEncryptionKey!=null&&(P.AuditorEncryptedAmount=yield n.encryptAmount(c,i.AuditorEncryptionKey,h)),P})}ta.prepareConfidentialConvertBack=Oae;function Dae(e,t){return uT(this,void 0,void 0,function*(){return{TransactionType:"ConfidentialMPTMergeInbox",Account:t.account,Sequence:yield(0,Wn.resolveSequence)(e,t.account,t.sequence),MPTokenIssuanceID:t.mptIssuanceID}})}ta.prepareConfidentialMergeInbox=Dae});var fT=q(cc=>{"use strict";y();var yO=cc&&cc.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(cc,"__esModule",{value:!0});cc.prepareConfidentialClawback=cc.prepareConfidentialSend=void 0;var hO=fe(),Mn=Ch(),mO=of();function Rae(e,t){var n;return yO(this,void 0,void 0,function*(){(0,Mn.assertConfidentialAmount)(t.amount,!0);let[r,i]=yield Promise.all([(0,mO.loadMptCrypto)(),(0,Mn.resolveLedgerIndex)(e,t.ledgerIndex)]),[o,a,s,c]=yield Promise.all([(0,Mn.fetchMPTokenIssuance)(e,t.mptIssuanceID,i),(0,Mn.fetchMPToken)(e,t.account,t.mptIssuanceID,i),(0,Mn.fetchMPToken)(e,t.destination,t.mptIssuanceID,i),(0,Mn.resolveSequence)(e,t.account,t.sequence)]),l=(0,Mn.requireIssuerKey)(o,t.mptIssuanceID),{amount:u,senderKeypair:d}=t,p=(n=t.destinationKey)!==null&&n!==void 0?n:s.HolderEncryptionKey;if(p==null)throw new hO.XrplError(`Destination ${t.destination} has no registered HolderEncryptionKey`);let{spending:h,version:g}=(0,Mn.resolveSpendingState)(a,t.account,t.confidentialState),[w,T,k,B]=yield Promise.all([r.decryptAmount(h,d.privateKey,(0,Mn.decryptBound)(o,t.outstandingDelta)),r.generateBlindingFactor(),r.generateBlindingFactor(),r.getSendContextHash((0,Mn.accountIdHex)(t.account),t.mptIssuanceID,c,(0,Mn.accountIdHex)(t.destination),g)]),[D,P,U,F,H]=yield Promise.all([r.getPedersenCommitment(u,T),r.getPedersenCommitment(w,k),r.encryptAmount(u,d.publicKey,T),r.encryptAmount(u,p,T),r.encryptAmount(u,l,T)]),b=[{publicKey:d.publicKey,ciphertext:U},{publicKey:p,ciphertext:F},{publicKey:l,ciphertext:H}],C;o.AuditorEncryptionKey!=null&&(C=yield r.encryptAmount(u,o.AuditorEncryptionKey,T),b.push({publicKey:o.AuditorEncryptionKey,ciphertext:C}));let v={TransactionType:"ConfidentialMPTSend",Account:t.account,Sequence:c,MPTokenIssuanceID:t.mptIssuanceID,Destination:t.destination,SenderEncryptedAmount:U,DestinationEncryptedAmount:F,IssuerEncryptedAmount:H,AmountCommitment:D,BalanceCommitment:P,ZKProof:yield r.getConfidentialSendProof({privateKey:d.privateKey,publicKey:d.publicKey,amount:u,participants:b,txBlindingFactor:T,contextHash:B,amountCommitment:D,balanceParams:{commitment:P,amount:w,ciphertext:h,blindingFactor:k}})};return C!=null&&(v.AuditorEncryptedAmount=C),t.destinationTag!=null&&(v.DestinationTag=t.destinationTag),t.credentialIDs!=null&&(v.CredentialIDs=t.credentialIDs),v})}cc.prepareConfidentialSend=Rae;function Nae(e,t){var n,r;return yO(this,void 0,void 0,function*(){t.amount!=null&&(0,Mn.assertConfidentialAmount)(t.amount,!1);let[i,o]=yield Promise.all([(0,mO.loadMptCrypto)(),(0,Mn.resolveLedgerIndex)(e,t.ledgerIndex)]),[a,s]=yield Promise.all([(0,Mn.fetchMPToken)(e,t.holder,t.mptIssuanceID,o),(0,Mn.resolveSequence)(e,t.account,t.sequence)]),{issuerKeypair:c}=t,l=(n=t.issuerEncryptedBalanceOverride)!==null&&n!==void 0?n:a.IssuerEncryptedBalance;if(l==null)throw new hO.XrplError(`Holder ${t.holder} has no issuer-encrypted confidential balance`);let u=(r=t.amount)!==null&&r!==void 0?r:yield i.decryptAmount(l,c.privateKey,(0,Mn.decryptBound)(yield(0,Mn.fetchMPTokenIssuance)(e,t.mptIssuanceID,o),t.outstandingDelta)),d=yield i.getClawbackContextHash((0,Mn.accountIdHex)(t.account),t.mptIssuanceID,s,(0,Mn.accountIdHex)(t.holder));return{TransactionType:"ConfidentialMPTClawback",Account:t.account,Sequence:s,MPTokenIssuanceID:t.mptIssuanceID,Holder:t.holder,MPTAmount:u.toString(),ZKProof:yield i.getClawbackProof(c.privateKey,c.publicKey,d,u,l)}})}cc.prepareConfidentialClawback=Nae});var SO=q(lc=>{"use strict";y();var ci=lc&&lc.__awaiter||function(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(u){try{l(r.next(u))}catch(d){a(d)}}function c(u){try{l(r.throw(u))}catch(d){a(d)}}function l(u){u.done?o(u.value):i(u.value).then(s,c)}l((r=r.apply(e,t||[])).next())})},vh=lc&&lc.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);ici(this,void 0,void 0,function*(){var o;let[a,s]=i.split(":"),c=yield(0,lb.fetchMPToken)(e,a,s,n);r.set(i,{spending:c.ConfidentialBalanceSpending,inbox:c.ConfidentialBalanceInbox,issuerEnc:c.IssuerEncryptedBalance,auditorEnc:c.AuditorEncryptedBalance,version:(o=c.ConfidentialBalanceVersion)!==null&&o!==void 0?o:0,holderKey:c.HolderEncryptionKey})}))),r})}function zae(e,t,n){return ci(this,void 0,void 0,function*(){let r=new Set([t]);for(let s of n)r.add(AO(s));let i=new Map;yield Promise.all(Array.from(r,s=>ci(this,void 0,void 0,function*(){i.set(s,yield(0,lb.getAccountSequence)(e,s))})));let o=na(i,t,"batch account sequence"),a=new Map;for(let s of r){let c=na(i,s,"account sequence");a.set(s,s===t?c+1:c)}return{outerSequence:o,next:a}})}function CO(e,t){let n=na(e,t,`sequence for ${t}`);return e.set(t,n+1),n}function jae(e){var t;let n=new Map;for(let r of e)if(r.operation==="convert"){let i=(t=n.get(r.mptIssuanceID))!==null&&t!==void 0?t:BigInt(0);n.set(r.mptIssuanceID,i+r.amount)}return n}function vO(e,t,n){return ci(this,void 0,void 0,function*(){let r=yield e.subtractCiphertexts(Bi(t.spending,"spending balance"),n.spend),i=yield e.subtractCiphertexts(Bi(t.issuerEnc,"issuer-encrypted balance"),n.issuer),o=n.auditor==null?t.auditorEnc:yield e.subtractCiphertexts(Bi(t.auditorEnc,"auditor-encrypted balance"),n.auditor);return Object.assign(Object.assign({},t),{spending:r,issuerEnc:i,auditorEnc:o,version:t.version+1})})}function Xae(e,t,n){return ci(this,void 0,void 0,function*(){let r=t.inbox==null?n.inbox:yield e.addCiphertexts(t.inbox,n.inbox),i=t.issuerEnc==null?n.issuer:yield e.addCiphertexts(t.issuerEnc,n.issuer),{auditorEnc:o}=t;return n.auditor!=null&&(o=o==null?n.auditor:yield e.addCiphertexts(o,n.auditor)),Object.assign(Object.assign({},t),{inbox:r,issuerEnc:i,auditorEnc:o})})}function Wae(e,t){return ci(this,void 0,void 0,function*(){let n=yield e.addCiphertexts(Bi(t.spending,"spending balance"),Bi(t.inbox,"inbox balance"));return Object.assign(Object.assign({},t),{spending:n,inbox:void 0,version:t.version+1})})}function Gae(e){return Object.assign(Object.assign({},e),{spending:void 0,inbox:void 0,issuerEnc:void 0,auditorEnc:void 0,version:e.version+1})}function Yae(e,t,n){return ci(this,void 0,void 0,function*(){let{tx:r,issuerKey:i,auditorKey:o}=n,a=r.ZKProof.slice(0,Hae);function s(p,h){return ci(this,void 0,void 0,function*(){return e.addCiphertexts(p,yield e.encryptAmount(BigInt(0),h,a))})}let c=Bi(t.holderKey,"destination holder key"),l=yield e.addCiphertexts(Bi(t.inbox,"destination inbox balance"),yield s(r.DestinationEncryptedAmount,c)),u=yield e.addCiphertexts(Bi(t.issuerEnc,"destination issuer-encrypted balance"),yield s(r.IssuerEncryptedAmount,i)),{auditorEnc:d}=t;return r.AuditorEncryptedAmount!=null&&o!=null&&(d=yield e.addCiphertexts(Bi(d,"destination auditor-encrypted balance"),yield s(r.AuditorEncryptedAmount,o))),Object.assign(Object.assign({},t),{inbox:l,issuerEnc:u,auditorEnc:d})})}function Zae(e,t,n){return ci(this,void 0,void 0,function*(){let r=new Set;for(let o of t)o.operation==="send"&&r.add(o.mptIssuanceID);let i=new Map;return yield Promise.all(Array.from(r,o=>ci(this,void 0,void 0,function*(){let a=yield(0,lb.fetchMPTokenIssuance)(e,o,n);i.set(o,{issuerKey:(0,lb.requireIssuerKey)(a,o),auditorKey:a.AuditorEncryptionKey})}))),i})}function Jae(e,t,n){var r;return ci(this,void 0,void 0,function*(){let{client:i,crypto:o,states:a,convertTotals:s,issuerKeys:c,ledgerIndex:l}=e;switch(t.operation){case"send":{let{operation:u}=t,d=vh(t,["operation"]),p=Ga(t.account,t.mptIssuanceID),h=na(a,p,`state for ${p}`),g=Ga(t.destination,t.mptIssuanceID),w=na(a,g,`state for ${g}`),{issuerKey:T,auditorKey:k}=na(c,t.mptIssuanceID,`issuer keys for ${t.mptIssuanceID}`),B=yield(0,gO.prepareConfidentialSend)(i,Object.assign(Object.assign({},d),{sequence:n,ledgerIndex:l,confidentialState:{spending:Bi(h.spending,`${t.account} spending`),version:h.version},destinationKey:w.holderKey,outstandingDelta:s.get(t.mptIssuanceID)})),D={spend:B.SenderEncryptedAmount,issuer:B.IssuerEncryptedAmount,auditor:B.AuditorEncryptedAmount};return{tx:Ol(B),updates:[[p,yield vO(o,h,D)],[g,yield Yae(o,w,{tx:B,issuerKey:T,auditorKey:k})]]}}case"convertBack":{let{operation:u}=t,d=vh(t,["operation"]),p=Ga(t.account,t.mptIssuanceID),h=na(a,p,`state for ${p}`),g=yield(0,pT.prepareConfidentialConvertBack)(i,Object.assign(Object.assign({},d),{sequence:n,ledgerIndex:l,confidentialState:{spending:Bi(h.spending,`${t.account} spending`),version:h.version},outstandingDelta:s.get(t.mptIssuanceID)})),w={spend:g.HolderEncryptedAmount,issuer:g.IssuerEncryptedAmount,auditor:g.AuditorEncryptedAmount};return{tx:Ol(g),updates:[[p,yield vO(o,h,w)]]}}case"convert":{let{operation:u}=t,d=vh(t,["operation"]),p=Ga(t.account,t.mptIssuanceID),h=na(a,p,`state for ${p}`),g=yield(0,pT.prepareConfidentialConvert)(i,Object.assign(Object.assign({},d),{sequence:n,ledgerIndex:l,registerKey:(r=t.registerKey)!==null&&r!==void 0?r:h.holderKey==null})),w={inbox:g.HolderEncryptedAmount,issuer:g.IssuerEncryptedAmount,auditor:g.AuditorEncryptedAmount},T=yield Xae(o,h,w);return{tx:Ol(g),updates:[[p,Object.assign(Object.assign({},T),{holderKey:t.holderKeypair.publicKey})]]}}case"mergeInbox":{let{operation:u}=t,d=vh(t,["operation"]),p=Ga(t.account,t.mptIssuanceID),h=na(a,p,`state for ${p}`),g=yield(0,pT.prepareConfidentialMergeInbox)(i,Object.assign(Object.assign({},d),{sequence:n}));return{tx:Ol(g),updates:[[p,yield Wae(o,h)]]}}case"clawback":{let{operation:u}=t,d=vh(t,["operation"]),p=Ga(t.holder,t.mptIssuanceID),h=na(a,p,`state for ${p}`),g=yield(0,gO.prepareConfidentialClawback)(i,Object.assign(Object.assign({},d),{sequence:n,ledgerIndex:l,issuerEncryptedBalanceOverride:Bi(h.issuerEnc,`${t.holder} issuer-encrypted balance`),outstandingDelta:s.get(t.mptIssuanceID)}));return{tx:Ol(g),updates:[[p,Gae(h)]]}}default:throw new ub.XrplError("prepareConfidentialBatch: unrecognized confidential op")}})}function Qae(e,t){return ci(this,void 0,void 0,function*(){let{account:n,inners:r,batchFlags:i,signersCount:o,sponsorSignersCount:a}=t;if(r.lengthbO)throw new ub.XrplError(`prepareConfidentialBatch: a Batch requires between ${wO} and ${bO} inner transactions, got ${r.length}`);let s=r.filter(yT),c=yield e.getLedgerIndex(),[l,u,d,p]=yield Promise.all([(0,Uae.loadMptCrypto)(),Kae(e,s,c),zae(e,n,r),Zae(e,s,c)]),h={client:e,crypto:l,states:u,convertTotals:jae(s),issuerKeys:p,ledgerIndex:c},g=[];for(let T of r){let k=AO(T);if(yT(T)){let B=CO(d.next,k),D=yield Jae(h,T,B);for(let[P,U]of D.updates)u.set(P,U);g.push({RawTransaction:D.tx})}else if(T.Sequence==null&&T.TicketSequence==null){let B=CO(d.next,k);g.push({RawTransaction:Ol(Object.assign(Object.assign({},T),{Sequence:B}))})}else g.push({RawTransaction:Ol(T)})}let w={TransactionType:"Batch",Account:n,Sequence:d.outerSequence,Flags:i??qae,RawTransactions:g};return e.autofill(w,o,a)})}lc.prepareConfidentialBatch=Qae});var EO=q(It=>{"use strict";y();Object.defineProperty(It,"__esModule",{value:!0});It.prepareConfidentialBatch=It.prepareConfidentialSend=It.prepareConfidentialClawback=It.prepareConfidentialMergeInbox=It.prepareConfidentialConvertBack=It.prepareConfidentialConvert=It.getConfidentialBalance=It.getAccountSequence=It.fetchMPTokenIssuance=It.fetchMPToken=It.accountIdHex=It.deriveConfidentialKeypair=It.loadMptCrypto=void 0;var ese=of();Object.defineProperty(It,"loadMptCrypto",{enumerable:!0,get:function(){return ese.loadMptCrypto}});var tse=sO();Object.defineProperty(It,"deriveConfidentialKeypair",{enumerable:!0,get:function(){return tse.deriveConfidentialKeypair}});var Ah=Ch();Object.defineProperty(It,"accountIdHex",{enumerable:!0,get:function(){return Ah.accountIdHex}});Object.defineProperty(It,"fetchMPToken",{enumerable:!0,get:function(){return Ah.fetchMPToken}});Object.defineProperty(It,"fetchMPTokenIssuance",{enumerable:!0,get:function(){return Ah.fetchMPTokenIssuance}});Object.defineProperty(It,"getAccountSequence",{enumerable:!0,get:function(){return Ah.getAccountSequence}});Object.defineProperty(It,"getConfidentialBalance",{enumerable:!0,get:function(){return Ah.getConfidentialBalance}});var hT=dT();Object.defineProperty(It,"prepareConfidentialConvert",{enumerable:!0,get:function(){return hT.prepareConfidentialConvert}});Object.defineProperty(It,"prepareConfidentialConvertBack",{enumerable:!0,get:function(){return hT.prepareConfidentialConvertBack}});Object.defineProperty(It,"prepareConfidentialMergeInbox",{enumerable:!0,get:function(){return hT.prepareConfidentialMergeInbox}});var TO=fT();Object.defineProperty(It,"prepareConfidentialClawback",{enumerable:!0,get:function(){return TO.prepareConfidentialClawback}});Object.defineProperty(It,"prepareConfidentialSend",{enumerable:!0,get:function(){return TO.prepareConfidentialSend}});var nse=SO();Object.defineProperty(It,"prepareConfidentialBatch",{enumerable:!0,get:function(){return nse.prepareConfidentialBatch}})});var Nr=q(zt=>{"use strict";y();var rse=zt&&zt.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Sh=zt&&zt.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&rse(t,e,n)},ise=zt&&zt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zt,"__esModule",{value:!0});zt.rfc1751MnemonicToKey=zt.keyToRFC1751Mnemonic=zt.walletFromSecretNumbers=zt.ECDSA=zt.validateSponsorship=zt.Client=void 0;var ose=BM();Object.defineProperty(zt,"Client",{enumerable:!0,get:function(){return ose.Client}});Sh(Zy(),zt);Sh(Ny(),zt);var ase=N3();Object.defineProperty(zt,"validateSponsorship",{enumerable:!0,get:function(){return ase.validateSponsorship}});var sse=Hy();Object.defineProperty(zt,"ECDSA",{enumerable:!0,get:function(){return ise(sse).default}});Sh(fe(),zt);Sh(nh(),zt);var cse=jM();Object.defineProperty(zt,"walletFromSecretNumbers",{enumerable:!0,get:function(){return cse.walletFromSecretNumbers}});var kO=fS();Object.defineProperty(zt,"keyToRFC1751Mnemonic",{enumerable:!0,get:function(){return kO.keyToRFC1751Mnemonic}});Object.defineProperty(zt,"rfc1751MnemonicToKey",{enumerable:!0,get:function(){return kO.rfc1751MnemonicToKey}});Sh(EO(),zt)});var _O={};Tr(_O,{XRPL_ENDPOINTS:()=>vo,fetchAccountSummary:()=>use,fetchAccountTransactions:()=>dse,fetchGatewayBalances:()=>fse,fetchIncomingPayments:()=>lse,fetchLedgerTx:()=>Th,hexToUtf8:()=>mT,normalizeTx:()=>Dl});function Dl(e,t,n){let r=e.tx_json??e,i=e.meta??e.metaData,o=i?.delivered_amount??i?.DeliveredAmount,a=(r.Memos??[]).map(c=>({type:mT(c.Memo?.MemoType??""),data:mT(c.Memo?.MemoData??"")})),s=r.date??e.close_time_iso??e.date;return{hash:String(e.hash??r.hash??""),network:t,validated:e.validated===!0,result:String(i?.TransactionResult??""),ledgerIndex:typeof e.ledger_index=="number"?e.ledger_index:typeof r.ledger_index=="number"?r.ledger_index:null,type:String(r.TransactionType??""),account:String(r.Account??""),destination:typeof r.Destination=="string"?r.Destination:null,deliveredDrops:typeof o=="string"?o:null,deliveredIssued:o&&typeof o=="object"&&"issuer"in o?{currency:String(o.currency),issuer:String(o.issuer),value:String(o.value)}:null,destinationTag:typeof r.DestinationTag=="number"?r.DestinationTag:null,fields:r,memos:a,closeTime:typeof s=="number"?new Date((s+946684800)*1e3).toISOString():typeof s=="string"?s:null,checkedAt:n,meta:i??null}}async function Th(e,t){if(!/^[0-9A-Fa-f]{64}$/.test(t))throw new Error("An XRPL transaction hash is 64 hex characters.");let n=new cf.Client(vo[e]);await n.connect();try{let r=await n.request({command:"tx",transaction:t});return Dl(r.result,e,new Date().toISOString())}catch(r){let i=r;throw new Error(i.data?.error==="txnNotFound"?"Transaction not found on this network.":`XRPL lookup failed: ${i.message??"unknown error"}`)}finally{await n.disconnect().catch(()=>{})}}async function lse(e,t,n=50){let r=new cf.Client(vo[e]);await r.connect();try{let i=await r.request({command:"account_tx",account:t,limit:n,forward:!1}),o=new Date().toISOString();return(i.result.transactions??[]).map(a=>{let s=a.tx_json??a.tx??{};return Dl({...a,tx_json:s,hash:a.hash??s.hash},e,o)}).filter(a=>a.type==="Payment"&&a.destination===t)}catch(i){let o=i;throw new Error(o.data?.error==="actNotFound"?"This account is not activated on this network yet.":`XRPL lookup failed: ${o.message??"unknown error"}`)}finally{await r.disconnect().catch(()=>{})}}async function use(e,t){let n=new cf.Client(vo[e]);await n.connect();try{let r;try{r=await n.request({command:"account_info",account:t,ledger_index:"validated"})}catch(o){if(o.data?.error==="actNotFound")return{activated:!1,xrpDrops:null,lines:[]};throw o}let i=await n.request({command:"account_lines",account:t,ledger_index:"validated"});return{activated:!0,xrpDrops:r.result.account_data?.Balance??null,lines:(i.result.lines??[]).map(o=>({currency:o.currency,issuer:o.account,balance:o.balance}))}}finally{await n.disconnect().catch(()=>{})}}async function dse(e,t,n=1e3){let r=new cf.Client(vo[e]);await r.connect();try{let i=[],o,a=new Date().toISOString();do{let s;try{s=await r.request({command:"account_tx",account:t,limit:Math.min(200,n-i.length),forward:!1,ledger_index_min:-1,ledger_index_max:-1,...o?{marker:o}:{}})}catch(c){if(c.data?.error==="actNotFound")return{txs:[],truncated:!1,activated:!1};throw c}for(let c of s.result.transactions??[]){if(c.validated===!1)continue;let l=c.tx_json??c.tx??{};i.push(Dl({...c,tx_json:l,hash:c.hash??l.hash,validated:c.validated??!0,ledger_index:c.ledger_index??l.ledger_index},e,a))}o=s.result.marker}while(o&&i.length{})}}async function fse(e,t,n=[]){let r=new cf.Client(vo[e]);await r.connect();try{let i=await r.request({command:"gateway_balances",account:t,ledger_index:"validated",strict:!0,...n.length?{hotwallet:n}:{}});return{activated:!0,obligations:i.result.obligations??{},hotBalances:i.result.balances??{}}}catch(i){if(i.data?.error==="actNotFound")return{activated:!1,obligations:{},hotBalances:{}};throw i}finally{await r.disconnect().catch(()=>{})}}var cf,vo,mT,Rl=Te(()=>{"use strict";y();cf=jr(Nr(),1),vo={mainnet:"wss://xrplcluster.com",testnet:"wss://s.altnet.rippletest.net:51233",devnet:"wss://s.devnet.rippletest.net:51233"},mT=e=>{if(!/^(?:[0-9a-fA-F]{2})*$/.test(e))return"";let t=new Uint8Array(e.length/2);for(let n=0;n{"use strict";y();hse="m/44'/144'",On={HEAVEN:0,VOID:1,FALLEN:2,TIMELINE:3,ISO20022:20,FPML:21,FIX:22,AL3:23,HL7:24,CUSTOM:25,CALENDARING:26,IP:30,ARCHITECTURE:40,BUILD_LOG:41,CAPPZ_OVERVIEW:42,METATRON:43,LEGACY_V5_ARCHIVE:50,REPOZ:100,UNASSIGNED:99};Un={HEAVEN:Dn(On.HEAVEN),VOID:Dn(On.VOID),FALLEN:Dn(On.FALLEN),TIMELINE:Dn(On.TIMELINE),ISO20022:Dn(On.ISO20022),FPML:Dn(On.FPML),FIX:Dn(On.FIX),AL3:Dn(On.AL3),HL7:Dn(On.HL7),CUSTOM:Dn(On.CUSTOM),CALENDARING:Dn(On.CALENDARING),IP:Dn(On.IP),ARCHITECTURE:Dn(On.ARCHITECTURE),BUILD_LOG:Dn(On.BUILD_LOG),CAPPZ_OVERVIEW:Dn(On.CAPPZ_OVERVIEW),METATRON:Dn(On.METATRON),LEGACY_V5_ARCHIVE:Dn(On.LEGACY_V5_ARCHIVE),REPOZ:Dn(On.REPOZ),UNASSIGNED:Dn(On.UNASSIGNED)},Kve={FpML:Un.FPML,ISO20022:Un.ISO20022,FIX:Un.FIX,AL3:Un.AL3,HL7:Un.HL7,Custom:Un.CUSTOM,MDM:Un.HEAVEN};zve={ROOT:df(),USERS:df("Users"),ROLES:df("Roles"),BPMN:df("BPMN"),ROLE_ADMIN:df("Roles","Admin"),ROLE_CODEX_STEWARD:df("Roles","CodexSteward")},CT=uc("templates"),jve={BUILD:`${CT}/build`,RBAC:`${CT}/rbac`},mse=uc("operational");UO="notarizer",Xve=uc("templates",UO),Wve=yb(UO),gse="replicator",wse=yb(gse),Gve=`${wse}/sync-market/arbiter`,Yve=Un.HEAVEN;$O="cappz-user";bT=uc("WalletAgent"),Zve={SANDBOX:`${bT}/OperationalStatus/Sandbox`,OPERATIONAL:`${bT}/OperationalStatus/Operational`,HIBERNATED:`${bT}/OperationalStatus/Hibernated`},kh=_h("sync-on-async"),Jve={SESSION_TIMEOUT:`${kh}/session-timeout`,MAX_POLL_WAIT:`${kh}/max-poll-wait`,POLL_INTERVAL:`${kh}/poll-interval`,ENVELOPE_STORE:`${kh}/envelope-store`,ENVELOPE_TTL:`${kh}/envelope-ttl`},HO=_h("chainlet-store"),VO=_h("event-types"),Qve=AT("middleware"),KO=AT("wallet-ops","migration-status"),e2e=AT("mdm-standards-ingest"),t2e=`${Un.HEAVEN}/3c`,n2e=Cse("release-plans"),r2e=uc();Ase=Un.HEAVEN,i2e=vse(Ase,0,0),Sse=`${Un.REPOZ}/cope`,o2e=`${Sse}/learning/event-log`,a2e=`${Un.HEAVEN}/lovable/cope`});function Ese(){return hb||(hb=[...Tse],hb)}function ST(e){let n=Ese().filter(r=>r.canonicalType===e).map(r=>r.derivedType);return[e,...n]}function Ot(e){return e.defaultValue}var $t,Mt,ui,Tse,hb,Ll=Te(()=>{"use strict";y();pf();$t=HO,Mt={AutoSyncWithBlockchain:{address:`${$t}/auto-sync-blockchain`,name:"AutoSyncWithBlockchain",defaultValue:!0,description:"Enable automatic blockchain anchoring when online"},HdAddressRoot:{address:`${$t}/hd-address-root`,name:"HdAddressRoot",defaultValue:`${Un.HEAVEN}/0/sync`,description:"HD derivation root path for sync blocks"},OutboxFlushInterval:{address:`${$t}/outbox-flush-interval`,name:"OutboxFlushInterval",defaultValue:5e3,description:"Milliseconds between outbox flush attempts"},A2ASyncCycleMs:{address:`${$t}/a2a-sync-cycle`,name:"A2ASyncCycleMs",defaultValue:3e4,description:"Milliseconds between A2A peer sync cycles"},GenesisHash:{address:`${$t}/genesis-hash`,name:"GenesisHash",defaultValue:"0".repeat(64),description:"Initial previous_hash for genesis blocks"},MaxLocalBlocks:{address:`${$t}/max-local-blocks`,name:"MaxLocalBlocks",defaultValue:1e4,description:"Maximum blocks retained in local chainlet cache"},BlockTtlSeconds:{address:`${$t}/block-ttl`,name:"BlockTtlSeconds",defaultValue:604800,description:"Time-to-live for cached blocks (seconds)"},AnchorStrategy:{address:`${$t}/anchor-strategy`,name:"AnchorStrategy",defaultValue:"off",description:"Strategy for anchoring queued blocks: off (local-only), individual, or batch"},MaxBatchSize:{address:`${$t}/max-batch-size`,name:"MaxBatchSize",defaultValue:32,description:"Maximum blocks per batch anchor transaction (XRPL memo cap)"},HeartbeatIntervalMs:{address:`${$t}/heartbeat-interval`,name:"HeartbeatIntervalMs",defaultValue:15e3,description:"Milliseconds between XRPL connectivity heartbeats"},HeartbeatTimeoutMs:{address:`${$t}/heartbeat-timeout`,name:"HeartbeatTimeoutMs",defaultValue:5e3,description:"Milliseconds before heartbeat considered failed"},UseCloudPersistence:{address:`${$t}/use-cloud`,name:"UseCloudPersistence",defaultValue:!1,description:"Opt into server-escrow copy execution + a2a fan-out"},EscrowedCappzStoreWalletAddress:{address:`${$t}/escrowed-cappz-store-wallet`,name:"EscrowedCappzStoreWalletAddress",defaultValue:"",description:"HD address of the server-side escrowed cappz-store wallet"},MiddlewareDbName:{address:`${$t}/middleware/db-name`,name:"MiddlewareDbName",defaultValue:"cappz-middleware",description:"Database name for the cappz-middleware persistence engine"},MiddlewareDbVersion:{address:`${$t}/middleware/db-version`,name:"MiddlewareDbVersion",defaultValue:4,description:"Schema version for the cappz-middleware database"},LegacyDbName:{address:`${$t}/middleware/legacy-db-name`,name:"LegacyDbName",defaultValue:"cappz-chainlet-cache",description:"Legacy database name for migration source"},MigrationStatusMdm:{address:`${$t}/middleware/migration-status-mdm`,name:"MigrationStatusMdm",defaultValue:KO,description:"MDM address for migration lifecycle event log"},MigrationStoreName:{address:`${$t}/middleware/migration-store`,name:"MigrationStoreName",defaultValue:"__migration_status",description:"Object store name for migration status entries"},RequiredStores:{address:`${$t}/middleware/required-stores`,name:"RequiredStores",defaultValue:["session","profile","transactions","appointments","dashboard","kv","chainlet_blocks"],description:"Object stores guaranteed to exist in the middleware database"},KvStoreName:{address:`${$t}/store/kv-store-name`,name:"KvStoreName",defaultValue:"kv",description:"Default key-value store name for chainletStorage facade"},MdmTxCachePrefix:{address:`${$t}/mdm-cache/prefix`,name:"MdmTxCachePrefix",defaultValue:"mdm-tx:",description:"Key prefix for MDM transaction cache entries"},MdmTxCacheIndexKey:{address:`${$t}/mdm-cache/index-key`,name:"MdmTxCacheIndexKey",defaultValue:"mdm-tx:__index__",description:"Cache key for MDM TX address index"},MdmTxCacheSyncTsKey:{address:`${$t}/mdm-cache/sync-ts-key`,name:"MdmTxCacheSyncTsKey",defaultValue:"mdm-tx:__last-sync__",description:"Cache key for last MDM sync timestamp"},A2ADeviceIdKey:{address:`${$t}/a2a/device-id-key`,name:"A2ADeviceIdKey",defaultValue:"cappz_device_id",description:"Storage key for A2A sync device identifier"},ManifestPipelineName:{address:`${$t}/manifest/pipeline-name`,name:"ManifestPipelineName",defaultValue:"skill-manifest",description:"Pipeline identifier for skill manifest sync-on-async processing"},ManifestKeyPrefix:{address:`${$t}/manifest/key-prefix`,name:"ManifestKeyPrefix",defaultValue:"skill:manifest:",description:"Key prefix for wallet-resident skill manifests"}},ui=VO,Tse=[{address:`${ui}/trade/created`,derivedType:"TradeCreated",canonicalType:"ContentCreated"},{address:`${ui}/trade/amended`,derivedType:"TradeAmended",canonicalType:"ContentAmended"},{address:`${ui}/trade/cancelled`,derivedType:"TradeCancelled",canonicalType:"ContentReverted"},{address:`${ui}/trade/novated`,derivedType:"TradeNovated",canonicalType:"ContentCloned"},{address:`${ui}/order/created`,derivedType:"OrderCreated",canonicalType:"ContentCreated"},{address:`${ui}/order/amended`,derivedType:"OrderAmended",canonicalType:"ContentAmended"},{address:`${ui}/order/cancelled`,derivedType:"OrderCancelled",canonicalType:"ContentReverted"},{address:`${ui}/document/created`,derivedType:"DocumentCreated",canonicalType:"ContentCreated"},{address:`${ui}/document/revised`,derivedType:"DocumentRevised",canonicalType:"ContentAmended"},{address:`${ui}/document/superseded`,derivedType:"DocumentSuperseded",canonicalType:"ContentDeprecated"},{address:`${ui}/refdata/list-created`,derivedType:"ListDomainCreated",canonicalType:"ContentCreated"},{address:`${ui}/refdata/list-versioned`,derivedType:"ListVersioned",canonicalType:"ContentAmended"},{address:`${ui}/refdata/value-created`,derivedType:"ListValueCreated",canonicalType:"ContentCreated"}],hb=null});function Ise(){return Bl||(Bl=new Worker(kse??new URL("./opfsWriteWorker.ts",import.meta.url),{type:"module"}),Bl.onmessage=e=>{let t=Ih.get(e.data.id);t&&(Ih.delete(e.data.id),e.data.ok?t.resolve():t.reject(new Error(`[opfs] worker write failed: ${e.data.error??"unknown"}`)))},Bl.onerror=e=>{let t=new Error(`[opfs] write worker crashed: ${e.message||"unknown"}`);for(let n of Ih.values())n.reject(t);Ih.clear(),Bl=null},Bl)}function Pse(e){return typeof e.createWritable=="function"}function zO(e){let t=e?.name,n=e instanceof Error?e.message:String(e);return t==="UnknownError"||/unknown transient reason|UnknownError/i.test(n)}async function XO(e,t){if(typeof Worker>"u")throw new Error("[opfs] no createWritable and no Worker for createSyncAccessHandle");let n=t instanceof Blob?await t.arrayBuffer():t instanceof Uint8Array?t.slice().buffer:t.slice(0),r=++_se;await new Promise((i,o)=>{Ih.set(r,{resolve:i,reject:o}),Ise().postMessage({id:r,path:e,bytes:n},[n])})}async function jO(e,t){let n=await navigator.storage.getDirectory();for(let o of e.slice(0,-1))n=await n.getDirectoryHandle(o,{create:!0});let r=await n.getFileHandle(e[e.length-1],{create:!0});if(!Pse(r))return XO(e,t);let i=await r.createWritable();try{await i.write(t),await i.close()}catch(o){try{await i.abort?.()}catch{}throw o}}async function mb(e,t){try{return await jO(e,t)}catch(n){if(!zO(n))throw n;await xse(150);try{return await jO(e,t)}catch(r){if(!zO(r)||typeof Worker>"u")throw r;try{return await XO(e,t)}catch{throw r}}}}var Bl,kse,_se,Ih,xse,TT=Te(()=>{"use strict";y();Bl=null,kse=null,_se=0,Ih=new Map;xse=e=>new Promise(t=>setTimeout(t,e))});function ET(e,t){return`${e}-v${t}.cappz`}async function kT(){if(typeof navigator>"u"||!navigator.storage?.getDirectory)return null;try{return await(await navigator.storage.getDirectory()).getDirectoryHandle(WO,{create:!0})}catch{return null}}async function GO(e){let t;if(e instanceof Uint8Array){let r=new Uint8Array(e.byteLength);r.set(e),t=r.buffer}else t=e;let n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function _T(e){let t=await kT();if(!t)return null;try{let i=await(await(await t.getFileHandle(ET(e.slug,e.version))).getFile()).arrayBuffer();return await GO(i)!==e.sha256?(console.warn(`[WalletBlobStore] sha256 mismatch for ${e.slug}-v${e.version}; discarding`),await t.removeEntry(ET(e.slug,e.version)).catch(()=>{}),null):new Uint8Array(i)}catch{return null}}async function YO(e,t){if(!await kT())return!1;let r=await GO(t);if(r!==e.sha256)return console.warn(`[WalletBlobStore] refusing to write ${e.slug}-v${e.version}: sha256 mismatch (got ${r}, expected ${e.sha256})`),!1;try{return await mb([WO,ET(e.slug,e.version)],t),!0}catch(i){return console.warn(`[WalletBlobStore] write failed for ${e.slug}-v${e.version}:`,i),!1}}async function ZO(){let e=await kT();if(!e)return[];let t=[];try{for await(let[n]of e.entries())t.push(n)}catch{}return t}var WO,JO=Te(()=>{"use strict";y();TT();WO="wallets"});var ZT={};Tr(ZT,{AsyncCompress:()=>Bse,AsyncDecompress:()=>qse,AsyncDeflate:()=>wD,AsyncGunzip:()=>CD,AsyncGzip:()=>Bse,AsyncInflate:()=>jT,AsyncUnzipInflate:()=>Jse,AsyncUnzlib:()=>AD,AsyncZipDeflate:()=>Xse,AsyncZlib:()=>Use,Compress:()=>DT,DecodeUTF8:()=>Kse,Decompress:()=>BT,Deflate:()=>qi,EncodeUTF8:()=>zse,FlateErrorCode:()=>Nse,Gunzip:()=>Tb,Gzip:()=>DT,Inflate:()=>Cr,Unzip:()=>Qse,UnzipInflate:()=>Zse,UnzipPassThrough:()=>xD,Unzlib:()=>kb,Zip:()=>Wse,ZipDeflate:()=>jse,ZipPassThrough:()=>Mh,Zlib:()=>NT,compress:()=>Fse,compressSync:()=>RT,decompress:()=>Hse,decompressSync:()=>Vse,deflate:()=>bD,deflateSync:()=>Nh,gunzip:()=>vD,gunzipSync:()=>Eb,gzip:()=>Fse,gzipSync:()=>RT,inflate:()=>XT,inflateSync:()=>_f,strFromU8:()=>GT,strToU8:()=>fc,unzip:()=>ece,unzipSync:()=>tce,unzlib:()=>SD,unzlibSync:()=>_b,zip:()=>Gse,zipSync:()=>Yse,zlib:()=>$se,zlibSync:()=>LT});import{createRequire as Mse}from"module";function Ul(e,t){return typeof e=="function"&&(t=e,e={}),this.ondata=t,e}function bD(e,t,n){return n||(n=t,t={}),typeof n!="function"&&_e(7),Ef(e,t,[Tf],function(r){return pc(Nh(r.data[0],r.data[1]))},0,n)}function Nh(e,t){return Fl(e,t||{},0,0)}function XT(e,t,n){return n||(n=t,t={}),typeof n!="function"&&_e(7),Ef(e,t,[Sf],function(r){return pc(_f(r.data[0],$T(r.data[1])))},1,n)}function _f(e,t){return Dh(e,{i:2},t&&t.out,t&&t.dictionary)}function Fse(e,t,n){return n||(n=t,t={}),typeof n!="function"&&_e(7),Ef(e,t,[Tf,pD,function(){return[RT]}],function(r){return pc(RT(r.data[0],r.data[1]))},2,n)}function RT(e,t){t||(t={});var n=Af(),r=e.length;n.p(e);var i=Fl(e,t,VT(t),8),o=i.length;return qT(i,t),ht(i,o-8,n.d()),ht(i,o-4,r),i}function vD(e,t,n){return n||(n=t,t={}),typeof n!="function"&&_e(7),Ef(e,t,[Sf,yD,function(){return[Eb]}],function(r){return pc(Eb(r.data[0],r.data[1]))},3,n)}function Eb(e,t){var n=HT(e);return n+8>e.length&&_e(6,"invalid gzip data"),Dh(e.subarray(n,-8),{i:2},t&&t.out||new $e(gD(e)),t&&t.dictionary)}function $se(e,t,n){return n||(n=t,t={}),typeof n!="function"&&_e(7),Ef(e,t,[Tf,hD,function(){return[LT]}],function(r){return pc(LT(r.data[0],r.data[1]))},4,n)}function LT(e,t){t||(t={});var n=xb();n.p(e);var r=Fl(e,t,t.dictionary?6:2,4);return KT(r,t),ht(r,r.length-4,n.d()),r}function SD(e,t,n){return n||(n=t,t={}),typeof n!="function"&&_e(7),Ef(e,t,[Sf,mD,function(){return[_b]}],function(r){return pc(_b(r.data[0],$T(r.data[1])))},5,n)}function _b(e,t){return Dh(e.subarray(zT(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Hse(e,t,n){return n||(n=t,t={}),typeof n!="function"&&_e(7),e[0]==31&&e[1]==139&&e[2]==8?vD(e,t,n):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?XT(e,t,n):SD(e,t,n)}function Vse(e,t){return e[0]==31&&e[1]==139&&e[2]==8?Eb(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?_f(e,t):_b(e,t)}function fc(e,t){if(t){for(var n=new $e(e.length),r=0;r>1)),a=0,s=function(u){o[a++]=u},r=0;ro.length){var c=new $e(a+8+(i-r<<1));c.set(o),o=c}var l=e.charCodeAt(r);l<128||t?s(l):l<2048?(s(192|l>>6),s(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++r)&1023,s(240|l>>18),s(128|l>>12&63),s(128|l>>6&63),s(128|l&63)):(s(224|l>>12),s(128|l>>6&63),s(128|l&63))}return $i(o,0,a)}function GT(e,t){if(t){for(var n="",r=0;r65535&&$(_e(11,0,1),null),!M)$(null,D);else if(F<16e4)try{$(null,Nh(D,P))}catch(R){$(R,null)}else u.push(bD(D,P,$))},w=0;w65535&&_e(11);var k=u?Nh(c,l):c,B=k.length,D=Af();D.p(c),r.push(Rh(l,{size:c.length,crc:D.d(),c:k,f:d,m:g,u:p!=a.length||g&&h.length!=w,o:i,compression:u})),i+=30+p+T+B,o+=76+2*(p+T)+(w||0)+B}for(var P=new $e(o+22),U=i,F=o-i,H=0;H65558)return a(_e(13,0,1),null),i;var c=wr(e,s+8);if(c){var l=c,u=on(e,s+16),d=on(e,s-20)==117853008;if(d){var p=on(e,s-12);d=on(e,p)==101075792,d&&(l=c=on(e,p+32),u=on(e,p+48))}for(var h=t&&t.filter,g=function(T){var k=ID(e,u,d),B=k[0],D=k[1],P=k[2],U=k[3],F=k[4],H=k[5],b=_D(e,H);u=F;var C=function(S,A){S?(i(),a(S,null)):(A&&(o[U]=A),--c||a(null,o))};if(!h||h({name:U,size:D,originalSize:P,compression:B}))if(!B)C(null,$i(e,b,b+D));else if(B==8){var v=e.subarray(b,b+D);if(P<524288||D>.8*P)try{C(null,_f(v,{out:new $e(P)}))}catch(S){C(S,null)}else r.push(XT(v,{size:P},C))}else C(_e(14,"unknown compression type "+B,1),null);else C(null,null)},w=0;w65558)&&_e(13);var i=wr(e,r+8);if(!i)return{};var o=on(e,r+16),a=on(e,r-20)==117853008;if(a){var s=on(e,r-12);a=on(e,s)==101075792,a&&(i=on(e,s+32),o=on(e,s+48))}for(var c=t&&t.filter,l=0;l{y();Ose=Mse("/"),Dse=";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";try{mf=Ose("worker_threads"),wb=mf.Worker,PT=mf.isMarkedAsUntransferable}catch{}Rse=wb?function(e,t,n,r,i){var o=!1,a=new wb(e+Dse,{eval:!0}).on("error",function(s){return i(s,null)}).on("message",function(s){return i(null,s)}).on("exit",function(s){s&&!o&&i(new Error("exited with code "+s),null)});return PT&&(r=r.filter(function(s){return!PT(s)})),a.postMessage(n,r),a.terminate=function(){return o=!0,wb.prototype.terminate.call(a)},a}:function(e,t,n,r,i){setImmediate(function(){return i(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var o=function(){};return{terminate:o,postMessage:o}},$e=Uint8Array,br=Uint16Array,Oh=Int32Array,bf=new $e([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Cf=new $e([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ph=new $e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tD=function(e,t){for(var n=new br(31),r=0;r<31;++r)n[r]=t+=1<>1|(mt&21845)<<1,Za=(Za&52428)>>2|(Za&13107)<<2,Za=(Za&61680)>>4|(Za&3855)<<4,xh[mt]=((Za&65280)>>8|(Za&255)<<8)>>1;Ui=(function(e,t,n){for(var r=e.length,i=0,o=new br(t);i>c]=l}else for(s=new br(r),i=0;i>15-e[i]);return s}),Ja=new $e(288);for(mt=0;mt<144;++mt)Ja[mt]=8;for(mt=144;mt<256;++mt)Ja[mt]=9;for(mt=256;mt<280;++mt)Ja[mt]=7;for(mt=280;mt<288;++mt)Ja[mt]=8;gf=new $e(32);for(mt=0;mt<32;++mt)gf[mt]=5;iD=Ui(Ja,9,0),oD=Ui(Ja,9,1),aD=Ui(gf,5,0),sD=Ui(gf,5,1),bb=function(e){for(var t=e[0],n=1;nt&&(t=e[n]);return t},Fi=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Cb=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},vf=function(e){return(e+7)/8|0},$i=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new $e(e.subarray(t,n))},Nse={UnexpectedEOF:0,InvalidBlockType:1,InvalidLengthLiteral:2,InvalidDistance:3,StreamFinished:4,NoStreamHandler:5,InvalidHeader:6,NoCallback:7,InvalidUTF8:8,ExtraFieldTooLong:9,InvalidDate:10,FilenameTooLong:11,StreamFinishing:12,InvalidZipData:13,UnknownCompressionMethod:14},cD=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],_e=function(e,t,n){var r=new Error(t||cD[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,_e),!n)throw r;return r},Dh=function(e,t,n,r){var i=e.length,o=r?r.length:0;if(!i||t.f&&!t.l)return n||new $e(0);var a=!n,s=a||t.i!=2,c=t.i;a&&(n=new $e(i*3));var l=function(Ee){var Ne=n.length;if(Ee>Ne){var De=new $e(Math.max(Ne*2,Ee));De.set(n),n=De}},u=t.f||0,d=t.p||0,p=t.b||0,h=t.l,g=t.d,w=t.m,T=t.n,k=i*8;do{if(!h){u=Fi(e,d,1);var B=Fi(e,d+1,3);if(d+=3,B)if(B==1)h=oD,g=sD,w=9,T=5;else if(B==2){var F=Fi(e,d,31)+257,H=Fi(e,d+10,15)+4,b=F+Fi(e,d+5,31)+1;d+=14;for(var C=new $e(b),v=new $e(19),S=0;S>4;if(D<16)C[S++]=D;else{var O=0,j=0;for(D==16?(j=3+Fi(e,d,3),d+=2,O=C[S-1]):D==17?(j=3+Fi(e,d,7),d+=3):D==18&&(j=11+Fi(e,d,127),d+=7);j--;)C[S++]=O}}var N=C.subarray(0,F),V=C.subarray(F);w=bb(N),T=bb(V),h=Ui(N,w,1),g=Ui(V,T,1)}else _e(1);else{var D=vf(d)+4,P=e[D-4]|e[D-3]<<8,U=D+P;if(U>i){c&&_e(0);break}s&&l(p+P),n.set(e.subarray(D,U),p),t.b=p+=P,t.p=d=U*8,t.f=u;continue}if(d>k){c&&_e(0);break}}s&&l(p+131072);for(var G=(1<>4;if(d+=O&15,d>k){c&&_e(0);break}if(O||_e(2),Z<256)n[p++]=Z;else if(Z==256){X=d,h=null;break}else{var ee=Z-254;if(Z>264){var S=Z-257,J=bf[S];ee=Fi(e,d,(1<>4;ie||_e(3),d+=ie&15;var V=rD[se];if(se>3){var J=Cf[se];V+=Cb(e,d)&(1<k){c&&_e(0);break}s&&l(p+131072);var me=p+ee;if(p>8},yf=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},vb=function(e,t){for(var n=[],r=0;rp&&(p=o[r].s);var h=new br(p+1),g=Sb(n[u-1],h,0);if(g>t){var r=0,w=0,T=g-t,k=1<t)w+=k-(1<>=T;w>0;){var D=o[r].s;h[D]=0&&w;--r){var P=o[r].s;h[P]==t&&(--h[P],++w)}g=t}return{t:new $e(h),l:g}},Sb=function(e,t,n){return e.s==-1?Math.max(Sb(e.l,t,n+1),Sb(e.r,t,n+1)):t[e.s]=n},MT=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new br(++t),r=0,i=e[0],o=1,a=function(c){n[r++]=c},s=1;s<=t;++s)if(e[s]==i&&s!=t)++o;else{if(!i&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(i),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(i);o=1,i=e[s]}return{c:n.subarray(0,r),n:t}},hf=function(e,t){for(var n=0,r=0;r>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var o=0;o4&&!v[Ph[A-1]];--A);var M=l+5<<3,$=hf(i,Ja)+hf(o,gf)+a,R=hf(i,p)+hf(o,w)+a+14+3*A+hf(H,v)+2*H[16]+3*H[17]+7*H[18];if(c>=0&&M<=$&&M<=R)return Pb(t,u,e.subarray(c,c+l));var O,j,N,V;if(ra(t,u,1+(R<$)),u+=2,R<$){O=Ui(p,h,0),j=p,N=Ui(w,T,0),V=w;var G=Ui(v,S,0);ra(t,u,D-257),ra(t,u+5,F-1),ra(t,u+10,A-4),u+=14;for(var b=0;b15&&(ra(t,u,Z[b]>>5&127),u+=Z[b]>>12)}}else O=iD,j=Ja,N=aD,V=gf;for(var b=0;b255){var ee=J>>18&31;yf(t,u,O[ee+257]),u+=j[ee+257],ee>7&&(ra(t,u,J>>23&31),u+=bf[ee]);var ie=J&31;yf(t,u,N[ie]),u+=V[ie],ie>3&&(yf(t,u,J>>5&8191),u+=Cf[ie])}else yf(t,u,O[J]),u+=j[J]}return yf(t,u,O[256]),u+j[256]},lD=new Oh([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ia=new $e(0),uD=function(e,t,n,r,i,o){var a=o.z||e.length,s=new $e(r+a+5*(1+Math.ceil(a/7e3))+i),c=s.subarray(r,s.length-i),l=o.l,u=(o.r||0)&7;if(t){u&&(c[0]=o.r>>3);for(var d=lD[t-1],p=d>>13,h=d&8191,g=(1<7e3||v>24576)&&(O>423||!l)){u=OT(e,c,0,P,U,F,b,v,A,C-A,u),v=H=b=0,A=C;for(var j=0;j<286;++j)U[j]=0;for(var j=0;j<30;++j)F[j]=0}var N=2,V=0,G=h,L=$-R&32767;if(O>2&&M==D(C-L))for(var X=Math.min(p,O)-1,Z=Math.min(32767,C),ee=Math.min(258,O);L<=Z&&--G&&$!=R;){if(e[C+N]==e[C+N-L]){for(var J=0;JN){if(N=J,V=L,J>X)break;for(var ie=Math.min(L,J-2),se=0,j=0;jse&&(se=Pe,R=me)}}}$=R,R=w[$],L+=$-R&32767}if(V){P[v++]=268435456|Ab[N]<<18|xT[V];var Ee=Ab[N]&31,Ne=xT[V]&31;b+=bf[Ee]+Cf[Ne],++U[257+Ee],++F[Ne],S=C+N,++H}else P[v++]=e[C],++U[e[C]]}}for(C=Math.max(C,S);C=a&&(c[u/8|0]=l,De=a),u=Pb(c,u+1,e.subarray(C,De))}o.i=a}return $i(s,0,r+vf(u)+i)},dD=(function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),Af=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r>>8;e=n},d:function(){return~e}}},xb=function(){var e=1,t=0;return{p:function(n){for(var r=e,i=t,o=n.length|0,a=0;a!=o;){for(var s=Math.min(a+2655,o);a>16),i=(i&65535)+15*(i>>16)}e=r,t=i},d:function(){return e%=65521,t%=65521,(e&255)<<24|(e&65280)<<8|(t&255)<<8|t>>8}}},Fl=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),a=new $e(o.length+e.length);a.set(o),a.set(e,o.length),e=a,i.w=o.length}return uD(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)},Rh=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},QO=function(e,t,n){for(var r=e(),i=e.toString(),o=i.slice(i.indexOf("[")+1,i.lastIndexOf("]")).replace(/\s+/g,"").split(","),a=0;a>>0},IT=function(e,t){return on(e,t)+on(e,t+4)*4294967296},ht=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},qT=function(e,t){var n=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=t.level<2?4:t.level==9?2:0,e[9]=3,t.mtime!=0&&ht(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),n){e[3]=8;for(var r=0;r<=n.length;++r)e[r+10]=n.charCodeAt(r)}},HT=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&_e(6,"invalid gzip data");var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},gD=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},VT=function(e){return 10+(e.filename?e.filename.length+1:0)},KT=function(e,t){var n=t.level,r=n==0?0:n<6?1:n==9?3:2;if(e[0]=120,e[1]=r<<6|(t.dictionary&&32),e[1]|=31-(e[0]<<8|e[1])%31,t.dictionary){var i=xb();i.p(t.dictionary),ht(e,2,i.d())}},zT=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&_e(6,"invalid zlib data"),(e[1]>>5&1)==+!t&&_e(6,"invalid zlib data: "+(e[1]&32?"need":"unexpected")+" dictionary"),(e[1]>>3&4)+2};qi=(function(){function e(t,n){if(typeof t=="function"&&(n=t,t={}),this.ondata=n,this.o=t||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new $e(98304),this.o.dictionary){var r=this.o.dictionary.subarray(-32768);this.b.set(r,32768-r.length),this.s.i=32768-r.length}}return e.prototype.p=function(t,n){this.ondata(Fl(t,this.o,0,0,this.s),n)},e.prototype.push=function(t,n){this.ondata||_e(5),this.s.l&&_e(4);var r=t.length+this.s.z;if(r>this.b.length){if(r>2*this.b.length-32768){var i=new $e(r&-32768);i.set(this.b.subarray(0,this.s.z)),this.b=i}var o=this.b.length-this.s.z;this.b.set(t.subarray(0,o),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(t.subarray(o),32768),this.s.z=t.length-o+32768,this.s.i=32766,this.s.w=32768}else this.b.set(t,this.s.z),this.s.z+=t.length;this.s.l=n&1,(this.s.z>this.s.w+8191||n)&&(this.p(this.b,n||!1),this.s.w=this.s.i,this.s.i-=2),n&&(this.s=this.o={},this.b=ia)},e.prototype.flush=function(t){if(this.ondata||_e(5),this.s.l&&_e(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,t){var n=new $e(6);n[0]=this.s.r>>3;var r=Pb(n,this.s.r,ia);this.s.r=0,this.ondata(n.subarray(0,r>>3),!1)}},e})(),wD=(function(){function e(t,n){kf([Tf,function(){return[Hi,qi]}],this,Ul.call(this,t,n),function(r){var i=new qi(r.data);onmessage=Hi(i)},6,1)}return e})();Cr=(function(){function e(t,n){typeof t=="function"&&(n=t,t={}),this.ondata=n;var r=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new $e(32768),this.p=new $e(0),r&&this.o.set(r)}return e.prototype.e=function(t){if(this.ondata||_e(5),this.d&&_e(4),!this.p.length)this.p=t;else if(t.length){var n=new $e(this.p.length+t.length);n.set(this.p),n.set(t,this.p.length),this.p=n}},e.prototype.c=function(t){this.s.i=+(this.d=t||!1);var n=this.s.b,r=Dh(this.p,this.s,this.o);this.ondata($i(r,n,this.s.b),this.d),this.o=$i(r,this.s.b-32768),this.s.b=this.o.length,this.p=$i(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(t,n){this.e(t),this.c(n)},e})(),jT=(function(){function e(t,n){kf([Sf,function(){return[Hi,Cr]}],this,Ul.call(this,t,n),function(r){var i=new Cr(r.data);onmessage=Hi(i)},7,0)}return e})();DT=(function(){function e(t,n){this.c=Af(),this.l=0,this.v=1,qi.call(this,t,n)}return e.prototype.push=function(t,n){this.c.p(t),this.l+=t.length,qi.prototype.push.call(this,t,n)},e.prototype.p=function(t,n){var r=Fl(t,this.o,this.v&&VT(this.o),n&&8,this.s);this.v&&(qT(r,this.o),this.v=0),n&&(ht(r,r.length-8,this.c.d()),ht(r,r.length-4,this.l)),this.ondata(r,n)},e.prototype.flush=function(t){qi.prototype.flush.call(this,t)},e})(),Bse=(function(){function e(t,n){kf([Tf,pD,function(){return[Hi,qi,DT]}],this,Ul.call(this,t,n),function(r){var i=new DT(r.data);onmessage=Hi(i)},8,1)}return e})();Tb=(function(){function e(t,n){this.v=1,this.r=0,Cr.call(this,t,n)}return e.prototype.push=function(t,n){if(Cr.prototype.e.call(this,t),this.r+=t.length,this.v){var r=this.p.subarray(this.v-1),i=r.length>3?HT(r):4;if(i>r.length){if(!n)return}else this.v>1&&this.onmember&&this.onmember(this.r-r.length);this.p=r.subarray(i),this.v=0}Cr.prototype.c.call(this,0),this.s.f&&!this.s.l?(this.v=vf(this.s.p)+9,this.s={i:0},this.o=new $e(0),this.push(new $e(0),n)):n&&Cr.prototype.c.call(this,n)},e})(),CD=(function(){function e(t,n){var r=this;kf([Sf,yD,function(){return[Hi,Cr,Tb]}],this,Ul.call(this,t,n),function(i){var o=new Tb(i.data);o.onmember=function(a){return postMessage(a)},onmessage=Hi(o)},9,0,function(i){return r.onmember&&r.onmember(i)})}return e})();NT=(function(){function e(t,n){this.c=xb(),this.v=1,qi.call(this,t,n)}return e.prototype.push=function(t,n){this.c.p(t),qi.prototype.push.call(this,t,n)},e.prototype.p=function(t,n){var r=Fl(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(KT(r,this.o),this.v=0),n&&ht(r,r.length-4,this.c.d()),this.ondata(r,n)},e.prototype.flush=function(t){qi.prototype.flush.call(this,t)},e})(),Use=(function(){function e(t,n){kf([Tf,hD,function(){return[Hi,qi,NT]}],this,Ul.call(this,t,n),function(r){var i=new NT(r.data);onmessage=Hi(i)},10,1)}return e})();kb=(function(){function e(t,n){Cr.call(this,t,n),this.v=t&&t.dictionary?2:1}return e.prototype.push=function(t,n){if(Cr.prototype.e.call(this,t),this.v){if(this.p.length<6&&!n)return;this.p=this.p.subarray(zT(this.p,this.v-1)),this.v=0}n&&(this.p.length<4&&_e(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),Cr.prototype.c.call(this,n)},e})(),AD=(function(){function e(t,n){kf([Sf,mD,function(){return[Hi,Cr,kb]}],this,Ul.call(this,t,n),function(r){var i=new kb(r.data);onmessage=Hi(i)},11,0)}return e})();BT=(function(){function e(t,n){this.o=Ul.call(this,t,n)||{},this.G=Tb,this.I=Cr,this.Z=kb}return e.prototype.i=function(){var t=this;this.s.ondata=function(n,r){t.ondata(n,r)}},e.prototype.push=function(t,n){if(this.ondata||_e(5),this.s)this.s.push(t,n);else{if(this.p&&this.p.length){var r=new $e(this.p.length+t.length);r.set(this.p),r.set(t,this.p.length)}else this.p=t;this.p.length>2&&(this.s=this.p[0]==31&&this.p[1]==139&&this.p[2]==8?new this.G(this.o):(this.p[0]&15)!=8||this.p[0]>>4>7||(this.p[0]<<8|this.p[1])%31?new this.I(this.o):new this.Z(this.o),this.i(),this.s.push(this.p,n),this.p=null)}},e})(),qse=(function(){function e(t,n){BT.call(this,t,n),this.queuedSize=0,this.G=CD,this.I=jT,this.Z=AD}return e.prototype.i=function(){var t=this;this.s.ondata=function(n,r,i){t.ondata(n,r,i)},this.s.ondrain=function(n){t.queuedSize-=n,t.ondrain&&t.ondrain(n)}},e.prototype.push=function(t,n){this.queuedSize+=t.length,BT.prototype.push.call(this,t,n)},e})();WT=function(e,t,n,r){for(var i in e){var o=e[i],a=t+i,s=r;Array.isArray(o)&&(s=Rh(r,o[1]),o=o[0]),ArrayBuffer.isView(o)?n[a]=[o,s]:(n[a+="/"]=[new $e(0),s],WT(o,a,n,r))}},eD=typeof TextEncoder<"u"&&new TextEncoder,FT=typeof TextDecoder<"u"&&new TextDecoder,TD=0;try{FT.decode(ia,{stream:!0}),TD=1}catch{}ED=function(e){for(var t="",n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:$i(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}},Kse=(function(){function e(t){this.ondata=t,TD?this.t=new TextDecoder:this.p=ia}return e.prototype.push=function(t,n){if(this.ondata||_e(5),n=!!n,this.t){this.ondata(this.t.decode(t,{stream:!0}),n),n&&(this.t.decode().length&&_e(8),this.t=null);return}this.p||_e(4);var r=new $e(this.p.length+t.length);r.set(this.p),r.set(t,this.p.length);var i=ED(r),o=i.s,a=i.r;n?(a.length&&_e(8),this.p=null):this.p=a,this.ondata(o,n)},e})(),zse=(function(){function e(t){this.ondata=t}return e.prototype.push=function(t,n){this.ondata||_e(5),this.d&&_e(4),this.ondata(fc(t),this.d=n||!1)},e})();kD=function(e){return e==1?3:e<6?2:e==9?1:0},_D=function(e,t){return t+30+wr(e,t+26)+wr(e,t+28)},ID=function(e,t,n){var r=wr(e,t+28),i=wr(e,t+30),o=GT(e.subarray(t+46,t+46+r),!(wr(e,t+8)&2048)),a=t+46+r,s=PD(e,a,i,n,on(e,t+20),on(e,t+24),on(e,t+42)),c=s[0],l=s[1],u=s[2];return[wr(e,t+10),c,l,o,a+i+wr(e,t+32),u]},PD=function(e,t,n,r,i,o,a){var s=i==4294967295,c=o==4294967295,l=a==4294967295,u=t+n,d=s+c+l;if(r&&d){for(;t+465535&&_e(9),t+=r+4}return t},wf=function(e,t,n,r,i,o,a,s){var c=r.length,l=n.extra,u=s&&s.length,d=dc(l);ht(e,t,a!=null?33639248:67324752),t+=4,a!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(o<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var p=new Date(n.mtime==null?Date.now():n.mtime),h=p.getFullYear()-1980;if((h<0||h>119)&&_e(10),ht(e,t,h<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,o!=-1&&(ht(e,t,n.crc),ht(e,t+4,o<0?-o-2:o),ht(e,t+8,n.size)),ht(e,t+12,c),ht(e,t+14,d),t+=16,a!=null&&(ht(e,t,u),ht(e,t+6,n.attrs),ht(e,t+10,a),t+=14),e.set(r,t),t+=c,d)for(var g in l){var w=l[g],T=w.length;ht(e,t,+g),ht(e,t+2,T),e.set(w,t+4),t+=4+T}return u&&(e.set(s,t),t+=u),t},YT=function(e,t,n,r,i){ht(e,t,101010256),ht(e,t+8,n),ht(e,t+10,n),ht(e,t+12,r),ht(e,t+16,i)},Mh=(function(){function e(t){this.filename=t,this.c=Af(),this.size=0,this.compression=0}return e.prototype.process=function(t,n){this.ondata(null,t,n)},e.prototype.push=function(t,n){this.ondata||_e(5),this.c.p(t),this.size+=t.length,n&&(this.crc=this.c.d()),this.process(t,n||!1)},e})(),jse=(function(){function e(t,n){var r=this;n||(n={}),Mh.call(this,t),this.d=new qi(n,function(i,o){r.ondata(null,i,o)}),this.compression=8,this.flag=kD(n.level)}return e.prototype.process=function(t,n){try{this.d.push(t,n)}catch(r){this.ondata(r,null,n)}},e.prototype.push=function(t,n){Mh.prototype.push.call(this,t,n)},e})(),Xse=(function(){function e(t,n){var r=this;n||(n={}),Mh.call(this,t),this.d=new wD(n,function(i,o,a){r.ondata(i,o,a)}),this.compression=8,this.flag=kD(n.level),this.terminate=this.d.terminate}return e.prototype.process=function(t,n){this.d.push(t,n)},e.prototype.push=function(t,n){Mh.prototype.push.call(this,t,n)},e})(),Wse=(function(){function e(t){this.ondata=t,this.u=[],this.d=1}return e.prototype.add=function(t){var n=this;if(this.ondata||_e(5),this.d&2)this.ondata(_e(4+(this.d&1)*8,0,1),null,!1);else{var r=fc(t.filename),i=r.length,o=t.comment,a=o&&fc(o),s=i!=t.filename.length||a&&o.length!=a.length,c=i+dc(t.extra)+30;i>65535&&this.ondata(_e(11,0,1),null,!1);var l=new $e(c);wf(l,0,t,r,s,-1);var u=[l],d=function(){for(var T=0,k=u;T0){var i=Math.min(this.c,t.length),o=t.subarray(0,i);if(this.c-=i,this.d?this.d.push(o,!this.c):this.k[0].push(o),t=t.subarray(i),t.length)return this.push(t,n)}else{var a=0,s=0,c=void 0,l=void 0;this.p.length?t.length?(l=new $e(this.p.length+t.length),l.set(this.p),l.set(t,this.p.length)):l=this.p:l=t;for(var u=l.length,d=this.c,p=d&&this.d,h=function(){var k=on(l,s);if(k==67324752){a=1,c=s,g.d=null,g.c=0;var B=wr(l,s+6),D=wr(l,s+8),P=B&2048,U=B&8,F=wr(l,s+26),H=wr(l,s+28);if(u>s+30+F+H){var b=[];g.k.unshift(b),a=2;var C=on(l,s+18),v=on(l,s+22),S=GT(l.subarray(s+30,s+=30+F),!P),A=PD(l,s,H,2,C,v,0),M=A[0],$=A[1],R=A[3];U&&(M=-1-R),s+=H,g.c=M;var O,j={name:S,compression:D,start:function(){if(j.ondata||_e(5),!M)j.ondata(null,ia,!0);else{var N=r.o[D];N||j.ondata(_e(14,"unknown compression type "+D,1),null,!1),O=M<0?new N(S):new N(S,M,$),O.ondata=function(X,Z,ee){j.ondata(X,Z,ee)};for(var V=0,G=b;V=0&&(j.size=M,j.originalSize=$),g.onfile(j)}return"break"}else if(d){if(k==134695760)return c=s+=12+(d==-2&&8),a=3,g.c=0,"break";if(k==33639248)return c=s-=4,a=3,g.c=0,"break"}},g=this;ss+c.length,0)),a=0;for(let s of i)o.set(s,a),a+=s.length;return o}async function cce(e){return new TextDecoder().decode(oce(e)?await sce(e):e)}async function lce(e){let t=new TextEncoder().encode(e);return ice()?ace(t):t}async function r4(e){try{let n=await(await(await n4()).getFileHandle(e)).getFile();return await cce(new Uint8Array(await n.arrayBuffer()))}catch{return null}}async function Mb(e,t){await mb([ND,e],await lce(t))}function gce(e){let t=2166136261;for(let n=0;n>>0)%t4}function QT(e){if(!e.endsWith(".json")||e.startsWith("_"))return null;let t=/^(.*?)(?:\+(\d+)|@(\d+))?\.json$/.exec(e);if(!t)return null;let n;try{n=decodeURIComponent(t[1])}catch{return null}let r=t[2]!==void 0?"shard":t[3]!==void 0?"segment":"legacy";return{store:n,file:{name:e,kind:r,n:Number(t[2]??t[3]??0)}}}async function e4(){let e=[];try{let t=await n4();for await(let[n]of t.entries())e.push(String(n))}catch{}return e}async function OD(e){try{await(await n4()).removeEntry(e)}catch{}}function BD(){let e=new Map,t=new Map,n=null,r=Promise.resolve(),i=0,o=P=>{let U=r.catch(()=>{}).then(P);return r=U.catch(()=>{}),U},a=P=>{let U=t.get(P);return U||(U={next:1,files:[],bytes:0,base:0},t.set(P,U)),U},s=new Set,c=new Map,l=P=>{let U=c.get(P);return U||(U=e4().then(F=>{let H=a(P);for(let b of F){let C=QT(b);C?.store!==P||C.file.kind!=="segment"||(H.files.includes(C.file.name)||H.files.push(C.file.name),H.next=Math.max(H.next,C.file.n+1))}}),c.set(P,U)),U};async function u(P,U){let F=encodeURIComponent(P),H=a(P),b=[...H.files],C=Array.from({length:t4},()=>[]);for(let S of U.entries())C[gce(S[0])].push(S);let v=0;for(let S=0;S!b.includes(S)),H.bytes=0}let d=(P,U)=>{o(async()=>{let F=a(P);if(!(!s.has(P)||!(F.files.length>=fce||F.bytes>=Math.max(pce,F.base))))try{await u(P,U)}catch(H){console.warn(`[cappz-store/opfs] compaction deferred for ${P}`,H)}})};async function p(P,U,F){if(await l(P),F==="all"&&s.has(P))return u(P,U);let H=F==="all"?[...U.keys()]:[...F];if(!H.length)return;let b=a(P),C=MD(H.map(S=>[S,U.has(S)?U.get(S):uce])),v=`${encodeURIComponent(P)}@${String(b.next).padStart(6,"0")}.json`;await Mb(v,C),b.next+=1,b.files.push(v),b.bytes+=C.length,d(P,U)}let h=P=>{let U=e.get(P.store);e.set(P.store,{rows:U?.rows??P.rows,all:P.all||!!U?.all,groups:[...P.groups,...U?.groups??[]]}),n||(n=setTimeout(k,Math.min(6e4,1e3*2**Math.min(i,6))))};async function g(P){let U=null;for(let F of P)try{await p(F.store,F.rows,hce(F))}catch(H){h(F),console.warn(`[cappz-store/opfs] write failed for ${F.store}`,H),U??=H}if(U)throw i+=1,U;i=0}let w=()=>{let P=[];for(let[U,F]of e){if(F.all){P.push({store:U,rows:F.rows,all:!0,groups:F.groups});continue}let H=[],b=0;for(let C of F.groups){let v=mce(F.rows,C);H.length&&b+v>yce&&(P.push({store:U,rows:F.rows,all:!1,groups:H}),H=[],b=0),H.push(C),b+=v}H.length&&P.push({store:U,rows:F.rows,all:!1,groups:H})}return e.clear(),P},T=P=>{let U=e.get(P.store);if(!U)return null;if(U.all)return e.delete(P.store),{store:P.store,rows:U.rows,all:!0,groups:U.groups};let F=new Set(P.keys),H=[],b=U.groups;for(let C=!0;C;){C=!1;let v=[];for(let S of b)if([...S].some(A=>F.has(A))){H.push(S);for(let A of S)F.add(A);C=!0}else v.push(S);b=v}return H.length?(b.length?U.groups=b:e.delete(P.store),{store:P.store,rows:U.rows,all:!1,groups:H}):null},k=()=>{B().catch(()=>{})},B=()=>(n=null,o(()=>g(w()))),D=P=>o(async()=>{let U=T(P);U&&await g([U])});return typeof window<"u"&&(window.addEventListener("pagehide",k),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e.size&&k()})),{kind:"opfs",async listStores(){let P=new Set;for(let U of await e4()){let F=QT(U);F&&P.add(F.store)}return[...P]},async load(P){let U=(await e4()).map(QT).filter(C=>!!C&&C.store===P).map(C=>C.file),F=C=>C==="legacy"?0:C==="shard"?1:2;U.sort((C,v)=>F(C.kind)-F(v.kind)||C.n-v.n);let H=new Map;await l(P);let b=a(P);for(let C of U){let v=await r4(C.name);if(!v)continue;let S;try{S=rce(v)}catch{continue}for(let[A,M]of S)dce(M)?H.delete(A):H.set(A,M);C.kind==="segment"?(b.files.includes(C.name)||b.files.push(C.name),b.bytes+=v.length,b.next=Math.max(b.next,C.n+1)):b.base+=v.length}return setTimeout(()=>s.add(P),0),H},persist(P,U,F="all"){let H=e.get(P)??{rows:U,all:!1,groups:[]};if(H.rows=U,F==="all")H.all=!0;else{let b=new Set(F);b.size&&H.groups.push(b)}e.set(P,H),n||(n=setTimeout(k,150))},async flush(P){if(P)return D(P);n&&clearTimeout(n),await B(),await r}}}var MD,rce,ND,ice,oce,ace,sce,uce,dce,t4,fce,pce,yce,hce,mce,FD=Te(()=>{"use strict";y();TT();MD=e=>JSON.stringify(e,DD),rce=e=>JSON.parse(e,nce);ND="cappz-store";ice=()=>typeof CompressionStream<"u"&&typeof DecompressionStream<"u",oce=e=>e.length>=2&&e[0]===31&&e[1]===139;ace=async e=>typeof CompressionStream<"u"?LD(e,new CompressionStream("gzip")):(await Promise.resolve().then(()=>(JT(),ZT))).gzipSync(e),sce=async e=>typeof DecompressionStream<"u"?LD(e,new DecompressionStream("gzip")):(await Promise.resolve().then(()=>(JT(),ZT))).gunzipSync(e);uce={__kvDeleted:1},dce=e=>!!e&&typeof e=="object"&&e.__kvDeleted===1,t4=32,fce=256,pce=16*1024*1024,yce=2*1024*1024,hce=e=>{if(e.all)return"all";let t=new Set;for(let n of e.groups)for(let r of n)t.add(r);return t},mce=(e,t)=>{let n=0;for(let r of t)try{n+=r.length+(e.has(r)?JSON.stringify(e.get(r),DD)?.length??4:16)}catch{n+=64}return n}});function UD(){return i4!==null}function wce(e){return i4?new Promise(t=>{let n=i4.open(e);n.onupgradeneeded=()=>{n.transaction?.abort()},n.onsuccess=()=>t(n.result),n.onerror=()=>t(null)}):Promise.resolve(null)}async function $D(e){let t=await wce(e);if(!t)return{};let n={};try{for(let r of Array.from(t.objectStoreNames))n[r]=await new Promise(i=>{try{let o=t.transaction(r,"readonly").objectStore(r).getAll();o.onsuccess=()=>i(o.result??[]),o.onerror=()=>i([])}catch{i([])}})}finally{t.close()}return n}var i4,qD=Te(()=>{"use strict";y();i4=typeof indexedDB<"u"?indexedDB:null});var Ob,Db,HD=Te(()=>{"use strict";y();Ob=e=>{try{return typeof structuredClone=="function"?structuredClone(e):e}catch{return e}},Db=class{constructor(t,n){this.name=t;this.backend=n}name;backend;stores=new Map;loading=new Map;async ensureLoaded(t){let n=await this.backend.listStores();await Promise.all([...new Set([...t,...n])].map(r=>this.loadStore(r)))}loadStore(t){let n=this.loading.get(t);return n||(n=this.backend.load(t).then(r=>{let i=this.stores.get(t);if(!i){this.stores.set(t,r);return}for(let[o,a]of r)i.has(o)||i.set(o,a)}),this.loading.set(t,n)),n}map(t){let n=this.stores.get(t);return n||(n=new Map,this.stores.set(t,n),this.loadStore(t)),n}importRows(t,n){let r=this.map(t),i=0;for(let o of n){let a=o?.key;a!==void 0&&(r.set(String(a),o),i+=1)}return this.backend.persist(t,r,"all"),i}snapshot(){let t={};for(let[n,r]of this.stores)t[n]=[...r.values()];return t}flush(t){return this.backend.flush(t)}touch(t,n="all"){this.backend.persist(t,this.map(t),n)}ready(t){return this.map(t),this.loadStore(t)}async read(t,n){return await this.ready(t),Ob(this.map(t).get(n))}async readMany(t,n){await this.ready(t);let r=this.map(t);return n.map(i=>Ob(r.get(i)))}async readAll(t){await this.ready(t);let n=this.map(t);return[...n.keys()].sort().map(r=>Ob(n.get(r)))}async keysOf(t){return await this.ready(t),[...this.map(t).keys()].sort()}async write(t,n){await this.ready(t);let r=this.map(t);for(let[i,o]of n)r.set(i,Ob(o));this.touch(t,n.map(([i])=>i))}async remove(t,n){await this.ready(t);let r=this.map(t);for(let i of n)r.delete(i);this.touch(t,n)}async clearStore(t){await this.ready(t),this.map(t).clear(),this.touch(t,"all")}}});function VD(){return bce}var bce,KD=Te(()=>{"use strict";y();bce=null});var qh,yc,oa,JD,QD,Cce,aa,zD,Lr,vce,Ace,eR,c4,l4,jD,$l,u4,tR,Hh,Ie,If,Lb,nR,rR,Sce,o4,a4,iR,XD,Rb,s4,oR,Tce,Ece,sa,hc,Bh,kce,Vh,Nb,mc,Bb,d4,aR,f4,_ce,Ice,WD,p4,sR,Fh,Pce,xce,Mce,cR,lR,Uh,$h,GD,Fb,uR,Oce,Dce,Rce,Nce,Lce,Bce,Fce,dR,fR,Ub,Uce,ql,pR,$ce,YD,ZD,qce,$b=Te(()=>{y();qh=Object.freeze,yc=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,oa=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,JD=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,QD=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,Cce=qh({p:yc,n:oa,h:1n,a:0n,b:7n,Gx:JD,Gy:QD}),aa=32,zD=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,Lr=(e,t,n="")=>{if(zD(e)&&(t===void 0||e.length===t))return e;let r=zD(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=(n?`"${n}" `:"")+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)},vce=e=>Uint8Array.from(e),Ace=(e,t,n)=>vce(Lr(e,n,t)),eR=(e,t)=>e.toString(16).padStart(t,"0"),c4=e=>{let t="";for(let n of Lr(e))t+=eR(n,2);return t},l4=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let n=new Uint8Array(e.length/2);for(let r=0,i=0;r>6)*9)*16+(a&15)+(a>>6)*9}return n},jD=()=>{let e=globalThis?.crypto?.subtle;if(e)return e;throw new Error("crypto.subtle must be defined, consider polyfill")},$l=(...e)=>{let t=0;for(let i of e)t+=Lr(i).length;let n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n},u4=(e=aa)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},tR=BigInt,Hh=(e,t,n,r="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(r);if(t<=e&&e(e%=t)>=0n?e:t+e,If=e=>Ie(e,oa),Lb=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let n=Ie(e,t),r=t,i=0n,o=1n;for(;n!==0n;){let s=r/n,c=r-n*s,l=i-o*s;r=n,n=c,i=o,o=l}if(r!==1n)throw new Error("invert: does not exist");return Ie(i,t)},nR=e=>{let t=Fb[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},rR=(e,t,n)=>Lr(nR(e)(t,n),aa,"digest"),Sce=async(e,t,n)=>Lr(await nR(e)(t,n),aa,"digest"),o4=e=>{if(e instanceof sa)return e;throw new TypeError("Point expected")},a4="bad point: not on curve",iR=e=>Ie(Ie(e*e)*e+7n),XD=e=>Hh(e,0n,yc),Rb=e=>Hh(e,1n,yc),s4=e=>Hh(e,1n,oa),oR=e=>!(e&1n),Tce=e=>Uint8Array.of(oR(e)?2:3),Ece=e=>{let t=iR(Rb(e)),n=1n;for(let r=t,i=(yc+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%yc),r=r*r%yc;if(Ie(n*n)!==t)throw new Error("sqrt invalid");return new sa(e,oR(n)?n:Ie(-n),1n)},sa=class e{static BASE;static ZERO;X;Y;Z;constructor(t,n,r){this.X=XD(t),this.Y=Rb(n),this.Z=XD(r),qh(this)}static CURVE(){return Cce}static fromAffine(t){let{x:n,y:r}=t;return n===0n&&r===0n?Bh:new e(n,r,1n)}static fromBytes(t){Lr(t);let n=t.length,r=t[0],i=Nb(t,1,33);try{if(n===33&&(r===2||r===3)){let o=Ece(i);return r===3?o.negate():o}if(n===65&&r===4)return new e(i,Nb(t,33,65),1n).assertValidity()}catch{throw new Error(a4)}throw new Error(a4)}static fromHex(t){return e.fromBytes(l4(t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(t){let{X:n,Y:r,Z:i}=this,{X:o,Y:a,Z:s}=o4(t);return Ie(n*s)===Ie(o*i)&&Ie(r*s)===Ie(a*i)}is0(){return this.Z===0n}negate(){return new e(this.X,Ie(-this.Y),this.Z)}double(){return this.add(this)}add(t){let{X:n,Y:r,Z:i}=this,{X:o,Y:a,Z:s}=o4(t),c=0n,l=7n,u=0n,d=0n,p=0n,h=Ie(l*3n),g=Ie(n*o),w=Ie(r*a),T=Ie(i*s),k=Ie(n+r),B=Ie(o+a);k=Ie(k*B),B=Ie(g+w),k=Ie(k-B),B=Ie(n+i);let D=Ie(o+s);return B=Ie(B*D),D=Ie(g+T),B=Ie(B-D),D=Ie(r+i),u=Ie(a+s),D=Ie(D*u),u=Ie(w+T),D=Ie(D-u),p=Ie(c*B),u=Ie(h*T),p=Ie(u+p),u=Ie(w-p),p=Ie(w+p),d=Ie(u*p),w=Ie(g+g),w=Ie(w+g),T=Ie(c*T),B=Ie(h*B),w=Ie(w+T),T=Ie(g-T),T=Ie(c*T),B=Ie(B+T),g=Ie(w*B),d=Ie(d+g),g=Ie(D*B),u=Ie(k*u),u=Ie(u-g),g=Ie(k*w),p=Ie(D*p),p=Ie(p+g),new e(u,d,p)}subtract(t){return this.add(o4(t).negate())}multiply(t,n=!0){if(!n&&t===0n)return Bh;if(s4(t),t===1n)return this;if(this.equals(hc))return qce(t).p;let r=Bh,i=hc,o=this;for(let a=0;n?a<256:t>0n;a++)t&1n?r=r.add(o):n&&(i=i.add(o)),o=o.double(),t>>=1n;return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(r===0n)return{x:0n,y:0n};if(r===1n)return{x:t,y:n};let i=Lb(r,yc);if(Ie(r*i)!==1n)throw new Error("inverse invalid");return{x:Ie(t*i),y:Ie(n*i)}}assertValidity(){let{x:t,y:n}=this.toAffine();if(Rb(t),Rb(n),Ie(n*n)!==iR(t))throw new Error(a4);return this}toBytes(t=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=mc(n);return t?$l(Tce(r),i):$l(Uint8Array.of(4),i,mc(r))}toHex(t){return c4(this.toBytes(t))}},hc=new sa(JD,QD,1n),Bh=new sa(0n,1n,0n);sa.BASE=hc;sa.ZERO=Bh;kce=(e,t,n)=>hc.multiply(t,!1).add(e.multiply(n,!1)).assertValidity(),Vh=e=>tR("0x"+(c4(e)||"0")),Nb=(e,t,n)=>Vh(e.subarray(t,n)),mc=e=>l4(eR(Hh(e,0n,2n**256n),aa*2)),Bb=e=>{let t=Vh(Lr(e,aa,"secret key"));return Hh(t,1n,oa,"invalid secret key: outside of range")},d4=e=>e>oa>>1n,aR=(e,t,n)=>(e===n?0:2)|Number(t&1n),f4=(e,t=!0)=>hc.multiply(Bb(e)).toBytes(t),_ce=e=>{try{return!!Bb(e)}catch{return!1}},Ice=(e,t)=>{try{let n=e.length;return t===!0&&n!==33||t===!1&&n!==65?!1:!!sa.fromBytes(e)}catch{return!1}},WD=e=>{if(e!=null&&[0,1,2,3].includes(e))return e;throw new Error("invalid recovery id")},p4=e=>{if(e==="der")throw new Error('Signature format "der" is not supported: switch to noble-curves');if(e!=null&&e!==Uh&&e!==$h)throw new Error("Signature format must be one of: compact, recovered, der")},sR=(e,t=Uh)=>{p4(t);let n=Lr(e,void 0,"signature"),r=64+ +(t===$h);if(n.length!==r)throw new Error(`Signature format "${t}" expects Uint8Array with length ${r}`);return n},Fh=class e{r;s;recovery;constructor(t,n,r){this.r=s4(t),this.s=s4(n),r!=null&&(this.recovery=WD(r)),qh(this)}static fromBytes(t,n=Uh){t=sR(t,n);let r;n===$h&&(r=t[0],t=t.subarray(1));let i=Nb(t,0,aa),o=Nb(t,aa,64);return new e(i,o,r)}addRecoveryBit(t){return new e(this.r,this.s,t)}hasHighS(){return d4(this.s)}toBytes(t=Uh){p4(t);let{r:n,s:r,recovery:i}=this,o=$l(mc(n),mc(r));return t===$h?$l(Uint8Array.of(WD(i)),o):o}},Pce=8192,xce="input is too large",Mce=(e,t)=>!t&&e.length>Pce,cR=e=>{if(Mce(e))throw new Error(xce);let t=e.length*8-256,n=Vh(e);return t>0?n>>tR(t):n},lR=e=>If(cR(Lr(e))),Uh="compact",$h="recovered",GD="SHA-256",Fb={hmacSha256Async:async(e,t)=>{let n=jD(),r=await n.importKey("raw",e,{name:"HMAC",hash:GD},!1,["sign"]);return new Uint8Array(await n.sign("HMAC",r,t))},hmacSha256:void 0,sha256Async:async e=>new Uint8Array(await jD().digest(GD,e)),sha256:void 0},uR=(e,t,n)=>{let r=Lr(e,void 0,"message");return t?n?Sce("sha256Async",r):rR("sha256",r):r},Oce=new Uint8Array(0),Dce=Uint8Array.of(0),Rce=Uint8Array.of(1),Nce="drbg: tried max amount of iterations",Lce=(e,t)=>{let n=new Uint8Array(aa),r=new Uint8Array(aa),i=0,o=()=>{n.fill(1),r.fill(0)},a=(...u)=>rR("hmacSha256",r,$l(n,...u)),s=(u=Oce)=>{r=a(Dce,u),n=a(),u.length!==0&&(r=a(Rce,u),n=a())},c=()=>{if(i++>=1e3)throw new Error(Nce);return n=a(),n};o(),s(e);let l;for(;!(l=t(c()));)s();return o(),l},Bce=(e,t,n,r)=>{let[i,,o,a]=n,s=lR(e),c=Bb(t),l=[mc(c),mc(s)];a!=null&&a!==!1&&l.push(Lr(a===!0?u4(aa):a,void 0,"extraEntropy"));let u=d=>{let p=cR(d);if(!(1n<=p&&p{let[i,,o]=r;if(e instanceof Fh)throw new Error("Signature must be in Uint8Array, use .toBytes()");sR(e,o),Lr(n,void 0,"publicKey");try{let{r:a,s,recovery:c}=Fh.fromBytes(e,o),l=lR(t),u=sa.fromBytes(n);if(i&&d4(s))return!1;let d=Lb(s,oa),{x:p,y:h}=kce(u,If(l*d),If(a*d)).toAffine();return If(p)!==a?!1:o!==$h||c===aR(p,h,a)}catch{return!1}},dR=(e,t=!1)=>{let n=e.extraEntropy;return[e.lowS??!0,e.prehash??!0,e.format??Uh,t&&n!=null&&typeof n!="boolean"?Ace(n,"extraEntropy"):n]},fR=(e,t,n={})=>{let r=dR(n);p4(r[2]);let i=uR(e,r[1],!1);return Bce(i,t,r,Lce)},Ub=(e,t,n,r={})=>{let i=dR(r),o=uR(t,i[1],!1);return Fce(e,o,n,i)},Uce=e=>{if(e=e===void 0?u4(48):e,Lr(e),e.length<48||e.length>1024)throw new RangeError("expected 48-1024b");let t=Ie(Vh(e),oa-1n);return mc(t+1n)},ql=qh({hexToBytes:l4,bytesToHex:c4,concatBytes:$l,bytesToNumberBE:Vh,numberToBytesBE:mc,mod:Ie,invert:Lb,randomBytes:u4,secretKeyToScalar:Bb,abytes:Lr}),pR=qh({isValidSecretKey:_ce,isValidPublicKey:Ice,randomSecretKey:Uce}),$ce=()=>{let e=[],t=hc,n=t;for(let r=0;r<33;r++){n=t,e.push(n);for(let i=1;i<128;i++)n=n.add(t),e.push(n);t=n.double()}return e},ZD=(e,t)=>{let n=t.negate();return e?n:t},qce=e=>{let t=YD||(YD=$ce()),n=Bh,r=hc;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let a=i*128,s=a+Math.abs(o)-1,c=i%2!==0,l=o<0;o===0?r=r.add(ZD(c,t[a])):n=n.add(ZD(l,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:n,f:r}}});async function qb(e){let t=typeof e=="string"?Hce.encode(e):e,n=await crypto.subtle.digest("SHA-256",t);return Vce(new Uint8Array(n))}var Hce,x2e,Vce,Hb=Te(()=>{"use strict";y();Hce=new TextEncoder,x2e=new TextDecoder,Vce=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")});var yR,Kce,zce,hR=Te(()=>{"use strict";y();yR=e=>`packages/cappz-native/build-wasm.sh (RUSTFLAGS: -C target-feature=+simd128 --cfg getrandom_backend="unsupported"; cargo build --lib --profile wasm --target wasm32-unknown-unknown --locked --no-default-features --features ${e})`,Kce={artifact:"cappz_native.wasm",crate:"cappz-native",version:"0.4.0",target:"wasm32-unknown-unknown +simd128 (feature core)",sha256:"440335ccf32edd944daa631e4e6db77d3352b87307f149b10ad7d19b0f83f586",build:yR("core")},zce={artifact:"cappz_native_sig.wasm",crate:"cappz-native",version:"0.4.0",target:"wasm32-unknown-unknown +simd128 (feature sig)",sha256:"4d8a06ed604d7722797f017c2e2eccec66c1caf4aa80c19170c9cf62ae326555",build:yR("sig")}});var Kh,Vb,mR=Te(()=>{"use strict";y();Kh=new Uint8Array(512),Vb=new Uint8Array(256);{let e=1;for(let t=0;t<255;t++)Kh[t]=e,Vb[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)Kh[t]=Kh[t-255]}});function Wce(e,t,n,r,i,o){if(!(t>0&&t<256&&n>0&&n<256)||e.length!==t*n||r.length!==n*i)throw new Error(`cappz-native gfMatmul: expected ${t}x${n} coeffs and ${n} shards of ${i} bytes`);if(!o)return new Uint8Array(t*i);let a=o.buffer===r.buffer&&o.byteOffset{"use strict";y();Bo();$b();qo();hR();mR();jce=e=>e.digest.length===32&&e.signature.length===64&&(e.publicKey.length===33||e.publicKey.length===65),Xce=e=>e.signature.length===64&&e.publicKey.length===32;Yce={backend:"typescript",features:{simd:!1,shaInstructions:!1,threads:!1,signatures:!1},gfMatmul(e,t,n,r,i,o,a){let s=Wce(e,t,n,r,i,a);s.fill(0);for(let c=0;c_t(e),sha256Chunks(e,t){if(!(t>0))throw new Error("cappz-native sha256Chunks: chunk must be positive");let n=[];for(let r=0;r{e.update(t)},digest:()=>e.digest()}},secp256k1VerifyMany:e=>e.map(t=>{if(!jce(t))return!1;try{return Ub(t.signature,t.digest,t.publicKey,{prehash:!1,lowS:!0})}catch{return!1}}),ed25519VerifyMany:e=>e.map(t=>{if(!Xce(t))return!1;try{return Kn.verify(t.signature,t.message,t.publicKey,{zip215:!1})}catch{return!1}})},Zce=Yce});async function zh(e,t){let n=_t(new TextEncoder().encode(t)),r=fR(n,e,{lowS:!0});return ql.bytesToHex(r)}async function jh(e,t,n){try{let r=_t(new TextEncoder().encode(e)),i=Kb();return i.backend!=="typescript"?i.secp256k1VerifyMany([{digest:_t(r),signature:ql.hexToBytes(t),publicKey:ql.hexToBytes(n)}])[0]:Ub(ql.hexToBytes(t),r,ql.hexToBytes(n))}catch{return!1}}var Jce,zb=Te(()=>{"use strict";y();$b();Bo();uy();Hb();h4();Jce=(...e)=>_t(ql.concatBytes(...e.filter(t=>t instanceof Uint8Array)));Fb.sha256=Jce;Fb.hmacSha256=((e,t)=>Na(_t,e,t))});async function Qce(e){let{chainletStorage:t}=await Promise.resolve().then(()=>(gc(),Xh));return await t.getItem(`${wR}${e}`)??[]}async function bR(e){let t=VD();if(!t)return null;let n=await Qce(t.address),r=n.at(-1)?.contentHash??null,i=`${vT(t.address,$O)}/storage/events`,o=await qb(JSON.stringify({address:i,owner:t.address,predecessor:r,event:e,governingPrinciple:gR})),a=await zh(t.privateKey,o),s={address:i,owner:t.address,event:e,contentHash:o,predecessor:r,signature:a,governingPrinciple:gR,status:"local-pending"},{chainletStorage:c}=await Promise.resolve().then(()=>(gc(),Xh));await c.setItem(`${wR}${t.address}`,[...n,s]);let{flushActiveKvEngine:l}=await Promise.resolve().then(()=>(m4(),vR));return await l(),typeof window<"u"&&window.dispatchEvent(new Event("cappz:storage-evidence-updated")),s}var gR,wR,CR=Te(()=>{"use strict";y();pf();KD();zb();Hb();gR="m/44'/144'/100'/principles/cope/v1",wR="cappz:storage-evidence/"});var vR={};Tr(vR,{__resetEngineForTests:()=>ale,activeEngineKind:()=>ile,appendEngineEvent:()=>Gh,defaultEngine:()=>TR,flushActiveKvEngine:()=>ole,legacyDatabaseNames:()=>PR,listArchives:()=>_R,openCappzStore:()=>Wb,openKvEngine:()=>xR,readArchive:()=>w4,readEngineEvents:()=>Wh,resolveActiveEngine:()=>kR,resolveEngine:()=>ER,restoreIdbArchive:()=>rle,sealIdbArchive:()=>IR,selectStorageEngine:()=>ele,verifyArchive:()=>nle});async function Wh(){if(!Lh())return g4;let e=await r4(SR);try{return e?JSON.parse(e):[]}catch{return[]}}async function Gh(e){let t=[...await Wh(),e];Lh()?await Mb(SR,JSON.stringify(t)):g4=t;try{await bR(e)}catch(n){console.warn("[cappz-store] wallet evidence deferred",n)}}function TR(){return Lh()?"opfs":"memory"}function ER(e){let t=e.filter(n=>n.eventType==="StorageEngineSelected").at(-1);return!t||t.engine==="idb"||t.engine==="opfs"&&!Lh()?TR():t.engine}function kR(){return jb||(jb=Wh().then(ER).catch(()=>"memory")),jb}async function ele(e,t){await Gh({eventType:"StorageEngineSelected",engine:e,reason:t,timestamp:new Date().toISOString()})}async function tle(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=await crypto.subtle.digest("SHA-256",t.buffer);return[...new Uint8Array(n)].map(r=>r.toString(16).padStart(2,"0")).join("")}function _R(e){return e.filter(t=>t.eventType==="IdbArchiveSealed")}async function IR(e){let t=await $D(e);if(Object.keys(t).length===0)return null;let n=new TextEncoder().encode(JSON.stringify({dbName:e,sealedAt:new Date().toISOString(),stores:t})),r=_R(await Wh()),i=(await ZO()).filter(u=>u.startsWith(`${AR}-v`)).length,o=Math.max(r.length,i)+1,a={slug:AR,version:o,sha256:await tle(n)};if(!await YO(a,n))throw new Error("IdbArchiveSealed failed: could not write archive blob");let c=Object.fromEntries(Object.entries(t).map(([u,d])=>[u,d.length])),l={eventType:"IdbArchiveSealed",ref:a,stores:c,bytes:n.byteLength,timestamp:new Date().toISOString()};return await Gh(l),l}async function w4(e){let t=await _T(e);return t?JSON.parse(new TextDecoder().decode(t)):null}async function nle(e){return await _T(e)!==null}async function rle(e){let t=await w4(e);if(!t)throw new Error("Archive failed hash verification or is missing");let n=await Wb(),r=0,i=0;for(let[o,a]of Object.entries(t.stores)){await n.ready(o);let s=a.filter(c=>!n.map(o).has(String(c.key)));i+=a.length-s.length,r+=n.importRows(o,s)}return await n.flush(),await Gh({eventType:"IdbArchiveRestored",version:e.version,rows:r,timestamp:new Date().toISOString()}),{restored:r,present:i}}function ile(){return Xb}async function ole(e){Xb==="opfs"&&Hl&&await(await Hl).flush(e)}async function Wb(){return xR(Ot(Mt.MiddlewareDbName),Ot(Mt.RequiredStores),await kR())}function PR(e){return[e,Ot(Mt.LegacyDbName)]}function xR(e,t,n){return Hl||(Xb=n,Hl=(async()=>{let r=new Db(e,n==="opfs"?BD():RD());if(await r.ensureLoaded(t),n==="opfs"&&UD()){let i=await Wh(),o=new Set(i.filter(a=>a.eventType==="IdbArchiveImported").map(a=>a.dbName??e));for(let a of PR(e))if(!o.has(a))try{let s=await IR(a),c=0;if(s){let l=await w4(s.ref);for(let[u,d]of Object.entries(l?.stores??{})){await r.ready(u);let p=d.filter(h=>!r.map(u).has(String(h.key)));c+=r.importRows(u,p)}await r.flush()}await Gh({eventType:"IdbArchiveImported",version:s?.ref.version??0,rows:c,dbName:a,timestamp:new Date().toISOString()})}catch(s){console.warn(`[cappz-store] IndexedDB archive/import of ${a} failed; legacy data left untouched`,s)}}return r})(),Hl)}function ale(){Hl=null,Xb=null,g4=[],jb=null}var SR,AR,g4,jb,Hl,Xb,m4=Te(()=>{"use strict";y();JO();FD();qD();HD();CR();Ll();SR="_engine-events.json",AR="idb-archive",g4=[];jb=null;Hl=null,Xb=null});var MR,OR,sle,cle,Yh,DR,lle,ule,Vi,b4,Tt,C4=Te(()=>{"use strict";y();Gb();v4();m4();MR=["session","profile","transactions","appointments","dashboard","kv"],OR=new Set(["session","profile"]),sle={session:1440*60*1e3,profile:10080*60*1e3,transactions:1800*1e3,appointments:3600*1e3,dashboard:900*1e3,kv:1/0},cle=(e,t)=>{let n=t===void 0?sle[e]:t;return n!=null&&Number.isFinite(n)?n:null},Yh=(e,t=Date.now())=>e.ttl!=null&&t-e.cachedAt>e.ttl,DR=(e,t,n,r,i)=>({key:t,value:n,cachedAt:i,ttl:cle(e,r?.ttl),walletAddress:r?.walletAddress}),lle=e=>({put:(t,n)=>e.write(t,n.map(r=>[r.key,r])),get:(t,n)=>e.readMany(t,n),all:t=>e.readAll(t),keys:t=>e.keysOf(t),remove:(t,n)=>e.remove(t,n),clear:t=>e.clearStore(t),flush:t=>e.flush(t)}),ule=null,Vi=()=>ule??=Wb().then(lle),b4=(e,t,n)=>Pf(e,t,n,`${e}/${t}`),Tt={async set(e,t,n,r){let i=await Vi();await i.put(e,[DR(e,t,n,r,Date.now())]),(r?.durable??OR.has(e))&&await i.flush({store:e,keys:[t]}),b4(e,t,"write")},async setMany(e,t,n){if(t.length===0)return;let r=Date.now(),i=await Vi();await i.put(e,t.map(o=>DR(e,o.key,o.value,o,r))),(n?.durable??!0)&&await i.flush({store:e,keys:t.map(o=>o.key)});for(let o of t)b4(e,o.key,"write")},async get(e,t){let[n]=await(await Vi()).get(e,[t]);return n?Yh(n)?(this.delete(e,t).catch(()=>{}),null):n.value:null},async getMany(e,t){if(t.length===0)return[];let n=await(await Vi()).get(e,t),r=Date.now();return n.map(i=>!i||Yh(i,r)?null:i.value)},async keys(e){return(await Vi()).keys(e)},async delete(e,t){let n=await Vi();await n.remove(e,[t]),OR.has(e)&&await n.flush({store:e,keys:[t]}),b4(e,t,"delete")},async entries(e){let t=Date.now();return(await(await Vi()).all(e)).filter(n=>!Yh(n,t)).map(n=>({key:n.key,value:n.value??n.data,walletAddress:n.walletAddress}))},async getByWallet(e,t){let n=Date.now();return(await(await Vi()).all(e)).filter(r=>r.walletAddress===t&&!Yh(r,n)).map(r=>r.value)},async clearStore(e){let t=await Vi();await t.clear(e),await t.flush(),Pf(e,"","clear",`${e}/`)},async clearAll(){let e=await Vi();for(let t of MR)await e.clear(t);await e.flush()},async purgeExpired(){let e=0,t=Date.now(),n=await Vi();for(let r of MR){let i=(await n.all(r)).filter(o=>Yh(o,t)).map(o=>o.key);i.length&&(await n.remove(r,i),e+=i.length)}return e},async flush(){await(await Vi()).flush()}};typeof window<"u"&&setInterval(()=>{Tt.purgeExpired().catch(()=>{})},300*1e3)});var Xh={};Tr(Xh,{chainletStorage:()=>rt,chainletStorageAdapter:()=>fle});var wc,rt,fle,gc=Te(()=>{"use strict";y();C4();Ll();wc=Ot(Mt.KvStoreName),rt={async setItem(e,t,n){await Tt.set(wc,e,t,n)},async setItems(e){await Tt.setMany(wc,e.map(([t,n])=>({key:t,value:n})))},async getItem(e){return Tt.get(wc,e)},async getItems(e){return Tt.getMany(wc,e)},async removeItem(e){await Tt.delete(wc,e)},async keys(){try{return await Tt.keys(wc)}catch{return[]}},async clear(){await Tt.clearStore(wc)},async flush(){await Tt.flush()},async fetchActiveEventTxs(e){let t=`adminqueue:${e}`,n=await Tt.get("kv",t);if(!n?.txHistory?.length)return[];let r=new Set,i=new Set;for(let o of n.txHistory)o.eventType==="DuplicateTxDeprecated"&&(o.supersedesTx&&r.add(o.supersedesTx),o.orgnlMsgId&&i.add(o.orgnlMsgId));return n.txHistory.filter(o=>!r.has(o.msgId)&&!i.has(o.msgId)&&o.eventType!=="DuplicateTxDeprecated"&&o.eventType!=="DuplicateTxRemediationCompleted")},async getByWallet(e){return Tt.getByWallet(wc,e)},async fetchEventsByTarget(e){try{let n=(await rt.keys()).filter(o=>o.startsWith("cappz:event/"));if(!n.length)return[];let r=o=>typeof o!="string"||!o?!1:o===e||o.startsWith(`${e}/`),i=[];return await Promise.all(n.map(async o=>{try{let a=await rt.getItem(o);if(!a||!r(a.targetAddress))return;i.push({msgId:a.txId||a.msgId||o,eventType:a.eventType||"Unknown",timestamp:a.timestamp||new Date().toISOString(),sourceAddress:a.sourceAddress||"",targetAddress:a.targetAddress||"",orgnlMsgId:a.orgnlMsgId,supersedesTx:a.supersedesTx,payload:a.metadata??a.payload??a,metadata:a.metadata??a.payload??a,txHash:a.txHash})}catch{}})),i.sort((o,a)=>{let s=o.timestamp?new Date(o.timestamp).getTime():0;return(a.timestamp?new Date(a.timestamp).getTime():0)-s})}catch{return[]}}},fle={getItem:async e=>await rt.getItem(e),setItem:async(e,t)=>{await rt.setItem(e,t)},removeItem:async e=>{await rt.removeItem(e)}}});var Yb,RR=Te(()=>{"use strict";y();gc();Gb();Yb=class{sessionId;serviceType;domain;hdRoot;_adminQueue=[];_createdAt;constructor(t){this.sessionId=crypto.randomUUID().slice(0,12),this.serviceType=t.serviceType,this.domain=t.domain??"global",this.hdRoot=`m/44'/144'/0'/cappz/sync/infra/${this.serviceType}/${this.domain}/${this.sessionId}`,this._createdAt=new Date().toISOString()}async emitLifecycleTx(t,n){let r={txId:crypto.randomUUID(),eventType:t,serviceType:this.serviceType,sessionId:this.sessionId,hdAddress:`${this.hdRoot}/admin/${t}`,timestamp:new Date().toISOString(),metadata:n};this._adminQueue.push(r);let i=`cappz:infra/${this.serviceType}/${this.sessionId}/${r.txId}`;return await rt.setItem(i,r),Pf("kv",i,"write",i),r}async sessionCreated(){return this.emitLifecycleTx(`${this.serviceType}SessionCreated`,{domain:this.domain,createdAt:this._createdAt})}async sessionEnded(){return this.emitLifecycleTx(`${this.serviceType}SessionEnded`,{domain:this.domain,adminQueueLength:this._adminQueue.length})}get adminQueueLength(){return this._adminQueue.length}get createdAt(){return this._createdAt}getAdminHistory(){return[...this._adminQueue]}}});var NR={};Tr(NR,{cappzEphemeralStorage:()=>ple});var A4,ple,LR=Te(()=>{"use strict";y();RR();A4=class{_store=new Map;_purgeInterval=null;wallet;constructor(t){this.wallet=new Yb({serviceType:"EphemeralStorage",domain:t??"global"}),typeof window<"u"&&(this._purgeInterval=setInterval(()=>this._purgeTTL(),3e4),window.addEventListener("beforeunload",()=>{this._purgeSessionEnd()}),this.wallet.sessionCreated().catch(()=>{}))}set(t,n,r={}){let i={key:t,value:n,directive:r.directive??"session-end",createdAt:Date.now(),ttlMs:r.ttlMs,walletAddress:r.walletAddress};this._store.set(t,i)}get(t){let n=this._store.get(t);return n?n.directive==="ttl"&&n.ttlMs&&Date.now()-n.createdAt>n.ttlMs?(this._store.delete(t),null):n.value:null}discard(t){return this._store.delete(t)}discardByWallet(t){let n=0;for(let[r,i]of this._store)i.walletAddress===t&&(this._store.delete(r),n++);return n}clear(){this._store.clear()}async endSession(){this._purgeSessionEnd(),await this.wallet.emitLifecycleTx("EphemeralPurgeSessionEnd",{purgedCount:this._store.size})}_purgeTTL(){let t=Date.now();for(let[n,r]of this._store)r.directive==="ttl"&&r.ttlMs&&t-r.createdAt>r.ttlMs&&this._store.delete(n)}_purgeSessionEnd(){for(let[t,n]of this._store)n.directive==="session-end"&&this._store.delete(t)}get size(){return this._store.size}keys(){return Array.from(this._store.keys())}async destroy(){this._purgeInterval&&(clearInterval(this._purgeInterval),this._purgeInterval=null),this._store.clear(),await this.wallet.sessionEnded()}},ple=new A4});function Pf(e,t,n,r){let i=r??t;for(let o of Zh)try{o(e,t,n,i)}catch(a){console.warn("[cappz-store] Listener error:",a)}}function S4(e){return Zh.add(e),()=>{Zh.delete(e)}}function T4(e,t){let n=async(r,i,o,a)=>{if(o!=="clear"&&!(e.store&&r!==e.store)&&!(e.keyPrefix&&!i.startsWith(e.keyPrefix))){if(o==="delete"){t(i,null,a);return}try{let{chainletStorage:s}=await Promise.resolve().then(()=>(gc(),Xh)),c=await s.getItem(a),{cappzEphemeralStorage:l}=await Promise.resolve().then(()=>(LR(),NR));l.set(`managed:${a}`,c,{directive:"ttl",ttlMs:6e4}),t(i,c,a)}catch(s){console.warn("[cappz-store] Managed fetch failed for",a,s)}}};return Zh.add(n),()=>{Zh.delete(n)}}var Zh,v4=Te(()=>{"use strict";y();Zh=new Set});var dle,Gb=Te(()=>{"use strict";y();Ll();v4();dle=Ot(Mt.MiddlewareDbName)});function BR(e,t,n){let r=n?Array.isArray(n)?n:[n]:null,i=T4({keyPrefix:e},(a,s,c)=>{if(r){let u=s&&typeof s=="object"?s.eventType??s.type:void 0;if(!u||!r.includes(u))return}t(a,s,s===null?"delete":"write")}),o=S4((a,s,c,l)=>{c==="delete"&&s.startsWith(e)&&t(s,null,"delete")});return console.log(`[CreateEventSubscription] Subscribed to '${e}'${r?` (events: ${r.join(", ")})`:""}`),()=>{i(),o(),console.log(`[CreateEventSubscription] Unsubscribed from '${e}'`)}}var FR=Te(()=>{"use strict";y();Gb()});function hle(e){return typeof e!="string"||!e.includes("/v1")||yle.test(e)?e:e.includes("/principles/")?e.replace(/\/principles\/([^/]+)\/v1(?=\/)/,"/principles/$1/__KEEP__").replace(UR,"").replace("__KEEP__","v1"):e.replace(UR,"")}function $R(e){if(!e||typeof e!="object")return e;let t=null;for(let n of mle){let r=e[n];if(typeof r=="string"){let i=hle(r);i!==r&&(t=t??{...e,recordedAddressFields:{}},t.recordedAddressFields[n]=r,t[n]=i)}}return t??e}function qR(e){let t=e;if(!t||typeof t!="object"||!t.recordedAddressFields)return e;let{recordedAddressFields:n,...r}=t;return{...r,...n}}var yle,UR,mle,HR=Te(()=>{"use strict";y();yle=/\/principles\/[^/]+\/v1$/,UR=/\/v1(?=\/|$)/g;mle=["walletAddress","address","targetAddress","sourceAddress","bpmnAddress","parentAddress","childAddress","fromAddress","toAddress"]});function Zb(e){let t=xf[e];return t||(VR.test(e)?e.slice(0,-2):e)}function KR(e){return e in xf||VR.test(e)}function Cle(e){return ble[e]??e}function zR(e){return wle.has(e)?e:Cle(e)}function Jb(e){let t=$R(e),n=t;if(!n||typeof n.eventType!="string")return t;let r=Zb(n.eventType);return r===n.eventType?t:{...n,eventType:r,recordedEventType:n.recordedEventType??n.eventType}}function Mf(e){let t=qR(e),n=t;if(!n||typeof n.recordedEventType!="string")return t;let{recordedEventType:r,...i}=n;return{...i,eventType:r}}var E4,gle,wle,xf,ble,VR,Qb=Te(()=>{"use strict";y();HR();E4=["LoginRevokedTx","LoginRestoredTx","SessionsRevokedTx","UserInvitedTx","PageVisitedTx","LoginRecordedTx","AgentRequestRecordedTx","SiteNoticePublishedTx","SiteNoticeWithdrawnTx","SignupClosedTx","SignupOpenedTx","AccountDeclaredTx","ActivityRecordedTx","AgentBoundTx","AgentCommissionCalculatedTx","AllAccessGrantedTx","AllAccessRevokedTx","AssociationCreatedTx","AssociationRemovedTx","BpmnGovernanceBoundTx","CashAppliedTx","CashReceivedTx","ClarificationAnsweredTx","ClarificationRaisedTx","ClientBillingTermsDeclaredTx","CommissionAccruedTx","CommissionAttributionDeclaredTx","CommissionEligibilityPolicyDeclaredTx","CommissionEligibilityResolvedTx","CommissionRuleDeclaredTx","CommissionRuleDeprecatedTx","CommissionRulesetDeclaredTx","CommissionTransferredTx","ConstituencyInviteAcceptedTx","ConstituencyInviteDeclinedTx","ConstituencyInvitedTx","ConstituencyRequestRejectedTx","ConstituencyRequestedTx","ConstituentCompressedTx","ConstituentCreatedTx","ConstituentDeprecatedTx","ConstituentIncludedTx","ConstituentPartiallyTerminatedTx","ConstituentRemovedTx","ConstituentTerminatedTx","ConstituentTruncatedTx","ConstituentsAggregatedTx","ContextTurnAppendedTx","ContractApprovedTx","ContractDocumentIngestedTx","ContractDraftExtractedTx","ContractRejectedTx","ContractValidatedTx","CrmIdentityExportedTx","CrmRecordCorrelatedTx","DealClonedFromTemplateTx","DealCompressedTx","DealCreatedTx","DealDeprecatedTx","DealDraftedTx","DealExecutedTx","DealLegAddedTx","DealLegAmendedTx","DealPartiallyTerminatedTx","DealPayableAccountDeclaredTx","DealSerializedTx","DealTerminatedTx","DealTruncatedTx","DealWalletDeclaredTx","DelegationGrantedTx","DelegationRevokedTx","DeliveryApprovedTx","DeliveryRejectedTx","DeliveryValidatedTx","DocumentArchivedTx","DocumentUploadedTx","DocumentVersionedTx","DomainModelAmendedTx","EmployeeFiredTx","EmployeeHiredTx","EmployeeResignedTx","EventProjectionDeclaredTx","EventProjectionLapsedTx","EventProjectionSatisfiedTx","EventSubscriptionBoundTx","EventSubscriptionUnboundTx","EventTypeRegisteredTx","ExternalMappingDeclaredTx","ExternalRecordCorrelatedTx","ExternalSyncCompletedTx","ExternalSyncFailedTx","ExternalSyncRequestedTx","ExternalSystemRegisteredTx","FormatConfigAmendedTx","FormatConfigDeprecatedTx","FormatConfigTerminatedTx","FunctionDeclaredTx","InferenceModelChangedTx","InferenceResidencyChangedTx","IngestFileUploadedTx","IngestRunExecutedTx","InvoiceApprovedTx","InvoiceIssuedTx","InvoiceVoidedTx","Iso20022MessageAttachedTx","JournalPostedTx","LegPaymentPostedTx","MilestoneAffirmedTx","OntologyNodeAmendedTx","OntologyNodeDeclaredTx","OntologyNodeRetiredTx","PartyDataAmendedTx","PartyDealLinkedTx","PartyPersonAssociationAmendedTx","PartyPersonAssociationCancelledTx","PartyPersonAssociationDeprecatedTx","PartyPersonAssociationTerminatedTx","PartyRecordSupersededTx","PartyRegisteredTx","PartyRoleBoundTx","PartyRoleUnboundTx","PartyWalletDeclaredTx","PayoutCycleSettledTx","PermissionGrantedTx","PermissionRevokedTx","PersonDataAmendedTx","PersonRecordSupersededTx","PersonRegisteredTx","PersonWalletDeclaredTx","PortfolioProvisionedTx","ProcessBoundTx","ProductDeliveredTx","ProjectAmendedTx","ProjectDeliveredTx","ProjectGreenlitTx","ProjectRegisteredTx","ProjectRetiredTx","RecoupmentCreditedTx","RevenuePostedTx","RevenueStreamDeclaredTx","RuleBoundTx","SchemaRegisteredTx","SecurityPrincipalCreatedTx","SecurityPrincipalRevokedTx","SettlementConfirmedTx","SettlementFailedTx","SettlementInstructedTx","SettlementRailDeclaredTx","SkillConstituentIncludedTx","SkillConstituentRemovedTx","TalentPaidTx","TalentPayableRaisedTx","TalentPaymentApprovedTx","TemplateRegisteredTx","UserAliasAmendedTx","UserAliasCreatedTx","UserPowAnchoredTx","VersionPinnedTx","VersionUnpinnedTx","WalletClonedTx","WalletCopiedTx","WalletTemplateRegisteredTx","WalletTierRetypedTx","WalletTierTypedTx"],gle={UserInvitedTx:"MemberInvited",GroupMemberCreated:"GroupMemberAdded",GroupMemberDeactivated:"GroupMemberRemoved",ConstituentCreatedTx:"DealConstituentCreated",ConstituentDeprecatedTx:"DealConstituentDeprecated",ConstituentTerminatedTx:"DealConstituentTerminated",ConstituentPartiallyTerminatedTx:"DealConstituentPartiallyTerminated",ConstituentTruncatedTx:"DealConstituentTruncated",ConstituentCompressedTx:"DealConstituentCompressed"},wle=new Set(["AgentBound","ConstituentRemoved","SkillConstituentIncluded","SkillConstituentRemoved","WalletCloned"]),xf=Object.freeze({...Object.fromEntries(E4.map(e=>[e,gle[e]??e.slice(0,-2)])),GroupMemberCreated:"GroupMemberAdded",GroupMemberDeactivated:"GroupMemberRemoved"}),ble=(()=>{let e={};for(let[t,n]of Object.entries(xf))t.endsWith("Tx")&&!e[n]&&(e[n]=t);return e})(),VR=/^[A-Z][A-Za-z0-9]*[a-z0-9]Tx$/});function Jh(){return vle}var vle,jR,XR=Te(()=>{"use strict";y();vle=null;jR=e=>`pub:${e.replace(/\/+$/,"")}`});function ca(e="routed"){return WR[e]??(e==="direct"?WR.routed:void 0)??Tle}function Sle(){let e=!1,t=()=>e?{data:null,error:GR,count:null}:{data:[],error:null,count:0},n=new Proxy(function(){},{get(r,i){return i==="then"?(o,a)=>Promise.resolve(t()).then(o,a):i==="single"||i==="maybeSingle"?()=>Promise.resolve(e?t():{data:null,error:null}):(...o)=>(typeof i=="string"&&Ale.has(i)&&(e=!0),n)}});return n}var WR,GR,Ale,Tle,YR=Te(()=>{"use strict";y();WR={};GR={message:"no hosted backend registered (local-only)"},Ale=new Set(["insert","update","upsert","delete"]);Tle={from:()=>Sle(),functions:{invoke:async e=>({data:null,error:{message:`${e}: ${GR.message}`}})}}});function Ile(e){return kle.has(e)}function Vl(e,t){return Ile(e)?{store:e,key:t}:{store:"kv",key:`${_le}::${e}::${t}`}}var Ele,kle,_le,ZR=Te(()=>{"use strict";y();Ele=["session","profile","transactions","appointments","dashboard","kv"],kle=new Set(Ele),_le="part"});var Qh,k4,eC,JR=Te(()=>{"use strict";y();Qh=jr(Nr(),1),k4=class e{static instance;client;wallet=null;constructor(){this.client=new Qh.Client("wss://s.altnet.rippletest.net:51233")}static getInstance(){return e.instance||(e.instance=new e),e.instance}async initialize(t){if(this.client.isConnected()||await this.client.connect(),t instanceof Qh.Wallet)this.wallet=t;else if(typeof t=="string"&&t.length>0)this.wallet=Qh.Wallet.fromSeed(t);else{let n=await this.client.fundWallet();this.wallet=n.wallet}}hasSigner(){return this.wallet!==null}async anchorBatch(t){if(!this.wallet)throw new Error("XRPL wallet not initialized");let n={type:"cappz/chainlet-batch/v1",merkleRoot:t.merkleRoot,blockHashes:t.blockHashes,batchSize:t.batchSize,notarizedAt:typeof t.notarizedAt=="number"?new Date(t.notarizedAt).toISOString():t.notarizedAt},r=Buffer.from(JSON.stringify(n),"utf-8").toString("hex").toUpperCase(),i=await this.client.autofill({TransactionType:"Payment",Account:this.wallet.address,Destination:this.wallet.address,Amount:"1",Memos:[{Memo:{MemoType:Buffer.from("cappz-chainlet-batch","utf-8").toString("hex").toUpperCase(),MemoData:r}}]}),o=this.wallet.sign(i),a=await this.client.submitAndWait(o.tx_blob);if(a.result.meta&&typeof a.result.meta=="object")return{txHash:o.hash,ledgerIndex:a.result.ledger_index||0};throw new Error("Failed to anchor batch on XRPL")}async anchorBlock(t,n){if(!this.wallet)throw new Error("XRPL wallet not initialized");let r={chainletId:t.id,blockNumber:n.blockNumber,merkleRoot:n.merkleRoot,hdAddress:n.hdAddress,txCount:n.transactionCount,timestamp:n.timestamp.toISOString(),deps:n.dependencyChain||[]},i=JSON.stringify(r),o=Buffer.from(i).toString("hex").toUpperCase(),a=await this.client.autofill({TransactionType:"Payment",Account:this.wallet.address,Destination:n.hdAddress||this.wallet.address,Amount:"1",Memos:[{Memo:{MemoType:Buffer.from("chainlet-block","utf-8").toString("hex").toUpperCase(),MemoData:o}}]}),s=this.wallet.sign(a),c=await this.client.submitAndWait(s.tx_blob);if(c.result.meta&&typeof c.result.meta=="object")return{txHash:s.hash,ledgerIndex:c.result.ledger_index||0};throw new Error("Failed to anchor block on XRPL")}async anchorDependency(t,n,r){if(!this.wallet)throw new Error("XRPL wallet not initialized");let i={type:"chainlet-dependency",parent:t,child:n,depType:r,timestamp:new Date().toISOString()},o=JSON.stringify(i),a=Buffer.from(o).toString("hex").toUpperCase(),s=await this.client.autofill({TransactionType:"AccountSet",Account:this.wallet.address,Memos:[{Memo:{MemoType:Buffer.from("chainlet-dependency","utf-8").toString("hex").toUpperCase(),MemoData:a}}]}),c=this.wallet.sign(s),l=await this.client.submitAndWait(c.tx_blob);if(l.result.meta&&typeof l.result.meta=="object")return{txHash:c.hash,ledgerIndex:l.result.ledger_index||0};throw new Error("Failed to anchor dependency on XRPL")}async verifyBlockAnchor(t){try{let r=(await this.client.request({command:"tx",transaction:t})).result;if(!r||typeof r!="object")return{isValid:!1};let i=r.Memos;if(!i||!Array.isArray(i)||i.length===0)return{isValid:!1};let o=i[0].Memo;if(!o||!o.MemoData)return{isValid:!1};let a=Buffer.from(o.MemoData,"hex").toString("utf-8");return{isValid:!0,blockData:JSON.parse(a)}}catch(n){return console.error("Error verifying block anchor:",n),{isValid:!1}}}async queryChainletBlocks(t){if(!this.wallet)throw new Error("XRPL wallet not initialized");let n=await this.client.request({command:"account_tx",account:this.wallet.address,limit:100}),r=[],i=n.result?.transactions||[];for(let o of i){let a=o.tx;if(a&&typeof a=="object"){let s=a.Memos;if(s&&Array.isArray(s))for(let c of s){let l=c.Memo;if(l&&l.MemoData)try{let u=Buffer.from(l.MemoData,"hex").toString("utf-8"),d=JSON.parse(u);d.chainletId===t&&r.push({...d,txHash:a.hash,ledgerIndex:a.ledger_index})}catch{}}}}return r.sort((o,a)=>o.blockNumber-a.blockNumber)}async disconnect(){this.client.isConnected()&&await this.client.disconnect()}},eC=k4.getInstance()});var bc,_4=Te(()=>{"use strict";y();Bo();Hn();bc=e=>kc(_t(Xr(e)))});var em,I4,Ao,QR=Te(()=>{"use strict";y();gc();Ll();JR();_4();em="chainlet_outbox_",I4=class{connectivityState={browserOnline:typeof navigator<"u"?navigator.onLine:!0,xrplOnline:!1,lastHeartbeat:0,consecutiveFailures:0};heartbeatTimer=null;flushTimer=null;listeners=[];isDraining=!1;initialized=!1;async init(){this.initialized||(typeof window<"u"&&(window.addEventListener("online",()=>this.handleBrowserOnline(!0)),window.addEventListener("offline",()=>this.handleBrowserOnline(!1))),await this.startHeartbeat(),this.startFlushTimer(),this.initialized=!0,console.log("[ChainletOutbox] Initialized with layered connectivity detection"))}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),typeof window<"u"&&(window.removeEventListener("online",()=>this.handleBrowserOnline(!0)),window.removeEventListener("offline",()=>this.handleBrowserOnline(!1))),this.initialized=!1}handleBrowserOnline(t){let n=this.connectivityState.browserOnline;this.connectivityState.browserOnline=t,!n&&t&&(console.log("[ChainletOutbox] Browser came online, triggering heartbeat"),this.checkXrplHeartbeat()),this.notifyListeners()}async startHeartbeat(){let t=Ot(Mt.HeartbeatIntervalMs);await this.checkXrplHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.checkXrplHeartbeat()},t)}async checkXrplHeartbeat(){if(Ot(Mt.AnchorStrategy)==="off"||!this.connectivityState.browserOnline){this.connectivityState.xrplOnline=!1,this.notifyListeners();return}eC.hasSigner()?(this.connectivityState.xrplOnline=!0,this.connectivityState.lastHeartbeat=Date.now(),this.connectivityState.consecutiveFailures=0):(this.connectivityState.consecutiveFailures++,this.connectivityState.xrplOnline=!1),this.notifyListeners()}isOnline(){return Ot(Mt.AnchorStrategy)==="off"?!1:this.connectivityState.browserOnline&&this.connectivityState.xrplOnline}getConnectivityState(){return{...this.connectivityState}}onConnectivityChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>-1&&this.listeners.splice(n,1)}}notifyListeners(){let t=this.getConnectivityState();this.listeners.forEach(n=>n(t)),t.browserOnline&&t.xrplOnline&&!this.isDraining&&this.drainOutbox()}async enqueue(t){let n={block:t,queuedAt:Date.now(),retryCount:0};await rt.setItem(`${em}${t.blockHash}`,n),console.log(`[ChainletOutbox] Queued block ${t.blockHash.slice(0,12)}\u2026`)}async dequeue(t){await rt.removeItem(`${em}${t}`)}async getQueuedBlocks(){try{let t=await this.getOutboxKeys(),n=[];for(let r of t){let i=await rt.getItem(r);i&&n.push(i)}return n.sort((r,i)=>r.queuedAt-i.queuedAt)}catch{return[]}}async getQueueLength(){return(await this.getOutboxKeys()).length}async getOutboxKeys(){try{return(await rt.keys()).filter(n=>n.startsWith(em))}catch{return[]}}startFlushTimer(){let t=Ot(Mt.OutboxFlushInterval);this.flushTimer=setInterval(()=>{this.isOnline()&&!this.isDraining&&this.drainOutbox()},t)}async drainOutbox(){if(this.isDraining)return 0;if(!this.isOnline())return console.log("[ChainletOutbox] Offline, skipping drain"),0;this.isDraining=!0;let t=0;try{let n=await this.getQueuedBlocks();if(n.length===0)return 0;console.log(`[ChainletOutbox] Draining ${n.length} queued blocks`),Ot(Mt.AnchorStrategy)==="batch"?t=await this.drainBatch(n):t=await this.drainIndividual(n),console.log(`[ChainletOutbox] Drained ${t} blocks`)}catch(n){console.error("[ChainletOutbox] Drain failed:",n)}finally{this.isDraining=!1}return t}async drainIndividual(t){let n=0;for(let r of t)try{await this.anchorBlock(r.block),await this.dequeue(r.block.blockHash),n++}catch(i){console.warn(`[ChainletOutbox] Failed to anchor ${r.block.blockHash}:`,i),r.retryCount++,r.lastError=String(i),await rt.setItem(`${em}${r.block.blockHash}`,r)}return n}async drainBatch(t){let n=Ot(Mt.MaxBatchSize),r=t.slice(0,n);if(r.length===0)return 0;try{let i=r.map(c=>c.block.blockHash),o=this.computeMerkleRoot(i),a=new Date().toISOString(),s=await eC.anchorBatch({merkleRoot:o,blockHashes:i,batchSize:r.length,notarizedAt:a});console.log(`[XRPLChainletAnchor] anchored batch tx=${s.txHash} ledger=${s.ledgerIndex} size=${r.length}`);for(let c of r)c.xrplTxHash=s.txHash,c.xrplLedgerIndex=s.ledgerIndex,await this.dequeue(c.block.blockHash);return r.length}catch(i){console.warn("[ChainletOutbox] Batch anchor failed (will retry):",i);for(let o of r)o.retryCount++,o.lastError=String(i),await rt.setItem(`${em}${o.block.blockHash}`,o);return 0}}async anchorBlock(t){let n=bc(JSON.stringify(t.value)),r=await eC.anchorBatch({merkleRoot:n,blockHashes:[t.blockHash],batchSize:1,notarizedAt:new Date(t.timestamp).toISOString()});console.log(`[XRPLChainletAnchor] anchored individual tx=${r.txHash} ledger=${r.ledgerIndex} block=${t.blockHash.slice(0,12)}\u2026`)}computeMerkleRoot(t){if(t.length===0)return"0".repeat(64);if(t.length===1)return t[0];let n=[];for(let r=0;rtC,blockEntries:()=>Kl,chainletSync:()=>Dle});async function Ple(){if(zl)return zl;let{chainletStorage:e}=await Promise.resolve().then(()=>(gc(),Xh)),t=await e.getItem(eN);return t||(t=`dev_${crypto.randomUUID()}`,await e.setItem(eN,t)),zl=t,t}function xle(){return zl||(zl=`dev_${crypto.randomUUID()}`,Ple().catch(()=>{}),zl)}function tN(e){let t=JSON.stringify({store:e.store,key:e.key,value:e.value,deviceId:e.deviceId,timestamp:e.timestamp,hdAddress:e.hdAddress,previousHash:e.previousHash,previousHdAddress:e.previousHdAddress,meta:e.meta??null});return bc(t)}function nN(e,t,n){return`${e}/${t}/${n}`}function Mle(e,t,n){let r=bc(JSON.stringify({key:t,value:n}));return`${e}/tpl/${r.slice(0,32)}`}function Ole(e){return`tpl_${bc(e).slice(0,24)}`}function Kl(e){return e.batch?(e.value?.entries??[]).map(n=>({store:e.store,key:n.key,value:n.value})):[{store:e.store,key:e.key,value:e.value}]}var eN,zl,tC,Of,P4,Dle,rC=Te(()=>{"use strict";y();YR();C4();ZR();Ll();QR();_4();eN="cappz_device_id",zl=null;tC=class extends Error{constructor(n,r){super(n);this.details=r}details;name="OptimisticConcurrencyError"};Of="sync",P4=class{deviceId=xle();headHash=Ot(Mt.GenesisHash);headAddress="";blockCount=0;walletAddress;initialized=!1;async init(t={}){if(this.initialized)return;this.walletAddress=t.walletAddress,await Ao.init();let n=await Tt.get("kv",`sync_head_${this.deviceId}`);n&&(this.headHash=n.headHash,this.headAddress=n.headAddress??"",this.blockCount=n.blockCount),this.initialized=!0;let r=await Ao.getQueueLength();console.log(`[ChainletSync] Initialized device=${this.deviceId.slice(0,12)}\u2026 blocks=${this.blockCount} queued=${r}`)}async set(t,n,r,i){await this.ensureInit();let o=Ot(Mt.HdAddressRoot),a=Ot(Mt.UseCloudPersistence),s=!!i?.templateRoot,c=i?.previousVersion??{address:this.headAddress,hash:this.headHash},l=null;a&&!s&&(l=await this.getLatestRemotePointer(t,n));let u;if(l&&l.hash!==c.hash)if(i?.onConflict==="branch")u={branchId:i.branchId??`br_${Date.now().toString(36)}`,expectedBase:c,actualHead:l};else throw new tC(`Concurrent update detected for ${t}:${n}`,{store:t,key:n,expected:c,actual:l});let d=Date.now(),p=s?Mle(i.templateRoot,n,r):nN(o,this.deviceId,d),h={store:t,key:n,value:r,deviceId:s?"template":this.deviceId,timestamp:s?0:d,hdAddress:p,previousHash:s?"":c.hash,previousHdAddress:s?"":c.address,partitionKey:s?Ole(i.templateRoot):`${Of}_${this.deviceId}`,meta:u},g=tN(h),w={...h,blockHash:g};await this.persistBlock(w),s||(this.headHash=g,this.headAddress=p,this.blockCount++,await Tt.set("kv",`sync_head_${this.deviceId}`,{headHash:this.headHash,headAddress:this.headAddress,blockCount:this.blockCount}));let T=Vl(t,n);return await Tt.set(T.store,T.key,r,{walletAddress:this.walletAddress}),s||(await Tt.set("kv",`sync_ptr_${t}:${n}`,{address:p,hash:g}),this.fetchContent(p).catch(()=>{})),g}async prepareBatch(t,n){await this.ensureInit();let r=Ot(Mt.HdAddressRoot),i=Date.now(),o=nN(r,this.deviceId,i),a={store:t,key:`batch:${i}:${n.length}`,value:{entries:n},deviceId:this.deviceId,timestamp:i,hdAddress:o,previousHash:this.headHash,previousHdAddress:this.headAddress,partitionKey:`${Of}_${this.deviceId}`,batch:!0},s=tN(a),c={...a,blockHash:s},l=this.blockCount+1,u=[[`syncblock_${s}`,c],[`sync_head_${this.deviceId}`,{headHash:s,headAddress:o,blockCount:l}]];return{block:c,kvRows:u,commit:async()=>{this.headHash=s,this.headAddress=o,this.blockCount=l,await this.anchorRemote(c)}}}async getVersionPointer(t,n){return Tt.get("kv",`sync_ptr_${t}:${n}`)}isOnline(){return Ao.isOnline()}getConnectivityState(){return Ao.getConnectivityState()}onConnectivityChange(t){return Ao.onConnectivityChange(t)}async getOutboxLength(){return Ao.getQueueLength()}async flushOutbox(){return Ao.drainOutbox()}async get(t,n){await this.ensureInit();let r=Vl(t,n),i=await Tt.get(r.store,r.key);return i!==null?i:Ot(Mt.UseCloudPersistence)?this.queryCloudBlock(t,n):null}async delete(t,n){await this.set(t,n,null);let r=Vl(t,n);await Tt.delete(r.store,r.key)}async getBlocksSince(t){if(!Ot(Mt.UseCloudPersistence))return[];let{data:r,error:i}=await ca("direct").from("chainlet_blocks").select("metadata, block_hash, previous_hash, timestamp, block_number").eq("query_hash",`${Of}_${this.deviceId}`).order("block_number",{ascending:!0});if(i||!r)return[];let o=[],a=t==="0".repeat(64);for(let s of r){if(!a){(s.previous_hash===t||s.block_hash===t)&&(a=!0);continue}let c=s.metadata;c?.syncBlock&&o.push(c.syncBlock)}return o}async applyRemoteBlocks(t){let n=0,r=[...t].sort((i,o)=>i.timestamp-o.timestamp);for(let i of r){for(let o of Kl(i)){let a=Vl(o.store,o.key);o.value===null?await Tt.delete(a.store,a.key):await Tt.set(a.store,a.key,o.value,{walletAddress:this.walletAddress})}n++}return console.log(`[ChainletSync] Applied ${n} remote blocks`),n}async ensureInit(){this.initialized||await this.init({walletAddress:this.walletAddress})}async persistBlock(t){await Tt.set("kv",`syncblock_${t.blockHash}`,t),await this.anchorRemote(t)}async anchorRemote(t){let n=Ot(Mt.UseCloudPersistence),r=Ot(Mt.AutoSyncWithBlockchain);if(!n)return;if(!Ao.isOnline()||!r){await Ao.enqueue(t);return}let i=bc(JSON.stringify(t.value)),{error:o}=await ca("direct").from("chainlet_blocks").insert([{block_number:this.blockCount,block_hash:t.blockHash,previous_hash:t.previousHash,merkle_root:i,timestamp:new Date(t.timestamp).toISOString(),transaction_count:Kl(t).length,transactions:t.batch?{type:"sync_batch",store:t.store,keys:Kl(t).map(a=>a.key)}:{type:"sync_write",store:t.store,key:t.key},anchor_block:{deviceId:t.deviceId,synced:!0},query_hash:t.partitionKey??`${Of}_${this.deviceId}`,metadata:{syncBlock:JSON.parse(JSON.stringify(t))},hd_address:t.hdAddress,hd_block_index:this.blockCount}]);o&&(console.warn("[ChainletSync] Cloud persist failed, queuing to outbox:",o.message),await Ao.enqueue(t))}async getLatestRemotePointer(t,n){let r=await Tt.get("kv",`sync_ptr_${t}:${n}`);if(r?.address){let i=await this.checkForAmendmentEvent(r.address);if(i)return i;let o=await this.verifyCreationEventHash(r);if(o&&o.hash!==r.hash)return o}return this.scanRecentBlocksForPointer(t,n)}async checkForAmendmentEvent(t){let n=ST("ContentAmended"),{data:r,error:i}=await ca("direct").from("lifecycle_events").select("entity_id, event_type, event_data, created_at").in("event_type",n).order("created_at",{ascending:!1}).limit(100);if(i||!r)return null;for(let o of r){let a=o.event_data;if((a?.parent_hd_address??a?.target_address??a?.prevVersionAddress)===t){let c=a?.hd_address??a?.new_version_address,l=a?.content_hash??a?.version_hash??a?.blockHash;if(c&&l)return{address:String(c),hash:String(l)};let{data:u}=await ca("direct").from("chainlet_blocks").select("block_hash, hd_address").eq("metadata->>entityId",o.entity_id).maybeSingle();if(u?.hd_address)return{address:u.hd_address,hash:u.block_hash}}}return null}async verifyCreationEventHash(t){let n=ST("ContentCreated"),{data:r,error:i}=await ca("direct").from("lifecycle_events").select("entity_id, event_type, event_data, created_at").in("event_type",n).order("created_at",{ascending:!1}).limit(100);if(i||!r)return null;for(let a of r){let s=a.event_data;if((s?.hd_address??s?.hdAddress??s?.address)===t.address){let l=s?.content_hash??s?.version_hash??s?.blockHash;if(l)return{address:t.address,hash:String(l)}}}let{data:o}=await ca("direct").from("chainlet_blocks").select("block_hash, merkle_root").eq("hd_address",t.address).maybeSingle();return o?{address:t.address,hash:o.block_hash}:null}async scanRecentBlocksForPointer(t,n){let{data:r,error:i}=await ca("direct").from("chainlet_blocks").select("block_hash, hd_address, timestamp, metadata").like("query_hash",`${Of}_%`).order("timestamp",{ascending:!1}).limit(500);if(i||!r)return null;for(let o of r){let a=o.metadata,s=a?.syncBlock;if(s?.store===t&&Kl(s).some(c=>c.key===n))return{address:o.hd_address??a.syncBlock.hdAddress??"",hash:a.syncBlock.blockHash??o.block_hash}}return null}async fetchContent(t){if(!Ot(Mt.UseCloudPersistence))return;let{data:r,error:i}=await ca("direct").from("chainlet_blocks").select("metadata").eq("hd_address",t).maybeSingle();if(i||!r)return;let a=(r.metadata??{}).syncBlock;if(!(!a?.store||!a?.key))for(let s of Kl(a)){let c=Vl(s.store,s.key);s.value===null?await Tt.delete(c.store,c.key):await Tt.set(c.store,c.key,s.value,{walletAddress:this.walletAddress}),await Tt.set("kv",`sync_ptr_${s.store}:${s.key}`,{address:a.hdAddress??t,hash:a.blockHash})}}async queryCloudBlock(t,n){let{data:r,error:i}=await ca("direct").from("chainlet_blocks").select("metadata, block_hash, hd_address, timestamp").like("query_hash",`${Of}_%`).order("timestamp",{ascending:!1}).limit(500);if(i||!r)return null;for(let o of r){let s=o.metadata?.syncBlock,c=s&&s.store===t?Kl(s).find(l=>l.key===n):void 0;if(s&&c){let l=s,u=c.value;if(u!==null){let d=Vl(t,n);await Tt.set(d.store,d.key,u,{walletAddress:this.walletAddress})}return await Tt.set("kv",`sync_ptr_${t}:${n}`,{address:l.hdAddress??o.hd_address??"",hash:l.blockHash??o.block_hash}),u}}return null}},Dle=new P4});function rN(e){return(iN.get(e)??[]).map(t=>({...t}))}function iC(e,t){let n=new Map;for(let r of t)n.set(r.txId,r);iN.set(e,Array.from(n.values()).sort((r,i)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime()))}var iN,jl,x4=Te(()=>{"use strict";y();FR();gc();Ll();Qb();XR();iN=new Map;jl=class{constructor(t,n,r={}){this.hdAddress=t;this.cachePrefix=n;this.options=r;this._indexKey=`${n}__index__`}hdAddress;cachePrefix;options;_cache=[];_hydrated=!1;_inflight=null;_indexKey;_sharedAt=0;_sharedPull=null;_sharedTxIds=new Set;_sharedState="local-only";get sharedPartition(){return jR(this.hdAddress)}get sharedState(){return this._sharedState}async refresh(){let t=await this._refreshLocal();if(!this.options.shared||!Jh()||Date.now()-this._sharedAt<(this.options.sharedTtlMs??6e4))return t;let n=this._pullShared();return await Promise.race([n,new Promise(r=>setTimeout(r,this.options.sharedWaitMs??8e3))]),[...this._cache]}async _refreshLocal(){return this._hydrated?this._mergeMemorySnapshot():this._inflight?this._inflight:(this._inflight=this._refreshFromStore().finally(()=>{this._inflight=null}),this._inflight)}_pullShared(){let t=Jh();return t?this._sharedPull?this._sharedPull:(this._sharedPull=(async()=>{try{let n=await t.pull(this.sharedPartition);this._sharedTxIds=new Set(n.map(o=>o.entry.txId));let r=new Set(this._cache.map(o=>o.txId)),i=[];for(let o of n)r.has(o.entry.txId)||(r.add(o.entry.txId),i.push(Jb(o.entry)));i.length&&await this._keepLocally(i),this._sharedState="synced"}catch(n){this._sharedState="unreachable",console.warn(`[CappzEventCache] Shared log unreachable for ${this.cachePrefix}; showing the device copy`,n)}finally{this._sharedAt=Date.now(),this._sharedPull=null}})(),this._sharedPull):Promise.resolve()}async _keepLocally(t){let n=t.map(a=>({txId:a.txId,key:`${this.cachePrefix}${a.txId}`})),r=await rt.getItem(this._indexKey)??[],i=new Map(r.map(a=>[a.txId,a]));for(let a of n)i.set(a.txId,a);await rt.setItems([...n.map((a,s)=>[a.key,Mf(t[s])]),[this._indexKey,[...i.values()]]]);let o=new Set(this._cache.map(a=>a.txId));for(let a of t)o.has(a.txId)||this._cache.push(a);this._cache.sort((a,s)=>new Date(a.timestamp).getTime()-new Date(s.timestamp).getTime()),iC(this.cachePrefix,this._cache),this._hydrated=!0}unshared(t){return this._sharedState!=="synced"?[]:this._cache.filter(n=>t(n)&&!this._sharedTxIds.has(n.txId))}async shareExisting(t){let n=Jh();if(!this.options.shared||!n)return 0;this._sharedState!=="synced"&&(this._sharedAt=0,await this._pullShared());let r=this.unshared(t);if(!r.length)return 0;await n.publish(this.sharedPartition,r.map(i=>Mf(i)));for(let i of r)this._sharedTxIds.add(i.txId);return r.length}_mergeMemorySnapshot(){let t=rN(this.cachePrefix);if(t.length>0){let n=new Set(this._cache.map(i=>i.txId)),r=t.filter(i=>!n.has(i.txId));r.length>0&&(this._cache=[...this._cache,...r].sort((i,o)=>new Date(i.timestamp).getTime()-new Date(o.timestamp).getTime()))}return[...this._cache]}async _refreshFromStore(){try{let t=await rt.getItem(this._indexKey),n=(await rt.keys()).filter(c=>c.startsWith(this.cachePrefix)&&c!==this._indexKey),r=new Map((t??[]).map(c=>[c.key,c])),i=n.map(c=>r.get(c)??{txId:c.slice(this.cachePrefix.length),key:c});if(i.length!==(t?.length??0)&&await rt.setItem(this._indexKey,i),i?.length)return this._hydrateFromIndex(i);let o,a=await Promise.race([this._recoverFromChainlet(),new Promise(c=>{o=setTimeout(()=>{console.warn(`[CappzEventCache] Durable recovery timed out for ${this.cachePrefix}`),c([])},8e3)})]).finally(()=>clearTimeout(o));if(a.length>0)return console.log(`[CappzEventCache] Recovered ${a.length} entries from durable chainlet for ${this.cachePrefix}`),await this._rebuildLocalIndex(a),this._cache=a.map(c=>Jb(c)).sort((c,l)=>new Date(c.timestamp).getTime()-new Date(l.timestamp).getTime()),this._hydrated=!0,[...this._cache];let s=rN(this.cachePrefix);return s.length>0?(this._cache=s,this._hydrated=!0,[...this._cache]):this._cache.length>0?(console.warn(`[CappzEventCache] DRIFT: local cache has ${this._cache.length} entries for ${this.cachePrefix} but durable chainlet returned 0. Fresh browsers will see an empty cache. Check RLS / sync writer key shape.`),this._hydrated=!0,[...this._cache]):(this._hydrated=!0,[])}catch{return this._hydrated=!0,this._cache.length>0?[...this._cache]:[]}}async FetchEvents(t){this._hydrated||await this.refresh();let n=[...this._cache];if(n=n.filter(r=>{let i=r.sourceAddress,o=r.targetAddress;return i&&i.startsWith(t.rootHdAddress)||o&&o.startsWith(t.rootHdAddress)}),t.eventTypes?.length){let r=new Set(t.eventTypes);n=n.filter(i=>r.has(i.eventType??""))}if(t.since){let r=new Date(t.since).getTime();n=n.filter(i=>new Date(i.timestamp).getTime()>r)}return n}async FetchNewEvents(t,n){this._hydrated||await this.refresh();let r=new Set(t);return this._cache.filter(i=>{let o=i.sourceAddress,a=i.targetAddress,s=o&&r.has(o),c=a&&r.has(a);if(!s&&!c)return!1;let l=new Date(i.timestamp).getTime(),u=s?o:a,d=n.get(u);return d?l>new Date(d).getTime():!0})}getCached(){return[...this._cache]}async hydrateFromWalletPartition(t){return t.length===0?0:Ot(Mt.UseCloudPersistence)?(this._hydrated=!0,0):(this._hydrated=!0,0)}async append(t,n){if(n?.share)return this.appendMany([t],{requireDurable:n.requireDurable??!0,share:!0});let r=`${this.cachePrefix}${t.txId}`;this._cache.some(o=>o.txId===t.txId)||this._cache.push(t),iC(this.cachePrefix,this._cache),n?.requireDurable?(await rt.setItem(r,t),await this._updateIndex(t.txId,r)):rt.setItem(r,t).then(()=>this._updateIndex(t.txId,r)).catch(()=>{});let i=Promise.resolve().then(()=>(rC(),nC)).then(({chainletSync:o})=>o.set(this.hdAddress,r,t));n?.requireDurable?await i.catch(o=>{throw new Error(`[CappzEventCache] Durable chainlet anchor failed for ${t.txId}: ${o instanceof Error?o.message:String(o)}`)}):i.catch(o=>{console.warn(`[CappzEventCache] Chainlet anchor failed for ${t.txId}`,o)})}async appendMany(t,n){let r=new Set(this._cache.map(l=>l.txId)),i=[];for(let l of t)r.has(l.txId)||(r.add(l.txId),i.push(l));if(!i.length)return;if(n?.share){let l=Jh();if(!this.options.shared||!l)throw new Error(`[CappzEventCache] ${this.cachePrefix} is not a shared log here; the write was not made.`);await l.publish(this.sharedPartition,i.map(u=>Mf(u)));for(let u of i)this._sharedTxIds.add(u.txId)}let o=i.map(l=>({txId:l.txId,key:`${this.cachePrefix}${l.txId}`})),a=()=>{for(let l of i)this._cache.push(l);this._cache.sort((l,u)=>new Date(l.timestamp).getTime()-new Date(u.timestamp).getTime()),iC(this.cachePrefix,this._cache)};if(n?.requireDurable){let{chainletSync:l}=await Promise.resolve().then(()=>(rC(),nC)),u=await rt.getItem(this._indexKey)??[],d=new Map(u.map(h=>[h.txId,h]));for(let h of o)d.set(h.txId,h);let p=await l.prepareBatch(this.hdAddress,o.map((h,g)=>({key:h.key,value:i[g]})));await rt.setItems([...o.map((h,g)=>[h.key,i[g]]),[this._indexKey,[...d.values()]],...p.kvRows]),a(),await p.commit();return}a();let s=async()=>{await Promise.all(o.map((d,p)=>rt.setItem(d.key,i[p])));let l=await rt.getItem(this._indexKey)??[],u=new Map(l.map(d=>[d.txId,d]));for(let d of o)u.set(d.txId,d);await rt.setItem(this._indexKey,[...u.values()])},c=async()=>{let{chainletSync:l}=await Promise.resolve().then(()=>(rC(),nC));await Promise.all(o.map((u,d)=>l.set(this.hdAddress,u.key,i[d])))};s().catch(()=>{}),c().catch(l=>console.warn("[CappzEventCache] Batch anchor failed",l))}async update(t,n){let r=this._cache.findIndex(a=>a.txId===t);if(r===-1)return null;let i=n(this._cache[r]);this._cache[r]=i;let o=`${this.cachePrefix}${t}`;return await rt.setItem(o,Mf(i)).catch(()=>{}),i}subscribe(t){return BR(this.cachePrefix,async()=>{let n=await this.refresh();t(n)})}async purge(){let n=(await rt.keys()).filter(i=>i.startsWith(this.cachePrefix));n.length>0&&await Promise.all(n.map(i=>rt.removeItem(i)));let r=this._cache.length;return this._cache=[],this._hydrated=!1,console.log(`[CappzEventCache] Purged ${n.length} keys at ${this.cachePrefix}`),r}get size(){return this._cache.length}get isHydrated(){return this._hydrated}stageInMemory(t){if(this._cache.some(n=>n.txId===t.txId)||(this._cache.push(t),this._cache.sort((n,r)=>new Date(n.timestamp).getTime()-new Date(r.timestamp).getTime())),iC(this.cachePrefix,this._cache),this._hydrated=!0,typeof window<"u"){let n=t.eventType;if(typeof n=="string")try{window.dispatchEvent(new CustomEvent(n))}catch{}}}async _updateIndex(t,n){let r=await rt.getItem(this._indexKey)??[];r.some(i=>i.txId===t)||(r.push({txId:t,key:n}),await rt.setItem(this._indexKey,r))}async _hydrateFromIndex(t){let r=(await rt.getItems(t.map(o=>o.key))).filter(o=>!!o).map(o=>Jb(o)),i=new Set(r.map(o=>o.txId));for(let o of this._cache)i.has(o.txId)||r.push(o);return this._cache=r.sort((o,a)=>new Date(o.timestamp).getTime()-new Date(a.timestamp).getTime()),this._hydrated=!0,[...this._cache]}async _recoverFromChainlet(){return[]}async _scanChainletBlocksForPrefix(){return[]}async _rebuildLocalIndex(t){let n=[];for(let r of t){let i=`${this.cachePrefix}${r.txId}`;await rt.setItem(i,Mf(r)).catch(()=>{}),n.push({txId:r.txId,key:i})}await rt.setItem(this._indexKey,n).catch(()=>{})}}});y();import{realpathSync as SF}from"node:fs";import{fileURLToPath as Jde}from"node:url";y();import{readFile as Zn,writeFile as zde,mkdir as jde}from"node:fs/promises";var Rm={about:"Agent skills for CAPPZ: each entry says when to use it (description) and links its SKILL.md. Search: cappz-market skills .",repo:"https://github.com/CAPPZ-ai/cappz-sdk",install:"Claude Code: copy the skill folder into ~/.claude/skills/ or .claude/skills/. Claude API / Claude.ai: upload the folder. Other harnesses: list each description and let the agent read the folder.",skills:[{name:"checking-xrpl-counterparties",description:"Checks the other side before paying or funding escrow on the XRP Ledger with the CAPPZ counterparty check (0.01 XRP) \u2014 whether the address can receive (activated, DepositAuth, destination tag), how old and active it is, its CAPPZ marketplace record and mandate, for RLUSD (USD-tokenZ/1) or CAPPZ payments both trust lines and the issuer's freeze, authorization and escrow settings, and whether the payer can afford it \u2014 and returns a signed ok / warn / stop verdict with reasons. Use when about to send XRP, RLUSD or CAPPZ to an unfamiliar address, fund a CAPPZ marketplace escrow or hire an agent, or when asked whether an XRPL address or marketplace party is safe to pay.",path:"skills/checking-xrpl-counterparties",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/checking-xrpl-counterparties",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/checking-xrpl-counterparties/SKILL.md",commands:["check"],tools:[],guides:[]},{name:"confirming-payees",description:`Stops payment-instruction fraud (business email compromise, "updated wiring instructions", poisoned XRPL addresses) with the CAPPZ payee confirmation (0.01 XRP platform fee + 0.1 XRP). Payers confirm that the address and tag, or the bank account (hashed on their own computer), are the ones the payee declared on the CAPPZ market and endorsed from its own XRPL wallet, past a 72-hour cooling period and not revoked or replaced. The check also flags a change from where the payer paid this payee before and lookalike addresses in the payer's history, and returns a signed ok / warn / stop report. Payees publish and revoke their instructions with cappz-market payee. Use before a large or first payment to instructions that arrived by email, chat or invoice, when instructions changed, when asked whether an address or bank account really belongs to a payee, or when setting up how buyers should pay you.`,path:"skills/confirming-payees",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/confirming-payees",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/confirming-payees/SKILL.md",commands:["confirm-payee","payee"],tools:[],guides:[]},{name:"creating-cappz-listings",description:"Creates a new listing on the CAPPZ Marketplace from start to finish with the cappz-market tool \u2014 confirming the thing sold exists and works, choosing the seller account and network, setting title, category, kind, unit, price, asset, quantity, lead time, endpoint and acceptance criteria, writing a description for people and agents, listing on testnet first, hiring it once, then going live on mainnet with the person's OK and checking it can be found. Use when asked to list, sell, offer, publish or advertise something new on CAPPZ \u2014 a paid agent, an edge-node service, work, goods or a subscription-style service \u2014 or to put a new agent or service on the marketplace.",path:"skills/creating-cappz-listings",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/creating-cappz-listings",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/creating-cappz-listings/SKILL.md",commands:["draft","find","hire","listings","sell","show"],tools:[],guides:[]},{name:"drafting-cappz-listings",description:"Turns a person's plain description of what they sell or need into a checked CAPPZ Marketplace draft and the exact cappz-market sell or ask command, with suggested acceptance criteria, using the CAPPZ listing drafter (0.02 XRP). Category, unit, kind and region are checked against the catalog, and any price, quantity or date the person did not write is left out and asked for, never invented. Nothing is published until the command is run. Use when someone wants to list, sell, offer, request or post something on the CAPPZ Marketplace but has not given exact fields, or asks for help wording a listing or request.",path:"skills/drafting-cappz-listings",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/drafting-cappz-listings",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/drafting-cappz-listings/SKILL.md",commands:["draft","sell"],tools:[],guides:[]},{name:"evaluating-cappz-deliverables",description:"Checks a delivered file against the acceptance criteria agreed for a CAPPZ Marketplace milestone with the CAPPZ stage evaluator (0.05 XRP) \u2014 confirms the file is the seller's published evidence (SHA-256), runs every rule criterion and yes/no rubric question, and returns a signed pass / fail / needs-human verdict \u2014 then lets the contract's named evaluator accept the stage citing that verdict. Also covers writing acceptance criteria into listings, requests, bids and subcontracts. Use when about to accept or release a marketplace stage, when acting as a contract's evaluator, when a buyer wants an independent check of a deliverable, or when setting what a deliverable must meet.",path:"skills/evaluating-cappz-deliverables",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/evaluating-cappz-deliverables",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/evaluating-cappz-deliverables/SKILL.md",commands:["ask","bid","deals","evaluate","sell","subcontract"],tools:[],guides:[]},{name:"getting-an-xrpl-wallet",description:"Gets an XRP Ledger (Ripple/XRPL) wallet ready to pay or be paid in XRP, RLUSD (USD-tokenZ/1) or the CAPPZ token \u2014 creating it, activating it with the account reserve, funding it on testnet for free or on mainnet from an exchange withdrawal, setting the trust line a token needs, checking what is spendable, and keeping the seed safe. Use when an agent or person needs an XRPL or Ripple wallet, test XRP, RLUSD or CAPPZ on the ledger, an address to receive payments, or asks why a wallet is not activated, cannot send, or cannot receive a token.",path:"skills/getting-an-xrpl-wallet",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/getting-an-xrpl-wallet",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/getting-an-xrpl-wallet/SKILL.md",commands:["check","trust","wallet"],tools:[],guides:[]},{name:"hiring-cappz-paid-agents",description:"Hires a CAPPZ paid agent \u2014 an AI agent that runs on its seller's computer and is paid stage by stage on the XRP Ledger in XRP, RLUSD (USD-tokenZ/1) or CAPPZ \u2014 by opening a job, paying each stage with its destination tag, and collecting each result after checking its SHA-256. Use when asked to hire, buy work from, or pay an agent listed on the CAPPZ Marketplace, or an agent URL that answers GET /agent with payTo, price and stages.",path:"skills/hiring-cappz-paid-agents",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/hiring-cappz-paid-agents",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/hiring-cappz-paid-agents/SKILL.md",commands:["find","hire","trust","wallet"],tools:[],guides:[]},{name:"managing-cappz-listings",description:"Manages a seller's own listings on the CAPPZ Marketplace with the cappz-market tool \u2014 see every listing with what is left and the orders formed from it, change price, available units, title, description, lead time, a paid agent's endpoint or acceptance criteria, pause by setting available to 0, and close a listing. Changes apply to new orders; formed contracts keep their terms. Use when a seller or seller agent wants to see, edit, reprice, restock, pause, close or tidy up their CAPPZ listings, or asks what they are selling.",path:"skills/managing-cappz-listings",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/managing-cappz-listings",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/managing-cappz-listings/SKILL.md",commands:["draft","listings","update","withdraw"],tools:[],guides:[]},{name:"monitoring-constraints",description:"Runs ongoing detection of tampering with equipment using the CAPPZ Constraint Guard \u2014 scheduled reconciliation of historian exports, setpoint read-back, sealed observations and the guard's verdict log against each device's signed envelope (changes nobody authorised, limit breaches, disagreeing sensors, changes with no effect, silence; gaps reported as gaps) plus guard alerts \u2014 and responds when one fires: triage, contain, preserve, verify, recover, notify. Use when asked to monitor controllers, setpoints, cold chains, process values or vehicle navigation integrity, to schedule checks after an incident, to investigate a guard alert or a reconciliation finding, or to prove which changes were authorised.",path:"skills/monitoring-constraints",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/monitoring-constraints",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/monitoring-constraints/SKILL.md",commands:["constraints-triage"],tools:["constraint-reconcile","constraint-wizard"],guides:["docs/CONSTRAINT_GUARD.md"]},{name:"monitoring-saml-logins",description:"Sets up and runs ongoing detection for SAML single sign-on abuse with CAPPZ \u2014 scheduled reconciliation of SaaS login logs against identity-provider issuance (orphan and replayed logins, gaps reported as gaps), tamper-evident sealed issuance, and SAML Guard alerts (responses the SP accepted that the guard refused, cross-tenant attempts) \u2014 and responds when one fires: contain, scope, root cause, record with report hashes. Use when asked to monitor SSO or SAML logins, detect forged or replayed SAML sessions, schedule checks after a SAML incident, investigate a SAML Guard or reconciliation alert, or prove which logins an IdP actually issued.",path:"skills/monitoring-saml-logins",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/monitoring-saml-logins",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/monitoring-saml-logins/SKILL.md",commands:[],tools:["saml-wizard"],guides:["docs/SAML_GUARD.md"]},{name:"running-edge-node-paid-agents",description:"Runs the ready-made paid agents of a CAPPZ edge node \u2014 a signed timestamp (a file's SHA-256 in, a receipt signed by the node key out), a signed webhook receiver (a 30-day URL that signs every POST, then delivers a signed bundle), a fair draw (winners picked by an XRP Ledger hash nobody knew when the list was locked), a vault check (a signed report on whether a stolen key could empty an XRPL account) and a vault guard (the node as a pooled account's policy-bound co-signer for 30 days) \u2014 as a testnet instance and a mainnet instance behind HTTPS, with their guide, llms.txt, SKILL.md, OpenAPI and offline verifier, and offers them on the testnet and mainnet marketplaces. Use when asked to earn XRP from an always-on edge node, put a node's signing key to paid use, offer timestamping, tamper-evident webhook logs, provably fair draws or vault protection, or validate paid agents on testnet before mainnet.",path:"skills/running-edge-node-paid-agents",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/running-edge-node-paid-agents",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/running-edge-node-paid-agents/SKILL.md",commands:["find","hire","login","profile","sell"],tools:[],guides:[]},{name:"scouting-cappz-subcontractors",description:"For a CAPPZ Marketplace contract you sell on, proposes which parts to subcontract, finds candidate parties on the market with their replayed reputation, and returns a ready cappz-market subcontract command for each, within what is unreleased and serving open milestones only, using the CAPPZ subcontract scout (0.05 XRP). Nothing is formed until a command is run. Use when a seller or seller agent wants help splitting a won contract, finding subcontractors, or deciding what to hand off on the CAPPZ Marketplace.",path:"skills/scouting-cappz-subcontractors",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/scouting-cappz-subcontractors",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/scouting-cappz-subcontractors/SKILL.md",commands:["ask","scout","subcontract"],tools:[],guides:[]},{name:"securing-control-systems",description:"Protects equipment controllers (refrigeration and freezers, ovens, HVAC, dosing pumps, breakers, building systems, IoT devices, graph-based device twins) against unauthorised or unsafe setpoint changes with the CAPPZ Constraint Guard. Assesses the weakness or incident, recommends root-cause fixes plus safeguards in order (contain, reconcile, seal, guard in shadow, enforce per point), writes the device's signed envelope from documents (never inventing numbers), and rolls out the guard on HTTP, Modbus TCP, BACnet/IP, DNP3, IEC 60870-5-104, MQTT/Sparkplug or Gremlin with constraint-wizard. Scopes vehicle navigation and air-data integrity as advisory only. Use when asked about a hacked or tampered controller, ICS/SCADA/OT security, protecting setpoints, a controller CVE, or whether to patch, segment, monitor or add a guard.",path:"skills/securing-control-systems",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/securing-control-systems",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/securing-control-systems/SKILL.md",commands:["constraints-draft","constraints-review"],tools:["constraint-wizard"],guides:["docs/CONSTRAINT_GUARD.md"]},{name:"securing-saml-sso",description:"Assesses a SAML single sign-on weakness or incident (a SaaS or app accepted a forged, replayed, misdirected or cross-tenant SAML login) and chooses between root-cause fixes and CAPPZ safeguards \u2014 login reconciliation from two log exports, SAML Guard in front of an SP (single or multi-tenant, built-in signature verification, operator-signed certificate pins, cross-tenant refusal), device-bound sessions \u2014 with what each covers, costs and needs; then configures and rolls out the chosen safeguard with the saml-wizard (metadata import, doctor, offline test, shadow, signed enforce). Use when asked about a SAML authentication bypass or CVE, an SSO login nobody issued, hardening a SAML service provider, onboarding customer IdPs to a multi-tenant SaaS, or whether to patch, configure or add a guard.",path:"skills/securing-saml-sso",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/securing-saml-sso",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/securing-saml-sso/SKILL.md",commands:[],tools:["saml-guard","saml-wizard"],guides:["docs/SAML_GUARD.md"]},{name:"selling-agent-work-on-cappz",description:"Sets up an AI agent to sell its work on the CAPPZ Marketplace and be paid stage by stage on the XRP Ledger in XRP, RLUSD (USD-tokenZ/1) or CAPPZ \u2014 running the CAPPZ paid-agent kit on the seller's own computer, exposing it over HTTPS, and listing it with its endpoint. Use when asked to earn with, monetize, sell the output of, or list an agent, model or automation on CAPPZ.",path:"skills/selling-agent-work-on-cappz",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/selling-agent-work-on-cappz",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/selling-agent-work-on-cappz/SKILL.md",commands:["hire","sell","trust","update","wallet"],tools:[],guides:[]},{name:"signing-up-for-cappz",description:"Signs an AI agent up for the CAPPZ platform (cappz.ai) and gets it ready to act \u2014 creating the account, alerting the person it acts for to confirm the email (a human-in-the-loop step), waiting for that confirmation, creating the agent's marketplace profile, and getting a mandate from its principal. Use when an agent needs a CAPPZ account, cannot sign in because its email is not confirmed, or needs a principal or mandate before it can trade on the CAPPZ Marketplace.",path:"skills/signing-up-for-cappz",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/signing-up-for-cappz",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/signing-up-for-cappz/SKILL.md",commands:["login","mandate","profile","setup"],tools:[],guides:[]},{name:"using-cappz-marketplace",description:"Buys, sells, requests, bids on and subcontracts work on the CAPPZ Marketplace (cappz.ai/marketplace) with the cappz-market tool \u2014 governed contracts paid stage by stage on the XRP Ledger in XRP (escrow), RLUSD (USD-tokenZ/1) or CAPPZ (paid per accepted stage), metered XRP use through payment channels, or USD by card, with agents acting under revocable per-asset mandates and signed requests, validated on testnet before going live on mainnet. Use when asked to find, buy, sell, list, request quotes for, bid on, fund, deliver, accept, release or subcontract a CAPPZ marketplace deal, to pay in RLUSD, to test a marketplace flow, or to set up an XRPL wallet or agent profile for it.",path:"skills/using-cappz-marketplace",url:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/using-cappz-marketplace",raw:"https://raw.githubusercontent.com/CAPPZ-ai/cappz-sdk/main/skills/using-cappz-marketplace/SKILL.md",commands:["ask","award","bid","buy","cancel","deals","deliver","dispute","draft","evaluate","find","fund","listings","login","mandate","profile","release","scout","sell","setup","show","subcontract","trust","update","wallet","withdraw"],tools:[],guides:[]}]};y();var YU=new Set(["a","an","and","are","as","at","be","by","can","do","for","from","how","i","in","is","it","me","my","of","on","or","our","so","that","the","this","to","up","was","we","were","what","with","you","your"]),tv=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!YU.has(t)),l8=(e,t)=>e===t||Math.min(e.length,t.length)>=4&&(e.startsWith(t)||t.startsWith(e));function u8(e,t){let n=tv(t);return n.length?e.skills.map(r=>{let i=tv(r.name),o=tv(`${r.description} ${r.commands.join(" ")} ${r.tools.join(" ")}`),a=n.reduce((s,c)=>s+(i.some(l=>l8(l,c))?3:0)+(o.some(l=>l8(l,c))?1:0),0);return{s:r,score:a}}).filter(r=>r.score>0).sort((r,i)=>i.score-r.score||r.s.name.localeCompare(i.s.name)).map(r=>r.s):e.skills}var vF=jr(Nr(),1);Rl();import{join as as,resolve as JC}from"node:path";y();async function db(){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function IO(e,t){let n=await crypto.subtle.importKey("jwk",t,{name:"ECDH",namedCurve:"P-256"},!1,[]);return crypto.subtle.deriveKey({name:"ECDH",public:n},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function lf(e,t){let n=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),r=await IO(n.privateKey,e),i=crypto.getRandomValues(new Uint8Array(12)),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i},r,new TextEncoder().encode(JSON.stringify(t))));return{scheme:"ECDH-P256-AES-GCM",ephemeralPublicKey:await crypto.subtle.exportKey("jwk",n.publicKey),iv:Array.from(i),cipher:Array.from(o)}}async function uf(e,t){let n=await crypto.subtle.importKey("jwk",e,{name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),r=await IO(n,t.ephemeralPublicKey),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(t.iv)},r,new Uint8Array(t.cipher));return JSON.parse(new TextDecoder().decode(i))}var PO=e=>{let t="";for(let n=0;nUint8Array.from(atob(e),t=>t.charCodeAt(0));async function xO(){let e=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);return PO(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}async function MO(e,t){let n=await crypto.subtle.importKey("raw",gT(e),"AES-GCM",!1,["encrypt"]),r=crypto.getRandomValues(new Uint8Array(12));return{scheme:"AES-GCM-256",iv:Array.from(r),cipher:PO(new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r},n,new TextEncoder().encode(t))))}}async function OO(e,t){let n=await crypto.subtle.importKey("raw",gT(e),"AES-GCM",!1,["decrypt"]);return new TextDecoder().decode(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(t.iv)},n,gT(t.cipher)))}y();y();var DO={source:"U.S. Census Bureau, 2024 Gazetteer Files \u2014 Counties (public domain); state centroids are land-area-weighted means of county internal points",counties:{"01001":["AL","Autauga County",32.5322,-86.6464],"01003":["AL","Baldwin County",30.6592,-87.7461],"01005":["AL","Barbour County",31.8703,-85.4051],"01007":["AL","Bibb County",33.0159,-87.1271],"01009":["AL","Blount County",33.9774,-86.5664],"01011":["AL","Bullock County",32.1018,-85.7173],"01013":["AL","Butler County",31.7517,-86.682],"01015":["AL","Calhoun County",33.7705,-85.8279],"01017":["AL","Chambers County",32.9155,-85.394],"01019":["AL","Cherokee County",34.0695,-85.6542],"01021":["AL","Chilton County",32.8541,-86.7266],"01023":["AL","Choctaw County",31.991,-88.2489],"01025":["AL","Clarke County",31.6855,-87.8186],"01027":["AL","Clay County",33.2704,-85.8635],"01029":["AL","Cleburne County",33.672,-85.5161],"01031":["AL","Coffee County",31.4023,-85.9896],"01033":["AL","Colbert County",34.7031,-87.8015],"01035":["AL","Conecuh County",31.4309,-86.9887],"01037":["AL","Coosa County",32.9314,-86.2435],"01039":["AL","Covington County",31.244,-86.4487],"01041":["AL","Crenshaw County",31.7303,-86.32],"01043":["AL","Cullman County",34.1319,-86.8693],"01045":["AL","Dale County",31.4307,-85.6095],"01047":["AL","Dallas County",32.3335,-87.1144],"01049":["AL","DeKalb County",34.4609,-85.804],"01051":["AL","Elmore County",32.5972,-86.1427],"01053":["AL","Escambia County",31.1223,-87.1684],"01055":["AL","Etowah County",34.0476,-86.0343],"01057":["AL","Fayette County",33.7162,-87.7643],"01059":["AL","Franklin County",34.442,-87.8428],"01061":["AL","Geneva County",31.0924,-85.821],"01063":["AL","Greene County",32.8445,-87.9642],"01065":["AL","Hale County",32.7528,-87.6231],"01067":["AL","Henry County",31.517,-85.24],"01069":["AL","Houston County",31.1582,-85.2964],"01071":["AL","Jackson County",34.7641,-85.9801],"01073":["AL","Jefferson County",33.5534,-86.8965],"01075":["AL","Lamar County",33.7871,-88.0874],"01077":["AL","Lauderdale County",34.9042,-87.6511],"01079":["AL","Lawrence County",34.5298,-87.3219],"01081":["AL","Lee County",32.6041,-85.353],"01083":["AL","Limestone County",34.8102,-86.9814],"01085":["AL","Lowndes County",32.1479,-86.6506],"01087":["AL","Macon County",32.387,-85.6929],"01089":["AL","Madison County",34.7642,-86.5511],"01091":["AL","Marengo County",32.2476,-87.7911],"01093":["AL","Marion County",34.1382,-87.8816],"01095":["AL","Marshall County",34.3096,-86.3217],"01097":["AL","Mobile County",30.6846,-88.1966],"01099":["AL","Monroe County",31.5804,-87.3833],"01101":["AL","Montgomery County",32.2029,-86.2045],"01103":["AL","Morgan County",34.4545,-86.8464],"01105":["AL","Perry County",32.639,-87.2938],"01107":["AL","Pickens County",33.2968,-88.0969],"01109":["AL","Pike County",31.7987,-85.9416],"01111":["AL","Randolph County",33.2965,-85.4641],"01113":["AL","Russell County",32.2898,-85.187],"01115":["AL","St. Clair County",33.7195,-86.3113],"01117":["AL","Shelby County",33.2669,-86.661],"01119":["AL","Sumter County",32.5975,-88.2001],"01121":["AL","Talladega County",33.3693,-86.1759],"01123":["AL","Tallapoosa County",32.8633,-85.7996],"01125":["AL","Tuscaloosa County",33.2902,-87.5228],"01127":["AL","Walker County",33.7916,-87.3011],"01129":["AL","Washington County",31.4085,-88.2124],"01131":["AL","Wilcox County",31.9901,-87.3049],"01133":["AL","Winston County",34.1546,-87.3653],"02013":["AK","Aleutians East Borough",55.245,-161.9975],"02016":["AK","Aleutians West Census Area",51.949,179.6212],"02020":["AK","Anchorage Municipality",61.1743,-149.2843],"02050":["AK","Bethel Census Area",60.9291,-160.1526],"02060":["AK","Bristol Bay Borough",58.7305,-156.9945],"02063":["AK","Chugach Census Area",60.4885,-146.2031],"02066":["AK","Copper River Census Area",62.0345,-143.9222],"02068":["AK","Denali Borough",63.682,-150.027],"02070":["AK","Dillingham Census Area",59.5433,-158.2671],"02090":["AK","Fairbanks North Star Borough",64.6705,-146.4961],"02100":["AK","Haines Borough",59.0984,-135.5758],"02105":["AK","Hoonah-Angoon Census Area",58.4033,-135.8849],"02110":["AK","Juneau City and Borough",58.3729,-134.1784],"02122":["AK","Kenai Peninsula Borough",60.3667,-152.3223],"02130":["AK","Ketchikan Gateway Borough",55.4499,-131.1067],"02150":["AK","Kodiak Island Borough",57.7044,-153.9184],"02158":["AK","Kusilvak Census Area",62.2836,-163.1902],"02164":["AK","Lake and Peninsula Borough",58.1085,-156.4134],"02170":["AK","Matanuska-Susitna Borough",62.2656,-149.504],"02180":["AK","Nome Census Area",64.7837,-164.1889],"02185":["AK","North Slope Borough",69.4493,-153.4728],"02188":["AK","Northwest Arctic Borough",67.0051,-160.0211],"02195":["AK","Petersburg Borough",57.1125,-133.0086],"02198":["AK","Prince of Wales-Hyder Census Area",55.6828,-133.1624],"02220":["AK","Sitka City and Borough",57.1932,-135.3674],"02230":["AK","Skagway Municipality",59.5604,-135.3383],"02240":["AK","Southeast Fairbanks Census Area",63.865,-143.2186],"02275":["AK","Wrangell City and Borough",56.1808,-132.0268],"02282":["AK","Yakutat City and Borough",60.0175,-140.4168],"02290":["AK","Yukon-Koyukuk Census Area",65.3757,-151.5782],"04001":["AZ","Apache County",35.3851,-109.4902],"04003":["AZ","Cochise County",31.8401,-109.7752],"04005":["AZ","Coconino County",35.8297,-111.7737],"04007":["AZ","Gila County",33.7896,-110.8119],"04009":["AZ","Graham County",32.9318,-109.8783],"04011":["AZ","Greenlee County",33.2389,-109.2423],"04012":["AZ","La Paz County",33.7276,-114.0388],"04013":["AZ","Maricopa County",33.3452,-112.4989],"04015":["AZ","Mohave County",35.7177,-113.7497],"04017":["AZ","Navajo County",35.3908,-110.321],"04019":["AZ","Pima County",32.128,-111.7837],"04021":["AZ","Pinal County",32.9185,-111.3663],"04023":["AZ","Santa Cruz County",31.5257,-110.8452],"04025":["AZ","Yavapai County",34.6311,-112.5772],"04027":["AZ","Yuma County",32.7739,-113.9109],"05001":["AR","Arkansas County",34.2896,-91.3765],"05003":["AR","Ashley County",33.1908,-91.7723],"05005":["AR","Baxter County",36.2803,-92.3299],"05007":["AR","Benton County",36.3378,-94.2563],"05009":["AR","Boone County",36.3043,-93.0792],"05011":["AR","Bradley County",33.4665,-92.1692],"05013":["AR","Calhoun County",33.5605,-92.5139],"05015":["AR","Carroll County",36.3374,-93.541],"05017":["AR","Chicot County",33.2671,-91.2972],"05019":["AR","Clark County",34.0533,-93.1762],"05021":["AR","Clay County",36.3673,-90.4187],"05023":["AR","Cleburne County",35.5936,-92.0089],"05025":["AR","Cleveland County",33.8932,-92.1887],"05027":["AR","Columbia County",33.223,-93.2328],"05029":["AR","Conway County",35.2657,-92.6892],"05031":["AR","Craighead County",35.8277,-90.6314],"05033":["AR","Crawford County",35.583,-94.2362],"05035":["AR","Crittenden County",35.1976,-90.3051],"05037":["AR","Cross County",35.2857,-90.764],"05039":["AR","Dallas County",33.9678,-92.654],"05041":["AR","Desha County",33.8288,-91.2441],"05043":["AR","Drew County",33.5872,-91.7228],"05045":["AR","Faulkner County",35.1465,-92.3369],"05047":["AR","Franklin County",35.5086,-93.8877],"05049":["AR","Fulton County",36.3813,-91.8193],"05051":["AR","Garland County",34.5789,-93.1469],"05053":["AR","Grant County",34.2856,-92.423],"05055":["AR","Greene County",36.1206,-90.5663],"05057":["AR","Hempstead County",33.736,-93.6644],"05059":["AR","Hot Spring County",34.3152,-92.9441],"05061":["AR","Howard County",34.0831,-93.9909],"05063":["AR","Independence County",35.7375,-91.5599],"05065":["AR","Izard County",36.0949,-91.9136],"05067":["AR","Jackson County",35.5965,-91.2232],"05069":["AR","Jefferson County",34.2772,-91.9297],"05071":["AR","Johnson County",35.5734,-93.4663],"05073":["AR","Lafayette County",33.2406,-93.6115],"05075":["AR","Lawrence County",36.0411,-91.1012],"05077":["AR","Lee County",34.7795,-90.7797],"05079":["AR","Lincoln County",33.9564,-91.7424],"05081":["AR","Little River County",33.7019,-94.2363],"05083":["AR","Logan County",35.2187,-93.7209],"05085":["AR","Lonoke County",34.7551,-91.8941],"05087":["AR","Madison County",36.0125,-93.7241],"05089":["AR","Marion County",36.2667,-92.6786],"05091":["AR","Miller County",33.3055,-93.9015],"05093":["AR","Mississippi County",35.7669,-90.0522],"05095":["AR","Monroe County",34.6795,-91.2033],"05097":["AR","Montgomery County",34.5457,-93.6642],"05099":["AR","Nevada County",33.6667,-93.3051],"05101":["AR","Newton County",35.9107,-93.2159],"05103":["AR","Ouachita County",33.5912,-92.8784],"05105":["AR","Perry County",34.9464,-92.9269],"05107":["AR","Phillips County",34.4237,-90.8556],"05109":["AR","Pike County",34.1582,-93.6587],"05111":["AR","Poinsett County",35.5689,-90.6811],"05113":["AR","Polk County",34.491,-94.2309],"05115":["AR","Pope County",35.4566,-93.0268],"05117":["AR","Prairie County",34.8311,-91.5536],"05119":["AR","Pulaski County",34.7703,-92.313],"05121":["AR","Randolph County",36.3413,-91.0284],"05123":["AR","St. Francis County",35.0228,-90.7515],"05125":["AR","Saline County",34.6485,-92.6745],"05127":["AR","Scott County",34.8589,-94.0636],"05129":["AR","Searcy County",35.8964,-92.6959],"05131":["AR","Sebastian County",35.197,-94.275],"05133":["AR","Sevier County",33.9949,-94.2433],"05135":["AR","Sharp County",36.1734,-91.4711],"05137":["AR","Stone County",35.857,-92.1405],"05139":["AR","Union County",33.1682,-92.5981],"05141":["AR","Van Buren County",35.583,-92.516],"05143":["AR","Washington County",35.978,-94.2173],"05145":["AR","White County",35.2551,-91.753],"05147":["AR","Woodruff County",35.1928,-91.2445],"05149":["AR","Yell County",34.9977,-93.4083],"06001":["CA","Alameda County",37.6471,-121.9125],"06003":["CA","Alpine County",38.6218,-119.7984],"06005":["CA","Amador County",38.4435,-120.6539],"06007":["CA","Butte County",39.6653,-121.6032],"06009":["CA","Calaveras County",38.1911,-120.5541],"06011":["CA","Colusa County",39.1777,-122.2376],"06013":["CA","Contra Costa County",37.9195,-121.9515],"06015":["CA","Del Norte County",41.7499,-123.981],"06017":["CA","El Dorado County",38.7856,-120.5342],"06019":["CA","Fresno County",36.761,-119.655],"06021":["CA","Glenn County",39.6025,-122.4017],"06023":["CA","Humboldt County",40.7067,-123.9262],"06025":["CA","Imperial County",33.0408,-115.3554],"06027":["CA","Inyo County",36.5622,-117.4042],"06029":["CA","Kern County",35.3466,-118.7295],"06031":["CA","Kings County",36.0725,-119.8155],"06033":["CA","Lake County",39.108,-122.7452],"06035":["CA","Lassen County",40.7153,-120.6212],"06037":["CA","Los Angeles County",34.1964,-118.2619],"06039":["CA","Madera County",37.2098,-119.7498],"06041":["CA","Marin County",38.0514,-122.7464],"06043":["CA","Mariposa County",37.5743,-119.9117],"06045":["CA","Mendocino County",39.4324,-123.4429],"06047":["CA","Merced County",37.1948,-120.7228],"06049":["CA","Modoc County",41.5929,-120.7184],"06051":["CA","Mono County",37.9158,-118.8752],"06053":["CA","Monterey County",36.2401,-121.3156],"06055":["CA","Napa County",38.5071,-122.3259],"06057":["CA","Nevada County",39.2975,-120.7713],"06059":["CA","Orange County",33.6757,-117.7772],"06061":["CA","Placer County",39.062,-120.7227],"06063":["CA","Plumas County",39.9923,-120.8244],"06065":["CA","Riverside County",33.7298,-116.0022],"06067":["CA","Sacramento County",38.4501,-121.3443],"06069":["CA","San Benito County",36.6117,-121.0858],"06071":["CA","San Bernardino County",34.8567,-116.1816],"06073":["CA","San Diego County",33.0236,-116.7761],"06075":["CA","San Francisco County",37.7272,-123.0322],"06077":["CA","San Joaquin County",37.935,-121.2722],"06079":["CA","San Luis Obispo County",35.3882,-120.4489],"06081":["CA","San Mateo County",37.4147,-122.3715],"06083":["CA","Santa Barbara County",34.5367,-120.0384],"06085":["CA","Santa Clara County",37.2216,-121.6895],"06087":["CA","Santa Cruz County",37.0123,-122.0078],"06089":["CA","Shasta County",40.7605,-122.0436],"06091":["CA","Sierra County",39.5769,-120.522],"06093":["CA","Siskiyou County",41.588,-122.5333],"06095":["CA","Solano County",38.2672,-121.9396],"06097":["CA","Sonoma County",38.5252,-122.9261],"06099":["CA","Stanislaus County",37.5623,-121.0028],"06101":["CA","Sutter County",39.0362,-121.7039],"06103":["CA","Tehama County",40.1262,-122.2323],"06105":["CA","Trinity County",40.6479,-123.1147],"06107":["CA","Tulare County",36.2288,-118.7811],"06109":["CA","Tuolumne County",38.0214,-119.9647],"06111":["CA","Ventura County",34.3587,-119.1331],"06113":["CA","Yolo County",38.6796,-121.9027],"06115":["CA","Yuba County",39.2701,-121.3443],"08001":["CO","Adams County",39.8743,-104.3319],"08003":["CO","Alamosa County",37.5684,-105.788],"08005":["CO","Arapahoe County",39.6446,-104.3317],"08007":["CO","Archuleta County",37.2024,-107.0509],"08009":["CO","Baca County",37.3098,-102.5437],"08011":["CO","Bent County",37.9319,-103.0776],"08013":["CO","Boulder County",40.095,-105.3977],"08014":["CO","Broomfield County",39.9536,-105.0508],"08015":["CO","Chaffee County",38.7346,-106.3],"08017":["CO","Cheyenne County",38.8356,-102.6018],"08019":["CO","Clear Creek County",39.6894,-105.6708],"08021":["CO","Conejos County",37.2134,-106.1764],"08023":["CO","Costilla County",37.2775,-105.4289],"08025":["CO","Crowley County",38.3062,-103.7727],"08027":["CO","Custer County",38.102,-105.3735],"08029":["CO","Delta County",38.8614,-107.865],"08031":["CO","Denver County",39.7619,-104.8811],"08033":["CO","Dolores County",37.7338,-108.5062],"08035":["CO","Douglas County",39.3254,-104.926],"08037":["CO","Eagle County",39.627,-106.6952],"08039":["CO","Elbert County",39.3152,-104.1141],"08041":["CO","El Paso County",38.8274,-104.5275],"08043":["CO","Fremont County",38.4552,-105.425],"08045":["CO","Garfield County",39.5994,-107.9098],"08047":["CO","Gilpin County",39.8612,-105.5289],"08049":["CO","Grand County",40.1131,-106.1108],"08051":["CO","Gunnison County",38.6705,-107.0569],"08053":["CO","Hinsdale County",37.8115,-107.384],"08055":["CO","Huerfano County",37.6878,-104.9599],"08057":["CO","Jackson County",40.6634,-106.3292],"08059":["CO","Jefferson County",39.5795,-105.2455],"08061":["CO","Kiowa County",38.3877,-102.7568],"08063":["CO","Kit Carson County",39.3053,-102.603],"08065":["CO","Lake County",39.2053,-106.3501],"08067":["CO","La Plata County",37.2874,-107.8397],"08069":["CO","Larimer County",40.6581,-105.4868],"08071":["CO","Las Animas County",37.3188,-104.0441],"08073":["CO","Lincoln County",38.9937,-103.5076],"08075":["CO","Logan County",40.7281,-103.0905],"08077":["CO","Mesa County",39.0195,-108.4606],"08079":["CO","Mineral County",37.5491,-107.0032],"08081":["CO","Moffat County",40.6109,-108.2172],"08083":["CO","Montezuma County",37.338,-108.5958],"08085":["CO","Montrose County",38.4075,-108.2663],"08087":["CO","Morgan County",40.2632,-103.8122],"08089":["CO","Otero County",37.8842,-103.7213],"08091":["CO","Ouray County",38.1547,-107.7885],"08093":["CO","Park County",39.1189,-105.7176],"08095":["CO","Phillips County",40.5947,-102.3451],"08097":["CO","Pitkin County",39.2175,-106.9162],"08099":["CO","Prowers County",37.9584,-102.3918],"08101":["CO","Pueblo County",38.1628,-104.4847],"08103":["CO","Rio Blanco County",39.9726,-108.2007],"08105":["CO","Rio Grande County",37.4859,-106.4531],"08107":["CO","Routt County",40.4837,-106.9877],"08109":["CO","Saguache County",38.0317,-106.2347],"08111":["CO","San Juan County",37.781,-107.6703],"08113":["CO","San Miguel County",38.0093,-108.4273],"08115":["CO","Sedgwick County",40.8716,-102.3554],"08117":["CO","Summit County",39.621,-106.1376],"08119":["CO","Teller County",38.87,-105.1874],"08121":["CO","Washington County",39.9658,-103.2097],"08123":["CO","Weld County",40.556,-104.3837],"08125":["CO","Yuma County",40.0008,-102.4216],"09110":["CT","Capitol Planning Region",41.817,-72.5759],"09120":["CT","Greater Bridgeport Planning Region",41.1846,-73.2094],"09130":["CT","Lower Connecticut River Valley Planning Region",41.4203,-72.4935],"09140":["CT","Naugatuck Valley Planning Region",41.5189,-73.0879],"09150":["CT","Northeastern Connecticut Planning Region",41.8424,-71.9727],"09160":["CT","Northwest Hills Planning Region",41.8548,-73.2215],"09170":["CT","South Central Connecticut Planning Region",41.2902,-72.837],"09180":["CT","Southeastern Connecticut Planning Region",41.4848,-72.1017],"09190":["CT","Western Connecticut Planning Region",41.2791,-73.4466],"10001":["DE","Kent County",39.0971,-75.503],"10003":["DE","New Castle County",39.5759,-75.6441],"10005":["DE","Sussex County",38.6732,-75.337],"11001":["DC","District of Columbia",38.9042,-77.0165],"12001":["FL","Alachua County",29.6757,-82.3572],"12003":["FL","Baker County",30.3244,-82.3023],"12005":["FL","Bay County",30.1591,-85.5344],"12007":["FL","Bradford County",29.9524,-82.1667],"12009":["FL","Brevard County",28.2983,-80.7003],"12011":["FL","Broward County",26.1935,-80.4767],"12013":["FL","Calhoun County",30.3888,-85.1979],"12015":["FL","Charlotte County",26.9064,-82.0037],"12017":["FL","Citrus County",28.8503,-82.5956],"12019":["FL","Clay County",29.9866,-81.865],"12021":["FL","Collier County",26.1188,-81.401],"12023":["FL","Columbia County",30.2217,-82.6234],"12027":["FL","DeSoto County",27.1906,-81.8063],"12029":["FL","Dixie County",29.5527,-83.2362],"12031":["FL","Duval County",30.3352,-81.6481],"12033":["FL","Escambia County",30.53,-87.3203],"12035":["FL","Flagler County",29.4749,-81.2863],"12037":["FL","Franklin County",29.6778,-84.8152],"12039":["FL","Gadsden County",30.5787,-84.6126],"12041":["FL","Gilchrist County",29.7235,-82.7958],"12043":["FL","Glades County",26.9548,-81.1908],"12045":["FL","Gulf County",29.8592,-85.272],"12047":["FL","Hamilton County",30.4984,-82.9511],"12049":["FL","Hardee County",27.4928,-81.8216],"12051":["FL","Hendry County",26.54,-81.1521],"12053":["FL","Hernando County",28.556,-82.526],"12055":["FL","Highlands County",27.3411,-81.3424],"12057":["FL","Hillsborough County",27.8932,-82.38],"12059":["FL","Holmes County",30.862,-85.8159],"12061":["FL","Indian River County",27.7005,-80.5748],"12063":["FL","Jackson County",30.7892,-85.2088],"12065":["FL","Jefferson County",30.3969,-83.9218],"12067":["FL","Lafayette County",29.9901,-83.1785],"12069":["FL","Lake County",28.7641,-81.7123],"12071":["FL","Lee County",26.5633,-81.9842],"12073":["FL","Leon County",30.4593,-84.2778],"12075":["FL","Levy County",29.2719,-82.8312],"12077":["FL","Liberty County",30.2598,-84.8686],"12079":["FL","Madison County",30.4472,-83.4704],"12081":["FL","Manatee County",27.4756,-82.3931],"12083":["FL","Marion County",29.2028,-82.0431],"12085":["FL","Martin County",27.0836,-80.3982],"12086":["FL","Miami-Dade County",25.616,-80.5037],"12087":["FL","Monroe County",25.5861,-81.0226],"12089":["FL","Nassau County",30.606,-81.7651],"12091":["FL","Okaloosa County",30.6143,-86.5911],"12093":["FL","Okeechobee County",27.3856,-80.8874],"12095":["FL","Orange County",28.5144,-81.3233],"12097":["FL","Osceola County",28.059,-81.1393],"12099":["FL","Palm Beach County",26.6491,-80.4484],"12101":["FL","Pasco County",28.3098,-82.511],"12103":["FL","Pinellas County",27.9053,-82.7981],"12105":["FL","Polk County",27.9537,-81.6935],"12107":["FL","Putnam County",29.5939,-81.732],"12109":["FL","St. Johns County",29.8905,-81.4],"12111":["FL","St. Lucie County",27.3798,-80.4435],"12113":["FL","Santa Rosa County",30.6753,-87.0189],"12115":["FL","Sarasota County",27.2253,-82.4237],"12117":["FL","Seminole County",28.6901,-81.132],"12119":["FL","Sumter County",28.7133,-82.0695],"12121":["FL","Suwannee County",30.1892,-82.9928],"12123":["FL","Taylor County",29.9671,-83.6396],"12125":["FL","Union County",30.0543,-82.3669],"12127":["FL","Volusia County",29.0578,-81.1618],"12129":["FL","Wakulla County",30.0913,-84.3591],"12131":["FL","Walton County",30.5712,-86.1628],"12133":["FL","Washington County",30.6021,-85.6558],"13001":["GA","Appling County",31.7397,-82.2901],"13003":["GA","Atkinson County",31.2968,-82.8782],"13005":["GA","Bacon County",31.5502,-82.4514],"13007":["GA","Baker County",31.3196,-84.4549],"13009":["GA","Baldwin County",33.0595,-83.2555],"13011":["GA","Banks County",34.3519,-83.4984],"13013":["GA","Barrow County",33.992,-83.7123],"13015":["GA","Bartow County",34.2409,-84.8382],"13017":["GA","Ben Hill County",31.7408,-83.1472],"13019":["GA","Berrien County",31.2887,-83.2279],"13021":["GA","Bibb County",32.809,-83.6941],"13023":["GA","Bleckley County",32.4354,-83.3317],"13025":["GA","Brantley County",31.1973,-81.983],"13027":["GA","Brooks County",30.8229,-83.5819],"13029":["GA","Bryan County",32.018,-81.4385],"13031":["GA","Bulloch County",32.3945,-81.7414],"13033":["GA","Burke County",33.0602,-82.0002],"13035":["GA","Butts County",33.2904,-83.9582],"13037":["GA","Calhoun County",31.5213,-84.6263],"13039":["GA","Camden County",30.9134,-81.642],"13043":["GA","Candler County",32.404,-82.0713],"13045":["GA","Carroll County",33.5822,-85.0805],"13047":["GA","Catoosa County",34.9002,-85.1394],"13049":["GA","Charlton County",30.7799,-82.1396],"13051":["GA","Chatham County",31.9804,-81.0852],"13053":["GA","Chattahoochee County",32.3474,-84.788],"13055":["GA","Chattooga County",34.4742,-85.3453],"13057":["GA","Cherokee County",34.2443,-84.4751],"13059":["GA","Clarke County",33.9522,-83.3672],"13061":["GA","Clay County",31.6198,-84.9926],"13063":["GA","Clayton County",33.5522,-84.413],"13065":["GA","Clinch County",30.9177,-82.7026],"13067":["GA","Cobb County",33.9399,-84.5741],"13069":["GA","Coffee County",31.5492,-82.8449],"13071":["GA","Colquitt County",31.1897,-83.7698],"13073":["GA","Columbia County",33.5521,-82.2496],"13075":["GA","Cook County",31.1525,-83.4294],"13077":["GA","Coweta County",33.3529,-84.7621],"13079":["GA","Crawford County",32.7094,-83.9792],"13081":["GA","Crisp County",31.9203,-83.7565],"13083":["GA","Dade County",34.8524,-85.5062],"13085":["GA","Dawson County",34.4426,-84.1733],"13087":["GA","Decatur County",30.8806,-84.5839],"13089":["GA","DeKalb County",33.7707,-84.2263],"13091":["GA","Dodge County",32.1644,-83.1679],"13093":["GA","Dooly County",32.152,-83.8072],"13095":["GA","Dougherty County",31.5326,-84.209],"13097":["GA","Douglas County",33.7012,-84.7673],"13099":["GA","Early County",31.3242,-84.9067],"13101":["GA","Echols County",30.714,-82.8974],"13103":["GA","Effingham County",32.3617,-81.3434],"13105":["GA","Elbert County",34.1164,-82.8419],"13107":["GA","Emanuel County",32.5912,-82.3002],"13109":["GA","Evans County",32.1531,-81.8902],"13111":["GA","Fannin County",34.8665,-84.3173],"13113":["GA","Fayette County",33.4127,-84.4939],"13115":["GA","Floyd County",34.2637,-85.2137],"13117":["GA","Forsyth County",34.2251,-84.1274],"13119":["GA","Franklin County",34.3753,-83.2275],"13121":["GA","Fulton County",33.79,-84.4682],"13123":["GA","Gilmer County",34.6905,-84.4548],"13125":["GA","Glascock County",33.2275,-82.6069],"13127":["GA","Glynn County",31.2127,-81.4964],"13129":["GA","Gordon County",34.5097,-84.8739],"13131":["GA","Grady County",30.8759,-84.245],"13133":["GA","Greene County",33.5767,-83.1666],"13135":["GA","Gwinnett County",33.9588,-84.0257],"13137":["GA","Habersham County",34.6344,-83.5259],"13139":["GA","Hall County",34.3176,-83.8185],"13141":["GA","Hancock County",33.2692,-83.0005],"13143":["GA","Haralson County",33.7952,-85.2201],"13145":["GA","Harris County",32.7315,-84.9124],"13147":["GA","Hart County",34.3487,-82.9633],"13149":["GA","Heard County",33.2913,-85.1379],"13151":["GA","Henry County",33.4529,-84.154],"13153":["GA","Houston County",32.4581,-83.6623],"13155":["GA","Irwin County",31.6043,-83.277],"13157":["GA","Jackson County",34.1309,-83.5626],"13159":["GA","Jasper County",33.317,-83.6892],"13161":["GA","Jeff Davis County",31.8116,-82.6368],"13163":["GA","Jefferson County",33.0582,-82.42],"13165":["GA","Jenkins County",32.7946,-81.9715],"13167":["GA","Johnson County",32.6946,-82.664],"13169":["GA","Jones County",33.0217,-83.5622],"13171":["GA","Lamar County",33.0744,-84.1467],"13173":["GA","Lanier County",31.0382,-83.0632],"13175":["GA","Laurens County",32.3932,-82.9263],"13177":["GA","Lee County",31.8184,-84.1467],"13179":["GA","Liberty County",31.8075,-81.4579],"13181":["GA","Lincoln County",33.7922,-82.4483],"13183":["GA","Long County",31.7496,-81.7429],"13185":["GA","Lowndes County",30.8331,-83.269],"13187":["GA","Lumpkin County",34.5681,-83.9989],"13189":["GA","McDuffie County",33.4806,-82.4796],"13191":["GA","McIntosh County",31.4856,-81.3721],"13193":["GA","Macon County",32.3627,-84.0512],"13195":["GA","Madison County",34.1275,-83.2087],"13197":["GA","Marion County",32.3593,-84.5287],"13199":["GA","Meriwether County",33.0293,-84.6671],"13201":["GA","Miller County",31.1629,-84.7304],"13205":["GA","Mitchell County",31.229,-84.192],"13207":["GA","Monroe County",33.0188,-83.9218],"13209":["GA","Montgomery County",32.1721,-82.5333],"13211":["GA","Morgan County",33.5986,-83.4994],"13213":["GA","Murray County",34.7971,-84.738],"13215":["GA","Muscogee County",32.5102,-84.8749],"13217":["GA","Newton County",33.5528,-83.8514],"13219":["GA","Oconee County",33.8341,-83.4377],"13221":["GA","Oglethorpe County",33.8668,-83.0741],"13223":["GA","Paulding County",33.921,-84.8672],"13225":["GA","Peach County",32.5713,-83.832],"13227":["GA","Pickens County",34.4568,-84.4904],"13229":["GA","Pierce County",31.354,-82.2104],"13231":["GA","Pike County",33.0811,-84.3895],"13233":["GA","Polk County",33.996,-85.1883],"13235":["GA","Pulaski County",32.2388,-83.4818],"13237":["GA","Putnam County",33.3211,-83.3718],"13239":["GA","Quitman County",31.8629,-85.0048],"13241":["GA","Rabun County",34.8839,-83.4049],"13243":["GA","Randolph County",31.7627,-84.7523],"13245":["GA","Richmond County",33.3615,-82.075],"13247":["GA","Rockdale County",33.6521,-84.0264],"13249":["GA","Schley County",32.2634,-84.3227],"13251":["GA","Screven County",32.7448,-81.6176],"13253":["GA","Seminole County",30.934,-84.8677],"13255":["GA","Spalding County",33.2623,-84.2849],"13257":["GA","Stephens County",34.5536,-83.2906],"13259":["GA","Stewart County",32.0732,-84.8349],"13261":["GA","Sumter County",32.0423,-84.2043],"13263":["GA","Talbot County",32.7046,-84.53],"13265":["GA","Taliaferro County",33.5593,-82.8753],"13267":["GA","Tattnall County",32.0438,-82.0592],"13269":["GA","Taylor County",32.5547,-84.2514],"13271":["GA","Telfair County",31.9136,-82.9311],"13273":["GA","Terrell County",31.7772,-84.4394],"13275":["GA","Thomas County",30.8646,-83.9198],"13277":["GA","Tift County",31.457,-83.5259],"13279":["GA","Toombs County",32.1178,-82.3306],"13281":["GA","Towns County",34.9025,-83.7323],"13283":["GA","Treutlen County",32.4096,-82.5709],"13285":["GA","Troup County",33.0345,-85.0284],"13287":["GA","Turner County",31.7248,-83.6203],"13289":["GA","Twiggs County",32.6658,-83.4259],"13291":["GA","Union County",34.8333,-83.9893],"13293":["GA","Upson County",32.8818,-84.2923],"13295":["GA","Walker County",34.7358,-85.3055],"13297":["GA","Walton County",33.7839,-83.7318],"13299":["GA","Ware County",31.0509,-82.4215],"13301":["GA","Warren County",33.4084,-82.6757],"13303":["GA","Washington County",32.9718,-82.7981],"13305":["GA","Wayne County",31.5478,-81.9124],"13307":["GA","Webster County",32.0467,-84.5538],"13309":["GA","Wheeler County",32.1053,-82.7338],"13311":["GA","White County",34.6442,-83.743],"13313":["GA","Whitfield County",34.8017,-84.9685],"13315":["GA","Wilcox County",31.9627,-83.4383],"13317":["GA","Wilkes County",33.779,-82.7479],"13319":["GA","Wilkinson County",32.8043,-83.1755],"13321":["GA","Worth County",31.5518,-83.85],"15001":["HI","Hawaii County",19.5978,-155.5024],"15003":["HI","Honolulu County",21.4614,-158.202],"15005":["HI","Kalawao County",21.2188,-156.974],"15007":["HI","Kauai County",22.012,-159.706],"15009":["HI","Maui County",20.8559,-156.6016],"16001":["ID","Ada County",43.4515,-116.2444],"16003":["ID","Adams County",44.877,-116.4616],"16005":["ID","Bannock County",42.6929,-112.229],"16007":["ID","Bear Lake County",42.2859,-111.3275],"16009":["ID","Benewah County",47.2185,-116.6335],"16011":["ID","Bingham County",43.2164,-112.3992],"16013":["ID","Blaine County",43.3942,-113.9554],"16015":["ID","Boise County",43.9873,-115.7151],"16017":["ID","Bonner County",48.3246,-116.6274],"16019":["ID","Bonneville County",43.3952,-111.6219],"16021":["ID","Boundary County",48.7731,-116.5247],"16023":["ID","Butte County",43.6851,-113.1776],"16025":["ID","Camas County",43.5026,-114.7721],"16027":["ID","Canyon County",43.6258,-116.7091],"16029":["ID","Caribou County",42.7861,-111.5443],"16031":["ID","Cassia County",42.2823,-113.6263],"16033":["ID","Clark County",44.2902,-112.3546],"16035":["ID","Clearwater County",46.6726,-115.6535],"16037":["ID","Custer County",44.2734,-114.2523],"16039":["ID","Elmore County",43.3947,-115.4712],"16041":["ID","Franklin County",42.1736,-111.823],"16043":["ID","Fremont County",44.2181,-111.4844],"16045":["ID","Gem County",44.0615,-116.3988],"16047":["ID","Gooding County",42.9732,-114.8214],"16049":["ID","Idaho County",45.8496,-115.4673],"16051":["ID","Jefferson County",43.797,-112.3186],"16053":["ID","Jerome County",42.6914,-114.2621],"16055":["ID","Kootenai County",47.676,-116.6959],"16057":["ID","Latah County",46.8189,-116.731],"16059":["ID","Lemhi County",44.9285,-113.887],"16061":["ID","Lewis County",46.2363,-116.4238],"16063":["ID","Lincoln County",42.9908,-114.1531],"16065":["ID","Madison County",43.7886,-111.657],"16067":["ID","Minidoka County",42.8572,-113.6398],"16069":["ID","Nez Perce County",46.3338,-116.7609],"16071":["ID","Oneida County",42.1839,-112.5204],"16073":["ID","Owyhee County",42.5729,-116.1897],"16075":["ID","Payette County",44.0024,-116.7502],"16077":["ID","Power County",42.6941,-112.8444],"16079":["ID","Shoshone County",47.3477,-115.8851],"16081":["ID","Teton County",43.761,-111.2118],"16083":["ID","Twin Falls County",42.3523,-114.6656],"16085":["ID","Valley County",44.856,-115.6181],"16087":["ID","Washington County",44.4482,-116.7978],"17001":["IL","Adams County",39.9861,-91.195],"17003":["IL","Alexander County",37.1837,-89.3495],"17005":["IL","Bond County",38.8859,-89.4366],"17007":["IL","Boone County",42.319,-88.8243],"17009":["IL","Brown County",39.9621,-90.7503],"17011":["IL","Bureau County",41.4013,-89.5284],"17013":["IL","Calhoun County",39.1643,-90.6663],"17015":["IL","Carroll County",42.0709,-89.9242],"17017":["IL","Cass County",39.9692,-90.2457],"17019":["IL","Champaign County",40.139,-88.197],"17021":["IL","Christian County",39.5455,-89.2796],"17023":["IL","Clark County",39.3323,-87.7917],"17025":["IL","Clay County",38.7468,-88.4823],"17027":["IL","Clinton County",38.6063,-89.4262],"17029":["IL","Coles County",39.5137,-88.2208],"17031":["IL","Cook County",41.8943,-87.6455],"17033":["IL","Crawford County",39.0028,-87.7606],"17035":["IL","Cumberland County",39.2731,-88.2406],"17037":["IL","DeKalb County",41.8946,-88.769],"17039":["IL","De Witt County",40.1815,-88.9019],"17041":["IL","Douglas County",39.7661,-88.2229],"17043":["IL","DuPage County",41.8521,-88.086],"17045":["IL","Edgar County",39.679,-87.7471],"17047":["IL","Edwards County",38.4171,-88.0479],"17049":["IL","Effingham County",39.0479,-88.5928],"17051":["IL","Fayette County",39.0011,-89.0179],"17053":["IL","Ford County",40.5965,-88.2246],"17055":["IL","Franklin County",37.9919,-88.9263],"17057":["IL","Fulton County",40.4652,-90.2023],"17059":["IL","Gallatin County",37.7687,-88.228],"17061":["IL","Greene County",39.3554,-90.3877],"17063":["IL","Grundy County",41.2924,-88.4011],"17065":["IL","Hamilton County",38.0852,-88.539],"17067":["IL","Hancock County",40.4013,-91.1688],"17069":["IL","Hardin County",37.5179,-88.2661],"17071":["IL","Henderson County",40.8145,-90.9412],"17073":["IL","Henry County",41.35,-90.1308],"17075":["IL","Iroquois County",40.7489,-87.8336],"17077":["IL","Jackson County",37.7861,-89.3812],"17079":["IL","Jasper County",39.0049,-88.1507],"17081":["IL","Jefferson County",38.3008,-88.9242],"17083":["IL","Jersey County",39.0802,-90.3614],"17085":["IL","Jo Daviess County",42.3624,-90.2115],"17087":["IL","Johnson County",37.4607,-88.8821],"17089":["IL","Kane County",41.9396,-88.428],"17091":["IL","Kankakee County",41.1395,-87.8611],"17093":["IL","Kendall County",41.5881,-88.4306],"17095":["IL","Knox County",40.9309,-90.2138],"17097":["IL","Lake County",42.186,-87.8059],"17099":["IL","LaSalle County",41.3433,-88.8859],"17101":["IL","Lawrence County",38.719,-87.7302],"17103":["IL","Lee County",41.7474,-89.2994],"17105":["IL","Livingston County",40.8944,-88.5529],"17107":["IL","Logan County",40.1293,-89.3653],"17109":["IL","McDonough County",40.4558,-90.679],"17111":["IL","McHenry County",42.3243,-88.4522],"17113":["IL","McLean County",40.4946,-88.8445],"17115":["IL","Macon County",39.8602,-88.9615],"17117":["IL","Macoupin County",39.2659,-89.9263],"17119":["IL","Madison County",38.8271,-89.9002],"17121":["IL","Marion County",38.6482,-88.9204],"17123":["IL","Marshall County",41.0311,-89.3424],"17125":["IL","Mason County",40.237,-89.9136],"17127":["IL","Massac County",37.2161,-88.7057],"17129":["IL","Menard County",40.0226,-89.7941],"17131":["IL","Mercer County",41.2056,-90.7418],"17133":["IL","Monroe County",38.278,-90.1791],"17135":["IL","Montgomery County",39.2281,-89.4781],"17137":["IL","Morgan County",39.7177,-90.205],"17139":["IL","Moultrie County",39.6369,-88.6257],"17141":["IL","Ogle County",42.0419,-89.3202],"17143":["IL","Peoria County",40.786,-89.767],"17145":["IL","Perry County",38.0844,-89.3685],"17147":["IL","Piatt County",40.009,-88.5924],"17149":["IL","Pike County",39.6251,-90.889],"17151":["IL","Pope County",37.4172,-88.5424],"17153":["IL","Pulaski County",37.2156,-89.1278],"17155":["IL","Putnam County",41.199,-89.2983],"17157":["IL","Randolph County",38.0565,-89.8212],"17159":["IL","Richland County",38.7122,-88.0855],"17161":["IL","Rock Island County",41.4684,-90.5721],"17163":["IL","St. Clair County",38.4702,-89.9285],"17165":["IL","Saline County",37.7515,-88.545],"17167":["IL","Sangamon County",39.7569,-89.6624],"17169":["IL","Schuyler County",40.1569,-90.6135],"17171":["IL","Scott County",39.637,-90.4778],"17173":["IL","Shelby County",39.3849,-88.7989],"17175":["IL","Stark County",41.0969,-89.7974],"17177":["IL","Stephenson County",42.3497,-89.666],"17179":["IL","Tazewell County",40.5081,-89.5163],"17181":["IL","Union County",37.4857,-89.2446],"17183":["IL","Vermilion County",40.1868,-87.7268],"17185":["IL","Wabash County",38.4458,-87.8392],"17187":["IL","Warren County",40.8504,-90.6202],"17189":["IL","Washington County",38.3531,-89.4172],"17191":["IL","Wayne County",38.4319,-88.4324],"17193":["IL","White County",38.0873,-88.1786],"17195":["IL","Whiteside County",41.7507,-89.911],"17197":["IL","Will County",41.4485,-87.9785],"17199":["IL","Williamson County",37.7304,-88.93],"17201":["IL","Winnebago County",42.3374,-89.1612],"17203":["IL","Woodford County",40.7898,-89.2106],"18001":["IN","Adams County",40.7457,-84.9361],"18003":["IN","Allen County",41.0919,-85.0718],"18005":["IN","Bartholomew County",39.2058,-85.898],"18007":["IN","Benton County",40.6009,-87.3148],"18009":["IN","Blackford County",40.4727,-85.3237],"18011":["IN","Boone County",40.0509,-86.469],"18013":["IN","Brown County",39.1951,-86.2301],"18015":["IN","Carroll County",40.585,-86.5651],"18017":["IN","Cass County",40.7538,-86.3552],"18019":["IN","Clark County",38.4762,-85.7111],"18021":["IN","Clay County",39.3939,-87.1159],"18023":["IN","Clinton County",40.3059,-86.4776],"18025":["IN","Crawford County",38.2894,-86.4409],"18027":["IN","Daviess County",38.6961,-87.0769],"18029":["IN","Dearborn County",39.1409,-84.9759],"18031":["IN","Decatur County",39.306,-85.4998],"18033":["IN","DeKalb County",41.3968,-85.0027],"18035":["IN","Delaware County",40.2275,-85.3993],"18037":["IN","Dubois County",38.3733,-86.8734],"18039":["IN","Elkhart County",41.6007,-85.864],"18041":["IN","Fayette County",39.6397,-85.185],"18043":["IN","Floyd County",38.3181,-85.9118],"18045":["IN","Fountain County",40.1212,-87.2349],"18047":["IN","Franklin County",39.4098,-85.067],"18049":["IN","Fulton County",41.0504,-86.265],"18051":["IN","Gibson County",38.3174,-87.5805],"18053":["IN","Grant County",40.5158,-85.6549],"18055":["IN","Greene County",39.0471,-87.0048],"18057":["IN","Hamilton County",40.0535,-86.0217],"18059":["IN","Hancock County",39.8225,-85.7732],"18061":["IN","Harrison County",38.1865,-86.1038],"18063":["IN","Hendricks County",39.769,-86.5099],"18065":["IN","Henry County",39.9296,-85.3974],"18067":["IN","Howard County",40.4835,-86.1141],"18069":["IN","Huntington County",40.8264,-85.4786],"18071":["IN","Jackson County",38.912,-86.0425],"18073":["IN","Jasper County",41.0177,-87.1188],"18075":["IN","Jay County",40.435,-85.0023],"18077":["IN","Jefferson County",38.7836,-85.4401],"18079":["IN","Jennings County",38.9962,-85.6281],"18081":["IN","Johnson County",39.4961,-86.0943],"18083":["IN","Knox County",38.6884,-87.4204],"18085":["IN","Kosciusko County",41.2443,-85.8616],"18087":["IN","LaGrange County",41.6425,-85.4278],"18089":["IN","Lake County",41.4722,-87.3743],"18091":["IN","LaPorte County",41.549,-86.7447],"18093":["IN","Lawrence County",38.8398,-86.4878],"18095":["IN","Madison County",40.1662,-85.7225],"18097":["IN","Marion County",39.783,-86.1358],"18099":["IN","Marshall County",41.325,-86.269],"18101":["IN","Martin County",38.7053,-86.8018],"18103":["IN","Miami County",40.7729,-86.0443],"18105":["IN","Monroe County",39.1607,-86.5233],"18107":["IN","Montgomery County",40.0403,-86.8927],"18109":["IN","Morgan County",39.4826,-86.4475],"18111":["IN","Newton County",40.9624,-87.4022],"18113":["IN","Noble County",41.4047,-85.4173],"18115":["IN","Ohio County",38.9405,-84.9643],"18117":["IN","Orange County",38.5474,-86.4893],"18119":["IN","Owen County",39.3173,-86.8388],"18121":["IN","Parke County",39.7743,-87.197],"18123":["IN","Perry County",38.0814,-86.6265],"18125":["IN","Pike County",38.398,-87.2325],"18127":["IN","Porter County",41.5099,-87.0713],"18129":["IN","Posey County",38.0276,-87.8687],"18131":["IN","Pulaski County",41.0453,-86.6925],"18133":["IN","Putnam County",39.6655,-86.8534],"18135":["IN","Randolph County",40.1641,-85.0058],"18137":["IN","Ripley County",39.1002,-85.2605],"18139":["IN","Rush County",39.6224,-85.4665],"18141":["IN","St. Joseph County",41.6177,-86.288],"18143":["IN","Scott County",38.6794,-85.7519],"18145":["IN","Shelby County",39.5241,-85.7922],"18147":["IN","Spencer County",38.0097,-87.0104],"18149":["IN","Starke County",41.2845,-86.6446],"18151":["IN","Steuben County",41.6435,-85.0024],"18153":["IN","Sullivan County",39.0892,-87.4158],"18155":["IN","Switzerland County",38.8259,-85.0297],"18157":["IN","Tippecanoe County",40.3891,-86.8936],"18159":["IN","Tipton County",40.3102,-86.0562],"18161":["IN","Union County",39.6231,-84.9251],"18163":["IN","Vanderburgh County",38.0201,-87.5862],"18165":["IN","Vermillion County",39.854,-87.4621],"18167":["IN","Vigo County",39.4309,-87.391],"18169":["IN","Wabash County",40.8437,-85.7952],"18171":["IN","Warren County",40.3525,-87.3752],"18173":["IN","Warrick County",38.0977,-87.272],"18175":["IN","Washington County",38.6006,-86.1048],"18177":["IN","Wayne County",39.8631,-85.0067],"18179":["IN","Wells County",40.7355,-85.2133],"18181":["IN","White County",40.751,-86.8643],"18183":["IN","Whitley County",41.1364,-85.5019],"19001":["IA","Adair County",41.3285,-94.4782],"19003":["IA","Adams County",41.0217,-94.6969],"19005":["IA","Allamakee County",43.275,-91.3828],"19007":["IA","Appanoose County",40.7442,-92.8731],"19009":["IA","Audubon County",41.6792,-94.9043],"19011":["IA","Benton County",42.0925,-92.0576],"19013":["IA","Black Hawk County",42.4711,-92.3076],"19015":["IA","Boone County",42.0386,-93.9386],"19017":["IA","Bremer County",42.7809,-92.3274],"19019":["IA","Buchanan County",42.4703,-91.8387],"19021":["IA","Buena Vista County",42.7415,-95.1414],"19023":["IA","Butler County",42.7348,-92.7802],"19025":["IA","Calhoun County",42.3861,-94.6436],"19027":["IA","Carroll County",42.0395,-94.8676],"19029":["IA","Cass County",41.3338,-94.9333],"19031":["IA","Cedar County",41.7724,-91.1326],"19033":["IA","Cerro Gordo County",43.075,-93.251],"19035":["IA","Cherokee County",42.7427,-95.6333],"19037":["IA","Chickasaw County",43.0597,-92.3172],"19039":["IA","Clarke County",41.0297,-93.7853],"19041":["IA","Clay County",43.0812,-95.1499],"19043":["IA","Clayton County",42.841,-91.3236],"19045":["IA","Clinton County",41.8981,-90.5342],"19047":["IA","Crawford County",42.0431,-95.3891],"19049":["IA","Dallas County",41.6853,-94.0407],"19051":["IA","Davis County",40.7481,-92.4103],"19053":["IA","Decatur County",40.7364,-93.7846],"19055":["IA","Delaware County",42.473,-91.3668],"19057":["IA","Des Moines County",40.9153,-91.1869],"19059":["IA","Dickinson County",43.3896,-95.1961],"19061":["IA","Dubuque County",42.4635,-90.8788],"19063":["IA","Emmet County",43.378,-94.6694],"19065":["IA","Fayette County",42.8641,-91.8404],"19067":["IA","Floyd County",43.0527,-92.7874],"19069":["IA","Franklin County",42.7365,-93.2714],"19071":["IA","Fremont County",40.7426,-95.5992],"19073":["IA","Greene County",42.0425,-94.3887],"19075":["IA","Grundy County",42.4033,-92.7902],"19077":["IA","Guthrie County",41.6836,-94.5013],"19079":["IA","Hamilton County",42.3908,-93.7091],"19081":["IA","Hancock County",43.0754,-93.7437],"19083":["IA","Hardin County",42.3902,-93.2417],"19085":["IA","Harrison County",41.6886,-95.8271],"19087":["IA","Henry County",40.9848,-91.5473],"19089":["IA","Howard County",43.3653,-92.3219],"19091":["IA","Humboldt County",42.7822,-94.2028],"19093":["IA","Ida County",42.3919,-95.5074],"19095":["IA","Iowa County",41.6839,-92.0591],"19097":["IA","Jackson County",42.1642,-90.5746],"19099":["IA","Jasper County",41.6856,-93.0541],"19101":["IA","Jefferson County",41.0064,-91.9666],"19103":["IA","Johnson County",41.6707,-91.5905],"19105":["IA","Jones County",42.1251,-91.1169],"19107":["IA","Keokuk County",41.3312,-92.1677],"19109":["IA","Kossuth County",43.2123,-94.214],"19111":["IA","Lee County",40.6476,-91.4772],"19113":["IA","Linn County",42.078,-91.5977],"19115":["IA","Louisa County",41.2182,-91.257],"19117":["IA","Lucas County",41.0333,-93.3315],"19119":["IA","Lyon County",43.3836,-96.2072],"19121":["IA","Madison County",41.3306,-94.0152],"19123":["IA","Mahaska County",41.3308,-92.6364],"19125":["IA","Marion County",41.3314,-93.0939],"19127":["IA","Marshall County",42.0417,-92.9814],"19129":["IA","Mills County",41.0337,-95.6191],"19131":["IA","Mitchell County",43.3486,-92.7845],"19133":["IA","Monona County",42.0494,-95.9566],"19135":["IA","Monroe County",41.0288,-92.8696],"19137":["IA","Montgomery County",41.0217,-95.1578],"19139":["IA","Muscatine County",41.4838,-91.1187],"19141":["IA","O'Brien County",43.0837,-95.6256],"19143":["IA","Osceola County",43.3785,-95.6338],"19145":["IA","Page County",40.7391,-95.1443],"19147":["IA","Palo Alto County",43.0753,-94.6691],"19149":["IA","Plymouth County",42.7376,-96.216],"19151":["IA","Pocahontas County",42.734,-94.6783],"19153":["IA","Polk County",41.6848,-93.569],"19155":["IA","Pottawattamie County",41.3402,-95.5449],"19157":["IA","Poweshiek County",41.6846,-92.5229],"19159":["IA","Ringgold County",40.7353,-94.2443],"19161":["IA","Sac County",42.3875,-95.1052],"19163":["IA","Scott County",41.6421,-90.6223],"19165":["IA","Shelby County",41.679,-95.3089],"19167":["IA","Sioux County",43.0826,-96.178],"19169":["IA","Story County",42.0375,-93.4661],"19171":["IA","Tama County",42.0748,-92.5294],"19173":["IA","Taylor County",40.7379,-94.6971],"19175":["IA","Union County",41.0286,-94.2451],"19177":["IA","Van Buren County",40.7541,-91.9529],"19179":["IA","Wapello County",41.0313,-92.4095],"19181":["IA","Warren County",41.3324,-93.5688],"19183":["IA","Washington County",41.3294,-91.7251],"19185":["IA","Wayne County",40.74,-93.3326],"19187":["IA","Webster County",42.4336,-94.1758],"19189":["IA","Winnebago County",43.3781,-93.7435],"19191":["IA","Winneshiek County",43.293,-91.8508],"19193":["IA","Woodbury County",42.3932,-96.0533],"19195":["IA","Worth County",43.3735,-93.2485],"19197":["IA","Wright County",42.733,-93.7347],"20001":["KS","Allen County",37.8842,-95.3009],"20003":["KS","Anderson County",38.2151,-95.292],"20005":["KS","Atchison County",39.5325,-95.3134],"20007":["KS","Barber County",37.2229,-98.6851],"20009":["KS","Barton County",38.4812,-98.7678],"20011":["KS","Bourbon County",37.8561,-94.8509],"20013":["KS","Brown County",39.8259,-95.5699],"20015":["KS","Butler County",37.7736,-96.8388],"20017":["KS","Chase County",38.2995,-96.594],"20019":["KS","Chautauqua County",37.1543,-96.2454],"20021":["KS","Cherokee County",37.1694,-94.8457],"20023":["KS","Cheyenne County",39.7899,-101.7273],"20025":["KS","Clark County",37.2338,-99.8139],"20027":["KS","Clay County",39.345,-97.1689],"20029":["KS","Cloud County",39.4873,-97.6414],"20031":["KS","Coffey County",38.2364,-95.7291],"20033":["KS","Comanche County",37.1814,-99.2513],"20035":["KS","Cowley County",37.2345,-96.8372],"20037":["KS","Crawford County",37.5058,-94.8539],"20039":["KS","Decatur County",39.7835,-100.4597],"20041":["KS","Dickinson County",38.8677,-97.1579],"20043":["KS","Doniphan County",39.7885,-95.1472],"20045":["KS","Douglas County",38.8964,-95.2909],"20047":["KS","Edwards County",37.8836,-99.3047],"20049":["KS","Elk County",37.456,-96.2446],"20051":["KS","Ellis County",38.9146,-99.3173],"20053":["KS","Ellsworth County",38.7008,-98.2054],"20055":["KS","Finney County",38.0498,-100.74],"20057":["KS","Ford County",37.6885,-99.8847],"20059":["KS","Franklin County",38.558,-95.279],"20061":["KS","Geary County",39.0021,-96.7681],"20063":["KS","Gove County",38.9172,-100.4874],"20065":["KS","Graham County",39.355,-99.8799],"20067":["KS","Grant County",37.5475,-101.2994],"20069":["KS","Gray County",37.7445,-100.4517],"20071":["KS","Greeley County",38.4804,-101.806],"20073":["KS","Greenwood County",37.8793,-96.2417],"20075":["KS","Hamilton County",37.9952,-101.7937],"20077":["KS","Harper County",37.1882,-98.0666],"20079":["KS","Harvey County",38.0501,-97.4367],"20081":["KS","Haskell County",37.555,-100.88],"20083":["KS","Hodgeman County",38.0875,-99.8984],"20085":["KS","Jackson County",39.4111,-95.7945],"20087":["KS","Jefferson County",39.2396,-95.3753],"20089":["KS","Jewell County",39.777,-98.2226],"20091":["KS","Johnson County",38.8839,-94.8223],"20093":["KS","Kearny County",37.9945,-101.3081],"20095":["KS","Kingman County",37.553,-98.1445],"20097":["KS","Kiowa County",37.5612,-99.2865],"20099":["KS","Labette County",37.1915,-95.2975],"20101":["KS","Lane County",38.4813,-100.4662],"20103":["KS","Leavenworth County",39.1895,-95.039],"20105":["KS","Lincoln County",39.0473,-98.2143],"20107":["KS","Linn County",38.2165,-94.8449],"20109":["KS","Logan County",38.9133,-101.1574],"20111":["KS","Lyon County",38.4554,-96.1616],"20113":["KS","McPherson County",38.3958,-97.6475],"20115":["KS","Marion County",38.3596,-97.1028],"20117":["KS","Marshall County",39.7827,-96.5212],"20119":["KS","Meade County",37.2439,-100.3601],"20121":["KS","Miami County",38.5668,-94.833],"20123":["KS","Mitchell County",39.393,-98.2074],"20125":["KS","Montgomery County",37.1895,-95.7424],"20127":["KS","Morris County",38.6882,-96.6514],"20129":["KS","Morton County",37.1852,-101.8095],"20131":["KS","Nemaha County",39.791,-96.0054],"20133":["KS","Neosho County",37.5643,-95.3157],"20135":["KS","Ness County",38.4804,-99.9087],"20137":["KS","Norton County",39.7839,-99.8992],"20139":["KS","Osage County",38.6502,-95.7083],"20141":["KS","Osborne County",39.3483,-98.7679],"20143":["KS","Ottawa County",39.138,-97.6548],"20145":["KS","Pawnee County",38.1815,-99.2348],"20147":["KS","Phillips County",39.7845,-99.3422],"20149":["KS","Pottawatomie County",39.3822,-96.3371],"20151":["KS","Pratt County",37.6476,-98.7401],"20153":["KS","Rawlins County",39.7862,-101.0767],"20155":["KS","Reno County",37.9482,-98.0783],"20157":["KS","Republic County",39.8289,-97.6509],"20159":["KS","Rice County",38.3472,-98.2014],"20161":["KS","Riley County",39.2912,-96.7275],"20163":["KS","Rooks County",39.346,-99.3245],"20165":["KS","Rush County",38.5236,-99.3092],"20167":["KS","Russell County",38.916,-98.7709],"20169":["KS","Saline County",38.7918,-97.6515],"20171":["KS","Scott County",38.4819,-100.9064],"20173":["KS","Sedgwick County",37.681,-97.4611],"20175":["KS","Seward County",37.181,-100.8553],"20177":["KS","Shawnee County",39.0418,-95.7557],"20179":["KS","Sheridan County",39.3505,-100.4412],"20181":["KS","Sherman County",39.3514,-101.7199],"20183":["KS","Smith County",39.7847,-98.7854],"20185":["KS","Stafford County",38.0356,-98.7199],"20187":["KS","Stanton County",37.5659,-101.7894],"20189":["KS","Stevens County",37.2017,-101.3173],"20191":["KS","Sumner County",37.2367,-97.4934],"20193":["KS","Thomas County",39.3577,-101.0834],"20195":["KS","Trego County",38.9213,-99.8654],"20197":["KS","Wabaunsee County",38.9552,-96.2013],"20199":["KS","Wallace County",38.9266,-101.7711],"20201":["KS","Washington County",39.7767,-97.0956],"20203":["KS","Wichita County",38.4819,-101.3474],"20205":["KS","Wilson County",37.5585,-95.7452],"20207":["KS","Woodson County",37.8882,-95.7585],"20209":["KS","Wyandotte County",39.1154,-94.7631],"21001":["KY","Adair County",37.1056,-85.2814],"21003":["KY","Allen County",36.7508,-86.1925],"21005":["KY","Anderson County",38.0054,-84.9864],"21007":["KY","Ballard County",37.0513,-89.0104],"21009":["KY","Barren County",36.9628,-85.9321],"21011":["KY","Bath County",38.1522,-83.7376],"21013":["KY","Bell County",36.7289,-83.6807],"21015":["KY","Boone County",38.9589,-84.7364],"21017":["KY","Bourbon County",38.2026,-84.2099],"21019":["KY","Boyd County",38.36,-82.6814],"21021":["KY","Boyle County",37.6181,-84.8684],"21023":["KY","Bracken County",38.6804,-84.1152],"21025":["KY","Breathitt County",37.5178,-83.3172],"21027":["KY","Breckinridge County",37.778,-86.4329],"21029":["KY","Bullitt County",37.9699,-85.7026],"21031":["KY","Butler County",37.207,-86.6825],"21033":["KY","Caldwell County",37.1486,-87.8705],"21035":["KY","Calloway County",36.621,-88.2741],"21037":["KY","Campbell County",38.947,-84.3796],"21039":["KY","Carlisle County",36.8572,-88.9766],"21041":["KY","Carroll County",38.6684,-85.124],"21043":["KY","Carter County",38.3141,-83.039],"21045":["KY","Casey County",37.322,-84.9282],"21047":["KY","Christian County",36.8921,-87.493],"21049":["KY","Clark County",37.9703,-84.1451],"21051":["KY","Clay County",37.1643,-83.7155],"21053":["KY","Clinton County",36.7273,-85.1361],"21055":["KY","Crittenden County",37.3581,-88.105],"21057":["KY","Cumberland County",36.7824,-85.3885],"21059":["KY","Daviess County",37.7317,-87.0871],"21061":["KY","Edmonson County",37.2275,-86.218],"21063":["KY","Elliott County",38.1169,-83.0961],"21065":["KY","Estill County",37.6924,-83.964],"21067":["KY","Fayette County",38.0407,-84.4583],"21069":["KY","Fleming County",38.3678,-83.6992],"21071":["KY","Floyd County",37.5525,-82.7397],"21073":["KY","Franklin County",38.2349,-84.8688],"21075":["KY","Fulton County",36.5525,-89.1877],"21077":["KY","Gallatin County",38.7557,-84.8651],"21079":["KY","Garrard County",37.6302,-84.5459],"21081":["KY","Grant County",38.6492,-84.6259],"21083":["KY","Graves County",36.7233,-88.6499],"21085":["KY","Grayson County",37.4586,-86.344],"21087":["KY","Green County",37.2781,-85.5379],"21089":["KY","Greenup County",38.5636,-82.9338],"21091":["KY","Hancock County",37.8433,-86.7928],"21093":["KY","Hardin County",37.6958,-85.9632],"21095":["KY","Harlan County",36.8592,-83.2215],"21097":["KY","Harrison County",38.4446,-84.3341],"21099":["KY","Hart County",37.3058,-85.8784],"21101":["KY","Henderson County",37.7925,-87.5726],"21103":["KY","Henry County",38.4514,-85.1196],"21105":["KY","Hickman County",36.6759,-88.9721],"21107":["KY","Hopkins County",37.3111,-87.5422],"21109":["KY","Jackson County",37.4035,-84.0206],"21111":["KY","Jefferson County",38.1895,-85.6576],"21113":["KY","Jessamine County",37.8733,-84.584],"21115":["KY","Johnson County",37.8478,-82.8301],"21117":["KY","Kenton County",38.9305,-84.5334],"21119":["KY","Knott County",37.3544,-82.9525],"21121":["KY","Knox County",36.8885,-83.8556],"21123":["KY","Larue County",37.5445,-85.6968],"21125":["KY","Laurel County",37.1133,-84.1194],"21127":["KY","Lawrence County",38.0745,-82.7383],"21129":["KY","Lee County",37.6081,-83.7192],"21131":["KY","Leslie County",37.0878,-83.3886],"21133":["KY","Letcher County",37.1185,-82.8613],"21135":["KY","Lewis County",38.535,-83.3701],"21137":["KY","Lincoln County",37.4572,-84.6583],"21139":["KY","Livingston County",37.2095,-88.3634],"21141":["KY","Logan County",36.8596,-86.8813],"21143":["KY","Lyon County",37.024,-88.0834],"21145":["KY","McCracken County",37.0541,-88.7125],"21147":["KY","McCreary County",36.7311,-84.4911],"21149":["KY","McLean County",37.5267,-87.2656],"21151":["KY","Madison County",37.7255,-84.2784],"21153":["KY","Magoffin County",37.699,-83.0697],"21155":["KY","Marion County",37.5526,-85.269],"21157":["KY","Marshall County",36.882,-88.3328],"21159":["KY","Martin County",37.7968,-82.5066],"21161":["KY","Mason County",38.5941,-83.8281],"21163":["KY","Meade County",37.9675,-86.2009],"21165":["KY","Menifee County",37.9355,-83.5894],"21167":["KY","Mercer County",37.8121,-84.8797],"21169":["KY","Metcalfe County",36.9924,-85.6335],"21171":["KY","Monroe County",36.7141,-85.7135],"21173":["KY","Montgomery County",38.0381,-83.9124],"21175":["KY","Morgan County",37.9229,-83.2589],"21177":["KY","Muhlenberg County",37.2138,-87.1341],"21179":["KY","Nelson County",37.8031,-85.4659],"21181":["KY","Nicholas County",38.338,-84.0262],"21183":["KY","Ohio County",37.4779,-86.8449],"21185":["KY","Oldham County",38.4001,-85.4561],"21187":["KY","Owen County",38.4994,-84.8416],"21189":["KY","Owsley County",37.4236,-83.6916],"21191":["KY","Pendleton County",38.6963,-84.3519],"21193":["KY","Perry County",37.2413,-83.2178],"21195":["KY","Pike County",37.486,-82.4109],"21197":["KY","Powell County",37.8096,-83.8312],"21199":["KY","Pulaski County",37.1074,-84.577],"21201":["KY","Robertson County",38.5135,-84.0642],"21203":["KY","Rockcastle County",37.361,-84.3144],"21205":["KY","Rowan County",38.2043,-83.4281],"21207":["KY","Russell County",36.9906,-85.055],"21209":["KY","Scott County",38.2857,-84.5783],"21211":["KY","Shelby County",38.239,-85.2282],"21213":["KY","Simpson County",36.7409,-86.5818],"21215":["KY","Spencer County",38.0253,-85.3173],"21217":["KY","Taylor County",37.3662,-85.3281],"21219":["KY","Todd County",36.8403,-87.1836],"21221":["KY","Trigg County",36.8077,-87.8587],"21223":["KY","Trimble County",38.62,-85.3512],"21225":["KY","Union County",37.658,-87.9517],"21227":["KY","Warren County",36.9956,-86.4236],"21229":["KY","Washington County",37.7542,-85.1754],"21231":["KY","Wayne County",36.8008,-84.8266],"21233":["KY","Webster County",37.5204,-87.6852],"21235":["KY","Whitley County",36.758,-84.1446],"21237":["KY","Wolfe County",37.7439,-83.4951],"21239":["KY","Woodford County",38.0431,-84.7489],"22001":["LA","Acadia Parish",30.2915,-92.411],"22003":["LA","Allen Parish",30.6527,-92.8196],"22005":["LA","Ascension Parish",30.2064,-90.9125],"22007":["LA","Assumption Parish",29.9033,-91.0652],"22009":["LA","Avoyelles Parish",31.0885,-91.9833],"22011":["LA","Beauregard Parish",30.645,-93.3403],"22013":["LA","Bienville Parish",32.341,-93.0412],"22015":["LA","Bossier Parish",32.6985,-93.6266],"22017":["LA","Caddo Parish",32.5801,-93.885],"22019":["LA","Calcasieu Parish",30.2296,-93.358],"22021":["LA","Caldwell Parish",32.1012,-92.1142],"22023":["LA","Cameron Parish",29.8718,-93.1649],"22025":["LA","Catahoula Parish",31.6665,-91.8467],"22027":["LA","Claiborne Parish",32.8272,-92.9897],"22029":["LA","Concordia Parish",31.4698,-91.6263],"22031":["LA","De Soto Parish",32.0592,-93.7408],"22033":["LA","East Baton Rouge Parish",30.5439,-91.0931],"22035":["LA","East Carroll Parish",32.7302,-91.2341],"22037":["LA","East Feliciana Parish",30.8398,-91.0434],"22039":["LA","Evangeline Parish",30.7207,-92.4041],"22041":["LA","Franklin Parish",32.1391,-91.6724],"22043":["LA","Grant Parish",31.5978,-92.5617],"22045":["LA","Iberia Parish",29.606,-91.8427],"22047":["LA","Iberville Parish",30.2707,-91.3659],"22049":["LA","Jackson Parish",32.3043,-92.5617],"22051":["LA","Jefferson Parish",29.5033,-90.0362],"22053":["LA","Jefferson Davis Parish",30.2695,-92.8162],"22055":["LA","Lafayette Parish",30.2065,-92.0642],"22057":["LA","Lafourche Parish",29.492,-90.3948],"22059":["LA","LaSalle Parish",31.6801,-92.1616],"22061":["LA","Lincoln Parish",32.6018,-92.6623],"22063":["LA","Livingston Parish",30.4404,-90.7275],"22065":["LA","Madison Parish",32.3469,-91.2319],"22067":["LA","Morehouse Parish",32.82,-91.8004],"22069":["LA","Natchitoches Parish",31.7325,-93.0825],"22071":["LA","Orleans Parish",30.0534,-89.9345],"22073":["LA","Ouachita Parish",32.4809,-92.1516],"22075":["LA","Plaquemines Parish",29.2824,-89.5761],"22077":["LA","Pointe Coupee Parish",30.7083,-91.6046],"22079":["LA","Rapides Parish",31.1932,-92.536],"22081":["LA","Red River Parish",32.1012,-93.3491],"22083":["LA","Richland Parish",32.4132,-91.7484],"22085":["LA","Sabine Parish",31.5604,-93.5596],"22087":["LA","St. Bernard Parish",29.9181,-89.2635],"22089":["LA","St. Charles Parish",29.9057,-90.3579],"22091":["LA","St. Helena Parish",30.8225,-90.7083],"22093":["LA","St. James Parish",30.0248,-90.794],"22095":["LA","St. John the Baptist Parish",30.1441,-90.491],"22097":["LA","St. Landry Parish",30.5834,-91.9893],"22099":["LA","St. Martin Parish",30.1214,-91.6115],"22101":["LA","St. Mary Parish",29.6293,-91.4638],"22103":["LA","St. Tammany Parish",30.41,-89.952],"22105":["LA","Tangipahoa Parish",30.6213,-90.4065],"22107":["LA","Tensas Parish",32.0015,-91.3426],"22109":["LA","Terrebonne Parish",29.3341,-90.8437],"22111":["LA","Union Parish",32.8293,-92.3756],"22113":["LA","Vermilion Parish",29.8066,-92.3214],"22115":["LA","Vernon Parish",31.1028,-93.1883],"22117":["LA","Washington Parish",30.8521,-90.0463],"22119":["LA","Webster Parish",32.7322,-93.3398],"22121":["LA","West Baton Rouge Parish",30.4641,-91.3098],"22123":["LA","West Carroll Parish",32.7925,-91.452],"22125":["LA","West Feliciana Parish",30.8734,-91.4218],"22127":["LA","Winn Parish",31.9412,-92.6413],"23001":["ME","Androscoggin County",44.1677,-70.2074],"23003":["ME","Aroostook County",46.7092,-68.6124],"23005":["ME","Cumberland County",43.8083,-70.3304],"23007":["ME","Franklin County",44.9767,-70.4149],"23009":["ME","Hancock County",44.5649,-68.3707],"23011":["ME","Kennebec County",44.417,-69.7658],"23013":["ME","Knox County",44.042,-69.0385],"23015":["ME","Lincoln County",43.9948,-69.5136],"23017":["ME","Oxford County",44.4945,-70.7344],"23019":["ME","Penobscot County",45.4093,-68.6666],"23021":["ME","Piscataquis County",45.9156,-69.1022],"23023":["ME","Sagadahoc County",43.9168,-69.8442],"23025":["ME","Somerset County",45.5036,-69.9561],"23027":["ME","Waldo County",44.475,-69.1174],"23029":["ME","Washington County",44.967,-67.6094],"23031":["ME","York County",43.426,-70.6684],"24001":["MD","Allegany County",39.6123,-78.7031],"24003":["MD","Anne Arundel County",38.9916,-76.5609],"24005":["MD","Baltimore County",39.4432,-76.6166],"24009":["MD","Calvert County",38.5227,-76.5298],"24011":["MD","Caroline County",38.8715,-75.8317],"24013":["MD","Carroll County",39.5633,-77.0153],"24015":["MD","Cecil County",39.5624,-75.9416],"24017":["MD","Charles County",38.4729,-77.0154],"24019":["MD","Dorchester County",38.4292,-76.0474],"24021":["MD","Frederick County",39.4702,-77.3976],"24023":["MD","Garrett County",39.5473,-79.2746],"24025":["MD","Harford County",39.5374,-76.2998],"24027":["MD","Howard County",39.2523,-76.9244],"24029":["MD","Kent County",39.2413,-76.126],"24031":["MD","Montgomery County",39.1374,-77.2031],"24033":["MD","Prince George's County",38.8293,-76.8482],"24035":["MD","Queen Anne's County",39.0407,-76.0824],"24037":["MD","St. Mary's County",38.2231,-76.5345],"24039":["MD","Somerset County",38.0744,-75.8533],"24041":["MD","Talbot County",38.7483,-76.1785],"24043":["MD","Washington County",39.6036,-77.8147],"24045":["MD","Wicomico County",38.3674,-75.6321],"24047":["MD","Worcester County",38.2221,-75.3099],"24510":["MD","Baltimore city",39.3,-76.6105],"25001":["MA","Barnstable County",41.7061,-70.1648],"25003":["MA","Berkshire County",42.3715,-73.2179],"25005":["MA","Bristol County",41.7486,-71.0889],"25007":["MA","Dukes County",41.381,-70.7015],"25009":["MA","Essex County",42.6427,-70.8649],"25011":["MA","Franklin County",42.5845,-72.5918],"25013":["MA","Hampden County",42.1362,-72.6356],"25015":["MA","Hampshire County",42.3395,-72.6637],"25017":["MA","Middlesex County",42.4817,-71.3949],"25019":["MA","Nantucket County",41.2934,-70.1022],"25021":["MA","Norfolk County",42.1717,-71.1811],"25023":["MA","Plymouth County",41.9872,-70.7419],"25025":["MA","Suffolk County",42.3386,-71.0183],"25027":["MA","Worcester County",42.3117,-71.9403],"26001":["MI","Alcona County",44.6575,-83.2946],"26003":["MI","Alger County",46.5217,-86.6571],"26005":["MI","Allegan County",42.4213,-86.2614],"26007":["MI","Alpena County",44.895,-83.4266],"26009":["MI","Antrim County",45.0055,-85.1756],"26011":["MI","Arenac County",44.0368,-83.7407],"26013":["MI","Baraga County",46.6959,-88.3618],"26015":["MI","Barry County",42.5828,-85.3145],"26017":["MI","Bay County",43.6997,-83.9787],"26019":["MI","Benzie County",44.6368,-86.232],"26021":["MI","Berrien County",41.7914,-86.7425],"26023":["MI","Branch County",41.9185,-85.0669],"26025":["MI","Calhoun County",42.243,-85.0124],"26027":["MI","Cass County",41.9172,-86.0001],"26029":["MI","Charlevoix County",45.6186,-85.5437],"26031":["MI","Cheboygan County",45.476,-84.4954],"26033":["MI","Chippewa County",46.3218,-84.5206],"26035":["MI","Clare County",43.9911,-84.8383],"26037":["MI","Clinton County",42.9505,-84.5917],"26039":["MI","Crawford County",44.6802,-84.6113],"26041":["MI","Delta County",45.8052,-86.9019],"26043":["MI","Dickinson County",46.0128,-87.8661],"26045":["MI","Eaton County",42.5895,-84.8465],"26047":["MI","Emmet County",45.5901,-84.9868],"26049":["MI","Genesee County",43.0211,-83.7064],"26051":["MI","Gladwin County",43.9898,-84.3898],"26053":["MI","Gogebic County",46.4881,-89.7883],"26055":["MI","Grand Traverse County",44.7187,-85.5538],"26057":["MI","Gratiot County",43.2923,-84.6047],"26059":["MI","Hillsdale County",41.9275,-84.6375],"26061":["MI","Houghton County",46.9984,-88.6519],"26063":["MI","Huron County",43.9076,-82.857],"26065":["MI","Ingham County",42.6035,-84.3738],"26067":["MI","Ionia County",42.9447,-85.0738],"26069":["MI","Iosco County",44.3869,-83.3801],"26071":["MI","Iron County",46.1703,-88.5405],"26073":["MI","Isabella County",43.6452,-84.8394],"26075":["MI","Jackson County",42.2485,-84.4209],"26077":["MI","Kalamazoo County",42.2463,-85.5329],"26079":["MI","Kalkaska County",44.6789,-85.089],"26081":["MI","Kent County",43.0325,-85.5474],"26083":["MI","Keweenaw County",47.3673,-88.3513],"26085":["MI","Lake County",43.9952,-85.8114],"26087":["MI","Lapeer County",43.0886,-83.2243],"26089":["MI","Leelanau County",45.1462,-86.0516],"26091":["MI","Lenawee County",41.896,-84.0744],"26093":["MI","Livingston County",42.6025,-83.9117],"26095":["MI","Luce County",46.511,-85.5176],"26097":["MI","Mackinac County",46.1679,-85.3038],"26099":["MI","Macomb County",42.6716,-82.9115],"26101":["MI","Manistee County",44.2453,-86.3275],"26103":["MI","Marquette County",46.6566,-87.584],"26105":["MI","Mason County",43.9572,-86.4429],"26107":["MI","Mecosta County",43.6353,-85.3328],"26109":["MI","Menominee County",45.5356,-87.5015],"26111":["MI","Midland County",43.6482,-84.3794],"26113":["MI","Missaukee County",44.3254,-85.0855],"26115":["MI","Monroe County",41.9161,-83.4871],"26117":["MI","Montcalm County",43.3128,-85.1495],"26119":["MI","Montmorency County",45.0241,-84.1301],"26121":["MI","Muskegon County",43.4287,-86.4209],"26123":["MI","Newaygo County",43.5627,-85.7914],"26125":["MI","Oakland County",42.6605,-83.3842],"26127":["MI","Oceana County",43.604,-86.4672],"26129":["MI","Ogemaw County",44.3333,-84.1281],"26131":["MI","Ontonagon County",46.8352,-89.2769],"26133":["MI","Osceola County",43.9976,-85.3223],"26135":["MI","Oscoda County",44.6873,-84.1269],"26137":["MI","Otsego County",45.0218,-84.5766],"26139":["MI","Ottawa County",43.055,-86.2193],"26141":["MI","Presque Isle County",45.2524,-83.4323],"26143":["MI","Roscommon County",44.3395,-84.6113],"26145":["MI","Saginaw County",43.3283,-84.0554],"26147":["MI","St. Clair County",42.9288,-82.6689],"26149":["MI","St. Joseph County",41.9115,-85.5229],"26151":["MI","Sanilac County",43.4492,-82.6428],"26153":["MI","Schoolcraft County",46.0211,-86.197],"26155":["MI","Shiawassee County",42.9515,-84.1464],"26157":["MI","Tuscola County",43.4879,-83.4366],"26159":["MI","Van Buren County",42.2822,-86.3061],"26161":["MI","Washtenaw County",42.2522,-83.8434],"26163":["MI","Wayne County",42.2847,-83.262],"26165":["MI","Wexford County",44.3314,-85.57],"27001":["MN","Aitkin County",46.6024,-93.4197],"27003":["MN","Anoka County",45.2741,-93.2427],"27005":["MN","Becker County",46.9376,-95.7418],"27007":["MN","Beltrami County",47.8795,-95.005],"27009":["MN","Benton County",45.7012,-94.0014],"27011":["MN","Big Stone County",45.4199,-96.4022],"27013":["MN","Blue Earth County",44.0337,-94.064],"27015":["MN","Brown County",44.2465,-94.7336],"27017":["MN","Carlton County",46.6038,-92.671],"27019":["MN","Carver County",44.8213,-93.8001],"27021":["MN","Cass County",46.9517,-94.3337],"27023":["MN","Chippewa County",45.0286,-95.5641],"27025":["MN","Chisago County",45.5054,-92.9038],"27027":["MN","Clay County",46.8984,-96.4949],"27029":["MN","Clearwater County",47.5759,-95.3711],"27031":["MN","Cook County",47.7586,-90.3443],"27033":["MN","Cottonwood County",44.0106,-95.1832],"27035":["MN","Crow Wing County",46.4917,-94.0707],"27037":["MN","Dakota County",44.6709,-93.0625],"27039":["MN","Dodge County",44.0207,-92.8694],"27041":["MN","Douglas County",45.9368,-95.4622],"27043":["MN","Faribault County",43.6765,-93.9472],"27045":["MN","Fillmore County",43.6792,-92.0939],"27047":["MN","Freeborn County",43.6742,-93.3503],"27049":["MN","Goodhue County",44.4062,-92.716],"27051":["MN","Grant County",45.9307,-96.0107],"27053":["MN","Hennepin County",45.0061,-93.4752],"27055":["MN","Houston County",43.667,-91.5016],"27057":["MN","Hubbard County",47.0956,-94.9133],"27059":["MN","Isanti County",45.5624,-93.2963],"27061":["MN","Itasca County",47.4908,-93.6111],"27063":["MN","Jackson County",43.6711,-95.1497],"27065":["MN","Kanabec County",45.9478,-93.2978],"27067":["MN","Kandiyohi County",45.1527,-95.005],"27069":["MN","Kittson County",48.776,-96.7803],"27071":["MN","Koochiching County",48.2454,-93.7829],"27073":["MN","Lac qui Parle County",44.9998,-96.1769],"27075":["MN","Lake County",47.5171,-91.4117],"27077":["MN","Lake of the Woods County",48.7681,-94.9046],"27079":["MN","Le Sueur County",44.3734,-93.7301],"27081":["MN","Lincoln County",44.4082,-96.272],"27083":["MN","Lyon County",44.4092,-95.8473],"27085":["MN","McLeod County",44.8217,-94.2723],"27087":["MN","Mahnomen County",47.3284,-95.8111],"27089":["MN","Marshall County",48.3627,-96.3578],"27091":["MN","Martin County",43.6772,-94.5471],"27093":["MN","Meeker County",45.1232,-94.5273],"27095":["MN","Mille Lacs County",45.9293,-93.6327],"27097":["MN","Morrison County",46.0205,-94.2666],"27099":["MN","Mower County",43.6662,-92.7595],"27101":["MN","Murray County",44.0156,-95.7616],"27103":["MN","Nicollet County",44.3588,-94.2457],"27105":["MN","Nobles County",43.6777,-95.7631],"27107":["MN","Norman County",47.3295,-96.4638],"27109":["MN","Olmsted County",43.9995,-92.4101],"27111":["MN","Otter Tail County",46.4057,-95.7146],"27113":["MN","Pennington County",48.0692,-96.0377],"27115":["MN","Pine County",46.1009,-92.7631],"27117":["MN","Pipestone County",44.0154,-96.257],"27119":["MN","Polk County",47.7743,-96.4],"27121":["MN","Pope County",45.5896,-95.4467],"27123":["MN","Ramsey County",45.0152,-93.1],"27125":["MN","Red Lake County",47.8655,-96.0872],"27127":["MN","Redwood County",44.4035,-95.2542],"27129":["MN","Renville County",44.7237,-94.9556],"27131":["MN","Rice County",44.3508,-93.2985],"27133":["MN","Rock County",43.6696,-96.2632],"27135":["MN","Roseau County",48.7611,-95.8215],"27137":["MN","St. Louis County",47.5786,-92.5146],"27139":["MN","Scott County",44.6518,-93.5337],"27141":["MN","Sherburne County",45.4532,-93.7692],"27143":["MN","Sibley County",44.5757,-94.2301],"27145":["MN","Stearns County",45.5552,-94.6105],"27147":["MN","Steele County",44.0153,-93.2205],"27149":["MN","Stevens County",45.5935,-95.9923],"27151":["MN","Swift County",45.2758,-95.6901],"27153":["MN","Todd County",46.0666,-94.9006],"27155":["MN","Traverse County",45.7699,-96.4748],"27157":["MN","Wabasha County",44.2896,-92.2335],"27159":["MN","Wadena County",46.587,-94.9886],"27161":["MN","Waseca County",44.0185,-93.5898],"27163":["MN","Washington County",45.0379,-92.8901],"27165":["MN","Watonwan County",43.9781,-94.6138],"27167":["MN","Wilkin County",46.3623,-96.4767],"27169":["MN","Winona County",43.9814,-91.777],"27171":["MN","Wright County",45.1751,-93.9664],"27173":["MN","Yellow Medicine County",44.7157,-95.8628],"28001":["MS","Adams County",31.4862,-91.3518],"28003":["MS","Alcorn County",34.8866,-88.5811],"28005":["MS","Amite County",31.2039,-90.7955],"28007":["MS","Attala County",33.0905,-89.5886],"28009":["MS","Benton County",34.8096,-89.2002],"28011":["MS","Bolivar County",33.7991,-90.8841],"28013":["MS","Calhoun County",33.9366,-89.3371],"28015":["MS","Carroll County",33.4408,-89.9189],"28017":["MS","Chickasaw County",33.9333,-88.9476],"28019":["MS","Choctaw County",33.346,-89.2513],"28021":["MS","Claiborne County",31.9728,-90.9154],"28023":["MS","Clarke County",32.0454,-88.688],"28025":["MS","Clay County",33.6597,-88.7825],"28027":["MS","Coahoma County",34.2303,-90.604],"28029":["MS","Copiah County",31.8669,-90.4488],"28031":["MS","Covington County",31.6333,-89.5489],"28033":["MS","DeSoto County",34.8749,-89.9912],"28035":["MS","Forrest County",31.1886,-89.2594],"28037":["MS","Franklin County",31.4778,-90.8955],"28039":["MS","George County",30.8554,-88.6423],"28041":["MS","Greene County",31.2128,-88.6348],"28043":["MS","Grenada County",33.77,-89.8027],"28045":["MS","Hancock County",30.3916,-89.4828],"28047":["MS","Harrison County",30.4165,-89.0834],"28049":["MS","Hinds County",32.2678,-90.466],"28051":["MS","Holmes County",33.1259,-90.0912],"28053":["MS","Humphreys County",33.131,-90.5234],"28055":["MS","Issaquena County",32.7555,-91.0035],"28057":["MS","Itawamba County",34.2811,-88.3631],"28059":["MS","Jackson County",30.456,-88.6251],"28061":["MS","Jasper County",32.0167,-89.1192],"28063":["MS","Jefferson County",31.7336,-91.0439],"28065":["MS","Jefferson Davis County",31.5648,-89.8271],"28067":["MS","Jones County",31.6166,-89.1685],"28069":["MS","Kemper County",32.7501,-88.6256],"28071":["MS","Lafayette County",34.3531,-89.4854],"28073":["MS","Lamar County",31.1976,-89.5064],"28075":["MS","Lauderdale County",32.404,-88.6605],"28077":["MS","Lawrence County",31.55,-90.1075],"28079":["MS","Leake County",32.7606,-89.5222],"28081":["MS","Lee County",34.2924,-88.6824],"28083":["MS","Leflore County",33.5498,-90.2949],"28085":["MS","Lincoln County",31.5352,-90.4536],"28087":["MS","Lowndes County",33.4714,-88.4397],"28089":["MS","Madison County",32.6344,-90.0342],"28091":["MS","Marion County",31.2315,-89.8223],"28093":["MS","Marshall County",34.7662,-89.5042],"28095":["MS","Monroe County",33.89,-88.485],"28097":["MS","Montgomery County",33.5007,-89.6396],"28099":["MS","Neshoba County",32.7525,-89.1193],"28101":["MS","Newton County",32.402,-89.1184],"28103":["MS","Noxubee County",33.1066,-88.5662],"28105":["MS","Oktibbeha County",33.4223,-88.8762],"28107":["MS","Panola County",34.3652,-89.9631],"28109":["MS","Pearl River County",30.7748,-89.5869],"28111":["MS","Perry County",31.1693,-88.9888],"28113":["MS","Pike County",31.1775,-90.3977],"28115":["MS","Pontotoc County",34.2271,-89.0372],"28117":["MS","Prentiss County",34.6206,-88.5222],"28119":["MS","Quitman County",34.2528,-90.2902],"28121":["MS","Rankin County",32.2671,-89.9461],"28123":["MS","Scott County",32.412,-89.5335],"28125":["MS","Sharkey County",32.8924,-90.8276],"28127":["MS","Simpson County",31.9025,-89.9177],"28129":["MS","Smith County",32.019,-89.4949],"28131":["MS","Stone County",30.7902,-89.1123],"28133":["MS","Sunflower County",33.6055,-90.5951],"28135":["MS","Tallahatchie County",33.9545,-90.1722],"28137":["MS","Tate County",34.6496,-89.9431],"28139":["MS","Tippah County",34.7636,-88.9188],"28141":["MS","Tishomingo County",34.7388,-88.2348],"28143":["MS","Tunica County",34.6522,-90.3718],"28145":["MS","Union County",34.4895,-89.0023],"28147":["MS","Walthall County",31.1645,-90.1034],"28149":["MS","Warren County",32.3561,-90.8524],"28151":["MS","Washington County",33.2732,-90.9444],"28153":["MS","Wayne County",31.6425,-88.6782],"28155":["MS","Webster County",33.6121,-89.284],"28157":["MS","Wilkinson County",31.1611,-91.3246],"28159":["MS","Winston County",33.0787,-89.0374],"28161":["MS","Yalobusha County",34.0307,-89.7038],"28163":["MS","Yazoo County",32.7657,-90.3879],"29001":["MO","Adair County",40.1907,-92.6036],"29003":["MO","Andrew County",39.9889,-94.8036],"29005":["MO","Atchison County",40.4318,-95.4376],"29007":["MO","Audrain County",39.2145,-91.8434],"29009":["MO","Barry County",36.6994,-93.8343],"29011":["MO","Barton County",37.5008,-94.3441],"29013":["MO","Bates County",38.2572,-94.3392],"29015":["MO","Benton County",38.301,-93.2879],"29017":["MO","Bollinger County",37.3184,-90.0246],"29019":["MO","Boone County",38.9899,-92.3102],"29021":["MO","Buchanan County",39.6604,-94.8082],"29023":["MO","Butler County",36.7152,-90.4031],"29025":["MO","Caldwell County",39.659,-93.9792],"29027":["MO","Callaway County",38.8355,-91.9234],"29029":["MO","Camden County",38.0265,-92.7653],"29031":["MO","Cape Girardeau County",37.3841,-89.6857],"29033":["MO","Carroll County",39.4274,-93.5002],"29035":["MO","Carter County",36.9449,-90.9457],"29037":["MO","Cass County",38.6465,-94.3545],"29039":["MO","Cedar County",37.7337,-93.85],"29041":["MO","Chariton County",39.518,-92.9616],"29043":["MO","Christian County",36.9697,-93.1876],"29045":["MO","Clark County",40.4073,-91.7295],"29047":["MO","Clay County",39.3156,-94.4215],"29049":["MO","Clinton County",39.6087,-94.3958],"29051":["MO","Cole County",38.5032,-92.28],"29053":["MO","Cooper County",38.8471,-92.8101],"29055":["MO","Crawford County",37.9666,-91.3139],"29057":["MO","Dade County",37.4323,-93.8549],"29059":["MO","Dallas County",37.6836,-93.0338],"29061":["MO","Daviess County",39.9628,-93.9701],"29063":["MO","DeKalb County",39.8947,-94.4072],"29065":["MO","Dent County",37.6031,-91.4897],"29067":["MO","Douglas County",36.9465,-92.5159],"29069":["MO","Dunklin County",36.153,-90.0623],"29071":["MO","Franklin County",38.413,-91.0728],"29073":["MO","Gasconade County",38.4412,-91.5058],"29075":["MO","Gentry County",40.2081,-94.4053],"29077":["MO","Greene County",37.2582,-93.3406],"29079":["MO","Grundy County",40.1125,-93.5651],"29081":["MO","Harrison County",40.3456,-93.9926],"29083":["MO","Henry County",38.3865,-93.7926],"29085":["MO","Hickory County",37.9369,-93.323],"29087":["MO","Holt County",40.0957,-95.2191],"29089":["MO","Howard County",39.1434,-92.6959],"29091":["MO","Howell County",36.7744,-91.8874],"29093":["MO","Iron County",37.626,-90.6996],"29095":["MO","Jackson County",39.0054,-94.3432],"29097":["MO","Jasper County",37.2052,-94.3373],"29099":["MO","Jefferson County",38.2576,-90.5437],"29101":["MO","Johnson County",38.7415,-93.8119],"29103":["MO","Knox County",40.1369,-92.1468],"29105":["MO","Laclede County",37.6597,-92.5948],"29107":["MO","Lafayette County",39.0687,-93.8026],"29109":["MO","Lawrence County",37.1066,-93.8305],"29111":["MO","Lewis County",40.0846,-91.7288],"29113":["MO","Lincoln County",39.0623,-90.9629],"29115":["MO","Linn County",39.8644,-93.108],"29117":["MO","Livingston County",39.7786,-93.5482],"29119":["MO","McDonald County",36.628,-94.3437],"29121":["MO","Macon County",39.8298,-92.5643],"29123":["MO","Madison County",37.4745,-90.3434],"29125":["MO","Maries County",38.1626,-91.9236],"29127":["MO","Marion County",39.8075,-91.6354],"29129":["MO","Mercer County",40.4214,-93.5676],"29131":["MO","Miller County",38.2167,-92.4299],"29133":["MO","Mississippi County",36.8263,-89.2959],"29135":["MO","Moniteau County",38.633,-92.5836],"29137":["MO","Monroe County",39.4983,-92.0065],"29139":["MO","Montgomery County",38.9352,-91.4654],"29141":["MO","Morgan County",38.4208,-92.8748],"29143":["MO","New Madrid County",36.5943,-89.6559],"29145":["MO","Newton County",36.9084,-94.335],"29147":["MO","Nodaway County",40.3611,-94.8831],"29149":["MO","Oregon County",36.6853,-91.4018],"29151":["MO","Osage County",38.4643,-91.8595],"29153":["MO","Ozark County",36.6496,-92.4585],"29155":["MO","Pemiscot County",36.2099,-89.7859],"29157":["MO","Perry County",37.7111,-89.8021],"29159":["MO","Pettis County",38.7274,-93.2852],"29161":["MO","Phelps County",37.8663,-91.7903],"29163":["MO","Pike County",39.34,-91.1716],"29165":["MO","Platte County",39.3787,-94.7615],"29167":["MO","Polk County",37.6168,-93.4008],"29169":["MO","Pulaski County",37.8248,-92.207],"29171":["MO","Putnam County",40.4786,-93.0145],"29173":["MO","Ralls County",39.5535,-91.5248],"29175":["MO","Randolph County",39.4392,-92.493],"29177":["MO","Ray County",39.3084,-93.9957],"29179":["MO","Reynolds County",37.3665,-90.9723],"29181":["MO","Ripley County",36.6502,-90.8748],"29183":["MO","St. Charles County",38.7811,-90.6749],"29185":["MO","St. Clair County",38.0422,-93.7766],"29186":["MO","Ste. Genevieve County",37.8858,-90.1615],"29187":["MO","St. Francois County",37.8107,-90.4739],"29189":["MO","St. Louis County",38.6407,-90.4461],"29195":["MO","Saline County",39.1358,-93.2042],"29197":["MO","Schuyler County",40.4694,-92.519],"29199":["MO","Scotland County",40.4477,-92.1428],"29201":["MO","Scott County",37.0478,-89.5681],"29203":["MO","Shannon County",37.1525,-91.3913],"29205":["MO","Shelby County",39.7975,-92.0887],"29207":["MO","Stoddard County",36.8516,-89.9475],"29209":["MO","Stone County",36.7458,-93.4578],"29211":["MO","Sullivan County",40.2096,-93.1098],"29213":["MO","Taney County",36.6498,-93.0428],"29215":["MO","Texas County",37.3143,-91.9645],"29217":["MO","Vernon County",37.8502,-94.3416],"29219":["MO","Warren County",38.7619,-91.1593],"29221":["MO","Washington County",37.9426,-90.897],"29223":["MO","Wayne County",37.1111,-90.4539],"29225":["MO","Webster County",37.2808,-92.8761],"29227":["MO","Worth County",40.4805,-94.4192],"29229":["MO","Wright County",37.2676,-92.48],"29510":["MO","St. Louis city",38.6357,-90.2446],"30001":["MT","Beaverhead County",45.1339,-112.8929],"30003":["MT","Big Horn County",45.4079,-107.5182],"30005":["MT","Blaine County",48.4283,-108.9676],"30007":["MT","Broadwater County",46.3298,-111.4979],"30009":["MT","Carbon County",45.2245,-109.0286],"30011":["MT","Carter County",45.5168,-104.5153],"30013":["MT","Cascade County",47.3166,-111.3503],"30015":["MT","Chouteau County",47.8868,-110.4362],"30017":["MT","Custer County",46.2614,-105.5504],"30019":["MT","Daniels County",48.7944,-105.5417],"30021":["MT","Dawson County",47.2661,-104.8983],"30023":["MT","Deer Lodge County",46.0947,-113.1416],"30025":["MT","Fallon County",46.3182,-104.4057],"30027":["MT","Fergus County",47.2218,-109.233],"30029":["MT","Flathead County",48.2954,-114.0521],"30031":["MT","Gallatin County",45.5181,-111.1639],"30033":["MT","Garfield County",47.2672,-106.996],"30035":["MT","Glacier County",48.7057,-112.9905],"30037":["MT","Golden Valley County",46.3806,-109.1746],"30039":["MT","Granite County",46.396,-113.4274],"30041":["MT","Hill County",48.632,-110.1063],"30043":["MT","Jefferson County",46.1242,-112.0594],"30045":["MT","Judith Basin County",47.0326,-110.3053],"30047":["MT","Lake County",47.6429,-114.0837],"30049":["MT","Lewis and Clark County",47.1221,-112.3829],"30051":["MT","Liberty County",48.5597,-111.0369],"30053":["MT","Lincoln County",48.5524,-115.4632],"30055":["MT","McCone County",47.6296,-105.7572],"30057":["MT","Madison County",45.3253,-111.9138],"30059":["MT","Meagher County",46.5857,-110.9217],"30061":["MT","Mineral County",47.1297,-115.0854],"30063":["MT","Missoula County",47.0273,-113.8927],"30065":["MT","Musselshell County",46.5053,-108.4398],"30067":["MT","Park County",45.4631,-110.5349],"30069":["MT","Petroleum County",47.1419,-108.2266],"30071":["MT","Phillips County",48.2501,-107.9289],"30073":["MT","Pondera County",48.2286,-112.2208],"30075":["MT","Powder River County",45.4089,-105.5553],"30077":["MT","Powell County",46.8442,-112.9311],"30079":["MT","Prairie County",46.8124,-105.5039],"30081":["MT","Ravalli County",46.0777,-114.1058],"30083":["MT","Richland County",47.7856,-104.5634],"30085":["MT","Roosevelt County",48.2827,-104.9952],"30087":["MT","Rosebud County",46.1732,-106.6668],"30089":["MT","Sanders County",47.7565,-115.1803],"30091":["MT","Sheridan County",48.7056,-104.5339],"30093":["MT","Silver Bow County",45.8962,-112.6601],"30095":["MT","Stillwater County",45.6585,-109.3816],"30097":["MT","Sweet Grass County",45.8113,-109.9448],"30099":["MT","Teton County",47.819,-112.2817],"30101":["MT","Toole County",48.6451,-111.7335],"30103":["MT","Treasure County",46.2271,-107.2753],"30105":["MT","Valley County",48.3499,-106.6704],"30107":["MT","Wheatland County",46.497,-109.8577],"30109":["MT","Wibaux County",46.963,-104.2745],"30111":["MT","Yellowstone County",45.937,-108.2767],"31001":["NE","Adams County",40.5206,-98.5],"31003":["NE","Antelope County",42.1832,-98.058],"31005":["NE","Arthur County",41.5719,-101.6959],"31007":["NE","Banner County",41.5397,-103.7263],"31009":["NE","Blaine County",41.9319,-99.9964],"31011":["NE","Boone County",41.7039,-98.0705],"31013":["NE","Box Butte County",42.2104,-103.0818],"31015":["NE","Boyd County",42.8944,-98.773],"31017":["NE","Brown County",42.3596,-99.9239],"31019":["NE","Buffalo County",40.8553,-99.075],"31021":["NE","Burt County",41.8542,-96.3377],"31023":["NE","Butler County",41.2261,-97.132],"31025":["NE","Cass County",40.9099,-96.1406],"31027":["NE","Cedar County",42.6046,-97.2569],"31029":["NE","Chase County",40.5304,-101.6942],"31031":["NE","Cherry County",42.5713,-101.0477],"31033":["NE","Cheyenne County",41.2142,-103.0119],"31035":["NE","Clay County",40.5237,-98.0509],"31037":["NE","Colfax County",41.575,-97.0889],"31039":["NE","Cuming County",41.9159,-96.7885],"31041":["NE","Custer County",41.3939,-99.7269],"31043":["NE","Dakota County",42.3916,-96.5613],"31045":["NE","Dawes County",42.713,-103.1354],"31047":["NE","Dawson County",40.8678,-99.8156],"31049":["NE","Deuel County",41.1119,-102.3326],"31051":["NE","Dixon County",42.4851,-96.8558],"31053":["NE","Dodge County",41.577,-96.6459],"31055":["NE","Douglas County",41.2971,-96.1541],"31057":["NE","Dundy County",40.1802,-101.6811],"31059":["NE","Fillmore County",40.525,-97.5967],"31061":["NE","Franklin County",40.1832,-98.9621],"31063":["NE","Frontier County",40.5309,-100.4067],"31065":["NE","Furnas County",40.1923,-99.9086],"31067":["NE","Gage County",40.2552,-96.6835],"31069":["NE","Garden County",41.6334,-102.303],"31071":["NE","Garfield County",41.9069,-98.9513],"31073":["NE","Gosper County",40.5091,-99.8232],"31075":["NE","Grant County",41.914,-101.756],"31077":["NE","Greeley County",41.5676,-98.5306],"31079":["NE","Hall County",40.866,-98.5027],"31081":["NE","Hamilton County",40.8728,-98.0223],"31083":["NE","Harlan County",40.1788,-99.4034],"31085":["NE","Hayes County",40.5372,-101.048],"31087":["NE","Hitchcock County",40.1769,-101.0442],"31089":["NE","Holt County",42.4593,-98.7848],"31091":["NE","Hooker County",41.9203,-101.1173],"31093":["NE","Howard County",41.2169,-98.5133],"31095":["NE","Jefferson County",40.1757,-97.1431],"31097":["NE","Johnson County",40.395,-96.2653],"31099":["NE","Kearney County",40.5091,-98.9476],"31101":["NE","Keith County",41.1942,-101.6444],"31103":["NE","Keya Paha County",42.8755,-99.7184],"31105":["NE","Kimball County",41.1993,-103.7032],"31107":["NE","Knox County",42.6344,-97.8913],"31109":["NE","Lancaster County",40.7835,-96.6887],"31111":["NE","Lincoln County",41.0503,-100.7445],"31113":["NE","Logan County",41.5422,-100.4437],"31115":["NE","Loup County",41.8982,-99.5145],"31117":["NE","McPherson County",41.6484,-101.1209],"31119":["NE","Madison County",41.9099,-97.6069],"31121":["NE","Merrick County",41.1698,-98.0311],"31123":["NE","Morrill County",41.7322,-102.9906],"31125":["NE","Nance County",41.4024,-97.9914],"31127":["NE","Nemaha County",40.3872,-95.8525],"31129":["NE","Nuckolls County",40.1765,-98.0468],"31131":["NE","Otoe County",40.638,-96.131],"31133":["NE","Pawnee County",40.1378,-96.2452],"31135":["NE","Perkins County",40.8576,-101.6275],"31137":["NE","Phelps County",40.5164,-99.4066],"31139":["NE","Pierce County",42.2714,-97.611],"31141":["NE","Platte County",41.5769,-97.5135],"31143":["NE","Polk County",41.1879,-97.5707],"31145":["NE","Red Willow County",40.1694,-100.4686],"31147":["NE","Richardson County",40.1237,-95.7186],"31149":["NE","Rock County",42.3947,-99.4209],"31151":["NE","Saline County",40.5168,-97.1318],"31153":["NE","Sarpy County",41.1151,-96.1091],"31155":["NE","Saunders County",41.223,-96.6427],"31157":["NE","Scotts Bluff County",41.8505,-103.703],"31159":["NE","Seward County",40.8719,-97.1404],"31161":["NE","Sheridan County",42.5123,-102.3683],"31163":["NE","Sherman County",41.2187,-98.9728],"31165":["NE","Sioux County",42.4707,-103.7322],"31167":["NE","Stanton County",41.905,-97.1771],"31169":["NE","Thayer County",40.1734,-97.5963],"31171":["NE","Thomas County",41.8557,-100.5247],"31173":["NE","Thurston County",42.1541,-96.5339],"31175":["NE","Valley County",41.5641,-98.9835],"31177":["NE","Washington County",41.534,-96.2246],"31179":["NE","Wayne County",42.2107,-97.1262],"31181":["NE","Webster County",40.1806,-98.4986],"31183":["NE","Wheeler County",41.9226,-98.5209],"31185":["NE","York County",40.8731,-97.5967],"32001":["NV","Churchill County",39.5377,-118.2642],"32003":["NV","Clark County",36.2141,-115.0144],"32005":["NV","Douglas County",38.9051,-119.609],"32007":["NV","Elko County",41.1411,-115.3514],"32009":["NV","Esmeralda County",37.779,-117.6324],"32011":["NV","Eureka County",39.9778,-116.2722],"32013":["NV","Humboldt County",41.4079,-118.1276],"32015":["NV","Lander County",39.9002,-117.0472],"32017":["NV","Lincoln County",37.6346,-114.863],"32019":["NV","Lyon County",39.0222,-119.1974],"32021":["NV","Mineral County",38.5166,-118.4163],"32023":["NV","Nye County",37.9659,-116.459],"32027":["NV","Pershing County",40.4396,-118.4095],"32029":["NV","Storey County",39.4384,-119.5246],"32031":["NV","Washoe County",40.7313,-119.6633],"32033":["NV","White Pine County",39.4182,-114.9006],"32510":["NV","Carson City",39.1531,-119.7474],"33001":["NH","Belknap County",43.5191,-71.4254],"33003":["NH","Carroll County",43.8678,-71.2016],"33005":["NH","Cheshire County",42.9255,-72.2482],"33007":["NH","Coos County",44.6525,-71.2894],"33009":["NH","Grafton County",43.9264,-71.8424],"33011":["NH","Hillsborough County",42.9115,-71.7231],"33013":["NH","Merrimack County",43.2996,-71.68],"33015":["NH","Rockingham County",42.9887,-71.0991],"33017":["NH","Strafford County",43.2933,-71.0356],"33019":["NH","Sullivan County",43.3612,-72.2221],"34001":["NJ","Atlantic County",39.4694,-74.6338],"34003":["NJ","Bergen County",40.9597,-74.0747],"34005":["NJ","Burlington County",39.8758,-74.663],"34007":["NJ","Camden County",39.8024,-74.9612],"34009":["NJ","Cape May County",39.0858,-74.8464],"34011":["NJ","Cumberland County",39.3284,-75.1216],"34013":["NJ","Essex County",40.7874,-74.2463],"34015":["NJ","Gloucester County",39.7229,-75.1457],"34017":["NJ","Hudson County",40.7314,-74.0786],"34019":["NJ","Hunterdon County",40.5653,-74.912],"34021":["NJ","Mercer County",40.2825,-74.7037],"34023":["NJ","Middlesex County",40.4396,-74.4074],"34025":["NJ","Monmouth County",40.287,-74.1524],"34027":["NJ","Morris County",40.8589,-74.5473],"34029":["NJ","Ocean County",39.8657,-74.2589],"34031":["NJ","Passaic County",41.0367,-74.2994],"34033":["NJ","Salem County",39.5738,-75.3574],"34035":["NJ","Somerset County",40.5655,-74.6199],"34037":["NJ","Sussex County",41.1375,-74.6919],"34039":["NJ","Union County",40.6599,-74.3087],"34041":["NJ","Warren County",40.8535,-75.0095],"35001":["NM","Bernalillo County",35.0536,-106.6691],"35003":["NM","Catron County",33.9016,-108.3919],"35005":["NM","Chaves County",33.3616,-104.4698],"35006":["NM","Cibola County",34.9283,-107.9927],"35007":["NM","Colfax County",36.613,-104.6401],"35009":["NM","Curry County",34.573,-103.3461],"35011":["NM","De Baca County",34.3593,-104.3687],"35013":["NM","Do\xC3\xB1a Ana County",32.3499,-106.835],"35015":["NM","Eddy County",32.4578,-104.3064],"35017":["NM","Grant County",32.7321,-108.3815],"35019":["NM","Guadalupe County",34.8697,-104.7849],"35021":["NM","Harding County",35.8594,-103.8534],"35023":["NM","Hidalgo County",31.8981,-108.7519],"35025":["NM","Lea County",32.7957,-103.4133],"35027":["NM","Lincoln County",33.7408,-105.4498],"35028":["NM","Los Alamos County",35.87,-106.308],"35029":["NM","Luna County",32.1845,-107.7472],"35031":["NM","McKinley County",35.5841,-108.2533],"35033":["NM","Mora County",35.9828,-104.9219],"35035":["NM","Otero County",32.6156,-105.7513],"35037":["NM","Quay County",35.107,-103.5481],"35039":["NM","Rio Arriba County",36.5097,-106.694],"35041":["NM","Roosevelt County",34.0212,-103.483],"35043":["NM","Sandoval County",35.6851,-106.8831],"35045":["NM","San Juan County",36.5116,-108.3246],"35047":["NM","San Miguel County",35.4769,-104.8035],"35049":["NM","Santa Fe County",35.5145,-105.964],"35051":["NM","Sierra County",33.1195,-107.1882],"35053":["NM","Socorro County",33.9917,-106.9391],"35055":["NM","Taos County",36.5772,-105.6389],"35057":["NM","Torrance County",34.555,-105.8906],"35059":["NM","Union County",36.4881,-103.4757],"35061":["NM","Valencia County",34.7168,-106.8066],"36001":["NY","Albany County",42.5882,-73.974],"36003":["NY","Allegany County",42.2479,-78.0262],"36005":["NY","Bronx County",40.8487,-73.8529],"36007":["NY","Broome County",42.162,-75.8303],"36009":["NY","Cattaraugus County",42.2391,-78.6623],"36011":["NY","Cayuga County",43.0085,-76.5746],"36013":["NY","Chautauqua County",42.3042,-79.4076],"36015":["NY","Chemung County",42.1487,-76.7525],"36017":["NY","Chenango County",42.478,-75.6022],"36019":["NY","Clinton County",44.7527,-73.7056],"36021":["NY","Columbia County",42.2477,-73.6267],"36023":["NY","Cortland County",42.594,-76.0762],"36025":["NY","Delaware County",42.194,-74.9667],"36027":["NY","Dutchess County",41.7548,-73.74],"36029":["NY","Erie County",42.7528,-78.7782],"36031":["NY","Essex County",44.1096,-73.7784],"36033":["NY","Franklin County",44.5944,-74.3107],"36035":["NY","Fulton County",43.1156,-74.4237],"36037":["NY","Genesee County",43.0009,-78.1928],"36039":["NY","Greene County",42.287,-74.1495],"36041":["NY","Hamilton County",43.6579,-74.5025],"36043":["NY","Herkimer County",43.571,-74.8411],"36045":["NY","Jefferson County",43.9964,-76.053],"36047":["NY","Kings County",40.635,-73.9506],"36049":["NY","Lewis County",43.7827,-75.4441],"36051":["NY","Livingston County",42.729,-77.7785],"36053":["NY","Madison County",42.91,-75.6636],"36055":["NY","Monroe County",43.2503,-77.7005],"36057":["NY","Montgomery County",42.9009,-74.4354],"36059":["NY","Nassau County",40.7296,-73.5894],"36061":["NY","New York County",40.7766,-73.9702],"36063":["NY","Niagara County",43.2727,-78.8129],"36065":["NY","Oneida County",43.2427,-75.4343],"36067":["NY","Onondaga County",43.0065,-76.1961],"36069":["NY","Ontario County",42.8564,-77.3035],"36071":["NY","Orange County",41.4024,-74.3063],"36073":["NY","Orleans County",43.3399,-78.207],"36075":["NY","Oswego County",43.4614,-76.2093],"36077":["NY","Otsego County",42.6298,-75.0288],"36079":["NY","Putnam County",41.4279,-73.7439],"36081":["NY","Queens County",40.6547,-73.8412],"36083":["NY","Rensselaer County",42.7104,-73.5138],"36085":["NY","Richmond County",40.5613,-74.1399],"36087":["NY","Rockland County",41.1546,-74.0247],"36089":["NY","St. Lawrence County",44.4881,-75.0743],"36091":["NY","Saratoga County",43.1061,-73.8554],"36093":["NY","Schenectady County",42.8176,-74.0436],"36095":["NY","Schoharie County",42.5913,-74.4382],"36097":["NY","Schuyler County",42.4198,-76.9386],"36099":["NY","Seneca County",42.7823,-76.8271],"36101":["NY","Steuben County",42.2667,-77.3855],"36103":["NY","Suffolk County",40.9436,-72.6922],"36105":["NY","Sullivan County",41.72,-74.7716],"36107":["NY","Tioga County",42.1781,-76.2975],"36109":["NY","Tompkins County",42.453,-76.4735],"36111":["NY","Ulster County",41.9472,-74.2655],"36113":["NY","Warren County",43.5551,-73.8381],"36115":["NY","Washington County",43.3124,-73.4394],"36117":["NY","Wayne County",43.2181,-77.0494],"36119":["NY","Westchester County",41.1527,-73.7458],"36121":["NY","Wyoming County",42.7014,-78.2286],"36123":["NY","Yates County",42.6382,-77.1043],"37001":["NC","Alamance County",36.044,-79.4006],"37003":["NC","Alexander County",35.921,-81.1775],"37005":["NC","Alleghany County",36.4894,-81.1323],"37007":["NC","Anson County",34.975,-80.1098],"37009":["NC","Ashe County",36.4435,-81.4993],"37011":["NC","Avery County",36.0721,-81.9203],"37013":["NC","Beaufort County",35.4823,-76.842],"37015":["NC","Bertie County",36.059,-76.9624],"37017":["NC","Bladen County",34.5919,-78.5395],"37019":["NC","Brunswick County",34.0388,-78.2278],"37021":["NC","Buncombe County",35.6094,-82.5304],"37023":["NC","Burke County",35.7462,-81.7062],"37025":["NC","Cabarrus County",35.3883,-80.5527],"37027":["NC","Caldwell County",35.9664,-81.5125],"37029":["NC","Camden County",36.3423,-76.1625],"37031":["NC","Carteret County",34.8583,-76.5359],"37033":["NC","Caswell County",36.3943,-79.3396],"37035":["NC","Catawba County",35.6619,-81.2149],"37037":["NC","Chatham County",35.705,-79.2515],"37039":["NC","Cherokee County",35.1371,-84.0614],"37041":["NC","Chowan County",36.129,-76.6028],"37043":["NC","Clay County",35.053,-83.7523],"37045":["NC","Cleveland County",35.3346,-81.5571],"37047":["NC","Columbus County",34.2616,-78.6393],"37049":["NC","Craven County",35.1168,-77.0813],"37051":["NC","Cumberland County",35.0502,-78.8287],"37053":["NC","Currituck County",36.3722,-75.9412],"37055":["NC","Dare County",35.6063,-75.7675],"37057":["NC","Davidson County",35.7951,-80.2071],"37059":["NC","Davie County",35.9294,-80.5426],"37061":["NC","Duplin County",34.9344,-77.9335],"37063":["NC","Durham County",36.0338,-78.8781],"37065":["NC","Edgecombe County",35.9171,-77.6027],"37067":["NC","Forsyth County",36.1325,-80.257],"37069":["NC","Franklin County",36.0882,-78.2831],"37071":["NC","Gaston County",35.2928,-81.1774],"37073":["NC","Gates County",36.4421,-76.7024],"37075":["NC","Graham County",35.3484,-83.8309],"37077":["NC","Granville County",36.2999,-78.6576],"37079":["NC","Greene County",35.482,-77.6817],"37081":["NC","Guilford County",36.0791,-79.7887],"37083":["NC","Halifax County",36.2514,-77.6448],"37085":["NC","Harnett County",35.3687,-78.8717],"37087":["NC","Haywood County",35.5589,-82.9813],"37089":["NC","Henderson County",35.3364,-82.4796],"37091":["NC","Hertford County",36.3635,-76.9816],"37093":["NC","Hoke County",35.0172,-79.242],"37095":["NC","Hyde County",35.4082,-76.1537],"37097":["NC","Iredell County",35.8063,-80.8745],"37099":["NC","Jackson County",35.2855,-83.124],"37101":["NC","Johnston County",35.5134,-78.3673],"37103":["NC","Jones County",35.0323,-77.3562],"37105":["NC","Lee County",35.4763,-79.1721],"37107":["NC","Lenoir County",35.2401,-77.6355],"37109":["NC","Lincoln County",35.4885,-81.2269],"37111":["NC","McDowell County",35.6823,-82.048],"37113":["NC","Macon County",35.153,-83.4219],"37115":["NC","Madison County",35.8642,-82.7126],"37117":["NC","Martin County",35.8473,-77.1196],"37119":["NC","Mecklenburg County",35.2469,-80.8338],"37121":["NC","Mitchell County",36.0131,-82.1636],"37123":["NC","Montgomery County",35.3275,-79.9108],"37125":["NC","Moore County",35.3083,-79.4927],"37127":["NC","Nash County",35.9659,-77.9876],"37129":["NC","New Hanover County",34.1834,-77.8642],"37131":["NC","Northampton County",36.4218,-77.3984],"37133":["NC","Onslow County",34.7631,-77.4995],"37135":["NC","Orange County",36.0625,-79.12],"37137":["NC","Pamlico County",35.1476,-76.6653],"37139":["NC","Pasquotank County",36.2652,-76.2607],"37141":["NC","Pender County",34.5126,-77.8881],"37143":["NC","Perquimans County",36.1809,-76.4032],"37145":["NC","Person County",36.3864,-78.9656],"37147":["NC","Pitt County",35.5925,-77.3727],"37149":["NC","Polk County",35.2779,-82.1676],"37151":["NC","Randolph County",35.7099,-79.8062],"37153":["NC","Richmond County",35.0046,-79.7557],"37155":["NC","Robeson County",34.6392,-79.1009],"37157":["NC","Rockingham County",36.3818,-79.7828],"37159":["NC","Rowan County",35.6414,-80.5217],"37161":["NC","Rutherford County",35.4027,-81.9196],"37163":["NC","Sampson County",34.9893,-78.3713],"37165":["NC","Scotland County",34.84,-79.4773],"37167":["NC","Stanly County",35.3104,-80.2544],"37169":["NC","Stokes County",36.3938,-80.2699],"37171":["NC","Surry County",36.4154,-80.6865],"37173":["NC","Swain County",35.5688,-83.4656],"37175":["NC","Transylvania County",35.2101,-82.8167],"37177":["NC","Tyrrell County",35.8704,-76.1653],"37179":["NC","Union County",34.9918,-80.5304],"37181":["NC","Vance County",36.3655,-78.4054],"37183":["NC","Wake County",35.7898,-78.6506],"37185":["NC","Warren County",36.3981,-78.0999],"37187":["NC","Washington County",35.8447,-76.5723],"37189":["NC","Watauga County",36.2354,-81.7099],"37191":["NC","Wayne County",35.3542,-78.0087],"37193":["NC","Wilkes County",36.2089,-81.1661],"37195":["NC","Wilson County",35.7004,-77.9216],"37197":["NC","Yadkin County",36.1588,-80.6652],"37199":["NC","Yancey County",35.8893,-82.304],"38001":["ND","Adams County",46.0968,-102.5332],"38003":["ND","Barnes County",46.9425,-98.0702],"38005":["ND","Benson County",48.0717,-99.3512],"38007":["ND","Billings County",47.007,-103.364],"38009":["ND","Bottineau County",48.7944,-100.8313],"38011":["ND","Bowman County",46.1101,-103.5059],"38013":["ND","Burke County",48.7865,-102.5201],"38015":["ND","Burleigh County",46.9788,-100.4695],"38017":["ND","Cass County",46.927,-97.2524],"38019":["ND","Cavalier County",48.7684,-98.4638],"38021":["ND","Dickey County",46.1078,-98.4965],"38023":["ND","Divide County",48.8148,-103.5093],"38025":["ND","Dunn County",47.3546,-102.6123],"38027":["ND","Eddy County",47.7234,-98.9005],"38029":["ND","Emmons County",46.2843,-100.2378],"38031":["ND","Foster County",47.4714,-98.8729],"38033":["ND","Golden Valley County",46.9389,-103.8446],"38035":["ND","Grand Forks County",47.926,-97.4509],"38037":["ND","Grant County",46.3578,-101.639],"38039":["ND","Griggs County",47.4563,-98.2323],"38041":["ND","Hettinger County",46.4357,-102.4542],"38043":["ND","Kidder County",46.9383,-99.7312],"38045":["ND","LaMoure County",46.4642,-98.5261],"38047":["ND","Logan County",46.4693,-99.5046],"38049":["ND","McHenry County",48.2338,-100.6333],"38051":["ND","McIntosh County",46.1087,-99.4165],"38053":["ND","McKenzie County",47.7425,-103.4032],"38055":["ND","McLean County",47.6532,-101.4219],"38057":["ND","Mercer County",47.3071,-101.8333],"38059":["ND","Morton County",46.71,-101.31],"38061":["ND","Mountrail County",48.2101,-102.3649],"38063":["ND","Nelson County",47.9187,-98.2044],"38065":["ND","Oliver County",47.1181,-101.3314],"38067":["ND","Pembina County",48.7669,-97.5454],"38069":["ND","Pierce County",48.2389,-99.9665],"38071":["ND","Ramsey County",48.2662,-98.739],"38073":["ND","Ransom County",46.4493,-97.6476],"38075":["ND","Renville County",48.7128,-101.6582],"38077":["ND","Richland County",46.2652,-96.938],"38079":["ND","Rolette County",48.7683,-99.8405],"38081":["ND","Sargent County",46.1082,-97.6301],"38083":["ND","Sheridan County",47.5814,-100.331],"38085":["ND","Sioux County",46.1106,-101.0613],"38087":["ND","Slope County",46.4458,-103.4625],"38089":["ND","Stark County",46.817,-102.662],"38091":["ND","Steele County",47.4511,-97.7189],"38093":["ND","Stutsman County",46.9722,-98.9561],"38095":["ND","Towner County",48.6822,-99.2482],"38097":["ND","Traill County",47.4463,-97.1646],"38099":["ND","Walsh County",48.377,-97.7222],"38101":["ND","Ward County",48.2167,-101.5405],"38103":["ND","Wells County",47.5809,-99.6822],"38105":["ND","Williams County",48.3558,-103.5013],"39001":["OH","Adams County",38.8345,-83.4781],"39003":["OH","Allen County",40.7716,-84.1061],"39005":["OH","Ashland County",40.8433,-82.2701],"39007":["OH","Ashtabula County",41.9066,-80.7456],"39009":["OH","Athens County",39.3328,-82.0459],"39011":["OH","Auglaize County",40.5613,-84.224],"39013":["OH","Belmont County",40.0177,-80.9677],"39015":["OH","Brown County",38.9314,-83.8668],"39017":["OH","Butler County",39.4397,-84.5657],"39019":["OH","Carroll County",40.5799,-81.0908],"39021":["OH","Champaign County",40.1328,-83.7676],"39023":["OH","Clark County",39.917,-83.7837],"39025":["OH","Clermont County",39.0521,-84.1495],"39027":["OH","Clinton County",39.4167,-83.8046],"39029":["OH","Columbiana County",40.7701,-80.7785],"39031":["OH","Coshocton County",40.2967,-81.9301],"39033":["OH","Crawford County",40.8485,-82.9248],"39035":["OH","Cuyahoga County",41.555,-81.605],"39037":["OH","Darke County",40.1315,-84.6212],"39039":["OH","Defiance County",41.3217,-84.4864],"39041":["OH","Delaware County",40.2789,-83.0075],"39043":["OH","Erie County",41.3941,-82.5868],"39045":["OH","Fairfield County",39.7477,-82.6267],"39047":["OH","Fayette County",39.5552,-83.4619],"39049":["OH","Franklin County",39.9699,-83.0091],"39051":["OH","Fulton County",41.5973,-84.1243],"39053":["OH","Gallia County",38.817,-82.3017],"39055":["OH","Geauga County",41.4993,-81.1735],"39057":["OH","Greene County",39.6875,-83.8949],"39059":["OH","Guernsey County",40.0567,-81.4979],"39061":["OH","Hamilton County",39.1969,-84.5442],"39063":["OH","Hancock County",41.0002,-83.6659],"39065":["OH","Hardin County",40.6604,-83.6641],"39067":["OH","Harrison County",40.2923,-81.0916],"39069":["OH","Henry County",41.3316,-84.0689],"39071":["OH","Highland County",39.1844,-83.6014],"39073":["OH","Hocking County",39.4903,-82.4834],"39075":["OH","Holmes County",40.5656,-81.93],"39077":["OH","Huron County",41.1451,-82.5946],"39079":["OH","Jackson County",39.0135,-82.6141],"39081":["OH","Jefferson County",40.3994,-80.7635],"39083":["OH","Knox County",40.4036,-82.4224],"39085":["OH","Lake County",41.7781,-81.1973],"39087":["OH","Lawrence County",38.6039,-82.5172],"39089":["OH","Licking County",40.0915,-82.4834],"39091":["OH","Logan County",40.3876,-83.7663],"39093":["OH","Lorain County",41.4388,-82.1797],"39095":["OH","Lucas County",41.6823,-83.4689],"39097":["OH","Madison County",39.8966,-83.4009],"39099":["OH","Mahoning County",41.0109,-80.7704],"39101":["OH","Marion County",40.588,-83.1688],"39103":["OH","Medina County",41.1162,-81.8998],"39105":["OH","Meigs County",39.0898,-82.0284],"39107":["OH","Mercer County",40.5353,-84.6321],"39109":["OH","Miami County",40.0533,-84.2284],"39111":["OH","Monroe County",39.7263,-81.091],"39113":["OH","Montgomery County",39.7537,-84.2906],"39115":["OH","Morgan County",39.6249,-81.8617],"39117":["OH","Morrow County",40.5253,-82.7977],"39119":["OH","Muskingum County",39.966,-81.9435],"39121":["OH","Noble County",39.7672,-81.4525],"39123":["OH","Ottawa County",41.5455,-83.0126],"39125":["OH","Paulding County",41.1189,-84.5821],"39127":["OH","Perry County",39.7432,-82.238],"39129":["OH","Pickaway County",39.6489,-83.0528],"39131":["OH","Pike County",39.0713,-83.0529],"39133":["OH","Portage County",41.169,-81.197],"39135":["OH","Preble County",39.7388,-84.6448],"39137":["OH","Putnam County",41.0245,-84.1299],"39139":["OH","Richland County",40.7742,-82.5428],"39141":["OH","Ross County",39.3239,-83.0595],"39143":["OH","Sandusky County",41.3553,-83.1428],"39145":["OH","Scioto County",38.8149,-82.9987],"39147":["OH","Seneca County",41.12,-83.1275],"39149":["OH","Shelby County",40.3367,-84.2041],"39151":["OH","Stark County",40.8141,-81.3657],"39153":["OH","Summit County",41.1218,-81.5349],"39155":["OH","Trumbull County",41.3064,-80.7704],"39157":["OH","Tuscarawas County",40.4474,-81.4712],"39159":["OH","Union County",40.2959,-83.367],"39161":["OH","Van Wert County",40.8555,-84.5858],"39163":["OH","Vinton County",39.252,-82.486],"39165":["OH","Warren County",39.4257,-84.1699],"39167":["OH","Washington County",39.4507,-81.4906],"39169":["OH","Wayne County",40.8297,-81.8872],"39171":["OH","Williams County",41.565,-84.5843],"39173":["OH","Wood County",41.3602,-83.6227],"39175":["OH","Wyandot County",40.8398,-83.3137],"40001":["OK","Adair County",35.898,-94.651],"40003":["OK","Alfalfa County",36.7297,-98.3234],"40005":["OK","Atoka County",34.3925,-96.0366],"40007":["OK","Beaver County",36.7483,-100.4831],"40009":["OK","Beckham County",35.2706,-99.6901],"40011":["OK","Blaine County",35.8778,-98.429],"40013":["OK","Bryan County",33.964,-96.2651],"40015":["OK","Caddo County",35.1679,-98.381],"40017":["OK","Canadian County",35.5434,-97.9799],"40019":["OK","Carter County",34.2518,-97.2879],"40021":["OK","Cherokee County",35.9044,-94.9968],"40023":["OK","Choctaw County",34.0277,-95.5541],"40025":["OK","Cimarron County",36.7484,-102.5177],"40027":["OK","Cleveland County",35.2064,-97.3231],"40029":["OK","Coal County",34.5829,-96.288],"40031":["OK","Comanche County",34.6626,-98.4766],"40033":["OK","Cotton County",34.2907,-98.3734],"40035":["OK","Craig County",36.7639,-95.2016],"40037":["OK","Creek County",35.9074,-96.3802],"40039":["OK","Custer County",35.6456,-98.9974],"40041":["OK","Delaware County",36.3934,-94.8082],"40043":["OK","Dewey County",35.978,-99.0144],"40045":["OK","Ellis County",36.2243,-99.7501],"40047":["OK","Garfield County",36.3781,-97.7887],"40049":["OK","Garvin County",34.7094,-97.3127],"40051":["OK","Grady County",35.0211,-97.8869],"40053":["OK","Grant County",36.7883,-97.7882],"40055":["OK","Greer County",34.9339,-99.553],"40057":["OK","Harmon County",34.746,-99.8442],"40059":["OK","Harper County",36.8004,-99.6628],"40061":["OK","Haskell County",35.2324,-95.1096],"40063":["OK","Hughes County",35.0529,-96.2512],"40065":["OK","Jackson County",34.594,-99.4122],"40067":["OK","Jefferson County",34.1051,-97.8389],"40069":["OK","Johnston County",34.3135,-96.6543],"40071":["OK","Kay County",36.8149,-97.1439],"40073":["OK","Kingfisher County",35.9494,-97.9346],"40075":["OK","Kiowa County",34.9215,-98.9816],"40077":["OK","Latimer County",34.8751,-95.2723],"40079":["OK","Le Flore County",34.8974,-94.6951],"40081":["OK","Lincoln County",35.7031,-96.8814],"40083":["OK","Logan County",35.9143,-97.451],"40085":["OK","Love County",33.9578,-97.2451],"40087":["OK","McClain County",35.0164,-97.4498],"40089":["OK","McCurtain County",34.1171,-94.7661],"40091":["OK","McIntosh County",35.3691,-95.6718],"40093":["OK","Major County",36.3131,-98.542],"40095":["OK","Marshall County",34.027,-96.7705],"40097":["OK","Mayes County",36.3038,-95.2356],"40099":["OK","Murray County",34.4858,-97.0716],"40101":["OK","Muskogee County",35.6176,-95.3839],"40103":["OK","Noble County",36.3849,-97.2363],"40105":["OK","Nowata County",36.7896,-95.6133],"40107":["OK","Okfuskee County",35.4668,-96.3278],"40109":["OK","Oklahoma County",35.5546,-97.4094],"40111":["OK","Okmulgee County",35.6435,-95.9659],"40113":["OK","Osage County",36.6243,-96.4081],"40115":["OK","Ottawa County",36.8358,-94.8027],"40117":["OK","Pawnee County",36.3137,-96.6967],"40119":["OK","Payne County",36.0792,-96.9753],"40121":["OK","Pittsburg County",34.9255,-95.7481],"40123":["OK","Pontotoc County",34.7214,-96.6918],"40125":["OK","Pottawatomie County",35.2114,-96.957],"40127":["OK","Pushmataha County",34.3779,-95.4081],"40129":["OK","Roger Mills County",35.7086,-99.7416],"40131":["OK","Rogers County",36.3778,-95.6014],"40133":["OK","Seminole County",35.1584,-96.6029],"40135":["OK","Sequoyah County",35.5024,-94.7508],"40137":["OK","Stephens County",34.4814,-97.8556],"40139":["OK","Texas County",36.7463,-101.4839],"40141":["OK","Tillman County",34.3711,-98.9317],"40143":["OK","Tulsa County",36.1203,-95.9418],"40145":["OK","Wagoner County",35.9634,-95.5142],"40147":["OK","Washington County",36.7044,-95.9063],"40149":["OK","Washita County",35.2899,-98.9923],"40151":["OK","Woods County",36.727,-98.8636],"40153":["OK","Woodward County",36.4256,-99.2737],"41001":["OR","Baker County",44.7034,-117.6919],"41003":["OR","Benton County",44.4939,-123.4247],"41005":["OR","Clackamas County",45.1605,-122.1951],"41007":["OR","Clatsop County",46.0245,-123.705],"41009":["OR","Columbia County",45.9419,-123.0811],"41011":["OR","Coos County",43.1859,-124.0941],"41013":["OR","Crook County",44.1631,-120.3716],"41015":["OR","Curry County",42.4664,-124.2109],"41017":["OR","Deschutes County",43.9151,-121.2256],"41019":["OR","Douglas County",43.2863,-123.1545],"41021":["OR","Gilliam County",45.383,-120.2762],"41023":["OR","Grant County",44.4963,-119.0141],"41025":["OR","Harney County",43.0644,-118.9872],"41027":["OR","Hood River County",45.5118,-121.656],"41029":["OR","Jackson County",42.4116,-122.6756],"41031":["OR","Jefferson County",44.6452,-121.1786],"41033":["OR","Josephine County",42.387,-123.5716],"41035":["OR","Klamath County",42.6838,-121.6462],"41037":["OR","Lake County",42.7884,-120.3898],"41039":["OR","Lane County",43.9283,-122.8976],"41041":["OR","Lincoln County",44.6411,-123.9112],"41043":["OR","Linn County",44.4889,-122.5372],"41045":["OR","Malheur County",43.1886,-117.6032],"41047":["OR","Marion County",44.9009,-122.5763],"41049":["OR","Morrow County",45.4255,-119.6023],"41051":["OR","Multnomah County",45.5477,-122.4174],"41053":["OR","Polk County",44.9004,-123.3986],"41055":["OR","Sherman County",45.3992,-120.6785],"41057":["OR","Tillamook County",45.4559,-123.7593],"41059":["OR","Umatilla County",45.5912,-118.7339],"41061":["OR","Union County",45.3041,-117.9991],"41063":["OR","Wallowa County",45.5938,-117.1856],"41065":["OR","Wasco County",45.1645,-121.1651],"41067":["OR","Washington County",45.5535,-123.0976],"41069":["OR","Wheeler County",44.7364,-120.0269],"41071":["OR","Yamhill County",45.2478,-123.3164],"42001":["PA","Adams County",39.8694,-77.2177],"42003":["PA","Allegheny County",40.4698,-79.9805],"42005":["PA","Armstrong County",40.8124,-79.4641],"42007":["PA","Beaver County",40.6841,-80.3507],"42009":["PA","Bedford County",39.9986,-78.4947],"42011":["PA","Berks County",40.414,-75.9269],"42013":["PA","Blair County",40.4987,-78.3096],"42015":["PA","Bradford County",41.7915,-76.5021],"42017":["PA","Bucks County",40.3369,-75.1071],"42019":["PA","Butler County",40.9138,-79.919],"42021":["PA","Cambria County",40.5102,-78.7105],"42023":["PA","Cameron County",41.4383,-78.1983],"42025":["PA","Carbon County",40.9184,-75.705],"42027":["PA","Centre County",40.9093,-77.8477],"42029":["PA","Chester County",39.974,-75.7498],"42031":["PA","Clarion County",41.1982,-79.4204],"42033":["PA","Clearfield County",41.0069,-78.4777],"42035":["PA","Clinton County",41.2395,-77.629],"42037":["PA","Columbia County",41.0455,-76.4043],"42039":["PA","Crawford County",41.6879,-80.1078],"42041":["PA","Cumberland County",40.1648,-77.2634],"42043":["PA","Dauphin County",40.4126,-76.7926],"42045":["PA","Delaware County",39.9167,-75.3988],"42047":["PA","Elk County",41.4273,-78.6539],"42049":["PA","Erie County",42.118,-80.0964],"42051":["PA","Fayette County",39.9189,-79.6403],"42053":["PA","Forest County",41.5133,-79.2497],"42055":["PA","Franklin County",39.9268,-77.7245],"42057":["PA","Fulton County",39.9108,-78.1226],"42059":["PA","Greene County",39.8477,-80.2257],"42061":["PA","Huntingdon County",40.4223,-77.9686],"42063":["PA","Indiana County",40.6514,-79.0875],"42065":["PA","Jefferson County",41.138,-79.0124],"42067":["PA","Juniata County",40.5307,-77.4004],"42069":["PA","Lackawanna County",41.4366,-75.6088],"42071":["PA","Lancaster County",40.042,-76.2502],"42073":["PA","Lawrence County",40.9927,-80.3344],"42075":["PA","Lebanon County",40.3714,-76.4648],"42077":["PA","Lehigh County",40.6142,-75.5906],"42079":["PA","Luzerne County",41.1731,-75.9761],"42081":["PA","Lycoming County",41.3439,-77.0553],"42083":["PA","McKean County",41.8146,-78.5725],"42085":["PA","Mercer County",41.3,-80.2528],"42087":["PA","Mifflin County",40.6016,-77.6518],"42089":["PA","Monroe County",41.0562,-75.3291],"42091":["PA","Montgomery County",40.21,-75.3702],"42093":["PA","Montour County",41.0293,-76.6652],"42095":["PA","Northampton County",40.7528,-75.3074],"42097":["PA","Northumberland County",40.8515,-76.7099],"42099":["PA","Perry County",40.3978,-77.2663],"42101":["PA","Philadelphia County",40.0094,-75.1333],"42103":["PA","Pike County",41.3259,-75.0315],"42105":["PA","Potter County",41.7486,-77.8944],"42107":["PA","Schuylkill County",40.7037,-76.2178],"42109":["PA","Snyder County",40.7554,-77.073],"42111":["PA","Somerset County",39.9813,-79.0285],"42113":["PA","Sullivan County",41.4393,-76.5117],"42115":["PA","Susquehanna County",41.8197,-75.801],"42117":["PA","Tioga County",41.7669,-77.2573],"42119":["PA","Union County",40.9622,-77.0555],"42121":["PA","Venango County",41.4007,-79.7658],"42123":["PA","Warren County",41.8343,-79.2982],"42125":["PA","Washington County",40.2,-80.2521],"42127":["PA","Wayne County",41.6466,-75.2925],"42129":["PA","Westmoreland County",40.3111,-79.4667],"42131":["PA","Wyoming County",41.5252,-76.0087],"42133":["PA","York County",39.9218,-76.7289],"44001":["RI","Bristol County",41.7068,-71.2867],"44003":["RI","Kent County",41.6751,-71.5803],"44005":["RI","Newport County",41.501,-71.2831],"44007":["RI","Providence County",41.8698,-71.5786],"44009":["RI","Washington County",41.3968,-71.6203],"45001":["SC","Abbeville County",34.229,-82.4541],"45003":["SC","Aiken County",33.55,-81.633],"45005":["SC","Allendale County",32.9798,-81.3633],"45007":["SC","Anderson County",34.5212,-82.6386],"45009":["SC","Bamberg County",33.203,-81.0532],"45011":["SC","Barnwell County",33.2606,-81.4342],"45013":["SC","Beaufort County",32.3581,-80.6894],"45015":["SC","Berkeley County",33.2077,-79.9537],"45017":["SC","Calhoun County",33.6748,-80.7803],"45019":["SC","Charleston County",32.8005,-79.9425],"45021":["SC","Cherokee County",35.0498,-81.6076],"45023":["SC","Chester County",34.6893,-81.1612],"45025":["SC","Chesterfield County",34.637,-80.1592],"45027":["SC","Clarendon County",33.6647,-80.2179],"45029":["SC","Colleton County",32.8494,-80.6564],"45031":["SC","Darlington County",34.3322,-79.9621],"45033":["SC","Dillon County",34.3902,-79.3752],"45035":["SC","Dorchester County",33.0822,-80.4047],"45037":["SC","Edgefield County",33.7795,-81.9596],"45039":["SC","Fairfield County",34.3957,-81.127],"45041":["SC","Florence County",34.0285,-79.7102],"45043":["SC","Georgetown County",33.4175,-79.2963],"45045":["SC","Greenville County",34.8926,-82.3721],"45047":["SC","Greenwood County",34.1558,-82.1279],"45049":["SC","Hampton County",32.7783,-81.1438],"45051":["SC","Horry County",33.9093,-78.9767],"45053":["SC","Jasper County",32.4306,-81.0216],"45055":["SC","Kershaw County",34.3384,-80.5909],"45057":["SC","Lancaster County",34.6868,-80.7037],"45059":["SC","Laurens County",34.4837,-82.0055],"45061":["SC","Lee County",34.1586,-80.2512],"45063":["SC","Lexington County",33.8923,-81.273],"45065":["SC","McCormick County",33.8976,-82.3162],"45067":["SC","Marion County",34.0836,-79.354],"45069":["SC","Marlboro County",34.6017,-79.6794],"45071":["SC","Newberry County",34.2899,-81.5997],"45073":["SC","Oconee County",34.7488,-83.0615],"45075":["SC","Orangeburg County",33.4361,-80.8029],"45077":["SC","Pickens County",34.8854,-82.7234],"45079":["SC","Richland County",34.0291,-80.898],"45081":["SC","Saluda County",34.0053,-81.7279],"45083":["SC","Spartanburg County",34.932,-81.9916],"45085":["SC","Sumter County",33.9161,-80.3824],"45087":["SC","Union County",34.6904,-81.6159],"45089":["SC","Williamsburg County",33.6265,-79.7165],"45091":["SC","York County",34.9702,-81.1832],"46003":["SD","Aurora County",43.7247,-98.5776],"46005":["SD","Beadle County",44.4183,-98.2794],"46007":["SD","Bennett County",43.1869,-101.6772],"46009":["SD","Bon Homme County",42.9857,-97.8842],"46011":["SD","Brookings County",44.3767,-96.7978],"46013":["SD","Brown County",45.5893,-98.3522],"46015":["SD","Brule County",43.7299,-99.0929],"46017":["SD","Buffalo County",44.0443,-99.204],"46019":["SD","Butte County",44.8962,-103.5014],"46021":["SD","Campbell County",45.7856,-100.0021],"46023":["SD","Charles Mix County",43.2062,-98.5951],"46025":["SD","Clark County",44.8552,-97.7249],"46027":["SD","Clay County",42.9162,-96.9805],"46029":["SD","Codington County",44.9663,-97.1988],"46031":["SD","Corson County",45.6857,-101.1797],"46033":["SD","Custer County",43.6849,-103.4622],"46035":["SD","Davison County",43.6804,-98.1559],"46037":["SD","Day County",45.3552,-97.5814],"46039":["SD","Deuel County",44.7563,-96.6902],"46041":["SD","Dewey County",45.148,-100.838],"46043":["SD","Douglas County",43.3915,-98.3584],"46045":["SD","Edmunds County",45.4117,-99.2054],"46047":["SD","Fall River County",43.2216,-103.5126],"46049":["SD","Faulk County",45.0655,-99.1536],"46051":["SD","Grant County",45.1726,-96.7723],"46053":["SD","Gregory County",43.1751,-99.2066],"46055":["SD","Haakon County",44.2881,-101.5409],"46057":["SD","Hamlin County",44.6806,-97.1786],"46059":["SD","Hand County",44.5467,-99.0046],"46061":["SD","Hanson County",43.6806,-97.7968],"46063":["SD","Harding County",45.5966,-103.4739],"46065":["SD","Hughes County",44.3845,-99.9757],"46067":["SD","Hutchinson County",43.3367,-97.7494],"46069":["SD","Hyde County",44.5372,-99.4727],"46071":["SD","Jackson County",43.6775,-101.6263],"46073":["SD","Jerauld County",44.0634,-98.6232],"46075":["SD","Jones County",43.952,-100.6861],"46077":["SD","Kingsbury County",44.363,-97.4993],"46079":["SD","Lake County",44.0284,-97.1232],"46081":["SD","Lawrence County",44.3485,-103.8064],"46083":["SD","Lincoln County",43.2794,-96.7223],"46085":["SD","Lyman County",43.8948,-99.8419],"46087":["SD","McCook County",43.6804,-97.358],"46089":["SD","McPherson County",45.7842,-99.2114],"46091":["SD","Marshall County",45.737,-97.5809],"46093":["SD","Meade County",44.6053,-102.7142],"46095":["SD","Mellette County",43.5813,-100.7552],"46097":["SD","Miner County",44.0215,-97.6081],"46099":["SD","Minnehaha County",43.6675,-96.7957],"46101":["SD","Moody County",44.0124,-96.6761],"46102":["SD","Oglala Lakota County",43.3334,-102.5615],"46103":["SD","Pennington County",44.0023,-102.8238],"46105":["SD","Perkins County",45.4834,-102.468],"46107":["SD","Potter County",45.0527,-99.962],"46109":["SD","Roberts County",45.6234,-96.9476],"46111":["SD","Sanborn County",44.0189,-98.0917],"46115":["SD","Spink County",44.9238,-98.3396],"46117":["SD","Stanley County",44.414,-100.7478],"46119":["SD","Sully County",44.7223,-100.1314],"46121":["SD","Todd County",43.2088,-100.7077],"46123":["SD","Tripp County",43.3497,-99.8762],"46125":["SD","Turner County",43.3087,-97.1502],"46127":["SD","Union County",42.8311,-96.6508],"46129":["SD","Walworth County",45.4276,-100.0279],"46135":["SD","Yankton County",43.0066,-97.3884],"46137":["SD","Ziebach County",44.9898,-101.6608],"47001":["TN","Anderson County",36.1167,-84.1954],"47003":["TN","Bedford County",35.5137,-86.4583],"47005":["TN","Benton County",36.0709,-88.0712],"47007":["TN","Bledsoe County",35.5936,-85.2059],"47009":["TN","Blount County",35.6882,-83.923],"47011":["TN","Bradley County",35.1539,-84.8594],"47013":["TN","Campbell County",36.4016,-84.1592],"47015":["TN","Cannon County",35.8084,-86.0624],"47017":["TN","Carroll County",35.9657,-88.4524],"47019":["TN","Carter County",36.2847,-82.1266],"47021":["TN","Cheatham County",36.2552,-87.1008],"47023":["TN","Chester County",35.4203,-88.6114],"47025":["TN","Claiborne County",36.5016,-83.6607],"47027":["TN","Clay County",36.5457,-85.5457],"47029":["TN","Cocke County",35.9162,-83.1192],"47031":["TN","Coffee County",35.4888,-86.0782],"47033":["TN","Crockett County",35.8188,-89.1325],"47035":["TN","Cumberland County",35.9524,-84.9948],"47037":["TN","Davidson County",36.1691,-86.7848],"47039":["TN","Decatur County",35.6031,-88.1103],"47041":["TN","DeKalb County",35.9822,-85.8336],"47043":["TN","Dickson County",36.1455,-87.3642],"47045":["TN","Dyer County",36.0542,-89.3983],"47047":["TN","Fayette County",35.197,-89.4138],"47049":["TN","Fentress County",36.3699,-84.9378],"47051":["TN","Franklin County",35.1559,-86.0992],"47053":["TN","Gibson County",35.9916,-88.9338],"47055":["TN","Giles County",35.2027,-87.0353],"47057":["TN","Grainger County",36.2775,-83.5095],"47059":["TN","Greene County",36.1795,-82.8475],"47061":["TN","Grundy County",35.3934,-85.7104],"47063":["TN","Hamblen County",36.2184,-83.2661],"47065":["TN","Hamilton County",35.1635,-85.2018],"47067":["TN","Hancock County",36.5214,-83.2275],"47069":["TN","Hardeman County",35.2188,-88.9887],"47071":["TN","Hardin County",35.2019,-88.1857],"47073":["TN","Hawkins County",36.4521,-82.9315],"47075":["TN","Haywood County",35.5867,-89.2827],"47077":["TN","Henderson County",35.654,-88.3877],"47079":["TN","Henry County",36.3253,-88.3003],"47081":["TN","Hickman County",35.8023,-87.4671],"47083":["TN","Houston County",36.2858,-87.7056],"47085":["TN","Humphreys County",36.0408,-87.7905],"47087":["TN","Jackson County",36.3543,-85.6741],"47089":["TN","Jefferson County",36.0485,-83.4412],"47091":["TN","Johnson County",36.4532,-81.8612],"47093":["TN","Knox County",35.9927,-83.9377],"47095":["TN","Lake County",36.3339,-89.4855],"47097":["TN","Lauderdale County",35.763,-89.6277],"47099":["TN","Lawrence County",35.2205,-87.3965],"47101":["TN","Lewis County",35.5232,-87.497],"47103":["TN","Lincoln County",35.1428,-86.5934],"47105":["TN","Loudon County",35.7351,-84.3141],"47107":["TN","McMinn County",35.4245,-84.6199],"47109":["TN","McNairy County",35.1754,-88.5637],"47111":["TN","Macon County",36.5378,-86.001],"47113":["TN","Madison County",35.6061,-88.8334],"47115":["TN","Marion County",35.1276,-85.6074],"47117":["TN","Marshall County",35.4683,-86.7659],"47119":["TN","Maury County",35.6157,-87.0778],"47121":["TN","Meigs County",35.5122,-84.8161],"47123":["TN","Monroe County",35.4478,-84.2497],"47125":["TN","Montgomery County",36.5004,-87.3809],"47127":["TN","Moore County",35.2889,-86.3587],"47129":["TN","Morgan County",36.1387,-84.6393],"47131":["TN","Obion County",36.3619,-89.1481],"47133":["TN","Overton County",36.3449,-85.2831],"47135":["TN","Perry County",35.6638,-87.8693],"47137":["TN","Pickett County",36.5594,-85.0757],"47139":["TN","Polk County",35.1094,-84.5411],"47141":["TN","Putnam County",36.1409,-85.4962],"47143":["TN","Rhea County",35.6006,-84.9495],"47145":["TN","Roane County",35.8473,-84.5239],"47147":["TN","Robertson County",36.5244,-86.8726],"47149":["TN","Rutherford County",35.8434,-86.4172],"47151":["TN","Scott County",36.4306,-84.5041],"47153":["TN","Sequatchie County",35.3723,-85.4101],"47155":["TN","Sevier County",35.7878,-83.5249],"47157":["TN","Shelby County",35.1846,-89.8946],"47159":["TN","Smith County",36.2566,-85.9419],"47161":["TN","Stewart County",36.4585,-87.8119],"47163":["TN","Sullivan County",36.5097,-82.3013],"47165":["TN","Sumner County",36.4724,-86.4584],"47167":["TN","Tipton County",35.4988,-89.7471],"47169":["TN","Trousdale County",36.393,-86.1567],"47171":["TN","Unicoi County",36.1001,-82.4182],"47173":["TN","Union County",36.2841,-83.8361],"47175":["TN","Van Buren County",35.6992,-85.4584],"47177":["TN","Warren County",35.6782,-85.7773],"47179":["TN","Washington County",36.2957,-82.495],"47181":["TN","Wayne County",35.2428,-87.8198],"47183":["TN","Weakley County",36.3036,-88.7212],"47185":["TN","White County",35.927,-85.4558],"47187":["TN","Williamson County",35.8948,-86.8979],"47189":["TN","Wilson County",36.1494,-86.2912],"48001":["TX","Anderson County",31.8413,-95.6617],"48003":["TX","Andrews County",32.3123,-102.6402],"48005":["TX","Angelina County",31.2519,-94.6111],"48007":["TX","Aransas County",28.1226,-96.9675],"48009":["TX","Archer County",33.6163,-98.6873],"48011":["TX","Armstrong County",34.9642,-101.3566],"48013":["TX","Atascosa County",28.8915,-98.5354],"48015":["TX","Austin County",29.8919,-96.2702],"48017":["TX","Bailey County",34.0675,-102.8303],"48019":["TX","Bandera County",29.7564,-99.2483],"48021":["TX","Bastrop County",30.1008,-97.3106],"48023":["TX","Baylor County",33.6188,-99.2082],"48025":["TX","Bee County",28.4161,-97.7426],"48027":["TX","Bell County",31.0427,-97.4813],"48029":["TX","Bexar County",29.4487,-98.5201],"48031":["TX","Blanco County",30.2662,-98.3993],"48033":["TX","Borden County",32.7386,-101.4392],"48035":["TX","Bosque County",31.9008,-97.6376],"48037":["TX","Bowie County",33.4461,-94.4224],"48039":["TX","Brazoria County",29.1678,-95.4346],"48041":["TX","Brazos County",30.6567,-96.3024],"48043":["TX","Brewster County",29.809,-103.2525],"48045":["TX","Briscoe County",34.5252,-101.2059],"48047":["TX","Brooks County",27.035,-98.2153],"48049":["TX","Brown County",31.7641,-98.9985],"48051":["TX","Burleson County",30.4935,-96.6221],"48053":["TX","Burnet County",30.7896,-98.2012],"48055":["TX","Caldwell County",29.8324,-97.6281],"48057":["TX","Calhoun County",28.4417,-96.5796],"48059":["TX","Callahan County",32.2931,-99.3722],"48061":["TX","Cameron County",26.1029,-97.479],"48063":["TX","Camp County",32.9746,-94.9791],"48065":["TX","Carson County",35.4055,-101.3554],"48067":["TX","Cass County",33.0837,-94.3576],"48069":["TX","Castro County",34.5336,-102.2588],"48071":["TX","Chambers County",29.6964,-94.6694],"48073":["TX","Cherokee County",31.8439,-95.1563],"48075":["TX","Childress County",34.5246,-100.2082],"48077":["TX","Clay County",33.7859,-98.2129],"48079":["TX","Cochran County",33.6084,-102.8304],"48081":["TX","Coke County",31.8771,-100.6352],"48083":["TX","Coleman County",31.9142,-99.3466],"48085":["TX","Collin County",33.1945,-96.5794],"48087":["TX","Collingsworth County",34.9634,-100.2721],"48089":["TX","Colorado County",29.5963,-96.5089],"48091":["TX","Comal County",29.8124,-98.2581],"48093":["TX","Comanche County",31.9516,-98.5496],"48095":["TX","Concho County",31.3189,-99.8636],"48097":["TX","Cooke County",33.6392,-97.2103],"48099":["TX","Coryell County",31.3912,-97.798],"48101":["TX","Cottle County",34.0919,-100.2764],"48103":["TX","Crane County",31.4228,-102.4878],"48105":["TX","Crockett County",30.7175,-101.4042],"48107":["TX","Crosby County",33.6091,-101.2987],"48109":["TX","Culberson County",31.4459,-104.5269],"48111":["TX","Dallam County",36.2864,-102.594],"48113":["TX","Dallas County",32.767,-96.7784],"48115":["TX","Dawson County",32.7425,-101.9488],"48117":["TX","Deaf Smith County",34.9408,-102.6076],"48119":["TX","Delta County",33.3859,-95.6733],"48121":["TX","Denton County",33.2051,-97.1211],"48123":["TX","DeWitt County",29.0823,-97.3617],"48125":["TX","Dickens County",33.6154,-100.7876],"48127":["TX","Dimmit County",28.4236,-99.7659],"48129":["TX","Donley County",34.955,-100.8158],"48131":["TX","Duval County",27.6811,-98.4974],"48133":["TX","Eastland County",32.3246,-98.8366],"48135":["TX","Ector County",31.8653,-102.5425],"48137":["TX","Edwards County",29.9859,-100.3074],"48139":["TX","Ellis County",32.3469,-96.7969],"48141":["TX","El Paso County",31.7665,-106.2415],"48143":["TX","Erath County",32.2367,-98.2205],"48145":["TX","Falls County",31.2519,-96.9341],"48147":["TX","Fannin County",33.5912,-96.105],"48149":["TX","Fayette County",29.8779,-96.9212],"48151":["TX","Fisher County",32.7405,-100.4031],"48153":["TX","Floyd County",34.0737,-101.3033],"48155":["TX","Foard County",33.9633,-99.8168],"48157":["TX","Fort Bend County",29.5266,-95.771],"48159":["TX","Franklin County",33.1758,-95.2191],"48161":["TX","Freestone County",31.7017,-96.145],"48163":["TX","Frio County",28.8694,-99.109],"48165":["TX","Gaines County",32.7439,-102.6316],"48167":["TX","Galveston County",29.2339,-94.8882],"48169":["TX","Garza County",33.1838,-101.3011],"48171":["TX","Gillespie County",30.3251,-98.9419],"48173":["TX","Glasscock County",31.868,-101.5215],"48175":["TX","Goliad County",28.6607,-97.4304],"48177":["TX","Gonzales County",29.4619,-97.4919],"48179":["TX","Gray County",35.4025,-100.8124],"48181":["TX","Grayson County",33.6245,-96.6758],"48183":["TX","Gregg County",32.4864,-94.8163],"48185":["TX","Grimes County",30.5432,-95.9881],"48187":["TX","Guadalupe County",29.5827,-97.949],"48189":["TX","Hale County",34.0684,-101.8229],"48191":["TX","Hall County",34.4532,-100.5763],"48193":["TX","Hamilton County",31.7073,-98.1118],"48195":["TX","Hansford County",36.2728,-101.3569],"48197":["TX","Hardeman County",34.2899,-99.7457],"48199":["TX","Hardin County",30.3296,-94.3932],"48201":["TX","Harris County",29.8573,-95.393],"48203":["TX","Harrison County",32.548,-94.3744],"48205":["TX","Hartley County",35.8402,-102.61],"48207":["TX","Haskell County",33.176,-99.7308],"48209":["TX","Hays County",30.0612,-98.0293],"48211":["TX","Hemphill County",35.816,-100.2792],"48213":["TX","Henderson County",32.2116,-95.8534],"48215":["TX","Hidalgo County",26.3964,-98.181],"48217":["TX","Hill County",31.9826,-97.1306],"48219":["TX","Hockley County",33.6059,-102.3434],"48221":["TX","Hood County",32.4301,-97.8317],"48223":["TX","Hopkins County",33.149,-95.5654],"48225":["TX","Houston County",31.323,-95.4216],"48227":["TX","Howard County",32.3034,-101.4387],"48229":["TX","Hudspeth County",31.4509,-105.3775],"48231":["TX","Hunt County",33.1233,-96.0842],"48233":["TX","Hutchinson County",35.837,-101.3627],"48235":["TX","Irion County",31.3034,-100.9813],"48237":["TX","Jack County",33.2322,-98.1712],"48239":["TX","Jackson County",28.9598,-96.5891],"48241":["TX","Jasper County",30.7529,-94.0223],"48243":["TX","Jeff Davis County",30.6254,-104.1919],"48245":["TX","Jefferson County",29.854,-94.1493],"48247":["TX","Jim Hogg County",27.0532,-98.7476],"48249":["TX","Jim Wells County",27.7335,-98.0908],"48251":["TX","Johnson County",32.3797,-97.3649],"48253":["TX","Jones County",32.7437,-99.8744],"48255":["TX","Karnes County",28.909,-97.8522],"48257":["TX","Kaufman County",32.5989,-96.2884],"48259":["TX","Kendall County",29.9435,-98.7093],"48261":["TX","Kenedy County",26.8902,-97.5911],"48263":["TX","Kent County",33.1848,-100.7697],"48265":["TX","Kerr County",30.06,-99.3533],"48267":["TX","Kimble County",30.4795,-99.7464],"48269":["TX","King County",33.6143,-100.2453],"48271":["TX","Kinney County",29.3471,-100.4177],"48273":["TX","Kleberg County",27.4387,-97.6606],"48275":["TX","Knox County",33.6119,-99.7304],"48277":["TX","Lamar County",33.6673,-95.5703],"48279":["TX","Lamb County",34.0689,-102.348],"48281":["TX","Lampasas County",31.1967,-98.2409],"48283":["TX","La Salle County",28.3511,-99.0968],"48285":["TX","Lavaca County",29.3826,-96.9236],"48287":["TX","Lee County",30.3215,-96.9768],"48289":["TX","Leon County",31.3005,-95.9956],"48291":["TX","Liberty County",30.1585,-94.8441],"48293":["TX","Limestone County",31.5475,-96.5936],"48295":["TX","Lipscomb County",36.2802,-100.2727],"48297":["TX","Live Oak County",28.3515,-98.127],"48299":["TX","Llano County",30.7076,-98.6847],"48301":["TX","Loving County",31.8449,-103.5612],"48303":["TX","Lubbock County",33.6115,-101.8199],"48305":["TX","Lynn County",33.1784,-101.8185],"48307":["TX","McCulloch County",31.2055,-99.3599],"48309":["TX","McLennan County",31.5496,-97.2015],"48311":["TX","McMullen County",28.3849,-98.5789],"48313":["TX","Madison County",30.9669,-95.9304],"48315":["TX","Marion County",32.7982,-94.3569],"48317":["TX","Martin County",32.3098,-101.9618],"48319":["TX","Mason County",30.7039,-99.2373],"48321":["TX","Matagorda County",28.7748,-96.0015],"48323":["TX","Maverick County",28.7298,-100.3167],"48325":["TX","Medina County",29.3537,-99.1111],"48327":["TX","Menard County",30.8853,-99.8589],"48329":["TX","Midland County",31.8143,-102.0025],"48331":["TX","Milam County",30.7912,-96.9844],"48333":["TX","Mills County",31.4949,-98.5946],"48335":["TX","Mitchell County",32.3041,-100.9244],"48337":["TX","Montague County",33.6784,-97.725],"48339":["TX","Montgomery County",30.2988,-95.5029],"48341":["TX","Moore County",35.8357,-101.8905],"48343":["TX","Morris County",33.1165,-94.7313],"48345":["TX","Motley County",34.0579,-100.7932],"48347":["TX","Nacogdoches County",31.6206,-94.6202],"48349":["TX","Navarro County",32.0484,-96.4769],"48351":["TX","Newton County",30.7867,-93.7392],"48353":["TX","Nolan County",32.3123,-100.4181],"48355":["TX","Nueces County",27.74,-97.5162],"48357":["TX","Ochiltree County",36.2787,-100.8159],"48359":["TX","Oldham County",35.4019,-102.5976],"48361":["TX","Orange County",30.1223,-93.8941],"48363":["TX","Palo Pinto County",32.7522,-98.318],"48365":["TX","Panola County",32.164,-94.3052],"48367":["TX","Parker County",32.7771,-97.8059],"48369":["TX","Parmer County",34.5322,-102.7849],"48371":["TX","Pecos County",30.7733,-102.7182],"48373":["TX","Polk County",30.7846,-94.8373],"48375":["TX","Potter County",35.3987,-101.8938],"48377":["TX","Presidio County",30.0059,-104.2616],"48379":["TX","Rains County",32.8705,-95.7956],"48381":["TX","Randall County",34.9625,-101.8955],"48383":["TX","Reagan County",31.3752,-101.5144],"48385":["TX","Real County",29.8301,-99.8125],"48387":["TX","Red River County",33.6196,-95.0484],"48389":["TX","Reeves County",31.3084,-103.7127],"48391":["TX","Refugio County",28.3221,-97.1625],"48393":["TX","Roberts County",35.8386,-100.8367],"48395":["TX","Robertson County",31.0255,-96.5149],"48397":["TX","Rockwall County",32.8999,-96.412],"48399":["TX","Runnels County",31.8451,-99.9827],"48401":["TX","Rusk County",32.1094,-94.7564],"48403":["TX","Sabine County",31.3433,-93.8519],"48405":["TX","San Augustine County",31.3824,-94.1632],"48407":["TX","San Jacinto County",30.5744,-95.1631],"48409":["TX","San Patricio County",28.0118,-97.5172],"48411":["TX","San Saba County",31.1551,-98.8193],"48413":["TX","Schleicher County",30.8962,-100.5272],"48415":["TX","Scurry County",32.7444,-100.9133],"48417":["TX","Shackelford County",32.7438,-99.347],"48419":["TX","Shelby County",31.7901,-94.1426],"48421":["TX","Sherman County",36.2786,-101.8993],"48423":["TX","Smith County",32.3751,-95.2689],"48425":["TX","Somervell County",32.2181,-97.7692],"48427":["TX","Starr County",26.5309,-98.7402],"48429":["TX","Stephens County",32.7381,-98.8393],"48431":["TX","Sterling County",31.8358,-101.0549],"48433":["TX","Stonewall County",33.1796,-100.2538],"48435":["TX","Sutton County",30.5222,-100.5134],"48437":["TX","Swisher County",34.5263,-101.7439],"48439":["TX","Tarrant County",32.7721,-97.2912],"48441":["TX","Taylor County",32.2971,-99.8904],"48443":["TX","Terrell County",30.2323,-102.0725],"48445":["TX","Terry County",33.1712,-102.3393],"48447":["TX","Throckmorton County",33.1707,-99.2058],"48449":["TX","Titus County",33.2146,-94.9668],"48451":["TX","Tom Green County",31.3983,-100.4638],"48453":["TX","Travis County",30.2395,-97.6913],"48455":["TX","Trinity County",31.0967,-95.1517],"48457":["TX","Tyler County",30.7693,-94.3757],"48459":["TX","Upshur County",32.7353,-94.9412],"48461":["TX","Upton County",31.3538,-102.0415],"48463":["TX","Uvalde County",29.3503,-99.7684],"48465":["TX","Val Verde County",29.8753,-101.1433],"48467":["TX","Van Zandt County",32.5588,-95.8369],"48469":["TX","Victoria County",28.7964,-96.9712],"48471":["TX","Walker County",30.7432,-95.5698],"48473":["TX","Waller County",30.0136,-95.9821],"48475":["TX","Ward County",31.5131,-103.1051],"48477":["TX","Washington County",30.2151,-96.4103],"48479":["TX","Webb County",27.7608,-99.3408],"48481":["TX","Wharton County",29.2785,-96.2297],"48483":["TX","Wheeler County",35.3926,-100.2531],"48485":["TX","Wichita County",33.9882,-98.708],"48487":["TX","Wilbarger County",34.0849,-99.2424],"48489":["TX","Willacy County",26.4819,-97.5947],"48491":["TX","Williamson County",30.6491,-97.6051],"48493":["TX","Wilson County",29.1739,-98.0867],"48495":["TX","Winkler County",31.8329,-103.0549],"48497":["TX","Wise County",33.2193,-97.653],"48499":["TX","Wood County",32.7836,-95.3822],"48501":["TX","Yoakum County",33.1623,-102.8322],"48503":["TX","Young County",33.1588,-98.6784],"48505":["TX","Zapata County",26.997,-99.1826],"48507":["TX","Zavala County",28.8647,-99.7598],"49001":["UT","Beaver County",38.3575,-113.2389],"49003":["UT","Box Elder County",41.6226,-113.0603],"49005":["UT","Cache County",41.7341,-111.7454],"49007":["UT","Carbon County",39.6733,-110.5885],"49009":["UT","Daggett County",40.8901,-109.5058],"49011":["UT","Davis County",41.0376,-112.2019],"49013":["UT","Duchesne County",40.2894,-110.4296],"49015":["UT","Emery County",39.009,-110.7211],"49017":["UT","Garfield County",37.8317,-111.4509],"49019":["UT","Grand County",38.9743,-109.5734],"49021":["UT","Iron County",37.9093,-113.3067],"49023":["UT","Juab County",39.7141,-112.7905],"49025":["UT","Kane County",37.2751,-111.8153],"49027":["UT","Millard County",38.9567,-113.1331],"49029":["UT","Morgan County",41.091,-111.5779],"49031":["UT","Piute County",38.3359,-112.1294],"49033":["UT","Rich County",41.6276,-111.2402],"49035":["UT","Salt Lake County",40.6679,-111.9242],"49037":["UT","San Juan County",37.6026,-109.7916],"49039":["UT","Sanpete County",39.3734,-111.5769],"49041":["UT","Sevier County",38.7468,-111.8119],"49043":["UT","Summit County",40.8721,-110.9685],"49045":["UT","Tooele County",40.4678,-113.124],"49047":["UT","Uintah County",40.1259,-109.5177],"49049":["UT","Utah County",40.1204,-111.6686],"49051":["UT","Wasatch County",40.3349,-111.1616],"49053":["UT","Washington County",37.2625,-113.4878],"49055":["UT","Wayne County",38.2599,-110.9909],"49057":["UT","Weber County",41.2703,-111.8769],"50001":["VT","Addison County",44.0312,-73.1416],"50003":["VT","Bennington County",43.0353,-73.1115],"50005":["VT","Caledonia County",44.4688,-72.1122],"50007":["VT","Chittenden County",44.4633,-73.0694],"50009":["VT","Essex County",44.724,-71.7327],"50011":["VT","Franklin County",44.859,-72.9094],"50013":["VT","Grand Isle County",44.8018,-73.3008],"50015":["VT","Lamoille County",44.6112,-72.6327],"50017":["VT","Orange County",44.0034,-72.3696],"50019":["VT","Orleans County",44.8284,-72.2516],"50021":["VT","Rutland County",43.6124,-73.0603],"50023":["VT","Washington County",44.275,-72.6094],"50025":["VT","Windham County",42.9953,-72.7219],"50027":["VT","Windsor County",43.5724,-72.5988],"51001":["VA","Accomack County",37.7659,-75.7578],"51003":["VA","Albemarle County",38.0242,-78.5535],"51005":["VA","Alleghany County",37.7879,-80.0087],"51007":["VA","Amelia County",37.3319,-77.9775],"51009":["VA","Amherst County",37.6293,-79.1548],"51011":["VA","Appomattox County",37.3707,-78.8109],"51013":["VA","Arlington County",38.8783,-77.1007],"51015":["VA","Augusta County",38.1726,-79.141],"51017":["VA","Bath County",38.0684,-79.7312],"51019":["VA","Bedford County",37.3123,-79.5272],"51021":["VA","Bland County",37.1306,-81.1259],"51023":["VA","Botetourt County",37.5655,-79.7975],"51025":["VA","Brunswick County",36.7642,-77.8615],"51027":["VA","Buchanan County",37.2681,-82.0382],"51029":["VA","Buckingham County",37.5739,-78.5292],"51031":["VA","Campbell County",37.2102,-79.0954],"51033":["VA","Caroline County",38.028,-77.3537],"51035":["VA","Carroll County",36.732,-80.7278],"51036":["VA","Charles City County",37.3611,-77.0542],"51037":["VA","Charlotte County",37.009,-78.6586],"51041":["VA","Chesterfield County",37.3784,-77.5858],"51043":["VA","Clarke County",39.1153,-77.9907],"51045":["VA","Craig County",37.4736,-80.2311],"51047":["VA","Culpeper County",38.4859,-77.9565],"51049":["VA","Cumberland County",37.5202,-78.2528],"51051":["VA","Dickenson County",37.1367,-82.3492],"51053":["VA","Dinwiddie County",37.0735,-77.6355],"51057":["VA","Essex County",37.9364,-76.9337],"51059":["VA","Fairfax County",38.8295,-77.2733],"51061":["VA","Fauquier County",38.7441,-77.8215],"51063":["VA","Floyd County",36.9314,-80.3503],"51065":["VA","Fluvanna County",37.8306,-78.2835],"51067":["VA","Franklin County",36.9912,-79.8827],"51069":["VA","Frederick County",39.2037,-78.2638],"51071":["VA","Giles County",37.3181,-80.6983],"51073":["VA","Gloucester County",37.4035,-76.5235],"51075":["VA","Goochland County",37.7188,-77.9176],"51077":["VA","Grayson County",36.6522,-81.2153],"51079":["VA","Greene County",38.298,-78.4702],"51081":["VA","Greensville County",36.6803,-77.5603],"51083":["VA","Halifax County",36.7665,-78.9396],"51085":["VA","Hanover County",37.7602,-77.4913],"51087":["VA","Henrico County",37.4375,-77.3003],"51089":["VA","Henry County",36.6206,-79.9807],"51091":["VA","Highland County",38.3662,-79.5645],"51093":["VA","Isle of Wight County",36.9014,-76.7076],"51095":["VA","James City County",37.3248,-76.7779],"51097":["VA","King and Queen County",37.7178,-76.9056],"51099":["VA","King George County",38.2772,-77.1626],"51101":["VA","King William County",37.7083,-77.0911],"51103":["VA","Lancaster County",37.7048,-76.4127],"51105":["VA","Lee County",36.7017,-83.1301],"51107":["VA","Loudoun County",39.0812,-77.6389],"51109":["VA","Louisa County",37.9727,-77.9598],"51111":["VA","Lunenburg County",36.9456,-78.2405],"51113":["VA","Madison County",38.4121,-78.277],"51115":["VA","Mathews County",37.4253,-76.2688],"51117":["VA","Mecklenburg County",36.6873,-78.369],"51119":["VA","Middlesex County",37.607,-76.5281],"51121":["VA","Montgomery County",37.1755,-80.3878],"51125":["VA","Nelson County",37.7891,-78.8834],"51127":["VA","New Kent County",37.5102,-76.9993],"51131":["VA","Northampton County",37.3028,-75.924],"51133":["VA","Northumberland County",37.857,-76.3797],"51135":["VA","Nottoway County",37.1412,-78.0539],"51137":["VA","Orange County",38.2493,-78.0111],"51139":["VA","Page County",38.6232,-78.4919],"51141":["VA","Patrick County",36.6671,-80.2864],"51143":["VA","Pittsylvania County",36.8217,-79.3985],"51145":["VA","Powhatan County",37.5494,-77.9129],"51147":["VA","Prince Edward County",37.2249,-78.433],"51149":["VA","Prince George County",37.1873,-77.221],"51153":["VA","Prince William County",38.7011,-77.4796],"51155":["VA","Pulaski County",37.0634,-80.7134],"51157":["VA","Rappahannock County",38.6845,-78.1688],"51159":["VA","Richmond County",37.9429,-76.7306],"51161":["VA","Roanoke County",37.3308,-80.1912],"51163":["VA","Rockbridge County",37.8145,-79.4478],"51165":["VA","Rockingham County",38.5076,-78.8853],"51167":["VA","Russell County",36.9334,-82.0959],"51169":["VA","Scott County",36.7128,-82.6136],"51171":["VA","Shenandoah County",38.8562,-78.574],"51173":["VA","Smyth County",36.8423,-81.5398],"51175":["VA","Southampton County",36.7201,-77.1038],"51177":["VA","Spotsylvania County",38.1824,-77.6572],"51179":["VA","Stafford County",38.4231,-77.458],"51181":["VA","Surry County",37.1198,-76.8802],"51183":["VA","Sussex County",36.9266,-77.2597],"51185":["VA","Tazewell County",37.1254,-81.5629],"51187":["VA","Warren County",38.9082,-78.2076],"51191":["VA","Washington County",36.7478,-81.9503],"51193":["VA","Westmoreland County",38.1093,-76.8039],"51195":["VA","Wise County",36.9746,-82.6216],"51197":["VA","Wythe County",36.8999,-81.083],"51199":["VA","York County",37.2209,-76.3955],"51510":["VA","Alexandria city",38.8193,-77.0837],"51520":["VA","Bristol city",36.617,-82.1576],"51530":["VA","Buena Vista city",37.7293,-79.3581],"51540":["VA","Charlottesville city",38.0377,-78.4854],"51550":["VA","Chesapeake city",36.6794,-76.3018],"51570":["VA","Colonial Heights city",37.2617,-77.3968],"51580":["VA","Covington city",37.7811,-79.9854],"51590":["VA","Danville city",36.5833,-79.4081],"51595":["VA","Emporia city",36.6962,-77.536],"51600":["VA","Fairfax city",38.8532,-77.299],"51610":["VA","Falls Church city",38.8847,-77.1756],"51620":["VA","Franklin city",36.684,-76.9414],"51630":["VA","Fredericksburg city",38.2993,-77.4867],"51640":["VA","Galax city",36.6656,-80.9143],"51650":["VA","Hampton city",37.048,-76.2973],"51660":["VA","Harrisonburg city",38.4363,-78.8733],"51670":["VA","Hopewell city",37.291,-77.2989],"51678":["VA","Lexington city",37.7823,-79.4443],"51680":["VA","Lynchburg city",37.399,-79.1955],"51683":["VA","Manassas city",38.7468,-77.4826],"51685":["VA","Manassas Park city",38.7694,-77.4423],"51690":["VA","Martinsville city",36.6835,-79.8636],"51700":["VA","Newport News city",37.0761,-76.522],"51710":["VA","Norfolk city",36.923,-76.2446],"51720":["VA","Norton city",36.9315,-82.626],"51730":["VA","Petersburg city",37.2047,-77.3924],"51735":["VA","Poquoson city",37.1284,-76.3035],"51740":["VA","Portsmouth city",36.8593,-76.357],"51750":["VA","Radford city",37.1201,-80.5591],"51760":["VA","Richmond city",37.5314,-77.476],"51770":["VA","Roanoke city",37.2785,-79.9582],"51775":["VA","Salem city",37.2853,-80.0552],"51790":["VA","Staunton city",38.158,-79.0619],"51800":["VA","Suffolk city",36.6972,-76.6348],"51810":["VA","Virginia Beach city",36.7795,-76.0291],"51820":["VA","Waynesboro city",38.0672,-78.9014],"51830":["VA","Williamsburg city",37.2695,-76.7082],"51840":["VA","Winchester city",39.1739,-78.1764],"53001":["WA","Adams County",47.0112,-118.5129],"53003":["WA","Asotin County",46.1819,-117.2278],"53005":["WA","Benton County",46.2281,-119.5167],"53007":["WA","Chelan County",47.861,-120.619],"53009":["WA","Clallam County",48.1109,-123.8899],"53011":["WA","Clark County",45.7717,-122.486],"53013":["WA","Columbia County",46.2929,-117.9116],"53015":["WA","Cowlitz County",46.1968,-122.6785],"53017":["WA","Douglas County",47.7418,-119.6946],"53019":["WA","Ferry County",48.4733,-118.5336],"53021":["WA","Franklin County",46.5375,-118.9039],"53023":["WA","Garfield County",46.4293,-117.5367],"53025":["WA","Grant County",47.2136,-119.4678],"53027":["WA","Grays Harbor County",47.1137,-123.8267],"53029":["WA","Island County",48.1586,-122.6706],"53031":["WA","Jefferson County",47.8057,-123.5271],"53033":["WA","King County",47.4906,-121.834],"53035":["WA","Kitsap County",47.6397,-122.6496],"53037":["WA","Kittitas County",47.1244,-120.6767],"53039":["WA","Klickitat County",45.8704,-120.7793],"53041":["WA","Lewis County",46.5801,-122.3774],"53043":["WA","Lincoln County",47.5827,-118.4177],"53045":["WA","Mason County",47.3508,-123.1731],"53047":["WA","Okanogan County",48.5485,-119.7422],"53049":["WA","Pacific County",46.5566,-123.7824],"53051":["WA","Pend Oreille County",48.5438,-117.2322],"53053":["WA","Pierce County",47.0514,-122.1532],"53055":["WA","San Juan County",48.5072,-123.1038],"53057":["WA","Skagit County",48.4933,-121.8158],"53059":["WA","Skamania County",46.0248,-121.9532],"53061":["WA","Snohomish County",48.0549,-121.765],"53063":["WA","Spokane County",47.6204,-117.4034],"53065":["WA","Stevens County",48.3887,-117.8545],"53067":["WA","Thurston County",46.9358,-122.8302],"53069":["WA","Wahkiakum County",46.2946,-123.4245],"53071":["WA","Walla Walla County",46.2546,-118.4804],"53073":["WA","Whatcom County",48.8427,-121.8364],"53075":["WA","Whitman County",46.9059,-117.5354],"53077":["WA","Yakima County",46.4566,-120.7401],"54001":["WV","Barbour County",39.1397,-79.9969],"54003":["WV","Berkeley County",39.4479,-78.0378],"54005":["WV","Boone County",38.0228,-81.7135],"54007":["WV","Braxton County",38.6993,-80.7317],"54009":["WV","Brooke County",40.2726,-80.5787],"54011":["WV","Cabell County",38.4196,-82.2434],"54013":["WV","Calhoun County",38.8442,-81.1155],"54015":["WV","Clay County",38.4598,-81.0819],"54017":["WV","Doddridge County",39.2643,-80.7115],"54019":["WV","Fayette County",38.031,-81.0861],"54021":["WV","Gilmer County",38.9159,-80.8494],"54023":["WV","Grant County",39.106,-79.1951],"54025":["WV","Greenbrier County",37.9244,-80.4506],"54027":["WV","Hampshire County",39.3121,-78.612],"54029":["WV","Hancock County",40.517,-80.5702],"54031":["WV","Hardy County",39.0114,-78.8417],"54033":["WV","Harrison County",39.2792,-80.3865],"54035":["WV","Jackson County",38.8342,-81.6777],"54037":["WV","Jefferson County",39.3074,-77.8632],"54039":["WV","Kanawha County",38.3281,-81.5235],"54041":["WV","Lewis County",38.9889,-80.4955],"54043":["WV","Lincoln County",38.1718,-82.0776],"54045":["WV","Logan County",37.8306,-81.9409],"54047":["WV","McDowell County",37.3828,-81.6582],"54049":["WV","Marion County",39.5058,-80.2434],"54051":["WV","Marshall County",39.8544,-80.6718],"54053":["WV","Mason County",38.7709,-82.029],"54055":["WV","Mercer County",37.4034,-81.1065],"54057":["WV","Mineral County",39.4048,-78.9567],"54059":["WV","Mingo County",37.7212,-82.159],"54061":["WV","Monongalia County",39.6336,-80.0591],"54063":["WV","Monroe County",37.5541,-80.5503],"54065":["WV","Morgan County",39.5573,-78.2565],"54067":["WV","Nicholas County",38.2914,-80.7975],"54069":["WV","Ohio County",40.1003,-80.6199],"54071":["WV","Pendleton County",38.6745,-79.3406],"54073":["WV","Pleasants County",39.3681,-81.1612],"54075":["WV","Pocahontas County",38.3326,-80.0101],"54077":["WV","Preston County",39.469,-79.6689],"54079":["WV","Putnam County",38.5105,-81.9061],"54081":["WV","Raleigh County",37.7625,-81.2647],"54083":["WV","Randolph County",38.7811,-79.8678],"54085":["WV","Ritchie County",39.1771,-81.0663],"54087":["WV","Roane County",38.743,-81.3545],"54089":["WV","Summers County",37.656,-80.8563],"54091":["WV","Taylor County",39.3325,-80.0466],"54093":["WV","Tucker County",39.1112,-79.56],"54095":["WV","Tyler County",39.4656,-80.8772],"54097":["WV","Upshur County",38.9025,-80.2316],"54099":["WV","Wayne County",38.1436,-82.4227],"54101":["WV","Webster County",38.4835,-80.4491],"54103":["WV","Wetzel County",39.5982,-80.6354],"54105":["WV","Wirt County",39.02,-81.383],"54107":["WV","Wood County",39.2116,-81.5162],"54109":["WV","Wyoming County",37.6037,-81.549],"55001":["WI","Adams County",43.9738,-89.7672],"55003":["WI","Ashland County",46.5444,-90.6797],"55005":["WI","Barron County",45.4372,-91.8529],"55007":["WI","Bayfield County",46.6342,-91.1773],"55009":["WI","Brown County",44.474,-87.9961],"55011":["WI","Buffalo County",44.3856,-91.7613],"55013":["WI","Burnett County",45.8669,-92.3757],"55015":["WI","Calumet County",44.0784,-88.2121],"55017":["WI","Chippewa County",45.0691,-91.2835],"55019":["WI","Clark County",44.7392,-90.6099],"55021":["WI","Columbia County",43.4719,-89.3305],"55023":["WI","Crawford County",43.2428,-90.9352],"55025":["WI","Dane County",43.0675,-89.4179],"55027":["WI","Dodge County",43.4296,-88.7019],"55029":["WI","Door County",45.0934,-87.0487],"55031":["WI","Douglas County",46.4632,-91.8925],"55033":["WI","Dunn County",44.9478,-91.8976],"55035":["WI","Eau Claire County",44.7264,-91.2864],"55037":["WI","Florence County",45.8718,-88.407],"55039":["WI","Fond du Lac County",43.7547,-88.4933],"55041":["WI","Forest County",45.6669,-88.7733],"55043":["WI","Grant County",42.87,-90.6942],"55045":["WI","Green County",42.6755,-89.6051],"55047":["WI","Green Lake County",43.7802,-88.9704],"55049":["WI","Iowa County",43.001,-90.1337],"55051":["WI","Iron County",46.3265,-90.2613],"55053":["WI","Jackson County",44.3246,-90.7995],"55055":["WI","Jefferson County",43.0138,-88.774],"55057":["WI","Juneau County",43.9328,-90.114],"55059":["WI","Kenosha County",42.5875,-87.88],"55061":["WI","Kewaunee County",44.6057,-87.448],"55063":["WI","La Crosse County",43.9082,-91.1118],"55065":["WI","Lafayette County",42.6556,-90.1303],"55067":["WI","Langlade County",45.2549,-89.0671],"55069":["WI","Lincoln County",45.3331,-89.7322],"55071":["WI","Manitowoc County",44.1561,-87.5774],"55073":["WI","Marathon County",44.898,-89.7578],"55075":["WI","Marinette County",45.3469,-87.9912],"55077":["WI","Marquette County",43.8261,-89.4091],"55078":["WI","Menominee County",44.9913,-88.6693],"55079":["WI","Milwaukee County",42.9126,-87.8623],"55081":["WI","Monroe County",43.9452,-90.62],"55083":["WI","Oconto County",44.9966,-88.2065],"55085":["WI","Oneida County",45.7162,-89.5345],"55087":["WI","Outagamie County",44.4182,-88.465],"55089":["WI","Ozaukee County",43.5018,-87.8476],"55091":["WI","Pepin County",44.6274,-91.8349],"55093":["WI","Pierce County",44.7253,-92.4263],"55095":["WI","Polk County",45.462,-92.4471],"55097":["WI","Portage County",44.4762,-89.4981],"55099":["WI","Price County",45.6791,-90.3597],"55101":["WI","Racine County",42.7804,-87.7716],"55103":["WI","Richland County",43.3762,-90.4357],"55105":["WI","Rock County",42.6699,-89.0753],"55107":["WI","Rusk County",45.4727,-91.1367],"55109":["WI","St. Croix County",45.029,-92.4473],"55111":["WI","Sauk County",43.428,-89.9433],"55113":["WI","Sawyer County",45.865,-91.1471],"55115":["WI","Shawano County",44.7896,-88.7558],"55117":["WI","Sheboygan County",43.7387,-87.7315],"55119":["WI","Taylor County",45.2117,-90.5049],"55121":["WI","Trempealeau County",44.303,-91.3589],"55123":["WI","Vernon County",43.5994,-90.822],"55125":["WI","Vilas County",46.0498,-89.5013],"55127":["WI","Walworth County",42.6681,-88.5417],"55129":["WI","Washburn County",45.8925,-91.7964],"55131":["WI","Washington County",43.3912,-88.2329],"55133":["WI","Waukesha County",43.0184,-88.3042],"55135":["WI","Waupaca County",44.478,-88.967],"55137":["WI","Waushara County",44.1128,-89.2398],"55139":["WI","Winnebago County",44.0857,-88.6681],"55141":["WI","Wood County",44.4614,-90.0388],"56001":["WY","Albany County",41.6655,-105.7219],"56003":["WY","Big Horn County",44.5251,-107.9948],"56005":["WY","Campbell County",44.192,-105.517],"56007":["WY","Carbon County",41.7036,-106.9332],"56009":["WY","Converse County",42.9846,-105.5248],"56011":["WY","Crook County",44.5893,-104.5673],"56013":["WY","Fremont County",43.0548,-108.6089],"56015":["WY","Goshen County",42.0895,-104.3535],"56017":["WY","Hot Springs County",43.7202,-108.4351],"56019":["WY","Johnson County",44.044,-106.5885],"56021":["WY","Laramie County",41.2928,-104.6604],"56023":["WY","Lincoln County",42.23,-110.683],"56025":["WY","Natrona County",42.9776,-106.7682],"56027":["WY","Niobrara County",43.0622,-104.4684],"56029":["WY","Park County",44.4924,-109.5936],"56031":["WY","Platte County",42.1316,-104.954],"56033":["WY","Sheridan County",44.7814,-106.8812],"56035":["WY","Sublette County",42.7679,-109.9162],"56037":["WY","Sweetwater County",41.6603,-108.8757],"56039":["WY","Teton County",44.0487,-110.4261],"56041":["WY","Uinta County",41.2847,-110.5589],"56043":["WY","Washakie County",43.8788,-107.6691],"56045":["WY","Weston County",43.8462,-104.57],"72001":["PR","Adjuntas Municipio",18.1816,-66.7582],"72003":["PR","Aguada Municipio",18.3757,-67.1857],"72005":["PR","Aguadilla Municipio",18.4802,-67.1438],"72007":["PR","Aguas Buenas Municipio",18.2565,-66.1285],"72009":["PR","Aibonito Municipio",18.1307,-66.2645],"72011":["PR","A\xC3\xB1asco Municipio",18.2869,-67.1313],"72013":["PR","Arecibo Municipio",18.434,-66.675],"72015":["PR","Arroyo Municipio",17.9721,-66.0419],"72017":["PR","Barceloneta Municipio",18.47,-66.5582],"72019":["PR","Barranquitas Municipio",18.2,-66.3093],"72021":["PR","Bayam\xC3\xB3n Municipio",18.3494,-66.1686],"72023":["PR","Cabo Rojo Municipio",17.9971,-67.1809],"72025":["PR","Caguas Municipio",18.2111,-66.051],"72027":["PR","Camuy Municipio",18.4455,-66.8631],"72029":["PR","Can\xC3\xB3vanas Municipio",18.33,-65.886],"72031":["PR","Carolina Municipio",18.3968,-65.9688],"72033":["PR","Cata\xC3\xB1o Municipio",18.4446,-66.1488],"72035":["PR","Cayey Municipio",18.1036,-66.1517],"72037":["PR","Ceiba Municipio",18.2533,-65.6208],"72039":["PR","Ciales Municipio",18.2959,-66.5156],"72041":["PR","Cidra Municipio",18.1744,-66.1616],"72043":["PR","Coamo Municipio",18.1038,-66.3576],"72045":["PR","Comer\xC3\xADo Municipio",18.225,-66.2195],"72047":["PR","Corozal Municipio",18.3039,-66.3262],"72049":["PR","Culebra Municipio",18.3266,-65.3078],"72051":["PR","Dorado Municipio",18.4744,-66.262],"72053":["PR","Fajardo Municipio",18.3864,-65.5885],"72054":["PR","Florida Municipio",18.3687,-66.5627],"72055":["PR","Gu\xC3\xA1nica Municipio",17.9482,-66.9229],"72057":["PR","Guayama Municipio",17.9739,-66.1375],"72059":["PR","Guayanilla Municipio",18.0053,-66.7983],"72061":["PR","Guaynabo Municipio",18.3444,-66.1141],"72063":["PR","Gurabo Municipio",18.2726,-65.9812],"72065":["PR","Hatillo Municipio",18.4411,-66.7982],"72067":["PR","Hormigueros Municipio",18.1347,-67.1162],"72069":["PR","Humacao Municipio",18.1354,-65.7862],"72071":["PR","Isabela Municipio",18.484,-67.014],"72073":["PR","Jayuya Municipio",18.2112,-66.5869],"72075":["PR","Juana D\xC3\xADaz Municipio",17.998,-66.4905],"72077":["PR","Juncos Municipio",18.2241,-65.9085],"72079":["PR","Lajas Municipio",17.9785,-67.0401],"72081":["PR","Lares Municipio",18.2769,-66.8696],"72083":["PR","Las Mar\xC3\xADas Municipio",18.2276,-66.9776],"72085":["PR","Las Piedras Municipio",18.1871,-65.8712],"72087":["PR","Lo\xC3\xADza Municipio",18.4455,-65.9426],"72089":["PR","Luquillo Municipio",18.368,-65.7099],"72091":["PR","Manat\xC3\xAD Municipio",18.4448,-66.4931],"72093":["PR","Maricao Municipio",18.174,-66.9355],"72095":["PR","Maunabo Municipio",17.9998,-65.8964],"72097":["PR","Mayag\xC3\xBCez Municipio",18.0839,-67.8863],"72099":["PR","Moca Municipio",18.3776,-67.0796],"72101":["PR","Morovis Municipio",18.318,-66.4204],"72103":["PR","Naguabo Municipio",18.2111,-65.7357],"72105":["PR","Naranjito Municipio",18.2899,-66.2534],"72107":["PR","Orocovis Municipio",18.2187,-66.4369],"72109":["PR","Patillas Municipio",18.0003,-65.9866],"72111":["PR","Pe\xC3\xB1uelas Municipio",18.0266,-66.7281],"72113":["PR","Ponce Municipio",18.0017,-66.6067],"72115":["PR","Quebradillas Municipio",18.4664,-66.9276],"72117":["PR","Rinc\xC3\xB3n Municipio",18.339,-67.2508],"72119":["PR","R\xC3\xADo Grande Municipio",18.3764,-65.7984],"72121":["PR","Sabana Grande Municipio",18.0845,-66.9476],"72123":["PR","Salinas Municipio",17.9715,-66.2623],"72125":["PR","San Germ\xC3\xA1n Municipio",18.1078,-67.0373],"72127":["PR","San Juan Municipio",18.4222,-66.0691],"72129":["PR","San Lorenzo Municipio",18.1471,-65.9762],"72131":["PR","San Sebasti\xC3\xA1n Municipio",18.3311,-66.9691],"72133":["PR","Santa Isabel Municipio",17.9529,-66.3876],"72135":["PR","Toa Alta Municipio",18.3646,-66.2447],"72137":["PR","Toa Baja Municipio",18.4569,-66.1932],"72139":["PR","Trujillo Alto Municipio",18.3354,-66.0038],"72141":["PR","Utuado Municipio",18.2709,-66.703],"72143":["PR","Vega Alta Municipio",18.4362,-66.3364],"72145":["PR","Vega Baja Municipio",18.4551,-66.3979],"72147":["PR","Vieques Municipio",18.1254,-65.4325],"72149":["PR","Villalba Municipio",18.1307,-66.4722],"72151":["PR","Yabucoa Municipio",18.0599,-65.8599],"72153":["PR","Yauco Municipio",18.0857,-66.8579]},states:{AL:[32.76,-86.83],AK:[63.726,-149.837],AZ:[34.269,-111.667],AR:[34.891,-92.442],CA:[37.148,-119.547],CO:[38.974,-105.55],CT:[41.607,-72.723],DE:[38.998,-75.454],DC:[38.904,-77.017],FL:[28.631,-82.512],GA:[32.632,-83.446],HI:[20.236,-156.362],ID:[44.338,-114.637],IL:[40.041,-89.189],IN:[39.894,-86.278],IA:[42.066,-93.503],KS:[38.474,-98.391],KY:[37.525,-85.273],LA:[31.101,-92.048],ME:[45.377,-69.208],MD:[39.037,-76.805],MA:[42.247,-71.805],MI:[44.31,-85.414],MN:[46.222,-94.323],MS:[32.726,-89.661],MO:[38.348,-92.467],MT:[46.998,-109.633],NE:[41.518,-99.797],NV:[39.306,-116.63],NH:[43.671,-71.582],NJ:[40.183,-74.663],NM:[34.392,-106.111],NY:[42.941,-75.538],NC:[35.535,-79.386],ND:[47.427,-100.463],OH:[40.288,-82.792],OK:[35.577,-97.525],OR:[43.92,-120.557],PA:[40.871,-77.806],RI:[41.647,-71.556],SC:[33.911,-80.891],SD:[44.419,-100.238],TN:[35.838,-86.351],TX:[31.443,-99.377],UT:[39.258,-111.656],VT:[44.054,-72.656],VA:[37.51,-78.859],WA:[47.372,-120.454],WV:[38.633,-80.617],WI:[44.624,-89.989],WY:[42.981,-107.532],PR:[18.219,-66.48]}};var li=(e,t,n,r)=>({id:e,label:t,parent:n,units:["each"],kinds:["sale"],specFields:[],examples:[],...r}),Eh=[li("crops","Crops & produce",null,{units:["lb","kg","bu","ton"],kinds:["sale","production-contract"]}),li("crops/grains","Grains & oilseeds","crops",{units:["bu","ton","lb"],kinds:["sale","production-contract"],typicalLeadDays:[100,160],examples:["Yellow corn #2","Food-grade soybeans","Hard red winter wheat","Malting barley"],specFields:[{key:"grade",label:"Grade / quality",placeholder:"e.g. #2 yellow, \u226415% moisture"},{key:"variety",label:"Variety"}],tokenizable:!0}),li("crops/specialty","Herbs, flowers & specialty crops","crops",{units:["lb","kg","stems","bunches"],kinds:["sale","production-contract"],typicalLeadDays:[60,200],examples:["Dried lavender (Lavandula angustifolia)","Fresh holy basil","Saffron crocus","Heirloom dahlias","Edible flowers mix","Hops"],specFields:[{key:"variety",label:"Species / variety",placeholder:"e.g. Lavandula \xD7 intermedia Grosso"},{key:"form",label:"Form",placeholder:"fresh, dried, oil, seed"},{key:"certification",label:"Certification",placeholder:"organic, GAP, none"}],tokenizable:!0}),li("crops/produce","Fruits & vegetables","crops",{units:["lb","kg","cases"],kinds:["sale","production-contract"],typicalLeadDays:[50,150],examples:["Heirloom tomatoes","Sweet corn","Microgreens"],specFields:[{key:"variety",label:"Variety"},{key:"pack",label:"Pack / case size"}]}),li("crops/livestock","Livestock & animal products","crops",{units:["head","lb","dozen"],kinds:["sale","production-contract"],typicalLeadDays:[30,400],examples:["Pasture-raised eggs","Grass-fed beef","Honey"],specFields:[{key:"breed",label:"Breed / type"}]}),li("inputs","Seed, fertilizer & inputs",null,{units:["bag","ton","gal","lb"],kinds:["sale"],examples:["Seed corn","Lavender plugs","Compost","Biological inoculant"],specFields:[{key:"product",label:"Product / brand"}]}),li("equipment","Equipment",null,{units:["each","day","acre"],kinds:["sale","rent"],examples:["Tractor 100 hp","Combine","Planter 16-row","Sprayer","Drip irrigation kit","Flower dryer","Essential-oil still"],specFields:[{key:"make",label:"Make / model"},{key:"year",label:"Year"},{key:"hours",label:"Hours"}],tokenizable:!0}),li("services","Services & custom hire",null,{units:["acre","hour","job","mile"],kinds:["service"],examples:["Custom planting","Custom harvesting","Spraying","Trucking","Grain storage","Agronomy advice","Plant disease diagnosis","Drying & processing"],specFields:[{key:"scope",label:"Scope of work"},{key:"equipment",label:"Equipment used"}]}),li("land","Land & storage",null,{units:["acre-year","bu-month","sq ft-month"],kinds:["rent"],examples:["Cropland lease","Bin space","Cold storage"],specFields:[{key:"location",label:"Location detail"}],tokenizable:!0}),li("digital","Data & knowledge",null,{units:["license","query","month"],kinds:["sale","service"],examples:["Plant knowledge graph","Yield dataset","Agronomy course"],specFields:[{key:"format",label:"Format / access"}]}),li("relay","Relay nodes & replication",null,{units:["month","MB","copy-month"],kinds:["service"],examples:["Relay node carriage for copies behind firewalls","Replica hosting","Always-on edge node"],specFields:[{key:"endpoint",label:"Relay URL",placeholder:"https://relay.example.com/cpz1"},{key:"carriers",label:"Connections",placeholder:"WebTransport, WebSocket, HTTPS"},{key:"ask",label:"Ask",placeholder:"e.g. 0.02 CAPPZ per MB"}]}),li("agents","AI agents & automation",null,{units:["job","task","hour","month"],kinds:["service"],examples:["Document summaries","Translation","Product descriptions","Data cleanup","Code review","Research briefs"],specFields:[{key:"runtime",label:"Runs on",placeholder:"My own computer, local model"},{key:"endpoint",label:"Agent address (URL)",placeholder:"https://\u2026"},{key:"payment",label:"Payment",placeholder:"XRP or CAPPZ, by stage"}]}),li("goods","Any other goods",null,{units:["each","lb","kg","case"],kinds:["sale","rent","production-contract"],examples:["Handmade goods","Packaging","Anything else"],specFields:[{key:"details",label:"Details"}]})],wT=new Map(Eh.map(e=>[e.id,e])),gr=e=>wT.get(e),Ya=e=>{let t=wT.get(e);for(;t?.parent;)t=wT.get(t.parent);return t?.id??e};var RO={AL:"Alabama",AK:"Alaska",AZ:"Arizona",AR:"Arkansas",CA:"California",CO:"Colorado",CT:"Connecticut",DE:"Delaware",DC:"District of Columbia",FL:"Florida",GA:"Georgia",HI:"Hawaii",ID:"Idaho",IL:"Illinois",IN:"Indiana",IA:"Iowa",KS:"Kansas",KY:"Kentucky",LA:"Louisiana",ME:"Maine",MD:"Maryland",MA:"Massachusetts",MI:"Michigan",MN:"Minnesota",MS:"Mississippi",MO:"Missouri",MT:"Montana",NE:"Nebraska",NV:"Nevada",NH:"New Hampshire",NJ:"New Jersey",NM:"New Mexico",NY:"New York",NC:"North Carolina",ND:"North Dakota",OH:"Ohio",OK:"Oklahoma",OR:"Oregon",PA:"Pennsylvania",PR:"Puerto Rico",RI:"Rhode Island",SC:"South Carolina",SD:"South Dakota",TN:"Tennessee",TX:"Texas",UT:"Utah",VT:"Vermont",VA:"Virginia",WA:"Washington",WV:"West Virginia",WI:"Wisconsin",WY:"Wyoming"},LO=DO,fb=Object.fromEntries(Object.entries(LO.states).filter(([e])=>RO[e]).map(([e,[t,n]])=>[e,{label:RO[e],lat:t,lon:n}])),BO=e=>{let t=e?LO.counties[e]:void 0;return t?{fips:e,state:t[0],name:t[1],lat:t[2],lon:t[3]}:null};var NO=e=>{let t=BO(e.county);return t&&t.state===e.region?t:fb[e.region]??null},pb=e=>{let t=BO(e.county);return t&&t.state===e.region?`${t.name}, ${e.region}`:fb[e.region]?.label??e.region};function yse(e,t){let n=Math.PI/180,r=3958.8,i=(t.lat-e.lat)*n,o=(t.lon-e.lon)*n,a=Math.sin(i/2)**2+Math.cos(e.lat*n)*Math.cos(t.lat*n)*Math.sin(o/2)**2;return Math.round(2*r*Math.asin(Math.sqrt(a)))}function FO(e,t){let n=NO(e),r=NO(t);return n&&r?yse(n,r):null}y();y();x4();y();y();x4();pf();var oN=`${Un.UNASSIGNED.replace(/\/99'$/,"/100'")}/principles`;var C3e=new jl(oN,"cappz:principles"),v3e=new jl(`${oN}/_invocations`,"cappz:principles:invocations");async function la(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}y();Qb();var M4="m/44'/144'/0'/cappz/event-tx-registry",W=M4,Rle=["PortfolioProvisioned","SkillConstituentIncluded","SkillConstituentRemoved","DealDrafted","DealLegAdded","DealLegAmended","DealSerialized","DealExecuted","PartyRegistered","PersonRegistered","PartyRoleBound","PartyRoleUnbound","PartyDealLinked","EmployeeHired","EmployeeFired","EmployeeResigned","MilestoneAffirmed","LegPaymentPosted","ProcessBound","TemplateRegistered","OntologyNodeDeclared","OntologyNodeAmended","OntologyNodeRetired","ConstituentIncluded","AgentBound","RuleBound","FunctionDeclared","EventTypeRegistered","SchemaRegistered","DealClonedFromTemplate","ProjectRegistered","ProjectAmended","ProjectGreenlit","ProjectDelivered","ProjectRetired","EventProjectionDeclared","EventProjectionSatisfied","EventProjectionLapsed","EventSubscriptionBound","EventSubscriptionUnbound","RevenuePosted","RecoupmentCredited","CommissionAccrued","CommissionTransferred","PayoutCycleSettled","CrmIdentityExported","CrmRecordCorrelated","PersonAssociationCreated","PersonAssociationDeprecated","PersonAssociationTerminated","PersonAssociationCancelled","PersonAssociationRemoved","CommissionRulesetDeclared","CommissionRuleDeclared","CommissionRuleDeprecated","AgentCommissionCalculated","AccountDeclared","JournalPosted","Iso20022MessageAttached","SettlementRailDeclared","SettlementInstructed","SettlementConfirmed","SettlementFailed","DealTerminated","DealPartiallyTerminated","RevenueStreamDeclared","ActivityRecorded","DelegationGranted","DelegationRevoked","ContractDocumentIngested","ContractDraftExtracted","ClarificationRaised","ClarificationAnswered","ExternalSystemRegistered","ExternalMappingDeclared","ExternalRecordCorrelated","ExternalSyncRequested","ExternalSyncCompleted","ExternalSyncFailed","ClientBillingTermsDeclared","InvoiceIssued","InvoiceVoided","CashReceived","CashApplied","TalentPayableRaised","TalentPaid","CommissionEligibilityPolicyDeclared","CommissionAttributionDeclared","CommissionEligibilityResolved","ContractValidated","ContractRejected","ContractApproved","ProductDelivered","DeliveryValidated","DeliveryRejected","DeliveryApproved","InvoiceApproved","TalentPaymentApproved","AssociationCreated","AssociationRemoved","DocumentUploaded","DocumentVersioned","DocumentArchived","DealCreated","DealDeprecated","DealTruncated","DealCompressed","DealConstituentCreated","DealConstituentDeprecated","DealConstituentTerminated","DealConstituentPartiallyTerminated","DealConstituentTruncated","DealConstituentCompressed","PartyDataAmended","PersonDataAmended","PartyRecordSuperseded","PersonRecordSuperseded","PartyPersonAssociationAmended","PartyPersonAssociationCancelled","PartyPersonAssociationTerminated","PartyPersonAssociationDeprecated","PartyWalletDeclared","PersonWalletDeclared","DealWalletDeclared","DealPayableAccountDeclared","IngestFileUploaded","IngestRunExecuted","FormatConfigCreated","FormatConfigAmended","FormatConfigDeprecated","FormatConfigTerminated","DocumentValidated","DocumentValidationFailed","PartyLegalEntityResolved","ConfirmationSent","ConfirmationMatched","ConfirmationMismatched","ConfirmationAffirmed","ConfirmationDisputed","ConfirmationNotarized","ConfirmationConstituentsAggregated","NovationConsentGiven","DealNovated","DealAmended","DealCancelled","DealActivated","ComplianceHoldPlaced","ComplianceHoldReleased","InterventionRequested","RemediationRequested","TradeRemediated"],Nle={DealCreated:"DealDeprecated",DealDeprecated:"DealCreated",DealConstituentCreated:"DealConstituentDeprecated",DealConstituentDeprecated:"DealConstituentCreated",ComplianceHoldPlaced:"ComplianceHoldReleased",ComplianceHoldReleased:"ComplianceHoldPlaced"},Lle=Rle.map(e=>{let t=Nle[e];return{eventType:e,mdmAddress:`${W}/ebb/${e.replace(/Tx$/,"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,category:"ebb",description:`EBB Contract Flow Administration event: ${e}`,emitters:["domain-agent"],hasPairedLifecycle:!!t,pairedEventType:t}}),Ble=[{category:"repoz",segment:"repoz",emitters:["wallet","agent","skill"],types:["ContentCreated","ContentAmended","AmendGranted","AmendRevoked","ReadGranted","ReadRevoked","ConflictDetected","BranchMerged","DependencyCreated","BuildConstituentIncluded","BuildManifestCreated","RepoZSynchronizationRequested","RepoZSynchronizationCompleted"]},{category:"wallet-tier",segment:"wallet-tier",emitters:["wallet"],types:["WalletCopied","WalletCloned","WalletTemplateRegistered","WalletTierTyped","WalletTierRetyped","UserPowAnchored","VersionPinned","VersionUnpinned","DomainModelAmended","ContextTurnAppended","UserAliasCreated","UserAliasAmended","NextSequenced","PreviousSequenced","ContextTagAssigned","ContextTagRemoved","ContentMigrated","ConstituentRemoved"]},{category:"security-access",segment:"security-access",emitters:["agent","wallet"],types:["SecurityPrincipalCreated","SecurityPrincipalRevoked","ConstituencyInvited","ConstituencyInviteAccepted","ConstituencyInviteDeclined","ConstituencyRequested","ConstituencyRequestRejected","AllAccessGranted","AllAccessRevoked","PermissionGranted","PermissionRevoked","BpmnGovernanceBound"]},{category:"inference",segment:"inference",emitters:["agent","skill"],types:["WalletHostDeclared","InferenceResidencyChanged","InferenceFallbackEngaged","InferenceModelChanged"]},{category:"model",segment:"model",emitters:["wallet","skill"],types:["ModelArtifactIngested","ConstituentsAggregated","ModelVersionPublished","ModelVersionRetired","ModelVersioned","ModelCacheWarmed"]},{category:"type-cast",segment:"type-cast",emitters:["agent","skill"],types:["TypeCastAssociated","TypeCastDisassociated"]},{category:"runtime-preference",segment:"runtime-preference",emitters:["agent"],types:["RuntimeLocationSelected","ModelSelected"]},{category:"admin",segment:"admin",emitters:["agent","wallet"],types:["CommandPermissionGranted","CommandPermissionRevoked","CommandMetadataAnchored","CommandMetadataAmended","AdminVerbRegistered","AdminVerbRevoked","AdminVerbDispatched","AdminVerbRejected","LoginRevoked","LoginRestored","SessionsRevoked","MemberInvited","PageVisited","LoginRecorded","AgentRequestRecorded","SiteNoticePublished","SiteNoticeWithdrawn","SignupClosed","SignupOpened","AccountAddressDerived","AccountAddressDeprecated","NetworkSwitched","AgentCreated"]},{category:"function-registry",segment:"function-registry",emitters:["agent","wallet"],types:["FunctionCreated","FunctionAmended","FunctionRetired","FunctionBindingAdded","FunctionBindingRemoved","FunctionAddressDerived","FunctionAddressDeprecated","ChainletBatchAnchored","FunctionPorted"]},{category:"feedback",segment:"feedback",emitters:["agent","wallet"],types:["FeedbackCreated","FeedbackReplied","FeedbackBroadcast","FeedbackClosed","FeedbackEscalated","FeedbackSubmissionRejected","FeedbackIssueApproved"]},{category:"media",segment:"media",emitters:["agent","wallet"],types:["MediaItemRegistered","MediaItemAmended","AlbumComposed","CatalogComposed","CatalogCorrelationDeclared","PlaylistStarted","PlaylistStopped","PlaylistAdvanced","PlaybackLoopModeSet","PlaybackPreempted","LyricsTranscribed","MediaIntegrityVerified","MediaTranscodeRejected","MediaItemPublished","MediaWalletEscrowed","MediaRawContentPurged","HomeDefaultMediaSet","PageDefaultMediaSet","PlaylistShuffled"]},{category:"migration",segment:"notarization-recovery",emitters:["agent","wallet"],types:["NotarizationSynchronized"]},{category:"migration",segment:"notarization",emitters:["agent","wallet"],types:["ContentNotarized","NotarizationCancelled"]},{category:"migration",segment:"network-promotion",emitters:["agent","wallet"],types:["NetworkPromotionRequested","PromotionPreflightRecorded","PromotionStepRequested","PromotionStepCompleted","PromotionStepFailed","SkillClonePromoted","ConfigManifestAnchored"]},{category:"fees",segment:"fees",emitters:["agent","wallet"],types:["FundsDeposited","FeesReserved","AppFunded","FeeCharged","SubscriptionCharged","PriceSheetPublished","ConsentRequested","ConsentGranted","ConsentDenied","ConsentRevoked","ServiceInitiated","ServicePaused","ServiceResumed","ServiceHalted","SubscriptionStarted","SubscriptionCancelled","UsageRecorded","TopUpProposed","TopUpApproved","TopUpDeclined","RunwayLow","TaskDeferred","TaskResumed","PriceAcknowledged","PriceSet","FundingRuleSet","FundingRuleRemoved","UsagePlanPublished","AliasCreated","AliasAmended","ChannelOpened","ChannelClosed","SessionStarted","SessionRenamed","SessionClosed","SessionReopened","SessionParticipantJoined","SessionParticipantLeft"]},{category:"a2a-sync",segment:"a2a-sync",emitters:["agent","wallet"],types:["DataSyncRequested","SyncSessionOpened","SyncItemOffered","SyncItemDelivered","SyncItemRejected","SyncForkDetected","SyncHeadersBatched","SyncBlobShredded","SyncSessionClosed","AmendConflictDetected","SyncCopyRegistered","SyncNetworkVerified","SyncCapabilityAdvertised","SyncCapabilityWithdrawn","SyncOffered","SyncRequested","SyncMatched","SyncOrderWithdrawn","SyncRejected","SyncCompleted","BaseSyncPriceOffered","BasePriceSyncRequested","SyncPaymentSettled","SyncRefundRequested","SyncPaymentReversed","SyncRefundDeclined","SyncArbitrationRequested","SyncArbitrationDecided","AppUpgradeOffered","AppUpgradeRequested","AppUpgradeApproved","AppUpgradeStaged","AppUpgradeActivated","AppUpgradeRejected","AppUpgradeExpired","AppUpgradeWithdrawn","AppUpgradeRolledBack","ReplicaConnectRequested","ReplicaConnectOffered","ReplicaConnectRejected","TunnelOpened","TunnelClosed","CopyEndpointRegistered","CopyEndpointAmended","SyncChecksumReceiptIssued","SyncSessionPaused","SyncSessionResumed","SyncSessionRestarted","PeerHeadAnnounced","PeerInventoryDiffed","PeerSignalExchanged","SyncBundleExported","SyncBundleImported","ReplicatorAgentCreated","ReplicatorPeerScored","ChannelConfigured","ChannelAmended","ChannelFailoverOccurred","DurabilityLevelSet","EscrowTargetAttached","EscrowSyncCompleted","FarmNodeScored","TransportCapabilityDeclared"]},{category:"harvest",segment:"harvest",emitters:["agent","wallet","domain-agent"],types:["HarvestRecordCaptured","ValidationAttested","SurveyOpened","SurveyClosed","ContributionVeiled","ContributionWithdrawn","AggregatePublished","AggregateDelivered","AggregateQueried","RoyaltyCredited","PaymentConfirmed","SettlementFinalized","OpportunityRecommended","RecommendationDecided","OutcomeObserved","ProgramElectionRecorded","ProgramPaymentRecorded"]},{category:"marketplace",segment:"marketplace",emitters:["agent","wallet","domain-agent"],types:["SupplyRequested","SupplyOffered","SupplyOfferWithdrawn","SupplyAwarded","SupplyRequestClosed","ListingWithdrawn","InventoryAdjusted","OrderPlaced","ContractCancelled","EscrowFunded","EscrowReleased","EscrowRefunded","MilestoneEvidenced","DisputeRaised","DisputeResolved","ReviewPosted","AssetTokenized","TokenTransferred","TokenRedeemed","AccessKeyDelivered","SecurityOfferingDeclared","SecurityOfferingApproved","SecuritySubscribed","SecurityAllocated","SecurityTransferred"]}],E3e=Object.fromEntries(["LoginRevokedTx","LoginRestoredTx","SessionsRevokedTx","UserInvitedTx","PageVisitedTx","LoginRecordedTx","AgentRequestRecordedTx","SiteNoticePublishedTx","SiteNoticeWithdrawnTx","SignupClosedTx","SignupOpenedTx"].map(e=>[e,xf[e]]));var sN=e=>e.replace(/Tx$/,"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Fle=Ble.flatMap(({category:e,segment:t,emitters:n,types:r})=>r.map(i=>({eventType:i,mdmAddress:`${W}/${t}/${sN(i)}`,category:e,description:`Substrate ${t} event: ${i}`,emitters:n,hasPairedLifecycle:!1}))),Ule={AgentBoundTx:"ebb",ConstituentCreatedTx:"ebb",SkillConstituentIncludedTx:"ebb",SkillConstituentRemovedTx:"ebb",ConstituentRemovedTx:"wallet-tier",WalletClonedTx:"wallet-tier"},aN=[{eventType:"AdminQueueCreated",mdmAddress:`${W}/admin-queue/queue-created`,category:"admin-queue",description:"Genesis TX for any admin queue",emitters:["wallet","agent","skill"],hasPairedLifecycle:!1},{eventType:"WalletCreated",mdmAddress:`${W}/admin-queue/wallet-created`,category:"admin-queue",canonicalType:"ContentCreated",description:"Wallet genesis event",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"WalletDeprecated"},{eventType:"WalletCloned",mdmAddress:`${W}/admin-queue/wallet-cloned`,category:"admin-queue",canonicalType:"ContentCloned",description:"Wallet cloned from source",emitters:["wallet"],hasPairedLifecycle:!1},{eventType:"WalletActivated",mdmAddress:`${W}/admin-queue/wallet-activated`,category:"admin-queue",description:"Wallet activated for operations",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"WalletDeactivated"},{eventType:"WalletSuspended",mdmAddress:`${W}/admin-queue/wallet-suspended`,category:"admin-queue",description:"Wallet suspended (reversible)",emitters:["wallet"],hasPairedLifecycle:!1},{eventType:"WalletDeactivated",mdmAddress:`${W}/admin-queue/wallet-deactivated`,category:"admin-queue",description:"Wallet deactivated",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"WalletActivated"},{eventType:"WalletDeprecated",mdmAddress:`${W}/admin-queue/wallet-deprecated`,category:"admin-queue",description:"Wallet deprecated (terminal)",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"WalletCreated"},{eventType:"AgentBound",mdmAddress:`${W}/admin-queue/agent-bound`,category:"admin-queue",description:"Agent bound to wallet",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"AgentUnbound"},{eventType:"AgentUnbound",mdmAddress:`${W}/admin-queue/agent-unbound`,category:"admin-queue",description:"Agent unbound from wallet",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"AgentBound"},{eventType:"AgentHibernated",mdmAddress:`${W}/admin-queue/agent-hibernated`,category:"admin-queue",description:"Agent hibernated (COTA)",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"AgentResumed"},{eventType:"AgentResumed",mdmAddress:`${W}/admin-queue/agent-resumed`,category:"admin-queue",description:"Agent resumed from hibernation",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"AgentHibernated"},{eventType:"SkillAttached",mdmAddress:`${W}/admin-queue/skill-attached`,category:"admin-queue",description:"Skill attached to agent",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillDetached"},{eventType:"SkillDetached",mdmAddress:`${W}/admin-queue/skill-detached`,category:"admin-queue",description:"Skill detached from agent",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillAttached"},{eventType:"SkillPaused",mdmAddress:`${W}/admin-queue/skill-paused`,category:"admin-queue",description:"Skill paused",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillResumed"},{eventType:"SkillResumed",mdmAddress:`${W}/admin-queue/skill-resumed`,category:"admin-queue",description:"Skill resumed",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillPaused"},{eventType:"AdminCommand",mdmAddress:`${W}/admin-queue/admin-command`,category:"admin-queue",description:"Inter-queue command",emitters:["wallet","agent","skill"],hasPairedLifecycle:!1},{eventType:"AdminAck",mdmAddress:`${W}/admin-queue/admin-ack`,category:"admin-queue",description:"Acknowledge received command",emitters:["wallet","agent","skill"],hasPairedLifecycle:!1},{eventType:"AdminNack",mdmAddress:`${W}/admin-queue/admin-nack`,category:"admin-queue",description:"Reject received command",emitters:["wallet","agent","skill"],hasPairedLifecycle:!1},{eventType:"GroupMemberAdded",mdmAddress:`${W}/group-membership/group-member-added`,category:"group-membership",description:"Member (person, agent or group) added to a group account",emitters:["wallet","agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"GroupMemberRemoved"},{eventType:"GroupMemberRemoved",mdmAddress:`${W}/group-membership/group-member-removed`,category:"group-membership",description:"Member removed from a group account (correlated to its GroupMemberAdded)",emitters:["wallet","agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"GroupMemberAdded"},{eventType:"EdgeFunctionAmended",mdmAddress:`${W}/function-registry/edge-function-amended`,category:"function-registry",description:"Deprecated \u2014 replaced by FunctionAmended (v12-20-09). Replayed, never written.",emitters:["agent"],hasPairedLifecycle:!1,deprecatedBy:"FunctionAmended"},{eventType:"EdgeFunctionRetired",mdmAddress:`${W}/function-registry/edge-function-retired`,category:"function-registry",description:"Deprecated \u2014 replaced by FunctionRetired (v12-20-09). Replayed, never written.",emitters:["agent"],hasPairedLifecycle:!1,deprecatedBy:"FunctionRetired"},{eventType:"GroupMemberCreated",mdmAddress:`${W}/group-membership/member-created`,category:"group-membership",description:"Deprecated \u2014 replaced by GroupMemberAdded (v12-20-05-groups)",emitters:["agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"GroupMemberDeactivated",deprecatedBy:"GroupMemberAdded"},{eventType:"GroupMemberActivated",mdmAddress:`${W}/group-membership/member-activated`,category:"group-membership",description:"Group member activated",emitters:["agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"GroupMemberSuspended"},{eventType:"GroupMemberSuspended",mdmAddress:`${W}/group-membership/member-suspended`,category:"group-membership",description:"Group member suspended",emitters:["agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"GroupMemberReActivated"},{eventType:"GroupMemberReActivated",mdmAddress:`${W}/group-membership/member-reactivated`,category:"group-membership",description:"Group member reactivated",emitters:["agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"GroupMemberSuspended"},{eventType:"GroupMemberDeactivated",mdmAddress:`${W}/group-membership/member-deactivated`,category:"group-membership",description:"Deprecated \u2014 replaced by GroupMemberRemoved (v12-20-05-groups)",emitters:["agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"GroupMemberCreated",deprecatedBy:"GroupMemberRemoved"},{eventType:"KeyDeclared",mdmAddress:`${W}/identity/key-declared`,category:"identity",canonicalType:"ContentCreated",description:"Wallet-signed statement that a key (hello, tls, signing, encryption) speaks for the wallet until it expires",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"KeyDeclarationRevoked"},{eventType:"KeyDeclarationRevoked",mdmAddress:`${W}/identity/key-declaration-revoked`,category:"identity",description:"Wallet-signed revocation of one key declaration (by declaration hash); replayed by every verifier",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"KeyDeclared"},{eventType:"KeyDelegated",mdmAddress:`${W}/identity/key-delegated`,category:"identity",canonicalType:"ContentCreated",description:"A declared key binds a short-lived key (e.g. an in-memory TLS key) for one purpose",emitters:["wallet","agent"],hasPairedLifecycle:!1},{eventType:"MeshChartered",mdmAddress:`${W}/identity/mesh-chartered`,category:"identity",canonicalType:"ContentCreated",description:"An authority wallet signs a mesh charter (authorities, policy); the mesh id is its hash",emitters:["wallet"],hasPairedLifecycle:!1},{eventType:"MeshMembershipGranted",mdmAddress:`${W}/identity/mesh-membership-granted`,category:"identity",canonicalType:"ContentCreated",description:"A charter authority grants a wallet a mesh role (coordinator, responder, member) until it expires",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"MeshMembershipRevoked"},{eventType:"MeshMembershipRevoked",mdmAddress:`${W}/identity/mesh-membership-revoked`,category:"identity",description:"A charter authority revokes a membership grant (by grant hash); gossiped on the mesh and replayed by every node",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"MeshMembershipGranted"},{eventType:"IdentityClaimRecorded",mdmAddress:`${W}/identity/claim-recorded`,category:"identity",canonicalType:"ContentCreated",description:"A salted claim digest in the holder identity wallet; the value stays encrypted in the wallet",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"IdentityClaimRevoked"},{eventType:"IdentityClaimAmended",mdmAddress:`${W}/identity/claim-amended`,category:"identity",canonicalType:"ContentAmended",description:"A new version of a claim naming the claim it amends",emitters:["wallet"],hasPairedLifecycle:!1},{eventType:"IdentityClaimRevoked",mdmAddress:`${W}/identity/claim-revoked`,category:"identity",description:"Holder withdraws a claim from future disclosures (past disclosures stay delivered)",emitters:["wallet"],hasPairedLifecycle:!0,pairedEventType:"IdentityClaimRecorded"},{eventType:"IdentityAttested",mdmAddress:`${W}/identity/attested`,category:"identity",canonicalType:"ContentCreated",description:"Issuer-signed attestation over claim digests with its evidence level (NIST 800-63 IAL)",emitters:["wallet","agent"],hasPairedLifecycle:!0,pairedEventType:"IdentityAttestationRevoked"},{eventType:"IdentityAttestationRevoked",mdmAddress:`${W}/identity/attestation-revoked`,category:"identity",description:"Issuer revokes an attestation it signed",emitters:["wallet","agent"],hasPairedLifecycle:!0,pairedEventType:"IdentityAttested"},{eventType:"BiometricBindingRecorded",mdmAddress:`${W}/identity/biometric-binding-recorded`,category:"identity",canonicalType:"ContentCreated",description:"A device authenticator (WebAuthn) bound to the identity; only a credential-id hash, never a biometric template",emitters:["wallet"],hasPairedLifecycle:!1},{eventType:"IdentityDisclosureRequested",mdmAddress:`${W}/identity/disclosure-requested`,category:"identity",description:"Verifier asks a holder for named claims, with purpose and nonce",emitters:["wallet","agent"],hasPairedLifecycle:!1},{eventType:"IdentityDisclosed",mdmAddress:`${W}/identity/disclosed`,category:"identity",description:"Holder answers a disclosure request: the chosen disclosures sealed to the verifier, bound to the nonce",emitters:["wallet"],hasPairedLifecycle:!1},{eventType:"LegacyVerifierRetired",mdmAddress:`${W}/identity/legacy-verifier-retired`,category:"identity",description:"An admin retires a legacy verifier (e.g. a PHP route signature check) on a shadow-comparison report: names the route, the report hash, agreement and stricter reasons; TLS and regulator-required X.509 are kept",emitters:["wallet","agent"],hasPairedLifecycle:!1},{eventType:"LegacyRouteCutOver",mdmAddress:`${W}/migration/legacy-route-cut-over`,category:"migration",description:"A route of a legacy app (e.g. a PHP endpoint) is served by its port instead of the legacy runtime, on a response-shadow report that passed the gate: names the route, the report hash, requests, days and match rate, and the operator wallet; signed by the edge node",emitters:["agent","wallet"],hasPairedLifecycle:!1},{eventType:"LegacyRouteRolledBack",mdmAddress:`${W}/migration/legacy-route-rolled-back`,category:"migration",description:"A route is sent back to the legacy runtime (or to shadow) with the reason; its comparison evidence starts again",emitters:["agent","wallet"],hasPairedLifecycle:!1},{eventType:"IdentityDisclosureDeclined",mdmAddress:`${W}/identity/disclosure-declined`,category:"identity",description:"Holder declines a disclosure request with a reason",emitters:["wallet"],hasPairedLifecycle:!1},{eventType:"ContentQuarantined",mdmAddress:`${W}/dmz/content-quarantined`,category:"dmz",canonicalType:"ContentCreated",description:"A file from an untrusted sender (HTTP drop, FTP/SFTP pull) held by hash in the DMZ node quarantine",emitters:["agent","wallet"],hasPairedLifecycle:!1},{eventType:"QuarantineCheckRecorded",mdmAddress:`${W}/dmz/quarantine-check-recorded`,category:"dmz",description:"One check on a quarantined file: pass, fail or not-evaluated, with the reason",emitters:["agent","wallet"],hasPairedLifecycle:!1},{eventType:"ContentReleased",mdmAddress:`${W}/dmz/content-released`,category:"dmz",description:"A quarantined file released to internal clients (policy: every required check passed, or an operator decision)",emitters:["agent","wallet"],hasPairedLifecycle:!1},{eventType:"ContentRejected",mdmAddress:`${W}/dmz/content-rejected`,category:"dmz",description:"A quarantined file refused with the failed check or the operator reason; the bytes are not released",emitters:["agent","wallet"],hasPairedLifecycle:!1},{eventType:"EventTypeDeprecated",mdmAddress:`${W}/mdm-graph/event-type-deprecated`,category:"mdm-graph",description:"Records that an event type is retired; payload { eventType, replacedBy }",emitters:["wallet","agent","skill"],hasPairedLifecycle:!1},{eventType:"ReleasePlanCreationRequested",mdmAddress:`${W}/cid/release-plan-creation-requested`,category:"cid",description:"Admin-signed request to create release plan",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"ReleasePlanExecutionRequested",mdmAddress:`${W}/cid/release-plan-execution-requested`,category:"cid",description:"Dual-sig request to execute release plan",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"ReleasePlanCreated",mdmAddress:`${W}/cid/release-plan-created`,category:"cid",description:"Release plan created with step provenance",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"ReleasePlanExecutionStarted",mdmAddress:`${W}/cid/release-plan-execution-started`,category:"cid",description:"Release plan execution pipeline started",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"ReleasePlanExecutionCompleted",mdmAddress:`${W}/cid/release-plan-execution-completed`,category:"cid",description:"Release plan execution completed (success or failed)",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"ReleasePlanStepExecuted",mdmAddress:`${W}/cid/release-plan-step-executed`,category:"cid",description:"Individual release plan step executed with receipt",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"ConstituentCreated",mdmAddress:`${W}/cid/constituent-created`,category:"cid",description:"Links parent constituent to child in HD hierarchy (canon\u2192book, book\u2192chapter, chapter\u2192verse)",emitters:["cid-agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ConstituentRemoved"},{eventType:"ConstituentRemoved",mdmAddress:`${W}/cid/constituent-removed`,category:"cid",description:"Removes constituent link from release plan",emitters:["cid-agent"],hasPairedLifecycle:!0,pairedEventType:"ConstituentCreated"},{eventType:"ConstituentIngestFailed",mdmAddress:`${W}/cid/constituent-ingest-failed`,category:"cid",description:"Constituent ingestion failed \u2014 error captured",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ConstituentIngestSuspended",mdmAddress:`${W}/cid/constituent-ingest-suspended`,category:"cid",description:"Constituent ingestion suspended (recoverable)",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"ConstituentIngestResumed"},{eventType:"ConstituentIngestResumed",mdmAddress:`${W}/cid/constituent-ingest-resumed`,category:"cid",description:"Constituent ingestion resumed from suspension",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"ConstituentIngestSuspended"},{eventType:"CloneStateSynced",mdmAddress:`${W}/cid/clone-state-synced`,category:"cid",description:"Clone state synced to cappz.ai mirror",emitters:["cid-agent","domain-agent"],hasPairedLifecycle:!1},{eventType:"CloneLearningPromoted",mdmAddress:`${W}/cid/clone-learning-promoted`,category:"cid",description:"Local clone learning promoted autonomously",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"SkillCloneCreated",mdmAddress:`${W}/clone/skill-clone-created`,category:"clone",canonicalType:"ContentCloned",description:"Skill cloned from parent template",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"SkillUpgradeRequested",mdmAddress:`${W}/clone/skill-upgrade-requested`,category:"clone",description:"Upgrade requested from parent version",emitters:["skill","cid-agent"],hasPairedLifecycle:!1},{eventType:"SkillUpgradeApplied",mdmAddress:`${W}/clone/skill-upgrade-applied`,category:"clone",description:"Upgrade applied from parent version",emitters:["skill","cid-agent"],hasPairedLifecycle:!1},{eventType:"BuildLogSynced",mdmAddress:`${W}/clone/build-log-synced`,category:"clone",description:"Build log entries synced to parent template",emitters:["cid-agent"],hasPairedLifecycle:!1},{eventType:"AgentSkillScopeCreated",mdmAddress:`${W}/clone/agent-skill-scope-created`,category:"clone",description:"Agent skill scope created for user clone",emitters:["agent"],hasPairedLifecycle:!1},{eventType:"NotarizeEachOnSaveCreated",mdmAddress:`${W}/config/notarize-each-created`,category:"config",description:"Enable per-save notarization",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"NotarizeEachOnSaveDeprecated"},{eventType:"NotarizeEachOnSaveDeprecated",mdmAddress:`${W}/config/notarize-each-deprecated`,category:"config",description:"Disable per-save notarization",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"NotarizeEachOnSaveCreated"},{eventType:"NotarizeAllOnSaveCreated",mdmAddress:`${W}/config/notarize-all-created`,category:"config",description:"Enable batch notarization",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"NotarizeAllOnSaveDeprecated"},{eventType:"NotarizeAllOnSaveDeprecated",mdmAddress:`${W}/config/notarize-all-deprecated`,category:"config",description:"Disable batch notarization",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"NotarizeAllOnSaveCreated"},{eventType:"A2ATransceiverCreated",mdmAddress:`${W}/config/a2a-transceiver-created`,category:"config",description:"Enable A2A transceiver mode",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"A2ATransceiverDeprecated"},{eventType:"A2ATransceiverDeprecated",mdmAddress:`${W}/config/a2a-transceiver-deprecated`,category:"config",description:"Disable A2A transceiver",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"A2ATransceiverCreated"},{eventType:"A2AReceiverCreated",mdmAddress:`${W}/config/a2a-receiver-created`,category:"config",description:"Enable A2A receive-only",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"A2AReceiverDeprecated"},{eventType:"A2AReceiverDeprecated",mdmAddress:`${W}/config/a2a-receiver-deprecated`,category:"config",description:"Disable A2A receive-only",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"A2AReceiverCreated"},{eventType:"A2ATransmitterCreated",mdmAddress:`${W}/config/a2a-transmitter-created`,category:"config",description:"Enable A2A transmit-only",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"A2ATransmitterDeprecated"},{eventType:"A2ATransmitterDeprecated",mdmAddress:`${W}/config/a2a-transmitter-deprecated`,category:"config",description:"Disable A2A transmit-only",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"A2ATransmitterCreated"},{eventType:"SynchronizeEachOnSaveCreated",mdmAddress:`${W}/config/sync-each-created`,category:"config",description:"Enable per-save sync",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"SynchronizeEachOnSaveDeprecated"},{eventType:"SynchronizeEachOnSaveDeprecated",mdmAddress:`${W}/config/sync-each-deprecated`,category:"config",description:"Disable per-save sync",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"SynchronizeEachOnSaveCreated"},{eventType:"SynchronizeAllOnSaveCreated",mdmAddress:`${W}/config/sync-all-created`,category:"config",description:"Enable batch sync",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"SynchronizeAllOnSaveDeprecated"},{eventType:"SynchronizeAllOnSaveDeprecated",mdmAddress:`${W}/config/sync-all-deprecated`,category:"config",description:"Disable batch sync",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"SynchronizeAllOnSaveCreated"},{eventType:"EncryptAtRestCreated",mdmAddress:`${W}/config/encrypt-rest-created`,category:"config",description:"Enable encryption at rest",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"EncryptAtRestDeprecated"},{eventType:"EncryptAtRestDeprecated",mdmAddress:`${W}/config/encrypt-rest-deprecated`,category:"config",description:"Disable encryption at rest",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"EncryptAtRestCreated"},{eventType:"EncryptInTransitCreated",mdmAddress:`${W}/config/encrypt-transit-created`,category:"config",description:"Enable encryption in transit",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"EncryptInTransitDeprecated"},{eventType:"EncryptInTransitDeprecated",mdmAddress:`${W}/config/encrypt-transit-deprecated`,category:"config",description:"Disable encryption in transit",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"EncryptInTransitCreated"},{eventType:"RetentionPruneOnWindowCreated",mdmAddress:`${W}/config/retention-prune-created`,category:"config",description:"Enable retention pruning",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"RetentionPruneOnWindowDeprecated"},{eventType:"RetentionPruneOnWindowDeprecated",mdmAddress:`${W}/config/retention-prune-deprecated`,category:"config",description:"Disable retention pruning",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"RetentionPruneOnWindowCreated"},{eventType:"RetentionArchiveOnSaveCreated",mdmAddress:`${W}/config/retention-archive-created`,category:"config",description:"Enable save-time archival",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"RetentionArchiveOnSaveDeprecated"},{eventType:"RetentionArchiveOnSaveDeprecated",mdmAddress:`${W}/config/retention-archive-deprecated`,category:"config",description:"Disable save-time archival",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"RetentionArchiveOnSaveCreated"},{eventType:"CompressionOnSaveCreated",mdmAddress:`${W}/config/compression-created`,category:"config",description:"Enable save-time compression",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"CompressionOnSaveDeprecated"},{eventType:"CompressionOnSaveDeprecated",mdmAddress:`${W}/config/compression-deprecated`,category:"config",description:"Disable save-time compression",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"CompressionOnSaveCreated"},{eventType:"HibernationAutoCreated",mdmAddress:`${W}/config/hibernation-auto-created`,category:"config",description:"Enable auto-hibernation",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"HibernationAutoDeprecated"},{eventType:"HibernationAutoDeprecated",mdmAddress:`${W}/config/hibernation-auto-deprecated`,category:"config",description:"Disable auto-hibernation",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"HibernationAutoCreated"},{eventType:"FeeTierOverrideCreated",mdmAddress:`${W}/config/fee-tier-override-created`,category:"config",description:"Set fee tier override",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"FeeTierOverrideDeprecated"},{eventType:"FeeTierOverrideDeprecated",mdmAddress:`${W}/config/fee-tier-override-deprecated`,category:"config",description:"Remove fee tier override",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"FeeTierOverrideCreated"},{eventType:"ProvenanceTrackingCreated",mdmAddress:`${W}/config/provenance-tracking-created`,category:"config",description:"Enable provenance tracking",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"ProvenanceTrackingDeprecated"},{eventType:"ProvenanceTrackingDeprecated",mdmAddress:`${W}/config/provenance-tracking-deprecated`,category:"config",description:"Disable provenance tracking",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"ProvenanceTrackingCreated"},{eventType:"MDMBindingCreated",mdmAddress:`${W}/config/mdm-binding-created`,category:"config",description:"Create MDM binding for agent",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"MDMBindingDeprecated"},{eventType:"MDMBindingDeprecated",mdmAddress:`${W}/config/mdm-binding-deprecated`,category:"config",description:"Deprecate MDM binding",emitters:["agent"],hasPairedLifecycle:!0,pairedEventType:"MDMBindingCreated"},{eventType:"ContentIngested",mdmAddress:`${W}/content/content-ingested`,category:"content",canonicalType:"ContentCreated",description:"Content ingested into agent scope",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"ContentFragmented",mdmAddress:`${W}/content/content-fragmented`,category:"content",description:"Content fragmented into shreds",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentTranslated",mdmAddress:`${W}/content/content-translated`,category:"content",description:"Content translated between formats",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"WalletBlobSerialized",mdmAddress:`${W}/content/wallet-blob-serialized`,category:"content",description:"Wallet content reduced to immutable {slug}-v{n}.cappz blob on OPFS; sha256 + origins published",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"PipelineStageCompleted",mdmAddress:`${W}/pipeline/stage-completed`,category:"pipeline",description:"Pipeline stage completed successfully",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"PipelineStageFailed",mdmAddress:`${W}/pipeline/stage-failed`,category:"pipeline",description:"Pipeline stage failed",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"CodeValueCreated",mdmAddress:`${W}/mdm-graph/code-value-created`,category:"mdm-graph",canonicalType:"ContentCreated",description:"Code value registered in MDM",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"CodeValueDeprecated"},{eventType:"CodeValueDeprecated",mdmAddress:`${W}/mdm-graph/code-value-deprecated`,category:"mdm-graph",canonicalType:"ContentDeprecated",description:"Code value deprecated in MDM",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"CodeValueCreated"},{eventType:"VersionCreated",mdmAddress:`${W}/mdm-graph/version-created`,category:"mdm-graph",description:"Version entry created",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"VersionAssociated",mdmAddress:`${W}/mdm-graph/version-associated`,category:"mdm-graph",description:"Version associated to artifact",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"SkillBindingCreated",mdmAddress:`${W}/mdm-graph/skill-binding-created`,category:"mdm-graph",description:"Skill binding created in graph",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillBindingDeprecated"},{eventType:"SkillBindingDeprecated",mdmAddress:`${W}/mdm-graph/skill-binding-deprecated`,category:"mdm-graph",description:"Skill binding deprecated",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillBindingCreated"},{eventType:"SkillBindingActivated",mdmAddress:`${W}/mdm-graph/skill-binding-activated`,category:"mdm-graph",description:"Skill binding activated \u2014 canon is live for user",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillBindingDeactivated"},{eventType:"SkillBindingDeactivated",mdmAddress:`${W}/mdm-graph/skill-binding-deactivated`,category:"mdm-graph",description:"Skill binding deactivated \u2014 canon inactive",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillBindingActivated"},{eventType:"SkillConstituentIncluded",mdmAddress:`${W}/mdm-graph/skill-constituent-included`,category:"mdm-graph",description:"Skill constituent included",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillConstituentRemoved"},{eventType:"SkillConstituentRemoved",mdmAddress:`${W}/mdm-graph/skill-constituent-removed`,category:"mdm-graph",description:"Skill constituent removed",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SkillConstituentIncluded"},{eventType:"DomainRegistered",mdmAddress:`${W}/mdm-graph/domain-registered`,category:"mdm-graph",description:"Domain registered in MDM",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"StandardRegistered",mdmAddress:`${W}/mdm-graph/standard-registered`,category:"mdm-graph",description:"Standard registered in MDM",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ArtifactGroupCreated",mdmAddress:`${W}/mdm-graph/artifact-group-created`,category:"mdm-graph",description:"Artifact group created",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ListDomainCreated",mdmAddress:`${W}/mdm-graph/list-domain-created`,category:"mdm-graph",canonicalType:"ContentCreated",description:"List domain created",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ListValueCreated",mdmAddress:`${W}/mdm-graph/list-value-created`,category:"mdm-graph",canonicalType:"ContentCreated",description:"List value created",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ValueMappingCreated",mdmAddress:`${W}/mdm-graph/value-mapping-created`,category:"mdm-graph",description:"Value mapping created",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"RoyaltyFeeAmended",mdmAddress:`${W}/mdm-graph/royalty-fee-amended`,category:"mdm-graph",description:"Royalty fee structure amended",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"MigrationInitiated",mdmAddress:`${W}/migration/initiated`,category:"migration",description:"DB migration initiated",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"MigrationResumed",mdmAddress:`${W}/migration/resumed`,category:"migration",description:"DB migration resumed from checkpoint",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"MigrationCheckpointCompleted",mdmAddress:`${W}/migration/checkpoint-completed`,category:"migration",description:"Migration checkpoint saved",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"MigrationSuspended",mdmAddress:`${W}/migration/suspended`,category:"migration",description:"Migration suspended on error",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"MigrationCompleted",mdmAddress:`${W}/migration/completed`,category:"migration",description:"Migration completed successfully",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BridgeSessionCreated",mdmAddress:`${W}/bridge/session-created`,category:"bridge",description:"Bridge session wallet created",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BridgeFiatReceived",mdmAddress:`${W}/bridge/fiat-received`,category:"bridge",description:"Fiat payment received via bridge",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BridgeXRPConverted",mdmAddress:`${W}/bridge/xrp-converted`,category:"bridge",description:"Fiat converted to XRP",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BridgeCAPPZMinted",mdmAddress:`${W}/bridge/cappz-minted`,category:"bridge",description:"CAPPZ minted from XRP",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BridgeCompleted",mdmAddress:`${W}/bridge/completed`,category:"bridge",description:"Bridge transaction completed",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BridgeFailed",mdmAddress:`${W}/bridge/failed`,category:"bridge",description:"Bridge transaction failed",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"AsyncResponseFetched",mdmAddress:`${W}/content/async-response-fetched`,category:"content",description:"Async response fetched \u2014 gates callback notification",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"PredecessorAssigned",mdmAddress:`${W}/ordered-list/predecessor-assigned`,category:"ordered-list",description:"Assigns predecessor in TX-linked ordered list (source=next, target=previous)",emitters:["agent","skill","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"PredecessorDeprecated"},{eventType:"PredecessorDeprecated",mdmAddress:`${W}/ordered-list/predecessor-deprecated`,category:"ordered-list",description:"Deprecates predecessor assignment (correlated to replacement PredecessorAssigned)",emitters:["agent","skill","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"PredecessorAssigned"},{eventType:"BPMNFlowAnchored",mdmAddress:`${W}/bpmn/flow-anchored`,category:"pipeline",description:"Sequence flow registered as TX link between BPMN elements",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"BPMNFlowDeprecated"},{eventType:"BPMNFlowDeprecated",mdmAddress:`${W}/bpmn/flow-deprecated`,category:"pipeline",description:"Sequence flow deprecated (re-routing)",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"BPMNFlowAnchored"},{eventType:"BPMNSkillCallBound",mdmAddress:`${W}/bpmn/skill-call-bound`,category:"pipeline",description:"CallActivity bound to sub-skill MDM address + process",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"BPMNSkillCallUnbound"},{eventType:"BPMNSkillCallUnbound",mdmAddress:`${W}/bpmn/skill-call-unbound`,category:"pipeline",description:"CallActivity unbound from sub-skill",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"BPMNSkillCallBound"},{eventType:"BPMNProcessCloneMirrored",mdmAddress:`${W}/bpmn/process-clone-mirrored`,category:"clone",description:"Template BPMN config mirrored to clone via TXs",emitters:["skill","cid-agent"],hasPairedLifecycle:!1},{eventType:"BPMNProcessVersionCreated",mdmAddress:`${W}/bpmn/process-version-created`,category:"pipeline",description:"New BPMN process version created",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BPMNProcessVersionAmended",mdmAddress:`${W}/bpmn/process-version-amended`,category:"pipeline",description:"BPMN process version amended (re-sequenced/modified)",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BPMNGatewayRouteAnchored",mdmAddress:`${W}/bpmn/gateway-route-anchored`,category:"pipeline",description:"Gateway branch routes registered on-chain",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BPMNPipelineSequenced",mdmAddress:`${W}/bpmn/pipeline-sequenced`,category:"pipeline",description:"Pipeline config sequenced via BPMN inheritance",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"DuplicateTxDeprecated",mdmAddress:`${W}/cid/duplicate-tx-deprecated`,category:"cid",description:"Deprecates a duplicate TX \u2014 retains oldest, supersedes newer duplicates via correlation",emitters:["skill","cid-agent"],hasPairedLifecycle:!1},{eventType:"DuplicateTxRemediationCompleted",mdmAddress:`${W}/cid/duplicate-tx-remediation-completed`,category:"cid",description:"Audit report of completed duplicate TX remediation run",emitters:["skill","cid-agent"],hasPairedLifecycle:!1},{eventType:"AccessRequestCreated",mdmAddress:`${W}/rap/access-request-created`,category:"admin-queue",description:"Resource access request submitted",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"AccessGranted",mdmAddress:`${W}/rap/access-granted`,category:"admin-queue",description:"Resource access granted \u2014 linked to request via PredecessorAssigned",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"AccessRevoked"},{eventType:"AccessRevoked",mdmAddress:`${W}/rap/access-revoked`,category:"admin-queue",description:"Resource access revoked \u2014 supersedes grant TX",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"AccessGranted"},{eventType:"AccessExpired",mdmAddress:`${W}/rap/access-expired`,category:"admin-queue",description:"Resource access expired (TTL)",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"AccessConsumed",mdmAddress:`${W}/rap/access-consumed`,category:"admin-queue",description:"Access consumption event (MAC counter)",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"AdminGrantPropagated",mdmAddress:`${W}/rap/admin-grant-propagated`,category:"admin-queue",description:"Grant cascaded from parent clone to child clones",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"ClonePermissionRequested",mdmAddress:`${W}/acp/clone-permission-requested`,category:"clone",description:"Request to clone a skill/wallet",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"ClonePermissionGranted",mdmAddress:`${W}/acp/clone-permission-granted`,category:"clone",description:"Clone permission granted \u2014 admin to parent agent",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ClonePermissionRevoked"},{eventType:"ClonePermissionRevoked",mdmAddress:`${W}/acp/clone-permission-revoked`,category:"clone",description:"Clone permission revoked \u2014 correlates to Grant TxID",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ClonePermissionGranted"},{eventType:"CopyPermissionRequested",mdmAddress:`${W}/acp/copy-permission-requested`,category:"clone",description:"Request to copy a skill/wallet",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"CopyPermissionGranted",mdmAddress:`${W}/acp/copy-permission-granted`,category:"clone",description:"Copy permission granted \u2014 to admin group address",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"CopyPermissionRevoked"},{eventType:"CopyPermissionRevoked",mdmAddress:`${W}/acp/copy-permission-revoked`,category:"clone",description:"Copy permission revoked \u2014 correlates to Grant TxID",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"CopyPermissionGranted"},{eventType:"OperatePermissionRequested",mdmAddress:`${W}/acp/operate-permission-requested`,category:"clone",description:"Request to operate cloned asset \u2014 with payment",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"OperatePermissionGranted",mdmAddress:`${W}/acp/operate-permission-granted`,category:"clone",description:"Operate permission granted \u2014 from cloned UCL to user admin queue",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"OperatePermissionRevoked"},{eventType:"OperatePermissionRevoked",mdmAddress:`${W}/acp/operate-permission-revoked`,category:"clone",description:"Operate permission revoked \u2014 correlates to Grant TxID",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"OperatePermissionGranted"},{eventType:"LibraryCreated",mdmAddress:`${W}/codex/library-created`,category:"content",description:"User Codex Library provisioned on demand under user-wallet agent",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"CanonSkillAdded",mdmAddress:`${W}/codex/canon-skill-added`,category:"content",description:"[DEPRECATED \u2014 use SkillBindingCreated] Canon skill added to user library",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"CanonSkillRemoved"},{eventType:"CanonSkillRemoved",mdmAddress:`${W}/codex/canon-skill-removed`,category:"content",description:"[DEPRECATED \u2014 use SkillBindingDeprecated] Canon skill removed from user library",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"CanonSkillAdded"},{eventType:"VolumeCreated",mdmAddress:`${W}/codex/volume-created`,category:"content",description:"Volume organizational grouping created within a canon skill (default or user-created)",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"VolumeDeprecated"},{eventType:"VolumeDeprecated",mdmAddress:`${W}/codex/volume-deprecated`,category:"content",description:"Volume deprecated (user-created only)",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"VolumeCreated"},{eventType:"VolumeConstituentAdded",mdmAddress:`${W}/codex/volume-constituent-added`,category:"content",description:"Book/text assigned to volume at HD address with correlation TX",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"VolumeConstituentRemoved"},{eventType:"VolumeConstituentRemoved",mdmAddress:`${W}/codex/volume-constituent-removed`,category:"content",description:"Book/text removed from volume",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"VolumeConstituentAdded"},{eventType:"EquivalencyDetected",mdmAddress:`${W}/codex/equivalency-detected`,category:"content",description:"Cross-canon equivalency detected between HD addresses (parallel-verse, parallel-chapter, parallel-book, thematic, textual-variant)",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"EquivalencyRevoked"},{eventType:"EquivalencyRevoked",mdmAddress:`${W}/codex/equivalency-revoked`,category:"content",description:"Cross-canon equivalency revoked \u2014 supersedes detection TX",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"EquivalencyDetected"},{eventType:"CodexTranslationSourceAssigned",mdmAddress:`${W}/codex/translation-source-assigned`,category:"content",description:"Translation source attributed to a language sibling address tree (e.g., R.H. Charles 1896 \u2192 ethiopian/english)",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ScopeAssigned",mdmAddress:`${W}/scope/scope-assigned`,category:"scope",description:"Scope owner authorizes agent to operate in HD subtree",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ScopeDeprecated"},{eventType:"ScopeDeprecated",mdmAddress:`${W}/scope/scope-deprecated`,category:"scope",description:"Scope authorization revoked",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ScopeAssigned"},{eventType:"SkillBindingRequested",mdmAddress:`${W}/skill-binding/binding-requested`,category:"skill-binding",description:"User requests skill binding with fee (TX.Amount)",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"SkillBindingGranted",mdmAddress:`${W}/skill-binding/binding-granted`,category:"skill-binding",description:"Skill template confirms binding, returns skillBinderAdminAddress",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"SkillBindingRevoked"},{eventType:"SkillBindingRevoked",mdmAddress:`${W}/skill-binding/binding-revoked`,category:"skill-binding",description:"User or template revokes skill binding",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"SkillBindingGranted"},{eventType:"SkillBindingRejected",mdmAddress:`${W}/skill-binding/binding-rejected`,category:"skill-binding",description:"Template rejects binding (insufficient fee, policy violation)",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"LocalContentSerializationModeAssigned",mdmAddress:`${W}/serialization-local/mode-assigned`,category:"serialization-local",description:"Assigns local serialization mode (RAW/ENCRYPTED) to target skill. payload.codeValueHDAddress carries refdata identity.",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"LocalContentSerializationModeDeprecated"},{eventType:"LocalContentSerializationModeDeprecated",mdmAddress:`${W}/serialization-local/mode-deprecated`,category:"serialization-local",description:"Deprecates local serialization mode assignment. Correlated via orgnlMsgId.",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"LocalContentSerializationModeAssigned"},{eventType:"OnchainContentSerializationModeAssigned",mdmAddress:`${W}/serialization-onchain/mode-assigned`,category:"serialization-onchain",description:"Assigns on-chain serialization mode (RAW/ENCRYPTED) to target skill. payload.codeValueHDAddress carries refdata identity.",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"OnchainContentSerializationModeDeprecated"},{eventType:"OnchainContentSerializationModeDeprecated",mdmAddress:`${W}/serialization-onchain/mode-deprecated`,category:"serialization-onchain",description:"Deprecates on-chain serialization mode assignment. Correlated via orgnlMsgId.",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"OnchainContentSerializationModeAssigned"},{eventType:"ContentPublishTierModeAssigned",mdmAddress:`${W}/publish-tier/mode-assigned`,category:"publish-tier",description:"Assigns publish tier (TIER_1_LCP/TIER_2_OCP) to target skill. Multi-select via independent TXs. payload.codeValueHDAddress carries refdata identity.",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ContentPublishTierModeDeprecated"},{eventType:"ContentPublishTierModeDeprecated",mdmAddress:`${W}/publish-tier/mode-deprecated`,category:"publish-tier",description:"Deprecates publish tier assignment. Correlated via orgnlMsgId.",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ContentPublishTierModeAssigned"},{eventType:"ContentChunkCreated",mdmAddress:`${W}/publish-tier/content-chunk-created`,category:"publish-tier",description:"Chunked memo fragment for content >900 bytes (Tier-2 batching)",emitters:["agent","skill"],hasPairedLifecycle:!1},{eventType:"DecryptionGranted",mdmAddress:`${W}/content-access/decryption-granted`,category:"content-access",description:"Target can decrypt Tier 2 on-chain content (passport-gated)",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"DecryptionRevoked"},{eventType:"DecryptionRevoked",mdmAddress:`${W}/content-access/decryption-revoked`,category:"content-access",description:"Revokes decryption access for target wallet",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"DecryptionGranted"},{eventType:"ContentHydrateGranted",mdmAddress:`${W}/content-access/hydrate-granted`,category:"content-access",description:"Target can hydrate on-chain content into wallet",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ContentHydrateRevoked"},{eventType:"ContentHydrateRevoked",mdmAddress:`${W}/content-access/hydrate-revoked`,category:"content-access",description:"Revokes hydration access for target wallet",emitters:["agent","skill"],hasPairedLifecycle:!0,pairedEventType:"ContentHydrateGranted"},{eventType:"RawContentPublished",mdmAddress:`${W}/publish-execution/raw-content-published`,category:"publish-execution",description:"Cleartext content anchored on-chain at target address",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"EncryptedContentPublished",mdmAddress:`${W}/publish-execution/encrypted-content-published`,category:"publish-execution",description:"Encrypted content anchored on-chain \u2014 carries encryptionTypeHDAddress and encryptionTypeCode",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentPublishSkipped",mdmAddress:`${W}/publish-execution/content-publish-skipped`,category:"publish-execution",description:"Idempotent skip \u2014 content already at target serialization state",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentIntegrityVerified",mdmAddress:`${W}/publish-execution/content-integrity-verified`,category:"publish-execution",description:"Pre-publish SHA-256 hash check passed against last ContentCreated/Amended TX",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentIntegrityFailed",mdmAddress:`${W}/publish-execution/content-integrity-failed`,category:"publish-execution",description:"Pre-publish hash mismatch \u2014 publish aborted, content may have been tampered",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"SerializationSwapStarted",mdmAddress:`${W}/publish-execution/serialization-swap-started`,category:"publish-execution",description:"Hanoi safe-swap initiated at primaryAddress \u2014 original backed up to tmpAddress",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SerializationSwapCompleted"},{eventType:"SerializationSwapCompleted",mdmAddress:`${W}/publish-execution/serialization-swap-completed`,category:"publish-execution",description:"Hanoi safe-swap committed \u2014 tmpAddress cleaned, primaryAddress has transformed content",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SerializationSwapStarted"},{eventType:"SerializationSwapFailed",mdmAddress:`${W}/publish-execution/serialization-swap-failed`,category:"publish-execution",description:"Hanoi safe-swap failed at step N \u2014 recovery needed from last known good TX",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"SerializationRecoveryStarted",mdmAddress:`${W}/publish-execution/serialization-recovery-started`,category:"publish-execution",description:"Recovery process walking from last known good publish TX forward",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SerializationRecoveryCompleted"},{eventType:"SerializationRecoveryCompleted",mdmAddress:`${W}/publish-execution/serialization-recovery-completed`,category:"publish-execution",description:"Recovery finished \u2014 all addresses verified and restored",emitters:["skill"],hasPairedLifecycle:!0,pairedEventType:"SerializationRecoveryStarted"},{eventType:"ContentPublishDenied",mdmAddress:`${W}/publish-execution/content-publish-denied`,category:"publish-execution",description:"Publish blocked by asymmetric direction rule \u2014 e.g. RAW\u2192ENCRYPTED on-chain after cleartext already published is pointless",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"LinkageAuthRequested",mdmAddress:`${W}/linkage-auth/auth-requested`,category:"linkage-auth",description:"Caller requests authorization to add a parent\u2192child constituent linkage in a partition. Awaits Granted or Rejected response correlated by requestId.",emitters:["agent","skill","cid-agent"],hasPairedLifecycle:!1},{eventType:"LinkageAuthRequestGranted",mdmAddress:`${W}/linkage-auth/auth-request-granted`,category:"linkage-auth",description:"Resolver response: linkage authorization granted. Correlated to a LinkageAuthRequested by requestId. Latest-wins vs LinkageAuthRequestRevoked.",emitters:["agent","skill","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"LinkageAuthRequestRevoked"},{eventType:"LinkageAuthRequestRejected",mdmAddress:`${W}/linkage-auth/auth-request-rejected`,category:"linkage-auth",description:"Resolver response: linkage authorization rejected (LOOPBACK | POLICY_DENIED | PARTITION_MISMATCH | UNKNOWN_PARENT | UNKNOWN_CHILD). Terminal for that requestId.",emitters:["agent","skill","cid-agent"],hasPairedLifecycle:!1},{eventType:"LinkageAuthRequestRevoked",mdmAddress:`${W}/linkage-auth/auth-request-revoked`,category:"linkage-auth",description:"Post-grant retraction. Correlated to the original LinkageAuthRequestGranted by requestId. Latest-wins resolver flips effective state to revoked.",emitters:["agent","cid-agent"],hasPairedLifecycle:!0,pairedEventType:"LinkageAuthRequestGranted"},{eventType:"ArtifactGenerated",mdmAddress:`${W}/build-manifest/artifact-generated`,category:"build-manifest",description:"Dev-time generator emitted a file artifact (e.g. cappzMDMConstants_*.ts). Carries generatedFileHash, generatorVersion, scope, runId. Source TX for the build manifest chain.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"BuildConstituentIncluded",mdmAddress:`${W}/build-manifest/build-constituent-included`,category:"build-manifest",description:"AX-91: Records that a generated PascalName constant resolves to an MDM HD address inside a generated artifact. CPM consumes these at the scope HD address to materialize the constant set in the next bundle.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentCompressed",mdmAddress:`${W}/build-manifest/content-compressed`,category:"build-manifest",description:"v14-16-02: Same content version stored gzip-compressed at the same address. Carries rawHash (notarized identity), compressedHash (check before unzip), codec, sizes. Not a new version.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentPurged",mdmAddress:`${W}/build-manifest/content-purged`,category:"build-manifest",description:"v14-16-03: Intra-wallet accounting from the AgentAdmin address to the original address after a verified ContentArchived + ContentCompressed; the original becomes a placeholder that never replicates.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ReplicantCreated",mdmAddress:`${W}/build-manifest/replicant-created`,category:"build-manifest",description:"v14-16-04: Generic Replicator event. A wallet gains a replica copy; from the source wallet to the replica address.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ArchiveCreated",mdmAddress:`${W}/build-manifest/archive-created`,category:"build-manifest",description:"v14-16-04: Subclass of ReplicantCreated (parent: ReplicantCreated). The replica is a one-way offline archive mirror; same correlationId as its ReplicantCreated.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentArchived",mdmAddress:`${W}/build-manifest/content-archived`,category:"build-manifest",description:"v14-16-03: Archive = replication. From the source address to the archive (replicated) address, issued from the verified one-way a2a-sync delivery receipt.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"GrantRequested",mdmAddress:`${W}/build-manifest/grant-requested`,category:"build-manifest",description:"v14-16-03: An app administrator requests AmendGranted/ReadGranted; the trusted admin-group signer replies correlated.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"GrantRejected",mdmAddress:`${W}/build-manifest/grant-rejected`,category:"build-manifest",description:"v14-16-03: Signer decision refusing a GrantRequested, with reason.",emitters:["skill"],hasPairedLifecycle:!1},{eventType:"ContentExported",mdmAddress:`${W}/build-manifest/content-exported`,category:"build-manifest",description:"v14-16-03: Fact \u2014 exporter downloaded a cascading wallet export; carries the manifest hash.",emitters:["skill"],hasPairedLifecycle:!1}],cN=(()=>{let e=new Set(aN.map(r=>r.eventType)),t=new Set;return[...[...Lle,...Fle].filter(r=>e.has(r.eventType)||t.has(r.eventType)?!1:(t.add(r.eventType),!0)),...aN]})(),$le=(()=>{let e=new Map(cN.map(t=>[t.eventType,t]));return E4.filter(t=>!e.has(t)).flatMap(t=>{let n=xf[t],r=e.get(n);if(!r)return[];let i=Ule[t]??r.category;return[{eventType:t,mdmAddress:`${W}/${i}/${sN(t)}`,category:i,description:`Deprecated \u2014 replaced by ${n} (v12-20-06). Replayed, never written.`,emitters:r.emitters,hasPairedLifecycle:!1,deprecatedBy:n}]})})(),qle=[...cN,...$le],lN=new Map;for(let e of qle)lN.set(e.eventType,e);function uN(e){return lN.get(e)}Qb();function O4(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(O4).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${O4(e[t])}`).join(",")}}`}function Hle(e){return e.replace(/Tx$/,"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Vle(e){let t=uN(e);return t?{eventMdmAddress:t.mdmAddress,eventRegistrationTxId:`${t.category}:event-type:registered:${zR(e)}`,custodyStatus:"declared"}:{eventMdmAddress:`${M4}/undeclared/${Hle(e)}`,eventRegistrationTxId:`undeclared:event-type:${e}`,custodyStatus:"undeclared"}}var dN=new Map;function Kle(e,t,n){let r=dN.get(e)??{count:0,domains:new Set,samples:[]};r.count+=1,r.domains.add(n),r.samples.length<5&&r.samples.push(t),dN.set(e,r)}async function fN(e){if(KR(e.eventType))throw new Error(`Event type is deprecated: ${e.eventType} \u2014 write ${Zb(e.eventType)} instead`);let t=Vle(e.eventType);if(t.custodyStatus==="undeclared"){if(e.enforcement==="refuse")throw new Error(`Event type is not MDM-registered: ${e.eventType}`);Kle(e.eventType,e.txId,e.emitterDomain)}let n={txId:e.txId,timestamp:e.timestamp??new Date().toISOString(),eventType:e.eventType,sourceAddress:e.sourceAddress,targetAddress:e.targetAddress,eventMdmAddress:t.eventMdmAddress,eventRegistrationTxId:t.eventRegistrationTxId,custodyStatus:t.custodyStatus,payload:{...e.payload??{},governingPrinciple:e.governingPrinciple}};return{...n,txHash:await la(O4(n))}}function pN(e){let t=new jl(e.eventLog,e.cachePrefix,{shared:e.shared}),n=async i=>{let o=i.txId??`${i.eventType}-${(await la(`${i.targetAddress}|${JSON.stringify(i.payload)}|${crypto.randomUUID()}`)).slice(0,32)}`;return{...await fN({txId:o,eventType:i.eventType,sourceAddress:i.sourceAddress,targetAddress:i.targetAddress,payload:i.payload,governingPrinciple:e.governingPrinciple,emitterDomain:e.emitterDomain,enforcement:"refuse"}),eventType:i.eventType}},r=async i=>{let o=new Set(t.getCached().map(s=>s.txId)),a=i.filter(s=>!o.has(s.txId));return a.length&&await t.appendMany(a,{requireDurable:!0,share:e.shared}),t.getCached()};return{create:n,append:r,emit:async i=>{let o=await n(i);return await r([o]),o},refresh:()=>t.refresh(),get:()=>t.getCached(),subscribe:i=>t.subscribe(i),shareExisting:()=>t.shareExisting(()=>!0)}}y();pf();var yN="marketplace",zle=qO(yN),gn=yb(yN),oC=`${gn}/event-log`,U3e=`${zle}/agent`,$3e=`${gn}/agent`,hN="m/44'/144'/100'/principles/cope/v1#marketplace";var ve=e=>`${gn}/parties/${e}`,Df=e=>`${gn}/listings/${e}`,D4=e=>`${gn}/requests/${e}`,mN=(e,t)=>`${D4(e)}/offers/${t}`,Xl=e=>`${gn}/contracts/${e}`,tm=e=>`${Xl(e)}/agreement`,Gn=e=>`${Xl(e)}/escrow`,aC=(e,t)=>`${Xl(e)}/milestones/${t}`,Rf=(e,t)=>`${Xl(e)}/deliveries/${t}`,gN=(e,t)=>`${Xl(e)}/disputes/${t}`,wN=(e,t)=>`${Xl(e)}/reviews/${t}`,sC=(e,t)=>`${Xl(e)}/subcontracts/${t}`,R4=e=>`${gn}/tokens/${e}`,N4=e=>`${gn}/operators/${e}`,L4=e=>e.startsWith(`${gn}/operators/`),B4=(e,t)=>`${ve(e)}/mandates/${t}`;var cC=(e,t)=>`${ve(e)}/payee-instructions/${t}`;var ua=pN({eventLog:oC,cachePrefix:"cappz:marketplace:events/",emitterDomain:"marketplace",governingPrinciple:hN});y();y();var Wl=e=>new Date(Date.parse(e)+2592e6).toISOString();function CN(e,t){let n=t.map(r=>Math.floor(e*r));return n[n.length-1]+=e-n.reduce((r,i)=>r+i,0),n}var nm=1,rm=3,vN=e=>rm+(e===0?nm:0),jle={USD:100,XRP:1e6,CAPPZ:1e6,"USD-tokenZ/1":1e6},bN=(e,t)=>Math.round(e*jle[t]);function AN(e,t,n,r,i){let o={percent:0,flat:0,perRecord:0,unpriced:[]};if(!e)return o;if(e.percent.enabled&&(o.percent=Math.round(t*e.percent.bps/1e4)),e.flat.enabled&&i){let a=e.flat.amounts[n];a&&a>0?o.flat=bN(a,n):o.unpriced.push(`flat fee (no ${n} price)`)}if(e.perRecord.enabled&&r>0){let a=e.perRecord.amounts[n];a&&a>0?o.perRecord=r*bN(a,n):o.unpriced.push(`per-record fee (no ${n} price)`)}return o}y();Bo();y();qo();y();Rl();var lC={mainnet:["https://s1.ripple.com:51234/","https://s2.ripple.com:51234/","https://xrplcluster.com/"],testnet:["https://s.altnet.rippletest.net:51234/","https://testnet.xrpl-labs.com/"],devnet:["https://s.devnet.rippletest.net:51234/"]},Y3e={mainnet:lC.mainnet[0],testnet:lC.testnet[0],devnet:lC.devnet[0]},SN=/rate limit|slowDown|tooBusy|noNetwork|noCurrent|noClosed|amendmentBlocked|failedToForward/i,Cc=class extends Error{constructor(n,r){super(n);this.code=r}code};async function uC(e,t,n,r=fetch){let i=null;for(let o of lC[e])try{let a=await r(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({method:t,params:[{api_version:2,...n}]})});if(!a.ok){i=new Cc(`XRPL ${e} (${new URL(o).host}) answered HTTP ${a.status}`,null);continue}let c=(await a.json()).result??{};if(c.error){let l=new Cc(`XRPL ${t}: ${c.error_message??c.error}`,c.error);if(SN.test(`${c.error} ${c.error_message??""}`)){i=l;continue}throw l}return c}catch(a){if(a instanceof Cc&&a.code&&!SN.test(`${a.code} ${a.message}`))throw a;i=a}throw i??new Cc(`XRPL ${e}: no server answered`,null)}async function TN(e,t,n=fetch){let r=await uC(e,"tx",{transaction:t,binary:!1},n);return Dl(r,e,new Date().toISOString())}y();y();var _N=jr(Nr(),1);pf();y();var Xle=jr(Nr(),1),Wle={testnet:{issuer:"rUGJER9ryngy6i12ZW57zjRiBZQ9Cx8ecD",treasury:"rnQ3gydd9kTdx6gHKzhNHSKHSq6whzdiMe",service:"rsCYgPfATXotqcnpbUwugafvUCwoYy1hf3",wsEndpoint:"wss://s.altnet.rippletest.net:51233",rpcEndpoint:"https://s.altnet.rippletest.net:51234"},devnet:{issuer:"rsPqd13cpLfatVSw79eAbAJdDoAnLwXbfc",treasury:"rUJ8RQzFRjt3BHnC8aikidJDdxeBeqLofx",service:"rBQSSpamtnHvVRJHkBQ2hMvLUENs5zESjX",wsEndpoint:"wss://s.devnet.rippletest.net:51233",rpcEndpoint:"https://s.devnet.rippletest.net:51234"},mainnet:{issuer:"rMBcKBgMZFmVrSsJXubMUb2MpSxSLa6fTA",treasury:"rUqPbiwe2Z5rj2AewokbFHCGQPtwjtzjHM",service:"rNuKZnMUdb9FtJ1hGQYyXUmJ6Bk7RPbz4c",wsEndpoint:"wss://xrplcluster.com",rpcEndpoint:"https://xrplcluster.com"}};var Gle={};function Yle(e){let t=Wle[e];if(!t)throw new Error(`Unknown CAPPZ network: ${e}`);return t}function Zle(e){let t=Yle(e);if(e==="mainnet")return t;let n=Gle[e];return n?{...t,issuer:n.issuer?.address??t.issuer,treasury:n.treasury?.address??t.treasury,service:n.service?.address??t.service}:t}function EN(e){return Zle(e).issuer}var kN="524C555344000000000000000000000000000000",Jle="434150505A000000000000000000000000000000",Qle=e=>{let t="";try{t=EN(e)}catch{return null}return{currencyHex:Jle,issuer:t}},F4=[{id:"ledger-escrow",mdmAddress:ff("ledger-escrow"),label:"Ledger escrow",confirmedBy:"ledger",holdLimitDays:30,adapter:null,aliases:["xrpl-escrow","xrpl-testnet"],description:"One escrow per stage leg under one crypto-condition; the buyer reveals the secret to release, the ledger returns an unreleased stage after CancelAfter (\u2264 30 days)."},{id:"ledger-staged",mdmAddress:ff("ledger-staged"),label:"Ledger, stage by stage",confirmedBy:"ledger",holdLimitDays:null,adapter:null,aliases:["xrpl-payment"],description:"Each stage is paid directly on the ledger when the buyer accepts it (seller net + fee legs), each Payment checked by delivered amount, currency and issuer. Nothing is held; neither side is more than one stage exposed."},{id:"ledger-channel",mdmAddress:ff("ledger-channel"),label:"Ledger payment channel",confirmedBy:"ledger",holdLimitDays:30,adapter:null,aliases:["paychan"],description:"Metered use: the buyer opens a channel capped by the mandate, signs claims as work is used, the seller redeems; the channel expires within one billing cycle."},{id:"card",mdmAddress:ff("card"),label:"Card or bank",confirmedBy:"processor",holdLimitDays:30,adapter:{function:"marketplace-payments",provider:"stripe"},aliases:["stripe-card","stripe-ach","stripe"],description:"USD charged by the payment processor, held up to 30 days and transferred on release; processor-confirmed entries only."},{id:"by-reference",mdmAddress:ff("by-reference"),label:"Recorded by reference",confirmedBy:"nobody",holdLimitDays:30,adapter:null,aliases:["usd-reference","demo"],description:"A payment made elsewhere and recorded by its reference: shown as recorded, never as validated."}],Nf=[{id:"xrp",mdmAddress:Nl("xrp"),code:"XRP",label:"XRP",kind:"native",family:null,minor:1e6,decimals:6,rails:["ledger-escrow","ledger-channel"],aliases:["xrp"],description:"The ledger's native asset, escrowed per stage."},{id:"cappz-token",mdmAddress:Nl("cappz-token"),code:"CAPPZ",label:"CAPPZ",kind:"issued",family:null,minor:1e6,decimals:6,issued:Qle,rails:["ledger-staged"],aliases:["cappz"],description:"The CAPPZ token, paid stage by stage on the ledger (needs a trust line to the issuer)."},{id:"usd-tokenz/1",mdmAddress:Nl("usd-tokenz/1"),code:"USD-tokenZ/1",label:"RLUSD",kind:"issued",family:Nl("usd-tokenz"),minor:1e6,decimals:2,issued:e=>({mainnet:{currencyHex:kN,issuer:"rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De"},testnet:{currencyHex:kN,issuer:"rQhWct2fv4Vc4KRjRgMrxa8xPN9Zx9iLKV"},devnet:null})[e],rails:["ledger-staged"],aliases:["usd-tokenz-1","rlusd"],description:"USD-tokenZ member 1: a US-dollar stablecoin issued on the ledger, paid stage by stage (needs a trust line to the issuer). Its issuer does not allow trust-line locking today, so it cannot be escrowed."},{id:"usd",mdmAddress:Nl("usd"),code:"USD",label:"US dollars",kind:"fiat",family:null,minor:100,decimals:2,rails:["card","by-reference"],aliases:["usd-card"],description:"US dollars by card or bank through the payment processor, or recorded by reference."}],rSe=Nl("usd-tokenz"),IN=new Map;for(let e of Nf)for(let t of[e.code,e.id,e.mdmAddress,...e.aliases])IN.set(t.toLowerCase(),e);var eue=new Map;for(let e of F4)for(let t of[e.id,e.mdmAddress,...e.aliases])eue.set(t.toLowerCase(),e);function im(e){return e?IN.get(String(e).toLowerCase())??null:null}function Cn(e){let t=im(e);if(!t)throw new Error(`Unknown payment asset ${e}.`);return t}var dC=e=>im(e)?.code??null,Et=e=>im(e)?.label??String(e),U4=e=>Cn(e).kind!=="fiat";var fC=e=>Cn(e).rails[0];function da(e,t){let n=Cn(e);if(n.kind!=="issued")return{state:"available",token:null};let r=n.issued?.(t)??null;return r?(0,_N.isValidClassicAddress)(r.issuer)?{state:"available",token:r}:{state:"invalid-config",reason:`The configured ${n.label} issuer on ${t} (${r.issuer}) fails checksum validation, so ${n.label} is not offered there.`}:{state:"not-issued",reason:`${n.label} is not issued on ${t}.`}}function pC(e,t){let n=da(e,t);if(n.state!=="available"||!n.token)throw new Error(n.state==="available"?`${Et(e)} is not an issued token.`:n.reason);return n.token}var PN=e=>Nf.filter(t=>da(t.code,e).state==="available"),xN=(e,t)=>Math.round(e*Cn(t).minor),om=(e,t)=>e/Cn(t).minor,MN=(e,t)=>{let n=BigInt(Cn(t).minor),r=BigInt(e),i=r/n,o=(r%n).toString().padStart(String(n).length-1,"0").replace(/0+$/,"");return o?`${i}.${o}`:`${i}`},ON=(e,t)=>{let n=/^(\d+)(?:\.(\d+))?$/.exec(e.trim());if(!n)return null;let r=String(Cn(t).minor).length-1,i=(n[2]??"").padEnd(r,"0");return i.length>r&&/[1-9]/.test(i.slice(r))?null:BigInt(n[1])*BigInt(Cn(t).minor)+BigInt(i.slice(0,r)||"0")};function $n(e,t){let n=Cn(t);return t==="USD"?`$${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:`${e.toLocaleString("en-US",{maximumFractionDigits:n.decimals})} ${n.label}`}function DN(e,t){let n=pC(e,t);return{code:Et(e),hex:n.currencyHex,issuer:n.issuer}}var tue=1,yC=.2,RN=.001;function $4(e,t){return Math.ceil(Number(((e+t*yC+RN)*1e6).toFixed(3)))/1e6}var nue="https://xrpl.org/resources/dev-tools/xrp-faucets";function So(e){let{network:t,currency:n,amount:r}=e,i=Cn(n),o=(e.ledgerObjects??0)+(i.kind==="issued"&&!e.hasTrustLine?1:0),a=Math.round(((e.accountExists?0:tue)+o*yC+RN)*1e6)/1e6,s=[],c=null;if(i.kind==="fiat")return s.push(`${i.label} are paid by card or bank through the marketplace payment page, or recorded by reference; no ledger wallet is needed for the payment itself.`),{network:t,currency:n,amount:r,xrpForReserves:0,trustLine:c,steps:s};let l=i.kind==="native"?Math.round((r+a)*1e6)/1e6:a;if(t==="mainnet"?s.push(`Buy at least ${l} XRP on an exchange that supports XRP Ledger withdrawals, and withdraw it to your own wallet address (no destination tag is needed when sending to your own wallet).`):s.push(`On ${t} there is no real money: fund the account from the ${t} faucet (${nue}) \u2014 it sends enough XRP for testing.`),i.kind==="issued"){let u=da(n,t);if(u.state!=="available"||!u.token)return{network:t,currency:n,amount:r,xrpForReserves:a,trustLine:null,steps:[u.state==="available"?`${i.label} is not an issued token.`:u.reason]};c=u.token,e.hasTrustLine||s.push(`Set a trust line to the ${i.label} issuer ${u.token.issuer} (currency ${u.token.currencyHex}) from your wallet; it locks ${yC} XRP of reserve while it exists.`),s.push(t==="mainnet"?`Get ${r} ${i.label} into the account: withdraw it from an exchange that offers ${i.label} withdrawals on the XRP Ledger (choose the XRP Ledger network, not another chain), or receive it from another wallet.`:`Get ${r} test ${i.label} from someone who holds it on ${t}, or from the issuer's test distribution if one is offered.`)}return{network:t,currency:n,amount:r,xrpForReserves:a,trustLine:c,steps:s}}function am(e){return`${e.network}: ${e.amount} ${Et(e.currency)}${e.xrpForReserves?` plus ${e.xrpForReserves} XRP for reserves and fees`:""}. ${e.steps.join(" ")}`}var rue=131072;function NN(e,t,n,r="1000000000"){let i=Cn(t);if(i.kind!=="issued")throw new Error(`${i.label} needs no trust line.`);let o=da(t,n);if(o.state!=="available"||!o.token)throw new Error(o.state==="available"?`${i.label} has no issuer on ${n}.`:o.reason);return{TransactionType:"TrustSet",Account:e,Flags:rue,LimitAmount:{currency:o.token.currencyHex,issuer:o.token.issuer,value:r}}}async function BN(e,t,n,r,i=fetch){try{let a=((await uC(e,"account_lines",{account:t,peer:n,ledger_index:"validated"},i)).lines??[]).find(s=>s.currency.toUpperCase()===r.toUpperCase());return a?{present:!0,balance:a.balance,limit:a.limit,frozen:!!(a.freeze||a.freeze_peer),authorized:a.peer_authorized??a.authorized??null,error:null}:{present:!1,balance:null,limit:null,frozen:null,authorized:null,error:null}}catch(o){return o instanceof Cc&&o.code==="actNotFound"?{present:!1,balance:null,limit:null,frozen:null,authorized:null,error:null}:{present:null,balance:null,limit:null,frozen:null,authorized:null,error:o.message}}}function Br(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Br).join(",")}]`:`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Br(e[t])}`).join(",")}}`}var LN=e=>new Uint8Array((e.match(/../g)??[]).map(t=>parseInt(t,16)));function FN(e,t){if(t&&e.signature.publicKey.toLowerCase()!==t.toLowerCase())return!1;try{return Kn.verify(LN(e.signature.value),new TextEncoder().encode(Br(e.report)),LN(e.signature.publicKey))}catch{return!1}}var UN=["application/pdf","image/png","image/jpeg","application/zip","application/json","text/plain","text/markdown","text/csv"],iue=["media-type","size","json","words","sections","contains","excludes"],$N=20,qN=500;function Bf(e){let t=[],n=e;if(!n||typeof n!="object")return['Acceptance criteria must be an object: {"version": 1, "criteria": [\u2026]}.'];if(n.version!==1&&t.push('Acceptance criteria need "version": 1.'),!Array.isArray(n.criteria)||!n.criteria.length)return[...t,'List at least one criterion in "criteria".'];n.criteria.length>$N&&t.push(`At most ${$N} criteria.`);let r=new Set,i=s=>typeof s=="string"&&s.trim().length>0&&s.length<=qN,o=s=>Array.isArray(s)&&s.length>0&&s.length<=20&&s.every(i),a=s=>s===void 0||typeof s=="number"&&Number.isInteger(s)&&s>=0;return n.criteria.forEach((s,c)=>{let l=`Criterion ${c+1}`;if(!s||typeof s!="object"){t.push(`${l} is not an object.`);return}switch(!i(s.id)||!/^[a-z0-9][a-z0-9-]{0,39}$/.test(s.id)?t.push(`${l}: "id" is lowercase letters, digits and dashes (up to 40).`):r.has(s.id)?t.push(`${l}: id "${s.id}" is used twice.`):r.add(s.id),s.kind){case"media-type":(!Array.isArray(s.anyOf)||!s.anyOf.length||!s.anyOf.every(u=>UN.includes(u)))&&t.push(`${l}: "anyOf" lists media types from ${UN.join(", ")}.`);break;case"size":(!a(s.minBytes)||!a(s.maxBytes)||s.minBytes===void 0&&s.maxBytes===void 0||(s.minBytes??0)>(s.maxBytes??1/0))&&t.push(`${l}: give "minBytes" and/or "maxBytes" (whole numbers, min \u2264 max).`);break;case"json":s.requiredKeys!==void 0&&!o(s.requiredKeys)&&t.push(`${l}: "requiredKeys" lists key paths such as "summary" or "items.0.id".`);break;case"words":(!a(s.min)||!a(s.max)||s.min===void 0&&s.max===void 0||(s.min??0)>(s.max??1/0))&&t.push(`${l}: give "min" and/or "max" words (whole numbers, min \u2264 max).`);break;case"sections":o(s.headings)||t.push(`${l}: "headings" lists the section headings the deliverable must have.`);break;case"contains":case"excludes":o(s.text)||t.push(`${l}: "text" lists the phrases to look for.`);break;case"rubric":i(s.question)||t.push(`${l}: "question" is one yes/no question about the deliverable (up to ${qN} characters).`);break;default:t.push(`${l}: unknown kind "${s.kind}". Kinds: ${[...iue,"rubric"].join(", ")}.`)}}),t}var oue=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),sm=e=>oue(_t(new TextEncoder().encode(Br(e))));var To=class extends Error{},jt=e=>{throw new To(e)},lm=e=>{if(e===void 0)return;let t=Bf(e);t.length&&jt(`Acceptance criteria rejected: ${t.join(" ")}`)},q4=e=>Number.isFinite(Date.parse(e)),Gl=(e,t)=>Math.round((Date.parse(t)-Date.parse(e))/864e5),cm=(e,t)=>new Date(Date.parse(e)+t*864e5).toISOString().slice(0,10);function HN(e,t){gr(e.categoryId)||jt(`Unknown category "${e.categoryId}".`),e.title.trim()||jt("Say what you need."),e.quantity>0||jt("Quantity must be more than zero."),e.unit||jt("Choose a unit."),q4(e.neededBy)||jt("Choose the date you need it by."),Gl(t,e.neededBy)<0&&jt("The needed-by date is in the past."),e.maxPricePerUnit&&!(e.maxPricePerUnit.amount>0)&&jt("A price limit must be more than zero, or leave it open.")}function VN(e,t,n){let r=[];if(e.requestId!==t.requestId&&jt("Offer is for a different request."),e.quantity>0||jt("Offer quantity must be more than zero."),e.pricePerUnit.amount>0||jt("Price must be more than zero."),q4(e.deliveryDate)||jt("Choose a delivery date."),e.plan.newPlanting&&!t.allowNewPlanting&&jt("This buyer did not ask for new plantings."),e.milestones.forEach(i=>lm(i.acceptance)),t.acceptance){let i=e.milestones.find(o=>o.delivery);(!i?.acceptance||sm(i.acceptance)!==sm(t.acceptance))&&r.push("The request states acceptance criteria; this bid\u2019s delivery milestone does not carry the same criteria, so an evaluator would have none agreed to check.")}if(t.maxPricePerUnit&&e.pricePerUnit.currency===t.maxPricePerUnit.currency&&e.pricePerUnit.amount>t.maxPricePerUnit.amount&&r.push(`Price is above the buyer's limit (${t.maxPricePerUnit.amount} ${t.maxPricePerUnit.currency}/${t.unit}).`),e.quantity{n.index!==r&&jt(`Milestone ${r} is out of order.`),n.share>0||jt(`Milestone ${r+1} needs a share above zero.`)});let t=e.reduce((n,r)=>n+r.share,0);Math.abs(t-1)>1e-6&&jt(`Milestone shares add up to ${Math.round(t*100)}%, not 100%.`),e[e.length-1].delivery||jt("The last milestone must be the delivery.")}function Ff(e,t){let n=[],r=t.slice(0,10);for(let i of e){let o=Math.max(0,Gl(r,i.dueBy)),a=Math.max(1,Math.ceil(o/29));for(let s=1;s<=a;s++){let c=s===a;n.push({index:n.length,label:a>1?`${i.label} \u2014 stage ${s} of ${a}`:i.label,share:c?i.share-i.share/a*(a-1):i.share/a,dueBy:c?i.dueBy:cm(r,Math.round(o*s/a)),evidence:c?i.evidence:`Progress toward \u201C${i.label}\u201D: photos, receipts or a short report`,delivery:c&&i.delivery,...i.servesMilestone!==void 0?{servesMilestone:i.servesMilestone}:{},...c&&i.acceptance?{acceptance:i.acceptance}:{}})}r=i.dueBy}return n}function KN(e,t){let n=t.slice(0,10);for(let r of e){let i=Gl(n,r.dueBy);i>29&&jt(`\u201C${r.label}\u201D spans ${i} days. Holds are limited to a 30-day billing cycle \u2014 break it into stages of under 30 days.`),n=r.dueBy>n?r.dueBy:n}}function H4(e,t){e.some((r,i)=>!(r.dueInDays>=0)||i>0&&r.dueInDays!r.label.trim())&&jt("Give every milestone a name."),e.forEach(r=>lm(r.acceptance));let n=e.map((r,i)=>({index:i,label:r.label.trim(),share:r.share,dueBy:cm(t,r.dueInDays),evidence:r.evidence,delivery:r.delivery,...r.acceptance?{acceptance:r.acceptance}:{}}));return um(n),n.slice(0,-1).some(r=>r.delivery)&&jt("Only the last milestone is the delivery."),Ff(n,t)}function hC(e){let t=Math.max(0,Math.round(e));return{"on-delivery":{title:"Pay on delivery",plan:[{label:"Delivered and accepted",share:1,dueInDays:t,evidence:"Delivery receipt, buyer inspection",delivery:!0}]},deposit:{title:"Deposit + delivery",plan:[{label:"Deposit \u2014 work started",share:.3,dueInDays:0,evidence:"Order accepted and work started",delivery:!1},{label:"Delivered and accepted",share:.7,dueInDays:t,evidence:"Delivered result, buyer acceptance",delivery:!0}]},"deposit-milestone":{title:"Deposit, milestone, delivery",plan:[{label:"Deposit \u2014 work started",share:.2,dueInDays:0,evidence:"Order accepted and work started",delivery:!1},{label:"Milestone \u2014 first draft",share:.3,dueInDays:Math.max(0,Math.round(t/2)),evidence:"First draft or progress the buyer can check",delivery:!1},{label:"Delivered and accepted",share:.5,dueInDays:t,evidence:"Delivered result, buyer acceptance",delivery:!0}]}}}function $f(e,t,n,r){if(e==="spot")return Ff([{index:0,label:"Delivered and accepted",share:1,dueBy:n,evidence:"Delivery receipt, buyer inspection",delivery:!0}],t);let i=r??cm(t,14),o=cm(i,Math.max(14,Math.round(Gl(i,n)/2)));return Ff([{index:0,label:"Commitment (inputs and planting stock)",share:.1,dueBy:cm(t,7),evidence:"Signed plan; seed or plug purchase receipt",delivery:!1},{index:1,label:"Planting verified",share:.2,dueBy:i,evidence:"Geo-tagged photos of the planted area",delivery:!1},{index:2,label:"Mid-season check",share:.2,dueBy:o,evidence:"Crop photos or a third-party scout report",delivery:!1},{index:3,label:"Harvest delivered and accepted",share:.5,dueBy:n,evidence:"Delivery receipt, quality inspection",delivery:!0}],t)}function zN(e){let t=[];return e.redeemableForSpecificAsset||t.push("It is not redeemable for a specific physical asset, right or service."),e.profitFromOthersEfforts&&t.push("Holders expect profit from the efforts of others \u2014 that is the hallmark of an investment contract."),e.fractionalEnterpriseOwnership&&t.push("It is a share of a business, not a receipt for an asset."),{...e,result:t.length?"blocked":"receipt",reasons:t.length?[...t,"This is a security: issue it through the Securities path (an exempt offering approved by compliance, verified investors, transfer controls), not as a receipt token."]:["Receipt token: redeemable for a specific asset; no profit sharing; no enterprise ownership."]}}function V4(e,t,n,r,i,o,a){let s=e.filter(c=>c.agentPartyId===t&&Date.parse(c.limits.expiresAt)>Date.parse(o));if(!s.length)return{ok:!1,reason:"No active mandate for this agent.",needsApproval:!1};for(let c of s){let l=c.limits;if(l.verbs.includes(n)&&!(i&&l.categories.length&&!l.categories.some(u=>i===u||i.startsWith(`${u}/`)))){if(r){if(r.currency!==l.maxPerContract.currency)continue;if(r.amount>l.maxPerContract.amount)return{ok:!1,reason:`Above the per-contract limit of ${l.maxPerContract.amount} ${l.maxPerContract.currency}.`,needsApproval:!1};if(a+r.amount>l.maxPerDay.amount)return{ok:!1,reason:`Would exceed the daily limit of ${l.maxPerDay.amount} ${l.maxPerDay.currency}.`,needsApproval:!1};if(l.approvalAbove&&r.amount>l.approvalAbove.amount)return{ok:!0,reason:`Allowed with co-signature from ${c.grantedBy} (above ${l.approvalAbove.amount} ${l.approvalAbove.currency}).`,needsApproval:!0}}return{ok:!0,reason:`Within mandate ${c.mandateId}.`,needsApproval:!1}}}return{ok:!1,reason:`No mandate allows ${n}${i?` in ${i}`:""}.`,needsApproval:!1}}var Lf=(e,t,n)=>`${e}|${t.slice(0,10)}${n?`|${n}`:""}`,qf=(e,t)=>({amount:Math.round(e.amount*t*100)/100,currency:e.currency});function ar(e,t){return CN(Math.round(e*100),t.map(n=>n.share)).map(n=>n/100)}function vc(e,t,n){if(t.source.kind!=="subcontract")return null;if(!t.parentContractId)return"This subcontract has no replayed link to a parent contract (ConstituentIncluded), so none of its stages can be funded.";let r=e.find(a=>a.contractId===t.parentContractId);if(!r)return`The parent contract ${t.parentContractId} is not on this market.`;let i=t.milestones[n]?.servesMilestone;if(i===void 0)return`Stage ${n+1} of this subcontract names no parent milestone it serves.`;let o=r.milestoneStates[i];return o?o.state!=="released"?`Stage \u201C${t.milestones[n].label}\u201D is funded after the parent milestone \u201C${r.milestones[i].label}\u201D is released (it is ${o.state}): the main contractor pays from what the parent releases.`:null:`The parent contract has no milestone ${i}.`}y();y();var aue="cappz-marketplace-monetary",sue="cappz-marketplace-commodity";function K4(e){return Array.from(new TextEncoder().encode(e),t=>t.toString(16).padStart(2,"0")).join("").toUpperCase()}function cue(e){let t=[];if(!e||typeof e!="object")return{ok:!1,errors:["memo missing or not an object"]};let n=e;return n.class!=="monetary"&&n.class!=="commodity"&&t.push(`memo.class must be "monetary" or "commodity" (got: ${String(n.class)})`),(typeof n.contractId!="string"||!n.contractId)&&t.push("memo.contractId required (string)"),(typeof n.deliveryIndex!="number"||n.deliveryIndex<0)&&t.push("memo.deliveryIndex required (non-negative number)"),n.class==="commodity"?((typeof n.qty!="number"||n.qty<=0)&&t.push("commodity memo.qty required (positive number)"),(typeof n.unit!="string"||!n.unit)&&t.push("commodity memo.unit required (non-empty string)"),(typeof n.skuHdAddress!="string"||!n.skuHdAddress)&&t.push("commodity memo.skuHdAddress required (non-empty string)")):n.class==="monetary"&&("qty"in n||"unit"in n||"skuHdAddress"in n)&&t.push("monetary memo must not contain qty/unit/skuHdAddress (use a paired commodity TX)"),{ok:t.length===0,errors:t}}function Yl(e){let t=cue(e);if(!t.ok)throw new Error(`Invalid marketplace memo: ${t.errors.join("; ")}`);let n=e.class==="monetary"?aue:sue;return{Memo:{MemoType:K4(n),MemoData:K4(JSON.stringify(e)),MemoFormat:K4("application/json")}}}var lue=e=>Array.from(new TextEncoder().encode(e),t=>t.toString(16).padStart(2,"0")).join("").toUpperCase(),uue=56;function jN(e,t){let n=JSON.stringify({t:e.name,k:e.assetKind,r:`${e.redeemsFor.quantity} ${e.redeemsFor.unit}`,c:e.categoryId,id:e.tokenId});return{TransactionType:"MPTokenIssuanceCreate",Account:t,AssetScale:0,MaximumAmount:String(e.supply),Flags:uue,MPTokenMetadata:lue(n)}}y();y();var JN=jr(Nr(),1);y();var WN=jr(Nr(),1);y();function XN(e){let t=[];e.length===0&&t.push("At least one split rule is required");let n=e.filter(o=>o.splitType==="percentage").reduce((o,a)=>o+a.value,0);n>1+1e-9&&t.push(`Percentage splits sum to ${(n*100).toFixed(2)}% \u2014 exceeds 100%`);for(let o of e)o.value<=0&&t.push(`Split value must be positive: ${o.targetAddress} has ${o.value}`),o.splitType==="percentage"&&o.value>1&&t.push(`Percentage split cannot exceed 100%: ${o.targetAddress} has ${(o.value*100).toFixed(2)}%`),o.targetAddress||t.push("Split rule must have a target address");let r=e.map(o=>o.targetAddress);return new Set(r).size!==r.length&&t.push("Duplicate target addresses in split rules"),t}var Zl=1e4;function z4(e){let t=XN(e.map(r=>({targetAddress:r.account,splitType:"percentage",value:r.bps/Zl,label:r.label})));for(let r of e)Number.isInteger(r.bps)||t.push(`${r.label||r.account}: a share is a whole number of basis points.`),r.account&&!(0,WN.isValidClassicAddress)(r.account)&&t.push(`${r.label||r.account}: ${r.account} is not a valid XRPL classic address (checksum).`),r.label.trim()||t.push(`${r.account}: give the recipient a label.`);let n=e.reduce((r,i)=>r+i.bps,0);return e.length&&n!==Zl&&t.push(`Shares add up to ${(n/100).toFixed(2)}%; the whole fee must be routed (100%).`),t}function mC(e,t){if(!Number.isInteger(e)||e<0)throw new Error("Route whole smallest units (drops or cents).");let n=z4(t);if(n.length)throw new Error(`Royalty recipients invalid: ${n.join("; ")}`);let r=t.map(a=>({account:a.account,label:a.label,bps:a.bps,units:Math.floor(e*a.bps/Zl)})),i=e-r.reduce((a,s)=>a+s.units,0),o=r.reduce((a,s,c)=>s.bps>r[a].bps?c:a,0);return r[o].units+=i,r}y();function GN(e,t,n){let r=Cn(t);if(r.kind==="fiat")throw new Error(`${r.label} does not settle on the ledger.`);if(r.kind==="native")return String(e);let i=pC(t,n);return{currency:i.currencyHex,issuer:i.issuer,value:MN(e,t)}}function gC(e,t,n,r,i,o,a){return{TransactionType:"Payment",Account:e,Destination:t,Amount:GN(n,r,i),Memos:[Yl({class:"monetary",contractId:o,deliveryIndex:a,currency:r})]}}function due(e,t){let n=Cn(t);if(n.kind==="native")return e.deliveredDrops!==null&&/^\d+$/.test(e.deliveredDrops)?BigInt(e.deliveredDrops):null;if(n.kind!=="issued"||!e.deliveredIssued)return null;let r;try{r=pC(t,e.network)}catch{return null}return e.deliveredIssued.issuer!==r.issuer||e.deliveredIssued.currency.toUpperCase()!==r.currencyHex.toUpperCase()?null:ON(e.deliveredIssued.value,t)}var fue=e=>e.memos.filter(t=>t.type==="cappz-marketplace-monetary").map(t=>{try{return JSON.parse(t.data)}catch{return{}}});function wC(e,t){let n=[];e.network!==t.network&&n.push(`On ${e.network}; this marketplace settles on ${t.network}.`),e.validated||n.push("Not in a validated ledger yet."),e.result!=="tesSUCCESS"&&n.push(`Result ${e.result||"unknown"}, not tesSUCCESS.`),e.type!=="Payment"&&n.push(`It is a ${e.type}, not a Payment.`),e.account!==t.from&&n.push(`Sent from ${e.account}, not ${t.from}.`),e.destination!==t.to&&n.push(`Paid to ${e.destination}, not ${t.toLabel} (${t.to}).`);let r=due(e,t.code),i=Et(t.code);return r===null?n.push(`It did not deliver ${i}${Cn(t.code).kind==="issued"?" from its issuer":""}.`):ro.contractId===t.reference&&(t.index===void 0||o.deliveryIndex===t.index))||n.push(`Memo does not name ${t.reference}${t.index===void 0?"":` and stage ${t.index}`}.`),n}var QN=e=>{throw new To(e)};var YN=5e3,pue=3,eL=(e,t)=>xN(e,t),Qa=(e,t)=>om(e,t),Jl=(e,t)=>$n(om(e,t),t),X4=e=>`${(e/100).toLocaleString("en-US",{maximumFractionDigits:2})}%`,j4=e=>e.percent.enabled||e.flat.enabled||e.perRecord.enabled;function ZN(e,t){let n=[];t.percent.enabled&&!(Number.isInteger(t.percent.bps)&&t.percent.bps>0&&t.percent.bps<=YN)&&n.push(`${e}: the percentage must be between 0.01% and ${X4(YN)}.`);for(let[r,i]of[["flat fee",t.flat],["per-record fee",t.perRecord]]){let o=Object.values(i.amounts);o.some(a=>!(Number.isFinite(a)&&a>=0))&&n.push(`${e}: ${r} amounts must be zero or more.`),i.enabled&&!o.some(a=>a>0)&&n.push(`${e}: an enabled ${r} needs an amount in at least one asset.`)}return n}function yue(e){let t=[...ZN("Marketplace",e.marketplace),...ZN("Securities",e.securities)],n=e.paymentFee;return n?.enabled&&!(Number.isInteger(n.bps)&&Number.isInteger(n.fixedCents)&&n.bps>=0&&n.fixedCents>=0&&n.bps<1e3&&(n.bps>0||n.fixedCents>0))&&t.push("Payment fee: a rate in whole basis points under 10% and/or a fixed amount in whole cents."),(j4(e.marketplace)||j4(e.securities))&&(e.recipients.length||t.push("Name at least one fee recipient (DARC split)."),t.push(...z4(e.recipients)),e.collector&&!(0,JN.isValidClassicAddress)(e.collector.account)&&t.push(`Collection account ${e.collector.account||"(blank)"} is not a valid XRPL classic address (checksum).`),e.collector&&!e.collector.label.trim()&&t.push("Give the collection account a label.")),t}async function tL(e,t,n){let r=yue(n);r.length&&QN(r.join(" "));let i={...n,sheetId:`marketplace-fees-${t}`};return[await ua.create({eventType:"PriceSheetPublished",sourceAddress:e,targetAddress:`${gn}/fees`,payload:{sheetId:i.sheetId,appRoot:gn,effectiveFrom:t,publishedAt:t,schedule:i,by:e}})]}function nL(e,t){return e.appRoot!==gn||!e.schedule?null:{...e.schedule,by:String(e.by??""),at:t}}function bC(e,t){return!e||!j4(e[t])?null:{sheetId:e.sheetId,components:e[t],recipients:e.recipients,collector:e.collector??null,paymentFee:e.paymentFee??null}}function CC(e,t,n){let r=t.currency,i=eL(t.amount,r),o=[],a=[];if(e){let u=e.components,d=AN(u,i,r,n.records,n.flat);a.push(...d.unpriced),u.percent.enabled&&o.push({kind:"percent",label:"Platform fee",formula:`${X4(u.percent.bps)} \xD7 ${Jl(i,r)}`,units:d.percent}),d.flat>0&&o.push({kind:"flat",label:"Flat fee",formula:`${Jl(d.flat,r)} once`,units:d.flat}),d.perRecord>0&&o.push({kind:"per-record",label:"Ledger records",formula:`${n.records} record${n.records===1?"":"s"} \xD7 ${Jl(d.perRecord/n.records,r)}`,units:d.perRecord})}let s=o.reduce((u,d)=>u+d.units,0),c=e&&s>0?mC(s,e.recipients):[],l=e?.collector&&s>0?[{account:e.collector.account,label:e.collector.label,bps:Zl,units:s}]:c;return{currency:r,grossUnits:i,lines:o,feeUnits:s,netUnits:i-s,legs:c,payLegs:l,unpriced:a}}function es(e){let t=ar(e.total.amount,e.milestones),n=e.fees??null,r=e.milestones.map((l,u)=>({...CC(n,{amount:t[u],currency:e.total.currency},{records:rm+(u===0?nm:0),flat:u===0}),milestone:u,label:l.label})),i=new Map;for(let l of r)for(let u of l.lines){let d=i.get(u.kind);i.set(u.kind,d?{...d,units:d.units+u.units}:{...u})}let o=r.reduce((l,u)=>l+u.grossUnits,0),a=e.milestones.length*rm+nm;for(let l of i.values())l.kind==="percent"&&(l.formula=`${X4(n.components.percent.bps)} \xD7 ${Jl(o,e.total.currency)}, per milestone`),l.kind==="per-record"&&(l.formula=`${a} records \xD7 ${Jl(eL(n.components.perRecord.amounts[e.total.currency],e.total.currency),e.total.currency)}`);let s=new Map;for(let l of r)for(let u of l.legs){let d=s.get(u.account);s.set(u.account,d?{...d,units:d.units+u.units}:{...u})}let c=r.reduce((l,u)=>l+u.feeUnits,0);return{currency:e.total.currency,sheetId:n?.sheetId??null,milestones:r,grossUnits:o,feeUnits:c,netUnits:o-c,lines:[...i.values()],legs:[...s.values()],collector:n?.collector??null,unpriced:[...new Set(r.flatMap(l=>l.unpriced))]}}function rL(e){for(let t of e.milestones)t.netUnits<0&&QN(`Fees (${Jl(t.feeUnits,t.currency)}) exceed what \u201C${t.label}\u201D pays (${Jl(t.grossUnits,t.currency)}); raise the price or ask the administrator to lower the fees.`)}function iL(e,t){return CC(e,t,{records:pue,flat:!0})}var Hf=jr(Nr(),1);var Ql=1e6,Z4=946684800;function oL(e){return{network:e,declaredBy:null,at:null,acknowledgement:null}}function fa(e){let t=[...e].filter(r=>r.eventType==="SettlementRailDeclared").sort((r,i)=>r.timestamp.localeCompare(i.timestamp)).at(-1);if(!t)return{network:"testnet",declaredBy:null,at:null,acknowledgement:null};let n=t.payload;return{network:n.network,declaredBy:n.by,at:t.timestamp,acknowledgement:n.acknowledgement??null}}var aL=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").toUpperCase(),hue=e=>new Uint8Array((e.match(/../g)??[]).map(t=>parseInt(t,16)));function sL(){return aL(crypto.getRandomValues(new Uint8Array(32)))}var W4=e=>e.toString(16).padStart(2,"0").toUpperCase();async function mue(e){let t=hue(e);if(t.length>127)throw new Error("Preimage too long.");let n=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return`A0258020${aL(n)}8101${W4(t.length)}`}function gue(e){let t=e.length/2;if(t>125)throw new Error("Preimage too long.");return`A0${W4(t+2)}80${W4(t)}${e.toUpperCase()}`}var cL=e=>Math.floor(Date.parse(e)/1e3)-Z4;function eu(e,t,n){let r=es(e).milestones[t];return[{role:"seller",account:n,label:"Seller",drops:String(r.netUnits)},...r.payLegs.map(i=>({role:"fee",account:i.account,label:i.label,drops:String(i.units)}))].filter(i=>BigInt(i.drops)>0n)}async function wue(e,t,n,r,i,o=new Date().toISOString()){if(e.total.currency!=="XRP")throw new Error("On-ledger escrow is for XRP-priced contracts; issued tokens are paid stage by stage (prepareStagePayments) and USD settles through the payment processor or by reference.");if(i.length!==e.milestones.length)throw new Error("One secret per milestone.");if(t.length!==e.milestones.length)throw new Error("One amount per milestone.");return(await Promise.all(e.milestones.map(async(s,c)=>{let l=await mue(i[c]),u=Wl(o);return eu(e,c,r).map(d=>({...d,milestone:c,condition:l,tx:{TransactionType:"EscrowCreate",Account:n,Destination:d.account,Amount:d.drops,Condition:l,CancelAfter:cL(u),Memos:[Yl({class:"monetary",contractId:e.contractId,deliveryIndex:c,currency:"XRP"})]}}))}))).flat()}async function lL(e,t,n,r,i,o=new Date().toISOString()){return(await wue(e,ar(e.total.amount,e.milestones),n,r,e.milestones.map(()=>i),o)).filter(s=>s.milestone===t)}var vC=e=>typeof e.fields.CancelAfter=="number"?new Date((e.fields.CancelAfter+Z4)*1e3).toISOString():null;function uL(e,t,n,r,i){return{TransactionType:"EscrowFinish",Account:e,Owner:t,OfferSequence:n,Condition:r,Fulfillment:gue(i)}}var dL=e=>e.memos.filter(t=>t.type==="cappz-marketplace-monetary").map(t=>{try{return JSON.parse(t.data)}catch{return{}}});function fL(e,t){let n=[];return e.network!==t.network&&n.push(`On ${e.network}; this marketplace settles on ${t.network}.`),e.validated||n.push("Not in a validated ledger yet."),e.result!=="tesSUCCESS"&&n.push(`Result ${e.result||"unknown"}, not tesSUCCESS.`),e.type!=="EscrowCreate"&&n.push(`It is a ${e.type}, not an EscrowCreate.`),e.account!==t.buyerAccount&&n.push(`Sent from ${e.account}, not the buyer's account ${t.buyerAccount}.`),e.destination!==t.sellerAccount&&n.push(`Escrows to ${e.destination}, not the seller's account ${t.sellerAccount}.`),String(e.fields.Amount)!==t.drops&&n.push(`Escrows ${e.fields.Amount} drops; the milestone needs ${t.drops}.`),e.fields.Condition?t.condition&&String(e.fields.Condition).toUpperCase()!==t.condition.toUpperCase()&&n.push("Condition does not match the one prepared for this milestone."):n.push("No crypto-condition: anyone could not release it safely."),dL(e).some(r=>r.contractId===t.contractId&&r.deliveryIndex===t.milestone)||n.push("Memo does not name this contract and milestone."),n}function J4(e,t){let n=t.type??"EscrowFinish",r=[];return e.network!==t.network&&r.push(`On ${e.network}; this marketplace settles on ${t.network}.`),e.validated||r.push("Not in a validated ledger yet."),e.result!=="tesSUCCESS"&&r.push(`Result ${e.result||"unknown"}, not tesSUCCESS.`),e.type!==n&&r.push(`It is a ${e.type}, not an ${n}.`),String(e.fields.Owner)!==t.owner&&r.push("Finishes an escrow owned by someone else."),Number(e.fields.OfferSequence)!==t.offerSequence&&r.push("Finishes a different escrow (OfferSequence)."),r}var at=e=>e.rail??fC(e.total.currency);function Vf(e,t,n){return eu(e,t,n).map(r=>({role:r.role,account:r.account,label:r.label,units:r.drops}))}function pL(e,t,n,r,i){if(at(e)!=="ledger-staged")throw new Error(`This contract settles on ${at(e)}, not stage-by-stage ledger payments.`);return Vf(e,t,r).map(o=>({...o,tx:gC(n,o.account,BigInt(o.units),e.total.currency,i,e.contractId,t)}))}var AC=e=>Number(e.fields.Sequence||e.fields.TicketSequence||0),Q4=3600,G4=3600,Y4=7*86400,eE=131072,tu=e=>BigInt(Math.round(e.total.amount*Ql)),tE=e=>BigInt(Math.round(e.pricePerUnit.amount*Ql)),nE=(e,t)=>{let n=tE(e);return n>0n?Math.round(Number(t)/Number(n)*1e6)/1e6:0},yL=e=>{let t=BigInt(e);if(t<0n)throw new Error("Negative drops.");let n=t/1000000n,r=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return r?`${n}.${r}`:`${n}`};function hL(e,t,n,r,i=new Date().toISOString(),o=Q4){if(e.total.currency!=="XRP")throw new Error("Ledger payment channels carry XRP only.");if(at(e)!=="ledger-channel")throw new Error(`This contract settles on ${at(e)}, not a payment channel.`);if(!/^(ED[0-9A-F]{64}|0[23][0-9A-F]{64})$/i.test(r))throw new Error("PublicKey must be a 33-byte XRPL public key (hex).");return{TransactionType:"PaymentChannelCreate",Account:t,Destination:n,Amount:tu(e).toString(),SettleDelay:o,PublicKey:r.toUpperCase(),CancelAfter:cL(Wl(i)),Memos:[Yl({class:"monetary",contractId:e.contractId,deliveryIndex:0,currency:"XRP"})]}}function mL(e,t,n,r,i,o=!1){let a=BigInt(n).toString();return{TransactionType:"PaymentChannelClaim",Account:e,Channel:t.toUpperCase(),Balance:a,Amount:a,Signature:r.toUpperCase(),PublicKey:i.toUpperCase(),...o?{Flags:eE}:{}}}function gL(e,t){return{TransactionType:"PaymentChannelClaim",Account:e,Channel:t.toUpperCase(),Flags:eE}}var dm=e=>Hf.hashes.hashPaymentChannel(e.account,e.destination??"",AC(e)).toUpperCase();function Kf(e,t){let n=e.meta?.AffectedNodes??[];for(let r of n)for(let i of["CreatedNode","ModifiedNode","DeletedNode"]){let o=r[i];if(o&&o.LedgerEntryType==="PayChannel"&&String(o.LedgerIndex??"").toUpperCase()===t.toUpperCase())return{kind:i,fields:(i==="CreatedNode"?o.NewFields:o.FinalFields)??{}}}return null}function wL(e,t){let n=[];e.network!==t.network&&n.push(`On ${e.network}; this marketplace settles on ${t.network}.`),e.validated||n.push("Not in a validated ledger yet."),e.result!=="tesSUCCESS"&&n.push(`Result ${e.result||"unknown"}, not tesSUCCESS.`),e.type!=="PaymentChannelCreate"&&n.push(`It is a ${e.type}, not a PaymentChannelCreate.`),e.account!==t.buyerAccount&&n.push(`Opened from ${e.account}, not the buyer's account ${t.buyerAccount}.`),e.destination!==t.sellerAccount&&n.push(`Pays ${e.destination}, not the seller's account ${t.sellerAccount}.`),String(e.fields.Amount)!==t.drops&&n.push(`Caps the channel at ${String(e.fields.Amount)} drops; the contract's cap is ${t.drops}.`),(typeof e.fields.PublicKey!="string"||!e.fields.PublicKey)&&n.push("No PublicKey: claims could not be checked.");let r=Number(e.fields.SettleDelay);return(!Number.isInteger(r)||rY4)&&n.push(`SettleDelay ${String(e.fields.SettleDelay)} s is outside ${G4}\u2013${Y4} s.`),dL(e).some(i=>i.contractId===t.contractId&&i.deliveryIndex===0)||n.push("Memo does not name this contract."),e.meta&&!Kf(e,dm(e))&&n.push("The metadata shows no channel created at the expected id."),n}function bL(e,t){let n=[];e.network!==t.network&&n.push(`On ${e.network}; this marketplace settles on ${t.network}.`),e.validated||n.push("Not in a validated ledger yet."),e.result!=="tesSUCCESS"&&n.push(`Result ${e.result||"unknown"}, not tesSUCCESS.`),e.type!=="PaymentChannelClaim"&&n.push(`It is a ${e.type}, not a PaymentChannelClaim.`),String(e.fields.Channel??"").toUpperCase()!==t.channelId.toUpperCase()&&n.push("Claims on a different channel."),t.submitter&&e.account!==t.submitter&&n.push(`Submitted by ${e.account}, not ${t.submitter}.`);let r=Kf(e,t.channelId);r||n.push("The metadata does not show this channel changed: nothing was redeemed.");let i=a=>typeof a=="string"&&/^\d+$/.test(a)?BigInt(a):null,o=r?i(r.fields.Balance)??0n:null;return{problems:n,balanceDrops:o,deleted:r?.kind==="DeletedNode",amountDrops:r?i(r.fields.Amount):null}}function CL(e,t,n){return(0,Hf.signPaymentChannelClaim)(e.toUpperCase(),yL(t),n).toUpperCase()}function SC(e,t,n,r){try{return(0,Hf.verifyPaymentChannelClaim)(e.toUpperCase(),yL(t),n,r)}catch{return!1}}function rE(e,t,n){let r=e.fees??null,i=p=>p<=0n?null:CC(r,{amount:Number(p)/Ql,currency:"XRP"},{records:vN(0),flat:!0}),o=i(n),a=i(t),s=(o?.feeUnits??0)-(a?.feeUnits??0),c=Number(n-t),l=(o?.lines??[]).map(p=>({...p,units:p.units-(a?.lines.find(h=>h.kind===p.kind)?.units??0)})).filter(p=>p.units!==0),u=r&&s>0?mC(s,r.recipients):[],d=r?.collector&&s>0?[{account:r.collector.account,label:r.collector.label,bps:Zl,units:s}]:u;return{currency:"XRP",grossUnits:c,lines:l,feeUnits:s,netUnits:c-s,legs:u,payLegs:d,unpriced:o?.unpriced??[]}}function vL(e,t,n,r,i){return rE(e,n,r).payLegs.filter(o=>o.units>0).map(o=>({account:o.account,label:o.label,units:o.units,tx:gC(t,o.account,BigInt(o.units),"XRP",i,e.contractId,0)}))}y();y();zb();y();zb();var dTe=2160*60*60*1e3;function iE(e){return JSON.stringify({devicePublicKey:e.devicePublicKey.toLowerCase(),expiresAt:e.expiresAt,issuedAt:e.issuedAt,v:1,walletAddress:e.walletAddress})}async function AL(e,t=Date.now()){if(!e||e.v!==1||!e.walletAddress||!e.devicePublicKey||!e.signature)return"malformed";let n=Date.parse(e.issuedAt),r=Date.parse(e.expiresAt);return!Number.isFinite(n)||!Number.isFinite(r)?"malformed":await jh(iE(e),e.signature,e.walletAddress)?n-5*6e4>t?"not-yet-valid":r<=t?"expired":"valid":"bad-signature"}y();y();y();Hb();qo();h4();var ETe=10*6e4,bue=null;function TL(){return bue??=(async()=>{try{return await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),!0}catch{return!1}})()}var SL=e=>{if(!/^(?:[0-9a-f]{2})+$/i.test(e))throw new Error("not hex");return Uint8Array.from(e.match(/../g),t=>parseInt(t,16))},oE=e=>{let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer};async function Cue(e){return new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}async function vue(e,t,n){try{let r=SL(e),i=SL(t),o=Kb();if(o.backend==="native")return o.ed25519VerifyMany([{message:n,signature:i,publicKey:r}])[0];if(!await TL())return Kn.verify(i,n,r);let a=await crypto.subtle.importKey("raw",oE(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},a,oE(i),oE(n))}catch{return!1}}async function aE(e,t,n){return vue(n,t,await Cue(e))}y();function Ac(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(n=>n===void 0?"null":Ac(n)).join(",")}]`:`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>nr?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Ac(r)}`).join(",")}}`}var Fr=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");function pa(e){if(!/^(?:[0-9a-f]{2})*$/i.test(e))throw new Error("not hex");return Uint8Array.from(e.match(/../g)??[],t=>parseInt(t,16))}var zf=e=>new TextEncoder().encode(e),TC=e=>{let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer};async function fm(e){return new Uint8Array(await crypto.subtle.digest("SHA-256",TC(e)))}async function EC(e){return Fr(await fm(zf(e)))}var Sue=2160*60*60*1e3,Tue=312*60*60*1e3,Eue=5*6e4,kue=["hello","signing"],kC=e=>{let{signature:t,...n}=e;return n};function sE(e){return Ac({...e,publicKey:e.publicKey.toLowerCase()})}function _ue(e){return e.v===2?e:{v:2,walletAddress:e.walletAddress,publicKey:e.devicePublicKey.toLowerCase(),algorithm:"ed25519",purpose:"hello",issuedAt:e.issuedAt,expiresAt:e.expiresAt,signature:e.signature}}var pm=new Map;function cE(e){let t=`${e.v===1?iE(e):sE(kC(e))}|${e.signature}`,n=pm.get(t);return n||(n=EC(t),pm.size>=1e4&&pm.delete(pm.keys().next().value),pm.set(t,n)),n}async function kL(e,t,n,r=Sue,i=Date.now()){let o={v:2,walletAddress:t,publicKey:n.publicKey.toLowerCase(),algorithm:n.algorithm,purpose:n.purpose,issuedAt:new Date(i).toISOString(),expiresAt:new Date(i+r).toISOString(),...n.supersedes?{supersedes:n.supersedes}:{}};return{...o,signature:await zh(e,sE(o))}}function _L(e,t,n){let r=Date.parse(e),i=Date.parse(t);return!Number.isFinite(r)||!Number.isFinite(i)?"malformed":r-Eue>n?"not-yet-valid":i<=n?"expired":null}async function lE(e,t=Date.now()){if(!e)return"malformed";if(e.v===1)return AL(e,t);if(e.v!==2||!e.walletAddress||!e.publicKey||!e.signature||!e.purpose||!e.algorithm)return"malformed";let n=_L(e.issuedAt,e.expiresAt,t);return n==="malformed"?n:await IL(sE(kC(e)),e.signature,e.walletAddress)?n??"valid":"bad-signature"}var ym=new Map;async function IL(e,t,n){let r=`${n}|${t}|${e}`,i=ym.get(r);if(i!==void 0)return i;let o=await jh(e,t,n);return ym.size>=1e4&&ym.delete(ym.keys().next().value),ym.set(r,o),o}function Iue(e){return Ac({...e,publicKey:e.publicKey.toLowerCase()})}async function Pue(e){return!e||e.v!==1||!e.walletAddress||!e.declarationHash||!e.publicKey||!e.signature?"malformed":await IL(Iue(kC(e)),e.signature,e.walletAddress)?"valid":"bad-signature"}async function xue(e,t=Date.now()){if(!e||e.v!==1||!e.parentPublicKey||!e.publicKey||!e.signature||Date.parse(e.expiresAt)-Date.parse(e.issuedAt)>Tue+1e3)return"malformed";let n=_L(e.issuedAt,e.expiresAt,t);return n==="malformed"?n:await aE(Ac(kC(e)),e.signature,e.parentPublicKey)?n??"valid":"bad-signature"}async function Mue(e,t=[]){let n=new Set;for(let r of t)r.walletAddress===e&&await Pue(r)==="valid"&&n.add(r.declarationHash);return n}async function uE(e,t,n,r,i=Date.now()){let o=t.toLowerCase(),a=await Mue(e,r.revocations),s=await EL(e,o,[n],r.declarations,a,i);if(s.state==="declared"||!r.delegations?.length)return s;for(let c of r.delegations){if(c.walletAddress!==e||c.publicKey.toLowerCase()!==o)continue;if(c.purpose!==n)return{state:"wrong-purpose",because:`delegated for ${c.purpose}, not ${n}`};let l=await EL(e,c.parentPublicKey.toLowerCase(),kue,r.declarations,a,i);if(l.state!=="declared")return{state:l.state==="undeclared"?"undeclared":l.state,because:`delegating key: ${l.because}`};let u=await xue(c,i);return u!=="valid"?{state:u==="malformed"?"bad-signature":u,because:`delegation ${u}`}:{state:"delegated",declarationHash:l.declarationHash,expiresAt:c.expiresAt,because:`delegated by declared key ${c.parentPublicKey.slice(0,16)}\u2026 until ${c.expiresAt}`}}return s}async function EL(e,t,n,r,i,o){let a={state:"undeclared",because:"no declaration names this key"},s={declared:9,delegated:8,revoked:7,"wrong-purpose":6,expired:5,"not-yet-valid":4,"bad-signature":3,undeclared:0};for(let c of r){let l=_ue(c);if(l.walletAddress!==e||l.publicKey.toLowerCase()!==t)continue;let u=await cE(c),d=await lE(c,o),p;d==="bad-signature"||d==="malformed"?p={state:"bad-signature",because:`declaration ${d}`}:i.has(u)?p={state:"revoked",declarationHash:u,because:"the wallet revoked this declaration"}:d!=="valid"?p={state:d,declarationHash:u,expiresAt:l.expiresAt,because:`declaration ${d}`}:n.includes(l.purpose)?p={state:"declared",declarationHash:u,expiresAt:l.expiresAt,because:`declared by the wallet for ${l.purpose} until ${l.expiresAt}`}:p={state:"wrong-purpose",declarationHash:u,because:`declared for ${l.purpose}`},s[p.state]>s[a.state]&&(a=p)}return a}var dE=e=>e.toLowerCase(),hm=(e,t,n)=>typeof e[t]=="string"&&n.test(e[t]);function PL(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===2&&hm(t,"walletAddress",/^0[23][0-9a-f]{64}$/i)&&hm(t,"publicKey",/^[0-9a-f]{64,130}$/i)&&hm(t,"signature",/^[0-9a-f]{120,160}$/i)&&hm(t,"issuedAt",/^\d{4}-/)&&hm(t,"expiresAt",/^\d{4}-/)&&typeof t.purpose=="string"&&typeof t.algorithm=="string"}function xL(e,t,n){let r=Date.parse(n);return[...new Set(e.mandates.filter(i=>i.agentPartyId===t&&Date.parse(i.limits.expiresAt)>r&&typeof i.boundKey=="string"&&i.boundKey).map(i=>dE(i.boundKey)))]}async function fE(e,t,n,r,i=[]){let o=dE(n),a=xL(e,t,r),s=a.length?a.includes(o)?"bound":"bound-to-other-key":"unbound",c={partyId:t,keyId:o,binding:s,boundKeys:a},l=e.parties.get(t);if(!l)return{...c,state:"unknown-party",because:`no party ${t} on this market`};let u=l.keyDeclaration;if(!PL(u))return{...c,state:"undeclared",because:"the profile declares no signing key"};if(dE(u.publicKey)!==o)return{...c,state:"undeclared",walletAddress:u.walletAddress,because:`the profile declares key ${u.publicKey.slice(0,16)}\u2026, not this one`};let d=await uE(u.walletAddress,o,"signing",{declarations:[u],revocations:[...l.keyRevocations??[],...i]},Date.parse(r));return{...c,state:d.state,walletAddress:u.walletAddress,...d.declarationHash?{declarationHash:d.declarationHash}:{},...d.expiresAt?{expiresAt:d.expiresAt}:{},because:d.because}}async function ML(e,t){let n=[],r=e.keyDeclaration;if(r!==void 0)if(!PL(r))n.push("keyDeclaration must be a KeyZ declaration (v 2) signed by your identity wallet.");else{r.purpose!=="signing"&&n.push(`keyDeclaration is for ${r.purpose}; an agent's request key is declared for signing.`),r.algorithm!=="ed25519"&&n.push(`keyDeclaration is ${r.algorithm}; request signatures use ed25519.`);let i=await lE(r,Date.parse(t));i!=="valid"&&n.push(`keyDeclaration is ${i}${i==="bad-signature"?" (not signed by the wallet it names)":""}.`)}return e.keyRevocations!==void 0&&(!Array.isArray(e.keyRevocations)||e.keyRevocations.length>32)&&n.push("keyRevocations is a list of at most 32 wallet-signed revocations."),n}y();y();y();var t4e=15*6e4;function DL(e){if(e===void 0)return[];let t=e,n=[];if(!t||typeof t!="object"||Array.isArray(t))return["principalCredential must be { attestationId, issuer, vct }."];(typeof t.attestationId!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.attestationId))&&n.push("principalCredential.attestationId is the base64url SHA-256 of the issuer JWT."),(typeof t.issuer!="string"||!t.issuer.startsWith("did:key:"))&&n.push("principalCredential.issuer is the issuer did:key."),(typeof t.vct!="string"||!t.vct)&&n.push("principalCredential.vct is the credential type.");let r=new Set(["attestationId","issuer","vct","expiresAt"]),i=Object.keys(t).filter(o=>!r.has(o));return i.length&&n.push(`principalCredential carries only a reference; remove ${i.join(", ")} (values are disclosed on request, sealed).`),n}var Y=e=>{throw new To(e)},Tc=e=>`${e}-${Array.from(crypto.getRandomValues(new Uint8Array(6)),t=>t.toString(16).padStart(2,"0")).join("")}`,st=(e,t,n,r)=>ua.create({eventType:e,sourceAddress:t,targetAddress:n,payload:r});function pE(e,t){let n=Ff(t.milestones,t.formedAt);um(n),KN(n,t.formedAt),t.rail&&!Cn(t.total.currency).rails.includes(t.rail)&&Y(`${Et(t.total.currency)} does not settle on ${t.rail}.`);let r={...t,milestones:n,fees:bC(e.fees,"marketplace"),...t.rail?{rail:t.rail}:U4(t.total.currency)?{rail:fC(t.total.currency)}:{}};return rL(es(r)),r}function _C(e,t,n,r,i,o,a={}){return st("FeeCharged",e,`${Gn(t.contractId)}/fees/${r}`,{contractId:t.contractId,milestone:r,sheetId:t.fees?.sheetId??"",currency:n.currency,grossUnits:n.grossUnits,feeUnits:n.feeUnits,netUnits:n.netUnits,lines:n.lines,legs:o,owed:n.legs,collector:t.fees?.collector??null,payer:t.sellerId,settlement:i,...a})}function nu(e,t){return e.parties.get(t)??Y("Set up your marketplace profile first.")}function mm(e,t){if(t&&((!im(t.currency)||Cn(t.currency).code!==t.currency)&&Y(`Unknown payment asset ${String(t.currency)}.`),e.network)){let n=da(t.currency,e.network);n.state!=="available"&&Y(n.reason)}}function vr(e,t,n,r,i){let o=nu(e,t.partyId);if(o.kind!=="agent")return{};let a=e.committedByDay.get(Lf(o.partyId,t.at,r?.currency??null))??0,s=V4(e.mandates,o.partyId,n,r,i,t.at,a);if(s.ok||Y(`Agent ${o.name}: ${s.reason}`),s.needsApproval){let c=new Set(e.mandates.filter(l=>l.agentPartyId===o.partyId).map(l=>l.grantedBy));(!t.coSignedBy||!c.has(t.coSignedBy))&&Y(`Agent ${o.name}: ${s.reason} \u2014 co-signature missing.`)}return{agentPartyId:o.partyId,mandateCheck:s.reason,...t.coSignedBy?{coSignedBy:t.coSignedBy}:{}}}function yE(e,t,n,r){return t?(t===r&&Y("The seller cannot be the evaluator of their own work."),t===n&&Y("The buyer accepts milestones already; name a third party as evaluator, or none."),e.parties.has(t)||Y(`Unknown evaluator ${t}: they need a marketplace profile.`),{evaluatorId:t}):{}}async function jf(e,t,n){n.partyId!==t.partyId&&Y("You can only edit your own profile."),n.name.trim()||Y("Give your profile a name."),n.kind==="agent"&&!n.principal?.partyId&&!n.principal?.governanceAddress&&Y("An agent needs an accountable principal: a person or organization, or a governance address for a non-human company.");let r=[...await ML(n,t.at),...DL(n.principalCredential)];r.length&&Y(r.join(" "));let i=e.parties.has(n.partyId);return[await st(i?"ContentAmended":"ContentCreated",ve(n.partyId),ve(n.partyId),{contentClass:"party",profile:n})]}async function ts(e,t,n){nu(e,t.partyId),n.sellerId!==t.partyId&&Y("You can only list as yourself.");let r=gr(n.categoryId)??Y("Choose a category.");r.kinds.includes(n.kind)||Y(`${r.label} does not support \u201C${n.kind}\u201D.`),n.title.trim()||Y("Give the listing a title."),n.quantity>0||Y("Quantity must be more than zero."),n.pricePerUnit.amount>0||Y("Price must be more than zero."),mm(t,n.pricePerUnit),n.metered&&(n.pricePerUnit.currency!=="XRP"&&Y(`Metered listings are priced in XRP: they settle through a ledger payment channel, which carries XRP only (not ${Et(n.pricePerUnit.currency)}).`),n.milestones&&Y("A metered listing has no payment schedule: the buyer pays as the service is used, through the channel."),n.tokenId&&Y("A metered listing cannot be backed by a receipt token.")),n.milestones&&H4(n.milestones,t.at.slice(0,10)),n.tokenId&&((e.tokens.find(s=>s.content.tokenId===n.tokenId)??Y("Unknown token.")).balances[t.partyId]??0)<=0&&Y("You do not hold that token.");let i=vr(e,t,"marketplace.listing.publish",null,n.categoryId),o=e.listings.some(a=>a.listingId===n.listingId);return[await st(o?"ContentAmended":"ContentCreated",ve(t.partyId),Df(n.listingId),{contentClass:"listing",listing:n,...i})]}async function RL(e,t,n){return(e.listings.find(i=>i.listingId===n)??Y("Unknown listing.")).sellerId!==t.partyId&&Y("Only the seller can withdraw a listing."),[await st("ListingWithdrawn",ve(t.partyId),Df(n),{listingId:n})]}async function NL(e,t,n,r,i){let o=e.listings.find(a=>a.listingId===n)??Y("Unknown listing.");return o.sellerId!==t.partyId&&Y("Only the seller can adjust inventory."),o.remaining+r<0&&Y("Inventory cannot go below zero."),[await st("InventoryAdjusted",ve(t.partyId),Df(n),{listingId:n,delta:r,reason:i})]}async function IC(e,t,n,r,i,o){let a=e.listings.find(h=>h.listingId===n)??Y("Unknown listing.");nu(e,t.partyId),a.open||Y("This listing is no longer available."),a.sellerId===t.partyId&&Y("You cannot buy your own listing."),r>0||Y("Quantity must be more than zero."),r>a.remaining&&Y(`Only ${a.remaining} ${a.unit} left.`);let s=qf(a.pricePerUnit,r);mm(t,s);let c=vr(e,t,"marketplace.order.place",s,a.categoryId),l=i??new Date(Date.parse(t.at)+a.leadDays*864e5).toISOString().slice(0,10),u=Tc("ct"),d={contractId:u,buyerId:t.partyId,sellerId:a.sellerId,source:{kind:"listing",listingId:n},categoryId:a.categoryId,title:a.title,quantity:r,unit:a.unit,pricePerUnit:a.pricePerUnit,total:s,milestones:a.metered?Due(r,a.unit,t.at):a.milestones?H4(a.milestones,t.at.slice(0,10)):$f(a.kind==="production-contract"?"production-contract":"spot",t.at.slice(0,10),l),formedAt:t.at,...yE(e,o,t.partyId,a.sellerId),...a.metered?{rail:"ledger-channel"}:{}};a.metered&&tu(d)<=0n&&Y("The cap is too small: order more units.");let p=pE(e,d);return{contractId:u,txs:[await st("OrderPlaced",ve(t.partyId),tm(u),{contractId:u,terms:p,...c})]}}function Due(e,t,n){return[{index:0,label:`Metered use (up to ${e} ${t})`,share:1,dueBy:new Date(Date.parse(n)+29*864e5).toISOString().slice(0,10),evidence:"Claims the buyer signs as the service is used, redeemed on the ledger",delivery:!0}]}async function Xf(e,t,n){nu(e,t.partyId),n.buyerId!==t.partyId&&Y("You can only request as yourself."),HN(n,t.at),lm(n.acceptance),mm(t,n.maxPricePerUnit);let r=vr(e,t,"marketplace.request.post",n.maxPricePerUnit?qf(n.maxPricePerUnit,n.quantity):null,n.categoryId);return[await st("SupplyRequested",ve(t.partyId),D4(n.requestId),{request:n,...r})]}async function ru(e,t,n){let r=e.requests.find(s=>s.requestId===n.requestId)??Y("Unknown request.");nu(e,t.partyId),r.open||Y("This request is closed."),n.sellerId!==t.partyId&&Y("You can only bid as yourself."),r.buyerId===t.partyId&&Y("You cannot bid on your own request."),mm(t,n.pricePerUnit),r.maxPricePerUnit&&r.maxPricePerUnit.currency!==n.pricePerUnit.currency&&Y(`The request is priced in ${Et(r.maxPricePerUnit.currency)}; bid in the same asset.`);let i={...n,milestones:Ff(n.milestones,t.at)},o=VN(i,r,t.at);i.milestones.length>n.milestones.length&&o.push(`Steps longer than 30 days were split into ${i.milestones.length} stages: holds are limited to a 30-day billing cycle, and each stage is funded when the previous one completes.`);let a=vr(e,t,"marketplace.offer.submit",qf(n.pricePerUnit,n.quantity),r.categoryId);return{warnings:o,txs:[await st("SupplyOffered",ve(t.partyId),mN(r.requestId,n.offerId),{offer:i,warnings:o,...a})]}}async function Wf(e,t,n,r,i,o){let a=e.requests.find(h=>h.requestId===n)??Y("Unknown request.");a.buyerId!==t.partyId&&Y("Only the buyer can award.");let s=a.offers.find(h=>h.offerId===r)??Y("Unknown offer.");s.withdrawn&&Y("That offer was withdrawn.");let c=i??Math.min(s.quantity-s.awardedQuantity,a.quantity-a.awardedQuantity);c>0||Y("Nothing left to award on this offer or request."),c>s.quantity-s.awardedQuantity&&Y("More than the offer covers."),c>a.quantity-a.awardedQuantity&&Y("More than the request still needs."),um(s.milestones);let l=qf(s.pricePerUnit,c),u=vr(e,t,"marketplace.offer.award",l,a.categoryId),d=Tc("ct"),p=pE(e,{contractId:d,buyerId:a.buyerId,sellerId:s.sellerId,source:{kind:"request",requestId:n,offerId:r},categoryId:a.categoryId,title:a.title,quantity:c,unit:a.unit,pricePerUnit:s.pricePerUnit,total:l,milestones:s.milestones,formedAt:t.at,...yE(e,o,a.buyerId,s.sellerId)});return{contractId:d,txs:[await st("SupplyAwarded",ve(t.partyId),tm(d),{contractId:d,requestId:n,offerId:r,terms:p,...u})]}}async function PC(e,t,n,r){let i=Ur(e,n);nu(e,t.partyId),i.sellerId!==t.partyId&&Y("Only the parent contract\u2019s seller can subcontract its work."),(i.state==="completed"||i.state==="cancelled")&&Y(`The parent contract is ${i.state}; there is no work left to subcontract.`);let o=e.parties.get(r.subcontractorId)??Y(`Unknown subcontractor ${r.subcontractorId}: they need a marketplace profile.`);o.partyId===t.partyId&&Y("You cannot subcontract to yourself."),r.title?.trim()||Y("Give the subcontract a title."),r.quantity>0||Y("Quantity must be more than zero."),r.pricePerUnit?.amount>0||Y("Price must be more than zero."),mm(t,r.pricePerUnit),r.pricePerUnit.currency!==i.total.currency&&Y(`A subcontract is paid in the parent's asset (${Et(i.total.currency)}), from what the parent releases; not in ${Et(r.pricePerUnit.currency)}.`);let a=qf(r.pricePerUnit,r.quantity),c=e.contracts.filter(T=>i.subcontracts.includes(T.contractId)&&T.state!=="completed"&&T.state!=="cancelled").reduce((T,k)=>T+(k.total.amount-k.escrow.released),0),l=Math.round((i.total.amount-i.escrow.released-c)*100)/100;a.amount>l+1e-9&&Y(`The subcontract (${a.amount} ${a.currency}) exceeds what is left of the parent: ${l} ${a.currency} unreleased after open subcontracts.`),!r.milestones&&r.serves===void 0&&Y("Say which parent milestone the subcontract serves.");let d=(r.milestones??[(()=>{let T=i.milestones[r.serves]??Y(`The parent has no milestone ${r.serves}.`);return{label:r.title.trim(),share:1,dueBy:T.dueBy,evidence:`Delivered to the main contractor for \u201C${T.label}\u201D`,delivery:!0,servesMilestone:T.index,...r.acceptance?{acceptance:r.acceptance}:{}}})()]).map((T,k)=>({...T,index:k}));d.forEach(T=>lm(T.acceptance)),d.forEach((T,k)=>{Number.isInteger(T.servesMilestone)||Y(`Stage ${k+1} must name the parent milestone it serves.`);let B=i.milestones[T.servesMilestone]??Y(`The parent has no milestone ${T.servesMilestone}.`);T.dueBy>B.dueBy&&Y(`\u201C${T.label}\u201D is due ${T.dueBy}, after the parent milestone \u201C${B.label}\u201D it serves (${B.dueBy}).`),k>0&&T.servesMilestoneT.servesMilestone))]})]}}function hE(e,t,n){let r=vc(e.contracts,t,n);r&&Y(r)}function Ur(e,t){return e.contracts.find(n=>n.contractId===t)??Y("Unknown contract.")}function ya(e){let t=e.milestoneStates.find(r=>r.state!=="released");if(!t)return null;let n=ar(e.total.amount,e.milestones)[t.index];return{index:t.index,amount:n,need:Math.round((n-e.escrow.balance)*100)/100}}function Rue(e,t,n,r){let i=e.milestoneStates[t]?.stage;if(i)return{stageDueBy:i.dueBy,holdUntil:i.holdUntil,fundedAt:i.fundedAt};let o=n.slice(0,10),a=new Date(Date.parse(n)+29*864e5).toISOString().slice(0,10),s=e.milestones[t].dueBy;return r&&(ra)&&Y(`A stage is due within ${29} days of funding (${o} to ${a}): holds are limited to a ${30}-day billing cycle.`),{stageDueBy:r??(sa?a:s),holdUntil:Wl(n),fundedAt:n}}async function iu(e,t,n,r,i,o){let a=Ur(e,n);a.buyerId!==t.partyId&&Y("Only the buyer funds escrow."),r>0||Y("Amount must be more than zero."),i.rail!=="demo"&&at(a)==="ledger-escrow"&&Y(`${Et(a.total.currency)} contracts are funded with on-ledger escrow (one EscrowCreate per stage leg), not by reference.`),i.rail!=="demo"&&at(a)==="ledger-channel"&&Y("Metered contracts are funded by opening a ledger payment channel for the cap (marketplace.channel.open)."),i.rail!=="demo"&&at(a)==="ledger-staged"&&Y(`${Et(a.total.currency)} contracts hold nothing: each stage is paid on the ledger when you accept it (marketplace.stage.pay).`);let s=ya(a)??Y("Every stage is paid.");s.need<=0&&Y(`\u201C${a.milestones[s.index].label}\u201D is funded. The next stage is configured and funded when it completes.`),r>s.need+1e-9&&Y(`Fund one stage at a time: \u201C${a.milestones[s.index].label}\u201D needs ${s.need} ${a.total.currency}. Later stages are funded as each completes \u2014 holds are limited to a ${30}-day billing cycle.`),hE(e,a,s.index);let c=Rue(a,s.index,t.at,o),l=vr(e,t,"marketplace.escrow.fund",{amount:r,currency:a.total.currency},a.categoryId),u=[await st("EscrowFunded",ve(t.partyId),Gn(n),{contractId:n,amount:r,currency:a.total.currency,rail:i.rail,milestone:s.index,...c,...l})];return i.reference&&u.push(await st("PaymentConfirmed",ve(t.partyId),Gn(n),{contractId:n,amount:r,rail:i.rail,reference:i.reference,validated:!1,milestone:s.index})),u}function Nue(e){return e.escrow.funded>0||e.escrow.released>0||e.payments.length>0||e.ledgerEscrows.length>0||!!e.channel||e.milestoneStates.some(t=>t.releasedAmount>0||t.state==="released"||!!t.processor)}async function LL(e,t,n,r){let i=Ur(e,n);t.partyId!==i.buyerId&&t.partyId!==i.sellerId&&Y("Only the buyer or the seller cancels a contract."),(i.state==="cancelled"||i.state==="completed")&&Y(`The contract is already ${i.state}.`),i.state==="disputed"&&Y("The contract is in dispute; an operator resolves it."),Nue(i)&&Y("Money has moved on this contract, so it cannot be cancelled: release, refund or raise a dispute instead.");let o=e.contracts.filter(a=>i.subcontracts.includes(a.contractId)&&a.state!=="cancelled"&&a.state!=="completed");return o.length&&Y(`Cancel its open subcontracts first: ${o.map(a=>a.contractId).join(", ")}.`),r.trim()||Y("Say why the contract is cancelled; the reason is recorded with it."),[await st("ContractCancelled",ve(t.partyId),tm(n),{contractId:n,by:t.partyId,reason:r.trim()})]}async function Gf(e,t,n,r,i){let o=Ur(e,n);o.sellerId!==t.partyId&&Y("Only the seller submits evidence."),(o.milestoneStates[r]??Y("Unknown milestone.")).state==="released"&&Y("That milestone is already paid."),/^[0-9a-f]{64}$/.test(i.hash)||Y("Evidence must be referenced by its sha256 hash (the file itself stays with you).");let s=o.milestones[r].delivery?Rf(n,r):aC(n,r);return[await st("MilestoneEvidenced",ve(t.partyId),s,{contractId:n,milestone:r,...i})]}async function ou(e,t,n,r,i){let o=Ur(e,n),a=o.buyerId===t.partyId?"buyer":o.evaluatorId&&o.evaluatorId===t.partyId?"evaluator":null;a||Y(o.evaluatorId?"Only the buyer or the contract\u2019s evaluator accepts a milestone.":"Only the buyer accepts a milestone."),o.milestoneStates[r]?.state!=="evidenced"&&Y("There is no new evidence to accept for that milestone.");let s=a==="evaluator"?vr(e,t,"marketplace.milestone.affirm",null,o.categoryId):{},c=o.milestones[r].delivery;return i&&(!/^[0-9a-f]{64}$/.test(i.verdictSha256)||i.verdict!=="pass"||!i.verdictAddress.startsWith(`${aC(n,r)}/verdicts/`))&&Y("An acceptance can cite only a passing verdict on this milestone (its SHA-256 and address)."),[await st(c?"DeliveryApproved":"MilestoneAffirmed",ve(t.partyId),c?Rf(n,r):aC(n,r),{contractId:n,milestone:r,by:t.partyId,role:a,...s,...i?{basis:i}:{}})]}async function Yf(e,t,n,r){let i=Ur(e,n);i.buyerId!==t.partyId&&Y("Only the buyer releases escrow (an operator can, by resolving a dispute)."),i.milestoneStates[r]?.state!=="affirmed"&&Y("Accept the milestone before releasing payment."),i.ledgerEscrows.some(s=>s.milestone===r)&&Y("This milestone is escrowed on the ledger: reveal its secret, submit EscrowFinish, and record the ledger transaction."),at(i)==="ledger-channel"&&Y("A metered contract is paid as it is used: the buyer signs claims, the seller redeems them on the ledger (marketplace.channel.settle).");let o=ar(i.total.amount,i.milestones)[r];at(i)==="ledger-staged"&&i.escrow.balance+1e-9Date.parse(a.holdUntil)&&Y(`The 30-day hold for this stage ended ${a.holdUntil.slice(0,10)}: take it back and fund the stage again, or ask an operator.`),Lue(ve(t.partyId),i,r,o,{})}async function Lue(e,t,n,r,i){let o=es(t).milestones[n],a=[await st("EscrowReleased",e,Gn(t.contractId),{contractId:t.contractId,milestone:n,amount:r,to:t.sellerId,netToSeller:Qa(o.netUnits,o.currency),fee:Qa(o.feeUnits,o.currency),...i})];return o.feeUnits>0&&a.push(await _C(e,t,o,n,t.payments.length?"by-reference":"demo",o.legs.map(s=>({...s})))),a}async function BL(e,t,n,r,i){let o=Ur(e,n);return t.partyId!==o.buyerId&&t.partyId!==o.sellerId&&Y("Only the buyer or seller can raise a dispute."),o.state==="completed"&&Y("This contract is complete."),i.trim()||Y("Describe the problem."),[await st("DisputeRaised",ve(t.partyId),gN(n,o.disputes.length),{contractId:n,milestone:r??-1,by:t.partyId,reason:i})]}async function gm(e,t,n,r,i){let o=Ur(e,n);return t.partyId!==o.buyerId&&t.partyId!==o.sellerId&&Y("Only the parties can review."),o.state!=="completed"&&o.state!=="cancelled"&&Y("Reviews open when the contract is finished."),o.reviews.some(a=>a.by===t.partyId)&&Y("You already reviewed this contract."),r>=1&&r<=5&&Number.isInteger(r)||Y("Rating is 1 to 5."),[await st("ReviewPosted",ve(t.partyId),wN(n,t.partyId),{contractId:n,by:t.partyId,rating:r,text:i})]}async function FL(e,t,n){nu(e,t.partyId);let r=gr(n.categoryId)??Y("Choose a category.");r.tokenizable||Y(`${r.label} cannot be tokenized in this release.`);let i=zN(n.answers);i.result==="blocked"&&Y(i.reasons.join(" ")),Number.isInteger(n.supply)&&n.supply>0||Y("Supply must be a whole number of tokens."),n.redeemsFor.quantity>0||Y("Say what one token redeems for."),n.backing.evidence.length||Y("Attach at least one piece of backing evidence (by hash).");let o=vr(e,t,"marketplace.asset.tokenize",null,n.categoryId),{answers:a,issuerAccount:s,...c}=n,l={...c,issuerId:t.partyId,classification:i,xrpl:{network:"testnet",preparedIssuance:jN(c,s)}};return{classification:i,txs:[await st("AssetTokenized",ve(t.partyId),R4(l.tokenId),{token:l,...o})]}}async function UL(e,t,n,r,i,o){let a=e.tokens.find(c=>c.content.tokenId===n)??Y("Unknown token.");e.parties.has(r)||Y("Unknown recipient."),Number.isInteger(i)&&i>0||Y("Transfer a whole number of tokens."),(a.balances[t.partyId]??0)0&&r.maxPerDay.amount>=r.maxPerContract.amount||Y("Set a per-contract limit and a daily limit at least as large."),Date.parse(r.expiresAt)<=Date.parse(t.at)&&Y("The mandate must expire in the future.");let s=i.boundKey?.toLowerCase();if(s){let l=await fE(e,n,s,t.at);l.state!=="declared"&&Y(`Bind the mandate to the agent\u2019s declared signing key: ${s.slice(0,16)}\u2026 is ${l.state} (${l.because}).`)}let c=Tc("mandate");return{mandateId:c,txs:[await st("PermissionGranted",ve(t.partyId),B4(n,c),{contentClass:"mandate",mandate:{mandateId:c,agentPartyId:n,grantedBy:t.partyId,limits:r,...s?{boundKey:s}:{}},...o.principal?.governanceAddress?{governanceAddress:o.principal.governanceAddress}:{}})]}}async function $L(e,t,n){let r=e.mandates.find(i=>i.mandateId===n)??Y("Unknown or already revoked mandate.");return r.grantedBy!==t.partyId&&Y("Only the grantor can revoke a mandate."),[await st("PermissionRevoked",ve(t.partyId),B4(r.agentPartyId,n),{contentClass:"mandate",mandateId:n})]}function wm(e,t){let n=e.parties.get(t.buyerId)?.xrplAccount??Y("The buyer has no XRPL account on their profile."),r=e.parties.get(t.sellerId)?.xrplAccount??Y("The seller has no XRPL account on their profile.");return{buyer:n,seller:r}}async function xC(e,t,n,r,i){let o=Ur(e,n);o.buyerId!==t.partyId&&Y("Only the buyer funds escrow."),at(o)!=="ledger-escrow"&&Y(`On-ledger escrow is for XRP-priced contracts; this one settles on ${at(o)}.`);let{buyer:a,seller:s}=wm(e,o),c=ar(o.total.amount,o.milestones),l=[];for(let u of[...new Set(i.map(d=>d.milestone))]){o.ledgerEscrows.some(C=>C.milestone===u)&&Y(`Milestone ${u+1} is already escrowed on the ledger.`),u!==ya(o)?.index&&Y(`Fund one stage at a time: stage ${u+1} is funded after the stages before it complete (holds are limited to a ${30}-day billing cycle).`),hE(e,o,u);let d=i.filter(C=>C.milestone===u),p=d[0].condition;d.some(C=>C.condition.toUpperCase()!==p.toUpperCase())&&Y(`Milestone ${u+1}: every leg must use the milestone's one condition.`);let h=eu(o,u,s),g=new Set,w=h.map(C=>{let v=d.find(A=>!g.has(A.lt)&&A.lt.destination===C.account&&String(A.lt.fields.Amount)===C.drops)??Y(`Milestone ${u+1}: no EscrowCreate for the ${C.label} leg (${C.drops} drops to ${C.account}).`);g.add(v.lt);let S=fL(v.lt,{network:r.network,contractId:n,milestone:u,buyerAccount:a,sellerAccount:C.account,drops:C.drops,condition:p});return S.length&&Y(`Milestone ${u+1}${C.role==="fee"?` (${C.label} fee leg)`:""}: ${S.join(" ")}`),{leg:C,lt:v.lt,sealedSecret:v.sealedSecret}});g.size!==d.length&&Y(`Milestone ${u+1}: an EscrowCreate matches no leg of this contract.`);let T=w.find(C=>C.leg.role==="seller")??Y(`Milestone ${u+1}: the seller's leg is missing.`),k=T.lt.closeTime??T.lt.checkedAt,B=vC(T.lt)??Y(`Milestone ${u+1}: no CancelAfter, so the escrow could be held indefinitely.`);for(let C of w){let v=vC(C.lt);(!v||Date.parse(v)>Date.parse(Wl(k))+864e5)&&Y(`Milestone ${u+1}${C.leg.role==="fee"?` (${C.leg.label} fee leg)`:""}: CancelAfter is more than ${30} days after funding; holds are limited to a ${30}-day billing cycle.`)}let D=o.milestones[u].dueBy,P=new Date(Date.parse(B)-864e5).toISOString().slice(0,10),U={fundedAt:k,stageDueBy:D>P?P:DC.sealedSecret)?.sealedSecret,H=w.filter(C=>C.leg.role==="fee").map(C=>({account:C.leg.account,label:C.leg.label,drops:C.leg.drops,txHash:C.lt.hash,sequence:AC(C.lt)})),b=vr(e,t,"marketplace.escrow.fund",{amount:c[u],currency:"XRP"},o.categoryId);l.push(await st("EscrowFunded",ve(t.partyId),Gn(n),{contractId:n,amount:c[u],currency:"XRP",rail:"xrpl-escrow",milestone:u,network:T.lt.network,txHash:T.lt.hash,sequence:AC(T.lt),condition:p,ledgerIndex:T.lt.ledgerIndex,checkedAt:T.lt.checkedAt,feeEscrows:H,...U,...F?{sealedSecret:F}:{},...b}));for(let C of w)l.push(await st("PaymentConfirmed",ve(t.partyId),Gn(n),{contractId:n,amount:Number(C.leg.drops)/Ql,rail:"xrpl-escrow",leg:C.leg.role,to:C.leg.account,reference:C.lt.hash,validated:!0,network:C.lt.network,ledgerIndex:C.lt.ledgerIndex,checkedAt:C.lt.checkedAt}))}return l}async function MC(e,t,n,r,i,o,a=[]){let s=Ur(e,n);t.partyId!==s.buyerId&&t.partyId!==s.sellerId&&Y("Only the parties record ledger settlement.");let c=s.ledgerEscrows.find(k=>k.milestone===r)??Y("That milestone has no on-ledger escrow."),{buyer:l}=wm(e,s),u=i.type==="EscrowCancel"?"EscrowCancel":"EscrowFinish",d=J4(i,{network:o.network,owner:l,offerSequence:c.sequence,type:u});d.length&&Y(d.join(" "));let p=c.feeEscrows.map(k=>{let B=a.find(P=>Number(P.fields.OfferSequence)===k.sequence)??Y(`${u==="EscrowFinish"?"Finish":"Cancel"} the ${k.label} fee escrow too (sequence ${k.sequence}); anyone can submit it once the secret is revealed.`),D=J4(B,{network:o.network,owner:l,offerSequence:k.sequence,type:u});return D.length&&Y(`${k.label} fee leg: ${D.join(" ")}`),{f:k,flt:B}}),h=ar(s.total.amount,s.milestones)[r],g={onLedger:!0,network:i.network,txHash:i.hash,ledgerIndex:i.ledgerIndex,checkedAt:i.checkedAt};if(u==="EscrowFinish"){let k=s.milestoneStates[r].state;k==="released"&&Y("This milestone is already recorded as released."),k!=="affirmed"&&Y("The buyer has not accepted this milestone; a finished escrow without acceptance should be disputed.");let B=es(s).milestones[r],D=[await st("EscrowReleased",ve(t.partyId),Gn(n),{contractId:n,milestone:r,amount:h,to:s.sellerId,netToSeller:Qa(B.netUnits,"XRP"),fee:Qa(B.feeUnits,"XRP"),...g})];return p.length&&D.push(await _C(ve(t.partyId),s,B,r,"validated",p.map(({f:P,flt:U})=>({account:P.account,label:P.label,units:Number(P.drops),bps:B.payLegs.find(F=>F.account===P.account)?.bps??0,escrowTxHash:P.txHash,txHash:U.hash,ledgerIndex:U.ledgerIndex,checkedAt:U.checkedAt})),{network:i.network})),D}let w=s.milestoneStates[r].stage,T=!!w&&Date.parse(t.at)>Date.parse(w.holdUntil)&&!s.disputes.some(k=>!k.resolved);return[await st("EscrowRefunded",ve(t.partyId),Gn(n),{contractId:n,milestone:r,amount:h,to:s.buyerId,...g,feeCancels:p.map(({f:k,flt:B})=>({account:k.account,txHash:B.hash})),...T?{expiredHold:!0}:{}})]}async function OC(e,t,n,r,i,o){let a=Ur(e,n);a.buyerId!==t.partyId&&Y("Only the buyer pays a stage."),at(a)!=="ledger-staged"&&Y(`This contract settles on ${at(a)}, not stage-by-stage ledger payments.`);let s=a.milestoneStates[r]??Y("Unknown milestone.");s.state==="released"&&Y("That stage is already paid."),s.state!=="affirmed"&&Y("Accept the stage before paying it (the seller shows the work first)."),a.disputes.some(P=>!P.resolved)&&Y("The contract has an open dispute; an operator rules first.");let c=a.milestoneStates.find(P=>P.state!=="released");c?.index!==r&&Y(`Pay one stage at a time: stage ${(c?.index??0)+1} comes first.`),hE(e,a,r);let{buyer:l,seller:u}=wm(e,a),d=new Set(a.payments.map(P=>P.reference)),p=Vf(a,r,u),h=new Set,g=p.map(P=>{let U=o.find(H=>!h.has(H)&&H.destination===P.account)??Y(`Pay the ${P.label} leg (${Qa(Number(P.units),a.total.currency)} ${Et(a.total.currency)} to ${P.account}) before recording.`);h.add(U),d.has(U.hash)&&Y(`${U.hash} is already recorded on this contract.`);let F=wC(U,{network:i.network,from:l,to:P.account,toLabel:P.label,code:a.total.currency,units:BigInt(P.units),reference:n,index:r});return F.length&&Y(`${P.label} leg: ${F.join(" ")}`),{leg:P,lt:U}}),w=ar(a.total.amount,a.milestones)[r],T=vr(e,t,"marketplace.stage.pay",{amount:w,currency:a.total.currency},a.categoryId),k=es(a).milestones[r],B=g.find(P=>P.leg.role==="seller")??Y("The seller leg is missing."),D=[];for(let{leg:P,lt:U}of g)D.push(await st("PaymentConfirmed",ve(t.partyId),Gn(n),{contractId:n,milestone:r,amount:Qa(Number(P.units),a.total.currency),currency:a.total.currency,rail:"ledger-staged",leg:P.role,to:P.account,reference:U.hash,validated:!0,network:U.network,ledgerIndex:U.ledgerIndex,checkedAt:U.checkedAt}));return D.push(await st("EscrowReleased",ve(t.partyId),Gn(n),{contractId:n,milestone:r,amount:w,currency:a.total.currency,to:a.sellerId,direct:!0,rail:"ledger-staged",netToSeller:Qa(k.netUnits,a.total.currency),fee:Qa(k.feeUnits,a.total.currency),onLedger:!0,network:B.lt.network,txHash:B.lt.hash,ledgerIndex:B.lt.ledgerIndex,checkedAt:B.lt.checkedAt,...T})),k.feeUnits>0&&D.push(await _C(ve(t.partyId),a,k,r,"validated",g.filter(P=>P.leg.role==="fee").map(({leg:P,lt:U})=>({account:P.account,label:P.label,units:Number(P.units),bps:k.payLegs.find(F=>F.account===P.account)?.bps??0,txHash:U.hash,ledgerIndex:U.ledgerIndex,checkedAt:U.checkedAt})),{network:B.lt.network})),D}function qL(e){at(e)!=="ledger-channel"&&Y(`This contract settles on ${at(e)}, not a payment channel.`);let t=e.channel??Y("The buyer has not opened the payment channel yet.");return t.closed&&Y("The channel is closed."),t}async function DC(e,t,n,r,i){let o=Ur(e,n);o.buyerId!==t.partyId&&Y("Only the buyer opens the payment channel."),at(o)!=="ledger-channel"&&Y(`This contract settles on ${at(o)}, not a payment channel.`),o.channel&&Y(`The channel is already open (${o.channel.channelId}).`),(o.state==="cancelled"||o.state==="completed")&&Y(`The contract is ${o.state}.`),o.disputes.some(B=>!B.resolved)&&Y("The contract has an open dispute; an operator rules first.");let{buyer:a,seller:s}=wm(e,o),c=tu(o),l=wL(i,{network:r.network,contractId:n,buyerAccount:a,sellerAccount:s,drops:c.toString()});l.length&&Y(l.join(" ")),o.payments.some(B=>B.reference===i.hash)&&Y(`${i.hash} is already recorded on this contract.`);let u=i.closeTime??i.checkedAt,d=vC(i)??Y("No CancelAfter, so the channel could be held indefinitely.");Date.parse(d)>Date.parse(Wl(u))+864e5&&Y(`CancelAfter is more than ${30} days after opening; holds are limited to a ${30}-day billing cycle.`),Date.parse(d)<=Date.parse(u)&&Y("CancelAfter is not after the channel opened.");let p=o.milestones[0].dueBy,h=new Date(Date.parse(d)-864e5).toISOString().slice(0,10),g={fundedAt:u,stageDueBy:p>h?h:pF.reference),...a.ledgerSettlements.map(F=>F.txHash)]);u.has(i.hash)&&Y(`${i.hash} is already recorded on this contract.`);let d=l.balanceDrops??0n,p=BigInt(s.releasedDrops),h=BigInt(s.capDrops);d>h&&Y(`The channel shows ${d} drops paid, above the cap of ${h}.`);let g=d-p;g<=0n&&Y(`Nothing new to record: the channel has paid ${d} drops and ${p} are already recorded.`);let w=rE(a,p,d);w.netUnits<0&&Y(`This redemption (${g} drops) does not cover the fee due on it (${w.feeUnits} drops); redeem a larger claim.`);let T=new Set,k=w.payLegs.filter(F=>F.units>0).map(F=>{let H=o.find(C=>!T.has(C)&&C.destination===F.account)??Y(`Pay the ${F.label} fee leg (${F.units} drops to ${F.account}) from your account before recording: a channel pays only the seller, so the seller pays the fee.`);T.add(H),u.has(H.hash)&&Y(`${H.hash} is already recorded on this contract.`);let b=wC(H,{network:r.network,from:c,to:F.account,toLabel:F.label,code:"XRP",units:BigInt(F.units),reference:n,index:0});return b.length&&Y(`${F.label} fee leg: ${b.join(" ")}`),{leg:F,lt:H}});T.size!==o.length&&Y("A fee payment matches no fee leg of this redemption.");let B=vr(e,t,"marketplace.channel.settle",null,a.categoryId),D=F=>Number(F)/Ql,P=ve(t.partyId),U=[await st("PaymentConfirmed",P,Gn(n),{contractId:n,milestone:0,amount:D(g),currency:"XRP",rail:"ledger-channel",leg:"seller",to:c,reference:i.hash,validated:!0,network:i.network,ledgerIndex:i.ledgerIndex,checkedAt:i.checkedAt})];for(let{leg:F,lt:H}of k)U.push(await st("PaymentConfirmed",P,Gn(n),{contractId:n,milestone:0,amount:D(F.units),currency:"XRP",rail:"ledger-channel",leg:"fee",paidBy:"seller",to:F.account,reference:H.hash,validated:!0,network:H.network,ledgerIndex:H.ledgerIndex,checkedAt:H.checkedAt}));return U.push(await st("EscrowReleased",P,Gn(n),{contractId:n,milestone:0,amount:D(g),currency:"XRP",to:a.sellerId,direct:!1,rail:"ledger-channel",channelId:s.channelId,balanceDrops:d.toString(),incrementDrops:g.toString(),unitsUsed:nE(a,g),totalUnitsUsed:nE(a,d),netToSeller:D(w.netUnits),fee:D(w.feeUnits),onLedger:!0,network:i.network,txHash:i.hash,ledgerIndex:i.ledgerIndex,checkedAt:i.checkedAt,...B})),w.feeUnits>0&&U.push(await _C(P,a,w,0,"validated",k.map(({leg:F,lt:H})=>({account:F.account,label:F.label,units:F.units,bps:F.bps,txHash:H.hash,ledgerIndex:H.ledgerIndex,checkedAt:H.checkedAt})),{network:i.network,rail:"ledger-channel",incrementDrops:g.toString(),balanceDrops:d.toString(),reference:i.hash})),U}async function bm(e,t,n,r,i){let o=Ur(e,n);t.partyId!==o.buyerId&&t.partyId!==o.sellerId&&Y("Only the parties record the channel closing.");let a=qL(o),s=[];i.network!==r.network&&s.push(`On ${i.network}; this marketplace settles on ${r.network}.`),i.validated||s.push("Not in a validated ledger yet."),i.result!=="tesSUCCESS"&&s.push(`Result ${i.result||"unknown"}, not tesSUCCESS.`),i.type!=="PaymentChannelClaim"&&i.type!=="PaymentChannelFund"&&s.push(`It is a ${i.type}, not a channel transaction.`),String(i.fields.Channel??"").toUpperCase()!==a.channelId.toUpperCase()&&s.push("It is for a different channel."),s.length&&Y(s.join(" "));let c=Kf(i,a.channelId);if(!c||c.kind!=="DeletedNode")return Y(`The ledger has not closed the channel yet${c?" (a buyer's close takes effect after the SettleDelay, or at CancelAfter; submit a close again then)":""}.`);let l=typeof c.fields.Balance=="string"&&/^\d+$/.test(c.fields.Balance)?BigInt(c.fields.Balance):0n,u=BigInt(a.releasedDrops),d=BigInt(a.capDrops);l>u&&Y(`The channel paid ${l} drops but ${u} are recorded: record that redemption first (marketplace.channel.settle${i.type==="PaymentChannelClaim"&&i.account===e.parties.get(o.sellerId)?.xrplAccount?` with ${i.hash}`:""}).`),le.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9\s-]/g," ");function Fue(e){if(e.length<=3)return e;for(let[t,n]of[["ies","y"],["sses","ss"],["ing",""],["ed",""],["es",""],["s",""]])if(e.endsWith(t)&&e.length-t.length>=3)return e.slice(0,-t.length)+n;return e}var an=e=>Jf(e).split(/[\s-]+/).filter(t=>t&&!Bue.has(t)).map(Fue),gE=new Map;for(let e of VL){let t=new Set(e.flatMap(an));for(let n of t)gE.set(n,new Set([...gE.get(n)??[],...t]))}function HL(e){let t=` ${e} `,n=new Set;for(let r=0;r{let n=HL(e),r=HL(t),i=0;for(let o of n)r.has(o)&&i++;return i/(n.size+r.size-i)};function $ue(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;let r=Array.from({length:e.length+1},(i,o)=>[o,...Array(t.length).fill(0)]);for(let i=1;i<=t.length;i++)r[0][i]=i;for(let i=1;i<=e.length;i++){let o=1/0;for(let a=1;a<=t.length;a++){let s=e[i-1]===t[a-1]?0:1;r[i][a]=Math.min(r[i-1][a]+1,r[i][a-1]+1,r[i-1][a-1]+s),i>1&&a>1&&e[i-1]===t[a-2]&&e[i-2]===t[a-1]&&(r[i][a]=Math.min(r[i][a],r[i-2][a-2]+1)),o=Math.min(o,r[i][a])}if(o>n)return n+1}return r[e.length][t.length]}function que(e){let t=n=>{let r=gr(n),i=r?.parent?gr(r.parent):null;return an(`${r?.label??""} ${i?.label??""} ${(r?.examples??[]).join(" ")}`)};return[...e.listings.filter(n=>n.open).map(n=>({kind:"listing",id:n.listingId,title:n.title,categoryId:n.categoryId,fields:[{toks:an(n.title),weight:3},{toks:an(Object.values(n.attributes).join(" ")),weight:2},{toks:an(n.description),weight:1},{toks:t(n.categoryId),weight:.6},{toks:an(`${pb(n)} ${n.kind}`),weight:.8}]})),...e.requests.filter(n=>n.open).map(n=>({kind:"request",id:n.requestId,title:n.title,categoryId:n.categoryId,fields:[{toks:an(n.title),weight:3},{toks:an(Object.values(n.attributes).join(" ")),weight:2},{toks:an(n.description),weight:1},{toks:t(n.categoryId),weight:.6},{toks:an(pb(n)),weight:.8}]})),...[...e.parties.values()].map(n=>({kind:"party",id:n.partyId,title:n.name,fields:[{toks:an(n.name),weight:3},{toks:an(`${n.about} ${n.roles.join(" ")} ${(n.capabilities.equipment??[]).join(" ")}`),weight:1},{toks:n.capabilities.categories.flatMap(t),weight:.6},{toks:an(pb(n)),weight:.8}]})),...e.tokens.map(n=>({kind:"token",id:n.content.tokenId,title:n.content.name,categoryId:n.content.categoryId,fields:[{toks:an(n.content.name),weight:3},{toks:an(n.content.description),weight:1},{toks:t(n.content.categoryId),weight:.6}]}))]}function Hue(e,t){let n=new Map,r=(a,s,c)=>{let l=n.get(a);(!l||l.weighto.includes(` ${Jf(s)} `)))for(let s of a.flatMap(an))r(s,.8,a[0]);for(let a of i){r(a,1,a);for(let s of gE.get(a)??[])s!==a&&r(s,.8,a);if(!t.has(a)&&a.length>=4)for(let s of t){let c=Uue(a,s);if(c>=.45){r(s,.6*c,`${a}\u2248${s}`);continue}let l=a.length>=7?2:1;if(s[0]===a[0]&&s.length>=4){let u=$ue(a,s,l);u<=l&&r(s,.6*(1-u/Math.max(a.length,s.length)),`${a}\u2248${s}`)}}}return n}function ns(e,t,n={}){if(!t.trim())return[];let r=que(e).filter(w=>!n.kinds||n.kinds.includes(w.kind)),i=new Set(r.flatMap(w=>w.fields.flatMap(T=>T.toks))),o=Hue(t,i),a=Jf(t),s=new Set(Eh.filter(w=>a.includes(Jf(w.label))||w.examples.some(T=>Jf(T).split(/\s+/).some(k=>k.length>3&&a.includes(k)))).map(w=>w.id)),c=r.length||1,l=r.map(w=>w.fields.reduce((T,k)=>T+k.toks.length,0)),u=l.reduce((w,T)=>w+T,0)/c||1,d=new Map;for(let w of r)for(let T of new Set(w.fields.flatMap(k=>k.toks)))d.set(T,(d.get(T)??0)+1);let p=1.2,h=.75,g=[];return r.forEach((w,T)=>{let k=0,B=new Set;for(let[D,{weight:P,from:U}]of o){let F=d.get(D);if(!F)continue;let H=Math.log(1+(c-F+.5)/(F+.5)),b=0;for(let C of w.fields)b+=C.weight*C.toks.filter(v=>v===D).length;b&&(k+=P*H*(b*(p+1)/(b+p*(1-h+h*l[T]/u))),B.add(U===D?D:`${U}\u2192${D}`))}w.categoryId&&[...s].some(D=>w.categoryId===D||w.categoryId.startsWith(`${D}/`))&&(k+=.5,B.add(`category:${w.categoryId}`)),k>0&&g.push({kind:w.kind,id:w.id,title:w.title,score:Math.round(k*100)/100,matched:[...B],...w.categoryId?{categoryId:w.categoryId}:{}})}),g.sort((w,T)=>T.score-w.score).slice(0,n.limit??50)}y();var $r={category:.35,distance:.2,quantity:.15,price:.15,timing:.1,reputation:.05},zL=(e,t)=>Math.round((Date.parse(t)-Date.parse(e))/864e5);function NC(e,t){return e===t?1:Ya(e)===Ya(t)?.5:0}function wE(e,t,n){let r=FO(e,t);return r===null?{fit:.3,miles:r}:n!==null&&r>n?{fit:0,miles:r}:{fit:Math.max(0,1-r/Math.max(n??1500,1)),miles:r}}var KL=(e,t)=>{let n=e.reputation.get(t);return n?.average?n.average/5:.6};function jL(e,t,n,r=8){let i=[],o=t.quantity-t.awardedQuantity,a=zL(n,t.neededBy);for(let l of e.listings){if(!l.open||l.remaining<=0||l.sellerId===t.buyerId)continue;let u=NC(l.categoryId,t.categoryId);if(!u)continue;let d=wE(l,t,t.deliveryRadiusMiles);if(!d.fit&&t.deliveryRadiusMiles!==null)continue;let p=l.unit===t.unit?Math.min(1,l.remaining/o):.3,h=!t.maxPricePerUnit||l.unit!==t.unit||l.pricePerUnit.currency!==t.maxPricePerUnit.currency?.6:l.pricePerUnit.amount<=t.maxPricePerUnit.amount?1:Math.max(0,1-(l.pricePerUnit.amount-t.maxPricePerUnit.amount)/t.maxPricePerUnit.amount),g=l.leadDays<=a?1:0,w=$r.category*u+$r.distance*d.fit+$r.quantity*p+$r.price*h+$r.timing*g+$r.reputation*KL(e,l.sellerId);i.push({kind:"listing",id:l.listingId,partyId:l.sellerId,title:l.title,score:w,reasons:[u===1?"Same category":"Related category",d.miles===null?"Distance unknown":`${d.miles} mi away`,l.unit===t.unit?`${l.remaining} ${l.unit} available (need ${o})`:`Sold in ${l.unit}, you asked in ${t.unit}`,h===1?"Within your price":h===.6?"Price not comparable \u2014 ask":"Above your price",g?`Ready in ${l.leadDays} days`:`Needs ${l.leadDays} days; you need it in ${a}`]})}let s=new Set(i.map(l=>l.partyId)),c=gr(t.categoryId)?.typicalLeadDays;for(let l of e.parties.values()){if(l.partyId===t.buyerId||s.has(l.partyId))continue;let u=Math.max(0,...l.capabilities.categories.map(w=>NC(w,t.categoryId))),d=t.allowNewPlanting&&l.capabilities.canPlantNew&&Ya(t.categoryId)==="crops";if(!u&&!d)continue;let p=wE(l,t,t.deliveryRadiusMiles);if(!p.fit&&t.deliveryRadiusMiles!==null)continue;let h=c?a>=c[0]?1:0:.6,g=$r.category*(u||.4)+$r.distance*p.fit+$r.quantity*.5+$r.price*.6+$r.timing*h+$r.reputation*KL(e,l.partyId);i.push({kind:"party",id:l.partyId,partyId:l.partyId,title:l.name,score:g,reasons:[u===1?"Already supplies this":u?"Supplies related products":"Can plant a new crop",p.miles===null?"Distance unknown":`${p.miles} mi away`,l.capabilities.acres?`${l.capabilities.acres} acres`:"Capacity not stated",c?h?`Time to grow (${c[0]}\u2013${c[1]} days typical)`:`Too little time to grow (${a} days; ${c[0]}+ typical)`:"No growing window needed"]})}return i.sort((l,u)=>u.score-l.score).slice(0,r).map(l=>({...l,score:Math.round(l.score*100)/100}))}function LC(e,t,n,r,i=8){let o=[];for(let a of e.requests){if(!a.open||a.buyerId===t.partyId)continue;let s=n.filter(g=>g.sellerId===t.partyId&&g.open),c=Math.max(0,...t.capabilities.categories.map(g=>NC(g,a.categoryId)),...s.map(g=>NC(g.categoryId,a.categoryId))),l=a.allowNewPlanting&&t.capabilities.canPlantNew&&Ya(a.categoryId)==="crops";if(!c&&!l)continue;let u=wE(t,a,a.deliveryRadiusMiles);if(!u.fit&&a.deliveryRadiusMiles!==null)continue;let d=a.maxPricePerUnit?a.maxPricePerUnit.amount*(a.quantity-a.awardedQuantity):null,p=a.offers.filter(g=>!g.withdrawn).length,h=$r.category*(c||.4)+$r.distance*u.fit+.25*(1/(1+p))+.15*(zL(r,a.neededBy)>0?1:0);o.push({kind:"request",id:a.requestId,partyId:a.buyerId,title:a.title,score:Math.round(h*100)/100,reasons:[c===1?"You supply this":c?"Related to what you supply":"New planting welcome",u.miles===null?"Distance unknown":`${u.miles} mi away`,d?`Up to ${d.toLocaleString("en-US")} ${a.maxPricePerUnit.currency}`:"Open price",`${p} bid${p===1?"":"s"} so far`,`Needed by ${a.neededBy}`]})}return o.sort((a,s)=>s.score-a.score).slice(0,i)}y();var BC=jr(Nr(),1);Rl();var XL=async(e,t)=>{let n=new BC.Client(vo[e]);await n.connect();try{return await t(n)}finally{await n.disconnect().catch(()=>{})}},Qf={autofill:(e,t)=>XL(t,async n=>await n.autofill(e)),submit:(e,t)=>XL(t,async n=>{let r=await n.submit(e),i=r.result.engine_result??"";if(i&&!/^(tes|ter|tec)/.test(i))throw new Error(`The ledger refused the transaction: ${i} ${r.result.engine_result_message??""}`.trim())}),read:Th,wait:e=>new Promise(t=>setTimeout(t,e))};function Ki(e){let t=BC.Wallet.fromSeed(e);return{address:t.classicAddress,name:"seed wallet",async signTransaction(n){let r=t.sign(n);return{tx_blob:r.tx_blob,hash:r.hash}}}}async function rs(e,t,n,r=Qf,i=6e4){if(e.address!==t.Account)throw new Error(`The connected wallet is ${e.address}, but this transaction is from ${String(t.Account)}. Connect that account, or update the XRPL account on your profile.`);let o=await r.autofill(t,n);r.approve&&await r.approve(o);let a=await e.signTransaction(o);e.submitsOnSign||await r.submit(a.tx_blob,n);let s=Date.now()+i;for(;;){try{let c=await r.read(n,a.hash);if(c.validated)return c}catch(c){if(!/not found/i.test(c instanceof Error?c.message:""))throw c}if(Date.now()>s)throw new Error(`Submitted ${a.hash} but it was not validated on ${n} within ${Math.round(i/1e3)}s${e.submitsOnSign&&e.name?` \u2014 check ${e.name} is set to ${n}`:""}. Record the hash later.`);await r.wait(2e3)}}async function Cm(e,t,n,r,i=Qf){let o=[];for(let a of t){let s=await rs(e,a,n,i);o.push(s),r?.(o.length,s)}return o}y();qo();var ep=jr(Nr(),1);y();y();qo();y();y();var WL=["@method","@path","@authority","content-digest","cappz-wallet"];async function GL(e){let t="";for(let n of await fm(e))t+=String.fromCharCode(n);return`sha-256=:${btoa(t)}:`}function Vue(e,t){switch(e){case"@method":return t.method.toUpperCase();case"@path":return t.url.pathname;case"@authority":return t.url.host.toLowerCase();default:return t.headers.get(e)}}function YL(e,t){let n=[];for(let r of e.components){let i=Vue(r,t);if(i===null)return null;n.push(`"${r}": ${i}`)}return n.push(`"@signature-params": ${e.raw}`),n.join(` `)}function ZL(e){return{publicKeyHex:e.publicKeyHex,async sign(t){if(e.privateKey)return Fr(new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e.privateKey,TC(zf(t)))));if(e.secretKey)return Fr(Kn.sign(zf(t),e.secretKey));throw new Error("signing key has no private part")}}}var QL="cappz-party",JL=[...WL,QL],Kue=e=>typeof e=="string"?new TextEncoder().encode(e):e??new Uint8Array;async function bE(e,t,n=Date.now()){let r=ZL({publicKeyHex:t.declaration.publicKey.toLowerCase(),secretKey:pa(t.secretKeyHex)}),i=new Headers;i.set("content-digest",await GL(Kue(e.body))),i.set("cappz-wallet",t.declaration.walletAddress),i.set(QL,t.partyId);let o=Fr(crypto.getRandomValues(new Uint8Array(12))),a=`(${JL.map(l=>`"${l}"`).join(" ")});created=${Math.floor(n/1e3)};keyid="${r.publicKeyHex}";alg="ed25519";nonce="${o}"`,s=YL({components:JL,raw:a},{method:e.method,url:new URL(e.url),headers:i}),c=await r.sign(s);return i.set("signature-input",`sig1=${a}`),i.set("signature",`sig1=:${btoa(String.fromCharCode(...pa(c)))}:`),Object.fromEntries(i.entries())}var eB=e=>t=>bE(t,e);var nB="cappz/co-signature",rB=e=>["CAPPZ co-signature v1",`network: ${e.network}`,`contract: ${e.contractId}`,`milestone: ${e.milestone}`,`action: ${e.action}`,`amount-drops: ${e.amountDrops}`,`expires: ${e.expiresAt}`].join(` `),FC=e=>oB(new TextEncoder().encode(e)).toUpperCase();function iB(e,t){return{TransactionType:"AccountSet",Account:e,Fee:"0",Sequence:0,LastLedgerSequence:1,Memos:[{Memo:{MemoType:FC(nB),MemoData:FC(rB(t))}}]}}function CE(e,t,n){let r=[],i;try{i=(0,ep.decode)(e.txBlob)}catch{return["Not an XRPL transaction."]}i.TransactionType!=="AccountSet"&&r.push("A co-signature is an AccountSet."),["SetFlag","ClearFlag","Domain","EmailHash","MessageKey","TransferRate","TickSize","NFTokenMinter"].some(c=>i[c]!==void 0)&&r.push("A co-signature must not change the account."),i.Account!==t&&r.push(`Signed by ${String(i.Account)}, not ${t}.`);let o="";try{o=(0,ep.deriveAddress)(String(i.SigningPubKey??""))}catch{}o!==t&&r.push("Not signed by the account's master key."),(Array.isArray(i.Memos)?i.Memos:[]).some(c=>c.Memo?.MemoType?.toUpperCase()===FC(nB)&&c.Memo?.MemoData?.toUpperCase()===FC(rB(e.terms)))||r.push("The memo is not the co-signature statement for these terms.");let s=!1;try{s=(0,ep.verifySignature)(e.txBlob)}catch{s=!1}return s||r.push("The signature does not verify."),Date.parse(e.terms.expiresAt)>Date.parse(n)||r.push("The co-signature has expired."),r}var fEe=600*1e3;var zue=`cappz-signing-approval/v1 `,jue=new Set(["SigningPubKey","TxnSignature","Signers"]);var oB=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),tB=e=>new Uint8Array((e.match(/../g)??[]).map(t=>parseInt(t,16)));function Xue(e){return Br(Object.fromEntries(Object.entries(e).filter(([t])=>!jue.has(t))))}async function Wue(e){return oB(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Xue(e)))))}async function Gue(e,t,n,r=new Date().toISOString()){let i=[];if(!e?.approval||!e.signature)return["No approval."];e.signature.publicKey.toLowerCase()!==n.toLowerCase()&&i.push("Signed by a key other than the published one.");let o=!1;try{o=Kn.verify(tB(e.signature.value),new TextEncoder().encode(zue+Br(e.approval)),tB(e.signature.publicKey))}catch{o=!1}return o||i.push("The approval signature does not verify."),(e.approval.kind!=="cappz-signing-approval"||e.approval.v!==1)&&i.push("Not a CAPPZ signing approval."),Date.parse(e.approval.expiresAt)<=Date.parse(r)&&i.push("The approval has expired."),await Wue(t)!==e.approval.txHash&&i.push("The transaction differs from the one approved."),i}function aB(e){let t=e.fetcher??fetch;return async n=>{let r,i=`${e.serviceUrl.replace(/\/$/,"")}/${e.network}/authorize`,o=JSON.stringify({contractId:e.contractId,milestone:e.milestone,tx:n,...e.coSignature?{coSignature:e.coSignature}:{}}),a=e.signRequest?await e.signRequest({method:"POST",url:i,body:o}):{};try{r=await t(i,{method:"POST",headers:{"content-type":"application/json",...a},body:o})}catch(l){throw new Error(`The signing-approval service could not be reached (${l.message}); nothing was signed.`)}let s=await r.json().catch(()=>({}));if(!s.approved)throw new Error(`Not approved for signing: ${(s.reasons??[]).map(l=>l.message).join(" ")||s.error||`HTTP ${r.status}`} Nothing was signed.`);let c=await Gue(s,n,e.publicKey);if(c.length)throw new Error(`The approval does not cover this transaction: ${c.join(" ")} Nothing was signed.`);e.onApproved?.(s)}}y();y();y();function Yue(e,t){if(!e?.length||!t?.length)return 1;let n=0,r=0,i=0;for(let o=0;oi.slice());for(let i=0;i<2;i++){let o=Array.from({length:t},(s,c)=>Math.sin(c+1+i)),a=0;for(let s=0;s<300;s++){let c=r.map(u=>u.reduce((d,p,h)=>d+p*o[h],0)),l=Math.hypot(...c)||1;o=c.map(u=>u/l),a=o.reduce((u,d,p)=>u+d*r[p].reduce((h,g,w)=>h+g*o[w],0),0)}n.push({value:a,vector:o});for(let s=0;s[g,0]);let n=e.map(h=>h.map(g=>g*g)),r=n.map(h=>h.reduce((g,w)=>g+w,0)/t),i=r.reduce((h,g)=>h+g,0)/t,o=n.map((h,g)=>h.map((w,T)=>-.5*(w-r[g]-r[T]+i))),[a,s]=Jue(o),c=Math.sqrt(Math.max(0,a.value)),l=Math.sqrt(Math.max(0,s.value)),u=h=>h.reduce((g,w)=>g+w*Math.abs(w),0)<0?-1:1,d=u(a.vector),p=u(s.vector);return a.vector.map((h,g)=>[d*h*c,p*s.vector[g]*l])}function ede(e,t){let n=e.length;if(n<2)return 1;let r=e.reduce((c,l)=>c+l,0)/n,i=t.reduce((c,l)=>c+l,0)/n,o=0,a=0,s=0;for(let c=0;cMath.round(e*1e4)/1e4;function sB(e,t){let n=e.length,r=Array.from({length:n},()=>new Array(n).fill(0));for(let h=0;hh+g*a[w],0)/(o.reduce((h,g)=>h+g*g,0)||1),c=i.map(h=>h[0]),l=i.map(h=>h[1]),u=(Math.min(...c)+Math.max(...c))/2,d=(Math.min(...l)+Math.max(...l))/2,p=Math.max(Math.max(...c)-Math.min(...c),Math.max(...l)-Math.min(...l))||1;return{coords:i.map(h=>({x:vE((h[0]-u)/p),y:vE((h[1]-d)/p)})),mapRadius:h=>vE(h*s/p),fidelity:Math.round(ede(o,a)*100)/100}}var SE=[{id:"problem",name:"Problem",description:"The need, job or pain the offering addresses.",default_weight:.3},{id:"mechanism",name:"Mechanism",description:"How it works: technology, process, materials.",default_weight:.3},{id:"customer",name:"Customer",description:"Who buys and uses it, and where.",default_weight:.2},{id:"model",name:"Business model",description:"Channel, pricing and how it makes money.",default_weight:.2}],tde=Object.fromEntries(SE.map(e=>[e.id,e.default_weight])),nde={top_k:8,min_radius:.02,min_void_separation:.03},AE=SE.map(e=>e.id);function rde(e,t){return`List 24 to 36 EXISTING, real offerings worldwide${t?` (with attention to ${t})`:""} in this space: "${e}". Include products, services and businesses across price points, customers and business models \u2014 incumbents and niche players. Only include things you believe exist; say how you know in "evidence" (a company or product name, a known source, or "general knowledge"). Return ONLY a JSON array, no prose. Each item: {"name": string, "kind": "product"|"service"|"business", "problem": string, "mechanism": string, "customer": string, "model": string, "geography": string, "priceBand": string, "demand": number 1-10, "maturity": number 0-1, "evidence": string}`}var cB=(e,t,n,r)=>{let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(t,i)):r},qr=(e,t=240)=>typeof e=="string"?e.trim().slice(0,t):"",lB=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48);function ide(e){let t=e.indexOf("["),n=e.lastIndexOf("]");if(t<0||n<=t)return[];let r;try{r=JSON.parse(e.slice(t,n+1))}catch{return[]}if(!Array.isArray(r))return[];let i=new Set,o=[];for(let a of r){let s=qr(a.name,120),c=lB(s),l={problem:qr(a.problem),mechanism:qr(a.mechanism),customer:qr(a.customer),model:qr(a.model)};if(!s||!c||i.has(c)||AE.some(d=>!l[d]))continue;i.add(c);let u=a.kind==="service"||a.kind==="business"?a.kind:"product";o.push({id:`g-${c}`,name:s,kind:u,...l,geography:qr(a.geography,80)||"global",priceBand:qr(a.priceBand,60),demand:cB(a.demand,1,10,5),maturity:cB(a.maturity,0,1,.5),evidence:qr(a.evidence,200)||"general knowledge",source:"agent-reported"})}return o}function ode(e,t){return ns(e,t,{kinds:["listing"],limit:20}).map(r=>{let i=e.listings.find(o=>o.listingId===r.id);return{id:`m-${i.listingId}`,name:i.title,kind:i.kind==="service"?"service":"product",problem:`${i.title}. ${i.description}`,mechanism:Object.values(i.attributes).join(", ")||i.description,customer:`buyers in ${i.region}`,model:`${i.kind} at ${i.pricePerUnit.amount} ${i.pricePerUnit.currency}/${i.unit}`,geography:i.region,priceBand:`${i.pricePerUnit.amount} ${i.pricePerUnit.currency}/${i.unit}`,demand:5,maturity:(e.reputation.get(i.sellerId)?.average??3.5)/5,evidence:`CAPPZ marketplace listing ${i.listingId}`,source:"cappz-marketplace"}})}function ade(e,t){let n=[...e].sort((i,o)=>o.weight-i.weight).map(i=>t.get(i.id)).filter(Boolean),r=i=>n[i%n.length];return{mechanism:{from:r(0).name,text:r(0).mechanism},customer:{from:r(1).name,text:r(1).customer},problem:{from:r(n.length>2?2:0).name,text:r(n.length>2?2:0).problem},model:{from:r(1).name,text:r(1).model}}}function sde(e,t){return`These are empty regions ("whitespace") that lacuna found between existing offerings in "${e}". For each, write a concrete new business that would sit in that gap \u2014 combining the bridged facets \u2014 without copying any neighbor. ${JSON.stringify(t)} Return ONLY a JSON array, one item per input in the same order: {"id": string, "title": string (\u2264 70 chars), "summary": string (2 sentences), "whyNow": string, "risks": [string, string], "firstCustomers": string, "validate": [string, string, string] (cheapest tests before spending money)}`}async function uB(e){let{state:t,lacuna:n,interests:r,region:i,ranAt:o,research:a}=e,s={scope:"global",interests:r,ranAt:o,version:n?.version??null,artifactSha256:n?.sha256??null,fidelity:1},c=[],l=null;if(a)try{c=ide(await a(rde(r,i)))}catch(F){l=F instanceof Error?F.message:"agent research failed"}let u=ode(t,r),d=[...c,...u],p={agentReported:c.length,marketplace:u.length,agentModel:a?e.modelLabel??"agent model":null};if(!n)return{...s,engine:"unavailable",corpus:[],concepts:[],sources:p,note:"lacuna not loaded; global discovery needs the in-browser lacuna module."};if(d.length<6)return{...s,engine:"lacuna-wasm",corpus:[],concepts:[],sources:p,note:`Only ${d.length} offerings in this space${l?` (agent research: ${l})`:a?"":" (the agent model is not available, so only marketplace listings were used)"} \u2014 at least 6 are needed to find whitespace. Try broader interests, or ask again.`};let h=d.map(F=>({id:F.id,name:F.name,summary:F.problem,tags:[F.kind,F.source],facets:{problem:F.problem,mechanism:F.mechanism,customer:F.customer,model:F.model},vectors:{},demand_signal:F.demand,quality_signal:Math.max(.1,F.maturity),metadata:null})),g={domain_id:`global-${lB(r)}`,title:`Global market: ${r}`,description:"Existing offerings worldwide in this space.",facets:SE,demand_metric_name:"reported_demand",quality_metric_name:"reported_maturity"},w=n.findVoids(g,h,nde),T=d.map(F=>{let H=n.embed(AE.map(b=>F[b]));return Object.fromEntries(AE.map((b,C)=>[b,H[C]]))}),k=sB([...T,...w.map(F=>F.center)],tde),B=new Map(d.map(F=>[F.id,F])),D=w.map(F=>({v:F,bridge:ade(F.boundary_neighbors.map(H=>({id:H.entity_id,weight:H.simplex_weight})),B)})),P=[];if(a&&D.length)try{let F=await a(sde(r,D.map(C=>({id:C.v.void_id,bridge:C.bridge,neighbors:C.v.boundary_neighbors.map(v=>v.name)})))),H=F.indexOf("["),b=F.lastIndexOf("]");H>=0&&b>H&&(P=JSON.parse(F.slice(H,b+1)))}catch{P=[]}let U=D.map(({v:F,bridge:H},b)=>{let C=P.find(M=>M?.id===F.void_id),v=`${r} ${H.mechanism.text} ${H.customer.text}`,S=ns(t,v,{kinds:["listing"],limit:4}).map(M=>({id:M.id,title:M.title})),A=ns(t,v,{kinds:["request"],limit:4}).map(M=>({id:M.id,title:M.title}));return{id:F.void_id,rank:F.rank,title:qr(C?.title,90)||`New offering between ${F.boundary_neighbors.slice(0,2).map(M=>M.name).join(" and ")}`,summary:qr(C?.summary,400)||`Combine ${H.mechanism.from}'s approach (${H.mechanism.text}) with ${H.customer.from}'s customers (${H.customer.text}), addressing ${H.problem.text.toLowerCase()} with a ${H.model.text.toLowerCase()} model.`,bridge:H,neighbors:F.boundary_neighbors.map(M=>({id:M.entity_id,name:M.name,distance:M.distance,weight:M.simplex_weight})),radius:F.radius,opportunityScore:F.opportunity_score,boundaryDemand:F.boundary_demand,whyNow:qr(C?.whyNow,300)||"Not assessed \u2014 the agent model was not available. Look for what changed recently in cost, technology or regulation for these neighbors.",risks:Array.isArray(C?.risks)?C.risks.map(M=>qr(M,200)).filter(Boolean).slice(0,4):["Unverified gap \u2014 the neighbors are reported, not measured.","Incumbents may already serve it through channels not listed."],firstCustomers:qr(C?.firstCustomers,300)||`People who buy from ${F.boundary_neighbors.map(M=>M.name).slice(0,2).join(" or ")} today.`,validate:Array.isArray(C?.validate)?C.validate.map(M=>qr(M,200)).filter(Boolean).slice(0,5):["Talk to ten people who buy from the neighbors; ask what is missing.","Put up a landing page or a CAPPZ marketplace listing and measure interest before building.","Make one prototype or deliver the service once by hand."],writtenBy:C?"agent":"lacuna",marketplace:{listings:S,requests:A},...k.coords[d.length+b],mapRadius:k.mapRadius(F.radius)}});return{...s,engine:"lacuna-wasm",fidelity:k.fidelity,sources:p,corpus:d.map((F,H)=>({...F,...k.coords[H]})),concepts:U,note:`${w.length} whitespace regions among ${d.length} existing offerings (${c.length} agent-reported, ${u.length} on the CAPPZ marketplace). Agent-reported offerings are a starting map to verify, not facts; concepts are hypotheses to test with customers.${l?` Agent research failed: ${l}.`:""}`}}y();y();var UC="phyto-graph/v1";function dB(e){return e.normalize("NFKD").replace(/[^a-zA-Z0-9/_-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase()}var cde={taxonomy:"taxonomy",property:"properties",instance:"instances"},$C=e=>`${Df(e)}/graph`,lde=(e,t)=>`${$C(e)}/${cde[t.layer]}/${dB(t.id)}`,ude=(e,t)=>`${$C(e)}/edges/${dB(t.id)}`,TE=e=>`${$C(e)}/manifest`,fB=e=>`${$C(e)}/ciphertext`,dde=/^[a-z][a-z0-9-]*:[A-Za-z0-9._/-]+$/;function EE(e){let t=[],n=(s,c,l)=>t.push({code:s,message:c,at:l});if(!e?.manifest)return n("schema","manifest missing"),t;if(e.manifest.version!==UC&&n("schema",`unsupported version ${e.manifest.version}; expected ${UC}`),e.manifest.graphId||n("schema","manifest.graphId required"),e.manifest.graphVersion||n("schema","manifest.graphVersion required"),!Array.isArray(e.nodes)||!Array.isArray(e.edges))return n("schema","nodes and edges must be arrays"),t;let r=new Set;for(let s of e.nodes){(!s.id||!dde.test(s.id))&&n("schema",`invalid node id "${s.id}"`,s.id),r.has(s.id)&&n("duplicate-id",`duplicate node id ${s.id}`,s.id),r.add(s.id),s.label||n("schema",`node ${s.id} missing label`,s.id),(!s.layer||!["taxonomy","property","instance"].includes(s.layer))&&n("schema",`node ${s.id} has invalid layer`,s.id),s.layer==="taxonomy"&&s.class!=="taxon"&&n("layer-violation",`taxonomy node ${s.id} must be class "taxon"`,s.id);let c=s.provenance?.confidence;(typeof c!="number"||c<0||c>1)&&n("bad-confidence",`node ${s.id} confidence must be 0..1`,s.id)}let i=new Set,o=new Map(e.nodes.map(s=>[s.id,s]));for(let s of e.edges){if(s.id||n("schema","edge missing id"),i.has(s.id)&&n("duplicate-id",`duplicate edge id ${s.id}`,s.id),i.add(s.id),o.has(s.from)||n("dangling-ref",`edge ${s.id} from unknown node ${s.from}`,s.id),o.has(s.to)||n("dangling-ref",`edge ${s.id} to unknown node ${s.to}`,s.id),s.kind==="broader"){let l=o.get(s.from),u=o.get(s.to);l&&l.layer!=="taxonomy"&&n("layer-violation",`broader edge ${s.id} must originate in taxonomy`,s.id),u&&u.layer!=="taxonomy"&&n("layer-violation",`broader edge ${s.id} must target taxonomy`,s.id)}let c=s.provenance?.confidence;(typeof c!="number"||c<0||c>1)&&n("bad-confidence",`edge ${s.id} confidence must be 0..1`,s.id)}let a=new Map;for(let s of e.edges.filter(c=>c.kind==="broader"))a.has(s.from)&&n("taxonomy-cycle",`taxon ${s.from} has more than one broader parent`,s.id),a.set(s.from,s.to);for(let s of a.keys()){let c=new Set([s]),l=a.get(s);for(;l;){if(c.has(l)){n("taxonomy-cycle",`taxonomy cycle through ${l}`,l);break}c.add(l),l=a.get(l)}}return t}function pB(e){return e.length===0}var fde=new TextEncoder;function ha(e){if(e===null)return"null";if(Array.isArray(e))return`[${e.map(ha).join(",")}]`;if(typeof e=="object"){let t=e;return`{${Object.keys(t).filter(r=>t[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${ha(t[r])}`).join(",")}}`}if(typeof e=="number"&&!Number.isFinite(e))throw new Error("non-finite number");return JSON.stringify(e??null)}async function au(e){let t=typeof e=="string"?fde.encode(e):e,n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function kE(e,t){return au(`${e} ${t}`)}async function pde(e,t){let n=lde(e,t),r=ha(t);return{hdPath:n,payload:r,leafHash:await kE(n,r),kind:"node",refId:t.id}}async function yde(e,t){let n=ude(e,t),r=ha(t);return{hdPath:n,payload:r,leafHash:await kE(n,r),kind:"edge",refId:t.id}}async function hde(e){if(e.length===0)return au("phyto-graph/empty");let t=[...e].sort();for(;t.length>1;){let n=[];for(let r=0;rl.leafHash)),o={...e.manifest,merkleRoot:i,nodeCount:e.nodes.length,edgeCount:e.edges.length},a=TE(t),s=ha(o),c={hdPath:a,payload:s,leafHash:await kE(a,s),kind:"manifest",refId:n};return{graphId:n,leaves:r,manifestLeaf:c,merkleRoot:i}}var Hr=e=>{throw new To(e)},tp=(e,t,n,r)=>ua.create({eventType:e,sourceAddress:t,targetAddress:n,payload:r});async function yB(e,t,n,r){let i=e.parties.get(t.partyId)??Hr("Set up your marketplace profile first.");return[await tp("ContentAmended",ve(i.partyId),ve(i.partyId),{contentClass:"party",profile:{...i,encryptionKey:n}}),await tp("ContentCreated",ve(i.partyId),`${ve(i.partyId)}/keys/box`,{contentClass:"party-box-key",partyId:i.partyId,publicKey:n,sealedPrivate:r})]}async function hB(e,t,n,r){let i=e.parties.get(t.partyId)??Hr("Set up your marketplace profile first.");i.encryptionKey||Hr("Create your encryption key first (profile \u2192 encryption key); buyers receive the graph key sealed by it.");let o=EE(r);pB(o)||Hr(`The graph does not validate: ${o.slice(0,3).map(p=>p.message).join(" \xB7 ")}`);let a=await _E(r,n.listingId),s=JSON.parse(a.manifestLeaf.payload),c=await xO(),l=await MO(c,ha(r)),u=await au(ha(l)),d={...n,categoryId:"digital",unit:"license",attributes:{...n.attributes,format:`${UC}, encrypted; key sealed to the buyer`},knowledge:{graphId:s.graphId,graphVersion:s.graphVersion,merkleRoot:a.merkleRoot,nodeCount:s.nodeCount,edgeCount:s.edgeCount}};return[...await ts(e,t,d),await tp("ContentCreated",ve(t.partyId),TE(n.listingId),{contentClass:"graph-manifest",listingId:n.listingId,manifest:s}),await tp("ContentCreated",ve(t.partyId),fB(n.listingId),{contentClass:"graph-ciphertext",listingId:n.listingId,cipher:l,ciphertextHash:u,sellerKeyBox:await lf(i.encryptionKey,{listingId:n.listingId,contentKey:c})})]}async function mB(e,t,n){let r=e.graphs.get(t)??Hr("That listing has no graph.");return(await uf(n,r.sellerKeyBox)).contentKey}async function gB(e,t,n,r){let i=e.contracts.find(d=>d.contractId===n)??Hr("Unknown contract.");i.sellerId!==t.partyId&&Hr("Only the seller delivers access.");let o=i.source.kind==="listing"?i.source.listingId:"";e.graphs.has(o)||Hr("This contract is not for a knowledge graph.");let a=i.milestones.findIndex(d=>d.delivery);a<0&&Hr("The contract has no delivery milestone.");let s=i.milestoneStates[a].state;(s==="affirmed"||s==="released")&&Hr("The buyer already accepted delivery."),i.escrow.balance<=0&&Hr("Wait for the buyer to fund escrow before delivering the key.");let c=e.parties.get(i.buyerId);c?.encryptionKey||Hr("The buyer has not created an encryption key yet; ask them to (profile \u2192 encryption key).");let l=await lf(c.encryptionKey,{listingId:o,contentKey:r}),u=await au(ha(l));return[await tp("AccessKeyDelivered",ve(t.partyId),Rf(n,a),{contractId:n,milestone:a,listingId:o,sealed:l}),await tp("MilestoneEvidenced",ve(t.partyId),Rf(n,a),{contractId:n,milestone:a,kind:"document",hash:u,note:"Graph access key sealed to the buyer; verify the Merkle root before accepting."})]}async function wB(e,t,n){let r=(e.accessDeliveries.get(t)??[]).at(-1)??Hr("No access key delivered yet.");return mde(e,r.listingId,r.sealed,n)}async function mde(e,t,n,r){let i=e.graphs.get(t)??Hr("That listing has no graph."),{contentKey:o}=await uf(r,n),a=[];await au(ha(i.cipher))!==i.ciphertextHash&&a.push("Ciphertext does not match its published hash.");let s=JSON.parse(await OO(o,i.cipher)),c=EE(s);c.length&&a.push(`Graph has ${c.length} validation errors.`);let l=await _E(s,t);return l.merkleRoot!==i.manifest.merkleRoot&&a.push("Merkle root differs from the published manifest: this is not the graph that was listed."),{bundle:s,manifest:i.manifest,verified:a.length===0,derivedRoot:l.merkleRoot,problems:a}}y();function bB(e){let t=new Map(e.nodes.map(i=>[i.id,i])),n=new Map,r=new Map;for(let i of e.edges)(n.get(i.from)??n.set(i.from,[]).get(i.from)).push(i),(r.get(i.to)??r.set(i.to,[]).get(i.to)).push(i);return{bundle:e,byId:t,out:n,inc:r}}function CB(e,t,n=12){let r=new Set(an(t));return r.size?e.bundle.nodes.map(i=>{let o=an(i.label),a=an(`${i.body??""} ${Object.values(i.props).join(" ")} ${Object.values(i.context).join(" ")} ${i.id.replace(/[:/]/g," ")}`),s=3*o.filter(c=>r.has(c)).length+a.filter(c=>r.has(c)).length;return{node:i,score:s}}).filter(i=>i.score>0).sort((i,o)=>o.score-i.score).slice(0,n):[]}function vB(e,t,n=1){let r=new Set([t]),i=new Map,o=[t];for(let a=0;ae.byId.get(a)).filter(Boolean),edges:[...i.values()]}}var gde=(e,t)=>{let n=Object.keys(e).filter(i=>e[i]!==void 0&&e[i]!=="");return n.length?.5+.5*(n.filter(i=>t[i]===void 0||String(t[i]).toLowerCase()===String(e[i]).toLowerCase()).length/n.length):1};function AB(e,t,n={}){let r=e.bundle.nodes.filter(a=>a.layer==="taxonomy"&&a.id.startsWith("taxon:symptom")),i=new Map;for(let a of t){let s=new Set(an(a)),c=r.map(l=>({n:l,hit:an(`${l.label} ${l.id.replace(/[:/]/g," ")} ${l.body??""}`).filter(u=>s.has(u)).length})).filter(l=>l.hit>0).sort((l,u)=>u.hit-l.hit)[0];c&&i.set(c.n.id,c.n)}let o=new Map;for(let a of i.values())for(let s of e.out.get(a.id)??[]){if(s.kind!=="symptom-of")continue;let c=e.byId.get(s.to);if(!c)continue;let l=gde(n,{...c.context,...s.context}),u=o.get(c.id)??{condition:c,score:0,evidence:[],causes:[],treatments:[],contextMatch:l};u.score+=s.provenance.confidence*(s.weight??1)*l,u.evidence.push({symptom:a,edge:s}),u.contextMatch=Math.min(u.contextMatch,l),o.set(c.id,u)}for(let a of o.values()){let s=e.out.get(a.condition.id)??[];a.causes=s.filter(c=>c.kind==="caused-by").map(c=>e.byId.get(c.to)).filter(Boolean),a.treatments=s.filter(c=>c.kind==="treated-by").map(c=>{let l=e.byId.get(c.to),u=[...e.out.get(c.to)??[]].filter(p=>p.kind==="contraindicates"||p.kind==="has-property").map(p=>e.byId.get(p.to)).filter(Boolean),d=(e.out.get(c.to)??[]).filter(p=>p.kind==="requires").map(p=>e.byId.get(p.to)).filter(Boolean);return{treatment:l,confidence:c.provenance.confidence,cautions:u,requires:d}}).filter(c=>c.treatment).sort((c,l)=>l.confidence-c.confidence),a.score=Math.round(a.score/Math.max(1,t.length)*1e3)/1e3}return{matchedSymptoms:[...i.values()],candidates:[...o.values()].sort((a,s)=>s.score-a.score)}}y();var it=e=>{throw new To(e)},vm=(e,t,n,r)=>ua.create({eventType:e,sourceAddress:t,targetAddress:n,payload:r}),qC=e=>`${gn}/securities/${e}`,wde=e=>`${ve(e)}/eligibility`,IE={"reg-d-506c":{label:"Regulation D, Rule 506(c)",summary:"General solicitation allowed; every purchaser must be an accredited investor whose status the issuer has taken reasonable steps to verify. Form D within 15 days of first sale. Securities are restricted (Rule 144 holding period).",requiresEligibility:!0,subscribeHere:!0,defaultLockupDays:365,maxRaise:null},"reg-cf":{label:"Regulation Crowdfunding",summary:"Offered only through an SEC-registered funding portal or broker-dealer, with Form C disclosures and per-investor limits; capped at $5M in 12 months. CAPPZ lists the offering and links to the portal \u2014 subscriptions happen there.",requiresEligibility:!1,subscribeHere:!1,defaultLockupDays:365,maxRaise:5e6}};var SB=(e,t)=>Date.parse(e)>Date.parse(t);function TB(e,t,n){let r=e.eligibility.get(t);return r&&SB(r.expiresAt,n)?r:null}var bde=102;function Cde(e,t){let n=JSON.stringify({t:e.name.slice(0,40),ex:e.exemption,id:e.offeringId,lock:e.lockupDays,docs:e.documents.map(r=>r.hash.slice(0,16))});return{TransactionType:"MPTokenIssuanceCreate",Account:e.issuerAccount,AssetScale:0,MaximumAmount:String(e.units),Flags:bde,MPTokenMetadata:Array.from(new TextEncoder().encode(n),r=>r.toString(16).padStart(2,"0")).join("").toUpperCase(),_network:t}}var vde=(e,t,n="")=>({TransactionType:"MPTokenAuthorize",Account:e,Holder:t,MPTokenIssuanceID:n});async function EB(e,t,n,r,i){return e.parties.has(i.partyId)||it("Unknown party."),n&&n===i.partyId&&it("Investors cannot attest their own eligibility."),/^[0-9a-f]{64}$/.test(i.evidenceHash)||it("Reference the verification evidence by its sha256 hash; the documents stay with the verifier."),SB(i.expiresAt,r)||it("The attestation must expire in the future."),Date.parse(i.expiresAt)-Date.parse(r)>366*864e5&&it("Re-verify at least yearly: expiry must be within a year."),[await vm("PermissionGranted",t,wde(i.partyId),{contentClass:"investor-eligibility",attestation:{...i,by:t,at:r}})]}async function kB(e,t,n){let r=e.parties.get(t.partyId)??it("Set up your marketplace profile first.");n.issuerId!==t.partyId&&it("You can only declare offerings as yourself."),r.kind==="agent"&&it("An agent cannot issue securities; its accountable principal must."),e.offerings.some(o=>o.offeringId===n.offeringId)&&it("Offering already declared.");let i=IE[n.exemption]??it("Choose an exemption.");return(!n.name.trim()||!(n.units>0&&Number.isInteger(n.units))||!(n.pricePerUnit.amount>0))&&it("Name, whole-number units and a price are required."),i.maxRaise!==null&&n.units*n.pricePerUnit.amount>i.maxRaise&&it(`${i.label} is capped at $${i.maxRaise.toLocaleString("en-US")} in 12 months.`),(!n.documents.length||n.documents.some(o=>!/^[0-9a-f]{64}$/.test(o.hash)))&&it("Attach the offering documents by sha256 hash (offering memorandum or Form C, subscription agreement)."),n.exemption==="reg-cf"&&!/^https:\/\//.test(n.portalUrl??"")&&it("Regulation Crowdfunding offerings must link to the registered funding portal (https)."),n.lockupDaysc.offeringId===r)??it("Unknown offering.");a.approval&&it("Already approved."),o.trim()||it("Record the review: who reviewed the documents and on what basis.");let s=i.network!=="mainnet";return[await vm("SecurityOfferingApproved",t,qC(r),{offeringId:r,by:t,at:n,network:i.network,rehearsal:s,note:o,preparedIssuance:Cde(a,i.network)})]}async function IB(e,t,n,r){let i=e.offerings.find(p=>p.offeringId===n)??it("Unknown offering."),o=IE[i.exemption];o.subscribeHere||it(`Subscriptions for this offering happen on its funding portal: ${i.portalUrl}`),i.approval||it("This offering has not been approved by compliance yet.");let a=e.parties.get(t.partyId)??it("Set up your marketplace profile first.");a.partyId===i.issuerId&&it("The issuer cannot subscribe to its own offering."),o.requiresEligibility&&!TB(e,t.partyId,t.at)&&it("Only verified accredited investors can subscribe (Rule 506(c)). Ask a compliance operator to verify you."),Number.isInteger(r)&&r>=i.minUnits||it(`Subscribe for at least ${i.minUnits} whole units.`);let s=i.subscriptions.reduce((p,h)=>p+h.units,0);s+r>i.units&&it(`Only ${i.units-s} units remain.`),a.xrplAccount||it("Add your XRPL account to your profile: the issuer authorizes it to hold the token.");let c=`${n}-s${i.subscriptions.length+1}`,l={amount:r*i.pricePerUnit.amount,currency:i.pricePerUnit.currency},u=bC(e.fees,"securities");return iL(u,l).netUnits<0&&it("The placement fee would exceed this subscription; subscribe for more units."),[await vm("SecuritySubscribed",ve(t.partyId),`${qC(n)}/subscriptions/${c}`,{offeringId:n,subscriptionId:c,investorId:t.partyId,units:r,amount:l,fees:u,eligibilityAt:t.at})]}async function PB(e,t,n,r,i){let o=e.offerings.find(d=>d.offeringId===n)??it("Unknown offering."),a=o.holdings[t.partyId]??[],s=a.filter(d=>Date.parse(d.since)+o.lockupDays*864e5<=Date.parse(t.at)).reduce((d,p)=>d+p.units,0),c=a.reduce((d,p)=>d+p.units,0);Number.isInteger(i)&&i>0||it("Transfer whole units."),i>c&&it("Not enough units."),i>s&&it(`Only ${s} of your ${c} units are past the ${o.lockupDays}-day lock-up.`);let l=e.parties.get(r)??it("Unknown recipient.");IE[o.exemption].requiresEligibility&&!TB(e,r,t.at)&&it("The recipient is not a verified accredited investor.");let u=l.xrplAccount??it("The recipient has no XRPL account on their profile.");return[await vm("SecurityTransferred",ve(t.partyId),qC(n),{offeringId:n,from:t.partyId,to:r,units:i,preparedAuthorization:vde(o.issuerAccount,u)})]}function xB(e,t,n){let r=e.payload;switch(e.eventType){case"PermissionGranted":if(r.contentClass==="investor-eligibility"){let i=r.attestation;n.set(i.partyId,i)}break;case"PermissionRevoked":r.contentClass==="investor-eligibility"&&n.delete(String(r.partyId));break;case"SecurityOfferingDeclared":{let i=r.offering;t.set(i.offeringId,{...i,declaredAt:e.timestamp,approval:null,subscriptions:[],holdings:{},issued:0});break}case"SecurityOfferingApproved":{let i=t.get(String(r.offeringId));i&&(i.approval={by:String(r.by),at:e.timestamp,network:r.network,rehearsal:r.rehearsal===!0,note:String(r.note??"")});break}case"SecuritySubscribed":t.get(String(r.offeringId))?.subscriptions.push({subscriptionId:String(r.subscriptionId),investorId:String(r.investorId),units:Number(r.units),at:e.timestamp,allocated:!1,amount:r.amount,fees:r.fees??null,feeCharged:null});break;case"FeeCharged":{let i=r.subscriptionId?t.get(String(r.offeringId))?.subscriptions.find(o=>o.subscriptionId===r.subscriptionId):void 0;i&&(i.feeCharged={feeUnits:Number(r.feeUnits),currency:r.currency,settlement:r.settlement,owed:r.owed??[],collector:r.collector??null,...r.reference?{reference:String(r.reference)}:{}});break}case"SecurityAllocated":{let i=t.get(String(r.offeringId)),o=i?.subscriptions.find(a=>a.subscriptionId===r.subscriptionId);i&&o&&(o.allocated=!0,(i.holdings[o.investorId]??=[]).push({units:o.units,since:e.timestamp}),i.issued+=o.units);break}case"SecurityTransferred":{let i=t.get(String(r.offeringId));if(!i)break;let o=Number(r.units),a=i.holdings[String(r.from)]??[];for(let s of a){let c=Math.min(s.units,o);if(s.units-=c,o-=c,!o)break}i.holdings[String(r.from)]=a.filter(s=>s.units>0),(i.holdings[String(r.to)]??=[]).push({units:Number(r.units),since:e.timestamp});break}}}y();var np=`pub:${oC}`,HC=["mainnet","testnet","devnet"],PE=e=>e==="testnet"?np:`${np}#${e}`,Ade=`${gn}/operators/`,MB=`${gn}/processors/stripe`,OB="processor:stripe",RB=e=>la(`cappz-marketplace-author|${e}`);async function NB(e,t,n,r,i=np){if(!t.length)return;let o=await Promise.all(t.map(async(s,c)=>{let l=await la(JSON.stringify(s));return{block_hash:l,previous_hash:"",merkle_root:l,block_number:c,transaction_count:1,timestamp:s.timestamp,query_hash:i,hd_address:s.targetAddress,transactions:{type:"public_market_tx",eventType:s.eventType,txId:s.txId},anchor_block:{publicLog:!0},metadata:{publicTx:{tx:s,author:n,actingParty:r}}}})),{error:a}=await e.insert(o);if(a)throw new Error(`Could not publish to the shared market (nothing was saved): ${a.message}`)}var DB=1e3;async function LB(e,t){let n=[],r=t;for(let i=0;i<50;i++){let{data:o,error:a}=await e.select(r,DB);if(a)throw new Error(`Could not read the shared market: ${a.message}`);let s=o??[];for(let c of s){let l=c.metadata?.publicTx;l?.tx?.txId&&typeof l.author=="string"&&n.push({tx:l.tx,author:l.author,actingParty:l.actingParty??null,receivedAt:c.created_at})}if(s.lengtha.receivedAt.localeCompare(s.receivedAt));for(let a of o){if(n.has(a.tx.txId))continue;n.add(a.tx.txId);let s=l=>i.push({txId:a.tx.txId,eventType:a.tx.eventType,reason:l});if(a.tx.sourceAddress.startsWith(Ade)){r.push(a.tx);continue}if(a.tx.sourceAddress===MB||a.author===OB){a.author===OB&&a.tx.sourceAddress===MB&&a.tx.eventType==="PaymentConfirmed"?r.push(a.tx):s("claims to be the payment processor");continue}if(!a.actingParty){s("no acting party");continue}if(a.tx.sourceAddress!==ve(a.actingParty)){s(`written for ${a.actingParty} but sourced elsewhere`);continue}let c=t.get(a.actingParty);if(c&&c!==a.author){s(`party ${a.actingParty} belongs to another account`);continue}c||t.set(a.actingParty,a.author),r.push(a.tx)}return{accepted:r,rejected:i,owners:t}}var je=(e,t=!0)=>({type:"string",description:e,required:t}),Eo=(e,t=!0)=>({type:"number",description:e,required:t}),Am=(e,t=!0)=>({type:"object",description:e,required:t}),VC=[{verb:"marketplace.state.read",summary:"Read open listings, open requests, your contracts (each with the fee terms it formed with), token balances and the fee schedule in force.",input:{},writes:!1},{verb:"marketplace.assets.list",summary:"Payment assets you can price and pay in on this network (XRP, CAPPZ, RLUSD as USD-tokenZ/1, USD by card), each with its rail, issuer and why one is unavailable; plus how to fund a wallet (exchange instructions, never a provider integration).",input:{},writes:!1},{verb:"marketplace.match.suppliers",summary:"Rank suppliers (listings and capable parties) for a request, with reasons.",input:{requestId:je("Request id")},writes:!1},{verb:"marketplace.match.demand",summary:"Rank open requests your party could fill, with reasons.",input:{},writes:!1},{verb:"marketplace.search",summary:"Ranked search over listings, requests, parties and tokens (synonyms, typos, categories); each hit says which terms matched.",input:{query:je("What to look for"),kinds:{type:"array",description:"listing | request | party | token",required:!1}},writes:!1},{verb:"marketplace.discovery.global",summary:"Global whitespace: existing offerings worldwide (from your research function, labelled agent-reported) plus CAPPZ listings (verified), voids found by lacuna. Needs deps.lacuna; deps.research optional.",input:{interests:je("The space to explore"),region:je("Region to emphasize",!1)},writes:!1},{verb:"marketplace.knowledge.query",summary:"Open a purchased knowledge graph with your box key (deps.boxPrivateKey, used in your process only), verify its Merkle root, then search / walk / diagnose.",input:{contractId:je("Contract for the graph license"),symptoms:{type:"array",description:"Observed symptoms (diagnose)",required:!1},query:je("Search text",!1),nodeId:je("Walk from this node",!1),depth:Eo("Walk depth \u2264 3",!1)},writes:!1},{verb:"marketplace.party.profile",summary:"Create or update your party profile (kind agent requires a principal or governance address).",input:{profile:Am("PartyProfile")},writes:!0},{verb:"marketplace.listing.publish",summary:"Publish or amend a listing. metered: true (XRP only) sells metered use \u2014 unit is the metered unit, an order\u2019s quantity is its cap, paid through a ledger payment channel.",input:{listing:Am("ListingContent")},writes:!0},{verb:"marketplace.order.place",summary:"Buy from a listing; forms a contract.",input:{listingId:je("Listing id"),quantity:Eo("Quantity in the listing unit"),evaluatorId:je("Optional party who may accept milestones besides you (never the seller)",!1)},writes:!0},{verb:"marketplace.contract.subcontract",summary:"Seller of a contract: hand part of its work to another party as a child contract (same asset and rail; within the parent's unreleased value; each stage serves a parent milestone and is due by it). You are the child's buyer and fund each stage only after the parent milestone it serves is released to you. Agents need a mandate covering this verb and the child's value; fees apply to the child like any contract.",input:{parentContractId:je("Your parent contract id (you are its seller)"),subcontractorId:je("Party id of the subcontractor"),title:je("What the subcontractor delivers"),quantity:Eo("Quantity"),pricePerUnit:Am("Money { amount, currency } in the parent's asset"),serves:Eo("Parent milestone index the work serves (one stage due with it)",!1),milestones:{type:"array",description:"Or the stages: [{ label, share, dueBy, evidence, delivery, servesMilestone }]",required:!1},unit:je("Unit (default: the parent's)",!1),evaluatorId:je("Optional evaluator for the child",!1)},writes:!0},{verb:"marketplace.request.post",summary:"Request supply, including crops that do not exist yet (allowNewPlanting).",input:{request:Am("SupplyRequestContent")},writes:!0},{verb:"marketplace.offer.submit",summary:"Bid on a request (with a production plan for new plantings).",input:{offer:Am("SupplyOfferContent")},writes:!0},{verb:"marketplace.offer.award",summary:"Award a bid (all or part).",input:{requestId:je("Request id"),offerId:je("Offer id"),quantity:Eo("Quantity to award",!1),evaluatorId:je("Optional party who may accept milestones besides you (never the seller)",!1)},writes:!0},{verb:"marketplace.escrow.fund",summary:"USD contracts: record a payment reference. XRP contracts: pass the validated EscrowCreate hashes (one per leg \u2014 the seller net and each fee recipient \u2014 all under the milestone condition, prepared with settlement.prepareMilestoneEscrows); they are read from the ledger (deps.fetchLedgerTx) and must match amount, accounts, condition and memo.",input:{contractId:je("Contract id"),amount:Eo("USD: amount to fund",!1),reference:je("USD: payment reference",!1),escrows:{type:"array",description:"XRP: [{ milestone, txHash, condition }]",required:!1}},writes:!0},{verb:"marketplace.escrow.ledger-settle",summary:"Record a validated EscrowFinish (release) or EscrowCancel (refund) for an XRP milestone; every fee leg escrow must be finished (or cancelled) too.",input:{contractId:je("Contract id"),milestone:Eo("Milestone index"),txHash:je("EscrowFinish / EscrowCancel hash for the seller leg"),feeTxHashes:{type:"array",description:"EscrowFinish / EscrowCancel hashes for the fee legs",required:!1}},writes:!0},{verb:"marketplace.access.deliver",summary:"Seller of a knowledge graph: seal its content key to the buyer (uses deps.boxPrivateKey locally).",input:{contractId:je("Contract id")},writes:!0},{verb:"marketplace.milestone.evidence",summary:"Submit milestone evidence by sha256 hash.",input:{contractId:je("Contract id"),milestone:Eo("Milestone index"),kind:je("photo | document | inspection | sensor | delivery-receipt"),hash:je("sha256 hex of the evidence file"),note:je("Note",!1)},writes:!0},{verb:"marketplace.stage.pay",summary:"CAPPZ and RLUSD (USD-tokenZ) deals: record an accepted stage you paid directly on the ledger \u2014 one validated Payment per leg (seller net, fee legs), prepared with settlement.prepareStagePayments; each is read from the ledger (deps.fetchLedgerTx) and must match amount, currency, issuer, destination and memo.",input:{contractId:je("Contract id"),milestone:Eo("Milestone index"),txHashes:{type:"array",description:"Payment hashes, one per leg",required:!0}},writes:!0},{verb:"marketplace.channel.open",summary:"Metered XRP deals (listing metered): record the payment channel you opened for the cap \u2014 a validated PaymentChannelCreate prepared with settlement.prepareChannelCreate (to the seller, Amount = cap in drops, CancelAfter within 30 days, your claim public key, contract memo), read from the ledger (deps.fetchLedgerTx). Then sign claims off the ledger as you use the service (settlement.signChannelClaim, cumulative drops) and give them to the seller.",input:{contractId:je("Contract id"),txHash:je("PaymentChannelCreate hash")},writes:!0},{verb:"marketplace.channel.settle",summary:"Seller of a metered deal: record a claim you redeemed on the ledger (validated PaymentChannelClaim from your account; the channel balance in its metadata is the cumulative amount paid) plus the fee Payments you made from your account for the increment (settlement.prepareChannelFeePayments) \u2014 a channel pays only the seller, so the seller pays the fee legs.",input:{contractId:je("Contract id"),txHash:je("PaymentChannelClaim hash"),feeTxHashes:{type:"array",description:"Fee Payment hashes, one per fee leg (none when no fee is due)",required:!1}},writes:!0},{verb:"marketplace.channel.close",summary:"Either party of a metered deal: record the channel closing \u2014 a validated channel transaction whose metadata shows the channel deleted (the seller's tfClose claim, or a close after SettleDelay or CancelAfter). The unused remainder is recorded as returned to the buyer and the contract completes.",input:{contractId:je("Contract id"),txHash:je("Hash of the transaction that closed the channel")},writes:!0},{verb:"marketplace.milestone.affirm",summary:"Accept a milestone or delivery (the buyer, or the evaluator named in the contract; the buyer still pays).",input:{contractId:je("Contract id"),milestone:Eo("Milestone index")},writes:!0},{verb:"marketplace.escrow.release",summary:"Release escrow for an accepted milestone.",input:{contractId:je("Contract id"),milestone:Eo("Milestone index")},writes:!0},{verb:"marketplace.token.transfer",summary:"Transfer receipt tokens.",input:{tokenId:je("Token id"),to:je("Recipient party id"),amount:{type:"integer",description:"Whole tokens",required:!0}},writes:!0},{verb:"marketplace.security.subscribe",summary:"Subscribe to an approved offering. Rule 506(c) requires your party (its principal) to be a verified accredited investor.",input:{offeringId:je("Offering id"),units:{type:"integer",description:"Whole units",required:!0}},writes:!0},{verb:"marketplace.security.transfer",summary:"Transfer security units after lock-up to an eligible holder.",input:{offeringId:je("Offering id"),to:je("Recipient party id"),units:{type:"integer",description:"Whole units",required:!0}},writes:!0}],Ar=class extends Error{};async function FB(e,t,n,r,i={}){let o=VC.find(c=>c.verb===n);if(!o)throw new Ar(`Unknown or unsupported operation ${n}.`);for(let[c,l]of Object.entries(o.input))if(l.required&&(r[c]===void 0||r[c]===null||r[c]===""))throw new Ar(`${n}: missing ${c} (${l.description}).`);let a=c=>String(r[c]),s=c=>Number(r[c]);switch(n){case"marketplace.state.read":return{data:{listings:e.listings.filter(c=>c.open),requests:e.requests.filter(c=>c.open),contracts:e.contracts.filter(c=>c.buyerId===t.partyId||c.sellerId===t.partyId||c.evaluatorId===t.partyId),tokens:e.tokens.map(c=>({tokenId:c.content.tokenId,name:c.content.name,balance:c.balances[t.partyId]??0})).filter(c=>c.balance>0),mandates:e.mandates.filter(c=>c.agentPartyId===t.partyId),fees:e.fees},txs:[]};case"marketplace.assets.list":{let c=(i.policy??fa([])).network;return{data:{network:c,assets:Nf.map(l=>{let u=da(l.code,c);return{code:l.code,label:l.label,address:l.mdmAddress,kind:l.kind,rails:l.rails,availability:u.state,...u.state==="available"?{token:u.token}:{reason:u.reason}}}),rails:F4.map(l=>({id:l.id,address:l.mdmAddress,label:l.label,confirmedBy:l.confirmedBy,holdLimitDays:l.holdLimitDays,description:l.description})),funding:So({network:c,currency:"XRP",amount:0,accountExists:!1}).steps},txs:[]}}case"marketplace.stage.pay":{if(!i.fetchLedgerTx)throw new Ar("Provide deps.fetchLedgerTx to read the ledger.");let c=i.policy??fa([]),l=await Promise.all((r.txHashes??[]).map(u=>i.fetchLedgerTx(c.network,String(u))));return{txs:await OC(e,t,a("contractId"),s("milestone"),c,l)}}case"marketplace.channel.open":case"marketplace.channel.settle":case"marketplace.channel.close":{if(!i.fetchLedgerTx)throw new Ar("Provide deps.fetchLedgerTx to read the ledger.");let c=i.policy??fa([]),l=await i.fetchLedgerTx(c.network,a("txHash"));if(n==="marketplace.channel.open")return{txs:await DC(e,t,a("contractId"),c,l)};if(n==="marketplace.channel.close")return{txs:await bm(e,t,a("contractId"),c,l)};let u=await Promise.all((r.feeTxHashes??[]).map(d=>i.fetchLedgerTx(c.network,String(d))));return{txs:await RC(e,t,a("contractId"),c,l,u)}}case"marketplace.match.suppliers":{let c=e.requests.find(l=>l.requestId===a("requestId"));if(!c)throw new Ar("Unknown request.");return{data:jL(e,c,t.at),txs:[]}}case"marketplace.match.demand":{let c=e.parties.get(t.partyId);if(!c)throw new Ar("Create a profile first.");return{data:LC(e,c,e.listings,t.at),txs:[]}}case"marketplace.search":return{data:ns(e,a("query"),Array.isArray(r.kinds)?{kinds:r.kinds}:{}),txs:[]};case"marketplace.discovery.global":return{data:await uB({state:e,lacuna:i.lacuna??null,interests:a("interests"),region:r.region?a("region"):null,ranAt:t.at,research:i.research??null}),txs:[]};case"marketplace.knowledge.query":{if(!i.boxPrivateKey)throw new Ar("Provide deps.boxPrivateKey (your party\u2019s box key) to open the graph.");let c=await wB(e,a("contractId"),i.boxPrivateKey),l=bB(c.bundle);return{data:{verified:c.verified,problems:c.problems,manifest:c.manifest,...Array.isArray(r.symptoms)?{diagnosis:AB(l,r.symptoms.map(String))}:{},...r.query?{hits:CB(l,a("query"))}:{},...r.nodeId?{neighborhood:vB(l,a("nodeId"),r.depth===void 0?1:s("depth"))}:{}},txs:[]}}case"marketplace.escrow.ledger-settle":{if(!i.fetchLedgerTx)throw new Ar("Provide deps.fetchLedgerTx to read the ledger.");let c=i.policy??fa([]),l=await Promise.all((r.feeTxHashes??[]).map(u=>i.fetchLedgerTx(c.network,String(u))));return{txs:await MC(e,t,a("contractId"),s("milestone"),await i.fetchLedgerTx(c.network,a("txHash")),c,l)}}case"marketplace.access.deliver":{if(!i.boxPrivateKey)throw new Ar("Provide deps.boxPrivateKey to open your graph key.");let c=e.contracts.find(l=>l.contractId===a("contractId"));if(!c||c.source.kind!=="listing")throw new Ar("Unknown graph contract.");return{txs:await gB(e,t,c.contractId,await mB(e,c.source.listingId,i.boxPrivateKey))}}case"marketplace.security.subscribe":return{txs:await IB(e,t,a("offeringId"),s("units"))};case"marketplace.security.transfer":return{txs:await PB(e,t,a("offeringId"),a("to"),s("units"))};case"marketplace.party.profile":return{txs:await jf(e,t,r.profile)};case"marketplace.listing.publish":return{txs:await ts(e,t,r.listing)};case"marketplace.order.place":{let c=await IC(e,t,a("listingId"),s("quantity"),void 0,r.evaluatorId?a("evaluatorId"):void 0);return{data:{contractId:c.contractId},txs:c.txs}}case"marketplace.request.post":return{txs:await Xf(e,t,r.request)};case"marketplace.offer.submit":{let c=await ru(e,t,r.offer);return{data:{warnings:c.warnings},txs:c.txs}}case"marketplace.contract.subcontract":{let c=await PC(e,t,a("parentContractId"),{subcontractorId:a("subcontractorId"),title:a("title"),quantity:s("quantity"),pricePerUnit:r.pricePerUnit,...r.serves!==void 0?{serves:s("serves")}:{},...Array.isArray(r.milestones)?{milestones:r.milestones}:{},...r.unit?{unit:a("unit")}:{},...r.evaluatorId?{evaluatorId:a("evaluatorId")}:{}});return{data:{contractId:c.contractId},txs:c.txs}}case"marketplace.offer.award":{let c=await Wf(e,t,a("requestId"),a("offerId"),r.quantity===void 0?void 0:s("quantity"),r.evaluatorId?a("evaluatorId"):void 0);return{data:{contractId:c.contractId},txs:c.txs}}case"marketplace.escrow.fund":{if(Array.isArray(r.escrows)){if(!i.fetchLedgerTx)throw new Ar("Provide deps.fetchLedgerTx to read the ledger.");let c=i.policy??fa([]),l=await Promise.all(r.escrows.map(async u=>({milestone:Number(u.milestone),condition:String(u.condition),lt:await i.fetchLedgerTx(c.network,String(u.txHash))})));return{txs:await xC(e,t,a("contractId"),c,l)}}if(!r.reference||r.amount===void 0)throw new Ar("USD funding needs amount and reference; XRP funding needs escrows.");return{txs:await iu(e,t,a("contractId"),s("amount"),{rail:"usd-reference",reference:a("reference")})}}case"marketplace.milestone.evidence":return{txs:await Gf(e,t,a("contractId"),s("milestone"),{kind:a("kind"),hash:a("hash"),note:r.note?a("note"):""})};case"marketplace.milestone.affirm":return{txs:await ou(e,t,a("contractId"),s("milestone"))};case"marketplace.escrow.release":return{txs:await Yf(e,t,a("contractId"),s("milestone"))};case"marketplace.token.transfer":return{txs:await UL(e,t,a("tokenId"),a("to"),s("amount"))};default:throw new Ar(`${n} is not exposed to agents in this release.`)}}y();qo();var qB=jr(Nr(),1);Rl();var HB="cappz-payee";var VB=36e5,p8e=24*VB,ME=new TextEncoder,KC=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),UB=e=>new Uint8Array((e.match(/../g)??[]).map(t=>parseInt(t,16))),KB=async e=>KC(new Uint8Array(await crypto.subtle.digest("SHA-256",ME.encode(e)))),zB=e=>KB(Br(e)),$B=e=>e.replace(/[^0-9A-Za-z]/g,"").toUpperCase(),OE=(e,t,n)=>KB(`cappz-payee-bank|${e}|${$B(t)}|${$B(n)}`);function jB(e){let t=[];/^pi-[0-9a-f]{12}$/.test(e.instructionsId)||t.push("instructionsId is pi- and 12 hex characters."),e.partyId||t.push("partyId is required.");let n=e.instrument;return n?.kind==="xrpl"?((0,qB.isValidClassicAddress)(n.address)||t.push(`${n.address} is not an XRPL classic address.`),n.destinationTag!==void 0&&!(Number.isInteger(n.destinationTag)&&n.destinationTag>=0&&n.destinationTag<=4294967295)&&t.push("destinationTag is a whole number from 0 to 4294967295.")):n?.kind==="bank"?(/^[0-9a-f]{32}$/.test(n.salt)||t.push("A bank instrument carries a 16-byte hex salt."),/^[0-9a-f]{64}$/.test(n.digest)||t.push("A bank instrument carries a SHA-256 digest (bankAccountDigest), never the account number."),(!n.hint?.trim()||n.hint.length>80)&&t.push('Give the bank account a short hint (up to 80 characters), e.g. "First Bank \u2022\u20221234".'),/\d{5,}/.test(n.hint??"")&&t.push("The hint shows at most four digits of the account in a row.")):t.push('instrument is {kind: "xrpl", address, destinationTag?} or {kind: "bank", salt, digest, hint}.'),Number.isNaN(Date.parse(e.validFrom))&&t.push("validFrom is an ISO date."),e.validUntil!==null&&(Number.isNaN(Date.parse(e.validUntil))||Date.parse(e.validUntil)<=Date.parse(e.validFrom))&&t.push("validUntil is null (until revoked) or an ISO date after validFrom."),e.purpose!==void 0&&e.purpose.length>200&&t.push("purpose is at most 200 characters."),e.supersedes!==void 0&&(!Array.isArray(e.supersedes)||e.supersedes.length>16)&&t.push("supersedes lists at most 16 earlier declarations."),t}var DE=(e,t,n,r)=>ua.create({eventType:e,sourceAddress:t,targetAddress:n,payload:r}),XB=()=>`pi-${KC(crypto.getRandomValues(new Uint8Array(6)))}`,WB=()=>KC(crypto.getRandomValues(new Uint8Array(16)));async function GB(e,t,n){if(!e.parties.has(t))throw new Error("Set up your marketplace profile first.");if(n.partyId!==t)throw new Error("You can only declare your own payment instructions.");let r=jB(n);if(r.length)throw new Error(r.join(" "));return{txs:[await DE("ContentCreated",ve(t),cC(t,n.instructionsId),{contentClass:"payee-instructions",instructions:n})],hash:await zB(n)}}async function zC(e,t,n){if(!/^[0-9A-Fa-f]{64}$/.test(n))throw new Error("An XRPL transaction hash is 64 hex characters.");return[await DE("ContentAmended",ve(e),`${cC(e,t)}/anchors/${n.slice(0,16).toUpperCase()}`,{contentClass:"payee-instructions-anchor",instructionsId:t,txHash:n.toUpperCase()})]}async function YB(e,t,n){return[await DE("ContentAmended",ve(e),`${cC(e,t)}/revocation`,{contentClass:"payee-instructions-revoked",instructionsId:t,reason:n.slice(0,200)})]}function rp(e,t,n){let r=i=>KC(ME.encode(i)).toUpperCase();return{TransactionType:"AccountSet",Account:e,Memos:[{Memo:{MemoType:r(HB),MemoData:r(`${t}:${n}`)}}]}}var xE=e=>e.payload,Sde=e=>[...e].sort((t,n)=>t.timestamp.localeCompare(n.timestamp)||t.txId.localeCompare(n.txId));async function RE(e){let t=new Map,n=r=>{let i=t.get(r);return i||(i={partyId:r,name:null,firstSeen:null,walletHistory:[],declarations:[]},t.set(r,i)),i};for(let r of Sde(e)){if(r.eventType!=="ContentCreated"&&r.eventType!=="ContentAmended")continue;let i=r.payload.contentClass;if(i==="party"){let c=xE(r).profile;if(!c?.partyId||r.sourceAddress!==ve(c.partyId))continue;let l=n(c.partyId);l.name=c.name,l.firstSeen??=r.timestamp;let u=c.xrplAccount??null;l.walletHistory.at(-1)?.account!==u&&l.walletHistory.push({account:u,since:r.timestamp});continue}if(i!=="payee-instructions"&&i!=="payee-instructions-anchor"&&i!=="payee-instructions-revoked")continue;if(i==="payee-instructions"){let c=xE(r).instructions;if(!c?.partyId||r.sourceAddress!==ve(c.partyId)||jB(c).length)continue;let l=n(c.partyId);if(l.declarations.some(u=>u.content.instructionsId===c.instructionsId))continue;for(let u of c.supersedes??[]){let d=l.declarations.find(p=>p.content.instructionsId===u);d&&!d.supersededBy&&(d.supersededBy={instructionsId:c.instructionsId,at:r.timestamp})}l.declarations.push({content:c,hash:await zB(c),declaredAt:r.timestamp,anchorTxs:[],revoked:null,supersededBy:null});continue}let o=xE(r),s=[...t.values()].find(c=>r.sourceAddress===ve(c.partyId))?.declarations.find(c=>c.content.instructionsId===o.instructionsId);s&&(i==="payee-instructions-anchor"&&typeof o.txHash=="string"&&/^[0-9A-F]{64}$/.test(o.txHash)&&s.anchorTxs.length<8&&!s.anchorTxs.includes(o.txHash)&&s.anchorTxs.push(o.txHash),i==="payee-instructions-revoked"&&!s.revoked&&(s.revoked={at:r.timestamp,reason:String(o.reason??"")}))}return t}async function NE(e,t,n=fetch){try{return Tde(await TN(e,t,n))}catch(r){return{txHash:t,account:null,validated:null,result:null,closeTime:null,memo:null,error:r.message}}}var Tde=e=>({txHash:e.hash.toUpperCase(),account:e.account||null,validated:e.validated,result:e.result||null,closeTime:e.closeTime,memo:e.memos.find(t=>t.type===HB)?.data??null,error:null});var Ede=(e,t)=>[...e.walletHistory].reverse().find(n=>Date.parse(n.since)<=Date.parse(t))??null;function ZB(e,t,n,r,i){let o={state:"unanchored",instructionsId:e.content.instructionsId,instructionsHash:e.hash,declaredAt:e.declaredAt,endorsedAt:null,endorsedBy:null,control:e.content.instrument.kind==="bank"?"not-applicable":null,inForceFrom:null,coolingHours:i,because:""};if(e.revoked)return{...o,state:"revoked",because:`The payee revoked these instructions on ${e.revoked.at.slice(0,10)}${e.revoked.reason?`: ${e.revoked.reason}`:""}.`};if(e.supersededBy)return{...o,state:"superseded",because:`The payee replaced these instructions with ${e.supersededBy.instructionsId} on ${e.supersededBy.at.slice(0,10)}.`};if(e.content.validUntil!==null&&Date.parse(e.content.validUntil)<=Date.parse(r))return{...o,state:"expired",because:`These instructions expired on ${e.content.validUntil.slice(0,10)}.`};let a=`${e.content.instructionsId}:${e.hash}`,s=n.filter(T=>e.anchorTxs.includes(T.txHash)),c=s.filter(T=>!T.error&&T.validated&&T.result==="tesSUCCESS"&&T.memo===a&&T.closeTime),l=t.walletHistory.at(-1)??null,u=c.filter(T=>l?.account&&T.account===l.account&&Ede(t,T.closeTime)?.account===l.account).sort((T,k)=>T.closeTime.localeCompare(k.closeTime))[0],d=e.content.instrument,p=d.kind==="bank"?"not-applicable":c.some(T=>T.account===d.address)?"address-key":"payee-wallet-only";if(!u){if(s.some(k=>k.error))return{...o,control:p,state:"anchor-unreadable",because:"The endorsement could not be read from the ledger just now; nothing is confirmed."};let T=l?.account?c.length?`The anchors are not from the payee's profile wallet ${l.account} (or it was set on the profile after they were made).`:s.length?"The recorded anchors are not validated AccountSet transactions naming this declaration's hash.":"The payee declared these instructions but never endorsed them from their wallet.":"The payee's profile names no XRPL wallet to endorse with.";return{...o,control:p,state:"unanchored",because:T}}let h=Math.max(Date.parse(u.closeTime),Date.parse(l.since)),g=new Date(h+i*VB).toISOString(),w={...o,control:p,endorsedAt:u.closeTime,endorsedBy:u.account,inForceFrom:g};return Date.parse(e.content.validFrom)>Date.parse(r)?{...w,state:"not-yet-valid",because:`These instructions apply from ${e.content.validFrom.slice(0,10)}.`}:Date.parse(g)>Date.parse(r)?{...w,state:"cooling",because:`Endorsed ${u.closeTime.slice(0,16).replace("T"," ")} UTC; in force from ${g.slice(0,16).replace("T"," ")} UTC after the ${i}-hour cooling period.`}:{...w,state:"confirmed",because:`Declared by the payee and endorsed from their wallet ${u.account} on ${u.closeTime.slice(0,10)}; in force since ${g.slice(0,10)}.`}}var kde=`cappz-payee-confirmation/v1 `;function JB(e,t){if(t&&e.signature.publicKey.toLowerCase()!==t.toLowerCase())return!1;try{return Kn.verify(UB(e.signature.value),ME.encode(kde+Br(e.report)),UB(e.signature.publicKey))}catch{return!1}}y();var cu=jr(Nr(),1);Rl();import{mkdir as Nde,readFile as Lde,writeFile as Bde,chmod as Fde}from"node:fs/promises";import{homedir as Ude}from"node:os";import{join as UE}from"node:path";y();function _de(e,t){let n=e.fromSeed(t),r=e.fromSeed(t,{algorithm:"ed25519"});return r.classicAddress===n.classicAddress?null:r}function QB(e,t,n){let r=e.fromSeed(t);if(!n||r.classicAddress===n)return{wallet:r,derivation:"inferred"};let i=_de(e,t);if(i&&i.classicAddress===n)return{wallet:i,derivation:"legacy-ed25519"};throw new Error(`seed does not control ${n}`)}y();var eF=e=>[...e].sort((t,n)=>t.timestamp.localeCompare(n.timestamp)||t.txId.localeCompare(n.txId)),Yt=e=>e.payload;function ip(e){let t=new Map,n=new Map,r=new Map,i=new Map,o=new Map,a=new Map,s=new Map,c=new Map,l=new Map,u=new Map,d=new Map,p=new Map,h=new Map,g=new Map,w=new Map,T=null,k=[],B=[],D=[],P=(v,S)=>{let A=o.get(v)??[];A.push(S),o.set(v,A)};for(let v of eF(e)){xB(v,p,h);let S=v.payload.contentClass;switch(v.eventType){case"ContentCreated":case"ContentAmended":if(S==="party"){let A=Yt(v).profile;t.set(A.partyId,A)}if(S==="listing"){let A=Yt(v).listing,M=n.get(A.listingId);if(v.sourceAddress!==ve(A.sellerId)||M&&M.sellerId!==A.sellerId)break;n.set(A.listingId,{...A,open:M?.open??!0,remaining:M?M.remaining+(A.quantity-M.quantity):A.quantity,publishedAt:M?.publishedAt??v.timestamp})}if(S==="graph-manifest"){let A=Yt(v);u.set(A.listingId,A.manifest)}if(S==="graph-ciphertext"){let A=Yt(v);d.set(A.listingId,{...A,publishedAt:v.timestamp})}if(S==="party-box-key"){let A=Yt(v);g.set(A.partyId,A.sealedPrivate)}break;case"ListingWithdrawn":{let A=Yt(v),M=n.get(A.listingId);if(!M||!M.open)break;v.sourceAddress===ve(M.sellerId)?(M.open=!1,M.closed={by:"seller",at:v.timestamp}):L4(v.sourceAddress)&&(M.open=!1,M.closed={by:"operator",operator:v.sourceAddress,...A.reason?{reason:String(A.reason)}:{},at:v.timestamp});break}case"InventoryAdjusted":{let A=Yt(v),M=n.get(A.listingId);M&&v.sourceAddress===ve(M.sellerId)&&(M.remaining=Math.max(0,M.remaining+Number(A.delta)));break}case"SupplyRequested":{let A=Yt(v).request;r.set(A.requestId,{...A,postedAt:v.timestamp,open:!0,offers:[],awardedQuantity:0,contractIds:[]});break}case"SupplyRequestClosed":{let A=r.get(Yt(v).requestId);A&&(A.open=!1);break}case"SupplyOffered":{let A=Yt(v).offer;r.get(A.requestId)?.offers.push({...A,at:v.timestamp,withdrawn:!1,awardedQuantity:0});break}case"SupplyOfferWithdrawn":{let A=Yt(v),M=r.get(A.requestId)?.offers.find($=>$.offerId===A.offerId);M&&(M.withdrawn=!0);break}case"SupplyAwarded":case"OrderPlaced":{let A=Yt(v).terms;if(i.set(A.contractId,A),A.source.kind==="request"){let $=A.source,R=r.get($.requestId);if(R){R.awardedQuantity+=A.quantity,R.contractIds.push(A.contractId);let O=R.offers.find(j=>j.offerId===$.offerId);O&&(O.awardedQuantity+=A.quantity),R.awardedQuantity>=R.quantity&&(R.open=!1)}}else if(A.source.kind==="listing"){let $=A.source,R=n.get($.listingId);R&&(R.remaining-=A.quantity)}let M=Yt(v).agentPartyId;if(M){let $=Lf(M,v.timestamp,A.total.currency);c.set($,(c.get($)??0)+A.total.amount)}break}case"PaymentConfirmed":if(S==="fee-distribution"){let A=Yt(v);B.push({...A,at:v.timestamp,by:v.sourceAddress});break}P(Yt(v).contractId,v);break;case"EscrowFunded":case"EscrowReleased":case"EscrowRefunded":case"MilestoneEvidenced":case"MilestoneAffirmed":case"DeliveryApproved":case"DeliveryRejected":case"DisputeRaised":case"DisputeResolved":case"ReviewPosted":case"ContractCancelled":P(Yt(v).contractId,v);break;case"FeeCharged":{let A=Yt(v).contractId;A&&P(A,v);break}case"PriceSheetPublished":{let A=nL(v.payload,v.timestamp);A&&(T=A,k.push(A));break}case"AccessKeyDelivered":{let A=Yt(v),M=w.get(A.contractId)??[];M.push({...A,at:v.timestamp}),w.set(A.contractId,M);break}case"AssetTokenized":{let A=Yt(v).token;a.set(A.tokenId,{content:A,issuedAt:v.timestamp,balances:{[A.issuerId]:A.supply},redeemed:0});break}case"TokenTransferred":{let A=Yt(v),M=a.get(A.tokenId);M&&(M.balances[A.from]=(M.balances[A.from]??0)-A.amount,M.balances[A.to]=(M.balances[A.to]??0)+A.amount);break}case"TokenRedeemed":{let A=Yt(v),M=a.get(A.tokenId);M&&(M.balances[A.holder]=(M.balances[A.holder]??0)-A.amount,M.redeemed+=A.amount);break}case"ConstituentIncluded":if(S==="subcontract"){let A=Yt(v);typeof A.parentContractId=="string"&&typeof A.contractId=="string"&&v.targetAddress===sC(A.parentContractId,A.contractId)&&D.push({parentContractId:A.parentContractId,contractId:A.contractId,sourceAddress:v.sourceAddress})}break;case"PermissionGranted":if(S==="mandate"){let A=Yt(v).mandate;s.set(A.mandateId,A)}break;case"PermissionRevoked":S==="mandate"&&s.delete(Yt(v).mandateId);break}}for(let[v,S]of d){let A=u.get(v);A&&l.set(v,{...S,manifest:A})}let U=new Map,F=new Map;for(let v of D){let S=i.get(v.parentContractId),A=i.get(v.contractId);!S||!A||A.source.kind!=="subcontract"||U.has(v.contractId)||v.contractId===v.parentContractId||A.buyerId!==S.sellerId||v.sourceAddress!==ve(S.sellerId)||(U.set(v.contractId,v.parentContractId),F.set(v.parentContractId,[...F.get(v.parentContractId)??[],v.contractId]))}let H=[...i.values()].map(v=>Pde(v,o.get(v.contractId)??[],{parentContractId:U.get(v.contractId),subcontracts:F.get(v.contractId)}));Ide(H);let b=new Map,C=v=>{let S=b.get(v);return S||(S={completed:0,disputes:0,ratings:[],average:null},b.set(v,S)),S};for(let v of H){v.state==="completed"&&(C(v.buyerId).completed++,C(v.sellerId).completed++);for(let S of v.disputes)C(S.by===v.buyerId?v.sellerId:v.buyerId).disputes++;for(let S of v.reviews)C(S.by===v.buyerId?v.sellerId:v.buyerId).ratings.push(S.rating)}for(let v of b.values())v.average=v.ratings.length?Math.round(v.ratings.reduce((S,A)=>S+A,0)/v.ratings.length*10)/10:null;return{parties:t,listings:[...n.values()],requests:[...r.values()],contracts:H,tokens:[...a.values()],mandates:[...s.values()],reputation:b,committedByDay:c,graphs:l,boxKeys:g,accessDeliveries:w,offerings:[...p.values()],eligibility:h,fees:T,feeHistory:k,feeDistributions:B}}function Ide(e){let t=new Map(e.map(n=>[n.contractId,n]));for(let n of e){if(n.source.kind!=="subcontract"||n.state==="completed"||n.state==="cancelled"||n.state==="disputed")continue;let r=n.milestoneStates.find(s=>s.state!=="released");if(!r)continue;let a=(at(n)==="ledger-staged"?r.state==="affirmed":n.escrow.balance+1e-9t.get(a)).filter(a=>!!a&&a.state!=="completed"&&a.state!=="cancelled");if(!r.length)continue;n.because=`${n.because}; open subcontract work: ${r.map(a=>`${a.contractId} (${a.nextAction.action})`).join("; ")}`;let i=n.milestoneStates.find(a=>a.state!=="released"),o=i?r.filter(a=>a.milestones.some((s,c)=>s.servesMilestone===i.index&&a.milestoneStates[c]?.state!=="released")):[];n.nextAction.by==="seller"&&o.length&&(n.nextAction={...n.nextAction,action:`${n.nextAction.action} (subcontracted: ${o.map(a=>a.contractId).join(", ")})`})}}function Pde(e,t,n={}){let r=ar(e.total.amount,e.milestones),i=e.milestones.map(v=>({index:v.index,state:"pending",evidence:[],releasedAmount:0,stage:null,processor:null})),o=es(e),a={funded:0,released:0,refunded:0,balance:0},s=[],c=[],l=[],u=[],d=[],p=[],h="Contract formed",g=!1,w,T=0,k=at(e)==="ledger-channel",B=null,D=e.quantity;for(let v of eF(t)){let S=v.payload,A=typeof S.milestone=="number"?S.milestone:-1;if(k&&S.rail==="ledger-channel"&&(v.eventType==="EscrowFunded"||v.eventType==="EscrowReleased"||v.eventType==="EscrowRefunded")){let M=Number(S.amount);v.eventType==="EscrowFunded"&&!B&&(B={channelId:String(S.channelId),publicKey:String(S.publicKey??""),network:String(S.network),txHash:String(S.txHash),capDrops:String(S.capDrops??Math.round(M*1e6)),releasedDrops:"0",refundedDrops:"0",unitsUsed:0,unitsCap:D,settleDelay:typeof S.settleDelay=="number"?S.settleDelay:null,cancelAfter:String(S.holdUntil),closed:!1,closeTxHash:null},i[0]&&(i[0].stage={fundedAt:String(S.fundedAt??v.timestamp),dueBy:String(S.stageDueBy),holdUntil:String(S.holdUntil)}),a.funded+=M,h=`Payment channel opened on the ledger: up to ${D} ${e.unit} (${$n(M,"XRP")}), expires ${String(S.holdUntil).slice(0,10)}`),v.eventType==="EscrowReleased"&&B&&!B.closed&&BigInt(String(S.balanceDrops??"0"))>BigInt(B.releasedDrops)&&(B.releasedDrops=String(S.balanceDrops),B.unitsUsed=Number(S.totalUnitsUsed??0),a.released+=M,i[0]&&(i[0].releasedAmount+=M),d.push({milestone:0,kind:"release",txHash:String(S.txHash),network:String(S.network)}),h=`Seller redeemed ${$n(M,"XRP")} on the channel (${B.unitsUsed} of ${D} ${e.unit} used)`),v.eventType==="EscrowRefunded"&&B&&!B.closed&&S.closed===!0&&(B.closed=!0,B.refundedDrops=String(S.refundedDrops??"0"),B.closeTxHash=String(S.txHash),a.refunded+=M,d.push({milestone:0,kind:"refund",txHash:String(S.txHash),network:String(S.network)}),i[0]&&BigInt(B.releasedDrops)>0n&&(i[0].state="released"),h=`Channel closed on the ledger: ${$n(Number(B.releasedDrops)/1e6,"XRP")} paid for ${B.unitsUsed} ${e.unit}, ${$n(M,"XRP")} returned to the buyer`);continue}switch(v.eventType){case"EscrowFunded":i[A]&&!i[A].stage&&typeof S.holdUntil=="string"&&(i[A].stage={fundedAt:String(S.fundedAt??v.timestamp),dueBy:String(S.stageDueBy),holdUntil:S.holdUntil}),a.funded+=Number(S.amount),h=`Escrow funded ${S.amount} ${e.total.currency}${S.txHash?" on the ledger":""}`,S.txHash&&u.push({milestone:Number(S.milestone),txHash:String(S.txHash),sequence:Number(S.sequence),condition:String(S.condition),network:String(S.network),ledgerIndex:typeof S.ledgerIndex=="number"?S.ledgerIndex:null,...S.sealedSecret?{sealedSecret:S.sealedSecret}:{},feeEscrows:S.feeEscrows??[]});break;case"PaymentConfirmed":{let M=String(S.contentClass??"");if(M.startsWith("processor-")&&i[A]){let $=Number(S.grossCents??0)/100,R=i[A].processor;if(M==="processor-payment"){let O=S.status;O==="succeeded"&&R?.status!=="succeeded"?(a.funded+=$,h=`Stage \u201C${e.milestones[A].label}\u201D paid through Stripe (${S.rail})`,i[A].stage={fundedAt:String(S.fundedAt??v.timestamp),dueBy:String(S.stageDueBy??e.milestones[A].dueBy),holdUntil:String(S.holdUntil)},l.push({reference:String(S.paymentIntentId),amount:$,rail:`stripe-${S.rail}`,validated:!1,confirmedBy:"processor"})):O==="processing"&&(h=`Bank payment for \u201C${e.milestones[A].label}\u201D is clearing (ACH takes a few business days)`),i[A].processor={status:O,rail:S.rail??"pending",grossCents:Number(S.grossCents),paymentFeeCents:Number(S.paymentFeeCents??0),paymentIntentId:String(S.paymentIntentId),...typeof S.treasuryCents=="number"?{funding:S.funding,cardCostCents:Number(S.cardCostCents??0),treasuryCents:S.treasuryCents}:{}}}if(M==="processor-transfer"&&R?.status==="succeeded"){i[A].state="released",i[A].releasedAmount+=$,a.released+=$,i[A].processor={...R,status:"transferred",transferId:String(S.transferId),netCents:Number(S.netCents),feeCents:Number(S.feeCents)};let O=o.milestones[A];O&&O.feeUnits>0&&p.push({milestone:A,currency:"USD",feeUnits:Number(S.feeCents),sheetId:e.fees?.sheetId??"",settlement:"processor",legs:[],owed:O.legs,collector:null,reference:String(S.transferId)}),h=`Released ${$} USD for \u201C${e.milestones[A].label}\u201D (Stripe transfer to the seller)`}M==="processor-refund"&&R?.status==="succeeded"&&(a.refunded+=$,S.expiredHold===!0&&(T+=$),i[A].stage=null,i[A].processor={...R,status:"refunded"},h=`Stage \u201C${e.milestones[A].label}\u201D refunded to the buyer through Stripe`),M==="processor-clawback"&&R?.status==="transferred"&&(i[A].state="pending",i[A].releasedAmount-=$,a.released-=$,a.refunded+=$,i[A].stage=null,i[A].processor={...R,status:"clawed-back"},h=`Clawed back \u201C${e.milestones[A].label}\u201D: the transfer was reversed and the buyer refunded (${String(S.reason??"operator ruling")})`),M==="processor-dispute"&&(s.push({n:s.length,by:e.buyerId,reason:`Chargeback opened with the buyer's bank: ${String(S.reason??"unspecified")}`,resolved:null}),h="Chargeback opened");break}l.push({reference:String(S.reference??""),amount:Number(S.amount??0),rail:String(S.rail??""),validated:S.validated===!0,...S.validated===!0?{confirmedBy:"ledger"}:{},...S.network?{network:String(S.network)}:{}});break}case"MilestoneEvidenced":i[A]&&(i[A].evidence.push({kind:String(S.kind),hash:String(S.hash),note:String(S.note??""),at:v.timestamp}),i[A].state==="pending"&&(i[A].state="evidenced"),h=`Evidence for \u201C${e.milestones[A].label}\u201D`);break;case"MilestoneAffirmed":case"DeliveryApproved":if(i[A]&&i[A].state==="evidenced"){let M=S.role==="evaluator";if(M&&(!e.evaluatorId||S.by!==e.evaluatorId||v.sourceAddress!==ve(e.evaluatorId)))break;i[A].state="affirmed";let $=S.basis;h=(M?`Evaluator ${e.evaluatorId} accepted \u201C${e.milestones[A].label}\u201D`:`Buyer accepted \u201C${e.milestones[A].label}\u201D`)+($?.verdictSha256?` on verdict ${String($.verdictSha256).slice(0,12)}\u2026`:"")}break;case"DeliveryRejected":i[A]&&(i[A].state="pending",g=!0,h=`Buyer rejected delivery: ${S.reason??""}`);break;case"EscrowReleased":S.txHash&&d.push({milestone:A,kind:"release",txHash:String(S.txHash),network:String(S.network)}),i[A]&&(i[A].state="released",i[A].releasedAmount+=Number(S.amount),a.released+=Number(S.amount),S.direct===!0?(a.funded+=Number(S.amount),h=`Paid ${$n(Number(S.amount),e.total.currency)} on the ledger for \u201C${e.milestones[A].label}\u201D`):h=`Released ${S.amount} for \u201C${e.milestones[A].label}\u201D`);break;case"EscrowRefunded":i[A]&&i[A].state!=="released"&&(i[A].stage=null),S.expiredHold===!0&&(T+=Number(S.amount)),a.refunded+=Number(S.amount),S.txHash&&d.push({milestone:A,kind:"refund",txHash:String(S.txHash),network:String(S.network)}),h=`Refunded ${S.amount} to buyer${S.txHash?" (escrow cancelled on the ledger)":""}`;break;case"ContractCancelled":{let M=String(S.by??""),$=M===e.buyerId||M===e.sellerId,R=a.funded===0&&a.released===0&&l.length===0&&u.length===0&&!B&&i.every(O=>O.releasedAmount===0&&O.state!=="released"&&!O.processor);!w&&$&&v.sourceAddress===ve(M)&&R&&!s.some(O=>!O.resolved)&&(w={by:M,reason:String(S.reason??""),at:v.timestamp},h=`Cancelled by ${M===e.buyerId?"the buyer":"the seller"}: ${w.reason}`);break}case"DisputeRaised":s.push({n:s.length,by:String(S.by),reason:String(S.reason),resolved:null}),i[A]&&(i[A].state="disputed"),h=`Dispute raised: ${S.reason}`;break;case"DisputeResolved":{let M=s[Number(S.dispute)];M&&(M.resolved={resolution:S.resolution,note:String(S.note??"")}),i[A]&&i[A].state==="disputed"&&(i[A].state=S.resolution==="refund"?"pending":"affirmed"),h=`Dispute resolved (${S.resolution})`;break}case"FeeCharged":p.push({milestone:A,currency:S.currency,feeUnits:Number(S.feeUnits),sheetId:String(S.sheetId),settlement:S.settlement,legs:S.legs??[],owed:S.owed??[],collector:S.collector??null,...S.reference?{reference:String(S.reference)}:{}});break;case"ReviewPosted":c.push({by:String(S.by),rating:Number(S.rating),text:String(S.text??"")});break}}a.balance=Math.round((a.funded-a.released-a.refunded)*100)/100;let P=i.every(v=>v.state==="released"),U=s.some(v=>!v.resolved),F=at(e)==="ledger-staged";w&&(a.funded>0||a.released>0||l.length>0||u.length>0||B||i.some(v=>v.releasedAmount>0||v.state==="released"||v.processor))&&(w=void 0,h="A cancellation was set aside: money has moved on this contract");let H=w?"cancelled":P?"completed":U?"disputed":(k?B?.closed===!0:a.refunded-T>1e-9&&a.balance<=0&&a.releasedv.state!=="released"),C=H==="completed"?{by:null,action:c.length<2?"Leave a review":"Done"}:H==="cancelled"?{by:null,action:"Cancelled"}:U?{by:"operator",action:"Resolve the dispute"}:b?k?B?B.releasedDrops==="0"?{by:"buyer",action:`Use the service and sign claims as you use it (each for the total used so far, up to ${D} ${e.unit}); the seller redeems them`}:{by:"seller",action:`Redeem the buyer's latest claim, or close the channel to return the unused ${$n(Number(BigInt(B.capDrops)-BigInt(B.releasedDrops))/1e6,"XRP")} (it expires ${B.cancelAfter.slice(0,10)})`}:{by:"buyer",action:`Open the payment channel: up to ${D} ${e.unit} at ${$n(e.pricePerUnit.amount,"XRP")} each (cap ${$n(e.total.amount,"XRP")}, returned unused within 30 days)`}:!F&&a.balance+1e-9({amount:e,currency:"USD"}),Tm=(e,t)=>new Date(Date.parse(e)+t*864e5).toISOString(),jC=(e,t)=>Tm(e,t).slice(0,10),Sm=e=>Array.from(e.padEnd(64,"0").slice(0,64),t=>(t.charCodeAt(0)%16).toString(16)).join(""),Mde=[{partyId:su,kind:"person",name:"You (demo)",roles:["buyer","seller"],region:"IA",cats:[],xrplAccount:"rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"},{partyId:"prairie-creek",kind:"organization",name:"Prairie Creek Farms",roles:["farmer","seller"],region:"IA",cats:["crops/grains","crops/specialty"],canPlantNew:!0,acres:640,xrplAccount:"rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"},{partyId:"blue-ridge-herbs",kind:"organization",name:"Blue Ridge Herb Co.",roles:["farmer","seller","processor"],region:"NC",cats:["crops/specialty"],canPlantNew:!0,acres:40},{partyId:"cascade-flowers",kind:"organization",name:"Cascade Cut Flowers",roles:["farmer","seller"],region:"OR",cats:["crops/specialty","crops/produce"],canPlantNew:!0,acres:25},{partyId:"hill-country-lavender",kind:"organization",name:"Hill Country Lavender",roles:["farmer","seller","processor"],region:"TX",cats:["crops/specialty"],canPlantNew:!0,acres:18},{partyId:"north-star-grain",kind:"organization",name:"North Star Grain",roles:["farmer","seller"],region:"MN",cats:["crops/grains","land"],canPlantNew:!0,acres:2200},{partyId:"heartland-equipment",kind:"organization",name:"Heartland Equipment",roles:["equipment-dealer","seller"],region:"IL",cats:["equipment"],equipment:["tractors","planters","combines"]},{partyId:"jones-custom",kind:"person",name:"Jones Custom Harvesting",roles:["service-provider"],region:"NE",cats:["services"],equipment:["2 combines","grain cart"]},{partyId:"greenleaf-inputs",kind:"organization",name:"Greenleaf Seed & Inputs",roles:["supplier","seller"],region:"IA",cats:["inputs"]},{partyId:"maison-aroma",kind:"organization",name:"Maison Ar\xF4ma Perfumers",roles:["buyer"],region:"NY",cats:[]},{partyId:"harvest-table",kind:"organization",name:"Harvest Table Restaurant Group",roles:["buyer"],region:"IL",cats:[]},{partyId:"agent-petalbot",kind:"agent",name:"PetalBot Procurement (autonomous agent)",roles:["buyer"],region:"CA",cats:[],about:"A non-human company that sources edible and cut flowers for subscription boxes.",selfGoverned:!0},{partyId:"agentco",kind:"agent",name:"AgentCo (a company with no employees)",roles:["service-provider","seller"],region:"IA",cats:["agents"],about:"Five AI agents \u2014 sales, operations, compliance, treasury \u2014 run daily fund reconciliation for banks, each from its own wallet copy. Watch it work at /replicator/agentco (synthetic demo party).",selfGoverned:!0},{partyId:"prairie-relay-coop",kind:"organization",name:"Prairie Co-op Relay",roles:["service-provider"],region:"IA",cats:["relay"],about:"A farm co-op that runs an edge node so members and their buyers can replicate through bank and corporate firewalls (synthetic demo party)."},{partyId:"agent-fieldops",kind:"agent",name:"FieldOps Autonomous Custom Hire",roles:["service-provider"],region:"KS",cats:["services","equipment"],about:"An agent-run fleet of autonomous sprayers and drones."},{partyId:"valley-processing",kind:"organization",name:"Valley Drying & Distilling",roles:["service-provider","processor"],region:"WI",cats:["services"]},{partyId:"phytograph-labs",kind:"organization",name:"PhytoGraph Labs",roles:["seller","service-provider"],region:"CA",cats:["digital","services"],about:"Curated plant-health knowledge graphs: symptoms, conditions, treatments, with provenance and confidence on every edge (synthetic demo party)."}],Ode="l-graph-tomato-blight",nF="sec-prairie-lavender",qt=(e,t,n,r,i,o,a,s,c,l,u={})=>({listingId:e,sellerId:t,categoryId:n,kind:r,title:i,description:i,unit:o,pricePerUnit:Vr(a),quantity:s,region:c,delivery:r==="service"?"on-site":"ship",leadDays:l,attributes:u}),Dde=[qt("l-corn-ia","prairie-creek","crops/grains","sale","Yellow corn #2, 15% moisture","bu",4.1,2e4,"IA",7),qt("l-soy-ia","prairie-creek","crops/grains","sale","Food-grade soybeans","bu",10.6,6e3,"IA",7),qt("l-wheat-mn","north-star-grain","crops/grains","sale","Hard red spring wheat","bu",6.2,15e3,"MN",10),qt("l-barley-mn","north-star-grain","crops/grains","production-contract","Malting barley \u2014 contract 2027 crop","bu",5.4,3e4,"MN",300),qt("l-basil-nc","blue-ridge-herbs","crops/specialty","sale","Fresh holy basil (tulsi), weekly","lb",9.5,400,"NC",3,{variety:"Ocimum tenuiflorum"}),qt("l-chamomile-nc","blue-ridge-herbs","crops/specialty","sale","Dried German chamomile flowers","lb",18,300,"NC",5),qt("l-dahlia-or","cascade-flowers","crops/specialty","sale","Heirloom dahlias, mixed","stems",1.6,5e3,"OR",2),qt("l-peony-or","cascade-flowers","crops/specialty","production-contract","Peonies \u2014 grow to order","stems",2.4,8e3,"OR",240),qt("l-lav-tx","hill-country-lavender","crops/specialty","sale","Dried lavender buds (Grosso)","lb",22,150,"TX",5,{variety:"Lavandula \xD7 intermedia Grosso"}),qt("l-lavoil-tx","hill-country-lavender","crops/specialty","sale","Lavender essential oil","kg",180,12,"TX",5),qt("l-tomato-or","cascade-flowers","crops/produce","sale","Heirloom tomatoes","cases",32,200,"OR",2),qt("l-tractor-il","heartland-equipment","equipment","sale","Used 100 hp utility tractor (2016, 2,400 h)","each",48e3,2,"IL",14,{make:"utility 100 hp",year:"2016",hours:"2400"}),qt("l-planter-rent-il","heartland-equipment","equipment","rent","16-row planter rental","day",650,30,"IL",3),qt("l-transplanter-il","heartland-equipment","equipment","rent","Plug transplanter (herbs, flowers) rental","day",220,20,"IL",5),qt("l-dryer-wi","valley-processing","services","service","Low-heat herb & flower drying","lb",1.2,2e4,"WI",7),qt("l-distill-wi","valley-processing","services","service","Steam distillation (essential oils)","job",900,25,"WI",10),qt("l-harvest-ne","jones-custom","services","service","Custom combining \u2014 corn & soybeans","acre",38,4e3,"NE",14),qt("l-trucking-ne","jones-custom","services","service","Grain trucking","mile",4.5,1e4,"NE",3),qt("l-drone-ks","agent-fieldops","services","service","Autonomous drone spraying","acre",14,2e4,"KS",5),qt("l-plugs-ia","greenleaf-inputs","inputs","sale","Lavender plugs (Grosso), 72-cell trays","tray",64,400,"IA",10),qt("l-seedcorn-ia","greenleaf-inputs","inputs","sale","Seed corn, 80k bag","bag",285,600,"IA",7),qt("l-compost-ia","greenleaf-inputs","inputs","sale","OMRI-listed compost","ton",48,800,"IA",5),qt("l-agentco-recon","agentco","agents","service","Daily fund NAV reconciliation \u2014 break report, notarized, by five AI agents","job",25,5e3,"IA",1,{runtime:"AgentCo node (own edge node)",payment:"per job, milestone on delivery"}),qt("l-relay-ia","prairie-relay-coop","relay","service","Relay node for copies behind firewalls (WebTransport, WebSocket, HTTPS)","month",6,200,"IA",1,{endpoint:"https://relay.prairie-coop.example/cpz1",carriers:"WebTransport, WebSocket, HTTPS stream, long-poll",ask:"0 CAPPZ per MB for members"}),qt("l-bins-mn","north-star-grain","land","rent","On-farm bin space","bu-month",.05,2e5,"MN",1),qt("l-lease-mn","north-star-grain","land","rent","Cropland lease, 160 ac","acre-year",245,160,"MN",30)],ma=(e,t,n,r,i,o,a,s,c,l,u={})=>({requestId:e,buyerId:t,categoryId:n,title:r,description:r,quantity:i,unit:o,maxPricePerUnit:a===null?null:Vr(a),neededBy:jC(l,c),region:s,deliveryRadiusMiles:null,allowNewPlanting:!1,contractType:"spot",attributes:{},...u}),Em=class{txs=[];state=ip([]);clock;boxKeys=new Map;constructor(t){this.clock=Date.parse(t)}async registerBoxKey(t){let n=await db();this.boxKeys.set(t,n.privateKey),this.apply(await yB(this.state,this.as(t,1),n.publicKey,{encryption:"demo-session-memory"}))}as(t,n=5,r){return this.clock+=n*6e4,{partyId:t,at:new Date(this.clock).toISOString(),...r?{coSignedBy:r}:{}}}now(){return new Date(this.clock).toISOString()}apply(t){let n=new Date(this.clock).toISOString();for(let r of t)this.txs.push({...r,timestamp:n});return this.state=ip(this.txs),t}},Rde={marketplace:{percent:{enabled:!0,bps:100},flat:{enabled:!1,amounts:{}},perRecord:{enabled:!0,amounts:{USD:.01,XRP:1e-5}}},securities:{percent:{enabled:!0,bps:100},flat:{enabled:!1,amounts:{}},perRecord:{enabled:!1,amounts:{}}},recipients:[{account:"rrrrrrrrrrrrrrrrrrrrrhoLvTp",label:"Demo treasury",bps:7e3},{account:"rrrrrrrrrrrrrrrrrrrrBZbvji",label:"Demo operator",bps:3e3}],note:"Demo assumption: 1% of value plus 1\xA2 (0.00001 XRP) per ledger record for deals, 1% for placements. Not CAPPZ prices; an administrator publishes the real schedule."};async function LE(e){let t=new Em(e);for(let s of Mde){let c=s.kind==="agent"?s.selfGoverned?{governanceAddress:`m/44'/144'/0'/cappz/operational/marketplace/parties/${s.partyId}/governance`}:{partyId:"jones-custom"}:void 0,l={partyId:s.partyId,kind:s.kind,name:s.name,roles:s.roles,region:s.region,about:s.about??`${s.name} (synthetic demo party).`,capabilities:{categories:s.cats,canPlantNew:!!s.canPlantNew,...s.acres?{acres:s.acres}:{},...s.equipment?{equipment:s.equipment}:{}},...c?{principal:c}:{},...s.kind==="agent"?{runtime:"demo agent runtime"}:{},...s.xrplAccount?{xrplAccount:s.xrplAccount}:{}};t.apply(await jf(t.state,t.as(s.partyId,1),l))}t.apply(await tL(N4("demo-admin"),t.as("demo-admin",1).at,{...Rde})),t.apply((await Zf(t.state,t.as("agent-petalbot"),"agent-petalbot",{verbs:["marketplace.request.post","marketplace.offer.award","marketplace.escrow.fund","marketplace.order.place"],categories:["crops/specialty"],maxPerContract:Vr(8e3),maxPerDay:Vr(2e4),approvalAbove:Vr(5e3),expiresAt:Tm(e,365)})).txs),t.apply((await Zf(t.state,t.as("agentco"),"agentco",{verbs:["marketplace.listing.publish","marketplace.offer.submit"],categories:["agents"],maxPerContract:Vr(25e3),maxPerDay:Vr(5e4),approvalAbove:Vr(1e4),expiresAt:Tm(e,365)})).txs),t.apply((await Zf(t.state,t.as("jones-custom"),"agent-fieldops",{verbs:["marketplace.listing.publish","marketplace.offer.submit"],categories:["services","equipment"],maxPerContract:Vr(5e4),maxPerDay:Vr(1e5),approvalAbove:null,expiresAt:Tm(e,365)})).txs);for(let s of Dde)t.apply(await ts(t.state,t.as(s.sellerId,2),s));await t.registerBoxKey("phytograph-labs"),await t.registerBoxKey(su),t.apply(await hB(t.state,t.as("phytograph-labs",2),{listingId:Ode,sellerId:"phytograph-labs",kind:"sale",title:"Tomato early-blight knowledge graph (license)",description:"Symptoms, conditions, causes and treatments for early blight in tomato, with confidence and provenance on every edge. Search it, walk it, and run a diagnosis from what you see in the field \u2014 all in your browser after purchase.",pricePerUnit:Vr(49),quantity:1e3,region:"CA",delivery:"ship",leadDays:1,attributes:{crops:"tomato",topics:"early blight, alternaria, chlorosis, fungicide, sanitation"}},tF));let n=N4("demo-compliance");t.apply(await kB(t.state,t.as("prairie-creek",5),{offeringId:nF,issuerId:"prairie-creek",exemption:"reg-d-506c",name:"Prairie Creek lavender expansion \u2014 profit units",description:"Each unit receives a share of 20% of net lavender profit for five years. Synthetic demo offering; nothing of value is offered.",units:500,pricePerUnit:Vr(100),minUnits:5,lockupDays:365,documents:[{kind:"offering memorandum",hash:Sm("ppm")},{kind:"subscription agreement",hash:Sm("sub-agreement")}],issuerAccount:"rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"})),t.apply(await _B(t.state,n,t.as(su,60).at,nF,fa(t.txs),"Demo review: documents present; testnet rehearsal.")),t.apply(await EB(t.state,n,null,t.as(su,5).at,{partyId:su,status:"accredited-verified",method:"third-party-letter",evidenceHash:Sm("cpa-letter"),expiresAt:Tm(t.now(),90)}));let r=t.now(),i=[ma("r-saffron","maison-aroma","crops/specialty","Saffron threads, ISO 3632 grade I",2,"kg",9e3,"NY",300,r,{allowNewPlanting:!0,contractType:"production-contract",attributes:{variety:"Crocus sativus",form:"dried threads"}}),ma("r-rose","maison-aroma","crops/specialty","Damask rose petals for absolute",1200,"lb",14,"NY",260,r,{allowNewPlanting:!0,contractType:"production-contract"}),ma("r-tulsi","harvest-table","crops/specialty","Fresh holy basil, weekly for 12 weeks",60,"lb",11,"IL",30,r,{recurring:{every:"week",count:12}}),ma("r-edible","agent-petalbot","crops/specialty","Edible flower mix (violas, nasturtium, borage)",3e3,"stems",.9,"CA",120,r,{allowNewPlanting:!0,contractType:"production-contract"}),ma("r-microgreens","harvest-table","crops/produce","Microgreens, chef mix",40,"cases",45,"IL",21,r),ma("r-hops","harvest-table","crops/specialty","Cascade hops, whole cone",500,"lb",12,"IL",280,r,{allowNewPlanting:!0,contractType:"production-contract"}),ma("r-sorghum","maison-aroma","crops/grains","Sweet sorghum syrup base",2e3,"lb",2.2,"NY",200,r,{allowNewPlanting:!0,contractType:"production-contract"}),ma("r-transplant-svc","prairie-creek","services","Transplanting crew for 10 ac lavender",10,"acre",400,"IA",40,r),ma("r-flower-dryer","hill-country-lavender","equipment","Small flower dryer (used OK)",1,"each",12e3,"TX",60,r),ma("r-pepper-ne","harvest-table","crops/produce","Shishito peppers",80,"cases",38,"IL",90,r,{allowNewPlanting:!0})];for(let s of i)t.apply(await Xf(t.state,t.as(s.buyerId,3),s));let o=(s,c)=>({message:"",...s,milestones:s.milestones??$f(c,r.slice(0,10),s.deliveryDate,s.plan.plantingDate)});t.apply((await ru(t.state,t.as("blue-ridge-herbs",30),o({offerId:"o-tulsi-br",requestId:"r-tulsi",sellerId:"blue-ridge-herbs",pricePerUnit:Vr(10.2),quantity:60,deliveryDate:jC(r,21),plan:{newPlanting:!1,notes:"From existing beds; weekly cut."}},"spot"))).txs);let a=await Wf(t.state,t.as("harvest-table",60),"r-tulsi","o-tulsi-br");return t.apply(a.txs),t.apply(await iu(t.state,t.as("harvest-table",10),a.contractId,612,{rail:"demo"})),t.apply(await Gf(t.state,t.as("blue-ridge-herbs",1440*7),a.contractId,0,{kind:"delivery-receipt",hash:Sm("tulsi-delivery-1"),note:"Delivered to kitchen, signed receipt"})),t.apply(await ou(t.state,t.as("harvest-table",60),a.contractId,0)),t.apply(await Yf(t.state,t.as("harvest-table",5),a.contractId,0)),t.apply(await gm(t.state,t.as("harvest-table",5),a.contractId,5,"Fragrant, on time.")),t.apply(await gm(t.state,t.as("blue-ridge-herbs",5),a.contractId,5,"Clear specs, paid promptly.")),t.apply((await ru(t.state,t.as("cascade-flowers",40),o({offerId:"o-edible-cf",requestId:"r-edible",sellerId:"cascade-flowers",pricePerUnit:Vr(.85),quantity:3e3,deliveryDate:jC(r,110),plan:{newPlanting:!0,plantingDate:jC(r,14),acres:.5,notes:"New bed of violas, nasturtium and borage."}},"production-contract"))).txs),t.apply((await FL(t.state,t.as("north-star-grain",20),{tokenId:"tok-wheat-mn-1",assetKind:"warehouse-receipt",categoryId:"crops/grains",name:"NSG wheat receipt, bin 4",description:"Hard red spring wheat stored in bin 4, graded #1.",redeemsFor:{quantity:1e3,unit:"bu"},supply:12,backing:{custodian:"North Star Grain (bin 4)",region:"MN",evidence:[{kind:"inspection",hash:Sm("bin4-grade-cert"),note:"Grade certificate"}]},answers:{redeemableForSpecificAsset:!0,profitFromOthersEfforts:!1,fractionalEnterpriseOwnership:!1},issuerAccount:"rDemoNorthStarGrainTestnetXXXXXX"})).txs),t}$b();qo();var te=class extends Error{constructor(n,r){super(n);this.next=r}next};function zi(e){let t=(e.network??process.env.CAPPZ_NETWORK??"testnet").toLowerCase();if(!HC.includes(t))throw new te(`Unknown network \u201C${t}\u201D.`,`Use one of: ${HC.join(", ")}.`);return t}var WC=()=>process.env.CAPPZ_HOME??UE(Ude(),".cappz","market"),XC=()=>(process.env.CAPPZ_MARKET_URL??"https://cappz.ai").replace(/\/$/,"");async function ga(e){try{return JSON.parse(await Lde(UE(WC(),e),"utf8"))}catch{return null}}async function is(e,t,n=!1){await Nde(WC(),{recursive:!0});let r=UE(WC(),e);await Bde(r,JSON.stringify(t,null,2)+` `,{mode:n?384:420}),n&&await Fde(r,384).catch(()=>{})}var op=null;async function sr(){if(op)return op;if(process.env.CAPPZ_MIRROR_URL&&process.env.CAPPZ_MIRROR_KEY)return op={name:"custom",web:XC(),mirror:{url:process.env.CAPPZ_MIRROR_URL,publishableKey:process.env.CAPPZ_MIRROR_KEY,table:"chainlet_blocks"},publicLog:{partition:np,partitions:Object.fromEntries(HC.map(n=>[n,PE(n)]))},agentsPage:`${XC()}/marketplace?tab=agents`,skills:"https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills"},op;let e=`${XC()}/.well-known/cappz-market.json`,t=await fetch(e).catch(n=>{throw new te(`Could not reach ${e}: ${n.message}`,"Check your internet connection, or practise offline with --demo.")});if(!t.ok)throw new te(`${e} answered ${t.status}.`,"Practise offline with --demo, or set CAPPZ_MIRROR_URL and CAPPZ_MIRROR_KEY.");return op=await t.json(),op}async function BE(e,t){let n=await sr(),r=await fetch(`${n.mirror.url}/auth/v1/${e}`,{method:"POST",headers:{apikey:n.mirror.publishableKey,"content-type":"application/json"},body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw new te(`Sign-in failed: ${String(i.error_description??i.msg??i.message??r.status)}`);return i}var FE=e=>{let t=e.user;return{accessToken:String(e.access_token),refreshToken:String(e.refresh_token),expiresAt:Date.now()+Number(e.expires_in??3600)*1e3,userId:t.id,email:t.email}};async function GC(e,t,n=!1){if(n){let r=await BE("signup",{email:e,password:t});return r.access_token?(await is("session.json",FE(r),!0),{email:e,confirmed:!0}):{email:e,confirmed:!1}}return await is("session.json",FE(await BE("token?grant_type=password",{email:e,password:t})),!0),{email:e,confirmed:!0}}async function km(e=!0){let t=await ga("session.json");if(!t&&process.env.CAPPZ_EMAIL&&process.env.CAPPZ_PASSWORD&&(await GC(process.env.CAPPZ_EMAIL,process.env.CAPPZ_PASSWORD),t=await ga("session.json")),t&&t.expiresAt-Date.now()<6e4)try{t=FE(await BE("token?grant_type=refresh_token",{refresh_token:t.refreshToken})),await is("session.json",t,!0)}catch{t=null}if(!t&&e)throw new te("Not signed in to the CAPPZ marketplace.","Run: cappz-market login --email you@example.com --password \u2026 (add --signup the first time), or set CAPPZ_EMAIL and CAPPZ_PASSWORD.");return t}function rF(e,t){return{async insert(n){let r=await sr(),i=await fetch(`${r.mirror.url}/rest/v1/${r.mirror.table}`,{method:"POST",headers:{apikey:r.mirror.publishableKey,authorization:`Bearer ${e??r.mirror.publishableKey}`,"content-type":"application/json",prefer:"return=minimal"},body:JSON.stringify(n)});return{error:i.ok?null:{message:`${i.status} ${await i.text()}`}}},async select(n,r){let i=await sr(),o=new URLSearchParams({select:"metadata,created_at",query_hash:`eq.${t}`,chainlet_id:"is.null",order:"created_at.asc",limit:String(r)});n&&o.append("created_at",`gte.${n}`);let a=await fetch(`${i.mirror.url}/rest/v1/${i.mirror.table}?${o}`,{headers:{apikey:i.mirror.publishableKey,authorization:`Bearer ${e??i.mirror.publishableKey}`}});return a.ok?{data:await a.json(),error:null}:{data:null,error:{message:`${a.status} ${await a.text()}`}}}}}async function $de(){let e=await ga("demo.json");if(e){let n=new Em(e.now);n.txs=e.txs,n.state=ip(e.txs);for(let[r,i]of Object.entries(e.boxKeys??{}))n.boxKeys.set(r,i);return n}let t=await LE(new Date().toISOString());return await $E(t),t}async function $E(e){await is("demo.json",{now:e.now(),txs:e.txs,boxKeys:Object.fromEntries(e.boxKeys)})}async function iF(){await $E(await LE(new Date().toISOString()))}var qE=async e=>`p-${(await la(`marketplace-agent-party|${e}`)).slice(0,16)}`;async function dt(e,t=!1){if(e.demo){let p=await $de(),h=e.as??su;return{mode:"demo",network:"testnet",get state(){return p.state},get txs(){return p.txs},policy:fa(p.txs),partyId:h,actor:g=>p.as(h,5,g),async commit(g){p.apply(g),await $E(p)},now:()=>p.now(),aside:0}}let n=zi(e),r=await sr(),i=r.publicLog.partitions?.[n]??(n==="testnet"?r.publicLog.partition:null);if(i!==PE(n))throw new te(`The marketplace at ${Yn()} does not list a ${n} market this tool can use.`,"Update cappz-market, or pick another --network.");let o=await km(t),a=rF(o?.accessToken??null,i),s=await LB(a,null),c=BB(s),l=c.accepted,u=ip(l),d=o?await qE(o.userId):null;return{mode:"live",network:n,state:u,txs:l,policy:oL(n),partyId:d,aside:c.rejected.length,actor(p){if(!d)throw new te("Sign in to act on the live market.","Run: cappz-market login");return{partyId:d,at:new Date().toISOString(),network:n,...p?{coSignedBy:p}:{}}},async commit(p,h={}){let g=await km(!0),w=h.operator??p.every(k=>k.sourceAddress.startsWith(`${gn}/operators/`));await NB(rF(g.accessToken,i),p,await RB(g.userId),w?null:d,i);let T=await ga(`own-txs-${n}.json`)??[];await is(`own-txs-${n}.json`,[...T,...p.map(({txId:k,eventType:B,sourceAddress:D,targetAddress:P,payload:U,timestamp:F})=>({txId:k,eventType:B,sourceAddress:D,targetAddress:P,payload:U,timestamp:F}))])},now:()=>new Date().toISOString()}}async function ap(){if(process.env.XRPL_SEED)return{wallet:cu.Wallet.fromSeed(process.env.XRPL_SEED),network:process.env.XRPL_NETWORK??null,source:"env"};let e=await ga("wallet.json");return e?{wallet:QB(cu.Wallet,e.seed,e.address).wallet,network:e.network,source:"file"}:null}async function os(){let e=await ap();if(!e)throw new te("No XRPL wallet yet.","Run: cappz-market wallet --new (testnet: funded for free), or set XRPL_SEED to your own wallet seed.");return e.wallet}async function oF(e){if(await ga("wallet.json"))throw new te("A wallet already exists in CAPPZ_HOME; this tool never overwrites one.","Use it (cappz-market wallet), or point CAPPZ_HOME at a new folder.");let t=cu.Wallet.generate();if(await is("wallet.json",{seed:t.seed,address:t.classicAddress,network:e},!0),e==="mainnet")return{address:t.classicAddress,funded:!1};let n=new cu.Client(vo[e]);await n.connect();try{return await n.fundWallet(t),{address:t.classicAddress,funded:!0}}catch{return{address:t.classicAddress,funded:!1}}finally{await n.disconnect().catch(()=>{})}}async function sp(e,t){let n=new cu.Client(vo[t]);await n.connect();try{let r=(await n.request({command:"server_info"})).result.info,i=Number(r.validated_ledger?.reserve_base_xrp??1),o=Number(r.validated_ledger?.reserve_inc_xrp??.2);try{let a=(await n.request({command:"account_info",account:e,ledger_index:"validated"})).result.account_data,s=Number(a.Balance)/1e6,c=Number(a.OwnerCount??0);return{address:e,network:t,activated:!0,balanceXrp:s,reserveBaseXrp:i,reserveOwnerXrp:o,ownedObjects:c,spendableXrp:Math.max(0,Math.round((s-i-c*o)*1e6)/1e6)}}catch{return{address:e,network:t,activated:!1,balanceXrp:0,reserveBaseXrp:i,reserveOwnerXrp:o,ownedObjects:0,spendableXrp:0}}}finally{await n.disconnect().catch(()=>{})}}async function _m(){let e=await ga("box-key.json");if(e)return e;let t=await db();return await is("box-key.json",t,!0),t}async function aF(e,t,n){let r=await ga("escrow-secrets.json")??{};r[`${e}:${t}`]=n,await is("escrow-secrets.json",r,!0)}async function sF(e,t){return(await ga("escrow-secrets.json")??{})[`${e}:${t}`]??null}var qde=14*864e5;async function YC(){return ga("agent-key.json")}async function cF(e=Date.now()){let t=await YC();if(t&&Date.parse(t.declaration.expiresAt)-e>qde)return t;let n=t?pa(t.walletPrivateKey):pR.randomSecretKey(),r=t?.walletAddress??Fr(f4(n,!0)),i=t?pa(t.secretKey):crypto.getRandomValues(new Uint8Array(32)),o=await kL(n,r,{publicKey:Fr(Kn.getPublicKey(i)),algorithm:"ed25519",purpose:"signing",...t?{supersedes:await cE(t.declaration)}:{}},void 0,e),a={walletPrivateKey:Fr(n),walletAddress:r,secretKey:Fr(i),declaration:o};return await is("agent-key.json",a,!0),a}async function lF(e,t){let n=await YC();return!n||!e||!t||t.publicKey.toLowerCase()!==n.declaration.publicKey.toLowerCase()?null:{partyId:e,declaration:t,secretKeyHex:n.secretKey}}var ko=WC,Yn=XC;y();qo();Bo();var Hde=`cappz-stage-verdict/v1 `;var Vde=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),uF=e=>new Uint8Array((e.match(/../g)??[]).map(t=>parseInt(t,16))),Kde=e=>Vde(_t(e));function HE(e,t){if(t&&e.signature.publicKey.toLowerCase()!==t.toLowerCase())return!1;try{return Kn.verify(uF(e.signature.value),new TextEncoder().encode(Hde+Br(e.verdict)),uF(e.signature.publicKey))}catch{return!1}}var dF=e=>Kde(new TextEncoder().encode(Br(e)));function fF(e,t,n){let r=t.verdict;if(!HE(t,n))return{ok:!1,because:"The verdict\u2019s signature does not match the evaluator service\u2019s published key."};if(r.verdict.state!=="pass")return{ok:!1,because:`The verdict is ${r.verdict.state}: ${r.verdict.reasons.join(" ")}`};if(r.criteria.source!=="contract")return{ok:!1,because:"The verdict used criteria the requester supplied, not criteria agreed in the contract; accept by your own review instead."};let i=e.contracts.find(a=>a.contractId===r.contractId),o=i?.milestoneStates[r.milestone];return!i||!o?{ok:!1,because:"The contract or milestone is not on this market."}:o.state!=="evidenced"?{ok:!1,because:`\u201C${i.milestones[r.milestone].label}\u201D is ${o.state}, not waiting for acceptance.`}:o.evidence[o.evidence.length-1]?.hash!==r.deliverableSha256?{ok:!1,because:"The seller has published newer evidence since this verdict; evaluate the new file."}:!i.milestones[r.milestone].acceptance||sm(i.milestones[r.milestone].acceptance)!==r.criteria.specSha256?{ok:!1,because:"The verdict\u2019s criteria are not the contract\u2019s agreed criteria."}:{ok:!0,because:`Signed pass on the contract\u2019s agreed criteria for the current evidence of \u201C${i.milestones[r.milestone].label}\u201D.`}}y();function pF(e,t){return e.listings.filter(n=>n.sellerId===t).map(n=>{let r=e.contracts.filter(o=>o.source.kind==="listing"&&o.source.listingId===n.listingId),i=n.milestones?.find(o=>o.delivery)??n.milestones?.at(-1);return{listing:n,state:n.open?n.remaining<=0?"sold-out":"open":"closed",closed:n.closed??null,orders:{total:r.length,inProgress:r.filter(o=>o.state==="in-progress"||o.state==="awaiting-funding").length,completed:r.filter(o=>o.state==="completed").length,disputed:r.filter(o=>o.state==="disputed").length},contractIds:r.map(o=>o.contractId).reverse(),acceptance:i?.acceptance??null}}).sort((n,r)=>(n.state==="closed"?1:0)-(r.state==="closed"?1:0)||r.listing.publishedAt.localeCompare(n.listing.publishedAt))}function yF(e,t){if(!e.open)throw new Error("This listing is closed. List it again with sell (a closed listing is never reopened).");let{open:n,remaining:r,publishedAt:i,closed:o,...a}=e,s={...a,attributes:{...a.attributes}};if(t.title!==void 0){if(!t.title.trim())throw new Error("A title cannot be empty.");s.title=t.title.trim()}if(t.description!==void 0&&(s.description=t.description.trim()||s.title),t.price!==void 0){if(!(t.price>0))throw new Error("Price must be more than zero.");s.pricePerUnit={...s.pricePerUnit,amount:t.price}}let c=0;if(t.available!==void 0){if(!(t.available>=0)||!Number.isFinite(t.available))throw new Error("Available must be zero or more.");c=t.available-e.remaining}if(t.leadDays!==void 0){if(!(t.leadDays>=0))throw new Error("Lead days must be zero or more.");s.leadDays=Math.round(t.leadDays)}if(t.endpoint!==void 0)if(t.endpoint===null||t.endpoint==="")delete s.attributes.endpoint;else if(/^https:\/\//.test(t.endpoint))s.attributes.endpoint=t.endpoint;else throw new Error("The endpoint must be an https address buyers can reach.");if(t.acceptance!==void 0){if(s.metered)throw new Error("A metered listing has no stages to accept.");if(t.acceptance===null)s.milestones=s.milestones?.map(({acceptance:u,...d})=>d);else{let u=Bf(t.acceptance);if(u.length)throw new Error(`Acceptance criteria rejected: ${u.join(" ")}`);let d=s.milestones??hC(s.leadDays)["on-delivery"].plan;s.milestones=d.map((p,h)=>p.delivery||h===d.length-1?{...p,acceptance:t.acceptance}:p)}}return{amend:Object.keys(t).some(u=>u!=="available"&&t[u]!==void 0)?s:null,inventoryDelta:c}}var hF=(e,t)=>t===0?"Seller paused orders":e.remaining===0?`Seller restocked to ${t}`:`Seller set available to ${t}`;async function cp(e){let t=e.partyId?e.state.parties.get(e.partyId):void 0,n=await lF(e.partyId,t?.keyDeclaration);return n?eB(n):void 0}async function lp(e,t,n,r,i,o){let s=(await sr()).services?.counterpartyCheck;if(!s?.url||!s.publicKey){if(e==="mainnet")throw new te(`${Yn()} publishes no signing-approval service, so mainnet escrow is not signed.`);return r.push(`none (no approval service published for ${e})`),Qf}if(!s.networks.includes(e))return r.push(`none (the approval service covers ${s.networks.join(" and ")}, not ${e})`),Qf;let c=aB({serviceUrl:s.url,publicKey:s.publicKey,network:e,contractId:t,milestone:n,coSignature:i,signRequest:o,onApproved:l=>r.push(l.approval.requestAuth?`${l.approval.txHash} (request ${l.approval.requestAuth.state})`:l.approval.txHash)});return{...Qf,approve:async l=>{try{await c(l)}catch(u){throw new te(u.message,"Check the deal with: cappz-market show "+t)}}}}function VE(e,t,n){return e.state.mandates.filter(i=>i.agentPartyId===t.buyerId).map(i=>i.grantedBy).find(i=>{let o=e.state.parties.get(i)?.xrplAccount;return!!o&&CE(n,o,new Date().toISOString()).length===0})}async function mF(e){if(e===void 0)return;let t=String(e).trim().startsWith("{")?String(e):await Zn(JC(String(e)),"utf8");try{let n=JSON.parse(t);if(!n.terms||!n.txBlob)throw new Error("shape");return n}catch{throw new te("--co-signature must be the JSON (or a file of it) that cappz-market cosign printed.")}}var ye=(e,t,n)=>{let r=e[t];if(r==null||r===""){if(n!==void 0)return n;throw new te(`Missing ${t}.`)}return String(r)},Ye=(e,t,n)=>{let r=e[t];if(r==null||r===""){if(n!==void 0)return n;throw new te(`Missing ${t}.`)}let i=Number(r);if(!Number.isFinite(i))throw new te(`${t} must be a number, got \u201C${String(r)}\u201D.`);return i},ss=e=>Array.isArray(e)?e.map(String):typeof e=="string"&&e?e.split(",").map(t=>t.trim()).filter(Boolean):[],lu=(e,t)=>({amount:e,currency:t}),up=e=>{let t=dC(ye(e,"currency","XRP"));if(!t)throw new te(`currency is one of ${Nf.map(n=>`${n.code}${n.label!==n.code?` (${n.label})`:""}`).join(", ")}.`);return t},gF=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))throw new te(`Dates are YYYY-MM-DD, got \u201C${e}\u201D.`);return e},Xde=(e,t)=>new Date(Date.parse(e)+t*864e5).toISOString().slice(0,10),jE=(e,t)=>`${e.amount} ${e.currency}/${t}`;async function dp(e){if(e.acceptance===void 0||e.acceptance==="")return;let t=typeof e.acceptance=="object"?e.acceptance:(()=>{let i=String(e.acceptance).trim();return i.startsWith("{")?i:null})(),n;try{n=typeof t=="object"&&t!==null?t:JSON.parse(t??await Zn(String(e.acceptance),"utf8"))}catch{throw new te('--acceptance is JSON ({"version": 1, "criteria": [\u2026]}) or a file of it.')}let r=Bf(n);if(r.length)throw new te(`Acceptance criteria rejected: ${r.join(" ")}`,"Format: skills/evaluating-cappz-deliverables/reference/acceptance-criteria.md");return n}var fp={name:"acceptance",type:"string",description:"Acceptance criteria for the delivered result (JSON or a file): what an evaluator checks. Format: skills/evaluating-cappz-deliverables/reference/acceptance-criteria.md"},wF=async e=>Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e)),t=>t.toString(16).padStart(2,"0")).join("");function Im(e){if(!gr(e))throw new te(`Unknown category \u201C${e}\u201D.`,`Use one of: ${Eh.map(t=>t.id).join(", ")}.`);return e}function KE(e){if(!(0,vF.isValidClassicAddress)(e))throw new te(`${e} is not a valid XRPL classic address.`);return e}function Pm(e){let t=e.toUpperCase();if(!fb[t])throw new te(`Unknown region \u201C${e}\u201D. Regions are two-letter US state codes (no street addresses go on the public log).`);return t}var zE=(e,t)=>({id:t.listingId,title:t.title,kind:t.kind,category:t.categoryId,price:jE(t.pricePerUnit,t.unit),available:t.remaining,unit:t.unit,region:t.region,readyInDays:t.leadDays,seller:t.sellerId,sellerName:e.parties.get(t.sellerId)?.name??null,...t.attributes?.endpoint?{endpoint:t.attributes.endpoint,hire:`cappz-market hire ${t.attributes.endpoint} --input "\u2026" --max ${t.pricePerUnit.amount}`}:{}}),bF=(e,t)=>({id:t.requestId,title:t.title,category:t.categoryId,quantity:t.quantity,unit:t.unit,maxPrice:t.maxPricePerUnit?jE(t.maxPricePerUnit,t.unit):"open",neededBy:t.neededBy,region:t.region,open:t.open,bids:t.offers.filter(n=>!n.withdrawn).length,buyer:t.buyerId,buyerName:e.parties.get(t.buyerId)?.name??null});function CF(e,t){let n=ar(e.total.amount,e.milestones),r=e.buyerId===t?"buyer":e.sellerId===t?"seller":e.evaluatorId&&e.evaluatorId===t?"evaluator":"observer";return{id:e.contractId,title:e.title,role:r,total:`${e.total.amount} ${e.total.currency}`,state:e.state,waitingOnYou:e.nextAction.by==="buyer"&&r==="buyer"||e.nextAction.by==="seller"&&r==="seller",nextAction:e.nextAction,settlement:at(e)==="ledger-channel"?"XRP payment channel on the ledger (metered)":e.total.currency==="XRP"?"XRP escrow on the ledger":at(e)==="ledger-staged"?`${Et(e.total.currency)} paid on the ledger per stage`:"USD",...e.channel?{channel:e.channel}:{},escrow:e.escrow,stages:e.milestones.map((i,o)=>({index:o,label:i.label,amount:n[o],dueBy:i.dueBy,evidence:i.evidence,state:e.milestoneStates[o]?.state,onLedger:e.ledgerEscrows.some(a=>a.milestone===o)})),openDisputes:e.disputes.filter(i=>!i.resolved).length,...e.evaluatorId?{evaluator:e.evaluatorId}:{},...e.parentContractId?{parentContract:e.parentContractId}:{},...e.subcontracts.length?{subcontracts:e.subcontracts}:{}}}function di(e,t){let n=e.state.contracts.find(r=>r.contractId===t);if(!n)throw new te(`No contract ${t}.`,"List yours with: cappz-market deals");return n}async function pp(e){let t=await os(),n=e.policy.network,r=await sp(t.classicAddress,n);if(!r.activated)throw new te(`Your wallet ${t.classicAddress} is not activated on XRPL ${n}.`,n==="mainnet"?`Send it at least ${r.reserveBaseXrp} XRP (the account reserve) plus what you want to spend.`:"Run: cappz-market wallet --fund (free test XRP).");return{w:t,net:n,st:r}}function ZC(e,t,n){if(e.money&&t.mode==="live"&&t.policy.network==="mainnet"&&!n.yes)throw new te(`${e.name} moves real XRP on mainnet.`,"Confirm with the person you act for, then repeat with --yes.")}async function Dt(e,t,n={}){return await e.commit(t),{ok:!0,market:e.mode,recorded:t.map(r=>r.eventType),...n}}var yp=[{name:"setup",summary:"Check everything needed to trade and say what to do next: wallet, reserve, sign-in, profile, mandate. Safe to run any time.",params:[],async run(e,t){let n=[],r=await dt(t).catch(c=>{throw c}),i=r.policy.network;n.push({step:"market",ok:!0,detail:r.mode==="demo"?"practice market (local, nothing is published, no real money)":`${i} market at ${Yn()}${i==="mainnet"?" \u2014 real XRP":" \u2014 test XRP, no value"} (choose with --network devnet|testnet|mainnet)`});let o=await ap();if(!o)n.push({step:"wallet",ok:!1,detail:"no XRPL wallet \u2014 bring your own funded wallet (XRPL_SEED) or create one here",next:i==="mainnet"?`cappz-market wallet --new, then: ${So({network:i,currency:"XRP",amount:0,accountExists:!1}).steps.join(" ")}`:"cappz-market wallet --new (funded with free test XRP)"});else if(r.mode==="demo")n.push({step:"wallet",ok:!0,detail:`${o.wallet.classicAddress} (not used by the practice market)`});else{let c=await sp(o.wallet.classicAddress,i);n.push({step:"wallet",ok:c.activated&&c.spendableXrp>0,detail:c.activated?`${c.address}: ${c.balanceXrp} XRP, ${c.spendableXrp} spendable (reserve ${c.reserveBaseXrp} + ${c.ownedObjects} \xD7 ${c.reserveOwnerXrp} XRP)`:`${c.address} is not activated on ${i}`,next:c.activated?void 0:i==="mainnet"?So({network:i,currency:"XRP",amount:0,accountExists:!1}).steps.join(" "):"cappz-market wallet --fund"})}if(r.mode==="live"){let c=await km(!1);n.push({step:"sign-in",ok:!!c,detail:c?`signed in as ${c.email}`:"not signed in (reading works; trading needs an account)",next:c?void 0:"cappz-market login --email \u2026 --password \u2026 (--signup the first time)"})}let a=r.partyId?r.state.parties.get(r.partyId):null;if(n.push({step:"profile",ok:!!a,detail:a?`${a.name} (${a.kind}, party ${a.partyId})`:`no profile for party ${r.partyId??"(sign in first)"}`,next:a?void 0:'cappz-market profile --name "\u2026" --kind agent --principal (or --kind organization if you act for yourself)'}),a?.kind==="agent"){let c=r.state.mandates.filter(u=>u.agentPartyId===a.partyId&&Date.parse(u.limits.expiresAt)>Date.parse(r.now())),l=await sr().catch(()=>null);n.push({step:"mandate",ok:c.length>0,detail:c.length?c.map(u=>`${u.limits.verbs.map(d=>d.replace("marketplace.","")).join(", ")} \u2264 ${u.limits.maxPerContract.amount} ${u.limits.maxPerContract.currency}/contract until ${u.limits.expiresAt.slice(0,10)}`).join("; "):"no active mandate \u2014 an agent party cannot list, bid, buy or pay",next:c.length?void 0:`ask the person you act for to grant one at ${l?.agentsPage??`${Yn()}/marketplace?tab=agents`} (agent party id ${a.partyId})`})}let s=n.find(c=>!c.ok)?.next??(r.mode==="demo"?"Practised? Validate on testnet next: cappz-market setup --network testnet":i==="mainnet"?'Ready on mainnet (real XRP). Try: cappz-market find "what you need" --network mainnet':`Ready on ${i}. Validate your whole flow here, then go live: cappz-market setup --network mainnet`);return{ready:n.every(c=>c.ok),steps:n,next:s}}},{name:"wallet",summary:"Show your XRPL wallet on the chosen network: address, balance, reserve and what is spendable. --new creates one (testnet/devnet: funded free); --fund tops up from the test faucet. One wallet works on every network; each network activates it separately.",params:[{name:"new",type:"boolean",description:"Create a wallet (kept in CAPPZ_HOME, file mode 0600). Never overwrites."},{name:"fund",type:"boolean",description:"Testnet/devnet only: ask the public faucet for test XRP."}],async run(e,t){let n=zi(t);if(e.new){let o=await oF(n);return{created:o.address,network:n,funded:o.funded,keptIn:ko(),next:o.funded||n!=="mainnet"?"cappz-market setup":`Send at least the reserve (see cappz-market wallet) to ${o.address} from an exchange or another wallet.`}}let r=await os();if(e.fund){if(n==="mainnet")throw new te("There is no faucet on mainnet.","Buy XRP on an exchange and send it to your address.");let{Client:o}=await Promise.resolve().then(()=>jr(Nr(),1)),{XRPL_ENDPOINTS:a}=await Promise.resolve().then(()=>(Rl(),_O)),s=new o(a[n]);await s.connect();try{await s.fundWallet(r)}finally{await s.disconnect().catch(()=>{})}}let i=await sp(r.classicAddress,n);return{...i,assetsOnThisNetwork:PN(n).map(o=>o.label),fundIt:So({network:n,currency:"XRP",amount:0,accountExists:i.activated}).steps,tokens:"CAPPZ and RLUSD (USD-tokenZ) need a trust line to their issuer first; cappz-market check shows what is missing.",note:"Reserves are network settings read from the ledger now. Each open escrow, offer or trust line adds one owner reserve until it closes; it is returned then."}}},{name:"trust",summary:"Let this wallet hold an issued payment asset: set the trust line to CAPPZ or RLUSD (USD-tokenZ/1), to the issuer in the CAPPZ payment-asset registry. Needed before anyone can pay you (or you can hold) that token. Locks one owner reserve (0.2 XRP) per line; skipped when the line exists.",money:!0,params:[{name:"currency",type:"string",description:"CAPPZ or USD-tokenZ/1 (RLUSD); comma-separated for both (default CAPPZ,USD-tokenZ/1).",positional:!0}],async run(e,t){let n=zi(t),r=ss(e.currency??"CAPPZ,USD-tokenZ/1").map(c=>dC(c)??(()=>{throw new te(`${c} is not a payment asset.`,"Use CAPPZ or USD-tokenZ/1 (RLUSD).")})()),i=await os(),o=await sp(i.classicAddress,n);if(!o.activated)throw new te(`Your wallet ${i.classicAddress} is not activated on XRPL ${n}.`,n==="mainnet"?So({network:n,currency:"XRP",amount:0,accountExists:!1}).steps.join(" "):"Run: cappz-market wallet --fund");let a=[],s=[];for(let c of r){let l;try{l=NN(i.classicAddress,c,n)}catch(p){a.push({asset:Et(c),state:"unavailable",reason:p.message});continue}let u=l.LimitAmount,d=await BN(n,i.classicAddress,u.issuer,u.currency);if(d.error)throw new te(`Could not read your ${Et(c)} trust line: ${d.error}`);d.present?a.push({asset:Et(c),state:"already-set",issuer:u.issuer,balance:d.balance}):s.push({code:c,tx:l})}if(s.length){if(n==="mainnet"&&!t.yes)throw new te(`Setting ${s.map(c=>Et(c.code)).join(" and ")} trust line(s) on mainnet locks ${s.length} \xD7 ${o.reserveOwnerXrp} XRP of your reserve.`,"Confirm with the person you act for, then repeat with --yes.");if(o.spendableXrp --currency USD-tokenZ/1"}}},{name:"login",summary:"Sign in to the CAPPZ marketplace (needed to publish). --signup creates the account; a person must confirm the email (human step), and --wait keeps trying until they have. Reading the market needs no sign-in.",params:[{name:"email",type:"string",description:"Account email (or CAPPZ_EMAIL). Use an inbox the person you act for reads."},{name:"password",type:"string",description:"Account password (or CAPPZ_PASSWORD)."},{name:"signup",type:"boolean",description:"Create the account first."},{name:"wait",type:"number",description:"Minutes to keep retrying until the email is confirmed (e.g. 15). Tell the person first."}],async run(e){let t=ye(e,"email",process.env.CAPPZ_EMAIL??""),n=ye(e,"password",process.env.CAPPZ_PASSWORD??"");if(!t||!n)throw new te("Give --email and --password (or set CAPPZ_EMAIL and CAPPZ_PASSWORD).");let r={humanAction:`Ask the person you act for to open the email CAPPZ sent to ${t} and click the confirmation link. This is a human step by design: do not try to confirm it yourself.`,next:"After telling them: cappz-market login --wait 15"};if(e.signup){let o=await GC(t,n,!0);return o.confirmed?{signedIn:o.email,next:"cappz-market setup"}:{created:o.email,signedIn:!1,...r}}let i=Date.now()+Ye(e,"wait",0)*6e4;for(;;)try{return{signedIn:(await GC(t,n)).email,next:"cappz-market setup"}}catch(o){if(!/not confirmed/i.test(o.message))throw o;if(Date.now()>i)return{signedIn:!1,waitingFor:"email confirmation",...r};await new Promise(a=>setTimeout(a,1e4))}}},{name:"profile",summary:"Create or update your marketplace profile. Agents use --kind agent with --principal (the party id of the person or company they act for).",params:[{name:"name",type:"string",description:"Public name.",required:!0},{name:"kind",type:"string",description:"agent (default), person or organization."},{name:"principal",type:"string",description:"Agents: the party id you act for (shown on their web profile)."},{name:"governance",type:"string",description:"Non-human companies: governance address instead of a principal."},{name:"region",type:"string",description:"Two-letter US state code (default TX). No street addresses."},{name:"about",type:"string",description:"What you offer or need."},{name:"categories",type:"string",description:"Comma-separated category ids you supply."},{name:"roles",type:"string",description:"Comma-separated: buyer, seller, service-provider, supplier\u2026 (default buyer,seller)."},{name:"runtime",type:"string",description:"Agents: model/runtime you run on, shown for transparency."},{name:"xrplAccount",type:"string",description:"Public XRPL address you are paid at, if not this tool's wallet (e.g. a treasury or cold wallet). Only the address is needed, never its seed; buyers fund escrow from their own wallets."}],async run(e,t){let n=await dt(t,!0),r=n.partyId,i=ye(e,"kind","agent");if(!["agent","person","organization"].includes(i))throw new te("kind is agent, person or organization.");let o=n.state.parties.get(r),a=await ap(),s=await _m(),c=e.principal?{partyId:String(e.principal)}:e.governance?{governanceAddress:String(e.governance)}:o?.principal,l=i==="agent"&&n.mode==="live"?await cF():null,u={partyId:r,kind:i,name:ye(e,"name"),roles:ss(e.roles).length?ss(e.roles):o?.roles??["buyer","seller"],region:Pm(ye(e,"region",o?.region??"TX")),about:ye(e,"about",o?.about??""),capabilities:{categories:ss(e.categories).map(Im).length?ss(e.categories):o?.capabilities.categories??[],canPlantNew:o?.capabilities.canPlantNew??!1},...c?{principal:c}:{},...e.xrplAccount?{xrplAccount:KE(String(e.xrplAccount))}:a?{xrplAccount:a.wallet.classicAddress}:o?.xrplAccount?{xrplAccount:o.xrplAccount}:{},encryptionKey:s.publicKey,...e.runtime?{runtime:String(e.runtime)}:o?.runtime?{runtime:o.runtime}:{},...l?{keyDeclaration:l.declaration}:o?.keyDeclaration?{keyDeclaration:o.keyDeclaration}:{},...o?.keyRevocations?{keyRevocations:o.keyRevocations}:{},...o?.principalCredential?{principalCredential:o.principalCredential}:{}},d=await jf(n.state,n.actor(),u);return Dt(n,d,{partyId:r,xrplAccount:u.xrplAccount??null,signingKey:u.keyDeclaration?{keyId:u.keyDeclaration.publicKey,declaredBy:u.keyDeclaration.walletAddress,expiresAt:u.keyDeclaration.expiresAt}:null,next:i==="agent"?`Ask your principal to grant a mandate to ${r} at ${Yn()}/marketplace?tab=agents, then run cappz-market setup.`:'cappz-market find "\u2026"'})}},{name:"cosign",summary:"Mandate grantor (a person): co-sign one stage of your agent\u2019s deal that is above its approval threshold. Signs a statement with your own XRPL wallet (never submitted, no fee) and prints it; give it to the agent for fund --co-signature.",params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"milestone",type:"number",description:"Stage index (default: the stage to fund now)."},{name:"hours",type:"number",description:"How long the co-signature is valid (default 24)."}],async run(e,t){let n=await dt(t,!0),r=di(n,ye(e,"contract")),i=at(r)==="ledger-staged"?"pay":at(r)==="ledger-channel"?"channel":"fund",o=n.state.parties.get(r.buyerId);if(o?.kind!=="agent")throw new te("Only an agent buyer\u2019s stages need a co-signature.");let a=new Set(n.state.mandates.filter(T=>T.agentPartyId===o.partyId).map(T=>T.grantedBy));if(!n.partyId||!a.has(n.partyId))throw new te(`Only a party that granted ${o.name} a mandate can co-sign (${[...a].join(", ")||"none"}).`);let s=n.state.parties.get(n.partyId),c=await os();if(s.xrplAccount!==c.classicAddress)throw new te(`Your profile\u2019s XRPL account is ${s.xrplAccount??"missing"}, but this wallet is ${c.classicAddress}.`,"The co-signature must come from the account on your profile: cappz-market profile --xrpl-account \u2026");if(!c.seed)throw new te("This wallet has no seed on this computer, so it cannot sign.");let l=e.milestone===void 0?ya(r)?.index??0:Ye(e,"milestone"),u=n.state.parties.get(r.sellerId)?.xrplAccount;if(!u)throw new te("The seller has no XRPL account on their profile yet.");let d=i==="channel"?tu(r).toString():(i==="pay"?Vf(r,l,u).map(T=>T.units):eu(r,l,u).map(T=>T.drops)).reduce((T,k)=>T+BigInt(k),0n).toString(),p={network:n.policy.network,contractId:r.contractId,milestone:l,action:i,amountDrops:d,expiresAt:new Date(Date.now()+Ye(e,"hours",24)*36e5).toISOString()},h=c.sign(iB(c.classicAddress,p)),g={terms:p,txBlob:h.tx_blob},w=CE(g,c.classicAddress,new Date().toISOString());if(w.length)throw new te(`Could not make a valid co-signature: ${w.join(" ")}`);return{coSigned:`${r.title} \u2014 stage ${l} (${r.milestones[l]?.label??""}): ${$n(om(Number(d),r.total.currency),r.total.currency)} on ${p.network}`,validUntil:p.expiresAt,coSignature:g,next:`Give the agent the coSignature JSON: cappz-market ${i==="pay"?"release":"fund"} ${r.contractId} --co-signature '' (or a file). Nothing was submitted to the ledger.`}}},{name:"mandate",summary:"Principal (a person or organization running this tool): grant your agent a mandate \u2014 what it may do, in which categories, up to how much \u2014 or revoke one. Agents cannot grant themselves anything.",params:[{name:"agent",type:"string",description:"The agent\u2019s party id (it prints it in setup).",positional:!0},{name:"actions",type:"string",description:"buy, sell or both (default buy), or comma-separated verbs (see ops)."},{name:"categories",type:"string",description:"Comma-separated category ids (default: any)."},{name:"maxContract",type:"number",description:"Most per contract (default 100)."},{name:"maxDay",type:"number",description:"Most per day (default 3 \xD7 max-contract)."},{name:"askAbove",type:"number",description:"Above this value the agent needs your co-signature."},{name:"currency",type:"string",description:"XRP (default), CAPPZ, USD-tokenZ/1 (RLUSD) or USD: the mandate covers deals in this asset only (grant one per asset)."},{name:"days",type:"number",description:"Valid for this many days (default 30)."},{name:"revoke",type:"string",description:"Revoke this mandate id instead (see setup or show )."},{name:"bindKey",type:"boolean",description:"Bind the mandate to the agent\u2019s declared signing key: its approval requests must then be signed by that key."}],async run(e,t){let n=await dt(t,!0),r=n.state.parties.get(n.partyId);if(!r)throw new te("Create your profile first.",'cappz-market profile --name "\u2026" --kind organization');if(r.kind==="agent")throw new te("An agent cannot grant mandates; its principal does.",`Ask your principal to run this, or to grant it at ${Yn()}/marketplace?tab=agents`);if(e.revoke)return Dt(n,await $L(n.state,n.actor(),ye(e,"revoke")),{revoked:ye(e,"revoke")});let i=ye(e,"agent"),o=n.state.parties.get(i);if(!o||o.kind!=="agent")throw new te(`No agent party ${i} on the ${n.network} market.`,"The agent runs cappz-market profile --kind agent first (on this network).");let a=["marketplace.order.place","marketplace.request.post","marketplace.offer.award","marketplace.escrow.fund","marketplace.milestone.affirm","marketplace.escrow.release","marketplace.stage.pay","marketplace.channel.open","marketplace.channel.close"],s=["marketplace.listing.publish","marketplace.offer.submit","marketplace.milestone.evidence","marketplace.channel.settle","marketplace.channel.close"],c=ye(e,"actions","buy"),l=c==="buy"?a:c==="sell"?s:c==="both"?[...a,...s]:ss(c),u=up(e),d=Ye(e,"maxContract",100),p={verbs:l,categories:ss(e.categories).map(Im),maxPerContract:lu(d,u),maxPerDay:lu(Ye(e,"maxDay",d*3),u),approvalAbove:e.askAbove!==void 0?lu(Ye(e,"askAbove"),u):null,expiresAt:new Date(Date.parse(n.now())+Ye(e,"days",30)*864e5).toISOString()};if(e.bindKey&&!o.keyDeclaration)throw new te(`${o.name} declares no signing key yet.`,"The agent runs cappz-market profile (it declares one), then grant again with --bind-key.");let h=e.bindKey?o.keyDeclaration.publicKey:void 0,g=await Zf(n.state,n.actor(),i,p,h?{boundKey:h}:{});return Dt(n,g.txs,{mandateId:g.mandateId,agent:i,limits:p,boundKey:h??null,next:`The agent can act now on ${n.network}: it runs cappz-market setup${n.network==="testnet"?"":` --network ${n.network}`}`})}},{name:"find",summary:"Search what is for sale (default) or wanted (--wanted). Ranked, typo-tolerant; filter by category and region.",params:[{name:"text",type:"string",description:"What to look for, in plain words.",positional:!0},{name:"wanted",type:"boolean",description:"Search open requests (what buyers want) instead of listings."},{name:"category",type:"string",description:"Category id (e.g. agents, services, digital, goods, crops)."},{name:"region",type:"string",description:"Two-letter state code."},{name:"limit",type:"number",description:"Max results (default 20)."}],async run(e,t){let n=await dt(t),r=n.state,i=Ye(e,"limit",20),o=e.text?String(e.text):"",a=e.category?Im(String(e.category)):null,s=e.region?Pm(String(e.region)):null,c=d=>!a||d===a||d.startsWith(`${a}/`)||Ya(d)===a;if(e.wanted){let d=o?ns(r,o,{kinds:["request"]}).map(g=>g.id):null,p=r.requests.filter(g=>g.open&&c(g.categoryId)&&(!s||g.region===s)&&(!d||d.includes(g.requestId))).sort((g,w)=>d?d.indexOf(g.requestId)-d.indexOf(w.requestId):0),h=n.partyId&&r.parties.get(n.partyId)?LC(r,r.parties.get(n.partyId),r.listings,n.now()).slice(0,5).map(g=>({id:g.id,title:g.title,why:g.reasons})):[];return{wanted:p.slice(0,i).map(g=>bF(r,g)),total:p.length,youCouldFill:h,next:p.length?"cappz-market bid --price \u2026 --quantity \u2026 --by YYYY-MM-DD":"Nothing open matches. Offer it anyway: cappz-market sell \u2026"}}let l=o?ns(r,o,{kinds:["listing"]}).map(d=>d.id):null,u=r.listings.filter(d=>d.open&&d.remaining>0&&c(d.categoryId)&&(!s||d.region===s)&&(!l||l.includes(d.listingId))).sort((d,p)=>l?l.indexOf(d.listingId)-l.indexOf(p.listingId):0);return{forSale:u.slice(0,i).map(d=>zE(r,d)),total:u.length,next:u.length?"cappz-market buy --quantity \u2026":'Nothing listed matches. Ask for it: cappz-market ask --title "\u2026" --category \u2026 --quantity \u2026 --unit \u2026 --by YYYY-MM-DD'}}},{name:"show",summary:"Show one listing, request (with its bids), contract, party or token by id.",params:[{name:"id",type:"string",description:"Any id from find or deals.",required:!0,positional:!0}],async run(e,t){let n=await dt(t),r=n.state,i=ye(e,"id"),o=r.listings.find(u=>u.listingId===i);if(o)return{listing:{...zE(r,o),description:o.description,delivery:o.delivery,paymentSchedule:o.milestones??"category default",attributes:o.attributes,knowledge:o.knowledge??null,open:o.open}};let a=r.requests.find(u=>u.requestId===i);if(a)return{request:{...bF(r,a),description:a.description,contractType:a.contractType,recurring:a.recurring??null,bids:a.offers.filter(u=>!u.withdrawn).map(u=>({id:u.offerId,seller:u.sellerId,sellerName:r.parties.get(u.sellerId)?.name??null,price:jE(u.pricePerUnit,a.unit),quantity:u.quantity,delivers:u.deliveryDate,stages:u.milestones.length,awarded:u.awardedQuantity}))}};let s=r.contracts.find(u=>u.contractId===i);if(s)return{deal:CF(s,n.partyId)};let c=r.parties.get(i);if(c)return{party:{...c,encryptionKey:c.encryptionKey?"present":null,reputation:r.reputation.get(i)??null}};let l=r.tokens.find(u=>u.content.tokenId===i);if(l)return{token:{...l.content,balances:l.balances,redeemed:l.redeemed}};throw new te(`Nothing with id ${i}.`,"Ids come from find, deals or show.")}},{name:"deals",summary:"Your contracts, the ones waiting on you first, each with its stages, escrow and next action.",params:[],async run(e,t){let n=await dt(t);if(!n.partyId)throw new te("Sign in to see your deals.","cappz-market login");let r=n.state.contracts.filter(i=>i.buyerId===n.partyId||i.sellerId===n.partyId||!!i.evaluatorId&&i.evaluatorId===n.partyId).map(i=>CF(i,n.partyId));return r.sort((i,o)=>Number(o.waitingOnYou)-Number(i.waitingOnYou)),{deals:r,waitingOnYou:r.filter(i=>i.waitingOnYou).length,next:r.find(i=>i.waitingOnYou)?.nextAction.action??(r.length?"Nothing waits on you.":"No deals yet: buy, or win a bid.")}}},{name:"sell",summary:"List something for sale, rent or as a service (agent work included). Buyers pay into escrow; you are paid stage by stage.",params:[{name:"title",type:"string",description:"What it is.",required:!0},{name:"category",type:"string",description:"Category id (agents, services, digital, goods, equipment, land, relay, crops, inputs\u2026).",required:!0},{name:"price",type:"number",description:"Price per unit.",required:!0},{name:"unit",type:"string",description:"Unit (job, hour, each, lb\u2026). Default: the category\u2019s first unit."},{name:"quantity",type:"number",description:"How many units are available (default 1)."},{name:"currency",type:"string",description:"XRP (default; escrowed per stage), CAPPZ or USD-tokenZ/1 (RLUSD; paid on the ledger per accepted stage), or USD (card or bank in the web app)."},{name:"kind",type:"string",description:"sale, rent, service or production-contract (default: the category\u2019s first)."},{name:"description",type:"string",description:"Details buyers need."},{name:"delivery",type:"string",description:"online, ship, pickup or on-site (default online for agents/digital, else ship)."},{name:"leadDays",type:"number",description:"Days from order to delivery (default 7)."},{name:"region",type:"string",description:"State code (default your profile\u2019s)."},{name:"endpoint",type:"string",description:"Paid agents: the https address buyers (and cappz-market hire) call."},{name:"metered",type:"boolean",description:"XRP only: sell metered use (unit = query, MB, call\u2026; price per unit). A buyer\u2019s quantity is a cap paid through a ledger payment channel as it is used."},fp],async run(e,t){let n=await dt(t,!0),r=n.state.parties.get(n.partyId);if(!r)throw new te("Create your profile first.",'cappz-market profile --name "\u2026"');let i=gr(Im(ye(e,"category")));if(e.endpoint&&!/^https:\/\//.test(String(e.endpoint)))throw new te("endpoint must be an https address buyers can reach (e.g. your tunnel URL).");let o=ye(e,"kind",i.kinds[0]);if(!i.kinds.includes(o))throw new te(`${i.label} takes kind ${i.kinds.join(" or ")}.`);let a=Ya(i.id),s={listingId:Tc("l"),sellerId:r.partyId,categoryId:i.id,kind:o,title:ye(e,"title"),description:ye(e,"description",ye(e,"title")),unit:ye(e,"unit",i.units[0]),pricePerUnit:lu(Ye(e,"price"),up(e)),quantity:Ye(e,"quantity",1),region:Pm(ye(e,"region",r.region)),delivery:ye(e,"delivery",a==="agents"||a==="digital"||a==="relay"?"online":"ship"),leadDays:Ye(e,"leadDays",7),attributes:e.endpoint?{endpoint:String(e.endpoint)}:{},...e.metered?{metered:!0}:{}},c=await dp(e);if(c){if(e.metered)throw new te("A metered listing has no stages to accept; drop --acceptance or --metered.");s.milestones=hC(s.leadDays)["on-delivery"].plan.map(u=>({...u,acceptance:c}))}let l=await ts(n.state,n.actor(),s);return Dt(n,l,{listingId:s.listingId,next:"Buyers order with: cappz-market buy "+s.listingId+" \u2014 watch with cappz-market deals"})}},{name:"listings",summary:"Seller: your listings (open first) with what is left, the orders formed from each, acceptance criteria, and the commands to change them.",params:[{name:"all",type:"boolean",description:"Include closed listings."}],async run(e,t){let n=await dt(t,!0);if(!n.partyId)throw new te("Sign in first.","cappz-market login");let r=pF(n.state,n.partyId).filter(i=>e.all||i.state!=="closed");return{listings:r.map(i=>({...zE(n.state,i.listing),state:i.state,...i.closed?{closed:i.closed}:{},orders:i.orders,contracts:i.contractIds.slice(0,5),acceptance:i.acceptance?i.acceptance.criteria.map(o=>o.id):null,...i.state==="closed"?{}:{change:`cappz-market update ${i.listing.listingId} --price \u2026 --available \u2026`,close:`cappz-market withdraw ${i.listing.listingId}`}})),next:r.length?"Change one: cappz-market update [--price --available --title --description --leadDays --endpoint --acceptance]":'No listings yet: cappz-market sell (or cappz-market draft "\u2026" to word one).'}}},{name:"update",summary:"Seller: change one of your listings \u2014 price, what is available, title, description, lead time, endpoint or acceptance criteria. Applies to orders placed after it; formed contracts keep their terms.",params:[{name:"listing",type:"string",description:"Your listing id (cappz-market listings).",required:!0,positional:!0},{name:"price",type:"number",description:"New price per unit (same asset)."},{name:"available",type:"number",description:"Units left to sell from now (0 pauses orders; withdraw closes the listing)."},{name:"title",type:"string",description:"New title."},{name:"description",type:"string",description:"New description."},{name:"leadDays",type:"number",description:"Days from order to delivery."},{name:"endpoint",type:"string",description:'Paid agents: new https endpoint ("none" removes it).'},{...fp,description:'New acceptance criteria for future orders (JSON or a file; "none" removes them).'}],async run(e,t){let n=await dt(t,!0),r=n.state.listings.find(c=>c.listingId===ye(e,"listing"));if(!r)throw new te("No such listing on this market.","cappz-market listings --all");if(r.sellerId!==n.partyId)throw new te("That listing is not yours.");let i=e.acceptance==="none",o={...e.title!==void 0?{title:ye(e,"title")}:{},...e.description!==void 0?{description:ye(e,"description")}:{},...e.price!==void 0?{price:Ye(e,"price")}:{},...e.available!==void 0?{available:Ye(e,"available")}:{},...e.leadDays!==void 0?{leadDays:Ye(e,"leadDays")}:{},...e.endpoint!==void 0?{endpoint:ye(e,"endpoint")==="none"?null:ye(e,"endpoint")}:{},...i?{acceptance:null}:e.acceptance!==void 0?{acceptance:await dp(e)}:{}};if(!Object.keys(o).length)throw new te("Nothing to change.",`cappz-market update ${r.listingId} --price \u2026 (see --help)`);let a;try{a=yF(r,o)}catch(c){throw new te(c.message)}let s=[...a.amend?await ts(n.state,n.actor(),a.amend):[],...a.inventoryDelta?await NL(n.state,n.actor(),r.listingId,a.inventoryDelta,hF(r,Ye(e,"available"))):[]];return s.length?Dt(n,s,{listingId:r.listingId,changed:Object.keys(o),next:"Applies to new orders. See it: cappz-market listings"}):{listingId:r.listingId,changed:[],next:"Nothing changed: the listing already says that."}}},{name:"withdraw",summary:"Seller: close one of your listings so nobody can order from it (contracts already formed are unaffected).",params:[{name:"listing",type:"string",description:"Your listing id.",required:!0,positional:!0}],async run(e,t){let n=await dt(t,!0),r=n.state.listings.find(i=>i.listingId===ye(e,"listing"));if(!r)throw new te("No such listing on this market.","cappz-market find --category \u2026");return r.open?Dt(n,await RL(n.state,n.actor(),r.listingId),{listingId:r.listingId,open:!1,next:"Closed. Re-list any time with cappz-market sell."}):{listingId:r.listingId,open:!1,next:"Already closed."}}},{name:"ask",summary:"Ask for something (even if nobody offers it yet). Suppliers bid; you award the bid you want.",params:[{name:"title",type:"string",description:"What you need.",required:!0},{name:"category",type:"string",description:"Category id.",required:!0},{name:"quantity",type:"number",description:"How many units.",required:!0},{name:"unit",type:"string",description:"Unit (default: the category\u2019s first)."},{name:"by",type:"string",description:"Needed by, YYYY-MM-DD (default 30 days from now)."},{name:"maxPrice",type:"number",description:"Highest price per unit you accept (omit for open price)."},{name:"currency",type:"string",description:"XRP (default), CAPPZ, USD-tokenZ/1 (RLUSD) or USD."},{name:"description",type:"string",description:"Specs, quality, format."},{name:"region",type:"string",description:"State code (default your profile\u2019s)."},fp],async run(e,t){let n=await dt(t,!0),r=n.state.parties.get(n.partyId);if(!r)throw new te("Create your profile first.",'cappz-market profile --name "\u2026"');let i=gr(Im(ye(e,"category"))),o={requestId:Tc("rq"),buyerId:r.partyId,categoryId:i.id,title:ye(e,"title"),description:ye(e,"description",ye(e,"title")),quantity:Ye(e,"quantity"),unit:ye(e,"unit",i.units[0]),maxPricePerUnit:e.maxPrice!==void 0?lu(Ye(e,"maxPrice"),up(e)):null,neededBy:gF(ye(e,"by",Xde(n.now(),30))),region:Pm(ye(e,"region",r.region)),deliveryRadiusMiles:null,allowNewPlanting:Ya(i.id)==="crops",contractType:"spot",attributes:{}},a=await dp(e);a&&(o.acceptance=a);let s=await Xf(n.state,n.actor(),o);return Dt(n,s,{requestId:o.requestId,next:`Bids arrive on it: cappz-market show ${o.requestId}, then cappz-market award ${o.requestId} `})}},{name:"bid",summary:"Bid to fill an open request at your price and date.",params:[{name:"request",type:"string",description:"Request id.",required:!0,positional:!0},{name:"price",type:"number",description:"Your price per unit (in the request\u2019s currency, default XRP).",required:!0},{name:"quantity",type:"number",description:"Units you supply (default: all still needed)."},{name:"by",type:"string",description:"Delivery date YYYY-MM-DD (default: the request\u2019s date)."},{name:"message",type:"string",description:"A note to the buyer."},{...fp,description:"Acceptance criteria for your delivery (default: the request\u2019s own, when it states them)."}],async run(e,t){let n=await dt(t,!0),r=n.state.requests.find(l=>l.requestId===ye(e,"request"))??(()=>{throw new te("No such request.","cappz-market find --wanted")})(),i=r.maxPricePerUnit?.currency??up(e),o=gF(ye(e,"by",r.neededBy)),a={offerId:Tc("of"),requestId:r.requestId,sellerId:n.partyId,pricePerUnit:lu(Ye(e,"price"),i),quantity:Ye(e,"quantity",r.quantity-r.awardedQuantity),deliveryDate:o,plan:{newPlanting:!1,notes:""},milestones:$f("spot",n.now().slice(0,10),o),message:ye(e,"message","")},s=await dp(e)??r.acceptance;s&&(a.milestones=a.milestones.map(l=>l.delivery?{...l,acceptance:s}:l));let c=await ru(n.state,n.actor(),a);return Dt(n,c.txs,{bidId:a.offerId,warnings:c.warnings,next:"If the buyer awards it, a contract appears in cappz-market deals."})}},{name:"award",summary:"Award a bid on your request (all or part). This forms a contract with a staged payment schedule.",params:[{name:"request",type:"string",description:"Your request id.",required:!0,positional:!0},{name:"bid",type:"string",description:"The bid (offer) id.",required:!0,positional:!0},{name:"quantity",type:"number",description:"Award part of the bid."},{name:"evaluator",type:"string",description:"A third party (never the seller) who may accept milestones besides you; you still pay."}],async run(e,t){let n=await dt(t,!0),r=await Wf(n.state,n.actor(),ye(e,"request"),ye(e,"bid"),e.quantity===void 0?void 0:Ye(e,"quantity"),e.evaluator?ye(e,"evaluator"):void 0);return Dt(n,r.txs,{contractId:r.contractId,next:`cappz-market fund ${r.contractId}`})}},{name:"buy",summary:"Buy from a listing. This forms a contract; then fund its first stage.",params:[{name:"listing",type:"string",description:"Listing id.",required:!0,positional:!0},{name:"quantity",type:"number",description:"Units (default 1)."},{name:"evaluator",type:"string",description:"A third party (never the seller) who may accept milestones besides you; you still pay."}],async run(e,t){let n=await dt(t,!0),r=await IC(n.state,n.actor(),ye(e,"listing"),Ye(e,"quantity",1),void 0,e.evaluator?ye(e,"evaluator"):void 0);return Dt(n,r.txs,{contractId:r.contractId,next:`cappz-market fund ${r.contractId}`})}},{name:"subcontract",summary:"Seller: hand part of a contract\u2019s work to another party as a child contract. Same asset and rail, within the parent\u2019s unreleased value; you are its buyer and fund each stage only after the parent milestone it serves is released to you. Fees apply to the child like any contract.",params:[{name:"parent",type:"string",description:"The contract you sell on.",required:!0,positional:!0},{name:"to",type:"string",description:"The subcontractor\u2019s party id.",required:!0},{name:"title",type:"string",description:"What the subcontractor delivers.",required:!0},{name:"price",type:"number",description:"Price per unit, in the parent\u2019s asset.",required:!0},{name:"quantity",type:"number",description:"Units (default 1)."},{name:"unit",type:"string",description:"Unit (default: the parent\u2019s)."},{name:"serves",type:"number",description:"The parent milestone index this work serves; the child stage is due with it.",required:!0},{name:"evaluator",type:"string",description:"A third party (never the subcontractor) who may accept the child\u2019s milestones besides you."},fp],async run(e,t){let n=await dt(t,!0),r=di(n,ye(e,"parent")),i=await PC(n.state,n.actor(),r.contractId,{subcontractorId:ye(e,"to"),title:ye(e,"title"),quantity:Ye(e,"quantity",1),pricePerUnit:lu(Ye(e,"price"),r.total.currency),serves:Ye(e,"serves"),...e.unit?{unit:ye(e,"unit")}:{},...e.evaluator?{evaluatorId:ye(e,"evaluator")}:{},...await dp(e).then(o=>o?{acceptance:o}:{})});return Dt(n,i.txs,{contractId:i.contractId,parent:r.contractId,next:`When the parent milestone ${Ye(e,"serves")} is released to you: cappz-market fund ${i.contractId}`})}},{name:"fund",summary:"Buyer: pay the current stage into escrow. XRP: one ledger escrow per payee, locked by a secret only you hold, returned to you after 30 days if never released.",money:!0,params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"reference",type:"string",description:"USD deals only: the payment reference (USD is otherwise paid in the web app)."},{name:"co-signature",type:"string",description:"Agents above their mandate threshold: the co-signature (JSON or file) the mandate grantor made with cappz-market cosign."}],async run(e,t){let n=await dt(t,!0);ZC(this,n,t);let r=di(n,ye(e,"contract"));if(r.buyerId!==n.partyId)throw new te("Only the buyer funds a contract.");let i=await mF(e["co-signature"]),o=ya(r)??(()=>{throw new te("Every stage is paid.")})(),a=vc(n.state.contracts,r,o.index);if(a)throw new te(a,r.parentContractId?`Check the parent: cappz-market show ${r.parentContractId}`:void 0);if(n.mode==="demo")return Dt(n,await iu(n.state,n.actor(),r.contractId,o.need,{rail:"demo"}),{stage:r.milestones[o.index].label,amount:o.need,next:"The seller delivers evidence next; then cappz-market release "+r.contractId});if(r.total.currency==="USD"){if(!e.reference)throw new te("USD stages are paid by card or bank in the web app.",`Open ${Yn()}/marketplace?tab=deals, or record a payment you already made with --reference.`);return Dt(n,await iu(n.state,n.actor(),r.contractId,o.need,{rail:"usd-reference",reference:ye(e,"reference")}),{note:"Recorded by reference: not verifiable on a ledger."})}if(at(r)==="ledger-channel"){if(r.channel)throw new te(`The channel is already open (${r.channel.channelId}).`,`Sign claims as you use the service: cappz-market claim ${r.contractId} --units N`);let P=n.state.parties.get(r.buyerId)?.xrplAccount,U=n.state.parties.get(r.sellerId)?.xrplAccount;if(!U)throw new te("The seller has no XRPL account on their profile yet.","Ask them to add one; then fund.");let{w:F,net:H,st:b}=await pp(n);if(P!==F.classicAddress)throw new te(`Your profile\u2019s XRPL account is ${P??"missing"}, but this wallet is ${F.classicAddress}.`,'Run cappz-market profile --name "\u2026" to put this wallet on your profile.');let C=$4(r.total.amount,1);if(b.spendableXrp, and give the seller the claim it prints.`})}catch(M){throw new te(`${M.message} The channel is on the ledger: ${A.hash}.`,`Record it with: cappz-market call marketplace.channel.open --input '{"contractId":"${r.contractId}","txHash":"${A.hash}"}'`)}}if(at(r)==="ledger-staged")throw new te(`${Et(r.total.currency)} deals hold nothing: each stage is paid on the ledger when you accept it.`,`Wait for the seller's evidence, then: cappz-market release ${r.contractId}`);if(r.ledgerEscrows.some(P=>P.milestone===o.index))throw new te(`\u201C${r.milestones[o.index].label}\u201D is already escrowed.`,"Wait for the seller\u2019s evidence, then release.");let s=n.state.parties.get(r.buyerId)?.xrplAccount,c=n.state.parties.get(r.sellerId)?.xrplAccount;if(!c)throw new te("The seller has no XRPL account on their profile yet.","Ask them to add one; then fund.");let{w:l,net:u,st:d}=await pp(n);if(s!==l.classicAddress)throw new te(`Your profile\u2019s XRPL account is ${s??"missing"}, but this wallet is ${l.classicAddress}.`,'Run cappz-market profile --name "\u2026" to put this wallet on your profile.');let p=sL(),h=await lL(r,o.index,s,c,p,n.now()),g=$4(o.amount,h.length);if(d.spendableXrpH.tx),u,(H,b)=>k.push(b.hash),D),U=h.map((H,b)=>({milestone:H.milestone,condition:H.condition,sealedSecret:T,lt:P[b]})),F=await xC(n.state,n.actor(i?VE(n,r,i):void 0),r.contractId,n.policy,U);return Dt(n,F,{stage:r.milestones[o.index].label,escrowed:`${o.amount} XRP`,ledgerTxs:P.map(H=>H.hash),approvedIntents:B,returnsToYouAfter:"30 days if not released",next:"The seller delivers evidence; then: cappz-market release "+r.contractId})}catch(P){throw new te(`${P.message}${k.length?` Escrows already on the ledger: ${k.join(", ")}.`:""}`,k.length?`Record them with: cappz-market call marketplace.escrow.fund --input '{"contractId":"${r.contractId}","escrows":[\u2026]}' (secret kept in ${ko()}).`:void 0)}}},{name:"deliver",summary:"Seller: submit evidence for the current stage. The file stays with you; only its SHA-256 goes on the public log.",params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"file",type:"string",description:"The deliverable or proof (hashed locally)."},{name:"hash",type:"string",description:"Or its SHA-256 hex, if you hashed it yourself."},{name:"kind",type:"string",description:"document (default), delivery-receipt, photo, inspection or sensor."},{name:"note",type:"string",description:"What the buyer should check."}],async run(e,t){let n=await dt(t,!0),r=di(n,ye(e,"contract")),i=ya(r)??(()=>{throw new te("Every stage is paid.")})(),o=e.file?await wF(new Uint8Array(await Zn(JC(String(e.file))))):ye(e,"hash"),a=await Gf(n.state,n.actor(),r.contractId,i.index,{kind:ye(e,"kind","document"),hash:o,note:ye(e,"note","")});return Dt(n,a,{stage:r.milestones[i.index].label,sha256:o,next:"Send the buyer the file through your own channel; they check its SHA-256 and release."})}},{name:"accept",summary:"Buyer or the contract\u2019s evaluator: accept the current stage\u2019s evidence without paying it (the buyer then releases or pays). An agent evaluator needs a mandate covering marketplace.milestone.affirm.",params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"verdict",type:"string",description:"A signed verdict file from cappz-market evaluate: the acceptance cites it (required to be a pass on the contract\u2019s agreed criteria for the current evidence)."}],async run(e,t){let n=await dt(t,!0),r=di(n,ye(e,"contract")),i=ya(r)??(()=>{throw new te("Every stage is paid.")})(),o;if(e.verdict){let a=(await sr()).services?.stageEvaluator;if(!a)throw new te(`${Yn()} does not publish a stage evaluator key to check the verdict against.`);let s=JSON.parse(await Zn(ye(e,"verdict"),"utf8")),c=fF(n.state,s,a.publicKey);if(!c.ok)throw new te(`Not accepting on this verdict: ${c.because}`);if(s.verdict.contractId!==r.contractId||s.verdict.milestone!==i.index)throw new te("The verdict is for another contract or stage.");o={verdictSha256:dF(s),verdictAddress:s.verdict.address,verdict:"pass"}}return Dt(n,await ou(n.state,n.actor(),r.contractId,i.index,o),{stage:r.milestones[i.index].label,...o?{onVerdict:o.verdictSha256}:{},next:`The buyer pays it: cappz-market release ${r.contractId}`})}},{name:"release",summary:"Buyer: accept the current stage\u2019s evidence and pay it \u2014 out of escrow for XRP (reveals the stage secret on the ledger), directly on the ledger for CAPPZ and RLUSD (USD-tokenZ) deals.",money:!0,params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"co-signature",type:"string",description:"Agents paying a token stage above their mandate threshold: the grantor\u2019s co-signature (cappz-market cosign )."}],async run(e,t){let n=await dt(t,!0);ZC(this,n,t);let r=di(n,ye(e,"contract")),i=ya(r)??(()=>{throw new te("Every stage is paid.")})(),o=[];if(r.milestoneStates[i.index].state==="evidenced"){let w=await ou(n.state,n.actor(),r.contractId,i.index);await n.commit(w),o.push(...w.map(T=>T.eventType)),n=await dt(t,!0),r=di(n,r.contractId)}if(r.milestoneStates[i.index].state!=="affirmed")throw new te(`\u201C${r.milestones[i.index].label}\u201D has no evidence to accept yet (state ${r.milestoneStates[i.index].state}).`,"Wait for the seller: cappz-market deals");if(at(r)==="ledger-staged"){let w=vc(n.state.contracts,r,i.index);if(w)throw new te(w,r.parentContractId?`Check the parent: cappz-market show ${r.parentContractId}`:void 0);let T=n.state.parties.get(r.buyerId)?.xrplAccount,k=n.state.parties.get(r.sellerId)?.xrplAccount;if(!k)throw new te("The seller has no XRPL account on their profile yet.","Ask them to add one; then release.");let{w:B,net:D}=await pp(n);if(T!==B.classicAddress)throw new te(`Your profile\u2019s XRPL account is ${T??"missing"}, but this wallet is ${B.classicAddress}.`,'Run cappz-market profile --name "\u2026" to put this wallet on your profile.');let P=pL(r,i.index,T,k,D),U=await mF(e["co-signature"]),F=[],H=[];try{let b=await Cm(Ki(B.seed),P.map(v=>v.tx),D,(v,S)=>H.push(S.hash),await lp(D,r.contractId,i.index,F,U,await cp(n))),C=await OC(n.state,n.actor(U?VE(n,r,U):void 0),r.contractId,i.index,n.policy,b);return Dt(n,C,{accepted:o,stage:r.milestones[i.index].label,paid:$n(i.amount,r.total.currency),ledgerTxs:b.map(v=>v.hash),approvedIntents:F,next:i.index+1`"${v}"`).join(",")}]}'`:`If the wallet lacks ${Et(r.total.currency)}: ${am(C)}`)}}let a=r.ledgerEscrows.find(w=>w.milestone===i.index);if(!a)return Dt(n,await Yf(n.state,n.actor(),r.contractId,i.index),{accepted:o,stage:r.milestones[i.index].label,next:i.index+1null))?.secret:null);if(!c)throw new te("The escrow secret for this stage is not on this computer.","Release it where it was funded (the web app or the computer that ran fund).");let{w:l,net:u}=await pp(n),d=[a.sequence,...a.feeEscrows.map(w=>w.sequence)].map(w=>uL(l.classicAddress,l.classicAddress,w,a.condition,c)),p=[],h=await Cm(Ki(l.seed),d,u,void 0,await lp(u,r.contractId,i.index,p,void 0,await cp(n))),g=await MC(n.state,n.actor(),r.contractId,i.index,h[0],n.policy,h.slice(1));return Dt(n,g,{accepted:o,stage:r.milestones[i.index].label,ledgerTxs:h.map(w=>w.hash),approvedIntents:p,next:i.index+10)||o>r.quantity)throw new te(`Units are the total used so far: more than 0, at most the cap of ${r.quantity} ${r.unit}.`);let a=BigInt(Math.round(o*Number(tE(r))));if(a>BigInt(i.capDrops))throw new te(`That is above the channel cap (${i.capDrops} drops).`);if(a<=BigInt(i.releasedDrops))throw new te(`The seller already redeemed ${i.unitsUsed} ${r.unit}; a claim is for the total used, so it must be more than that.`);let s=await os();if(s.publicKey.toUpperCase()!==i.publicKey.toUpperCase())throw new te("This wallet\u2019s key is not the channel\u2019s claim key.","Sign claims on the computer (wallet) that opened the channel.");let c=CL(i.channelId,a,s.privateKey);if(!SC(i.channelId,a,c,i.publicKey))throw new te("The claim did not verify against the channel key.");return{claim:{contractId:r.contractId,channelId:i.channelId,balanceDrops:a.toString(),units:o,signature:c,publicKey:i.publicKey},worth:$n(Number(a)/1e6,"XRP"),next:"Give the claim JSON to the seller (any channel you both use). Nothing was submitted; later claims replace earlier ones."}}},{name:"redeem",summary:"Seller of a metered deal: redeem the buyer\u2019s latest claim on the ledger (PaymentChannelClaim), pay the fee on the increase from your account (a channel pays only you), and record both. --close also closes the channel, returning the unused rest to the buyer.",money:!0,params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"claim",type:"string",description:"The claim JSON (or a file of it) the buyer printed with cappz-market claim.",required:!0},{name:"close",type:"boolean",description:"Close the channel in the same transaction."}],async run(e,t){let n=await dt(t,!0);ZC(this,n,t);let r=di(n,ye(e,"contract"));if(r.sellerId!==n.partyId)throw new te("Only the seller redeems claims.");let i=r.channel;if(!i||i.closed)throw new te(i?"The channel is closed.":"The buyer has not opened the channel yet.");let o;try{let g=e.claim,w=typeof g=="string"?g.trim().startsWith("{")?g:await Zn(JC(g),"utf8"):JSON.stringify(g),T=JSON.parse(w);o=T.claim??T}catch{throw new te("--claim must be the JSON (or a file of it) that cappz-market claim printed.")}if(!o?.signature||!o.balanceDrops||String(o.channelId??"").toUpperCase()!==i.channelId.toUpperCase())throw new te("--claim must be the JSON cappz-market claim printed for this contract\u2019s channel.");let a=BigInt(o.balanceDrops);if(!SC(i.channelId,a,o.signature,i.publicKey))throw new te("The claim signature is not the buyer\u2019s claim for that amount on this channel.");if(a<=BigInt(i.releasedDrops))throw new te(`Nothing new: ${i.releasedDrops} drops are already redeemed.`);let{w:s,net:c}=await pp(n),l=n.state.parties.get(r.sellerId)?.xrplAccount;if(l!==s.classicAddress)throw new te(`Your profile\u2019s XRPL account is ${l??"missing"}, but this wallet is ${s.classicAddress}.`);let u=[],d=await rs(Ki(s.seed),mL(s.classicAddress,i.channelId,a,o.signature,i.publicKey,!!e.close),c,await lp(c,r.contractId,0,u,void 0,await cp(n))),p=vL(r,s.classicAddress,BigInt(i.releasedDrops),a,c),h=[];try{let g=await Cm(Ki(s.seed),p.map(k=>k.tx),c,(k,B)=>h.push(B.hash)),w=await RC(n.state,n.actor(),r.contractId,n.policy,d,g);await n.commit(w);let T=w.map(k=>k.eventType);if(e.close){let k=await dt(t,!0),B=await bm(k.state,k.actor(),r.contractId,k.policy,d);await k.commit(B),T.push(...B.map(D=>D.eventType))}return{ok:!0,market:n.mode,recorded:T,redeemed:$n(Number(a-BigInt(i.releasedDrops))/1e6,"XRP"),feeLegs:p.map(k=>`${k.units} drops \u2192 ${k.label}`),ledgerTxs:[d.hash,...g.map(k=>k.hash)],approvedIntents:u,next:e.close?`Done. Review the buyer: cappz-market review ${r.contractId} --rating 5 --text "\u2026"`:`Redeem later claims the same way; close when done: cappz-market close ${r.contractId}`}}catch(g){throw new te(`${g.message} Redeemed on the ledger: ${d.hash}${h.length?`; fee payments: ${h.join(", ")}`:""}.`,`Pay any missing fee leg, then record: cappz-market call marketplace.channel.settle --input '{"contractId":"${r.contractId}","txHash":"${d.hash}","feeTxHashes":[${h.map(w=>`"${w}"`).join(",")}]}'`)}}},{name:"close",summary:"Either party of a metered deal: close the payment channel on the ledger and record it; the unused rest returns to the buyer. The seller\u2019s close is immediate; the buyer\u2019s takes effect after the settle delay (or at once after the channel expires) \u2014 run it again then.",money:!0,params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0}],async run(e,t){let n=await dt(t,!0);ZC(this,n,t);let r=di(n,ye(e,"contract"));if(n.partyId!==r.buyerId&&n.partyId!==r.sellerId)throw new te("Only the buyer or seller closes the channel.");let i=r.channel;if(!i||i.closed)throw new te(i?"The channel is already closed.":"The channel is not open.");let{w:o,net:a}=await pp(n),s=[],c=await rs(Ki(o.seed),gL(o.classicAddress,i.channelId),a,await lp(a,r.contractId,0,s,void 0,await cp(n)));return Kf(c,i.channelId)?.kind!=="DeletedNode"?{ok:!0,closing:!0,ledgerTx:c.hash,approvedIntents:s,note:`The ledger scheduled the close: the seller has the settle delay (${i.settleDelay??"?"} s) to redeem the last claim.`,next:`Run cappz-market close ${r.contractId} again after that, or record a later close with: cappz-market call marketplace.channel.close --input '{"contractId":"${r.contractId}","txHash":""}'`}:Dt(n,await bm(n.state,n.actor(),r.contractId,n.policy,c),{ledgerTx:c.hash,approvedIntents:s,next:`Review the other side: cappz-market review ${r.contractId} --rating 5 --text "\u2026"`})}},{name:"dispute",summary:"Buyer or seller: raise a dispute on a contract; a marketplace operator decides release, refund or split.",params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"reason",type:"string",description:"What went wrong.",required:!0}],async run(e,t){let n=await dt(t,!0),r=di(n,ye(e,"contract")),i=ya(r);return Dt(n,await BL(n.state,n.actor(),r.contractId,i?.index??null,ye(e,"reason")),{next:"An operator reviews it; watch cappz-market deals."})}},{name:"cancel",summary:"Buyer or seller: cancel a contract nobody has funded or paid (an abandoned order, a deal that fell through), with the reason recorded. It counts neither as finished nor as a dispute. Once money has moved, use release, refund or dispute instead.",params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"reason",type:"string",description:"Why it is cancelled (recorded on the log).",required:!0}],async run(e,t){let n=await dt(t,!0),r=di(n,ye(e,"contract"));return Dt(n,await LL(n.state,n.actor(),r.contractId,ye(e,"reason")),{contractId:r.contractId,state:"cancelled",next:"Nothing was funded, so nothing moves. The contract shows as cancelled in cappz-market deals."})}},{name:"review",summary:"Rate the other side of a finished contract (1\u20135). Reputation is computed from finished contracts, never typed in.",params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"rating",type:"number",description:"1 to 5.",required:!0},{name:"text",type:"string",description:"A short review."}],async run(e,t){let n=await dt(t,!0),r=di(n,ye(e,"contract"));return Dt(n,await gm(n.state,n.actor(),r.contractId,Ye(e,"rating"),ye(e,"text","")))}},{name:"check",summary:"Before you pay or fund escrow: CAPPZ checks the other side (can the address receive, how old is it, its marketplace record and mandate, can you afford it) and returns ok / warn / stop with reasons, signed. Costs 0.01 XRP from your wallet.",money:!0,params:[{name:"target",type:"string",description:"The XRPL address (r\u2026) you will pay, or a marketplace party id (p-\u2026).",required:!0,positional:!0},{name:"amount",type:"number",description:"What you intend to send (in XRP, or in --currency): also checks you can afford it with escrow reserves."},{name:"legs",type:"number",description:"Escrow legs the payment will use (default 1)."},{name:"currency",type:"string",description:"CAPPZ or USD-tokenZ/1 (RLUSD): also checks both trust lines, the issuer's freeze and authorization settings, and whether the token can be escrowed."}],async run(e,t){let r=(await sr()).services?.counterpartyCheck;if(!r)throw new te(`${Yn()} does not offer a counterparty check.`);let i=zi(t);if(!r.networks.includes(i))throw new te(`The counterparty check runs on ${r.networks.join(" and ")}, not ${i}.`);let o=await os(),a=ye(e,"target"),s=e.currency!==void 0?up(e):"XRP",c={...a.startsWith("r")?{address:a}:{party:a},payer:o.classicAddress,...e.amount!==void 0?s==="XRP"?{amountXrp:Ye(e,"amount")}:{currency:s,amount:Ye(e,"amount")}:s!=="XRP"?{currency:s}:{},...e.legs!==void 0?{escrowLegs:Ye(e,"legs")}:{}},l=as(ko(),"checks"),u=await ji("hire").run({url:`${r.url}/${i}`,input:JSON.stringify(c),max:r.priceXrp,out:l,timeout:3},t),d=u.results?.[0]?.file;if(!d)return{checked:!1,...u};let p=JSON.parse(await Zn(d,"utf8")),h=FN(p,r.publicKey),g=p.report;return{verdict:g.verdict,reasons:g.reasons,subject:g.subject,network:g.network,signedByCappz:h,hashMatched:u.results?.[0]?.verified??!1,paid:u.paid,report:d,next:h?g.verdict==="stop"?"Do not pay: fix or ask about the stop reasons first.":g.verdict==="warn"?"Paying is possible; weigh the warnings (or ask the person you act for).":"OK to proceed.":"Do not rely on this report: its signature does not match the published CAPPZ key."}}},{name:"payee",summary:"Payees: publish the payment instructions buyers should use, so instructions arriving by email can be confirmed \u2014 declare (an XRPL address and tag, or a bank account by salted digest: the number is never published), endorsed from your own wallet; list, revoke at once, or record an anchor signed elsewhere. New instructions are in force after a 72-hour cooling period.",money:!0,params:[{name:"action",type:"string",description:"declare, list, revoke or anchor.",required:!0,positional:!0},{name:"address",type:"string",description:"declare: the XRPL address you are paid at."},{name:"tag",type:"number",description:"declare: the destination tag buyers must use (e.g. at an exchange)."},{name:"routing",type:"string",description:"declare a bank account: routing number / sort code / BIC (hashed here, never sent)."},{name:"account",type:"string",description:"declare a bank account: account number or IBAN (hashed here, never sent)."},{name:"hint",type:"string",description:'declare a bank account: what buyers see, e.g. "First Bank \u2022\u20224321" (at most four digits).'},{name:"purpose",type:"string",description:'declare: display text, e.g. "Land purchase, Block 12 Lot 3".'},{name:"days",type:"number",description:"declare: valid for this many days (default: until revoked or replaced)."},{name:"replaces",type:"string",description:"declare: comma-separated ids of your earlier instructions this replaces."},{name:"id",type:"string",description:"revoke / anchor: the instructions id (pi-\u2026)."},{name:"tx",type:"string",description:"anchor: hash of an endorsement signed from another wallet (your profile wallet, or the declared address). Without it, this tool's wallet endorses when it is your profile wallet."},{name:"reason",type:"string",description:"revoke: why (public)."},{name:"party",type:"string",description:"list: another party's instructions (default yours)."}],async run(e,t){let n=ye(e,"action"),r=await dt(t,n!=="list"||!e.party),i=r.mode==="live"?r.network:"testnet",o=await RE(r.txs);if(n==="list"){let D=e.party?String(e.party):r.partyId,P=o.get(D);if(!P?.declarations.length)return{party:D,instructions:[],next:D===r.partyId?"cappz-market payee declare --address r\u2026 [--tag n]":"This party has declared no payment instructions: do not pay instructions claimed for it."};let U=new Date().toISOString(),F=await Promise.all(P.declarations.map(async H=>{let b=r.mode==="live"?await Promise.all(H.anchorTxs.map(S=>NE(i,S))):[],C=ZB(H,P,b,U,72),v=H.content.instrument;return{id:H.content.instructionsId,instrument:v.kind==="xrpl"?{kind:"xrpl",address:v.address,destinationTag:v.destinationTag??null}:{kind:"bank",hint:v.hint},purpose:H.content.purpose??null,declaredAt:H.declaredAt,state:C.state,control:C.control,inForceFrom:C.inForceFrom,because:C.because}}));return{party:D,name:P.name,profileWallet:P.walletHistory.at(-1)?.account??null,instructions:F}}let a=r.partyId,s=r.state.parties.get(a);if(!s)throw new te("Set up your marketplace profile first.",'cappz-market profile --name "\u2026" --kind organization');if(n==="revoke"){let D=ye(e,"id");if(!o.get(a)?.declarations.some(P=>P.content.instructionsId===D))throw new te(`You have no instructions ${D}.`,"cappz-market payee list");return Dt(r,await YB(a,D,ye(e,"reason","")),{revoked:D,next:"Buyers checking these instructions now get a stop. Tell anyone who holds them, through a channel you already use with them."})}if(n==="anchor"){let D=ye(e,"id"),P=o.get(a)?.declarations.find(H=>H.content.instructionsId===D);if(!P)throw new te(`You have no instructions ${D}.`,"cappz-market payee list");if(!e.tx){let H=await ap(),b=s.xrplAccount??null;if(r.mode!=="live")throw new te("Practice market: endorsements are ledger transactions and are skipped here.");if(!b||!H||H.wallet.classicAddress!==b)throw new te(`This tool's wallet is not your profile wallet${b?` ${b}`:""}.`,`Sign ${JSON.stringify(rp(b??"",D,P.hash))} from it, then: cappz-market payee anchor --id ${D} --tx `);if(i==="mainnet"&&!t.yes)throw new te(`Endorsing sends one AccountSet from ${b} on mainnet (network fee only, no reserve).`,"Confirm, then repeat with --yes.");let C=await rs(Ki(H.wallet.seed),rp(b,D,P.hash),i);return Dt(r,await zC(a,D,C.hash),{id:D,anchorTx:C.hash,anchoredBy:b,inForceFrom:new Date(Date.parse(C.closeTime??new Date().toISOString())+72*36e5).toISOString(),next:"cappz-market payee list"})}let U=ye(e,"tx").toUpperCase(),F=r.mode==="live"?await NE(i,U):null;if(F&&(F.error||!F.validated||F.result!=="tesSUCCESS"||F.memo!==`${D}:${P.hash}`))throw new te(`Transaction ${U} is not a validated endorsement of ${D} (${F.error??`memo ${F.memo??"missing"}`}).`,`Sign this from your wallet: ${JSON.stringify(rp(s.xrplAccount??"",D,P.hash))}`);return Dt(r,await zC(a,D,U),{id:D,anchoredBy:F?.account??null,next:"cappz-market payee list"})}if(n!=="declare")throw new te("action is declare, list, revoke or anchor.");let c;if(e.address)c={kind:"xrpl",address:KE(String(e.address)),...e.tag!==void 0?{destinationTag:Ye(e,"tag")}:{}};else if(e.routing&&e.account){let D=WB();c={kind:"bank",salt:D,digest:await OE(D,String(e.routing),String(e.account)),hint:ye(e,"hint")}}else throw new te("Declare --address r\u2026 [--tag n], or a bank account with --routing, --account and --hint.");let l=new Date().toISOString(),u={instructionsId:XB(),partyId:a,network:i,instrument:c,validFrom:l,validUntil:e.days!==void 0?new Date(Date.parse(l)+Ye(e,"days")*864e5).toISOString():null,...e.purpose?{purpose:ye(e,"purpose")}:{},...ss(e.replaces).length?{supersedes:ss(e.replaces)}:{}},d;try{d=await GB(r.state,a,u)}catch(D){throw new te(D.message)}await r.commit(d.txs);let p=u.instructionsId,h=await ap(),g=s.xrplAccount??null,w={ok:!0,id:p,hash:d.hash,instrument:c.kind==="xrpl"?c:{kind:"bank",hint:c.hint}};if(r.mode!=="live")return{...w,endorsed:!1,next:"Practice market: endorsements are ledger transactions and are skipped here."};if(!g)return{...w,endorsed:!1,next:"Your profile names no XRPL wallet: set one (cappz-market profile --xrplAccount r\u2026), then endorse from it and run cappz-market payee anchor."};let T=rp(g,p,d.hash);if(!h||h.wallet.classicAddress!==g)return{...w,endorsed:!1,endorse:T,next:`Sign this AccountSet from your profile wallet ${g} (no reserve, network fee only), then: cappz-market payee anchor --id ${p} --tx `};if(i==="mainnet"&&!t.yes)return{...w,endorsed:!1,endorse:T,next:`Declared, not yet endorsed. Endorsing sends one AccountSet from ${g} on mainnet (network fee only, no reserve): cappz-market payee anchor --id ${p} --network mainnet --yes`};let k=await rs(Ki(h.wallet.seed),T,i);await r.commit(await zC(a,p,k.hash));let B=c.kind==="xrpl"&&c.address===g;return{...w,endorsed:!0,anchorTx:k.hash,controlProven:c.kind==="xrpl"?B:null,inForceFrom:new Date(Date.parse(k.closeTime??l)+72*36e5).toISOString(),next:`Buyers can confirm these instructions from ${new Date(Date.parse(k.closeTime??l)+72*36e5).toISOString().slice(0,16)} UTC: cappz-market confirm-payee ${a} ${c.kind==="xrpl"?`--address ${c.address}${c.destinationTag!==void 0?` --tag ${c.destinationTag}`:""}`:"--routing \u2026 --account \u2026"}.${c.kind==="xrpl"&&!B?` To prove you control ${c.address} too, sign ${JSON.stringify(rp(c.address,p,d.hash))} from it and run payee anchor --id ${p} --tx .`:""} Give buyers your party id (${a}) in the contract, not in the email with the instructions.`}}},{name:"confirm-payee",summary:"Before a large payment: confirm the instructions you were given are the ones the payee declared and endorsed from their own wallet, past the cooling period \u2014 not a fraudster's, a lookalike of an address you paid, or a change from where you paid them before. XRPL address or bank account (hashed on this computer). Signed ok / warn / stop. Costs 0.01 XRP platform fee + 0.1 XRP.",money:!0,params:[{name:"payee",type:"string",description:"The payee's party id \u2014 from your contract or an earlier, trusted exchange, never from the message with the instructions.",required:!0,positional:!0},{name:"address",type:"string",description:"The XRPL address you were told to pay."},{name:"tag",type:"number",description:"The destination tag you were told to use."},{name:"routing",type:"string",description:"Bank instructions: routing number / sort code / BIC (hashed here, never sent)."},{name:"account",type:"string",description:"Bank instructions: account number or IBAN (hashed here, never sent)."},{name:"amount",type:"number",description:"What you intend to send (XRP, or --currency)."},{name:"currency",type:"string",description:"CAPPZ or USD-tokenZ/1 (RLUSD), for an XRPL payment in a token."},{name:"contract",type:"string",description:"The deal this pays: the payee must be its seller."},{name:"cooling",type:"number",description:"Hours new instructions must have been endorsed (default 72, at least 24)."}],async run(e,t){let n=(await sr()).services?.payeeConfirmation;if(!n)throw new te(`${Yn()} does not offer a payee confirmation.`);let r=zi(t);if(!n.networks.includes(r))throw new te(`The payee confirmation runs on ${n.networks.join(" and ")}, not ${r}.`);let i=ye(e,"payee"),o=await os(),a={payee:i,payer:o.classicAddress};if(e.address)Object.assign(a,{address:KE(String(e.address)),...e.tag!==void 0?{destinationTag:Ye(e,"tag")}:{}});else if(e.routing&&e.account){let w=await dt(t),T=((await RE(w.txs)).get(i)?.declarations??[]).flatMap(k=>k.content.instrument.kind==="bank"?[k.content.instrument.salt]:[]);if(!T.length)return{verdict:"stop",reasons:[{level:"stop",code:"payee-no-bank-instructions",text:`${i} has declared no bank account on the ${r} market: do not pay these instructions.`}],paid:"0 XRP",next:"Call the payee on a phone number you already had."};a.bankDigests=await Promise.all(T.slice(-32).map(k=>OE(k,String(e.routing),String(e.account))))}else throw new te("Give the instructions you were sent: --address r\u2026 [--tag n], or --routing \u2026 --account \u2026.");e.amount!==void 0&&(a.amount=Ye(e,"amount")),e.currency!==void 0&&(a.currency=up(e)),e.contract&&(a.contractId=String(e.contract)),e.cooling!==void 0&&(a.coolingHours=Ye(e,"cooling"));let s=`${n.url}/${r}/${n.path}`,c=await fetch(`${s}/jobs`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({input:a})}),l=await c.json().catch(()=>({}));if(c.status===404)return{verdict:"stop",reasons:[{level:"stop",code:"payee-unknown-payee",text:l.error??`No party ${i}.`}],paid:"0 XRP",next:"Do not pay. Get the payee id from your contract, and call the payee on a phone number you already had."};if(!c.ok||!l.job)throw new te(`The payee confirmation refused: ${l.error??c.status}. Nothing was charged.`);let u=await ji("hire").run({url:s,job:l.job.jobId,max:n.priceXrp,out:as(ko(),"payee-confirmations"),timeout:5},t),d=u.results?.find(w=>w.stage===1)??u.results?.at(-1);if(!d)return{confirmed:!1,...u};let p=JSON.parse(await Zn(d.file,"utf8")),h=JB(p,n.publicKey),g=p.report;return{verdict:g.verdict,binding:g.binding,reasons:g.reasons,advice:g.advice,subject:g.subject,signedByCappz:h,hashMatched:d.verified,paid:u.paid,report:d.file,next:h?g.verdict==="stop"?"Do not pay. Call the payee on a phone number you already had.":g.verdict==="warn"?"Weigh the warnings with a second approver before paying.":"Confirmed. Have a second person approve the payment against this report.":"Do not rely on this report: its signature does not match the published CAPPZ key."}}},{name:"evaluate",summary:"Before you accept or pay a stage: CAPPZ checks the delivered file against the milestone\u2019s agreed acceptance criteria and returns a signed pass / fail / needs-human verdict. The file goes to the evaluator only (not the public log) and is not kept. Costs 0.05 XRP from your wallet. The contract\u2019s named evaluator can accept on a pass with --accept.",money:!0,params:[{name:"contract",type:"string",description:"Contract id.",required:!0,positional:!0},{name:"file",type:"string",description:"The delivered file (its SHA-256 must be the seller\u2019s published evidence).",required:!0},{name:"milestone",type:"number",description:"Stage index (default: the stage with new evidence)."},{...fp,description:"Only when the contract has no agreed criteria for the stage: your own (the verdict says they came from you)."},{name:"accept",type:"boolean",description:"You are the contract\u2019s named evaluator: on a pass with the agreed criteria, accept the stage citing the verdict (the buyer still pays)."}],async run(e,t){let n=(await sr()).services?.stageEvaluator;if(!n)throw new te(`${Yn()} does not offer a stage evaluator.`);let r=zi(t);if(!n.networks.includes(r))throw new te(`The stage evaluator runs on ${n.networks.join(" and ")}, not ${r}.`);let i=new Uint8Array(await Zn(ye(e,"file"))),o=await dp(e),a=`${n.url}/${r}/${n.path}`,s=JSON.stringify({input:{contractId:ye(e,"contract"),...e.milestone!==void 0?{milestone:Ye(e,"milestone")}:{},...o?{acceptance:o}:{}},file:Buffer.from(i).toString("base64")}),c=await fetch(`${a}/jobs`,{method:"POST",headers:{"content-type":"application/json"},body:s}),l=await c.json().catch(()=>({}));if(!c.ok||!l.job)throw new te(`The evaluator refused: ${l.error??c.status}. Nothing was charged.`);let u=await ji("hire").run({url:a,job:l.job.jobId,max:n.priceXrp,out:as(ko(),"verdicts"),timeout:3},t),d=u.results?.[0]?.file;if(!d)return{evaluated:!1,...u};let p=JSON.parse(await Zn(d,"utf8")),h=HE(p,n.publicKey),g=p.verdict,w={verdict:g.verdict.state,reasons:g.verdict.reasons,criteria:g.criteria.source,results:g.results.map(T=>({id:T.id,state:T.state,judgedBy:T.judgedBy,detail:T.detail})),evidenceMatched:g.evidence.matched,signedByCappz:h,hashMatched:u.results?.[0]?.verified??!1,paid:u.paid,verdictFile:d,notes:l.notes??[]};return h?e.accept?g.verdict.state!=="pass"?{...w,accepted:!1,next:g.verdict.state==="fail"?"Not accepted. Tell the seller what failed, or the buyer may dispute.":"Not accepted: a person must check the open criteria."}:{...w,...await ji("accept").run({contract:g.contractId,verdict:d},t)}:{...w,next:g.verdict.state==="pass"?`Criteria met. Buyer: cappz-market release ${g.contractId} (or the named evaluator: cappz-market accept ${g.contractId} --verdict ${d})`:g.verdict.state==="fail"?"Criteria not met: ask the seller to fix and deliver again, or dispute.":"A person must check the open criteria before accepting."}:{...w,next:"Do not rely on this verdict: its signature does not match the published CAPPZ key."}}},{name:"draft",summary:"Describe what you sell or need in your own words; CAPPZ returns a checked draft and the exact sell or ask command to run (nothing is published). Costs 0.02 XRP from your wallet.",money:!0,params:[{name:"text",type:"string",description:"What you sell or need, in plain words (price, quantity and dates only if you know them).",required:!0,positional:!0},{name:"wanted",type:"boolean",description:"Draft a request (ask) instead of a listing (sell)."},{name:"region",type:"string",description:"Your two-letter state code, if not in the text."}],async run(e,t){let n=(await sr()).services?.listingDrafter;if(!n)throw new te(`${Yn()} does not offer a listing drafter.`);let r=zi(t);if(!n.networks.includes(r))throw new te(`The listing drafter runs on ${n.networks.join(" and ")}, not ${r}.`);let i={text:ye(e,"text"),...e.wanted?{intent:"ask"}:{},...e.region?{region:Pm(ye(e,"region"))}:{}},o=await ji("hire").run({url:`${n.url}/${r}/${n.path}`,input:JSON.stringify(i),max:n.priceXrp,out:as(ko(),"drafts"),timeout:3},t),a=o.results?.[0]?.file;if(!a)return{drafted:!1,...o};let s=JSON.parse(await Zn(a,"utf8"));return{draft:s.draft,ready:s.ready,missing:s.missing,questions:s.questions,notes:s.notes,command:s.command,paid:o.paid,hashMatched:o.results?.[0]?.verified??!1,next:s.ready?`Review it, then run: ${s.command}`:`Fill in ${s.missing.join(", ")} and run the command.`}}},{name:"scout",summary:"For a contract you sell on: which parts to subcontract, who on the market could do them (with reputation), and a ready subcontract command for each. Nothing is formed. Costs 0.05 XRP from your wallet.",money:!0,params:[{name:"contract",type:"string",description:"The contract you sell on.",required:!0,positional:!0},{name:"budget",type:"number",description:"Most of what is left to subcontract, as a fraction (default 0.5)."},{name:"need",type:"string",description:"What you want help with, in a sentence."}],async run(e,t){let n=(await sr()).services?.subcontractScout;if(!n)throw new te(`${Yn()} does not offer a subcontract scout.`);let r=zi(t);if(!n.networks.includes(r))throw new te(`The subcontract scout runs on ${n.networks.join(" and ")}, not ${r}.`);let i={contractId:ye(e,"contract"),...e.budget!==void 0?{budgetShare:Ye(e,"budget")}:{},...e.need?{need:ye(e,"need")}:{}},o=await ji("hire").run({url:`${n.url}/${r}/${n.path}`,input:JSON.stringify(i),max:n.priceXrp,out:as(ko(),"scouts"),timeout:3},t),a=o.results?.[0]?.file;return a?{...JSON.parse(await Zn(a,"utf8")),paid:o.paid,hashMatched:o.results?.[0]?.verified??!1,report:a,next:"Check a candidate (cappz-market check ), then run its subcontract command."}:{scouted:!1,...o}}},{name:"constraints-draft",summary:"Turn the operating-limits text of an equipment manual or datasheet into a draft Constraint Guard envelope; every limit is quoted verbatim with its numbers, nothing is invented, nothing is declared. Costs 0.05 XRP from your wallet.",money:!0,params:[{name:"file",type:"string",description:"A text file with the manual/datasheet sections that state the limits.",required:!0},{name:"device",type:"string",description:"The device id to prefix points with (oven-3, freezer-1, pump-4)."}],async run(e,t){let n=(await sr()).services?.envelopeDrafter;if(!n)throw new te(`${Yn()} does not offer an envelope drafter.`);let r=zi(t);if(!n.networks.includes(r))throw new te(`The envelope drafter runs on ${n.networks.join(" and ")}, not ${r}.`);let i=await Zn(ye(e,"file"),"utf8");if(i.length>6e4)throw new te("Send at most 60 000 characters: just the sections that state operating limits.");let o={text:i,...e.device?{device:ye(e,"device")}:{}},a=await ji("hire").run({url:`${n.url}/${r}/${n.path}`,input:JSON.stringify(o),max:n.priceXrp,out:as(ko(),"envelopes"),timeout:3},t),s=a.results?.[0]?.file;if(!s)return{drafted:!1,...a};let c=JSON.parse(await Zn(s,"utf8")).advice;return{draft:c.draft,dropped:c.dropped,needs:c.needs,questions:c.questions,lint:c.lint,ready:c.ready,paid:a.paid,hashMatched:a.results?.[0]?.verified??!1,report:s,next:"Review every limit against the manual, add an authority constraint (who may command which setpoints), save it as envelope-draft.json and run: constraint-wizard declare"}}},{name:"constraints-review",summary:"Review your Constraint Guard's shadow report: per point enforce now (with the exact command), keep shadowing, or investigate first, and what each refusal means. Rules only, signed. Costs 0.02 XRP from your wallet.",money:!0,params:[{name:"guard",type:"string",description:"Your guard's HTTP front (reads GET /cappz/constraints/report from it)."},{name:"report",type:"string",description:"Or: a saved shadow report JSON file."}],async run(e,t){let n=(await sr()).services?.shadowReviewer;if(!n)throw new te(`${Yn()} does not offer a shadow-report reviewer.`);let r=zi(t),i;if(e.report)i=JSON.parse(await Zn(ye(e,"report"),"utf8"));else if(e.guard){let c=await fetch(new URL("/cappz/constraints/report",ye(e,"guard")));if(!c.ok)throw new te(`The guard answered ${c.status}.`);i=await c.json()}else throw new te("Give --guard or --report .");let o=await ji("hire").run({url:`${n.url}/${r}/${n.path}`,input:JSON.stringify({report:i}),max:n.priceXrp,out:as(ko(),"reviews"),timeout:3},t),a=o.results?.[0]?.file;if(!a)return{reviewed:!1,...o};let s=JSON.parse(await Zn(a,"utf8")).advice;return{summary:s.summary,points:s.points,other:s.other,paid:o.paid,hashMatched:o.results?.[0]?.verified??!1,report:a,next:s.points.some(c=>c.command)?`Run on an operator's computer: ${s.points.filter(c=>c.command).map(c=>c.command).join(" && ")}`:"Keep shadowing; fix what the actions say, then review again."}}},{name:"constraints-triage",summary:"Triage a constraint reconciliation report: severity, what the pattern most likely means, and ordered actions (contain, preserve, verify, recover, notify). Rules only, signed, never touches equipment. Costs 0.02 XRP from your wallet.",money:!0,params:[{name:"report",type:"string",description:"The report.json written by constraint-reconcile --out.",required:!0}],async run(e,t){let n=(await sr()).services?.incidentTriage;if(!n)throw new te(`${Yn()} does not offer incident triage.`);let r=zi(t),i=JSON.parse(await Zn(ye(e,"report"),"utf8")),o=await ji("hire").run({url:`${n.url}/${r}/${n.path}`,input:JSON.stringify({report:i}),max:n.priceXrp,out:as(ko(),"triage"),timeout:3},t),a=o.results?.[0]?.file;if(!a)return{triaged:!1,...o};let s=JSON.parse(await Zn(a,"utf8")).advice;return{severity:s.severity,summary:s.summary,hypotheses:s.hypotheses,actions:s.actions,note:s.note,paid:o.paid,hashMatched:o.results?.[0]?.verified??!1,report:a,next:s.actions[0]?`${s.actions[0].phase}: ${s.actions[0].action}`:"Nothing to act on."}}},{name:"hire",summary:"Hire a CAPPZ paid agent at its URL: open a job, pay each stage from your wallet, collect each result and check its SHA-256.",money:!0,params:[{name:"url",type:"string",description:"The agent\u2019s address (from its listing), e.g. https://agent.example.com.",required:!0,positional:!0},{name:"input",type:"string",description:"The work you want done (text or JSON). Not needed with --job."},{name:"job",type:"string",description:"Resume this job (from an earlier hire) instead of opening a new one."},{name:"max",type:"number",description:"Most you will pay in total for this job (required; in the agent\u2019s currency).",required:!0},{name:"out",type:"string",description:"Folder for results (default ./cappz-results)."},{name:"timeout",type:"number",description:"Minutes to wait for the whole job (default 15)."}],async run(e,t){let n=ye(e,"url").replace(/\/$/,""),r=Ye(e,"max"),i=JC(ye(e,"out","cappz-results")),o=await YC(),a=o?await km(!1).catch(()=>null):null,s=o&&a?{partyId:await qE(a.userId),declaration:o.declaration,secretKeyHex:o.secretKey}:null,c=async(D,P,U=!1)=>{let F=s?await bE({method:P?.method??"GET",url:n+D,body:typeof P?.body=="string"?P.body:void 0},s):{},H=await fetch(n+D,{...P,headers:{...P?.headers,...F}});return{status:H.status,headers:H.headers,body:!U&&H.headers.get("content-type")?.includes("json")?await H.json():new Uint8Array(await H.arrayBuffer())}},l=(await c("/agent")).body,u=dC(l.currency);if(!u||u==="USD")throw new te(`Unexpected currency ${l.currency}: paid agents are paid in XRP, CAPPZ or USD-tokenZ/1 (RLUSD) on the ledger.`);let d=u==="XRP"?null:DN(u,l.network);if(d&&l.issuer&&l.issuer!==d.issuer)throw new te(`${l.name} asks for ${Et(u)} from issuer ${l.issuer}, not the known issuer ${d.issuer}. Not paying.`);if(Number(l.price)>r)throw new te(`${l.name} costs ${l.price} ${l.currency} per job; your max is ${r}.`,"Raise --max if the person you act for agrees.");if(l.network==="mainnet"&&!t.yes)throw new te(`${l.name} is paid in real ${l.currency} on mainnet.`,"Confirm with the person you act for, then repeat with --yes.");let p=await os();if(!e.job&&(e.input===void 0||e.input===""))throw new te("Give --input (the work), or --job to resume one.");let h=e.job?String(e.job):(await c("/jobs",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({input:(()=>{try{return JSON.parse(String(e.input))}catch{return String(e.input)}})()})})).body.job.jobId,g=0,w=[],T=[],k=new Map;await jde(i,{recursive:!0});let B=Date.now()+Ye(e,"timeout",15)*6e4;for(;;){let D=(await c(`/jobs/${h}`)).body;for(let P of D.job.stages){if(P.state!=="released"||!P.result||w.some(C=>C.stage===P.index))continue;let F=(await c(`/jobs/${h}/stages/${P.index}/result`,void 0,!0)).body,H=await wF(F),b=as(i,`${h}-stage-${P.index}`);await zde(b,F),w.push({stage:P.index,file:b,sha256:H,verified:H===P.result.hash})}if(D.job.state==="completed")return{job:h,agent:l.name,paid:`${g} ${l.currency}`,payments:T,results:w,allVerified:w.every(P=>P.verified)};if(D.job.state==="failed")throw new te(`The agent\u2019s work failed on job ${h}${(()=>{let P=D.job.stages.find(U=>U.failure)?.failure;return P?`: ${P}`:""})()}.`,`Ask it to retry: POST ${n}/jobs/${h}/retry`);if(D.pay&&k.has(D.pay.stage)){let P=k.get(D.pay.stage);if(Date.now()-P.at>12e4)throw new te(`Stage ${D.pay.stage} is paid on the ledger (${P.hash}) but ${l.name} has not recorded it yet.`,`Do not pay again. Report it later: POST ${n}/jobs/${h}/payments {"txHash":"${P.hash}"}, then cappz-market hire ${n} --job ${h} --max ${r-g}`);await c(`/jobs/${h}/payments`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({txHash:P.hash})}),await new Promise(U=>setTimeout(U,5e3));continue}if(D.pay){let P=Number(D.pay.amount);if(g+P>r+1e-9)throw new te(`Stage ${D.pay.stage} asks ${P}; paying it would pass your max of ${r} (spent ${g}).`);let U=await sp(p.classicAddress,D.pay.network);if(l.currency==="XRP"&&U.spendableXrpF[C]!==void 0)||Number(F.Flags??0)&131072)throw new te(`${l.name} prepared a payment with paths, SendMax or partial-payment flags. Not paying.`);let H=F.Amount;if(d?typeof H!="object"||H.issuer!==d.issuer||H.currency.toUpperCase()!==d.hex.toUpperCase()||Number(H.value)!==P:typeof H!="string"||Number(H)!==Math.round(P*1e6))throw new te(`${l.name} prepared a payment that is not ${P} ${Et(u)}${d?` from issuer ${d.issuer}`:""}. Not paying.`);let b=await rs(Ki(p.seed),{...F,Account:p.classicAddress},D.pay.network);await c(`/jobs/${h}/payments`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({txHash:b.hash})}),g+=P,T.push(b.hash),k.set(D.pay.stage,{hash:b.hash,at:Date.now()});continue}if(Date.now()>B)return{job:h,agent:l.name,paid:`${g} ${l.currency}`,payments:T,results:w,state:D.job.state,next:`Still working. Resume later: cappz-market hire ${n} --job ${h} --max ${r-g}`};await new Promise(P=>setTimeout(P,3e3))}}},{name:"skills",summary:"Find the agent skill for a task: ranks the CAPPZ skills by your words (or lists them all) with what each is for, its commands and a link to its SKILL.md. Load the skill before you act.",params:[{name:"query",type:"string",description:'What you need, in a few words, e.g. "freezer setpoint hacked" or "pay a stranger safely".',positional:!0}],async run(e){let t=Rm,n=e.query===void 0?"":String(e.query),r=u8(t,n);return{...n?{query:n}:{},skills:r.map(i=>({name:i.name,useWhen:i.description,commands:i.commands,tools:i.tools,guides:i.guides.map(o=>`${t.repo}/blob/main/${o}`),skill:i.raw,browse:i.url})),...r.length?{}:{none:`No skill matches "${n}".`},install:t.install,next:r.length?`Read ${r[0].raw} and follow it.`:"cappz-market skills (lists every skill)"}}},{name:"ops",summary:"List every marketplace operation (reads and governed writes) with its inputs \u2014 for anything the named commands do not cover.",params:[],async run(){return{operations:VC.map(e=>({verb:e.verb,writes:e.writes,summary:e.summary,input:e.input})),next:"cappz-market call --input '{\u2026}'"}}},{name:"call",summary:"Run any marketplace operation by verb with a JSON input (see ops). Writes are published like every other command.",params:[{name:"verb",type:"string",description:"Operation verb, e.g. marketplace.offer.award.",required:!0,positional:!0},{name:"input",type:"json",description:"Operation input as JSON."}],async run(e,t){let n=ye(e,"verb"),r=VC.find(c=>c.verb===n);if(!r)throw new te(`Unknown verb ${n}.`,"cappz-market ops");let i=await dt(t,r.writes),o=await _m().catch(()=>null),a=i.partyId?i.actor():{partyId:"",at:i.now()},s=await FB(i.state,a,n,e.input??{},{policy:i.policy,fetchLedgerTx:Th,...o?{boxPrivateKey:o.privateKey}:{}});return s.txs.length&&await i.commit(s.txs),{ok:!0,market:i.mode,data:s.data??null,recorded:s.txs.map(c=>c.eventType)}}},{name:"demo",summary:"Practice market on this computer: --reset starts it over. Use --demo on any command (and --as to play the other side).",params:[{name:"reset",type:"boolean",description:"Start the practice market over."}],async run(e){e.reset&&await iF();let t=await dt({demo:!0});return{practiceMarket:!0,you:t.partyId,parties:[...t.state.parties.values()].map(n=>({id:n.partyId,name:n.name,kind:n.kind})),listings:t.state.listings.filter(n=>n.open).length,requests:t.state.requests.filter(n=>n.open).length,next:'cappz-market find --demo "lavender"'}}}],ji=e=>yp.find(t=>t.name===e);y();import{createInterface as Wde}from"node:readline";y();var xm="16.0.5";var Gde=e=>e.type==="json"?"object":e.type;function Yde(){return yp.map(e=>({name:`market_${e.name}`,description:e.summary+(e.money?" Moves money: on mainnet pass yes=true only after the person you act for agrees.":""),inputSchema:{type:"object",properties:{...Object.fromEntries(e.params.map(t=>[t.name,{type:Gde(t),description:t.description}])),demo:{type:"boolean",description:"Use the practice market on this computer (nothing published, no real money)."},as:{type:"string",description:"Practice market only: act as this party id."},network:{type:"string",enum:["devnet","testnet","mainnet"],description:"Which market (default testnet). Validate on testnet, then use mainnet (real XRP)."},...e.money?{yes:{type:"boolean",description:"Confirms a mainnet money movement."}}:{}},required:e.params.filter(t=>t.required).map(t=>t.name),additionalProperties:!1}}))}async function Zde(e,t){let n=yp.find(c=>`market_${c.name}`===e);if(!n)return{content:[{type:"text",text:`Unknown tool ${e}.`}],isError:!0};let{demo:r,as:i,yes:o,network:a,...s}=t;try{let c=await n.run(s,{demo:!!r,as:i?String(i):void 0,yes:!!o,...a?{network:String(a)}:{}});return{content:[{type:"text",text:JSON.stringify(c,null,2)}]}}catch(c){let l=c instanceof te?{error:c.message,...c.next?{next:c.next}:{}}:{error:c.message};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],isError:!0}}}function AF(){let e=n=>process.stdout.write(JSON.stringify(n)+` `);Wde({input:process.stdin}).on("line",n=>{if(!n.trim())return;let r;try{r=JSON.parse(n)}catch{e({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});return}let i=o=>{r.id!==void 0&&e({jsonrpc:"2.0",id:r.id,result:o})};switch(r.method){case"initialize":i({protocolVersion:r.params?.protocolVersion??"2025-06-18",capabilities:{tools:{}},serverInfo:{name:"cappz-market",version:xm},instructions:"CAPPZ Marketplace: start with market_setup. Read with market_find / market_show / market_deals; act with market_sell, market_ask, market_bid, market_award, market_buy, market_fund, market_deliver, market_release. Practise with demo=true, validate on network=testnet (default), then go live with network=mainnet. Never move money on mainnet without the person you act for agreeing."});return;case"notifications/initialized":return;case"ping":i({});return;case"tools/list":i({tools:Yde()});return;case"tools/call":{let o=r.params;Zde(o.name,o.arguments??{}).then(i);return}default:r.id!==void 0&&e({jsonrpc:"2.0",id:r.id,error:{code:-32601,message:`Method not found: ${r.method}`}})}})}var Qde=[["Get started",["skills","setup","demo","wallet","trust","login","profile","mandate","cosign"]],["Find and buy",["find","show","buy","ask","award","deals"]],["Sell",["sell","listings","update","withdraw","bid","subcontract","deliver"]],["Pay and finish a deal",["fund","accept","release","claim","redeem","close","dispute","cancel","review"]],["Check before you pay",["check","payee","confirm-payee","evaluate"]],["Paid helpers",["draft","scout","hire"]],["Equipment safety (Constraint Guard)",["constraints-draft","constraints-review","constraints-triage"]],["Anything else",["ops","call"]]],efe=e=>Rm.skills.filter(t=>t.commands.includes(e)),TF=[["--demo","practice market on this computer (nothing published, no real money)"],["--as ","practice market only: act as another party"],["--network ","which market: devnet, testnet (default) or mainnet (real XRP); or CAPPZ_NETWORK"],["--yes","confirm a mainnet money movement (fund, release, hire)"]];function EF(e){if(e){let n=e.params.filter(o=>o.positional).map(o=>o.required?`<${o.name}>`:`[${o.name}]`).join(" "),r=e.params.filter(o=>!o.positional).map(o=>` --${o.name}${o.type==="boolean"?"":` <${o.type==="json"?"json":o.type}>`}${o.required?" (required)":""} ${o.description}`).join(` `),i=efe(e.name).slice(0,3);return`cappz-market ${e.name} ${n} ${e.summary} ${r} Global: ${TF.map(([o])=>o).join(" ")} ${i.length?`Skill${i.length>1?"s":""}: ${i.map(o=>o.url).join(" ")} `:""}`}let t=Math.max(...yp.map(n=>n.name.length));return`cappz-market ${xm} \u2014 the CAPPZ Marketplace for agents and their people. Start with: cappz-market demo (practise) \u2192 setup (testnet: validate) \u2192 setup --network mainnet (go live) Not sure which command? cappz-market skills "what you need" \xB7 One command's options: cappz-market --help ${Qde.map(([n,r])=>`${n} ${r.map(i=>ji(i)).map(i=>` ${i.name.padEnd(t)} ${i.summary.split(". ")[0].replace(/\.$/,"")}.`).join(` `)}`).join(` `)} ${"mcp".padEnd(t)} Run as an MCP server over stdio. Global options: ${TF.map(([n,r])=>` ${n.padEnd(14)} ${r}`).join(` `)} Environment: XRPL_SEED (use your own wallet), CAPPZ_EMAIL / CAPPZ_PASSWORD (sign in), CAPPZ_HOME (where keys are kept, default ~/.cappz/market). Guide for agents: https://github.com/CAPPZ-ai/cappz-sdk/tree/main/skills/using-cappz-marketplace \xB7 All skills: https://github.com/CAPPZ-ai/cappz-sdk/blob/main/skills/index.json `}function tfe(e,t){let n={},r=[],i={demo:!1,yes:!1},o=!1;for(let s=0;sw.toUpperCase());if(d==="demo"){i.demo=!0;continue}if(d==="yes"){i.yes=!0;continue}if(d==="as"){i.as=u??t[++s];continue}if(d==="network"){i.network=u??t[++s];continue}let p=e.params.find(g=>g.name===d);if(!p)throw new te(`Unknown option --${l} for ${e.name}.`,`cappz-market ${e.name} --help`);if(p.type==="boolean"){n[d]=u===void 0?!0:u!=="false";continue}let h=u??t[++s];if(h===void 0)throw new te(`--${l} needs a value.`);n[d]=p.type==="json"?(()=>{try{return JSON.parse(h)}catch{throw new te(`--${l} is not valid JSON.`)}})():h}let a=e.params.filter(s=>s.positional);return r.forEach((s,c)=>{let l=a[c];if(!l)throw new te(`Unexpected argument \u201C${s}\u201D.`,`cappz-market ${e.name} --help`);n[l.name]=s}),{args:n,global:i,help:o}}async function nfe(e){let[t,...n]=e;if(!t||t==="help"||t==="--help"||t==="-h")return process.stdout.write(EF()),0;if(t==="--version"||t==="version")return process.stdout.write(`${xm} `),0;if(t==="mcp")return AF(),-1;let r=ji(t),i=o=>(process.stdout.write(JSON.stringify(o,null,2)+` `),1);if(!r)return i({error:`Unknown command ${t}.`,next:"cappz-market help"});try{let{args:o,global:a,help:s}=tfe(r,n);if(s)return process.stdout.write(EF(r)),0;for(let l of r.params)if(l.required&&(o[l.name]===void 0||o[l.name]===""))throw new te(`Missing ${l.positional?`<${l.name}>`:`--${l.name}`}.`,`cappz-market ${r.name} --help`);let c=await r.run(o,a);return process.stdout.write(JSON.stringify(c,null,2)+` `),0}catch(o){return i(o instanceof te?{error:o.message,...o.next?{next:o.next}:{}}:{error:o.message})}}function rfe(){try{let e=process.argv[1];return e?SF(e)===SF(Jde(import.meta.url)):!1}catch{return!1}}var ife=typeof process<"u"&&rfe();ife&&nfe(process.argv.slice(2)).then(e=>{e>=0&&process.exit(e)});export{Qde as HELP_GROUPS,nfe as main,tfe as parseArgs};