oneie 5.9.0 → 5.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +122 -3
- package/dist/package.json +2 -2
- package/dist/src/age-8m0v06sc.js +1 -0
- package/dist/src/client-vgmvv2zt.js +1 -0
- package/dist/src/{evm-tx-cqhm9rtt.js → evm-tx-mfhhgpsb.js} +1 -1
- package/dist/src/hl-run-z8bwmhf8.js +1 -0
- package/dist/src/index-abbkxz62.js +2170 -0
- package/dist/src/index-sdgefh6q.js +12 -0
- package/dist/src/{index-h3nrt8bx.js → index-y4xe5pm7.js} +3 -3
- package/dist/src/index.js +631 -685
- package/dist/src/message-key-eqq90drz.js +1 -0
- package/dist/src/message-lock-y872a869.js +5 -0
- package/dist/src/sweep-order-yf30eb7c.js +1 -0
- package/dist/src/sweep-runner-f1ee3pdt.js +1 -0
- package/dist/src/wallet-zjprdjn2.js +1 -0
- package/package.json +2 -2
- package/dist/src/age-1k8hs4ec.js +0 -1
- package/dist/src/client-n6fpnd9f.js +0 -1
- package/dist/src/hl-run-0pv1e0p2.js +0 -1
- package/dist/src/index-f5vhzspa.js +0 -12
- package/dist/src/index-st6k9vhc.js +0 -2062
- package/dist/src/message-key-yczrxszr.js +0 -1
- package/dist/src/message-lock-thr851d5.js +0 -5
- package/dist/src/sweep-order-jrq2hkye.js +0 -1
- package/dist/src/sweep-runner-jftw9em7.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Se,zt,an}from"./index-sdgefh6q.js";import{_,ie,de,ue,q}from"./index-abbkxz62.js";var o="message-x25519-v1";function n(e){if(e.length!==32)throw Error("the master is 32 bytes");let t=Se(_,e,new Uint8Array(0),new TextEncoder().encode(o),32),r=ie.getPublicKey(t);return{recipient:zt(r),publicKey:r,secret:t}}function f(e){let t=e.trim().toLowerCase().split(/\s+/).join(" ");if(!ue(t,q))throw Error("that is not a valid 24-word BIP-39 recovery phrase");let r=de(t,q);if(r.length!==32)throw Error("that is not a 24-word BIP-39 recovery phrase");try{return n(r)}finally{r.fill(0)}}function d(e){return an(e.secret)}export{o as MESSAGE_KEY_INFO,n as deriveMessageKey,d as messageIdentityText,f as messageKeyFromPhrase};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{j,L,xe}from"./index-abbkxz62.js";var a="ONE message lock v1",c=/^age1[a-z0-9]{58}$/,l=/^[a-z0-9][a-z0-9-]{0,62}$/,u=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function g(n,t){return`${a}
|
|
2
|
+
${n}
|
|
3
|
+
${t}`}function h(n,t,e){return`${a}
|
|
4
|
+
${n}/${t}
|
|
5
|
+
${e}`}function A(n){let[t,...e]=n.trim().split("/"),r=t.toLowerCase();if(!l.test(r))return null;if(e.length===0)return{slug:r};if(e.length>1||!u.test(e[0]))return null;return{slug:r,agent:e[0]}}var i=[3,0,0];function k(n){let t=[],e=n;do{let r=e&127;if(e>>>=7,e!==0)r|=128;t.push(r)}while(e!==0);return t}function f(n){let t=new TextEncoder().encode(n),e=k(t.length),r=new Uint8Array(i.length+e.length+t.length);return r.set(i,0),r.set(e,i.length),r.set(t,i.length+e.length),j(r,{dkLen:32})}var m=(n)=>{let t="";for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[e]);return btoa(t)};function E(n,t){if(n.length!==32)throw Error("a Sui ed25519 secret is 32 bytes");let e=L.getPublicKey(n),r=L.sign(f(t),n),o=new Uint8Array(97);return o[0]=0,o.set(r,1),o.set(e,65),{address:xe(e),signature:m(o)}}function p(n,t){let e;try{let s=atob(t.trim());e=Uint8Array.from(s,(d)=>d.charCodeAt(0))}catch{return null}if(e.length!==97||e[0]!==0)return null;let r=e.subarray(1,65),o=e.subarray(65,97);try{if(!L.verify(r,f(n),o))return null}catch{return null}return xe(o)}function w(n,t,e){if(!l.test(n))return{ok:!1,reason:"malformed",detail:"that is not a name"};if(e!==void 0&&!u.test(e))return{ok:!1,reason:"malformed",detail:"that is not an agent name"};if(typeof t?.lock!=="string"||!c.test(t.lock))return{ok:!1,reason:"malformed",detail:"the published lock is not a lock"};if(typeof t.suiAddress!=="string"||typeof t.signature!=="string")return{ok:!1,reason:"malformed",detail:"the published lock has no signer or no signature"};let r=e===void 0?n:`${n}/${e}`,o=e===void 0?g(n,t.lock):h(n,e,t.lock);if(t.message!==o)return{ok:!1,reason:"not_for_slug",detail:`the signed text does not say this lock belongs to ${r}`};let s=p(o,t.signature);if(!s)return{ok:!1,reason:"invalid",detail:"the signature does not hold for that text"};if(s.toLowerCase()!==t.suiAddress.toLowerCase())return{ok:!1,reason:"invalid",detail:"the signature was made by a different key than the address named"};return{ok:!0,lock:t.lock,suiAddress:s.toLowerCase()}}export{h as agentLockMessage,g as lockMessage,A as parseLockName,E as signSuiPersonalMessage,w as verifyLockRecord};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Wn,cn,Wt,ln}from"./index-y4xe5pm7.js";export{Wn as ORDER_MAX_TTL_MS,cn as ORDER_MIN_REMAINING_MS,ln as handoverMessage,Wt as sweepOrderMessage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{cn,Wt,ln}from"./index-y4xe5pm7.js";import{pe,wn}from"./index-abbkxz62.js";function A(e,r){return pe(r.chain,e,Wt(r))}function x(e,r){return pe(r.chain,e,ln(r))}function v(){let e=crypto.getRandomValues(new Uint8Array(24));return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var p=(e,r)=>typeof e==="string"&&typeof r==="string"&&e.toLowerCase()===r.toLowerCase();async function E(e,r){let s=r.now??(()=>Date.now()),t=await r.ask("wallet:sweep",{workspace:e.workspace,actor:e.actor,chain:e.chain,pending:!0});if(t.ok!==!0)return{ok:!1,error:String(t.error??"pending_read_failed"),results:[]};if(!p(t.agentAddress,e.agentKey.address))return{ok:!1,error:"agent_address_mismatch",results:[]};let c=String(t.to??"");if(!c)return{ok:!1,error:"owner_address_unproven",results:[]};if(e.ownerAddress!==void 0&&!p(e.ownerAddress,c))return{ok:!1,error:"owner_address_mismatch",results:[]};let i=Array.isArray(t.orders)?t.orders:[],a=[];for(let n of i){let o=String(n.nonce??""),u=(d)=>(a.push({nonce:o,ok:!1,error:d}),a),f=typeof n.amountUnits==="string"&&/^\d+$/.test(n.amountUnits)?BigInt(n.amountUnits):null,w=Number(n.expiresAt);if(f===null||f<=0n||!Number.isSafeInteger(w)){u("order_invalid");continue}if(w-s()<cn){u("order_too_close_to_expiry");continue}if(!p(n.destination,c)){u("order_destination_mismatch");continue}let m={workspace:e.workspace,actor:e.actor,chain:e.chain,destination:String(n.destination),amount:f,nonce:o,expiresAt:w};if(!wn(e.chain,c,n.signature,Wt(m))){u("order_signature_invalid");continue}let y=r.transfer?.[e.chain];if(!y){u(`no_signer:${e.chain}`);continue}let l;try{l=await y({chain:e.chain,from:e.agentKey.address,to:m.destination,amountUnits:f,privateKeyHex:e.agentKey.privateKeyHex})}catch(d){return u(`transfer_failed:${d instanceof Error?d.message:String(d)}`),{ok:!1,error:"transfer_failed",results:a}}let h=await r.ask("wallet:sweep",{workspace:e.workspace,actor:e.actor,chain:e.chain,nonce:o,paymentTx:l});if(h.settled===!0)a.push({nonce:o,ok:!0,settled:!0,paymentTx:l});else a.push({nonce:o,ok:!1,settled:!1,paymentTx:l,error:String(h.error??"settle_failed")})}return{ok:a.every((n)=>n.ok),results:a}}var _=(e)=>Uint8Array.from((e.match(/.{2}/g)??[]).map((r)=>parseInt(r,16)));async function g(e){let[r,s,t]=await Promise.all([e("@mysten/sui/keypairs/ed25519"),e("@mysten/sui/jsonRpc"),e("@mysten/sui/transactions")]);return{keypairs:r,client:s,transactions:t}}function K(e){let r=e.load??((s)=>import(s));return async(s)=>{if(s.chain!=="sui")throw Error(`no_signer:${s.chain}`);let t;try{t=await g(r)}catch{throw Error("sui_signer_unavailable: install @mysten/sui in the agent runtime")}let c=t.keypairs.Ed25519Keypair.fromSecretKey(_(s.privateKeyHex));if(!p(c.toSuiAddress(),s.from))throw Error("agent_key_mismatch");let i=new t.transactions.Transaction;i.setSender(c.toSuiAddress());let[a]=i.splitCoins(i.gas,[i.pure.u64(s.amountUnits)]);i.transferObjects([a],i.pure.address(s.to));let n=new t.client.SuiJsonRpcClient({url:e.rpcUrl,network:e.network}),o=await n.signAndExecuteTransaction({transaction:i,signer:c,options:{showEffects:!0}});if(await n.waitForTransaction({digest:o.digest}),o.effects?.status?.status!=="success")throw Error(o.effects?.status?.error??"sui_transfer_failed");return o.digest}}export{v as newOrderNonce,E as runSweepOrders,x as signHandoverOffer,A as signSweepOrder,K as suiTransfer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Le,Ft,on,yt,Kt,De,C,x}from"./index-abbkxz62.js";export{C as promptSecret,yt as registerAgentWallet,Kt as registerSealedWallet,Ft as sealWallet,x as unlock,on as walletCmd,Le as walletFor,De as writeKeysFile};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oneie",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.10.1",
|
|
4
4
|
"description": "Give your agent financial superpowers. One command makes a key on your machine, five wallets, a shop and a test sale — your agent can sell and be paid in USDC, and asks you before real money moves.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"@noble/curves": "^2.2.0",
|
|
49
49
|
"@noble/hashes": "^2.2.0",
|
|
50
50
|
"@oneie/evals": "^0.2.0",
|
|
51
|
-
"@oneie/sdk": "^0.17.
|
|
51
|
+
"@oneie/sdk": "^0.17.10",
|
|
52
52
|
"@types/node": "^25.6.0",
|
|
53
53
|
"commander": "^12.0.0",
|
|
54
54
|
"tsx": "^4.0.0",
|
package/dist/src/age-1k8hs4ec.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ye,G,se,Le,o,ie,Ve,we,ot,st,Je,Xe,Qe,et,tt,rt,it,at,nt,ct}from"./index-f5vhzspa.js";import"./index-st6k9vhc.js";export{G as AGE_ARMOR_BEGIN,se as AGE_ARMOR_END,ye as AGE_VERSION_LINE,o as AgeError,Le as MAX_STANZAS,et as armor,tt as dearmor,ot as decodeIdentity,Ve as decodeRecipient,Qe as decrypt,we as encodeIdentity,ie as encodeRecipient,Je as encrypt,rt as extractArmored,it as looksLikeAge,nt as openBytes,ct as openText,Xe as parseHeader,st as recipientOf,at as sealText};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r,s,n,t,e}from"./index-st6k9vhc.js";export{n as authHeaders,t as jsonMode,e as out,r as resolveBase,s as resolveKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{h,Me,Fe,me,f,Ge,u,he,S,F,z,E,ge,I,j,be,je,Ze,J,Ye,Pe}from"./index-st6k9vhc.js";import{join as Xs,sep as Gs}from"node:path";function wn(e,t,r){return e&t^~e&r}function En(e,t,r){return e&t^e&r^t&r}class Nt{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ge(this.buffer)}update(e){S(this),u(e);let{view:t,buffer:r,blockLen:n}=this,s=e.length,o=!1;for(let i=0;i<s;){let c=Math.min(n-this.pos,s-i);if(c===n){let a=ge(e);for(;n<=s-i;i+=n)this.process(a,i);o=!0;continue}if(r.set(i===0&&c===s?e:e.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===n)this.process(t,0),this.pos=0,o=!0}if(this.length+=e.length,o)this.roundClean();return this}digestInto(e){S(this),F(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:s}=this,{pos:o}=this;if(t[o++]=128,t.fill(0,o),this.padOffset>n-o)this.process(r,0),t.fill(0);Fe(r,n-8,this.length*8,s),this.process(r,0),this.roundClean();let i=e===t?r:ge(e),c=this.outputLen,a=c/4,d=this.get();if(c%4||a>d.length)throw Error("invalid outputLen");for(let p=0;p<a;p++)i.setUint32(4*p,d[p],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:s,pos:o}=this;if(e.destroyed=s,e.finished=n,e.length=r,e.pos=o,o)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var Bn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ur=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]),Ee=new Uint32Array(64);class An extends Nt{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:s,F:o,G:i,H:c}=this;return[e,t,r,n,s,o,i,c]}set(e,t,r,n,s,o,i,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let p=0;p<16;p++,t+=4)Ee[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let b=Ee[p-15],w=Ee[p-2],x=I(b,7)^I(b,18)^b>>>3,R=I(w,17)^I(w,19)^w>>>10;Ee[p]=R+Ee[p-7]+x+Ee[p-16]|0}let{A:r,B:n,C:s,D:o,E:i,F:c,G:a,H:d}=this;for(let p=0;p<64;p++){let b=I(i,6)^I(i,11)^I(i,25),w=d+b+wn(i,c,a)+Ur[p]+Ee[p]|0,R=(I(r,2)^I(r,13)^I(r,22))+En(r,n,s)|0;d=a,a=c,c=i,i=o+w|0,o=s,s=n,n=r,r=w+R|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,c=c+this.F|0,a=a+this.G|0,d=d+this.H|0,this.set(r,n,s,o,i,c,a,d)}roundClean(){E(Ee)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),E(this.buffer)}}class _n extends An{constructor(){super(32,Bn)}}var Sn=J(()=>new _n,Pe(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yt(e,t,r=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let n=0;n<e.length;n++)r(e[n],`${t}[${n}]`);return e}var K=(e,t,r)=>u(e,t,r),Ct=f;function On(e,t=""){if(typeof e!=="string"){let r=t&&`"${t}" `;throw TypeError(r+"expected string, got type="+typeof e)}return e}function Be(e,t="object"){if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function $e(e,t){if(typeof e!=="function")throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Ut=be,ue=(...e)=>Ze(...e),xt=(e)=>je(e),qe=me,wt=(e)=>Ye(e),bt=BigInt(0),kn=BigInt(1),qr=(e)=>e?`"${e}" `:"";function ae(e,t=""){if(typeof e!=="boolean")throw TypeError(qr(t)+"expected boolean, got type="+typeof e);return e}function Et(e){if(typeof e==="bigint"){if(!Ae(e))throw RangeError("positive bigint expected, got "+e)}else Ct(e);return e}function He(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function at(e){let t=Et(e).toString(16);return t.length&1?"0"+t:t}function vn(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?bt:BigInt("0x"+e)}function ce(e){return vn(be(e))}function qt(e){return vn(be(Pr(u(e)).reverse()))}function Bt(e,t){if(f(t),t===0)throw Error("zero output length is invalid");e=Et(e);let r=t*2,n=e.toString(16);if(n.length>r)throw RangeError("number is too large");return je(n.padStart(r,"0"))}function Pt(e,t){return Bt(e,t).reverse()}function Pr(e){return Uint8Array.from(K(e))}function Ae(e){return typeof e==="bigint"&&bt<=e}function jt(e,t,r){return Ae(e)&&Ae(t)&&Ae(r)&&t<=e&&e<r}function Mt(e,t,r,n){if(!jt(t,r,n))throw RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function ze(e){if(e<bt)throw Error("expected non-negative bigint, got "+e);return e===bt?0:e.toString(2).length}var ct=(e)=>(He(e,"n"),(kn<<BigInt(e))-kn);function In(e,t,r){if(f(e,"hashLen"),f(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let n=(k)=>new Uint8Array(k),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),c=1000,a=n(e),d=n(e),p=0,b=()=>{a.fill(1),d.fill(0),p=0},w=(...k)=>r(d,ue(a,...k)),x=(k=s)=>{if(d=w(o,k),a=w(),k.length===0)return;d=w(i,k),a=w()},R=()=>{if(p++>=c)throw Error("drbg: tried max amount of iterations");let k=0,N=[];while(k<t){a=w();let T=a.slice();N.push(T),k+=a.length}return ue(...N)};return(k,N)=>{b(),x(k);let T=void 0;while((T=N(R()))===void 0)x();return b(),T}}function _e(e,t={},r={},n="object"){Be(e,n),Be(t,"fields"),Be(r,"optFields");function s(i,c,a){let d=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,p=e[i];if(!Object.hasOwn(e,i)&&(a?p!==void 0:c!=="function"))throw TypeError(`${d} is invalid: expected own property`);if(a&&p===void 0)return;let b=typeof p;if(b!==c||p===null)throw TypeError(`${d} is invalid: expected ${c}, got ${b}`)}let o=(i,c)=>Object.entries(i).forEach(([a,d])=>s(a,d,c));o(t,!1),o(r,!0)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var V=BigInt(0),U=BigInt(1),Se=BigInt(2),Hn=BigInt(3),Wt=BigInt(4),Dn=BigInt(5),jr=BigInt(7),Fn=BigInt(8),Mr=BigInt(9),zr=BigInt(15),Ln=BigInt(16),Wr=BigInt("0x10000000000000000");function ne(e,t){if(t<=V)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=V?r:t+r}function Nn(e,t,r){if(r<=U)throw Error("pow: expected modulus > 1, got "+r);if(typeof t!=="bigint")throw TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<V)throw Error("invalid exponent, negatives unsupported");if(t===V)return U;if(t===U)return e;let n=e%r;if(n<V)n+=r;if(t<Wr){let c=U;while(t>V){if(t&U)c=c*n%r;n=n*n%r,t>>=U}return c}let s=[];while(t>V)s.push(Number(t&zr)),t>>=Wt;let o=Array(16);o[0]=U,o[1]=n;for(let c=2;c<16;c++)o[c]=o[c-1]*n%r;let i=o[s[s.length-1]];for(let c=s.length-2;c>=0;c--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;let a=s[c];if(a!==0)i=i*o[a]%r}return i}function re(e,t,r){if(r<=U)throw Error("pow2: expected modulus > 1, got "+r);if(t<V)throw Error("pow2: expected non-negative exponent, got "+t);let n=e;while(t-- >V)n*=n,n%=r;return n}function Rn(e,t){if(e===V)throw Error("invert: expected non-zero number");if(t<=U)throw Error("invert: expected modulus > 1, got "+t);let r=ne(e,t),n=t,s=V,o=U;while(r!==V){let c=n/r,a=n-r*c,d=s-o*c;n=r,r=a,s=o,o=d}if(n!==U)throw Error("invert: does not exist");return ne(s,t)}function Cn(e,t){if(t<=U)throw Error("invertCt: expected prime modulus > 1, got "+t);let r=ne(e,t);if(r===V)throw Error("invertCt: expected non-zero number");let n=Nn(r,t-Se,t);if(ne(r*n,t)!==U)throw Error("invertCt: does not exist");return n}function Zt(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw Error("Cannot find square root")}function Yt(e,t){if((e&U)===V)throw Error(t+": expected odd modulus, got "+e)}function Un(e,t){let r=e,n=(r.ORDER+U)/Wt,s=r.pow(t,n);return Zt(r,s,t),s}function Zr(e,t){let r=e,n=(r.ORDER-Dn)/Fn,s=r.mul(t,Se),o=r.pow(s,n),i=r.mul(t,o),c=r.mul(r.mul(i,Se),o),a=r.mul(i,r.sub(c,r.ONE));return Zt(r,a,t),a}function Yr(e){let t=Ke(e),r=qn(e),n=r(t,t.neg(t.ONE)),s=r(t,n),o=r(t,t.neg(n)),i=(e+jr)/Ln;return(c,a)=>{let d=c,p=d.pow(a,i),b=d.mul(p,n),w=d.mul(p,s),x=d.mul(p,o),R=d.eql(d.sqr(b),a),D=d.eql(d.sqr(w),a);p=d.cmov(p,b,R),b=d.cmov(x,w,D);let k=d.eql(d.sqr(b),a),N=d.cmov(p,b,k);return Zt(d,N,a),N}}function qn(e){if(e<Hn)throw Error("sqrt is not defined for small field");Yt(e,"tonelliShanks");let t=e-U,r=0;while(t%Se===V)t/=Se,r++;let n=Se,s=Ke(e);while(Tn(s,n)===1)if(n++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return Un;let o=s.pow(n,t),i=(t+U)/Se;return function(a,d){let p=a;if(p.is0(d))return d;if(Tn(p,d)!==1)throw Error("Cannot find square root");let b=r,w=p.mul(p.ONE,o),x=p.pow(d,t),R=p.pow(d,i);while(!p.eql(x,p.ONE)){if(p.is0(x))throw Error("Cannot find square root: probably non-prime P");let D=1,k=p.sqr(x);while(!p.eql(k,p.ONE))if(D++,k=p.sqr(k),D===b)throw Error("Cannot find square root");let N=U<<BigInt(b-D-1),T=p.pow(w,N);b=D,w=p.sqr(T),x=p.mul(x,w),R=p.mul(R,T)}return R}}function Kr(e){if(Yt(e,"Fp.sqrt"),e%Wt===Hn)return Un;if(e%Fn===Dn)return Zr;if(e%Ln===Mr)return Yr(e);return qn(e)}var Vr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function We(e){if(Be(e,"field"),typeof e.ORDER!=="bigint")throw TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);He(e.BYTES,"BYTES"),He(e.BITS,"BITS");for(let t of Vr)$e(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=U)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Kt(e,t,r=!1){We(e),yt(t,"nums"),ae(r,"passZero");let n=e,s=Array(t.length).fill(r?n.ZERO:void 0),o=t.reduce((c,a,d)=>{if(n.is0(a))return c;return s[d]=c,n.mul(c,a)},n.ONE),i=n.inv(o);return t.reduceRight((c,a,d)=>{if(n.is0(a))return c;return s[d]=n.mul(c,s[d]),n.mul(c,a)},i),s}function Tn(e,t){We(e);let r=e;Yt(r.ORDER,"FpLegendre");let n=(r.ORDER-U)/Se,s=r.pow(t,n),o=r.eql(s,r.ONE),i=r.eql(s,r.ZERO),c=r.eql(s,r.neg(r.ONE));if(!o&&!i&&!c)throw Error("invalid Legendre symbol result");return o?1:i?0:-1}function Xr(e,t){if(t!==void 0)Ct(t);if(e<=V)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=ze(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${r})`);let n=t!==void 0?t:r,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var $n=new WeakMap;class zt{ORDER;BITS;BYTES;isLE;ZERO=V;ONE=U;_lengths;_mod;constructor(e,t={}){if(e<=U)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:n,nByteLength:s}=Xr(e,r);if(s>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=s,Object.freeze(this)}create(e){return ne(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return V<=e&&e<this.ORDER}is0(e){return e===V}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&U)===U}neg(e){return ne(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ne(e*e,this.ORDER)}add(e,t){return ne(e+t,this.ORDER)}sub(e,t){return ne(e-t,this.ORDER)}mul(e,t){return ne(e*t,this.ORDER)}pow(e,t){return Nn(e,t,this.ORDER)}div(e,t){return ne(e*Rn(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Rn(e,this.ORDER)}sqrt(e){let t=$n.get(this);if(!t)$n.set(this,t=Kr(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?Pt(e,this.BYTES):Bt(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:r,BYTES:n,isLE:s,ORDER:o,_mod:i}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let a=new Uint8Array(n);a.set(e,s?0:a.length-e.length),e=a}if(e.length!==n)throw Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=s?qt(e):ce(e);if(i)c=ne(c,o);if(!t){if(!this.isValid(c))throw Error("invalid field element: outside of range 0..ORDER")}return c}invertBatch(e){return Kt(this,e,!0)}cmov(e,t,r){return ae(r,"condition"),r?t:e}}function Ke(e,t={}){return Object.freeze(zt.prototype),new zt(e,t)}function Pn(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=U)throw Error("field order must be greater than 1");let t=ze(e-U);return Math.ceil(t/8)}function At(e){let t=Pn(e);return t+Math.ceil(t/2)}function _t(e,t,r=!1){K(e);let n=e.length,s=Pn(t),o=Math.max(At(t),16);if(n<o||n>1024)throw Error("expected "+o+"-1024 bytes of input, got "+n);let i=r?qt(e):ce(e),c=ne(i,t-U)+U;return r?Pt(c,s):Bt(c,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Gt=BigInt(0),dt=BigInt(1),Gr=BigInt(4),Vt=16,jn=128,Jr=5,Mn=(()=>2147483648)();function Ve(e){let t=e;if(typeof t!=="function")throw TypeError('"Point" expected constructor, got type='+typeof e);$e(t.fromAffine,"Point.fromAffine"),$e(t.fromBytes,"Point.fromBytes"),$e(t.fromHex,"Point.fromHex"),Be(t.BASE,"Point.BASE"),Be(t.ZERO,"Point.ZERO"),We(t.Fp),We(t.Fn)}function Wn(e,t){Ve(e),Zn(t,e);let r=Kt(e.Fp,t.map((n)=>n.Z));return t.map((n,s)=>e.fromAffine(n.toAffine(r[s])))}function Qr(e,t,r=1){if(!Number.isSafeInteger(e)||e<r||e>t)throw Error("invalid window size, expected ["+r+".."+t+"], got W="+e)}function es(e,t){let r=e*(4*t+128);if(r>Mn)throw Error("invalid window size: table would need ~"+Math.ceil(r/1048576)+" MiB, max "+Mn/1048576+" MiB")}function Jt(e,t){if(e===void 0)return;$e(e,"randomBytes");try{let r=e(t);if(!qe(r)||r.length!==t)return}catch{return}return e}function Zn(e,t){yt(e,"points"),e.forEach((r,n)=>{if(!(r instanceof t))throw Error("invalid point at index "+n)})}function ts(e,t,r){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach((n,s)=>{if(!(r===void 0?t.isValid(n):Ae(n)&&n<r))throw Error("invalid scalar at index "+s)})}var Yn=new WeakMap;function Xt(e){return Yn.get(e)||1}function ns(e,t){let r=e.double(),n=[e];for(let s=1;s<t;s++)n.push(n[s-1].add(r));return n}function rs(e,t){let r=2**t,n=r/2,s=BigInt(r-1),o=[];while(e>Gt){let i=0;if(e&dt){if(i=Number(e&s),i>=n)i-=r;e-=BigInt(i)}o.push(i),e>>=dt}return o}function ss(e,t,r){let n=2**t,s=n/2,o=BigInt(n-1),i=BigInt(t),c=[];for(let a=0;a<r;a++){let d=Number(e&o);if(e>>=i,d>s)d-=n,e+=dt;c.push(d)}if(e!==Gt)throw Error("invalid wnaf");return c}function os(e,t,r){let n=0;for(let o of r)n=Math.max(n,o.length);let s=e;for(let o=n-1;o>=0;o--){if(o!==n-1)s=s.double();for(let i=0;i<r.length;i++){let c=r[i][o];if(c){let a=t[i][Math.abs(c)-1>>1];s=s.add(c<0?a.negate():a)}}}return s}class Qt{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Ve(e),this.randomBytes=Jt(t,Vt),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let n=Math.ceil(r/t)+1,s=2**(t-1),o=[],i=e;for(let c=0;c<n;c++){let a=i;for(let d=0;d<s;d++)o.push(a),a=a.add(i);i=o[o.length-1].double()}return{W:t,bits:r,windows:n,comp:o}}wnafCachedCT(e,t){let{W:r,windows:n,comp:s}=e,o=2**(r-1),i=ss(t,r,n),c=this.ZERO,a=this.BASE;for(let d=0;d<n;d++){let p=i[d],b=d*o,w=Math.abs(p)-1,x=s[b];for(let D=1;D<o;D++)x=D===w?s[b+D]:x;let R=x.negate();if(p===0)a=a.add(s[b]);else c=c.add(p<0?R:x)}return{p:c,f:a}}getWnafPrecomputes(e,t,r,n){let s=this.wnafPrecomputes.get(t),o=s?.find((i)=>i.W===e&&i.bits===r);if(!o){if(o=this.buildWnafTable(t,e,r),typeof n==="function")o={...o,comp:n(o.comp)};if(!s)s=[],this.wnafPrecomputes.set(t,s);s.push(o)}return o}assertPoint(e){if(!(e instanceof this.Point))throw TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!jt(t,dt,this.Point.Fn.ORDER))throw Error("invalid scalar")}runCT(e,t,r,n){let s=Xt(e);if(s===1)return this.fixedWindowCT(e,t,r);return this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,n),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+jn,s=this.randomBytes(Vt);if(!qe(s)||s.length!==Vt)throw Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let o=t+ce(s)*this.Point.Fn.ORDER;return this.runCT(e,o,n,r)}fixedWindowCT(e,t,r){let n=Jr,s=1<<n,o=ct(n),i=Array(s);i[0]=this.ZERO;for(let d=1;d<s;d++)i[d]=i[d-1].add(e);let c=Math.ceil(r/n),a=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let w=0;w<n;w++)a=a.double();let p=Number(t>>BigInt(d*n)&o),b=i[0];for(let w=1;w<s;w++)b=w===p?i[w]:b;a=a.add(b)}return{p:a,f:a}}shouldBlind(e,t){if(this.randomBytes===void 0)return!1;if(t===dt)return!0;if(e!==this.BASE)return!1;if(this.baseCanBeBlinded===void 0)this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0();return this.baseCanBeBlinded}mulSecret(e,t,r,n){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,n):this.mulCT(e,t,n)}mulUnsafe(e,t,r){if(this.assertPoint(e),!Ae(t))throw Error("invalid scalar");let n=Xt(e);if(n===1||t>=this.Point.Fn.ORDER)return St(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),Qr(t,this.bits);let r=Math.ceil((this.bits+jn)/t)+1;es(r*2**(t-1),this.Point.Fp.BYTES),Yn.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Xt(e)!==1}}function St(e,t,r,n=!1){if(Ve(e),Zn(t,e),ae(n,"allowOversized"),ts(r,e.Fn,n?e.Fn.ORDER**Gr:void 0),t.length!==r.length)throw Error("arrays of points and scalars must have equal length");let s=t.map((i)=>ns(i,4)),o=r.map((i)=>rs(i,4));return os(e.ZERO,s,o)}function zn(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return We(t),t}else return Ke(e,{isLE:r})}function Kn(e,t,r={},n){if(e!=="weierstrass"&&e!=="edwards")throw Error('expected curve type "weierstrass" or "edwards"');if(n===void 0)n=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);_e(r);for(let a of["p","n","h"]){let d=t[a];if(!(Ae(d)&&d!==Gt))throw Error(`CURVE.${a} must be positive bigint`)}let s=zn(t.p,r.Fp,n),o=zn(t.n,r.Fn,n),c=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let a of c)if(!s.isValid(t[a]))throw Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:s,Fn:o}}function Vn(e,t){return function(n){let s=e(n);return{secretKey:s,publicKey:t(s)}}}class en{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(he(e),u(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let s=0;s<n.length;s++)n[s]^=54;this.iHash.update(n),this.oHash=e.create();for(let s=0;s<n.length;s++)n[s]^=106;this.oHash.update(n),E(n)}update(e){return S(this),this.iHash.update(e),this}digestInto(e){S(this),F(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:o,outputLen:i,canXOF:c}=this;return e=e,e.finished=n,e.destroyed=s,e.blockLen=o,e.outputLen=i,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Xn=(()=>{let e=(t,r,n)=>new en(t,r).update(n).digest();return e.create=(t,r)=>new en(t,r),e})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var is=BigInt(0);class Gn extends Error{constructor(e=""){super(e)}}var le={Err:Gn,_tlv:{encode:(e,t)=>{let{Err:r}=le;if(He(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(On(t,"data"),t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,s=at(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?at(s.length/2|128):"";return at(e)+o+s+t},decode(e,t){let{Err:r}=le;t=K(t,void 0,"DER data");let n=0;if(e<0||e>255)throw new r("tlv.decode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let s=t[n++],o=!!(s&128),i=0;if(!o)i=s;else{let a=s&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+a);if(d.length!==a)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let p of d)i=i<<8|p;if(n+=a,i<128)throw new r("tlv.decode(long): not minimal encoding")}let c=t.subarray(n,n+i);if(c.length!==i)throw new r("tlv.decode: wrong value length");return{v:c,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=le;if(Et(e),e<is)throw new t("integer: negative integers are not allowed");let r=at(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=le;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ce(e)}},toSig(e,t){let{Err:r,_int:n,_tlv:s}=le;if(t!==void 0){if(He(t,"maxScalarBytes"),t<1)throw new r("invalid signature: maxScalarBytes must be positive")}let o=K(e,void 0,"signature"),{v:i,l:c}=s.decode(48,o);if(c.length)throw new r("invalid signature: left bytes after parsing");let{v:a,l:d}=s.decode(2,i),{v:p,l:b}=s.decode(2,d);if(b.length)throw new r("invalid signature: left bytes after parsing");if(t!==void 0&&(a.length>t||p.length>t))throw new r("invalid signature: integer too large");return{r:n.decode(a),s:n.decode(p)}},hexFromSig(e){let{_tlv:t,_int:r}=le;_e(e,{r:"bigint",s:"bigint"},{},"sig");let n=t.encode(2,r.encode(e.r)),s=t.encode(2,r.encode(e.s)),o=n+s;return t.encode(48,o)}},kt=(()=>(Object.freeze(le._tlv),Object.freeze(le._int),Object.freeze(le)))();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Jn=(e,t)=>(e+(e>=0?t:-t)/Qn)/t;function as(e,t,r){Mt("scalar",e,pe,r);let[[n,s],[o,i]]=t,c=Jn(i*e,r),a=Jn(-s*e,r),d=e-c*n-a*o,p=-c*s-a*i,b=d<pe,w=p<pe;if(b)d=-d;if(w)p=-p;let x=ct(Math.ceil(ze(r)/2))+De;if(d<pe||d>=x||p<pe||p>=x)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:b,k1:d,k2neg:w,k2:p}}function rn(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function tn(e,t){_e(e);let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];if(ae(r.lowS,"lowS"),ae(r.prehash,"prehash"),r.format!==void 0)rn(r.format);return r}var pe=BigInt(0),De=BigInt(1),Qn=BigInt(2),nn=BigInt(3),cs=BigInt(4);function er(e,t={}){let r=Kn("weierstrass",e,t),{Fp:n,Fn:s,CURVE:o}=r,{h:i,n:c}=o;_e(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:a,allowInfinityPoint:d,clearCofactor:p,isTorsionFree:b,fromBytes:w,toBytes:x}=t,R=t.randomBytes===void 0?wt:t.randomBytes;if(a){if(!n.is0(o.a)||typeof a.beta!=="bigint"||!Array.isArray(a.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let D=a?{beta:a.beta,basises:a.basises.map((l)=>[...l])}:void 0,k=nr(n,s);function N(){if(!n.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function T(l,g,m){if(g.is0()){if(!d)throw Error("bad point: ZERO");return Uint8Array.of(0)}let{x:B,y:A}=g.toAffine(),_=n.toBytes(B);if(ae(m,"isCompressed"),m){N();let O=!n.isOdd(A);return ue(tr(O),_)}else return ue(Uint8Array.of(4),_,n.toBytes(A))}function Q(l){K(l,void 0,"Point");let{publicKey:g,publicKeyUncompressed:m}=k,B=l.length,A=l[0],_=l.subarray(1);if(d&&B===1&&A===0)return{x:n.ZERO,y:n.ZERO};if(B===g&&(A===2||A===3)){let O=n.fromBytes(_);if(!n.isValid(O))throw Error("bad point: is not on curve, wrong x");let v=st(O),H;try{H=n.sqrt(v)}catch(P){let Z=P instanceof Error?": "+P.message:"";throw Error("bad point: is not on curve, sqrt error"+Z)}N();let L=n.isOdd(H);if((A&1)===1!==L)H=n.neg(H);return{x:O,y:H}}else if(B===m&&A===4){let O=n.BYTES,v=n.fromBytes(_.subarray(0,O)),H=n.fromBytes(_.subarray(O,O*2));if(!Ce(v,H))throw Error("bad point: is not on curve");return{x:v,y:H}}else throw Error(`bad point: got length ${B}, expected compressed=${g} or uncompressed=${m}`)}let G=x===void 0?T:x,fe=w===void 0?Q:w,se=n.mul(o.b,nn),X=n.is0(o.a)?(l)=>n.ZERO:(l)=>n.mul(o.a,l);function st(l){let g=n.sqr(l),m=n.mul(g,l);return n.add(n.add(m,n.mul(l,o.a)),o.b)}function Ce(l,g){let m=n.sqr(g),B=st(l);return n.eql(m,B)}if(!Ce(o.Gx,o.Gy))throw Error("bad curve params: generator point");let ee=n.mul(n.pow(o.a,nn),cs),pt=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(ee,pt)))throw Error("bad curve params: a or b");function Re(l,g,m=!1){if(!n.isValid(g)||m&&n.is0(g))throw Error(`bad point coordinate ${l}`);return typeof g==="object"&&g!==null?n.create(g):g}function Ue(l){if(!(l instanceof C))throw Error("Weierstrass Point expected")}function gt(l){if(!D||!D.basises)throw Error("no endo");return as(l,D.basises,s.ORDER)}function Te(l,g,m,B){if(!s.isValid(B))throw RangeError("invalid scalar: out of range");if(D){let{k1neg:A,k1:_,k2neg:O,k2:v}=gt(B),H=new C(n.mul(m.X,D.beta),m.Y,m.Z);l.push(A?m.negate():m,O?H.negate():H),g.push(_,v)}else l.push(m),g.push(B)}let mt=new WeakSet;class C{static BASE=new C(o.Gx,o.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(l,g,m){this.X=Re("x",l),this.Y=Re("y",g,!0),this.Z=Re("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(l){let{x:g,y:m}=l||{};if(!l||!n.isValid(g)||!n.isValid(m))throw Error("invalid affine point");if(l instanceof C)throw Error("projective point not allowed");if(n.is0(g)&&n.is0(m))return C.ZERO;return new C(g,m,n.ONE)}static fromBytes(l){let g=C.fromAffine(fe(K(l,void 0,"point")));return g.assertValidity(),g}static fromHex(l){return C.fromBytes(xt(l))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=6,g=!0){if(we.setWindowSize(this,l),!g)this.multiply(nn);return this}assertValidity(){let l=this;if(l.is0()){if(d&&n.is0(l.X)&&n.eql(l.Y,n.ONE)&&n.is0(l.Z))return;throw Error("bad point: ZERO")}if(mt.has(l))return;let{x:g,y:m}=l.toAffine();if(!n.isValid(g)||!n.isValid(m))throw Error("bad point: x or y not field elements");if(!Ce(g,m))throw Error("bad point: equation left != right");if(!l.isTorsionFree())throw Error("bad point: not in prime-order subgroup");mt.add(l)}hasEvenY(){let{y:l}=this.toAffine();if(!n.isOdd)throw Error("Field doesn't support isOdd");return!n.isOdd(l)}equals(l){Ue(l);let{X:g,Y:m,Z:B}=this,{X:A,Y:_,Z:O}=l,v=n.eql(n.mul(g,O),n.mul(A,B)),H=n.eql(n.mul(m,O),n.mul(_,B));return v&&H}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{X:l,Y:g,Z:m}=this,{ZERO:B,ZERO:A,ZERO:_}=n,O=n.mul(l,l),v=n.mul(g,g),H=n.mul(m,m),L=n.mul(l,g);return L=n.add(L,L),_=n.mul(l,m),_=n.add(_,_),B=X(_),A=n.mul(se,H),A=n.add(B,A),B=n.sub(v,A),A=n.add(v,A),A=n.mul(B,A),B=n.mul(L,B),_=n.mul(se,_),H=X(H),L=n.sub(O,H),L=X(L),L=n.add(L,_),_=n.add(O,O),O=n.add(_,O),O=n.add(O,H),O=n.mul(O,L),A=n.add(A,O),H=n.mul(g,m),H=n.add(H,H),O=n.mul(H,L),B=n.sub(B,O),_=n.mul(H,v),_=n.add(_,_),_=n.add(_,_),new C(B,A,_)}add(l){Ue(l);let{X:g,Y:m,Z:B}=this,{X:A,Y:_,Z:O}=l,{ZERO:v,ZERO:H,ZERO:L}=n,W=n.mul(g,A),P=n.mul(m,_),Z=n.mul(B,O),te=n.add(g,m),M=n.add(A,_);te=n.mul(te,M),M=n.add(W,P),te=n.sub(te,M),M=n.add(g,B);let Y=n.add(A,O);return M=n.mul(M,Y),Y=n.add(W,Z),M=n.sub(M,Y),Y=n.add(m,B),v=n.add(_,O),Y=n.mul(Y,v),v=n.add(P,Z),Y=n.sub(Y,v),L=X(M),v=n.mul(se,Z),L=n.add(v,L),v=n.sub(P,L),L=n.add(P,L),H=n.mul(v,L),P=n.add(W,W),P=n.add(P,W),Z=X(Z),M=n.mul(se,M),P=n.add(P,Z),Z=n.sub(W,Z),Z=X(Z),M=n.add(M,Z),W=n.mul(P,M),H=n.add(H,W),W=n.mul(Y,M),v=n.mul(te,v),v=n.sub(v,W),W=n.mul(te,P),L=n.mul(Y,L),L=n.add(L,W),new C(v,H,L)}subtract(l){return Ue(l),this.add(l.negate())}is0(){return this.equals(C.ZERO)}multiply(l){if(!s.isValidNot0(l))throw RangeError("invalid scalar: out of range");let{p:g,f:m}=we.mulSecret(this,l,i,ot);return ot([g,m])[0]}multiplyUnsafe(l){let g=this,m=l;if(!s.isValid(m))throw RangeError("invalid scalar: out of range");if(m===pe||g.is0())return C.ZERO;if(m===De)return g;if(we.hasWindowSize(this))return we.mulUnsafe(g,m,ot);let B=[],A=[];return Te(B,A,g,m),St(C,B,A)}mulAddUnsafe(l,g,m){Ue(g);let B=[],A=[];return Te(B,A,this,l),Te(B,A,g,m),St(C,B,A)}toAffine(l){let g=this,m=l;if(m!=null&&!n.isValid(m))throw RangeError('"invertedZ" expected valid field element');let{X:B,Y:A,Z:_}=g;if(n.eql(_,n.ONE))return{x:B,y:A};let O=g.is0();if(m==null)m=O?n.ONE:n.inv(_);let v=n.mul(B,m),H=n.mul(A,m),L=n.mul(_,m);if(O)return{x:n.ZERO,y:n.ZERO};if(!n.eql(L,n.ONE))throw Error("invZ was invalid");return{x:v,y:H}}isTorsionFree(){if(i===De)return!0;if(b)return b(C,this);return we.mulUnsafe(this,c).is0()}clearCofactor(){if(i===De)return this;if(p)return p(C,this);return this.multiplyUnsafe(i)}isSmallOrder(){if(i===De)return this.is0();return this.clearCofactor().is0()}toBytes(l=!0){return ae(l,"isCompressed"),this.assertValidity(),G(C,this,l)}toHex(l=!0){return Ut(this.toBytes(l))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ot=(l)=>Wn(C,l),we=new Qt(C,R);if(we.bits>=6)C.BASE.precompute(6);return Object.freeze(C.prototype),Object.freeze(C),C}function tr(e){return Uint8Array.of(e?2:3)}function nr(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ds(e,t={}){Ve(e);let{Fn:r}=e,n=t.randomBytes===void 0?wt:t.randomBytes,s=Object.assign(nr(e.Fp,r),{seed:Math.max(At(r.ORDER),16)});function o(x){try{let R=r.fromBytes(x);return r.isValidNot0(R)}catch(R){return!1}}function i(x,R){let{publicKey:D,publicKeyUncompressed:k}=s;try{let N=x.length;if(R===!0&&N!==D)return!1;if(R===!1&&N!==k)return!1;return!e.fromBytes(x).is0()}catch(N){return!1}}function c(x){return x=x===void 0?n(s.seed):x,_t(K(x,s.seed,"seed"),r.ORDER)}function a(x,R=!0){return e.BASE.multiply(r.fromBytes(x)).toBytes(R)}function d(x){let{secretKey:R,publicKey:D,publicKeyUncompressed:k}=s,N=r._lengths;if(!qe(x))return;let T=K(x,void 0,"key").length,Q=T===D||T===k,G=T===R||!!N?.includes(T);if(Q&&G)return;return Q}function p(x,R,D=!0){if(d(x)===!0)throw Error("first arg must be private key");if(d(R)===!1)throw Error("second arg must be public key");let k=r.fromBytes(x),N=e.fromBytes(R);if(N.is0())throw Error("invalid public key: point at infinity");return N.multiply(k).toBytes(D)}let b={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:c},w=Vn(c,a);return Object.freeze(b),Object.freeze(s),Object.freeze({getPublicKey:a,getSharedSecret:p,keygen:w,Point:e,utils:b,lengths:s})}function rr(e,t,r={}){Ve(e);let n=t;he(n),_e(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=Object.assign({},r),o=s.randomBytes===void 0?wt:s.randomBytes,i=s.hmac===void 0?(l,g)=>Xn(n,l,g):s.hmac,{Fp:c,Fn:a}=e,{ORDER:d,BITS:p}=a,b=At(d),w=Jt(o,b),{keygen:x,getPublicKey:R,getSharedSecret:D,utils:k,lengths:N}=ds(e,s),T={prehash:!0,lowS:typeof s.lowS==="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},Q=d*Qn+De<c.ORDER;function G(l){let g=d>>De;return l>g}function fe(l,g){if(!a.isValidNot0(g))throw Error(`invalid signature ${l}: out of range 1..Point.Fn.ORDER`);return g}function se(){if(!c.isOdd)throw Error("Field doesn't support isOdd")}function X(l,g,m){return se(),(l===m?0:2)|Number(c.isOdd(g))}function st(){if(Q)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function Ce(l,g){rn(g);let m=N.signature,B=g==="compact"?m:g==="recovered"?m+1:void 0;return K(l,B)}class ee{r;s;recovery;constructor(l,g,m){if(this.r=fe("r",l),this.s=fe("s",g),m!=null){if(st(),![0,1,2,3].includes(m))throw Error("invalid recovery id");this.recovery=m}Object.freeze(this)}static fromBytes(l,g=T.format){Ce(l,g);let m;if(g==="der"){if(l.length>2*a.BYTES+16)throw new kt.Err("invalid signature: DER signature too long");let{r:O,s:v}=kt.toSig(K(l),a.BYTES+1);return new ee(O,v)}if(g==="recovered")m=l[0],g="compact",l=l.subarray(1);let B=N.signature/2,A=l.subarray(0,B),_=l.subarray(B,B*2);return new ee(a.fromBytes(A),a.fromBytes(_),m)}static fromHex(l,g){return this.fromBytes(xt(l),g)}assertRecovery(){let{recovery:l}=this;if(l==null)throw Error("invalid recovery id: must be present");return l}addRecoveryBit(l){return new ee(this.r,this.s,l)}recoverPublicKey(l){let{r:g,s:m}=this,B=this.assertRecovery(),A=B===2||B===3?g+d:g;if(!c.isValid(A))throw Error("invalid recovery id: sig.r+curve.n != R.x");let _=c.toBytes(A),O=e.fromBytes(ue(tr((B&1)===0),_)),v=a.inv(A),H=Re(K(l,void 0,"msgHash")),L=a.create(-H*v),W=a.create(m*v),P=e.BASE.mulAddUnsafe(L,O,W);if(P.is0())throw Error("invalid recovery: point at infinify");return P.assertValidity(),P}hasHighS(){return G(this.s)}toBytes(l=T.format){if(rn(l),l==="der")return xt(kt.hexFromSig(this));let{r:g,s:m}=this,B=a.toBytes(g),A=a.toBytes(m);if(l==="recovered")return st(),ue(Uint8Array.of(this.assertRecovery()),B,A);return ue(B,A)}toHex(l){return Ut(this.toBytes(l))}}Object.freeze(ee.prototype),Object.freeze(ee);let pt=s.bits2int===void 0?function(g){if(g.length>8192)throw Error("input is too large");let m=ce(g),B=g.length*8-p;return B>0?m>>BigInt(B):m}:s.bits2int,Re=s.bits2int_modN===void 0?function(g){return a.create(pt(g))}:s.bits2int_modN,Ue=ct(p);function gt(l){return Mt("num < 2^"+p,l,pe,Ue),a.toBytes(l)}function Te(l,g){return K(l,void 0,"message"),g?K(n(l),void 0,"prehashed message"):l}function mt(l,g,m){let{lowS:B,prehash:A,extraEntropy:_}=tn(m,T);l=Te(l,A);let O=Re(l),v=a.fromBytes(g);if(!a.isValidNot0(v))throw Error("invalid private key");let H=[gt(v),gt(O)];if(_!=null&&_!==!1){let Z=_===!0?o(N.secretKey):_;H.push(K(Z,void 0,"extraEntropy"))}let L=ue(...H),W=O;function P(Z){let te=pt(Z);if(!a.isValidNot0(te))return;let M=e.BASE.multiply(te).toAffine(),Y=a.create(M.x);if(Y===pe)return;let ie;if(w!==void 0){let it=ce(_t(w(b),d)),Lr=a.inv(a.mul(it,te)),Nr=a.mul(it,W),Cr=a.mul(it,v);ie=a.create(Lr*a.create(Nr+Cr*Y))}else{let it=Cn(te,d);ie=a.create(it*a.create(W+Y*v))}if(ie===pe)return;let Lt=X(M.x,M.y,Y),xn=ie;if(B&&G(ie))xn=a.neg(ie),Lt^=1;return new ee(Y,xn,Q?void 0:Lt)}return{seed:L,k2sig:P}}function C(l,g,m={}){let{seed:B,k2sig:A}=mt(l,g,m);return In(n.outputLen,a.BYTES,i)(B,A).toBytes(m.format)}function ot(l,g,m,B={}){let{lowS:A,prehash:_,format:O}=tn(B,T);if(m=K(m,void 0,"publicKey"),g=Te(g,_),!qe(l)){let v=l instanceof ee?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+v)}Ce(l,O);try{let v=ee.fromBytes(l,O),H=e.fromBytes(m);if(H.is0())return!1;if(A&&v.hasHighS())return!1;let{r:L,s:W}=v,P=Re(g),Z=a.inv(W),te=a.create(P*Z),M=a.create(L*Z),Y=e.BASE.mulAddUnsafe(te,H,M);if(Y.is0())return!1;let ie=Y.toAffine();if(a.create(ie.x)!==L)return!1;if(O==="recovered"&&v.recovery!==X(ie.x,ie.y,L))return!1;return!0}catch(v){return!1}}function we(l,g,m={}){let{prehash:B}=tn(m,T);return g=Te(g,B),ee.fromBytes(l,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:x,getPublicKey:R,getSharedSecret:D,utils:k,lengths:N,Point:e,sign:C,verify:ot,recoverPublicKey:we,Signature:ee,hash:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var on={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},fs={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var sr=BigInt(2);function us(e){let t=on.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),c=BigInt(44),a=BigInt(88),d=e*e*e%t,p=d*d*e%t,b=re(p,r,t)*p%t,w=re(b,r,t)*p%t,x=re(w,sr,t)*d%t,R=re(x,s,t)*x%t,D=re(R,o,t)*R%t,k=re(D,c,t)*D%t,N=re(k,a,t)*k%t,T=re(N,c,t)*D%t,Q=re(T,r,t)*p%t,G=re(Q,i,t)*R%t,fe=re(G,n,t)*d%t,se=re(fe,sr,t);if(!sn.eql(sn.sqr(se),e))throw Error("Cannot find square root");return se}var sn=Ke(on.p,{sqrt:us}),ls=er(on,{Fp:sn,endo:fs}),ft=rr(ls,Sn),Ho=Object.create(null);class y extends Error{code;detail;constructor(e,t){super(t?`${e}: ${t}`:e);this.code=e;this.detail=t;this.name="HlRefusal"}}var ir={perp:6,spot:8},hs=/^\d+(\.\d+)?$/;function ut(e,t="value"){if(typeof e!=="string"||!hs.test(e.trim()))throw new y("bad_decimal",`${t}=${String(e)}`);let[r,n=""]=e.trim().split(".");return r=r.replace(/^0+(?=\d)/,""),n=n.replace(/0+$/,""),n?`${r}.${n}`:r}var ye=(e)=>e.includes(".")?e.split(".")[1].length:0,an=(e)=>/^0(\.0*)?$/.test(e),ps=(e)=>!e.includes(".");function or(e){let t=e.replace(".","").replace(/^0+/,"");if(!e.includes("."))return t.replace(/0+$/,"").length||1;return t.length||1}function ar(e,t){let r=ut(e,"size");if(an(r))throw new y("size_zero");if(ye(r)>t)throw new y("size_too_precise",`${r} has ${ye(r)} decimals, max ${t}`);return r}function cn(e,t,r){let n=ut(e,"price");if(an(n))throw new y("price_zero");if(ps(n))return n;if(or(n)>5)throw new y("price_sig_figs",`${n} has ${or(n)} significant figures, max 5`);let s=ir[r]-t;if(ye(n)>s)throw new y("price_too_precise",`${n} has ${ye(n)} decimals, max ${s}`);return n}function Xe(e){let t=ut(e,"amount");if(an(t))throw new y("amount_zero");if(ye(t)>6)throw new y("amount_too_precise",`${t} has ${ye(t)} decimals, max 6`);return t}function cr(e,t,r,n,s){let o=Number(ut(e,"mid"));if(!(o>0))throw new y("price_zero","mid");if(!(r>=0&&r<1))throw new y("bad_slippage",String(r));let i=o*(t?1+r:1-r),c=Number(i.toPrecision(5)),a=Math.max(0,ir[s]-n);return cn(ut(c.toFixed(a),"price"),n,s)}var dr={mainnet:"https://api.hyperliquid.xyz/info",testnet:"https://api.hyperliquid-testnet.xyz/info"};var Je=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),gs=1e4,dn=110000;function ms(e,t){let r=new Map,n=new Map,s=(d,...p)=>{n.set(d.asset,d);for(let b of p)if(!r.has(b))r.set(b,d)},o=Je(e)?e:{};(Array.isArray(o.universe)?o.universe:[]).forEach((d,p)=>{if(!Je(d)||typeof d.name!=="string"||typeof d.szDecimals!=="number")return;s({coin:d.name,label:d.name,asset:p,szDecimals:d.szDecimals,kind:"perp",delisted:d.isDelisted===!0},d.name)});let c=Je(t)?t:{},a=new Map;for(let d of Array.isArray(c.tokens)?c.tokens:[])if(Je(d)&&typeof d.index==="number")a.set(d.index,d);for(let d of Array.isArray(c.universe)?c.universe:[]){if(!Je(d)||typeof d.index!=="number"||typeof d.name!=="string"||!Array.isArray(d.tokens))continue;let[p,b]=d.tokens,w=a.get(p),x=a.get(b);if(!w||typeof w.szDecimals!=="number")continue;let R=`${String(w.name)}/${String(x?.name??"?")}`;s({coin:d.name,label:R,asset:gs+d.index,szDecimals:w.szDecimals,kind:"spot",delisted:!1},d.name,R)}return{byName:r,byIndex:n}}function fn(e,t){let r=e.byName.get(t);if(!r)throw new y("unknown_asset",t);if(r.delisted)throw new y("asset_delisted",t);return r}function un(e,t){if(t>=dn)throw new y("builder_dex_unsupported",String(t));let r=e.byIndex.get(t);if(!r)throw new y("unknown_asset",String(t));return r}async function xe(e,t,r={}){let n=r.fetchImpl??fetch;try{let s=await n(dr[t],{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(r.timeoutMs??5000)});if(!s.ok)return{ok:!1,error:"hyperliquid_unavailable",detail:`status_${s.status}`};return{ok:!0,data:await s.json()}}catch(s){return{ok:!1,error:"hyperliquid_unavailable",detail:s.message}}}async function ln(e,t={}){let[r,n]=await Promise.all([xe({type:"meta"},e,t),xe({type:"spotMeta"},e,t)]);if(!r.ok)return r;if(!n.ok)return n;return{ok:!0,data:ms(r.data,n.data)}}async function fr(e,t={}){let r=await xe({type:"allMids"},e,t);if(!r.ok)return r;let n={};if(Je(r.data)){for(let[s,o]of Object.entries(r.data))if(typeof o==="string"&&/^\d+(\.\d+)?$/.test(o))n[s]=o}return{ok:!0,data:n}}var bs=["Gtc","Ioc","Alo"],ys=/^0x[0-9a-fA-F]{32}$/,xs=/^0x[0-9a-fA-F]{40}$/;function hn(e){let t=e.tif??"Gtc";if(!bs.includes(t))throw new y("bad_tif",String(t));if(e.asset.delisted)throw new y("asset_delisted",e.asset.coin);let r=ar(e.sz,e.asset.szDecimals),n=cn(e.px,e.asset.szDecimals,e.asset.kind);if(e.cloid!==void 0&&!ys.test(e.cloid))throw new y("bad_cloid",e.cloid);let s={a:e.asset.asset,b:e.isBuy,p:n,s:r,r:e.reduceOnly??!1,t:{limit:{tif:t}}};if(e.cloid!==void 0)s.c=e.cloid.toLowerCase();return s}function pn(e){return{type:"order",orders:[hn(e)],grouping:"na"}}function ur(e){let t=cr(e.mid,e.isBuy,e.slippage??0.05,e.asset.szDecimals,e.asset.kind);return pn({asset:e.asset,isBuy:e.isBuy,sz:e.sz,px:t,tif:"Ioc",reduceOnly:e.reduceOnly,cloid:e.cloid})}function Ot(e){let t=e.asset.asset;if(!Number.isSafeInteger(t)||t<0)throw new y("unknown_asset",String(t));if(t>=dn)throw new y("builder_dex_unsupported",String(t));if(!Number.isSafeInteger(e.oid)||e.oid<0)throw new y("bad_oid",String(e.oid));return{type:"cancel",cancels:[{a:t,o:e.oid}]}}function lr(e){if(!Number.isSafeInteger(e)||e<=0)throw new y("nonce_required",String(e));return e}function vt(e){return{type:"usdClassTransfer",amount:Xe(e.amount),toPerp:e.toPerp,nonce:lr(e.nonce)}}function It(e){if(!xs.test(e.destination))throw new y("bad_address",e.destination);return{type:"withdraw3",destination:e.destination.toLowerCase(),amount:Xe(e.amount),time:lr(e.time)}}var ws=BigInt(0),lt=BigInt(1),Es=BigInt(2),Bs=BigInt(7),As=BigInt(256),_s=BigInt(113),gr=[],mr=[],br=[];for(let e=0,t=lt,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],gr.push(2*(5*n+r)),mr.push((e+1)*(e+2)/2%64);let s=ws;for(let o=0;o<7;o++)if(t=(t<<lt^(t>>Bs)*_s)%As,t&Es)s^=lt<<(lt<<BigInt(o))-lt;br.push(s)}var yr=Me(br,!0),Ss=yr[0],ks=yr[1],Os=(e,t,r)=>e<<r|t>>>32-r,vs=(e,t,r)=>t<<r|e>>>32-r,Is=(e,t,r)=>t<<r-32|e>>>64-r,Rs=(e,t,r)=>e<<r-32|t>>>64-r,hr=(e,t,r)=>r>32?Is(e,t,r):Os(e,t,r),pr=(e,t,r)=>r>32?Rs(e,t,r):vs(e,t,r),Qe=new Uint32Array(10);function Ts(e,t=24){if(!(e instanceof Uint32Array))throw TypeError('"s" expected Uint32Array(50), got type='+typeof e);if(e.length!==50)throw RangeError('"s" expected Uint32Array(50), got length='+e.length);if(f(t,"rounds"),t<1||t>24)throw Error('"rounds" expected integer 1..24');for(let r=24-t;r<24;r++){for(let o=0;o<10;o++)Qe[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){let i=(o+8)%10,c=(o+2)%10,a=Qe[c],d=Qe[c+1],p=hr(a,d,1)^Qe[i],b=pr(a,d,1)^Qe[i+1];for(let w=0;w<50;w+=10)e[o+w]^=p,e[o+w+1]^=b}let n=e[2],s=e[3];for(let o=0;o<24;o++){let i=mr[o],c=hr(n,s,i),a=pr(n,s,i),d=gr[o];n=e[d],s=e[d+1],e[d]=c,e[d+1]=a}for(let o=0;o<50;o+=10){let i=e[o],c=e[o+1],a=e[o+2],d=e[o+3];e[o]^=~e[o+2]&e[o+4],e[o+1]^=~e[o+3]&e[o+5],e[o+2]^=~e[o+4]&e[o+6],e[o+3]^=~e[o+5]&e[o+7],e[o+4]^=~e[o+6]&e[o+8],e[o+5]^=~e[o+7]&e[o+9],e[o+6]^=~e[o+8]&i,e[o+7]^=~e[o+9]&c,e[o+8]^=~i&a,e[o+9]^=~c&d}e[0]^=Ss[r],e[1]^=ks[r]}E(Qe)}class gn{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,r,n=!1,s=24){if(f(e,"blockLen"),f(t,"suffix"),f(s,"rounds"),Ge(n,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.canXOF=n,this.rounds=s,f(r,"outputLen"),!(0<e&&e<200))throw Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=z(this.state)}clone(){return this._cloneInto()}keccak(){j(this.state32),Ts(this.state32,this.rounds),j(this.state32),this.posOut=0,this.pos=0}update(e){S(this),u(e);let{blockLen:t,state:r,state32:n}=this,s=e.length,o=t%4===0&&e.byteOffset%4===0,i=t/4,c=o&&s>=t?z(e):void 0;for(let a=0;a<s;){if(c!==void 0&&this.pos===0&&a%4===0&&s-a>=t){for(let p=0,b=a/4;p<i;p++)n[p]^=c[b+p];a+=t,this.pos=t,this.keccak();continue}let d=Math.min(t-this.pos,s-a);for(let p=0;p<d;p++)r[this.pos++]^=e[a++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:n}=this;if(e[r]^=t,(t&128)!==0&&r===n-1)this.keccak();e[n-1]^=128,this.keccak()}writeInto(e){S(this,!1),u(e),this.finish();let t=this.state,{blockLen:r}=this;for(let n=0,s=e.length;n<s;){if(this.posOut>=r)this.keccak();let o=Math.min(r-this.posOut,s-n);e.set(t.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not enabled");return this.writeInto(e)}xof(e){return f(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(F(e,this),this.finished)throw Error("digest() was already called");this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,E(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:n,rounds:s,enableXOF:o}=this;return e||=new gn(t,r,n,o,s),e.blockLen=t,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=n,e.enableXOF=o,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}}var $s=(e,t,r,n={})=>J(()=>new gn(t,e,r),n);var ke=$s(1,136,32);var et=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Oe=(e)=>Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join(""),ve=(e)=>`0x${Oe(e)}`;function Ie(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||!/^[0-9a-fA-F]*$/.test(t))throw new y("bad_hex",e);let r=new Uint8Array(t.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(t.slice(2*n,2*n+2),16);return r}function Rt(e){if(e<0n||e>=1n<<256n)throw new y("eip712_range",String(e));let t=new Uint8Array(32);for(let r=31;r>=0;r--)t[r]=Number(e&0xffn),e>>=8n;return t}function xr(e,t,r){let n;if(typeof e==="bigint")n=e;else if(typeof e==="number"&&Number.isSafeInteger(e))n=BigInt(e);else if(typeof e==="string"&&/^(0x[0-9a-fA-F]+|\d+)$/.test(e))n=BigInt(e);else throw new y("eip712_value",`${r} not a uint`);if(n<0n||n>=1n<<BigInt(t))throw new y("eip712_range",r);return n}function Hs(e,t){switch(e.type){case"string":if(typeof t!=="string")throw new y("eip712_value",`${e.name} not a string`);return ke(new TextEncoder().encode(t));case"bytes32":{let r=t instanceof Uint8Array?t:typeof t==="string"?Ie(t):null;if(!r||r.length!==32)throw new y("eip712_value",`${e.name} not bytes32`);return r}case"address":{if(typeof t!=="string"||!/^0x[0-9a-fA-F]{40}$/.test(t))throw new y("eip712_value",`${e.name} not an address`);return Rt(BigInt(t))}case"bool":if(typeof t!=="boolean")throw new y("eip712_value",`${e.name} not a bool`);return Rt(t?1n:0n);case"uint64":return Rt(xr(t,64,e.name));case"uint256":return Rt(xr(t,256,e.name));default:throw new y("eip712_type",String(e.type))}}var Ds=(e,t)=>`${e}(${t.map((r)=>`${r.type} ${r.name}`).join(",")})`;function wr(e,t,r){let n=[ke(new TextEncoder().encode(Ds(e,t)))];for(let o of t){if(!(o.name in r))throw new y("eip712_missing",o.name);n.push(Hs(o,r[o.name]))}let s=new Uint8Array(n.length*32);return n.forEach((o,i)=>s.set(o,i*32)),ke(s)}function tt(e){let t=e.types[e.primaryType];if(!t)throw new y("eip712_type",e.primaryType);let r=wr("EIP712Domain",et,e.domain),n=wr(e.primaryType,t,e.message),s=new Uint8Array(66);return s[0]=25,s[1]=1,s.set(r,2),s.set(n,34),ke(s)}class ht extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}var Fs=(1n<<64n)-1n,Ls=-(1n<<63n);function nt(e){let t=[];return Tt(t,e,"$"),Uint8Array.from(t)}function oe(e,t,r){for(let n=r-1;n>=0;n--)e.push(Number(t>>BigInt(8*n)&0xffn))}function Er(e,t,r){if(t>Fs||t<Ls)throw new ht("msgpack_int_range",r);if(t>=0n){if(t<=0x7fn)e.push(Number(t));else if(t<=0xffn)e.push(204),oe(e,t,1);else if(t<=0xffffn)e.push(205),oe(e,t,2);else if(t<=0xffffffffn)e.push(206),oe(e,t,4);else e.push(207),oe(e,t,8);return}let n=(s)=>t+(1n<<BigInt(s));if(t>=-32n)e.push(Number(n(8)));else if(t>=-128n)e.push(208),oe(e,n(8),1);else if(t>=-32768n)e.push(209),oe(e,n(16),2);else if(t>=-2147483648n)e.push(210),oe(e,n(32),4);else e.push(211),oe(e,n(64),8)}function mn(e,t,r,n,s){if(t<=n)e.push(r|t);else if(s[0]!==null&&t<=255)e.push(s[0]),oe(e,BigInt(t),1);else if(t<=65535)e.push(s[1]),oe(e,BigInt(t),2);else e.push(s[2]),oe(e,BigInt(t),4)}function Tt(e,t,r){if(t===null){e.push(192);return}if(t===void 0)throw new ht("msgpack_undefined",r);if(typeof t==="boolean"){e.push(t?195:194);return}if(typeof t==="bigint"){Er(e,t,r);return}if(typeof t==="number"){if(!Number.isSafeInteger(t))throw new ht("msgpack_float",`${r}=${t}`);Er(e,BigInt(t),r);return}if(typeof t==="string"){let n=new TextEncoder().encode(t);mn(e,n.length,160,31,[217,218,219]);for(let s of n)e.push(s);return}if(Array.isArray(t)){mn(e,t.length,144,15,[null,220,221]),t.forEach((n,s)=>Tt(e,n,`${r}[${s}]`));return}if(typeof t==="object"&&Object.getPrototypeOf(t)===Object.prototype){let n=Object.keys(t);mn(e,n.length,128,15,[null,222,223]);for(let s of n)Tt(e,s,r),Tt(e,t[s],`${r}.${s}`);return}throw new ht("msgpack_type",`${r}: ${typeof t}`)}var $t={mainnet:"https://api.hyperliquid.xyz/exchange",testnet:"https://api.hyperliquid-testnet.xyz/exchange"},bn="0x66eee",_r="0x0000000000000000000000000000000000000000",Sr=/^0x[0-9a-fA-F]{40}$/;function Br(e){let t=BigInt(e);if(t<0n||t>=1n<<64n)throw new y("eip712_range",String(e));let r=new Uint8Array(8);for(let n=7;n>=0;n--)r[n]=Number(t&0xffn),t>>=8n;return r}function Ns(e,t,r,n){let s=[nt(e),Br(r)];if(t===null)s.push(Uint8Array.of(0));else s.push(Uint8Array.of(1),Ie(t));if(n!==null)s.push(Uint8Array.of(0),Br(n));let o=new Uint8Array(s.reduce((c,a)=>c+a.length,0)),i=0;for(let c of s)o.set(c,i),i+=c.length;return o}var Cs={name:"Exchange",version:"1",chainId:1337,verifyingContract:_r},Us=[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}];function qs(e,t){return{domain:Cs,types:{Agent:Us,EIP712Domain:et},primaryType:"Agent",message:{source:t==="mainnet"?"a":"b",connectionId:ve(e)}}}var Ps={usdClassTransfer:{primaryType:"HyperliquidTransaction:UsdClassTransfer",fields:[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}],nonceField:"nonce"},withdraw3:{primaryType:"HyperliquidTransaction:Withdraw",fields:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}],nonceField:"time"}};function js(e,t,r,n,s=bn){if(!/^0x[0-9a-fA-F]+$/.test(s))throw new y("bad_hex",s);let o={...r,hyperliquidChain:n==="mainnet"?"Mainnet":"Testnet"},i={};for(let c of t){if(!(c.name in o))throw new y("eip712_missing",c.name);i[c.name]=o[c.name]}return{domain:{name:"HyperliquidSignTransaction",version:"1",chainId:Number(BigInt(s)),verifyingContract:_r},types:{[e]:t,EIP712Domain:et},primaryType:e,message:i}}var kr=(e,t)=>Oe(nt(e))===Oe(nt(t));function Ms(e,t){let r=un(t,e.a),n=e.t?.limit?.tif;return hn({asset:r,isBuy:e.b,sz:e.s,px:e.p,tif:n,reduceOnly:e.r,cloid:e.c})}var zs=(e,t)=>{let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.join()===n.join()&&r.every((s)=>kr(e[s],t[s]))};function Ar(e,t){let{hyperliquidChain:r,signatureChainId:n,...s}=e,o=t.net==="mainnet"?"Mainnet":"Testnet";if(r!==void 0&&r!==o)throw new y("unsupported_action",`hyperliquidChain ${String(r)} on ${t.net}`);let i=(t.signatureChainId??bn).toLowerCase();if(n!==void 0&&String(n).toLowerCase()!==i)throw new y("unsupported_action",`signatureChainId ${String(n)} ≠ ${i}`);return s}function Ws(e,t){let r=t.assets;if(!e||typeof e!=="object")throw new y("unsupported_action","not an object");let n,s=e;switch(e.type){case"order":{if(!r)throw new y("meta_required","an order is checked against meta + spotMeta before it is signed");let i=Array.isArray(e.orders)?e.orders:[];if(i.length===0)throw new y("unsupported_action","order with no orders");n={type:"order",orders:i.map((c)=>Ms(c,r)),grouping:"na"};break}case"cancel":{let i=e.cancels??[];if(i.length===0)throw new y("unsupported_action","cancel with no cancels");n={type:"cancel",cancels:i.map((c)=>Ot({asset:r?un(r,c.a):{asset:c.a},oid:c.o}).cancels[0])};break}case"usdClassTransfer":{s=Ar(e,t);let i=s;if(typeof i.toPerp!=="boolean")throw new y("unsupported_action","toPerp");n=vt({amount:i.amount,toPerp:i.toPerp,nonce:i.nonce});break}case"withdraw3":{s=Ar(e,t);let i=s;n=It({destination:i.destination,amount:i.amount,time:i.time});break}default:throw new y("unsupported_action",String(e.type))}if(!(n.type==="order"||n.type==="cancel"?kr(n,s):zs(n,s)))throw new y("unsupported_action","action is not in canonical form");return n}function Ht(e,t){let r=Ws(e,t);if(r.type==="order"||r.type==="cancel"){if(t.nonce===void 0||!Number.isSafeInteger(t.nonce)||t.nonce<0)throw new y("nonce_required");if(t.vaultAddress!==void 0&&!Sr.test(t.vaultAddress))throw new y("bad_address",t.vaultAddress);if(t.expiresAfter!==void 0&&(!Number.isSafeInteger(t.expiresAfter)||t.expiresAfter<=0))throw new y("expires_unsupported",String(t.expiresAfter));let a=t.vaultAddress?.toLowerCase()??null,d=t.expiresAfter??null,p=Ns(r,a,t.nonce,d),b=ke(p),w=qs(b,t.net);return{kind:"l1",network:t.net,action:r,nonce:t.nonce,vaultAddress:a,expiresAfter:d,msgpackHex:Oe(nt(r)),hashInputHex:Oe(p),connectionId:ve(b),typedData:w,digest:ve(tt(w)),exchangeUrl:$t[t.net],posted:!1}}if(t.vaultAddress!==void 0)throw new y("vault_unsupported",r.type);if(t.expiresAfter!==void 0)throw new y("expires_unsupported",r.type);let n=Ps[r.type],s=r[n.nonceField];if(t.nonce!==void 0&&t.nonce!==s)throw new y("nonce_mismatch",`${t.nonce} ≠ ${s}`);let o=t.signatureChainId??bn,i={type:r.type,signatureChainId:o,hyperliquidChain:t.net==="mainnet"?"Mainnet":"Testnet",...Object.fromEntries(Object.entries(r).filter(([a])=>a!=="type"))},c=js(n.primaryType,n.fields,i,t.net,o);return{kind:"user",network:t.net,action:i,nonce:s,vaultAddress:null,expiresAfter:null,msgpackHex:null,hashInputHex:null,connectionId:null,typedData:c,digest:ve(tt(c)),exchangeUrl:$t[t.net],posted:!1}}function Zs(e){let t=Ie(e);if(t.length!==65)throw new y("bad_signature",`length ${t.length}`);let r=t[64]<27?t[64]+27:t[64];if(r!==27&&r!==28)throw new y("bad_signature",`v=${t[64]}`);return{r:ve(t.slice(0,32)),s:ve(t.slice(32,64)),v:r}}function Ys(e,t){let r=typeof e==="string"?Ie(e):e,n=(c)=>BigInt(c).toString(16).padStart(64,"0");if(t.v!==27&&t.v!==28)throw new y("bad_signature",`v=${t.v}`);let s=Ie(`${(t.v-27).toString(16).padStart(2,"0")}${n(t.r)}${n(t.s)}`),o=ft.recoverPublicKey(s,r,{prehash:!1}),i=ft.Point.fromBytes(o).toBytes(!1);return ve(ke(i.slice(1)).slice(12))}async function Or(e,t,r,n={}){let s=Ht(e,t);if(n.expectDigest!==void 0&&n.expectDigest.toLowerCase()!==s.digest)throw new y("signer_mismatch","the digest shown is not the digest being signed");if(!Sr.test(r.address))throw new y("bad_address",r.address);let{EIP712Domain:o,...i}=s.typedData.types,c=await r.signTypedData(s.typedData.domain,i,s.typedData.message),a=Zs(c),d=Ys(s.digest,a);if(d!==r.address.toLowerCase())throw new y("signer_mismatch",`recovered ${d}, expected ${r.address}`);return{dry:s,request:{action:s.action,nonce:s.nonce,signature:a,vaultAddress:s.vaultAddress,expiresAfter:s.expiresAfter}}}var Dt=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Ks(e){if(!Dt(e))return{ok:!1,error:"exchange_unavailable",detail:"not json"};if(e.status!=="ok")return{ok:!1,error:"exchange_refused",detail:typeof e.response==="string"?e.response:"err",response:e.response};let t=e.response,n=(Dt(t)&&Dt(t.data)&&Array.isArray(t.data.statuses)?t.data.statuses:[]).find((s)=>Dt(s)&&typeof s.error==="string");if(n)return{ok:!1,error:"exchange_refused",detail:String(n.error),response:t};return{ok:!0,response:t}}async function vr(e,t,r={}){let n=r.fetchImpl??fetch;try{let s=await n($t[t],{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(r.timeoutMs??1e4)}),o=await s.text(),i;try{i=JSON.parse(o)}catch{return{ok:!1,error:"exchange_unavailable",detail:`status_${s.status}: ${o.slice(0,200)}`}}return Ks(i)}catch(s){return{ok:!1,error:"exchange_unavailable",detail:s.message}}}var yn=/^0x[0-9a-fA-F]{40}$/,Ne=(e)=>e.testnet?"testnet":"mainnet";function q(e,t,r={}){return{data:{ok:!1,error:e,detail:t,...r}}}class Fr extends Error{code;constructor(e,t){super(t);this.code=e}}function Le(e,t={}){if(e instanceof y)return q(e.code,e.detail??e.message,t);let r=e?.code;return q(typeof r==="string"?r:"hl_error",e?.message??String(e),t)}function Js(e,t){let r=ye(e),n=ye(t),s=(BigInt(e.replace(".",""))*BigInt(t.replace(".",""))).toString().padStart(r+n+1,"0"),o=s.length-(r+n),i=s.slice(o).replace(/0+$/,"");return i?`${s.slice(0,o)}.${i}`:s.slice(0,o)}function Qs(e){let t=Ie(e.privateKeyHex);return{address:e.address,async signTypedData(r,n,s){let o=Object.keys(n);if(o.length!==1)throw new y("eip712_type",`expected one primary type, got ${o.length}`);let i=tt({domain:r,types:{...n,EIP712Domain:et},primaryType:o[0],message:s}),c=ft.sign(i,t,{prehash:!1,format:"recovered"}),a=new Uint8Array(65);return a.set(c.slice(1,65),0),a[64]=c[0]+27,`0x${Oe(a)}`}}}var de=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),rt=(e)=>typeof e==="string"&&/^-?\d+(\.\d+)?$/.test(e)?e:null;async function Ir(e,t,r){let[n,s]=await Promise.all([xe({type:"clearinghouseState",user:e},t,{fetchImpl:r.fetchImpl}),xe({type:"spotClearinghouseState",user:e},t,{fetchImpl:r.fetchImpl})]);if(!n.ok||!s.ok)return null;let o=de(n.data)?n.data:{},i=de(o.marginSummary)?o.marginSummary:{},c=de(s.data)&&Array.isArray(s.data.balances)?s.data.balances:[];return{perps:{accountValue:rt(i.accountValue),withdrawable:rt(o.withdrawable)},spot:c.filter(de).map((a)=>({coin:String(a.coin??"?"),total:String(a.total??"?"),hold:String(a.hold??"?")}))}}function Rr(e,t){if(!t)return[`${e} not read — Hyperliquid did not answer (never shown as 0)`];let r=t.spot.length?t.spot.map((n)=>`${n.total} ${n.coin}${n.hold!=="0"&&n.hold!=="0.0"?` (${n.hold} held)`:""}`).join(" · "):"empty";return[`${e} perps ${t.perps.accountValue??"—"} USDC (withdrawable ${t.perps.withdrawable??"—"}) · spot ${r} — never summed`]}async function Ft(e,t,r){let n=e?.trim();if(n)return yn.test(n)?{ok:!0,address:n}:q("bad_address","A Hyperliquid account is a 0x address of 40 hex characters.");let s=await r.ask("wallet:get",{});if(typeof s.error==="string"||s.ok===!1)return q(String(s.error??"wallet_read_failed"),"Could not read your workspace wallet — pass an address.");let i=(Array.isArray(s.addresses)?s.addresses:[]).filter((a)=>a.chain==="evm"&&typeof a.address==="string"&&yn.test(a.address)&&(!t||a.actor===t)),c=[...new Map(i.map((a)=>[a.address.toLowerCase(),a])).values()];if(c.length===0)return q("no_evm_address","Your workspace has no EVM address registered — pass one.");if(c.length>1)return q("ambiguous_address",`Several EVM addresses — pass one, or --actor <id>: ${c.map((a)=>`${a.actor??"?"} ${a.address}`).join(" · ")}`);return{ok:!0,address:c[0].address}}async function Bi(e,t){let r=Ne(e),n=await Ft(e.address,e.actor,t);if(!(("ok"in n)&&n.ok===!0))return n;let s=await xe({type:"clearinghouseState",user:n.address},r,{fetchImpl:t.fetchImpl});if(!s.ok)return q(s.error,s.detail,{network:r});let o=de(s.data)?s.data:{},i=de(o.marginSummary)?o.marginSummary:{},c=(Array.isArray(o.assetPositions)?o.assetPositions:[]).map((a)=>de(a)&&de(a.position)?a.position:null).filter((a)=>a!==null).map((a)=>({coin:String(a.coin??"?"),size:String(a.szi??"?"),entryPx:a.entryPx??null,positionValue:a.positionValue??null,unrealizedPnl:a.unrealizedPnl??null,liquidationPx:a.liquidationPx??null,leverage:de(a.leverage)?a.leverage:null}));return t.say([`${n.address} on ${r} — perps account ${rt(i.accountValue)??"—"} USDC, withdrawable ${rt(o.withdrawable)??"—"}`,...c.length?c.map((a)=>` ${a.coin.padEnd(8)} ${a.size.startsWith("-")?"short":"long "} ${a.size.replace(/^-/,"")} @ ${String(a.entryPx??"—")} value ${String(a.positionValue??"—")} pnl ${String(a.unrealizedPnl??"—")} liq ${String(a.liquidationPx??"—")}`):[" no open perps positions (spot holdings: one hl balance)"]]),{data:{ok:!0,network:r,address:n.address,accountValue:rt(i.accountValue),withdrawable:rt(o.withdrawable),positions:c}}}async function Ai(e,t){let r=Ne(e),n=await Ft(e.address,e.actor,t);if(!(("ok"in n)&&n.ok===!0))return n;let s=await xe({type:"openOrders",user:n.address},r,{fetchImpl:t.fetchImpl});if(!s.ok)return q(s.error,s.detail,{network:r});if(!Array.isArray(s.data))return q("hyperliquid_unavailable","openOrders did not answer a list",{network:r});let o=s.data.filter(de).map((i)=>({coin:String(i.coin??"?"),side:i.side==="B"?"buy":i.side==="A"?"sell":String(i.side??"?"),size:String(i.sz??"?"),limitPx:String(i.limitPx??"?"),oid:i.oid??null,timestamp:i.timestamp??null}));return t.say([`${n.address} on ${r} — ${o.length} resting order${o.length===1?"":"s"}`,...o.map((i)=>` ${i.side.padEnd(4)} ${i.size} ${i.coin} @ ${i.limitPx} oid ${String(i.oid)} cancel: one hl cancel ${i.coin} ${String(i.oid)}${r==="testnet"?" --testnet":""}`)]),{data:{ok:!0,network:r,address:n.address,count:o.length,orders:o}}}var eo="Hyperliquid takes its own trading fee on a fill (maker or taker, by your fee tier); ONE computes none and takes none.";async function _i(e,t){let r=Ne(e),n=e.side.toLowerCase();if(n!=="buy"&&n!=="sell")return q("bad_side","The side is buy or sell.");if(e.tif!==void 0&&e.limit===void 0&&e.tif!=="Ioc")return q("bad_tif","A market order is IOC by construction — --tif needs --limit.");let s=0.05;if(e.slippage!==void 0){if(!/^\d{1,4}$/.test(e.slippage)||Number(e.slippage)<1||Number(e.slippage)>2000)return q("bad_slippage","--slippage is basis points, 1–2000 (default 500 = 5%, the python SDK default).");s=Number(e.slippage)/1e4}let o=await ln(r,{fetchImpl:t.fetchImpl});if(!o.ok)return q(o.error,o.detail,{network:r});let i;try{i=fn(o.data,e.coin)}catch(b){return Le(b,{network:r,next:"A perp is its name (BTC, ETH, HYPE); a spot pair is BASE/QUOTE (HYPE/USDC, UBTC/USDC) or its @index."})}let c=null;if(e.limit===void 0){let b=await fr(r,{fetchImpl:t.fetchImpl});if(!b.ok)return q(b.error,b.detail,{network:r});if(c=b.data[i.coin]??null,c===null)return q("mid_unavailable",`allMids has no price for ${i.coin} (${i.label}) — a market order needs one; pass --limit <px>.`,{network:r})}let a=n==="buy",d=e.reduceOnly===!0,p=[e.limit!==void 0?`--limit ${e.limit}`:"",e.tif?`--tif ${e.tif}`:"",d?"--reduce-only":"",e.slippage?`--slippage ${e.slippage}`:""].filter(Boolean).join(" ");return{cmdline:`one hl order ${n} ${e.size} ${e.coin}${p?` ${p}`:""}`,build(b){let w=e.limit!==void 0?pn({asset:i,isBuy:a,sz:e.size,px:e.limit,tif:e.tif??"Gtc",reduceOnly:d}):ur({asset:i,isBuy:a,sz:e.size,mid:c,slippage:s,reduceOnly:d}),x=w.orders[0],R=i.kind==="spot"?"spot":"perps",D=Js(x.s,x.p),k=x.t.limit.tif,N=e.limit===void 0?`now, at ${a?"up to":"no less than"} ${x.p} (mid ${c} ${a?"+":"−"} ${s*100}%) — IOC: fills what it can at that cap, cancels the rest`:k==="Gtc"?`at ${x.p} or better — Gtc: rests on the book until filled or cancelled`:k==="Ioc"?`at ${x.p} or better — IOC: fills what it can now, cancels the rest`:`at ${x.p} — Alo (post-only): refused if it would take liquidity`,T=[`${a?"Buy":"Sell"} ${x.s} ${i.label} (${R}, asset ${x.a}) ${N}.`,`${a?"At most":"About"} ${D} USDC notional before fees.`,i.kind==="spot"?a?"Pays USDC from your SPOT balance.":`Sells ${i.label.split("/")[0]} you hold in SPOT for USDC.`:`${d?"Reduce-only: it can only shrink a position you already hold.":"Opens or adds to a perps position; margin comes from your PERPS balance — spot USDC backs it only if the account is in unified mode (move it first: one hl transfer <amount> --to perps)."}`,eo];return{action:w,opts:{net:r,nonce:b,assets:o.data},words:T,facts:{coin:i.coin,label:i.label,kind:i.kind,asset:x.a,side:n,size:x.s,price:x.p,tif:k,reduceOnly:d,notionalUsdc:D,...c?{mid:c,slippageBps:Math.round(s*1e4)}:{}}}}}}async function Si(e,t){let r=Ne(e);if(!/^\d{1,16}$/.test(e.oid)||!Number.isSafeInteger(Number(e.oid)))return q("bad_oid","The order id is the whole number `one hl orders` prints.");let n=await ln(r,{fetchImpl:t.fetchImpl});if(!n.ok)return q(n.error,n.detail,{network:r});let s;try{s=fn(n.data,e.coin)}catch(i){return Le(i,{network:r})}let o=Number(e.oid);return{cmdline:`one hl cancel ${e.coin} ${e.oid}`,build(i){return{action:Ot({asset:s,oid:o}),opts:{net:r,nonce:i,assets:n.data},words:[`Cancel resting order ${o} on ${s.label} (asset ${s.asset}). Nothing is bought or sold; an order already filled cannot be cancelled and Hyperliquid will say so.`],facts:{coin:s.coin,label:s.label,asset:s.asset,oid:o}}}}}async function ki(e,t){let r=Ne(e),n=(e.to??"").toLowerCase();if(n!=="perps"&&n!=="spot")return q("bad_to","--to perps (spot → perps) or --to spot (perps → spot).");let s=n==="perps";try{Xe(e.amount)}catch(o){return Le(o,{network:r})}return{cmdline:`one hl transfer ${e.amount} --to ${n}`,build(o){let i=vt({amount:e.amount,toPerp:s,nonce:o});return{action:i,opts:{net:r},words:[`Move ${i.amount} USDC from ${s?"SPOT to PERPS":"PERPS to SPOT"} on the same Hyperliquid account. Nothing leaves Hyperliquid; ONE takes nothing.`,s?"Perps USDC can margin a position and is what `one hl withdraw` sends out.":"Spot USDC can buy spot pairs; it no longer margins perps positions.","Whether the account needs this depends on its mode — read the `abstraction` line."],facts:{amount:i.amount,toPerp:s}}}}}async function Oi(e,t,r){let n=Ne(e);if(e.to!==void 0&&!yn.test(e.to))return q("bad_address","--to is an Arbitrum 0x address of 40 hex characters.");try{Xe(e.amount)}catch(o){return Le(o,{network:n})}let s=null;if(!e.live&&e.to===void 0){let o=await Ft(e.address,e.actor,t);if(!(("ok"in o)&&o.ok===!0))return{data:{...o.data,next:"Name the destination: --to 0x… (a live withdraw defaults to the vault's own address)"}};s=o.address}return{cmdline:`one hl withdraw ${e.amount}${e.to?` --to ${e.to}`:""}`,build(o,i){let c=i??s,a=e.to??c;if(!a)throw new y("bad_address","no destination");let d=c===null||a.toLowerCase()!==c.toLowerCase();if(r&&i!==null&&d)throw new Fr("to_other_refused",`An agent withdraws only to its own address (${i}); ${a} is another. A person signs that one.`);let p=It({destination:a,amount:e.amount,time:o});return{action:p,opts:{net:n},words:[`Send ${p.amount} USDC from the PERPS balance${c?` of ${c}`:""} to ${a} on Arbitrum.${d?" THIS IS SOMEONE ELSE'S ADDRESS (toOther) — a withdrawal cannot be undone.":" That is the same key on Arbitrum — your own address."}`,"Hyperliquid documents a 1 USDC withdrawal fee (unverified here): what lands is in its answer and the Arbitrum receipt, not computed by ONE.","Withdrawals leave from PERPS on a split account (move spot USDC first: one hl transfer <amount> --to perps); a unified account may withdraw from its one balance — unverified, the exchange's answer is the record.","ONE's Arbitrum signer is external: ONE cannot send it on from Arbitrum. Open that address in MetaMask or Rabby (same key)."],facts:{amount:p.amount,destination:p.destination,toOther:d}}}}}function to(e,t){let r=e.dir??".",n=h(t.env);if(n){let s=t.realpath(r),o=t.realpath(Xs(t.home,".one","agents"));if(!(s!==null&&o!==null&&s.startsWith(o+Gs)))return q("agent_shell",`This shell is driven by ${n}. A live Hyperliquid action here may sign only with the agent's OWN vault (a folder under ~/.one/agents/), and ${r} is not one. Run it yourself in a terminal no agent drives.`);if(!e.yes)return q("agent_shell_needs_yes",`This shell is driven by ${n}. Signing with the agent's own vault (${r}) needs --yes — no one is here to answer a prompt.`);return null}if(!t.interactive&&!e.yes)return q("confirm_required","Not at a terminal (or --json), so no one can answer [y/N] — pass --yes to sign without the prompt.");return null}function Tr(e){return[`action ${JSON.stringify(e.action)}`,`typed data ${JSON.stringify(e.typedData)}`,`digest ${e.digest}`,...e.connectionId?[`connectionId ${e.connectionId}`,`msgpack ${e.msgpackHex}`]:[],`nonce ${e.nonce}${e.vaultAddress?` vault ${e.vaultAddress}`:""}`,`posts to ${e.exchangeUrl} (from this machine, never through ONE)`]}function $r(e){return{kind:e.kind,action:e.action,typedData:e.typedData,digest:e.digest,connectionId:e.connectionId,msgpackHex:e.msgpackHex,nonce:e.nonce,exchangeUrl:e.exchangeUrl}}function Hr(e){if(typeof e!=="string")return"abstraction not read — whether this account is unified is unknown";if(/unified|portfolio/i.test(e))return`abstraction ${JSON.stringify(e)} — spot USDC already backs perps on this account, so Hyperliquid may REFUSE this transfer or not need it (unverified: its answer is the record)`;return`abstraction ${JSON.stringify(e)} — spot and perps are separate balances; the transfer is how USDC moves between them`}async function Dr(e,t,r){if(!e)return null;let n=await xe({type:"userAbstraction",user:e},t,{fetchImpl:r.fetchImpl});return n.ok?n.data:null}async function vi(e,t,r,n,s={}){let o=Ne(t),i=t.live?to(t,n):null;if(i)return{data:{network:o,...i.data}};let c=await r();if("data"in c)return{data:{network:o,...c.data}};if(!t.live){let T,Q;try{T=c.build(n.now(),null),Q=Ht(T.action,T.opts)}catch(X){return Le(X,{network:o})}let G=s.abstractionFor??null;if(e==="transfer"&&!G){let X=await Ft(void 0,void 0,n);if("ok"in X&&X.ok===!0)G=X.address}let fe=e==="transfer"?await Dr(G,o,n):void 0,se=`${c.cmdline}${o==="testnet"?" --testnet":""} --live --dir <your vault folder>`;return n.say([`DRY RUN — nothing signed, nothing sent · ${e} on ${o}`,...T.words.map((X)=>` ${X}`),...e==="transfer"?[Hr(fe),...G?[`account ${G}`]:[]]:[],...Tr(Q),`next ${se}`]),{data:{ok:!0,live:!1,posted:!1,network:o,verb:e,consequence:T.words,...T.facts,...e==="transfer"?{abstraction:fe??null,account:G}:{},...$r(Q),next:se}}}let a=await n.unlock(t.dir??".");if("error"in a)return q("vault_unavailable",a.error,{network:o,next:"Name the folder that holds .one/wallet.json: --dir ~/.one/<you>"});let d=a.keys.find((T)=>T.chain==="evm");if(!d)return q("no_evm_key",`The vault at ${t.dir??"."} holds no EVM key.`,{network:o});let p=Qs(d),b,w;try{b=c.build(n.now(),p.address),w=Ht(b.action,b.opts)}catch(T){return Le(T,{network:o,signer:p.address})}let x=await Ir(p.address,o,n),R=e==="transfer"?await Dr(p.address,o,n):void 0;if(n.say([`LIVE · ${e} on ${o} · signer ${p.address} (the vault's EVM key)`,...Rr("before",x),...b.words.map((T)=>` ${T}`),...e==="transfer"?[Hr(R)]:[],...Tr(w)]),!t.yes){if(!await n.confirm(`Sign this digest with ${p.address} and post it to Hyperliquid ${o}? [y/N] `))return{data:{ok:!1,error:"declined",network:o,signer:p.address,posted:!1,detail:"Nothing signed, nothing sent."}}}let D;try{({request:D}=await Or(b.action,b.opts,p,{expectDigest:w.digest}))}catch(T){return Le(T,{network:o,signer:p.address,posted:!1})}let k=await vr(D,o,{fetchImpl:n.fetchImpl}),N=await Ir(p.address,o,n);return n.say([`exchange ${JSON.stringify(k.ok?k.response:{error:k.error,detail:k.detail,response:k.response??null})}`,...Rr("after ",N)]),{data:{ok:k.ok,...k.ok?{}:{error:k.error,detail:k.detail},live:!0,posted:!0,network:o,verb:e,signer:p.address,...b.facts,...e==="transfer"?{abstraction:R??null}:{},...$r(w),signature:D.signature,exchange:k.ok?k.response:k.response??null,balanceBefore:x,balanceAfter:N}}}export{Hr as abstractionWords,to as liveGate,Si as prepareCancel,_i as prepareOrder,ki as prepareTransfer,Oi as prepareWithdraw,Ir as readBalance,Ft as resolveAccount,vi as runAction,Ai as runOrders,Bi as runPositions,Qs as vaultSigner};
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import{l,i,Z,c,m,L,x,Se,Y,p}from"./index-st6k9vhc.js";/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Jt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function kt(t){if(typeof t!=="boolean")throw TypeError(`boolean expected, not ${t}`)}function Lt(t){if(typeof t!=="number")throw TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw RangeError("positive integer expected, got "+t)}function X(t,e,r=""){let n=Jt(t),s=t?.length,a=e!==void 0;if(!n||a&&s!==e){let f=r&&`"${r}" `,u=a?` of length ${e}`:"",h=n?`length=${s}`:`type=${typeof t}`,d=f+"expected Uint8Array"+u+", got "+h;if(!n)throw TypeError(d);throw RangeError(d)}return t}function Rt(t,e=!0){if(t.destroyed)throw Error("Hash instance has been destroyed");if(e&&t.finished)throw Error("Hash#digest() has already been called")}function St(t,e,r=!1){X(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!Ut(t))throw Error("invalid output, must be aligned")}function ft(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function J(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function te(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var yt=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),ee=(t)=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var ne=(t)=>{for(let e=0;e<t.length;e++)t[e]=ee(t[e]);return t},lt=yt?(t)=>t:ne;function Nt(t,e){if(e==null||typeof e!=="object")throw Error("options must be defined");return Object.assign(t,e)}function Mt(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function vt(t,e,r){let n=e,s=r||(()=>[]),a=(u,h)=>n(h,...s(u)).update(u).digest(),f=n(new Uint8Array(t),...s(new Uint8Array(0)));return a.outputLen=f.outputLen,a.blockLen=f.blockLen,a.create=(u,...h)=>n(u,...h),a}var Kt=(t,e)=>{function r(n,...s){if(X(n,void 0,"key"),t.nonceLength!==void 0){let y=s[0];X(y,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let a=t.tagLength;if(a&&s[1]!==void 0)X(s[1],void 0,"AAD");let f=e(n,...s),u=(y,g)=>{if(g!==void 0){if(y!==2)throw Error("cipher output not supported");X(g,void 0,"output")}},h=!1;return{encrypt(y,g){if(h)throw Error("cannot encrypt() twice with same key + nonce");return h=!0,X(y),u(f.encrypt.length,g),f.encrypt(y,g)},decrypt(y,g){if(X(y),a&&y.length<a)throw Error('"ciphertext" expected length bigger than tagLength='+a);return u(f.decrypt.length,g),f.decrypt(y,g)}}}return Object.assign(r,t),r};function _t(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(X(e,void 0,"output"),e.length!==t)throw Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!Ut(e))throw Error("invalid output, must be aligned");return e}function Ht(t,e,r){Lt(t),Lt(e),kt(r);let n=new Uint8Array(16),s=te(n);return s.setBigUint64(0,BigInt(e),r),s.setBigUint64(8,BigInt(t),r),n}function Ut(t){return t.byteOffset%4===0}function Et(t){return Uint8Array.from(X(t))}var zt=(t)=>Uint8Array.from(t.split(""),(e)=>e.charCodeAt(0)),oe=(()=>lt(ft(zt("expand 16-byte k"))))(),re=(()=>lt(ft(zt("expand 32-byte k"))))();function B(t,e){return t<<e|t>>>32-e}var Bt=64,fe=16,Ct=(()=>4294967295)(),Pt=Uint32Array.of();function ce(t,e,r,n,s,a,f,u){let h=s.length,d=new Uint8Array(Bt),y=ft(d),g=yt&&Ut(s)&&Ut(a),E=g?ft(s):Pt,U=g?ft(a):Pt;if(!yt){for(let b=0;b<h;f++){if(t(e,r,n,y,f,u),lt(y),f>=Ct)throw Error("arx: counter overflow");let _=Math.min(Bt,h-b);for(let I=0,T;I<_;I++)T=b+I,a[T]=s[T]^d[I];b+=_}return}for(let b=0;b<h;f++){if(t(e,r,n,y,f,u),f>=Ct)throw Error("arx: counter overflow");let _=Math.min(Bt,h-b);if(g&&_===Bt){let I=b/4;if(b%4!==0)throw Error("arx: invalid block position");for(let T=0,F;T<fe;T++)F=I+T,U[F]=E[F]^y[T];b+=Bt;continue}for(let I=0,T;I<_;I++)T=b+I,a[T]=s[T]^d[I];b+=_}}function jt(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:a,rounds:f}=Nt({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!=="function")throw Error("core must be a function");return Lt(s),Lt(f),kt(a),kt(r),(u,h,d,y,g=0)=>{X(u,void 0,"key"),X(h,void 0,"nonce"),X(d,void 0,"data");let E=d.length;if(y=_t(E,y,!1),Lt(g),g<0||g>=Ct)throw Error("arx: counter overflow");let U=[],b=u.length,_,I;if(b===32)U.push(_=Et(u)),I=re;else if(b===16&&r)_=new Uint8Array(32),_.set(u),_.set(u,16),I=oe,U.push(_);else throw X(u,32,"arx key"),Error("invalid key size");if(!yt||!Ut(h))U.push(h=Et(h));let T=ft(_);if(n){if(h.length!==24)throw Error("arx: extended nonce must be 24 bytes");let Q=h.subarray(0,16);if(yt)n(I,T,ft(Q),T);else{let pt=lt(Uint32Array.from(I));n(pt,T,ft(Q),T),J(pt),lt(T)}h=h.subarray(16)}else if(!yt)lt(T);let F=16-s;if(F!==h.length)throw Error(`arx: nonce must be ${F} or 16 bytes`);if(F!==12){let Q=new Uint8Array(12);Q.set(h,a?0:12-h.length),h=Q,U.push(h)}let dt=lt(ft(h));try{return ce(t,I,T,dt,d,y,g,f),y}finally{J(...U)}}}function D(t,e){return t[e++]&255|(t[e++]&255)<<8}class $t{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(t){t=Et(X(t,32,"key"));let e=D(t,0),r=D(t,2),n=D(t,4),s=D(t,6),a=D(t,8),f=D(t,10),u=D(t,12),h=D(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|s<<9)&8191,this.r[4]=(s>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|f<<2)&8191,this.r[7]=(f>>>11|u<<5)&8065,this.r[8]=(u>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let d=0;d<8;d++)this.pad[d]=D(t,16+2*d)}process(t,e,r=!1){let n=r?0:2048,{h:s,r:a}=this,f=a[0],u=a[1],h=a[2],d=a[3],y=a[4],g=a[5],E=a[6],U=a[7],b=a[8],_=a[9],I=D(t,e+0),T=D(t,e+2),F=D(t,e+4),dt=D(t,e+6),Q=D(t,e+8),pt=D(t,e+10),V=D(t,e+12),q=D(t,e+14),k=s[0]+(I&8191),A=s[1]+((I>>>13|T<<3)&8191),R=s[2]+((T>>>10|F<<6)&8191),C=s[3]+((F>>>7|dt<<9)&8191),O=s[4]+((dt>>>4|Q<<12)&8191),S=s[5]+(Q>>>1&8191),N=s[6]+((Q>>>14|pt<<2)&8191),M=s[7]+((pt>>>11|V<<5)&8191),v=s[8]+((V>>>8|q<<8)&8191),H=s[9]+(q>>>5|n),w=0,z=w+k*f+A*(5*_)+R*(5*b)+C*(5*U)+O*(5*E);w=z>>>13,z&=8191,z+=S*(5*g)+N*(5*y)+M*(5*d)+v*(5*h)+H*(5*u),w+=z>>>13,z&=8191;let j=w+k*u+A*f+R*(5*_)+C*(5*b)+O*(5*U);w=j>>>13,j&=8191,j+=S*(5*E)+N*(5*g)+M*(5*y)+v*(5*d)+H*(5*h),w+=j>>>13,j&=8191;let W=w+k*h+A*u+R*f+C*(5*_)+O*(5*b);w=W>>>13,W&=8191,W+=S*(5*U)+N*(5*E)+M*(5*g)+v*(5*y)+H*(5*d),w+=W>>>13,W&=8191;let P=w+k*d+A*h+R*u+C*f+O*(5*_);w=P>>>13,P&=8191,P+=S*(5*b)+N*(5*U)+M*(5*E)+v*(5*g)+H*(5*y),w+=P>>>13,P&=8191;let ht=w+k*y+A*d+R*h+C*u+O*f;w=ht>>>13,ht&=8191,ht+=S*(5*_)+N*(5*b)+M*(5*U)+v*(5*E)+H*(5*g),w+=ht>>>13,ht&=8191;let wt=w+k*g+A*y+R*d+C*h+O*u;w=wt>>>13,wt&=8191,wt+=S*f+N*(5*_)+M*(5*b)+v*(5*U)+H*(5*E),w+=wt>>>13,wt&=8191;let gt=w+k*E+A*g+R*y+C*d+O*h;w=gt>>>13,gt&=8191,gt+=S*u+N*f+M*(5*_)+v*(5*b)+H*(5*U),w+=gt>>>13,gt&=8191;let xt=w+k*U+A*E+R*g+C*y+O*d;w=xt>>>13,xt&=8191,xt+=S*h+N*u+M*f+v*(5*_)+H*(5*b),w+=xt>>>13,xt&=8191;let bt=w+k*b+A*U+R*E+C*g+O*y;w=bt>>>13,bt&=8191,bt+=S*d+N*h+M*u+v*f+H*(5*_),w+=bt>>>13,bt&=8191;let mt=w+k*_+A*b+R*U+C*E+O*g;w=mt>>>13,mt&=8191,mt+=S*y+N*d+M*h+v*u+H*f,w+=mt>>>13,mt&=8191,w=(w<<2)+w|0,w=w+z|0,z=w&8191,w=w>>>13,j+=w,s[0]=z,s[1]=j,s[2]=W,s[3]=P,s[4]=ht,s[5]=wt,s[6]=gt,s[7]=xt,s[8]=bt,s[9]=mt}finalize(){let{h:t,pad:e}=this,r=new Uint16Array(10),n=t[1]>>>13;t[1]&=8191;for(let f=2;f<10;f++)t[f]+=n,n=t[f]>>>13,t[f]&=8191;t[0]+=n*5,n=t[0]>>>13,t[0]&=8191,t[1]+=n,n=t[1]>>>13,t[1]&=8191,t[2]+=n,r[0]=t[0]+5,n=r[0]>>>13,r[0]&=8191;for(let f=1;f<10;f++)r[f]=t[f]+n,n=r[f]>>>13,r[f]&=8191;r[9]-=8192;let s=(n^1)-1;for(let f=0;f<10;f++)r[f]&=s;s=~s;for(let f=0;f<10;f++)t[f]=t[f]&s|r[f];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let a=t[0]+e[0];t[0]=a&65535;for(let f=1;f<8;f++)a=(t[f]+e[f]|0)+(a>>>16)|0,t[f]=a&65535;J(r)}update(t){Rt(this),X(t),t=Et(t);let{buffer:e,blockLen:r}=this,n=t.length;for(let s=0;s<n;){let a=Math.min(r-this.pos,n-s);if(a===r){for(;r<=n-s;s+=r)this.process(t,s);continue}if(e.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r)this.process(e,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,J(this.h,this.r,this.buffer,this.pad)}digestInto(t){Rt(this),St(t,this),this.finished=!0;let{buffer:e,h:r}=this,{pos:n}=this;if(n){e[n++]=1;for(;n<16;n++)e[n]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let a=0;a<8;a++)t[s++]=r[a]>>>0,t[s++]=r[a]>>>8}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}}var Wt=vt(32,(t)=>new $t(t));function ae(t,e,r,n,s,a=20){let f=t[0],u=t[1],h=t[2],d=t[3],y=e[0],g=e[1],E=e[2],U=e[3],b=e[4],_=e[5],I=e[6],T=e[7],F=s,dt=r[0],Q=r[1],pt=r[2],V=f,q=u,k=h,A=d,R=y,C=g,O=E,S=U,N=b,M=_,v=I,H=T,w=F,z=dt,j=Q,W=pt;for(let ht=0;ht<a;ht+=2)V=V+R|0,w=B(w^V,16),N=N+w|0,R=B(R^N,12),V=V+R|0,w=B(w^V,8),N=N+w|0,R=B(R^N,7),q=q+C|0,z=B(z^q,16),M=M+z|0,C=B(C^M,12),q=q+C|0,z=B(z^q,8),M=M+z|0,C=B(C^M,7),k=k+O|0,j=B(j^k,16),v=v+j|0,O=B(O^v,12),k=k+O|0,j=B(j^k,8),v=v+j|0,O=B(O^v,7),A=A+S|0,W=B(W^A,16),H=H+W|0,S=B(S^H,12),A=A+S|0,W=B(W^A,8),H=H+W|0,S=B(S^H,7),V=V+C|0,W=B(W^V,16),v=v+W|0,C=B(C^v,12),V=V+C|0,W=B(W^V,8),v=v+W|0,C=B(C^v,7),q=q+O|0,w=B(w^q,16),H=H+w|0,O=B(O^H,12),q=q+O|0,w=B(w^q,8),H=H+w|0,O=B(O^H,7),k=k+S|0,z=B(z^k,16),N=N+z|0,S=B(S^N,12),k=k+S|0,z=B(z^k,8),N=N+z|0,S=B(S^N,7),A=A+R|0,j=B(j^A,16),M=M+j|0,R=B(R^M,12),A=A+R|0,j=B(j^A,8),M=M+j|0,R=B(R^M,7);let P=0;n[P++]=f+V|0,n[P++]=u+q|0,n[P++]=h+k|0,n[P++]=d+A|0,n[P++]=y+R|0,n[P++]=g+C|0,n[P++]=E+O|0,n[P++]=U+S|0,n[P++]=b+N|0,n[P++]=_+M|0,n[P++]=I+v|0,n[P++]=T+H|0,n[P++]=F+w|0,n[P++]=dt+z|0,n[P++]=Q+j|0,n[P++]=pt+W|0}var he=jt(ae,{counterRight:!1,counterLength:4,allowShortKeys:!1});var le=new Uint8Array(16),Xt=(t,e)=>{t.update(e);let r=e.length%16;if(r)t.update(le.subarray(r))},ue=new Uint8Array(32);function Ft(t,e,r,n,s){if(s!==void 0)X(s,void 0,"AAD");let a=t(e,r,ue),f=Ht(n.length,s?s.length:0,!0),u=Wt.create(a);if(s)Xt(u,s);Xt(u,n),u.update(f);let h=u.digest();return J(a,f),h}var pe=(t)=>(e,r,n)=>({encrypt(a,f){let u=a.length;f=_t(u+16,f,!1),f.set(a);let h=f.subarray(0,-16);t(e,r,h,h,1);let d=Ft(t,e,r,h,n);return f.set(d,u),J(d),f},decrypt(a,f){f=_t(a.length-16,f,!1);let u=a.subarray(0,-16),h=a.subarray(-16),d=Ft(t,e,r,u,n);if(!Mt(h,d))throw J(d),Error("invalid tag");return f.set(a.subarray(0,-16)),t(e,r,f,f,1),J(d),f}}),Tt=Kt({blockSize:64,nonceLength:12,tagLength:16},pe(he));var It=Uint8Array.of(0),de=Uint8Array.of();function ge(t,e,r,n=32,s){Z(t),l(n,"length"),i(e,void 0,"prk");let a=t.outputLen;if(e.length<a)throw Error('"prk" must be at least HashLen octets');if(n>255*a)throw Error("Length must be <= 255*HashLen");let f=Math.ceil(n/a);if(r===void 0)r=de;else i(r,void 0,"info");if(!f){if(s)c(e);return new Uint8Array}let u=s&&f===1?e:new Uint8Array(f*a),{iHash:h,oHash:d}=x.create(t,e),y=s?e:new Uint8Array(a),g=f>1?s?.iHash||t.create():void 0;for(let U=0;U<f-1;U++){It[0]=U+1;let b=h._cloneInto(g);if(U)b.update(y);b.update(r).update(It).digestInto(y),d._cloneInto(g).update(y).digestInto(y),u.set(y,a*U)}if(It[0]=f,f>1)h.update(y);if(h.update(r).update(It).digestInto(y),d.update(y).digestInto(y),u.set(y,a*(f-1)),h.destroy(),d.destroy(),g?.destroy(),y!==u)c(y);if(c(It),n===u.length)return u;let E=u.slice(0,n);return c(u),E}var K=(t,e,r,n,s)=>{if(Z(t),r===void 0)r=new Uint8Array(t.outputLen);let a=x.create(t,r).update(e);return ge(t,a.digest(),n,s,a)};var ye="age-encryption.org/v1",G="-----BEGIN AGE ENCRYPTED FILE-----",se="-----END AGE ENCRYPTED FILE-----",Gt="age-encryption.org/v1/X25519",Dt="age",Vt="age-secret-key-",At=65536,Le=128,Ot=16,xe=new TextEncoder,Yt=new TextDecoder,ut=(t)=>xe.encode(t);class o extends Error{code;constructor(t,e){super(e);this.code=t,this.name="AgeError"}}function ie(t){if(t.length!==32)throw new o("bad_key","an X25519 public key is 32 bytes");return p.encode(Dt,p.toWords(t),!1)}function Ve(t){let e=t.trim(),r;try{r=p.decode(e,!1)}catch{throw new o("bad_key","not an age recipient (age1…)")}if(r.prefix!==Dt)throw new o("bad_key",`not an age recipient: prefix ${r.prefix}`);let n=p.fromWords(r.words);if(n.length!==32)throw new o("bad_key","an age recipient carries 32 bytes");return n}function we(t){if(t.length!==32)throw new o("bad_key","an X25519 secret is 32 bytes");return p.encode(Vt,p.toWords(t),!1).toUpperCase()}function ot(t){let e=t.trim().toLowerCase(),r;try{r=p.decode(e,!1)}catch{throw new o("bad_key","not an age identity (AGE-SECRET-KEY-1…)")}if(r.prefix!==Vt)throw new o("bad_key",`not an age identity: prefix ${r.prefix}`);let n=p.fromWords(r.words);if(n.length!==32)throw new o("bad_key","an age identity carries 32 bytes");return n}function st(t){return ie(L.getPublicKey(t))}function be(t,e){let r=L.utils.randomSecretKey(),n=null,s=null;try{let a=L.getPublicKey(r);try{n=L.getSharedSecret(r,e)}catch{throw new o("bad_key","low-order recipient point")}if(n.every((h)=>h===0))throw new o("bad_key","low-order recipient point");let f=new Uint8Array(64);f.set(a,0),f.set(e,32),s=K(m,n,f,ut(Gt),32);let u=Tt(s,new Uint8Array(12)).encrypt(t);return{share:a,body:u}}finally{r.fill(0),n?.fill(0),s?.fill(0)}}function qt(t,e){let r=K(m,t,new Uint8Array(0),ut("header"),32),n=x(m,r,e);return r.fill(0),n}function Zt(t,e){let r=new Uint8Array(12),n=t;for(let s=10;s>=0&&n>0;s--)r[s]=n%256,n=Math.floor(n/256);return r[11]=e?1:0,r}function Qt(t){let e=new Uint8Array(t.reduce((n,s)=>n+s.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e}function Je(t,e){if(e.length===0)throw new o("bad_key","seal it for at least one recipient");let r=e.map(Ve),n=crypto.getRandomValues(new Uint8Array(16));try{let s=[ye];for(let E of r){let{share:U,body:b}=be(n,E);s.push(`-> X25519 ${Y.encode(U)}`,Y.encode(b))}s.push("---");let a=ut(s.join(`
|
|
2
|
-
`)),f=qt(n,a),u=ut(`${s.join(`
|
|
3
|
-
`)} ${Y.encode(f)}
|
|
4
|
-
`),h=crypto.getRandomValues(new Uint8Array(16)),d=K(m,n,h,ut("payload"),32),y=[u,h],g=Math.max(1,Math.ceil(t.length/At));for(let E=0;E<g;E++){let U=t.subarray(E*At,Math.min(t.length,(E+1)*At));y.push(Tt(d,Zt(E,E===g-1)).encrypt(U))}return d.fill(0),Qt(y)}finally{n.fill(0)}}var me=1048576,Ue=/^[\x21-\x7e]+$/;function Xe(t){let e=Math.min(t.length,me),r=0,n=()=>{let h=r;while(h<e&&t[h]!==10){if(t[h]<32||t[h]>126)throw new o("malformed","header byte outside printable ASCII");h++}if(h>=e)throw new o("malformed","header runs off the end of the file");let d=Yt.decode(t.subarray(r,h));return r=h+1,d};if(n()!==ye)throw new o("malformed","not an age file: missing version line");let s=[],a=null,f=0;while(a===null){f=r;let h=n();if(h.startsWith("---")){a=h;break}if(!h.startsWith("-> "))throw new o("malformed","unexpected header line");let d=h.slice(3).split(" ");if(!d.every((b)=>Ue.test(b)))throw new o("malformed","stanza arguments must be non-empty visible ASCII");let[y,...g]=d,E=[];for(;;){let b=n();if(E.push(b),b.length<64)break;if(b.length>64)throw new o("malformed","stanza body line over 64 columns")}let U;try{U=Y.decode(E.join(""))}catch{throw new o("malformed","stanza body is not base64")}if(s.push({type:y,args:g,body:U}),s.length>Le)throw new o("unsupported",`sealed for more than ${Le} readers`)}if(!a.startsWith("--- "))throw new o("malformed","header footer must be `--- ` and a MAC");let u;try{u=Y.decode(a.slice(4))}catch{throw new o("malformed","header MAC is not base64")}if(u.length!==32)throw new o("malformed","header MAC is not 32 bytes");if(s.some((h)=>h.type==="scrypt")&&s.length!==1)throw new o("malformed","scrypt must be the only recipient");return{stanzas:s,mac:u,upToDashes:t.subarray(0,f+3),payload:t.subarray(r)}}function Ee(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Qe(t,e){if(e.length===0)throw new o("no_identity","no identity to open it with");let{stanzas:r,mac:n,upToDashes:s,payload:a}=Xe(t),f=r.filter((d)=>d.type==="X25519");if(f.length===0){let d=[...new Set(r.map((y)=>y.type))].join(", ")||"none";throw new o("unsupported",`no X25519 recipient in this file (stanzas: ${d})`)}let u=null,h=e.map((d)=>L.getPublicKey(d));for(let d of f){if(d.args.length!==1||d.body.length!==32)throw new o("malformed","bad X25519 stanza");let y;try{y=Y.decode(d.args[0])}catch{throw new o("malformed","X25519 share is not base64")}if(y.length!==32)throw new o("malformed","X25519 share is not 32 bytes");for(let g=0;g<e.length;g++){let E;try{E=L.getSharedSecret(e[g],y)}catch{throw new o("malformed","X25519 share is a low-order point")}if(E.every((_)=>_===0))throw new o("malformed","X25519 share is a low-order point");let U=new Uint8Array(64);U.set(y,0),U.set(h[g],32);let b=K(m,E,U,ut(Gt),32);E.fill(0);try{u=Tt(b,new Uint8Array(12)).decrypt(d.body)}catch{u=null}finally{b.fill(0)}if(u)break}if(u)break}if(!u)throw new o("no_identity","none of your keys opens this");try{if(!Ee(qt(u,s),n))throw new o("tampered","header MAC does not match");if(a.length<16)throw new o("malformed","payload shorter than its nonce");let d=a.subarray(0,16),y=K(m,u,d,ut("payload"),32);try{let g=a.subarray(16),E=At+Ot,U=[],b=0,_=0;for(;;){let I=g.length-_;if(I<Ot)throw new o("malformed","payload chunk shorter than its tag");let T=I<=E,F=T?I:E;if(T&&F===Ot&&b>0)throw new o("malformed","empty final chunk");try{U.push(Tt(y,Zt(b,T)).decrypt(g.subarray(_,_+F)))}catch{throw new o("tampered",`payload chunk ${b} does not authenticate`)}if(_+=F,b++,T)break}return Qt(U)}finally{y.fill(0)}}finally{u.fill(0)}}function et(t){let e=Se.encode(t),r=[];for(let n=0;n<e.length;n+=64)r.push(e.slice(n,n+64));return[G,...r,se].join(`
|
|
5
|
-
`)+`
|
|
6
|
-
`}function tt(t){let r=t.replace(/^[ \t\r\n]+|[ \t\r\n]+$/g,"").replace(/\r\n/g,`
|
|
7
|
-
`);if(r.includes("\r"))throw new o("malformed","armor: a bare carriage return");let n=r.split(`
|
|
8
|
-
`);if(n.length<3||n[0]!==G||n[n.length-1]!==se)throw new o("malformed","no armored age block found");let s=n.slice(1,-1);for(let a=0;a<s.length;a++){let f=a===s.length-1;if(s[a].length>64||!f&&s[a].length!==64||s[a].length===0)throw new o("malformed","armor: lines must be 64 columns, the last 1-64");if(!/^[A-Za-z0-9+/=]+$/.test(s[a]))throw new o("malformed","armored body is not base64")}try{return Se.decode(s.join(""))}catch{throw new o("malformed","armored body is not base64")}}function rt(t){let e=t.replace(/\r\n?/g,`
|
|
9
|
-
`),r=e.indexOf(G),n=e.indexOf(se,r<0?0:r);if(r<0||n<0)throw new o("malformed","no armored age block found");let s=e.slice(r+G.length,n).split(`
|
|
10
|
-
`).map((a)=>a.trim()).filter((a)=>a.length>0);if(s.length===0)throw new o("malformed","armored block is empty");return[G,...s,se].join(`
|
|
11
|
-
`)}function it(t){let e=t.trimStart();return e.startsWith(G)||e.startsWith(ye)}function at(t,e){return et(Je(ut(t),e))}function nt(t,e){let r=t.includes(G)?tt(rt(t)):ut(t);return Qe(r,e)}function ct(t,e){return Yt.decode(nt(t,e))}
|
|
12
|
-
export{K,ye,G,se,Le,o,ie,Ve,we,ot,st,Je,Xe,Qe,et,tt,rt,it,at,nt,ct};
|