oneie 5.8.1 → 5.9.0
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 +114 -6
- package/dist/package.json +31 -4
- package/dist/src/age-1k8hs4ec.js +1 -0
- package/dist/src/client-n6fpnd9f.js +1 -0
- package/dist/src/evm-tx-cqhm9rtt.js +1 -0
- package/dist/src/hl-run-0pv1e0p2.js +1 -0
- package/dist/src/index-f5vhzspa.js +12 -0
- package/dist/src/index-h3nrt8bx.js +4 -0
- package/dist/src/index-st6k9vhc.js +2062 -0
- package/dist/src/index.js +711 -636
- package/dist/src/message-key-yczrxszr.js +1 -0
- package/dist/src/{message-lock-5vr8079x.js → message-lock-thr851d5.js} +3 -3
- package/dist/src/sweep-order-jrq2hkye.js +1 -0
- package/dist/src/sweep-runner-jftw9em7.js +1 -0
- package/package.json +31 -4
- package/dist/src/age-yefbe8pe.js +0 -1
- package/dist/src/evm-tx-ee2q0e3w.js +0 -1
- package/dist/src/hl-run-tgrkrk69.js +0 -1
- package/dist/src/index-0rj9wdk9.js +0 -4
- package/dist/src/index-91y484c2.js +0 -2052
- package/dist/src/index-940y3rnv.js +0 -12
- package/dist/src/message-key-db1xjdkw.js +0 -1
- package/dist/src/sweep-order-c2p6rk8c.js +0 -1
- package/dist/src/sweep-runner-t68xe7vx.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{K,ie,we}from"./index-f5vhzspa.js";import{m,L,D,U,v}from"./index-st6k9vhc.js";var o="message-x25519-v1";function n(e){if(e.length!==32)throw Error("the master is 32 bytes");let t=K(m,e,new Uint8Array(0),new TextEncoder().encode(o),32),r=L.getPublicKey(t);return{recipient:ie(r),publicKey:r,secret:t}}function d(e){let t=e.trim().toLowerCase().split(/\s+/).join(" ");if(!U(t,v))throw Error("that is not a valid 24-word BIP-39 recovery phrase");let r=D(t,v);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 h(e){return we(e.secret)}export{o as MESSAGE_KEY_INFO,n as deriveMessageKey,h as messageIdentityText,d as messageKeyFromPhrase};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{T,_,q}from"./index-st6k9vhc.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
2
|
${n}
|
|
3
|
-
${t}`}function
|
|
3
|
+
${t}`}function h(n,t,e){return`${a}
|
|
4
4
|
${n}/${t}
|
|
5
|
-
${e}`}function
|
|
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),_(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=T.getPublicKey(n),r=T.sign(f(t),n),o=new Uint8Array(97);return o[0]=0,o.set(r,1),o.set(e,65),{address:q(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(!T.verify(r,f(n),o))return null}catch{return null}return q(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{lt,ke,ae,ve}from"./index-h3nrt8bx.js";export{lt as ORDER_MAX_TTL_MS,ke as ORDER_MIN_REMAINING_MS,ve as handoverMessage,ae as sweepOrderMessage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ke,ae,ve}from"./index-h3nrt8bx.js";import{M,qe}from"./index-st6k9vhc.js";function A(e,r){return M(r.chain,e,ae(r))}function x(e,r){return M(r.chain,e,ve(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()<ke){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(!qe(e.chain,c,n.signature,ae(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};
|
package/package.json
CHANGED
|
@@ -1,12 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oneie",
|
|
3
|
-
"version": "5.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "5.9.0",
|
|
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": {
|
|
7
7
|
"oneie": "dist/src/index.js",
|
|
8
8
|
"one": "dist/src/index.js"
|
|
9
9
|
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"ai-agent",
|
|
12
|
+
"ai-agents",
|
|
13
|
+
"agent-payments",
|
|
14
|
+
"agentic-payments",
|
|
15
|
+
"agent-wallet",
|
|
16
|
+
"mcp",
|
|
17
|
+
"claude-code",
|
|
18
|
+
"codex",
|
|
19
|
+
"cursor",
|
|
20
|
+
"llms-txt",
|
|
21
|
+
"x402",
|
|
22
|
+
"usdc",
|
|
23
|
+
"stablecoin",
|
|
24
|
+
"sui",
|
|
25
|
+
"solana",
|
|
26
|
+
"base",
|
|
27
|
+
"crypto-payments",
|
|
28
|
+
"payments",
|
|
29
|
+
"wallet",
|
|
30
|
+
"checkout",
|
|
31
|
+
"cli",
|
|
32
|
+
"one"
|
|
33
|
+
],
|
|
10
34
|
"files": [
|
|
11
35
|
"dist",
|
|
12
36
|
"README.md"
|
|
@@ -34,7 +58,10 @@
|
|
|
34
58
|
"license": "SEE LICENSE IN LICENSE",
|
|
35
59
|
"repository": {
|
|
36
60
|
"type": "git",
|
|
37
|
-
"url": "git+https://github.com/one-ie/
|
|
38
|
-
|
|
61
|
+
"url": "git+https://github.com/one-ie/one.git"
|
|
62
|
+
},
|
|
63
|
+
"homepage": "https://one.ie/?utm_source=npm&utm_medium=package&utm_campaign=oneie",
|
|
64
|
+
"bugs": {
|
|
65
|
+
"url": "https://github.com/one-ie/one/issues"
|
|
39
66
|
}
|
|
40
67
|
}
|
package/dist/src/age-yefbe8pe.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{X,j,M,me,e,z,$e,Q,Ne,Pe,Ae,Te,Oe,Re,Ie,Ce,Le,De,je,Be}from"./index-940y3rnv.js";export{j as AGE_ARMOR_BEGIN,M as AGE_ARMOR_END,X as AGE_VERSION_LINE,e as AgeError,me as MAX_STANZAS,Re as armor,Ie as dearmor,Ne as decodeIdentity,$e as decodeRecipient,Oe as decrypt,Q as encodeIdentity,z as encodeRecipient,Ae as encrypt,Ce as extractArmored,Le as looksLikeAge,je as openBytes,Be as openText,Te as parseHeader,Pe as recipientOf,De as sealText};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o,k}from"./index-91y484c2.js";var c=(e)=>Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("");function u(e){let t=e.replace(/^0x/,"");if(t.length%2||/[^0-9a-fA-F]/.test(t))throw Error("bad hex");let r=new Uint8Array(t.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}function h(e){let t=e.toLowerCase().replace(/^0x/,""),r=c(k(new TextEncoder().encode(t))),n="0x";for(let s=0;s<t.length;s++)n+=parseInt(r[s],16)>=8?t[s].toUpperCase():t[s];return n}function w(e){let t=e.trim();if(/^0x[0-9a-fA-F]{64}$/.test(t))return"That looks like a Sui address, not an Ethereum one.";if(!/^0x[0-9a-fA-F]{40}$/.test(t))return"Enter an Ethereum address: 0x followed by 40 hex characters.";if(/^0x0{40}$/.test(t))return"That is the zero address — anything sent there is burned.";let r=t.slice(2);if(r!==r.toLowerCase()&&r!==r.toUpperCase()&&h(t)!==t)return"Address checksum does not match — check for a typo.";return null}function y(e){let t=[];while(e>0)t.unshift(e&255),e=Math.floor(e/256);return Uint8Array.from(t)}function a(e){let t=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function l(e,t){if(e<56)return Uint8Array.of(t+e);let r=y(e);return a([Uint8Array.of(t+55+r.length),r])}function f(e){if(e instanceof Uint8Array){if(e.length===1&&e[0]<128)return e;return a([l(e.length,128),e])}let t=a(e.map(f));return a([l(t.length,192),t])}function i(e){let t=BigInt(e);if(t<0n)throw Error("negative integer in transaction");let r=[];while(t>0n)r.unshift(Number(t&0xffn)),t>>=8n;return Uint8Array.from(r)}function d(e){return[i(e.chainId),i(e.nonce),i(e.maxPriorityFeePerGas),i(e.maxFeePerGas),i(e.gasLimit),u(e.to),i(e.value),u(e.data),[]]}function b(e,t){let r=k(a([Uint8Array.of(2),f(d(e))])),n=o.sign(r,t,{prehash:!1,format:"recovered"}),s=n[0],p=n.slice(1,33),x=n.slice(33,65),g=f([...d(e),i(s),i(BigInt(`0x${c(p)}`)),i(BigInt(`0x${c(x)}`))]);return`0x02${c(g)}`}function U(e){return`0x${c(k(u(e)))}`}function E(e){let t=o.getPublicKey(e,!1);return h(`0x${c(k(t.slice(1)).slice(12))}`)}function v(e,t){return`0xa9059cbb${e.toLowerCase().replace(/^0x/,"").padStart(64,"0")}${t.toString(16).padStart(64,"0")}`}export{h as checksumAddress,v as encodeErc20Transfer,E as evmAddressFromKey,w as evmRecipientProblem,U as evmTxHash,u as hexToBytes,f as rlpEncode,b as signEip1559};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{l,be,ye,G,a,_e,s,Y,g,R,I,b,V,x,_,J,ue,Se,B,Ee,fe}from"./index-91y484c2.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=V(this.buffer)}update(e){g(this),s(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let c=0;c<o;){let f=Math.min(n-this.pos,o-c);if(f===n){let d=V(e);for(;n<=o-c;c+=n)this.process(d,c);i=!0;continue}if(r.set(c===0&&f===o?e:e.subarray(c,c+f),this.pos),this.pos+=f,c+=f,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){g(this),R(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);ye(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let c=e===t?r:V(e),f=this.outputLen,d=f/4,u=this.get();if(f%4||d>u.length)throw Error("invalid outputLen");for(let p=0;p<d;p++)c.setUint32(4*p,u[p],o)}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:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)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]),ve=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:o,F:i,G:c,H:f}=this;return[e,t,r,n,o,i,c,f]}set(e,t,r,n,o,i,c,f){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=c|0,this.H=f|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)ve[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let w=ve[p-15],S=ve[p-2],A=x(w,7)^x(w,18)^w>>>3,F=x(S,17)^x(S,19)^S>>>10;ve[p]=F+ve[p-7]+A+ve[p-16]|0}let{A:r,B:n,C:o,D:i,E:c,F:f,G:d,H:u}=this;for(let p=0;p<64;p++){let w=x(c,6)^x(c,11)^x(c,25),S=u+w+wn(c,f,d)+Ur[p]+ve[p]|0,F=(x(r,2)^x(r,13)^x(r,22))+En(r,n,o)|0;u=d,d=f,f=c,c=i+S|0,i=o,o=n,n=r,r=S+F|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,c=c+this.E|0,f=f+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(r,n,o,i,c,f,d,u)}roundClean(){b(ve)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),b(this.buffer)}}class _n extends An{constructor(){super(32,Bn)}}var Sn=B(()=>new _n,fe(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 Q=(e,t,r)=>s(e,t,r),Ct=a;function On(e,t=""){if(typeof e!=="string"){let r=t&&`"${t}" `;throw TypeError(r+"expected string, got type="+typeof e)}return e}function Ie(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 Ue(e,t){if(typeof e!=="function")throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Ut=J,xe=(...e)=>Se(...e),xt=(e)=>ue(e),Ze=G,wt=(e)=>Ee(e),bt=BigInt(0),kn=BigInt(1),qr=(e)=>e?`"${e}" `:"";function he(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(!Re(e))throw RangeError("positive bigint expected, got "+e)}else Ct(e);return e}function qe(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 pe(e){return vn(J(e))}function qt(e){return vn(J(Pr(s(e)).reverse()))}function Bt(e,t){if(a(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 ue(n.padStart(r,"0"))}function Pt(e,t){return Bt(e,t).reverse()}function Pr(e){return Uint8Array.from(Q(e))}function Re(e){return typeof e==="bigint"&&bt<=e}function jt(e,t,r){return Re(e)&&Re(t)&&Re(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 Ye(e){if(e<bt)throw Error("expected non-negative bigint, got "+e);return e===bt?0:e.toString(2).length}var ct=(e)=>(qe(e,"n"),(kn<<BigInt(e))-kn);function In(e,t,r){if(a(e,"hashLen"),a(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let n=(T)=>new Uint8Array(T),o=Uint8Array.of(),i=Uint8Array.of(0),c=Uint8Array.of(1),f=1000,d=n(e),u=n(e),p=0,w=()=>{d.fill(1),u.fill(0),p=0},S=(...T)=>r(u,xe(d,...T)),A=(T=o)=>{if(u=S(i,T),d=S(),T.length===0)return;u=S(c,T),d=S()},F=()=>{if(p++>=f)throw Error("drbg: tried max amount of iterations");let T=0,q=[];while(T<t){d=S();let L=d.slice();q.push(L),T+=d.length}return xe(...q)};return(T,q)=>{w(),A(T);let L=void 0;while((L=q(F()))===void 0)A();return w(),L}}function Te(e,t={},r={},n="object"){Ie(e,n),Ie(t,"fields"),Ie(r,"optFields");function o(c,f,d){let u=n==="object"?`param "${String(c)}"`:`"${n}.${String(c)}"`,p=e[c];if(!Object.hasOwn(e,c)&&(d?p!==void 0:f!=="function"))throw TypeError(`${u} is invalid: expected own property`);if(d&&p===void 0)return;let w=typeof p;if(w!==f||p===null)throw TypeError(`${u} is invalid: expected ${f}, got ${w}`)}let i=(c,f)=>Object.entries(c).forEach(([d,u])=>o(d,u,f));i(t,!1),i(r,!0)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ee=BigInt(0),j=BigInt(1),$e=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 ie(e,t){if(t<=ee)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=ee?r:t+r}function Nn(e,t,r){if(r<=j)throw Error("pow: expected modulus > 1, got "+r);if(typeof t!=="bigint")throw TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<ee)throw Error("invalid exponent, negatives unsupported");if(t===ee)return j;if(t===j)return e;let n=e%r;if(n<ee)n+=r;if(t<Wr){let f=j;while(t>ee){if(t&j)f=f*n%r;n=n*n%r,t>>=j}return f}let o=[];while(t>ee)o.push(Number(t&zr)),t>>=Wt;let i=Array(16);i[0]=j,i[1]=n;for(let f=2;f<16;f++)i[f]=i[f-1]*n%r;let c=i[o[o.length-1]];for(let f=o.length-2;f>=0;f--){c=c*c%r,c=c*c%r,c=c*c%r,c=c*c%r;let d=o[f];if(d!==0)c=c*i[d]%r}return c}function ae(e,t,r){if(r<=j)throw Error("pow2: expected modulus > 1, got "+r);if(t<ee)throw Error("pow2: expected non-negative exponent, got "+t);let n=e;while(t-- >ee)n*=n,n%=r;return n}function Rn(e,t){if(e===ee)throw Error("invert: expected non-zero number");if(t<=j)throw Error("invert: expected modulus > 1, got "+t);let r=ie(e,t),n=t,o=ee,i=j;while(r!==ee){let f=n/r,d=n-r*f,u=o-i*f;n=r,r=d,o=i,i=u}if(n!==j)throw Error("invert: does not exist");return ie(o,t)}function Cn(e,t){if(t<=j)throw Error("invertCt: expected prime modulus > 1, got "+t);let r=ie(e,t);if(r===ee)throw Error("invertCt: expected non-zero number");let n=Nn(r,t-$e,t);if(ie(r*n,t)!==j)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&j)===ee)throw Error(t+": expected odd modulus, got "+e)}function Un(e,t){let r=e,n=(r.ORDER+j)/Wt,o=r.pow(t,n);return Zt(r,o,t),o}function Zr(e,t){let r=e,n=(r.ORDER-Dn)/Fn,o=r.mul(t,$e),i=r.pow(o,n),c=r.mul(t,i),f=r.mul(r.mul(c,$e),i),d=r.mul(c,r.sub(f,r.ONE));return Zt(r,d,t),d}function Yr(e){let t=Ve(e),r=qn(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),c=(e+jr)/Ln;return(f,d)=>{let u=f,p=u.pow(d,c),w=u.mul(p,n),S=u.mul(p,o),A=u.mul(p,i),F=u.eql(u.sqr(w),d),C=u.eql(u.sqr(S),d);p=u.cmov(p,w,F),w=u.cmov(A,S,C);let T=u.eql(u.sqr(w),d),q=u.cmov(p,w,T);return Zt(u,q,d),q}}function qn(e){if(e<Hn)throw Error("sqrt is not defined for small field");Yt(e,"tonelliShanks");let t=e-j,r=0;while(t%$e===ee)t/=$e,r++;let n=$e,o=Ve(e);while(Tn(o,n)===1)if(n++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return Un;let i=o.pow(n,t),c=(t+j)/$e;return function(d,u){let p=d;if(p.is0(u))return u;if(Tn(p,u)!==1)throw Error("Cannot find square root");let w=r,S=p.mul(p.ONE,i),A=p.pow(u,t),F=p.pow(u,c);while(!p.eql(A,p.ONE)){if(p.is0(A))throw Error("Cannot find square root: probably non-prime P");let C=1,T=p.sqr(A);while(!p.eql(T,p.ONE))if(C++,T=p.sqr(T),C===w)throw Error("Cannot find square root");let q=j<<BigInt(w-C-1),L=p.pow(S,q);w=C,S=p.sqr(L),A=p.mul(A,S),F=p.mul(F,L)}return F}}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 Ke(e){if(Ie(e,"field"),typeof e.ORDER!=="bigint")throw TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);qe(e.BYTES,"BYTES"),qe(e.BITS,"BITS");for(let t of Vr)Ue(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=j)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Kt(e,t,r=!1){Ke(e),yt(t,"nums"),he(r,"passZero");let n=e,o=Array(t.length).fill(r?n.ZERO:void 0),i=t.reduce((f,d,u)=>{if(n.is0(d))return f;return o[u]=f,n.mul(f,d)},n.ONE),c=n.inv(i);return t.reduceRight((f,d,u)=>{if(n.is0(d))return f;return o[u]=n.mul(f,o[u]),n.mul(f,d)},c),o}function Tn(e,t){Ke(e);let r=e;Yt(r.ORDER,"FpLegendre");let n=(r.ORDER-j)/$e,o=r.pow(t,n),i=r.eql(o,r.ONE),c=r.eql(o,r.ZERO),f=r.eql(o,r.neg(r.ONE));if(!i&&!c&&!f)throw Error("invalid Legendre symbol result");return i?1:c?0:-1}function Xr(e,t){if(t!==void 0)Ct(t);if(e<=ee)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=Ye(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,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var $n=new WeakMap;class zt{ORDER;BITS;BYTES;isLE;ZERO=ee;ONE=j;_lengths;_mod;constructor(e,t={}){if(e<=j)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:o}=Xr(e,r);if(o>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return ee<=e&&e<this.ORDER}is0(e){return e===ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&j)===j}neg(e){return ie(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ie(e*e,this.ORDER)}add(e,t){return ie(e+t,this.ORDER)}sub(e,t){return ie(e-t,this.ORDER)}mul(e,t){return ie(e*t,this.ORDER)}pow(e,t){return Nn(e,t,this.ORDER)}div(e,t){return ie(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){Q(e);let{_lengths:r,BYTES:n,isLE:o,ORDER:i,_mod:c}=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 d=new Uint8Array(n);d.set(e,o?0:d.length-e.length),e=d}if(e.length!==n)throw Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=o?qt(e):pe(e);if(c)f=ie(f,i);if(!t){if(!this.isValid(f))throw Error("invalid field element: outside of range 0..ORDER")}return f}invertBatch(e){return Kt(this,e,!0)}cmov(e,t,r){return he(r,"condition"),r?t:e}}function Ve(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<=j)throw Error("field order must be greater than 1");let t=Ye(e-j);return Math.ceil(t/8)}function At(e){let t=Pn(e);return t+Math.ceil(t/2)}function _t(e,t,r=!1){Q(e);let n=e.length,o=Pn(t),i=Math.max(At(t),16);if(n<i||n>1024)throw Error("expected "+i+"-1024 bytes of input, got "+n);let c=r?qt(e):pe(e),f=ie(c,t-j)+j;return r?Pt(f,o):Bt(f,o)}/*! 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 Xe(e){let t=e;if(typeof t!=="function")throw TypeError('"Point" expected constructor, got type='+typeof e);Ue(t.fromAffine,"Point.fromAffine"),Ue(t.fromBytes,"Point.fromBytes"),Ue(t.fromHex,"Point.fromHex"),Ie(t.BASE,"Point.BASE"),Ie(t.ZERO,"Point.ZERO"),Ke(t.Fp),Ke(t.Fn)}function Wn(e,t){Xe(e),Zn(t,e);let r=Kt(e.Fp,t.map((n)=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}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;Ue(e,"randomBytes");try{let r=e(t);if(!Ze(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,o)=>{if(!(r===void 0?t.isValid(n):Re(n)&&n<r))throw Error("invalid scalar at index "+o)})}var Yn=new WeakMap;function Xt(e){return Yn.get(e)||1}function ns(e,t){let r=e.double(),n=[e];for(let o=1;o<t;o++)n.push(n[o-1].add(r));return n}function rs(e,t){let r=2**t,n=r/2,o=BigInt(r-1),i=[];while(e>Gt){let c=0;if(e&dt){if(c=Number(e&o),c>=n)c-=r;e-=BigInt(c)}i.push(c),e>>=dt}return i}function ss(e,t,r){let n=2**t,o=n/2,i=BigInt(n-1),c=BigInt(t),f=[];for(let d=0;d<r;d++){let u=Number(e&i);if(e>>=c,u>o)u-=n,e+=dt;f.push(u)}if(e!==Gt)throw Error("invalid wnaf");return f}function os(e,t,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=e;for(let i=n-1;i>=0;i--){if(i!==n-1)o=o.double();for(let c=0;c<r.length;c++){let f=r[c][i];if(f){let d=t[c][Math.abs(f)-1>>1];o=o.add(f<0?d.negate():d)}}}return o}class Qt{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Xe(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,o=2**(t-1),i=[],c=e;for(let f=0;f<n;f++){let d=c;for(let u=0;u<o;u++)i.push(d),d=d.add(c);c=i[i.length-1].double()}return{W:t,bits:r,windows:n,comp:i}}wnafCachedCT(e,t){let{W:r,windows:n,comp:o}=e,i=2**(r-1),c=ss(t,r,n),f=this.ZERO,d=this.BASE;for(let u=0;u<n;u++){let p=c[u],w=u*i,S=Math.abs(p)-1,A=o[w];for(let C=1;C<i;C++)A=C===S?o[w+C]:A;let F=A.negate();if(p===0)d=d.add(o[w]);else f=f.add(p<0?F:A)}return{p:f,f:d}}getWnafPrecomputes(e,t,r,n){let o=this.wnafPrecomputes.get(t),i=o?.find((c)=>c.W===e&&c.bits===r);if(!i){if(i=this.buildWnafTable(t,e,r),typeof n==="function")i={...i,comp:n(i.comp)};if(!o)o=[],this.wnafPrecomputes.set(t,o);o.push(i)}return i}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 o=Xt(e);if(o===1)return this.fixedWindowCT(e,t,r);return this.wnafCachedCT(this.getWnafPrecomputes(o,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,o=this.randomBytes(Vt);if(!Ze(o)||o.length!==Vt)throw Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+pe(o)*this.Point.Fn.ORDER;return this.runCT(e,i,n,r)}fixedWindowCT(e,t,r){let n=Jr,o=1<<n,i=ct(n),c=Array(o);c[0]=this.ZERO;for(let u=1;u<o;u++)c[u]=c[u-1].add(e);let f=Math.ceil(r/n),d=this.ZERO;for(let u=f-1;u>=0;u--){if(u!==f-1)for(let S=0;S<n;S++)d=d.double();let p=Number(t>>BigInt(u*n)&i),w=c[0];for(let S=1;S<o;S++)w=S===p?c[S]:w;d=d.add(w)}return{p:d,f:d}}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),!Re(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 o=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(o,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(Xe(e),Zn(t,e),he(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 o=t.map((c)=>ns(c,4)),i=r.map((c)=>rs(c,4));return os(e.ZERO,o,i)}function zn(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return Ke(t),t}else return Ve(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`);Te(r);for(let d of["p","n","h"]){let u=t[d];if(!(Re(u)&&u!==Gt))throw Error(`CURVE.${d} must be positive bigint`)}let o=zn(t.p,r.Fp,n),i=zn(t.n,r.Fn,n),f=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let d of f)if(!o.isValid(t[d]))throw Error(`CURVE.${d} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function Vn(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}class en{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Y(e),s(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 o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),b(n)}update(e){return g(this),this.iHash.update(e),this}digestInto(e){g(this),R(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:o,blockLen:i,outputLen:c,canXOF:f}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=c,e.canXOF=f,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 we={Err:Gn,_tlv:{encode:(e,t)=>{let{Err:r}=we;if(qe(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,o=at(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?at(o.length/2|128):"";return at(e)+i+o+t},decode(e,t){let{Err:r}=we;t=Q(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 o=t[n++],i=!!(o&128),c=0;if(!i)c=o;else{let d=o&127;if(!d)throw new r("tlv.decode(long): indefinite length not supported");if(d>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+d);if(u.length!==d)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let p of u)c=c<<8|p;if(n+=d,c<128)throw new r("tlv.decode(long): not minimal encoding")}let f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: wrong value length");return{v:f,l:t.subarray(n+c)}}},_int:{encode(e){let{Err:t}=we;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}=we;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 pe(e)}},toSig(e,t){let{Err:r,_int:n,_tlv:o}=we;if(t!==void 0){if(qe(t,"maxScalarBytes"),t<1)throw new r("invalid signature: maxScalarBytes must be positive")}let i=Q(e,void 0,"signature"),{v:c,l:f}=o.decode(48,i);if(f.length)throw new r("invalid signature: left bytes after parsing");let{v:d,l:u}=o.decode(2,c),{v:p,l:w}=o.decode(2,u);if(w.length)throw new r("invalid signature: left bytes after parsing");if(t!==void 0&&(d.length>t||p.length>t))throw new r("invalid signature: integer too large");return{r:n.decode(d),s:n.decode(p)}},hexFromSig(e){let{_tlv:t,_int:r}=we;Te(e,{r:"bigint",s:"bigint"},{},"sig");let n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}},kt=(()=>(Object.freeze(we._tlv),Object.freeze(we._int),Object.freeze(we)))();/*! 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,Be,r);let[[n,o],[i,c]]=t,f=Jn(c*e,r),d=Jn(-o*e,r),u=e-f*n-d*i,p=-f*o-d*c,w=u<Be,S=p<Be;if(w)u=-u;if(S)p=-p;let A=ct(Math.ceil(Ye(r)/2))+Pe;if(u<Be||u>=A||p<Be||p>=A)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:w,k1:u,k2neg:S,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){Te(e);let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];if(he(r.lowS,"lowS"),he(r.prehash,"prehash"),r.format!==void 0)rn(r.format);return r}var Be=BigInt(0),Pe=BigInt(1),Qn=BigInt(2),nn=BigInt(3),cs=BigInt(4);function er(e,t={}){let r=Kn("weierstrass",e,t),{Fp:n,Fn:o,CURVE:i}=r,{h:c,n:f}=i;Te(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:d,allowInfinityPoint:u,clearCofactor:p,isTorsionFree:w,fromBytes:S,toBytes:A}=t,F=t.randomBytes===void 0?wt:t.randomBytes;if(d){if(!n.is0(i.a)||typeof d.beta!=="bigint"||!Array.isArray(d.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let C=d?{beta:d.beta,basises:d.basises.map((h)=>[...h])}:void 0,T=nr(n,o);function q(){if(!n.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function L(h,m,y){if(m.is0()){if(!u)throw Error("bad point: ZERO");return Uint8Array.of(0)}let{x:k,y:O}=m.toAffine(),v=n.toBytes(k);if(he(y,"isCompressed"),y){q();let H=!n.isOdd(O);return xe(tr(H),v)}else return xe(Uint8Array.of(4),v,n.toBytes(O))}function re(h){Q(h,void 0,"Point");let{publicKey:m,publicKeyUncompressed:y}=T,k=h.length,O=h[0],v=h.subarray(1);if(u&&k===1&&O===0)return{x:n.ZERO,y:n.ZERO};if(k===m&&(O===2||O===3)){let H=n.fromBytes(v);if(!n.isValid(H))throw Error("bad point: is not on curve, wrong x");let D=st(H),N;try{N=n.sqrt(D)}catch(z){let K=z instanceof Error?": "+z.message:"";throw Error("bad point: is not on curve, sqrt error"+K)}q();let U=n.isOdd(N);if((O&1)===1!==U)N=n.neg(N);return{x:H,y:N}}else if(k===y&&O===4){let H=n.BYTES,D=n.fromBytes(v.subarray(0,H)),N=n.fromBytes(v.subarray(H,H*2));if(!ze(D,N))throw Error("bad point: is not on curve");return{x:D,y:N}}else throw Error(`bad point: got length ${k}, expected compressed=${m} or uncompressed=${y}`)}let ne=A===void 0?L:A,me=S===void 0?re:S,ce=n.mul(i.b,nn),te=n.is0(i.a)?(h)=>n.ZERO:(h)=>n.mul(i.a,h);function st(h){let m=n.sqr(h),y=n.mul(m,h);return n.add(n.add(y,n.mul(h,i.a)),i.b)}function ze(h,m){let y=n.sqr(m),k=st(h);return n.eql(y,k)}if(!ze(i.Gx,i.Gy))throw Error("bad curve params: generator point");let se=n.mul(n.pow(i.a,nn),cs),pt=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(se,pt)))throw Error("bad curve params: a or b");function Ne(h,m,y=!1){if(!n.isValid(m)||y&&n.is0(m))throw Error(`bad point coordinate ${h}`);return typeof m==="object"&&m!==null?n.create(m):m}function We(h){if(!(h instanceof P))throw Error("Weierstrass Point expected")}function gt(h){if(!C||!C.basises)throw Error("no endo");return as(h,C.basises,o.ORDER)}function Ce(h,m,y,k){if(!o.isValid(k))throw RangeError("invalid scalar: out of range");if(C){let{k1neg:O,k1:v,k2neg:H,k2:D}=gt(k),N=new P(n.mul(y.X,C.beta),y.Y,y.Z);h.push(O?y.negate():y,H?N.negate():N),m.push(v,D)}else h.push(y),m.push(k)}let mt=new WeakSet;class P{static BASE=new P(i.Gx,i.Gy,n.ONE);static ZERO=new P(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(h,m,y){this.X=Ne("x",h),this.Y=Ne("y",m,!0),this.Z=Ne("z",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){let{x:m,y}=h||{};if(!h||!n.isValid(m)||!n.isValid(y))throw Error("invalid affine point");if(h instanceof P)throw Error("projective point not allowed");if(n.is0(m)&&n.is0(y))return P.ZERO;return new P(m,y,n.ONE)}static fromBytes(h){let m=P.fromAffine(me(Q(h,void 0,"point")));return m.assertValidity(),m}static fromHex(h){return P.fromBytes(xt(h))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=6,m=!0){if(Oe.setWindowSize(this,h),!m)this.multiply(nn);return this}assertValidity(){let h=this;if(h.is0()){if(u&&n.is0(h.X)&&n.eql(h.Y,n.ONE)&&n.is0(h.Z))return;throw Error("bad point: ZERO")}if(mt.has(h))return;let{x:m,y}=h.toAffine();if(!n.isValid(m)||!n.isValid(y))throw Error("bad point: x or y not field elements");if(!ze(m,y))throw Error("bad point: equation left != right");if(!h.isTorsionFree())throw Error("bad point: not in prime-order subgroup");mt.add(h)}hasEvenY(){let{y:h}=this.toAffine();if(!n.isOdd)throw Error("Field doesn't support isOdd");return!n.isOdd(h)}equals(h){We(h);let{X:m,Y:y,Z:k}=this,{X:O,Y:v,Z:H}=h,D=n.eql(n.mul(m,H),n.mul(O,k)),N=n.eql(n.mul(y,H),n.mul(v,k));return D&&N}negate(){return new P(this.X,n.neg(this.Y),this.Z)}double(){let{X:h,Y:m,Z:y}=this,{ZERO:k,ZERO:O,ZERO:v}=n,H=n.mul(h,h),D=n.mul(m,m),N=n.mul(y,y),U=n.mul(h,m);return U=n.add(U,U),v=n.mul(h,y),v=n.add(v,v),k=te(v),O=n.mul(ce,N),O=n.add(k,O),k=n.sub(D,O),O=n.add(D,O),O=n.mul(k,O),k=n.mul(U,k),v=n.mul(ce,v),N=te(N),U=n.sub(H,N),U=te(U),U=n.add(U,v),v=n.add(H,H),H=n.add(v,H),H=n.add(H,N),H=n.mul(H,U),O=n.add(O,H),N=n.mul(m,y),N=n.add(N,N),H=n.mul(N,U),k=n.sub(k,H),v=n.mul(N,D),v=n.add(v,v),v=n.add(v,v),new P(k,O,v)}add(h){We(h);let{X:m,Y:y,Z:k}=this,{X:O,Y:v,Z:H}=h,{ZERO:D,ZERO:N,ZERO:U}=n,Z=n.mul(m,O),z=n.mul(y,v),K=n.mul(k,H),oe=n.add(m,y),W=n.add(O,v);oe=n.mul(oe,W),W=n.add(Z,z),oe=n.sub(oe,W),W=n.add(m,k);let X=n.add(O,H);return W=n.mul(W,X),X=n.add(Z,K),W=n.sub(W,X),X=n.add(y,k),D=n.add(v,H),X=n.mul(X,D),D=n.add(z,K),X=n.sub(X,D),U=te(W),D=n.mul(ce,K),U=n.add(D,U),D=n.sub(z,U),U=n.add(z,U),N=n.mul(D,U),z=n.add(Z,Z),z=n.add(z,Z),K=te(K),W=n.mul(ce,W),z=n.add(z,K),K=n.sub(Z,K),K=te(K),W=n.add(W,K),Z=n.mul(z,W),N=n.add(N,Z),Z=n.mul(X,W),D=n.mul(oe,D),D=n.sub(D,Z),Z=n.mul(oe,z),U=n.mul(X,U),U=n.add(U,Z),new P(D,N,U)}subtract(h){return We(h),this.add(h.negate())}is0(){return this.equals(P.ZERO)}multiply(h){if(!o.isValidNot0(h))throw RangeError("invalid scalar: out of range");let{p:m,f:y}=Oe.mulSecret(this,h,c,ot);return ot([m,y])[0]}multiplyUnsafe(h){let m=this,y=h;if(!o.isValid(y))throw RangeError("invalid scalar: out of range");if(y===Be||m.is0())return P.ZERO;if(y===Pe)return m;if(Oe.hasWindowSize(this))return Oe.mulUnsafe(m,y,ot);let k=[],O=[];return Ce(k,O,m,y),St(P,k,O)}mulAddUnsafe(h,m,y){We(m);let k=[],O=[];return Ce(k,O,this,h),Ce(k,O,m,y),St(P,k,O)}toAffine(h){let m=this,y=h;if(y!=null&&!n.isValid(y))throw RangeError('"invertedZ" expected valid field element');let{X:k,Y:O,Z:v}=m;if(n.eql(v,n.ONE))return{x:k,y:O};let H=m.is0();if(y==null)y=H?n.ONE:n.inv(v);let D=n.mul(k,y),N=n.mul(O,y),U=n.mul(v,y);if(H)return{x:n.ZERO,y:n.ZERO};if(!n.eql(U,n.ONE))throw Error("invZ was invalid");return{x:D,y:N}}isTorsionFree(){if(c===Pe)return!0;if(w)return w(P,this);return Oe.mulUnsafe(this,f).is0()}clearCofactor(){if(c===Pe)return this;if(p)return p(P,this);return this.multiplyUnsafe(c)}isSmallOrder(){if(c===Pe)return this.is0();return this.clearCofactor().is0()}toBytes(h=!0){return he(h,"isCompressed"),this.assertValidity(),ne(P,this,h)}toHex(h=!0){return Ut(this.toBytes(h))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ot=(h)=>Wn(P,h),Oe=new Qt(P,F);if(Oe.bits>=6)P.BASE.precompute(6);return Object.freeze(P.prototype),Object.freeze(P),P}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={}){Xe(e);let{Fn:r}=e,n=t.randomBytes===void 0?wt:t.randomBytes,o=Object.assign(nr(e.Fp,r),{seed:Math.max(At(r.ORDER),16)});function i(A){try{let F=r.fromBytes(A);return r.isValidNot0(F)}catch(F){return!1}}function c(A,F){let{publicKey:C,publicKeyUncompressed:T}=o;try{let q=A.length;if(F===!0&&q!==C)return!1;if(F===!1&&q!==T)return!1;return!e.fromBytes(A).is0()}catch(q){return!1}}function f(A){return A=A===void 0?n(o.seed):A,_t(Q(A,o.seed,"seed"),r.ORDER)}function d(A,F=!0){return e.BASE.multiply(r.fromBytes(A)).toBytes(F)}function u(A){let{secretKey:F,publicKey:C,publicKeyUncompressed:T}=o,q=r._lengths;if(!Ze(A))return;let L=Q(A,void 0,"key").length,re=L===C||L===T,ne=L===F||!!q?.includes(L);if(re&&ne)return;return re}function p(A,F,C=!0){if(u(A)===!0)throw Error("first arg must be private key");if(u(F)===!1)throw Error("second arg must be public key");let T=r.fromBytes(A),q=e.fromBytes(F);if(q.is0())throw Error("invalid public key: point at infinity");return q.multiply(T).toBytes(C)}let w={isValidSecretKey:i,isValidPublicKey:c,randomSecretKey:f},S=Vn(f,d);return Object.freeze(w),Object.freeze(o),Object.freeze({getPublicKey:d,getSharedSecret:p,keygen:S,Point:e,utils:w,lengths:o})}function rr(e,t,r={}){Xe(e);let n=t;Y(n),Te(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),i=o.randomBytes===void 0?wt:o.randomBytes,c=o.hmac===void 0?(h,m)=>Xn(n,h,m):o.hmac,{Fp:f,Fn:d}=e,{ORDER:u,BITS:p}=d,w=At(u),S=Jt(i,w),{keygen:A,getPublicKey:F,getSharedSecret:C,utils:T,lengths:q}=ds(e,o),L={prehash:!0,lowS:typeof o.lowS==="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},re=u*Qn+Pe<f.ORDER;function ne(h){let m=u>>Pe;return h>m}function me(h,m){if(!d.isValidNot0(m))throw Error(`invalid signature ${h}: out of range 1..Point.Fn.ORDER`);return m}function ce(){if(!f.isOdd)throw Error("Field doesn't support isOdd")}function te(h,m,y){return ce(),(h===y?0:2)|Number(f.isOdd(m))}function st(){if(re)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function ze(h,m){rn(m);let y=q.signature,k=m==="compact"?y:m==="recovered"?y+1:void 0;return Q(h,k)}class se{r;s;recovery;constructor(h,m,y){if(this.r=me("r",h),this.s=me("s",m),y!=null){if(st(),![0,1,2,3].includes(y))throw Error("invalid recovery id");this.recovery=y}Object.freeze(this)}static fromBytes(h,m=L.format){ze(h,m);let y;if(m==="der"){if(h.length>2*d.BYTES+16)throw new kt.Err("invalid signature: DER signature too long");let{r:H,s:D}=kt.toSig(Q(h),d.BYTES+1);return new se(H,D)}if(m==="recovered")y=h[0],m="compact",h=h.subarray(1);let k=q.signature/2,O=h.subarray(0,k),v=h.subarray(k,k*2);return new se(d.fromBytes(O),d.fromBytes(v),y)}static fromHex(h,m){return this.fromBytes(xt(h),m)}assertRecovery(){let{recovery:h}=this;if(h==null)throw Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new se(this.r,this.s,h)}recoverPublicKey(h){let{r:m,s:y}=this,k=this.assertRecovery(),O=k===2||k===3?m+u:m;if(!f.isValid(O))throw Error("invalid recovery id: sig.r+curve.n != R.x");let v=f.toBytes(O),H=e.fromBytes(xe(tr((k&1)===0),v)),D=d.inv(O),N=Ne(Q(h,void 0,"msgHash")),U=d.create(-N*D),Z=d.create(y*D),z=e.BASE.mulAddUnsafe(U,H,Z);if(z.is0())throw Error("invalid recovery: point at infinify");return z.assertValidity(),z}hasHighS(){return ne(this.s)}toBytes(h=L.format){if(rn(h),h==="der")return xt(kt.hexFromSig(this));let{r:m,s:y}=this,k=d.toBytes(m),O=d.toBytes(y);if(h==="recovered")return st(),xe(Uint8Array.of(this.assertRecovery()),k,O);return xe(k,O)}toHex(h){return Ut(this.toBytes(h))}}Object.freeze(se.prototype),Object.freeze(se);let pt=o.bits2int===void 0?function(m){if(m.length>8192)throw Error("input is too large");let y=pe(m),k=m.length*8-p;return k>0?y>>BigInt(k):y}:o.bits2int,Ne=o.bits2int_modN===void 0?function(m){return d.create(pt(m))}:o.bits2int_modN,We=ct(p);function gt(h){return Mt("num < 2^"+p,h,Be,We),d.toBytes(h)}function Ce(h,m){return Q(h,void 0,"message"),m?Q(n(h),void 0,"prehashed message"):h}function mt(h,m,y){let{lowS:k,prehash:O,extraEntropy:v}=tn(y,L);h=Ce(h,O);let H=Ne(h),D=d.fromBytes(m);if(!d.isValidNot0(D))throw Error("invalid private key");let N=[gt(D),gt(H)];if(v!=null&&v!==!1){let K=v===!0?i(q.secretKey):v;N.push(Q(K,void 0,"extraEntropy"))}let U=xe(...N),Z=H;function z(K){let oe=pt(K);if(!d.isValidNot0(oe))return;let W=e.BASE.multiply(oe).toAffine(),X=d.create(W.x);if(X===Be)return;let le;if(S!==void 0){let it=pe(_t(S(w),u)),Lr=d.inv(d.mul(it,oe)),Nr=d.mul(it,Z),Cr=d.mul(it,D);le=d.create(Lr*d.create(Nr+Cr*X))}else{let it=Cn(oe,u);le=d.create(it*d.create(Z+X*D))}if(le===Be)return;let Lt=te(W.x,W.y,X),xn=le;if(k&&ne(le))xn=d.neg(le),Lt^=1;return new se(X,xn,re?void 0:Lt)}return{seed:U,k2sig:z}}function P(h,m,y={}){let{seed:k,k2sig:O}=mt(h,m,y);return In(n.outputLen,d.BYTES,c)(k,O).toBytes(y.format)}function ot(h,m,y,k={}){let{lowS:O,prehash:v,format:H}=tn(k,L);if(y=Q(y,void 0,"publicKey"),m=Ce(m,v),!Ze(h)){let D=h instanceof se?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+D)}ze(h,H);try{let D=se.fromBytes(h,H),N=e.fromBytes(y);if(N.is0())return!1;if(O&&D.hasHighS())return!1;let{r:U,s:Z}=D,z=Ne(m),K=d.inv(Z),oe=d.create(z*K),W=d.create(U*K),X=e.BASE.mulAddUnsafe(oe,N,W);if(X.is0())return!1;let le=X.toAffine();if(d.create(le.x)!==U)return!1;if(H==="recovered"&&D.recovery!==te(le.x,le.y,U))return!1;return!0}catch(D){return!1}}function Oe(h,m,y={}){let{prehash:k}=tn(y,L);return m=Ce(m,k),se.fromBytes(h,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:A,getPublicKey:F,getSharedSecret:C,utils:T,lengths:q,Point:e,sign:P,verify:ot,recoverPublicKey:Oe,Signature:se,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),o=BigInt(11),i=BigInt(22),c=BigInt(23),f=BigInt(44),d=BigInt(88),u=e*e*e%t,p=u*u*e%t,w=ae(p,r,t)*p%t,S=ae(w,r,t)*p%t,A=ae(S,sr,t)*u%t,F=ae(A,o,t)*A%t,C=ae(F,i,t)*F%t,T=ae(C,f,t)*C%t,q=ae(T,d,t)*T%t,L=ae(q,f,t)*C%t,re=ae(L,r,t)*p%t,ne=ae(re,c,t)*F%t,me=ae(ne,n,t)*u%t,ce=ae(me,sr,t);if(!sn.eql(sn.sqr(ce),e))throw Error("Cannot find square root");return ce}var sn=Ve(on.p,{sqrt:us}),ls=er(on,{Fp:sn,endo:fs}),ft=rr(ls,Sn),Ho=Object.create(null);class E 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 E("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 Ae=(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 E("size_zero");if(Ae(r)>t)throw new E("size_too_precise",`${r} has ${Ae(r)} decimals, max ${t}`);return r}function cn(e,t,r){let n=ut(e,"price");if(an(n))throw new E("price_zero");if(ps(n))return n;if(or(n)>5)throw new E("price_sig_figs",`${n} has ${or(n)} significant figures, max 5`);let o=ir[r]-t;if(Ae(n)>o)throw new E("price_too_precise",`${n} has ${Ae(n)} decimals, max ${o}`);return n}function Ge(e){let t=ut(e,"amount");if(an(t))throw new E("amount_zero");if(Ae(t)>6)throw new E("amount_too_precise",`${t} has ${Ae(t)} decimals, max 6`);return t}function cr(e,t,r,n,o){let i=Number(ut(e,"mid"));if(!(i>0))throw new E("price_zero","mid");if(!(r>=0&&r<1))throw new E("bad_slippage",String(r));let c=i*(t?1+r:1-r),f=Number(c.toPrecision(5)),d=Math.max(0,ir[o]-n);return cn(ut(f.toFixed(d),"price"),n,o)}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,o=(u,...p)=>{n.set(u.asset,u);for(let w of p)if(!r.has(w))r.set(w,u)},i=Je(e)?e:{};(Array.isArray(i.universe)?i.universe:[]).forEach((u,p)=>{if(!Je(u)||typeof u.name!=="string"||typeof u.szDecimals!=="number")return;o({coin:u.name,label:u.name,asset:p,szDecimals:u.szDecimals,kind:"perp",delisted:u.isDelisted===!0},u.name)});let f=Je(t)?t:{},d=new Map;for(let u of Array.isArray(f.tokens)?f.tokens:[])if(Je(u)&&typeof u.index==="number")d.set(u.index,u);for(let u of Array.isArray(f.universe)?f.universe:[]){if(!Je(u)||typeof u.index!=="number"||typeof u.name!=="string"||!Array.isArray(u.tokens))continue;let[p,w]=u.tokens,S=d.get(p),A=d.get(w);if(!S||typeof S.szDecimals!=="number")continue;let F=`${String(S.name)}/${String(A?.name??"?")}`;o({coin:u.name,label:F,asset:gs+u.index,szDecimals:S.szDecimals,kind:"spot",delisted:!1},u.name,F)}return{byName:r,byIndex:n}}function fn(e,t){let r=e.byName.get(t);if(!r)throw new E("unknown_asset",t);if(r.delisted)throw new E("asset_delisted",t);return r}function un(e,t){if(t>=dn)throw new E("builder_dex_unsupported",String(t));let r=e.byIndex.get(t);if(!r)throw new E("unknown_asset",String(t));return r}async function ke(e,t,r={}){let n=r.fetchImpl??fetch;try{let o=await n(dr[t],{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(r.timeoutMs??5000)});if(!o.ok)return{ok:!1,error:"hyperliquid_unavailable",detail:`status_${o.status}`};return{ok:!0,data:await o.json()}}catch(o){return{ok:!1,error:"hyperliquid_unavailable",detail:o.message}}}async function ln(e,t={}){let[r,n]=await Promise.all([ke({type:"meta"},e,t),ke({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 ke({type:"allMids"},e,t);if(!r.ok)return r;let n={};if(Je(r.data)){for(let[o,i]of Object.entries(r.data))if(typeof i==="string"&&/^\d+(\.\d+)?$/.test(i))n[o]=i}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 E("bad_tif",String(t));if(e.asset.delisted)throw new E("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 E("bad_cloid",e.cloid);let o={a:e.asset.asset,b:e.isBuy,p:n,s:r,r:e.reduceOnly??!1,t:{limit:{tif:t}}};if(e.cloid!==void 0)o.c=e.cloid.toLowerCase();return o}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 E("unknown_asset",String(t));if(t>=dn)throw new E("builder_dex_unsupported",String(t));if(!Number.isSafeInteger(e.oid)||e.oid<0)throw new E("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 E("nonce_required",String(e));return e}function vt(e){return{type:"usdClassTransfer",amount:Ge(e.amount),toPerp:e.toPerp,nonce:lr(e.nonce)}}function It(e){if(!xs.test(e.destination))throw new E("bad_address",e.destination);return{type:"withdraw3",destination:e.destination.toLowerCase(),amount:Ge(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 o=ws;for(let i=0;i<7;i++)if(t=(t<<lt^(t>>Bs)*_s)%As,t&Es)o^=lt<<(lt<<BigInt(i))-lt;br.push(o)}var yr=be(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(a(t,"rounds"),t<1||t>24)throw Error('"rounds" expected integer 1..24');for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)Qe[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,f=(i+2)%10,d=Qe[f],u=Qe[f+1],p=hr(d,u,1)^Qe[c],w=pr(d,u,1)^Qe[c+1];for(let S=0;S<50;S+=10)e[i+S]^=p,e[i+S+1]^=w}let n=e[2],o=e[3];for(let i=0;i<24;i++){let c=mr[i],f=hr(n,o,c),d=pr(n,o,c),u=gr[i];n=e[u],o=e[u+1],e[u]=f,e[u+1]=d}for(let i=0;i<50;i+=10){let c=e[i],f=e[i+1],d=e[i+2],u=e[i+3];e[i]^=~e[i+2]&e[i+4],e[i+1]^=~e[i+3]&e[i+5],e[i+2]^=~e[i+4]&e[i+6],e[i+3]^=~e[i+5]&e[i+7],e[i+4]^=~e[i+6]&e[i+8],e[i+5]^=~e[i+7]&e[i+9],e[i+6]^=~e[i+8]&c,e[i+7]^=~e[i+9]&f,e[i+8]^=~c&d,e[i+9]^=~f&u}e[0]^=Ss[r],e[1]^=ks[r]}b(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,o=24){if(a(e,"blockLen"),a(t,"suffix"),a(o,"rounds"),_e(n,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.canXOF=n,this.rounds=o,a(r,"outputLen"),!(0<e&&e<200))throw Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=I(this.state)}clone(){return this._cloneInto()}keccak(){_(this.state32),Ts(this.state32,this.rounds),_(this.state32),this.posOut=0,this.pos=0}update(e){g(this),s(e);let{blockLen:t,state:r,state32:n}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,c=t/4,f=i&&o>=t?I(e):void 0;for(let d=0;d<o;){if(f!==void 0&&this.pos===0&&d%4===0&&o-d>=t){for(let p=0,w=d/4;p<c;p++)n[p]^=f[w+p];d+=t,this.pos=t,this.keccak();continue}let u=Math.min(t-this.pos,o-d);for(let p=0;p<u;p++)r[this.pos++]^=e[d++];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){g(this,!1),s(e),this.finish();let t=this.state,{blockLen:r}=this;for(let n=0,o=e.length;n<o;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,o-n);e.set(t.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not enabled");return this.writeInto(e)}xof(e){return a(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(R(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,b(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:n,rounds:o,enableXOF:i}=this;return e||=new gn(t,r,n,i,o),e.blockLen=t,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=n,e.enableXOF=i,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}}var $s=(e,t,r,n={})=>B(()=>new gn(t,e,r),n);var He=$s(1,136,32);var et=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],De=(e)=>Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join(""),Fe=(e)=>`0x${De(e)}`;function Le(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||!/^[0-9a-fA-F]*$/.test(t))throw new E("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 E("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 E("eip712_value",`${r} not a uint`);if(n<0n||n>=1n<<BigInt(t))throw new E("eip712_range",r);return n}function Hs(e,t){switch(e.type){case"string":if(typeof t!=="string")throw new E("eip712_value",`${e.name} not a string`);return He(new TextEncoder().encode(t));case"bytes32":{let r=t instanceof Uint8Array?t:typeof t==="string"?Le(t):null;if(!r||r.length!==32)throw new E("eip712_value",`${e.name} not bytes32`);return r}case"address":{if(typeof t!=="string"||!/^0x[0-9a-fA-F]{40}$/.test(t))throw new E("eip712_value",`${e.name} not an address`);return Rt(BigInt(t))}case"bool":if(typeof t!=="boolean")throw new E("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 E("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=[He(new TextEncoder().encode(Ds(e,t)))];for(let i of t){if(!(i.name in r))throw new E("eip712_missing",i.name);n.push(Hs(i,r[i.name]))}let o=new Uint8Array(n.length*32);return n.forEach((i,c)=>o.set(i,c*32)),He(o)}function tt(e){let t=e.types[e.primaryType];if(!t)throw new E("eip712_type",e.primaryType);let r=wr("EIP712Domain",et,e.domain),n=wr(e.primaryType,t,e.message),o=new Uint8Array(66);return o[0]=25,o[1]=1,o.set(r,2),o.set(n,34),He(o)}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 de(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),de(e,t,1);else if(t<=0xffffn)e.push(205),de(e,t,2);else if(t<=0xffffffffn)e.push(206),de(e,t,4);else e.push(207),de(e,t,8);return}let n=(o)=>t+(1n<<BigInt(o));if(t>=-32n)e.push(Number(n(8)));else if(t>=-128n)e.push(208),de(e,n(8),1);else if(t>=-32768n)e.push(209),de(e,n(16),2);else if(t>=-2147483648n)e.push(210),de(e,n(32),4);else e.push(211),de(e,n(64),8)}function mn(e,t,r,n,o){if(t<=n)e.push(r|t);else if(o[0]!==null&&t<=255)e.push(o[0]),de(e,BigInt(t),1);else if(t<=65535)e.push(o[1]),de(e,BigInt(t),2);else e.push(o[2]),de(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 o of n)e.push(o);return}if(Array.isArray(t)){mn(e,t.length,144,15,[null,220,221]),t.forEach((n,o)=>Tt(e,n,`${r}[${o}]`));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 o of n)Tt(e,o,r),Tt(e,t[o],`${r}.${o}`);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 E("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 o=[nt(e),Br(r)];if(t===null)o.push(Uint8Array.of(0));else o.push(Uint8Array.of(1),Le(t));if(n!==null)o.push(Uint8Array.of(0),Br(n));let i=new Uint8Array(o.reduce((f,d)=>f+d.length,0)),c=0;for(let f of o)i.set(f,c),c+=f.length;return i}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:Fe(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,o=bn){if(!/^0x[0-9a-fA-F]+$/.test(o))throw new E("bad_hex",o);let i={...r,hyperliquidChain:n==="mainnet"?"Mainnet":"Testnet"},c={};for(let f of t){if(!(f.name in i))throw new E("eip712_missing",f.name);c[f.name]=i[f.name]}return{domain:{name:"HyperliquidSignTransaction",version:"1",chainId:Number(BigInt(o)),verifyingContract:_r},types:{[e]:t,EIP712Domain:et},primaryType:e,message:c}}var kr=(e,t)=>De(nt(e))===De(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((o)=>kr(e[o],t[o]))};function Ar(e,t){let{hyperliquidChain:r,signatureChainId:n,...o}=e,i=t.net==="mainnet"?"Mainnet":"Testnet";if(r!==void 0&&r!==i)throw new E("unsupported_action",`hyperliquidChain ${String(r)} on ${t.net}`);let c=(t.signatureChainId??bn).toLowerCase();if(n!==void 0&&String(n).toLowerCase()!==c)throw new E("unsupported_action",`signatureChainId ${String(n)} ≠ ${c}`);return o}function Ws(e,t){let r=t.assets;if(!e||typeof e!=="object")throw new E("unsupported_action","not an object");let n,o=e;switch(e.type){case"order":{if(!r)throw new E("meta_required","an order is checked against meta + spotMeta before it is signed");let c=Array.isArray(e.orders)?e.orders:[];if(c.length===0)throw new E("unsupported_action","order with no orders");n={type:"order",orders:c.map((f)=>Ms(f,r)),grouping:"na"};break}case"cancel":{let c=e.cancels??[];if(c.length===0)throw new E("unsupported_action","cancel with no cancels");n={type:"cancel",cancels:c.map((f)=>Ot({asset:r?un(r,f.a):{asset:f.a},oid:f.o}).cancels[0])};break}case"usdClassTransfer":{o=Ar(e,t);let c=o;if(typeof c.toPerp!=="boolean")throw new E("unsupported_action","toPerp");n=vt({amount:c.amount,toPerp:c.toPerp,nonce:c.nonce});break}case"withdraw3":{o=Ar(e,t);let c=o;n=It({destination:c.destination,amount:c.amount,time:c.time});break}default:throw new E("unsupported_action",String(e.type))}if(!(n.type==="order"||n.type==="cancel"?kr(n,o):zs(n,o)))throw new E("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 E("nonce_required");if(t.vaultAddress!==void 0&&!Sr.test(t.vaultAddress))throw new E("bad_address",t.vaultAddress);if(t.expiresAfter!==void 0&&(!Number.isSafeInteger(t.expiresAfter)||t.expiresAfter<=0))throw new E("expires_unsupported",String(t.expiresAfter));let d=t.vaultAddress?.toLowerCase()??null,u=t.expiresAfter??null,p=Ns(r,d,t.nonce,u),w=He(p),S=qs(w,t.net);return{kind:"l1",network:t.net,action:r,nonce:t.nonce,vaultAddress:d,expiresAfter:u,msgpackHex:De(nt(r)),hashInputHex:De(p),connectionId:Fe(w),typedData:S,digest:Fe(tt(S)),exchangeUrl:$t[t.net],posted:!1}}if(t.vaultAddress!==void 0)throw new E("vault_unsupported",r.type);if(t.expiresAfter!==void 0)throw new E("expires_unsupported",r.type);let n=Ps[r.type],o=r[n.nonceField];if(t.nonce!==void 0&&t.nonce!==o)throw new E("nonce_mismatch",`${t.nonce} ≠ ${o}`);let i=t.signatureChainId??bn,c={type:r.type,signatureChainId:i,hyperliquidChain:t.net==="mainnet"?"Mainnet":"Testnet",...Object.fromEntries(Object.entries(r).filter(([d])=>d!=="type"))},f=js(n.primaryType,n.fields,c,t.net,i);return{kind:"user",network:t.net,action:c,nonce:o,vaultAddress:null,expiresAfter:null,msgpackHex:null,hashInputHex:null,connectionId:null,typedData:f,digest:Fe(tt(f)),exchangeUrl:$t[t.net],posted:!1}}function Zs(e){let t=Le(e);if(t.length!==65)throw new E("bad_signature",`length ${t.length}`);let r=t[64]<27?t[64]+27:t[64];if(r!==27&&r!==28)throw new E("bad_signature",`v=${t[64]}`);return{r:Fe(t.slice(0,32)),s:Fe(t.slice(32,64)),v:r}}function Ys(e,t){let r=typeof e==="string"?Le(e):e,n=(f)=>BigInt(f).toString(16).padStart(64,"0");if(t.v!==27&&t.v!==28)throw new E("bad_signature",`v=${t.v}`);let o=Le(`${(t.v-27).toString(16).padStart(2,"0")}${n(t.r)}${n(t.s)}`),i=ft.recoverPublicKey(o,r,{prehash:!1}),c=ft.Point.fromBytes(i).toBytes(!1);return Fe(He(c.slice(1)).slice(12))}async function Or(e,t,r,n={}){let o=Ht(e,t);if(n.expectDigest!==void 0&&n.expectDigest.toLowerCase()!==o.digest)throw new E("signer_mismatch","the digest shown is not the digest being signed");if(!Sr.test(r.address))throw new E("bad_address",r.address);let{EIP712Domain:i,...c}=o.typedData.types,f=await r.signTypedData(o.typedData.domain,c,o.typedData.message),d=Zs(f),u=Ys(o.digest,d);if(u!==r.address.toLowerCase())throw new E("signer_mismatch",`recovered ${u}, expected ${r.address}`);return{dry:o,request:{action:o.action,nonce:o.nonce,signature:d,vaultAddress:o.vaultAddress,expiresAfter:o.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((o)=>Dt(o)&&typeof o.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 o=await n($t[t],{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(r.timeoutMs??1e4)}),i=await o.text(),c;try{c=JSON.parse(i)}catch{return{ok:!1,error:"exchange_unavailable",detail:`status_${o.status}: ${i.slice(0,200)}`}}return Ks(c)}catch(o){return{ok:!1,error:"exchange_unavailable",detail:o.message}}}var yn=/^0x[0-9a-fA-F]{40}$/,Me=(e)=>e.testnet?"testnet":"mainnet";function M(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 je(e,t={}){if(e instanceof E)return M(e.code,e.detail??e.message,t);let r=e?.code;return M(typeof r==="string"?r:"hl_error",e?.message??String(e),t)}function Js(e,t){let r=Ae(e),n=Ae(t),o=(BigInt(e.replace(".",""))*BigInt(t.replace(".",""))).toString().padStart(r+n+1,"0"),i=o.length-(r+n),c=o.slice(i).replace(/0+$/,"");return c?`${o.slice(0,i)}.${c}`:o.slice(0,i)}function Qs(e){let t=Le(e.privateKeyHex);return{address:e.address,async signTypedData(r,n,o){let i=Object.keys(n);if(i.length!==1)throw new E("eip712_type",`expected one primary type, got ${i.length}`);let c=tt({domain:r,types:{...n,EIP712Domain:et},primaryType:i[0],message:o}),f=ft.sign(c,t,{prehash:!1,format:"recovered"}),d=new Uint8Array(65);return d.set(f.slice(1,65),0),d[64]=f[0]+27,`0x${De(d)}`}}}var ge=(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,o]=await Promise.all([ke({type:"clearinghouseState",user:e},t,{fetchImpl:r.fetchImpl}),ke({type:"spotClearinghouseState",user:e},t,{fetchImpl:r.fetchImpl})]);if(!n.ok||!o.ok)return null;let i=ge(n.data)?n.data:{},c=ge(i.marginSummary)?i.marginSummary:{},f=ge(o.data)&&Array.isArray(o.data.balances)?o.data.balances:[];return{perps:{accountValue:rt(c.accountValue),withdrawable:rt(i.withdrawable)},spot:f.filter(ge).map((d)=>({coin:String(d.coin??"?"),total:String(d.total??"?"),hold:String(d.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}:M("bad_address","A Hyperliquid account is a 0x address of 40 hex characters.");let o=await r.ask("wallet:get",{});if(typeof o.error==="string"||o.ok===!1)return M(String(o.error??"wallet_read_failed"),"Could not read your workspace wallet — pass an address.");let c=(Array.isArray(o.addresses)?o.addresses:[]).filter((d)=>d.chain==="evm"&&typeof d.address==="string"&&yn.test(d.address)&&(!t||d.actor===t)),f=[...new Map(c.map((d)=>[d.address.toLowerCase(),d])).values()];if(f.length===0)return M("no_evm_address","Your workspace has no EVM address registered — pass one.");if(f.length>1)return M("ambiguous_address",`Several EVM addresses — pass one, or --actor <id>: ${f.map((d)=>`${d.actor??"?"} ${d.address}`).join(" · ")}`);return{ok:!0,address:f[0].address}}async function Bi(e,t){let r=Me(e),n=await Ft(e.address,e.actor,t);if(!(("ok"in n)&&n.ok===!0))return n;let o=await ke({type:"clearinghouseState",user:n.address},r,{fetchImpl:t.fetchImpl});if(!o.ok)return M(o.error,o.detail,{network:r});let i=ge(o.data)?o.data:{},c=ge(i.marginSummary)?i.marginSummary:{},f=(Array.isArray(i.assetPositions)?i.assetPositions:[]).map((d)=>ge(d)&&ge(d.position)?d.position:null).filter((d)=>d!==null).map((d)=>({coin:String(d.coin??"?"),size:String(d.szi??"?"),entryPx:d.entryPx??null,positionValue:d.positionValue??null,unrealizedPnl:d.unrealizedPnl??null,liquidationPx:d.liquidationPx??null,leverage:ge(d.leverage)?d.leverage:null}));return t.say([`${n.address} on ${r} — perps account ${rt(c.accountValue)??"—"} USDC, withdrawable ${rt(i.withdrawable)??"—"}`,...f.length?f.map((d)=>` ${d.coin.padEnd(8)} ${d.size.startsWith("-")?"short":"long "} ${d.size.replace(/^-/,"")} @ ${String(d.entryPx??"—")} value ${String(d.positionValue??"—")} pnl ${String(d.unrealizedPnl??"—")} liq ${String(d.liquidationPx??"—")}`):[" no open perps positions (spot holdings: one hl balance)"]]),{data:{ok:!0,network:r,address:n.address,accountValue:rt(c.accountValue),withdrawable:rt(i.withdrawable),positions:f}}}async function Ai(e,t){let r=Me(e),n=await Ft(e.address,e.actor,t);if(!(("ok"in n)&&n.ok===!0))return n;let o=await ke({type:"openOrders",user:n.address},r,{fetchImpl:t.fetchImpl});if(!o.ok)return M(o.error,o.detail,{network:r});if(!Array.isArray(o.data))return M("hyperliquid_unavailable","openOrders did not answer a list",{network:r});let i=o.data.filter(ge).map((c)=>({coin:String(c.coin??"?"),side:c.side==="B"?"buy":c.side==="A"?"sell":String(c.side??"?"),size:String(c.sz??"?"),limitPx:String(c.limitPx??"?"),oid:c.oid??null,timestamp:c.timestamp??null}));return t.say([`${n.address} on ${r} — ${i.length} resting order${i.length===1?"":"s"}`,...i.map((c)=>` ${c.side.padEnd(4)} ${c.size} ${c.coin} @ ${c.limitPx} oid ${String(c.oid)} cancel: one hl cancel ${c.coin} ${String(c.oid)}${r==="testnet"?" --testnet":""}`)]),{data:{ok:!0,network:r,address:n.address,count:i.length,orders:i}}}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=Me(e),n=e.side.toLowerCase();if(n!=="buy"&&n!=="sell")return M("bad_side","The side is buy or sell.");if(e.tif!==void 0&&e.limit===void 0&&e.tif!=="Ioc")return M("bad_tif","A market order is IOC by construction — --tif needs --limit.");let o=0.05;if(e.slippage!==void 0){if(!/^\d{1,4}$/.test(e.slippage)||Number(e.slippage)<1||Number(e.slippage)>2000)return M("bad_slippage","--slippage is basis points, 1–2000 (default 500 = 5%, the python SDK default).");o=Number(e.slippage)/1e4}let i=await ln(r,{fetchImpl:t.fetchImpl});if(!i.ok)return M(i.error,i.detail,{network:r});let c;try{c=fn(i.data,e.coin)}catch(w){return je(w,{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 f=null;if(e.limit===void 0){let w=await fr(r,{fetchImpl:t.fetchImpl});if(!w.ok)return M(w.error,w.detail,{network:r});if(f=w.data[c.coin]??null,f===null)return M("mid_unavailable",`allMids has no price for ${c.coin} (${c.label}) — a market order needs one; pass --limit <px>.`,{network:r})}let d=n==="buy",u=e.reduceOnly===!0,p=[e.limit!==void 0?`--limit ${e.limit}`:"",e.tif?`--tif ${e.tif}`:"",u?"--reduce-only":"",e.slippage?`--slippage ${e.slippage}`:""].filter(Boolean).join(" ");return{cmdline:`one hl order ${n} ${e.size} ${e.coin}${p?` ${p}`:""}`,build(w){let S=e.limit!==void 0?pn({asset:c,isBuy:d,sz:e.size,px:e.limit,tif:e.tif??"Gtc",reduceOnly:u}):ur({asset:c,isBuy:d,sz:e.size,mid:f,slippage:o,reduceOnly:u}),A=S.orders[0],F=c.kind==="spot"?"spot":"perps",C=Js(A.s,A.p),T=A.t.limit.tif,q=e.limit===void 0?`now, at ${d?"up to":"no less than"} ${A.p} (mid ${f} ${d?"+":"−"} ${o*100}%) — IOC: fills what it can at that cap, cancels the rest`:T==="Gtc"?`at ${A.p} or better — Gtc: rests on the book until filled or cancelled`:T==="Ioc"?`at ${A.p} or better — IOC: fills what it can now, cancels the rest`:`at ${A.p} — Alo (post-only): refused if it would take liquidity`,L=[`${d?"Buy":"Sell"} ${A.s} ${c.label} (${F}, asset ${A.a}) ${q}.`,`${d?"At most":"About"} ${C} USDC notional before fees.`,c.kind==="spot"?d?"Pays USDC from your SPOT balance.":`Sells ${c.label.split("/")[0]} you hold in SPOT for USDC.`:`${u?"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:S,opts:{net:r,nonce:w,assets:i.data},words:L,facts:{coin:c.coin,label:c.label,kind:c.kind,asset:A.a,side:n,size:A.s,price:A.p,tif:T,reduceOnly:u,notionalUsdc:C,...f?{mid:f,slippageBps:Math.round(o*1e4)}:{}}}}}}async function Si(e,t){let r=Me(e);if(!/^\d{1,16}$/.test(e.oid)||!Number.isSafeInteger(Number(e.oid)))return M("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 M(n.error,n.detail,{network:r});let o;try{o=fn(n.data,e.coin)}catch(c){return je(c,{network:r})}let i=Number(e.oid);return{cmdline:`one hl cancel ${e.coin} ${e.oid}`,build(c){return{action:Ot({asset:o,oid:i}),opts:{net:r,nonce:c,assets:n.data},words:[`Cancel resting order ${i} on ${o.label} (asset ${o.asset}). Nothing is bought or sold; an order already filled cannot be cancelled and Hyperliquid will say so.`],facts:{coin:o.coin,label:o.label,asset:o.asset,oid:i}}}}}async function ki(e,t){let r=Me(e),n=(e.to??"").toLowerCase();if(n!=="perps"&&n!=="spot")return M("bad_to","--to perps (spot → perps) or --to spot (perps → spot).");let o=n==="perps";try{Ge(e.amount)}catch(i){return je(i,{network:r})}return{cmdline:`one hl transfer ${e.amount} --to ${n}`,build(i){let c=vt({amount:e.amount,toPerp:o,nonce:i});return{action:c,opts:{net:r},words:[`Move ${c.amount} USDC from ${o?"SPOT to PERPS":"PERPS to SPOT"} on the same Hyperliquid account. Nothing leaves Hyperliquid; ONE takes nothing.`,o?"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:c.amount,toPerp:o}}}}}async function Oi(e,t,r){let n=Me(e);if(e.to!==void 0&&!yn.test(e.to))return M("bad_address","--to is an Arbitrum 0x address of 40 hex characters.");try{Ge(e.amount)}catch(i){return je(i,{network:n})}let o=null;if(!e.live&&e.to===void 0){let i=await Ft(e.address,e.actor,t);if(!(("ok"in i)&&i.ok===!0))return{data:{...i.data,next:"Name the destination: --to 0x… (a live withdraw defaults to the vault's own address)"}};o=i.address}return{cmdline:`one hl withdraw ${e.amount}${e.to?` --to ${e.to}`:""}`,build(i,c){let f=c??o,d=e.to??f;if(!d)throw new E("bad_address","no destination");let u=f===null||d.toLowerCase()!==f.toLowerCase();if(r&&c!==null&&u)throw new Fr("to_other_refused",`An agent withdraws only to its own address (${c}); ${d} is another. A person signs that one.`);let p=It({destination:d,amount:e.amount,time:i});return{action:p,opts:{net:n},words:[`Send ${p.amount} USDC from the PERPS balance${f?` of ${f}`:""} to ${d} on Arbitrum.${u?" 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:u}}}}}function to(e,t){let r=e.dir??".",n=l(t.env);if(n){let o=t.realpath(r),i=t.realpath(Xs(t.home,".one","agents"));if(!(o!==null&&i!==null&&o.startsWith(i+Gs)))return M("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 M("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 M("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 ke({type:"userAbstraction",user:e},t,{fetchImpl:r.fetchImpl});return n.ok?n.data:null}async function vi(e,t,r,n,o={}){let i=Me(t),c=t.live?to(t,n):null;if(c)return{data:{network:i,...c.data}};let f=await r();if("data"in f)return{data:{network:i,...f.data}};if(!t.live){let L,re;try{L=f.build(n.now(),null),re=Ht(L.action,L.opts)}catch(te){return je(te,{network:i})}let ne=o.abstractionFor??null;if(e==="transfer"&&!ne){let te=await Ft(void 0,void 0,n);if("ok"in te&&te.ok===!0)ne=te.address}let me=e==="transfer"?await Dr(ne,i,n):void 0,ce=`${f.cmdline}${i==="testnet"?" --testnet":""} --live --dir <your vault folder>`;return n.say([`DRY RUN — nothing signed, nothing sent · ${e} on ${i}`,...L.words.map((te)=>` ${te}`),...e==="transfer"?[Hr(me),...ne?[`account ${ne}`]:[]]:[],...Tr(re),`next ${ce}`]),{data:{ok:!0,live:!1,posted:!1,network:i,verb:e,consequence:L.words,...L.facts,...e==="transfer"?{abstraction:me??null,account:ne}:{},...$r(re),next:ce}}}let d=await n.unlock(t.dir??".");if("error"in d)return M("vault_unavailable",d.error,{network:i,next:"Name the folder that holds .one/wallet.json: --dir ~/.one/<you>"});let u=d.keys.find((L)=>L.chain==="evm");if(!u)return M("no_evm_key",`The vault at ${t.dir??"."} holds no EVM key.`,{network:i});let p=Qs(u),w,S;try{w=f.build(n.now(),p.address),S=Ht(w.action,w.opts)}catch(L){return je(L,{network:i,signer:p.address})}let A=await Ir(p.address,i,n),F=e==="transfer"?await Dr(p.address,i,n):void 0;if(n.say([`LIVE · ${e} on ${i} · signer ${p.address} (the vault's EVM key)`,...Rr("before",A),...w.words.map((L)=>` ${L}`),...e==="transfer"?[Hr(F)]:[],...Tr(S)]),!t.yes){if(!await n.confirm(`Sign this digest with ${p.address} and post it to Hyperliquid ${i}? [y/N] `))return{data:{ok:!1,error:"declined",network:i,signer:p.address,posted:!1,detail:"Nothing signed, nothing sent."}}}let C;try{({request:C}=await Or(w.action,w.opts,p,{expectDigest:S.digest}))}catch(L){return je(L,{network:i,signer:p.address,posted:!1})}let T=await vr(C,i,{fetchImpl:n.fetchImpl}),q=await Ir(p.address,i,n);return n.say([`exchange ${JSON.stringify(T.ok?T.response:{error:T.error,detail:T.detail,response:T.response??null})}`,...Rr("after ",q)]),{data:{ok:T.ok,...T.ok?{}:{error:T.error,detail:T.detail},live:!0,posted:!0,network:i,verb:e,signer:p.address,...w.facts,...e==="transfer"?{abstraction:F??null}:{},...$r(S),signature:C.signature,exchange:T.ok?T.response:T.response??null,balanceBefore:A,balanceAfter:q}}}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,4 +0,0 @@
|
|
|
1
|
-
var Ue=900000,ee=120000;function K(n){return["ONE sweep order",`workspace: ${n.workspace}`,`agent: ${n.actor}`,`chain: ${n.chain}`,`destination: ${n.destination}`,`amount: ${n.amount.toString()}`,`nonce: ${n.nonce}`,`expires: ${n.expiresAt}`].join(`
|
|
2
|
-
`)}function te(n){return["ONE agent handover",`agent: ${n.agent}`,`from: ${n.from}`,`to: ${n.to}`,`chain: ${n.chain}`,`nonce: ${n.nonce}`,`expires: ${n.expiresAt}`].join(`
|
|
3
|
-
`)}
|
|
4
|
-
export{Ue,ee,K,te};
|