oneie 5.9.0 → 5.10.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 +82 -3
- package/dist/package.json +2 -2
- package/dist/src/age-asypk941.js +1 -0
- package/dist/src/client-s5zcqyrf.js +1 -0
- package/dist/src/{evm-tx-cqhm9rtt.js → evm-tx-vkge2q9k.js} +1 -1
- package/dist/src/hl-run-mmq8z4kg.js +1 -0
- package/dist/src/index-h9b7545x.js +4 -0
- package/dist/src/index-w3wb5pdz.js +12 -0
- package/dist/src/index-zrktm90c.js +2062 -0
- package/dist/src/index.js +674 -655
- package/dist/src/message-key-1qtskhbc.js +1 -0
- package/dist/src/{message-lock-thr851d5.js → message-lock-ycej5rwa.js} +2 -2
- package/dist/src/sweep-order-zwbxh4zc.js +1 -0
- package/dist/src/sweep-runner-v10h6as5.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-h3nrt8bx.js +0 -4
- package/dist/src/index-st6k9vhc.js +0 -2062
- package/dist/src/message-key-yczrxszr.js +0 -1
- package/dist/src/sweep-order-jrq2hkye.js +0 -1
- package/dist/src/sweep-runner-jftw9em7.js +0 -1
package/README.md
CHANGED
|
@@ -9,8 +9,8 @@ npx oneie
|
|
|
9
9
|
One command, no sign-up, no form, no password:
|
|
10
10
|
|
|
11
11
|
1. **A key**, made on this machine. Shared with nobody, not even ONE.
|
|
12
|
-
2. **
|
|
13
|
-
|
|
12
|
+
2. **Wallets on six blockchains** from that key: Sui, Ethereum, Base,
|
|
13
|
+
Solana, Bitcoin and ASI (five addresses; Ethereum and Base share one).
|
|
14
14
|
3. **A product** in your own shop.
|
|
15
15
|
4. **A test sale**, end to end.
|
|
16
16
|
5. **It stops and asks you** before any real money moves.
|
|
@@ -111,6 +111,7 @@ one agent new <name> --profile core|commerce|asi
|
|
|
111
111
|
one agent validate | lint | compile --target mcp|a2a|web|skillmd
|
|
112
112
|
one agent publish # sync to your ONE workspace
|
|
113
113
|
one agent eval # run frontmatter evals (also: one skill eval)
|
|
114
|
+
one agent keys --caller K --ssh K --sui K --owner K # which chip key does which job; refuses the owner's key
|
|
114
115
|
one skill new | import <ref> | publish
|
|
115
116
|
one init --name N --email E # zero-to-live: register + workspace + agent + skills
|
|
116
117
|
one dev # boot the local CF stack: build → D1 migrate → wrangler dev
|
|
@@ -178,6 +179,22 @@ is kept as a new version (`~/.one/browser/paths/`, `--sync` also as a workflow:
|
|
|
178
179
|
steps). Live verbs need the verbs viewer (`one-view --caps` says `verbs`); until it is installed,
|
|
179
180
|
every live command says so and starts nothing. Paths are kept per workspace (`--workspace <slug>`, or `ONE_WORKSPACE`), readable only by you; a kept path holds no typed words, only `{{parameters}}` you pass to `run --params`. The viewer is found under `HERDR_APP_HOME` (default `~/.config/herdr-app`). Spec: `text/browser-commands.md`.
|
|
180
181
|
|
|
182
|
+
## Directories — file a business in ONE's Browser, you press submit
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
one directories list --category general --free # the registry (306 directories)
|
|
186
|
+
one directories start acme google-business-profile elocal # queue a run: a frozen pack per directory
|
|
187
|
+
one directories run acme --batch 10 # fill the queued forms in acme's agent tab; you submit
|
|
188
|
+
one directories done acme <row-id> --live <listing-url> # record a row: submitted, then live
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Each client gets its own agent tab and cookie jar (`--profile agent-dir-<workspace>`). The hand types only
|
|
192
|
+
what it is sure of (business name, phone, email, website, address, city, tagline, description) and
|
|
193
|
+
leaves the rest to you by name: dropdowns, uploads, consent boxes, anything ambiguous, and the submit.
|
|
194
|
+
It never solves a challenge, makes an account or keeps a password. A directory filled once is kept
|
|
195
|
+
as a path and replays for the next client with no model. Until the verbs viewer is installed, `run`
|
|
196
|
+
prints the plan and opens nothing. Spec: `text/directory-browser-plan.md`.
|
|
197
|
+
|
|
181
198
|
## Tasks — see, sequence, act
|
|
182
199
|
|
|
183
200
|
```bash
|
|
@@ -244,7 +261,7 @@ A key is 24 words you write on paper. ONE never holds it and cannot recover it.
|
|
|
244
261
|
one key new # mint 24 words, printed ONCE, for paper (v2: standard BIP-44 paths — what one.ie mints)
|
|
245
262
|
one key new --derivation v1 # the original ONE derivation (HKDF labels)
|
|
246
263
|
one key recover # rebuild from your words — prints BOTH address sets
|
|
247
|
-
one key public # the public identity + four
|
|
264
|
+
one key public # the public identity + its addresses (five under v2, four under v1); both sets unless you name --derivation
|
|
248
265
|
one key verify # compare this key's public identity with the server: locked | verified | mismatch | unregistered
|
|
249
266
|
```
|
|
250
267
|
|
|
@@ -309,6 +326,9 @@ one wallet register --from keys.json --workspace <slug> # register the PU
|
|
|
309
326
|
one wallet transactions --workspace <slug> --limit 50 # unified feed across every settlement rail
|
|
310
327
|
one wallet faucet <address> --chain sui # fund from testnet — sui/sol auto-fund, others return a manual URL
|
|
311
328
|
one wallet send <to> --chain SUI --amount 5 --payment-tx <hash> --workspace <slug>
|
|
329
|
+
one wallet request 25 USD --card --memo "Logo design" # pay:create: ask someone to pay you exactly $25 by card on your shop's own Stripe; prints the link (/u/<ws>/shop/checkout?req=preq_…). The amount lives on the request, never the link; --contact <actorId> attributes it, --days 1-90 (default 30). Card only: a coin request stays on wallet:invoice (`request 25 USD` without --card)
|
|
330
|
+
one wallet pay-by-name on|off|status # let the groups you tick pay you by name (they read your receive addresses, never a balance); off by default, status reads it; only a person's own key sets it — wallet:update { payByName } / wallet:get { view: 'pay-by-name' }. `on` reaches nobody until you tick groups on /request (wallet:update { payByNameGroups }); the CLI verb has no group flag yet. Gift links (/claim) have no CLI verb: their one-time key lives only in the payer's browser
|
|
331
|
+
one wallet keys --net testnet # your key map: YOUR KEY → each wallet it signs for (label, role, rules); read-only, --json for the raw keyMap; the key comes from ONE_API_KEY / ONEIE_API_KEY (prefer it to --key, which lands in shell history)
|
|
312
332
|
one wallet keygen # mint a self-hosted 4-chain wallet locally (a fresh one is v2), offline
|
|
313
333
|
one wallet paper # reprint the 24 words for paper — terminal only, same refusals as `one key new`
|
|
314
334
|
```
|
|
@@ -325,6 +345,18 @@ one swap assets # every alias, chain, decimals and wh
|
|
|
325
345
|
one hl balance 0x… # Hyperliquid perps + spot (never summed); no address = your EVM wallet
|
|
326
346
|
```
|
|
327
347
|
|
|
348
|
+
### Trade Hyperliquid — in dollars, with leverage
|
|
349
|
+
|
|
350
|
+
```bash
|
|
351
|
+
one hl leverage BTC 3 # set BTC to 3x isolated (dry: the action + digest; nothing sent)
|
|
352
|
+
one hl leverage ETH 5 --cross --live # sign with your vault and post; moves no money
|
|
353
|
+
one hl buy BTC --usd 20 --lev 5 # $20 at 5x: size = 20 × 5 ÷ mid, floored; leverage first if it differs
|
|
354
|
+
one hl sell ETH --usd 25 # $25 short at the account's current leverage
|
|
355
|
+
one hl buy BTC --usd 20 --lev 5 --live --dir ~/.one/you
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
Every `hl` action is dry until `--live`, which opens the vault in `--dir`, asks `[y/N]` (`--yes` skips it) and posts straight to Hyperliquid from your machine. `buy`/`sell` never order more than you asked for: the size is floored to the coin's lot size, and an order worth under Hyperliquid's $10 minimum is refused before anything is signed. With `--lev`, when your current setting on that coin differs (or cannot be read), `updateLeverage` goes first and the order is sent only if Hyperliquid accepts it.
|
|
359
|
+
|
|
328
360
|
`swap` never signs and ONE never holds the coins: you send from your own wallet to a NEAR Intents 1Click deposit address. Quotes are dry until `--live`; a live quote is read back from 1Click directly and checked against what you typed (assets, amount, slippage, fees, recipient, refund address) before the CLI prints `Send exactly … before …` — any mismatch prints `quote_mismatch` and nothing to send. Every answer says `network: mainnet`: 1Click has no testnet, so a live deposit is real money. Pass `--mine <your addresses>` to require that delivery and refunds go to them — off a terminal (scripts, agents, `--json`) a live quote needs it, or it stops at `mine_required` before anything is minted. `one swap status <addr> --mine … --amount …` prints the send line again only when 1Click's record passes the same check against the amount you name (add `--slippage` if you minted with one); without `--amount` it says `amount_not_given` and prints nothing to send. Every fee shown comes from the live quote.
|
|
329
361
|
|
|
330
362
|
`register` reads a `wallet keygen` output but transmits only its four address fields — the map it sends is built key-by-key from a fixed chain whitelist, so a `mnemonic` or `privateKey` in that file has no route onto the wire. The write is first-write-wins per chain and cannot be corrected afterwards (`address_conflict`), so it prints the addresses and asks for confirmation; `--yes` skips the prompt for scripted provisioning (needed when the JSON arrives on stdin, which leaves no terminal to answer with).
|
|
@@ -341,6 +373,8 @@ one finance pnl [--months N] # the P&L by month; open rul
|
|
|
341
373
|
one ramp status # add money / cash out: open or not, every reason, what comes next (anyone)
|
|
342
374
|
one front-desk set <slug> --file playbook.json # a client's AI front desk playbook: answers, qualifying questions, booking rules, hand-off (owner)
|
|
343
375
|
one front-desk get <slug> # read the playbook back as written (owner)
|
|
376
|
+
one sms send <to> <body> --purpose marketing [--workspace S] [--campaign ID] # one text from your workspace's own Twilio number, behind the consent gate
|
|
377
|
+
one whatsapp connect <phoneNumberId> --waba <id> [--workspace S] [--token-stdin] [--dry-run] # connect a client's own WhatsApp Business number; the token from WHATSAPP_TOKEN or stdin, never an argument
|
|
344
378
|
one workflow list --slug S # list workflows for a workspace
|
|
345
379
|
one workflow pull <id> --slug S [--out D] # round-trip a workflow's step graph to a local file
|
|
346
380
|
one workflow push <id> <file> --slug S [--commit] # apply a diff — simulates first, --commit persists
|
|
@@ -353,12 +387,38 @@ one broadcast list | send <id> # blasts to a workspace au
|
|
|
353
387
|
one segment list | preview <id> # audience segments — live count + sample
|
|
354
388
|
one newsletter pull <id> | push <id> <file> # round-trip newsletter content as a local file
|
|
355
389
|
one social list --group G | create --group G ... # draft/publish/list social posts
|
|
390
|
+
one social queue [--group G] # what waits for approval; an owner/admin approves on the social page
|
|
356
391
|
one fn run <name> '{json}' | list # call an allowlisted analytics/routing RPC
|
|
357
392
|
one coordinate recall [about] | reputation [uid] # cross-session memory and reputation
|
|
358
393
|
one group bulk-create --csv # idempotent batch client provisioning
|
|
359
394
|
one shop init [--facts F] [--workspace S] # seed the twelve-page shop pack; a fact left out stays a VISIBLE placeholder
|
|
360
395
|
```
|
|
361
396
|
|
|
397
|
+
The front desk command is `front-desk` on the command line and `frontDesk` in `src/index.ts` — the same command. The playbook is a JSON file (`business`, `greeting`, `answer[]`, `questions[]`, `booking`, `handoff`); the front desk follows it from the next chat turn, and booking checks its questions once a service is named. Only the workspace owner can write or read it.
|
|
398
|
+
|
|
399
|
+
`one sms send` reaches only people who texted JOIN, or YES to the front desk's invitation; STOP refuses it. From a key every text goes out as marketing — replies and invitations come only from the front desk itself. Exit 0 sent · 1 refused (consent, a bad number, forbidden) · 3 cannot run (no Twilio number or account connected, Composio unreachable).
|
|
400
|
+
|
|
401
|
+
## Secrets — `one secrets` and `one reset`
|
|
402
|
+
|
|
403
|
+
A `.env` that is safe to commit: names stay readable, every value is sealed to your paper key and to your own devices. No other person and no agent ever holds a key to it. `seal` runs offline, never prompts, never prints a value or a line of the `.env`, and answers `--json` with exit 0 done / 1 refused; `give` and `list` call one.ie (`--api` to point elsewhere). The key is a key file (`--key`) or `ONE_WALLET_MNEMONIC`, never stdin.
|
|
404
|
+
|
|
405
|
+
```bash
|
|
406
|
+
one secrets seal [.env] [--out F] [--remove] [--open NAME] # .env → .env.sealed; every name is `use` unless --open names it; --remove deletes the .env only after every value opens back byte for byte
|
|
407
|
+
one secrets add-device [--name L] [--replace] # make this Mac a reader — a Secure Enclave key opened by Touch ID
|
|
408
|
+
one run [--file F] -- <command...> # (also `one secrets run`) a `use` name gets a door on 127.0.0.1 and its name, never its value; an `open` name gets its value in memory; nothing is written to disk
|
|
409
|
+
one secrets hash [file] # the sha256 of a sealed file, to set on your vault
|
|
410
|
+
one secrets give NAME --provider openai|anthropic|stripe|github|dataforseo [--check] # give a key to ONE, sealed to the lock ONE's vault names, signed by your agent's own key; afterwards only its last four characters show
|
|
411
|
+
one secrets list # your desk: the keys you gave ONE, who uses them, keys lent to you — names and meters, never values
|
|
412
|
+
one secrets audit [folder] # count secret-shaped names still in plaintext (env files under the folder; npm, wrangler, gh, aws, docker, netrc); names and files, never a value; exit 1 if the count rose above the lowest seen
|
|
413
|
+
one reset [--dir D] [--yes] # set .one aside (renamed .one.bak-<time>) so the next `oneie` is a first run; never deletes
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
`one run` never opens a `use` secret. The program gets `OPENAI_BASE_URL` (or `ANTHROPIC_BASE_URL`) pointing at a door on 127.0.0.1 that lives only while it runs, and `OPENAI_API_KEY=one-door-…`, a random pass that works only at that door and only for this run. Each call through the door goes to ONE's opener as `secrets:call`, by name. So `one run -- printenv` prints a pass and a local address, never a `use` value. The door refuses a browser (any request with an Origin) and any Host but its own. A `use` name not given to ONE, or given for a provider with no base-address variable (stripe, github, dataforseo, composio today), refuses and says which; it never falls through to opening. Mark a secret that cannot travel through ONE (a database password) `open`: change `NAME=age:` to `NAME=open:age:` in `.env.sealed` (the sealed value stays as it is), or seal with `one secrets seal --open NAME`. `one run` opens it in memory and prints the names it opens and the program they go to. The mark is in the sealed bytes, so changing one means setting the new hash on your vault. The opener answers whole, so a streamed answer is not streamed through the door.
|
|
417
|
+
|
|
418
|
+
`one secrets give` refuses a key that can make other keys (an admin key, a full Stripe secret key) unless you pass `--allow-flagged`; `--check` tests a key and stores nothing. A person gives on the seal page with a passkey touch, never here. Rotate with `--replaces <sigHash>`.
|
|
419
|
+
|
|
420
|
+
`one reset` shows the addresses and every balance it can read, then asks y/N on a person's terminal; a pipe, CI, an agent shell or `--json` is refused without `--yes`. It says plainly when the wallet holds real money: setting the folder aside moves nothing, and the next run makes a new key that cannot spend it. One `mv .one.bak-<time> .one` brings it back.
|
|
421
|
+
|
|
362
422
|
## Your own endpoints — a tenant's HTTPS, called by a workflow
|
|
363
423
|
|
|
364
424
|
Register an HTTPS endpoint you own and let a workflow `tool` step call it. The
|
|
@@ -377,6 +437,25 @@ one endpoint call <name> --input '{json}' # the same door a workflow `tool` st
|
|
|
377
437
|
`--workspace` on any of these is a workspace you must already control: one you
|
|
378
438
|
may not write is **refused**, never silently downgraded to your own.
|
|
379
439
|
|
|
440
|
+
### The one door the other way — your inbound webhook
|
|
441
|
+
|
|
442
|
+
Every workspace can have **one** inbound URL that any tool POSTs JSON events to
|
|
443
|
+
(Supermove's Invoke Webhook, a booking tool, a Zapier step). `lead` lands a lead,
|
|
444
|
+
`booked` marks the matching contact booked with its job value, and anything else
|
|
445
|
+
is kept as a signal and answered `unhandled`. The secret is in the path, so the
|
|
446
|
+
URL is printed **once**; minting again stops the old one.
|
|
447
|
+
|
|
448
|
+
```bash
|
|
449
|
+
one endpoint inbound [--workspace S] # make it, or rotate it (the old URL answers 401 from that moment)
|
|
450
|
+
one endpoint inbound --status # mint nothing: is one live, and when did a tool last call it
|
|
451
|
+
one lead cost [--variants] [--workspace S] # cost per booked move: ad spend per campaign against its bookings
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
The event a tool sends: `{ "event": "booked", "phone": "+15550100", "job_value_cents": 189900,
|
|
455
|
+
"booked_at": 1795000000, "source": "supermove", "external_id": "job-77" }`. The answer is
|
|
456
|
+
`{ ok, event, matched, action }`; a booking that matches nobody answers `unmatched`. A `booked`
|
|
457
|
+
event needs `external_id` or `booked_at`, or it is refused (`external_id_or_booked_at_required`).
|
|
458
|
+
|
|
380
459
|
An endpoint is reachable **two** ways, and the second one is why an outside
|
|
381
460
|
agent can join at all. A workflow `tool` step names it —
|
|
382
461
|
`{ receiver: "endpoint:call", args: { endpoint: "<name>", input: {…} } }` — and
|
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oneie",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.10.0",
|
|
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.9",
|
|
52
52
|
"@types/node": "^25.6.0",
|
|
53
53
|
"commander": "^12.0.0",
|
|
54
54
|
"tsx": "^4.0.0",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{oe,D,J,ue,o,Z,ge,se,Se,Ae,be,ye,we,ke,ve,xe,Ee,$e,_e,Te}from"./index-w3wb5pdz.js";import"./index-zrktm90c.js";export{D as AGE_ARMOR_BEGIN,J as AGE_ARMOR_END,oe as AGE_VERSION_LINE,o as AgeError,ue as MAX_STANZAS,ke as armor,ve as dearmor,Se as decodeIdentity,ge as decodeRecipient,we as decrypt,se as encodeIdentity,Z as encodeRecipient,be as encrypt,xe as extractArmored,Ee as looksLikeAge,_e as openBytes,Te as openText,ye as parseHeader,Ae as recipientOf,$e as sealText};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n,s,r,t,e}from"./index-zrktm90c.js";export{r as authHeaders,t as jsonMode,e as out,n as resolveBase,s as resolveKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{l,m}from"./index-zrktm90c.js";var i=(e)=>Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("");function a(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=i(m(new TextEncoder().encode(t))),n="0x";for(let o=0;o<t.length;o++)n+=parseInt(r[o],16)>=8?t[o].toUpperCase():t[o];return n}function b(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 c(e){let t=new Uint8Array(e.reduce((n,o)=>n+o.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function f(e,t){if(e<56)return Uint8Array.of(t+e);let r=y(e);return c([Uint8Array.of(t+55+r.length),r])}function u(e){if(e instanceof Uint8Array){if(e.length===1&&e[0]<128)return e;return c([f(e.length,128),e])}let t=c(e.map(u));return c([f(t.length,192),t])}function s(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[s(e.chainId),s(e.nonce),s(e.maxPriorityFeePerGas),s(e.maxFeePerGas),s(e.gasLimit),a(e.to),s(e.value),a(e.data),[]]}function U(e,t){let r=m(c([Uint8Array.of(2),u(d(e))])),n=l.sign(r,t,{prehash:!1,format:"recovered"}),o=n[0],p=n.slice(1,33),x=n.slice(33,65),g=u([...d(e),s(o),s(BigInt(`0x${i(p)}`)),s(BigInt(`0x${i(x)}`))]);return`0x02${i(g)}`}function E(e){return`0x${i(m(a(e)))}`}function k(e){let t=l.getPublicKey(e,!1);return h(`0x${i(m(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,k as evmAddressFromKey,b as evmRecipientProblem,E as evmTxHash,a as hexToBytes,u as rlpEncode,U as signEip1559};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h,l,m}from"./index-zrktm90c.js";import{join as Dt,sep as Rt}from"node:path";var ie=10;function De(e,t,r){let n=Number(e),s=Number(t);if(!(n>0)||!(s>0)||!Number.isInteger(r)||r<0)return null;let i=10**r,o=Math.floor(n/s*i+0.000000001);if(o<=0)return null;let a=(o/i).toFixed(r);return r>0?a.replace(/\.?0+$/,""):a}class d extends Error{code;detail;constructor(e,t){super(t?`${e}: ${t}`:e);this.code=e;this.detail=t;this.name="HlRefusal"}}var Te={perp:6,spot:8},ot=/^\d+(\.\d+)?$/;function Z(e,t="value"){if(typeof e!=="string"||!ot.test(e.trim()))throw new d("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 C=(e)=>e.includes(".")?e.split(".")[1].length:0,fe=(e)=>/^0(\.0*)?$/.test(e),at=(e)=>!e.includes(".");function Re(e){let t=e.replace(".","").replace(/^0+/,"");if(!e.includes("."))return t.replace(/0+$/,"").length||1;return t.length||1}function He(e,t){let r=Z(e,"size");if(fe(r))throw new d("size_zero");if(C(r)>t)throw new d("size_too_precise",`${r} has ${C(r)} decimals, max ${t}`);return r}function ge(e,t,r){let n=Z(e,"price");if(fe(n))throw new d("price_zero");if(at(n))return n;if(Re(n)>5)throw new d("price_sig_figs",`${n} has ${Re(n)} significant figures, max 5`);let s=Te[r]-t;if(C(n)>s)throw new d("price_too_precise",`${n} has ${C(n)} decimals, max ${s}`);return n}function B(e){let t=Z(e,"amount");if(fe(t))throw new d("amount_zero");if(C(t)>6)throw new d("amount_too_precise",`${t} has ${C(t)} decimals, max 6`);return t}function Pe(e,t,r,n,s){let i=Number(Z(e,"mid"));if(!(i>0))throw new d("price_zero","mid");if(!(r>=0&&r<1))throw new d("bad_slippage",String(r));let o=i*(t?1+r:1-r),a=Number(o.toPrecision(5)),c=Math.max(0,Te[s]-n);return ge(Z(a.toFixed(c),"price"),n,s)}var Ee={mainnet:"https://api.hyperliquid.xyz/info",testnet:"https://api.hyperliquid-testnet.xyz/info"};var z=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Q=1e4,F=110000;function lt(e,t){let r=new Map,n=new Map,s=(u,...f)=>{n.set(u.asset,u);for(let b of f)if(!r.has(b))r.set(b,u)},i=z(e)?e:{};(Array.isArray(i.universe)?i.universe:[]).forEach((u,f)=>{if(!z(u)||typeof u.name!=="string"||typeof u.szDecimals!=="number")return;s({coin:u.name,label:u.name,asset:f,szDecimals:u.szDecimals,kind:"perp",delisted:u.isDelisted===!0,...typeof u.maxLeverage==="number"?{maxLeverage:u.maxLeverage}:{},...u.onlyIsolated===!0?{onlyIsolated:!0}:{}},u.name)});let a=z(t)?t:{},c=new Map;for(let u of Array.isArray(a.tokens)?a.tokens:[])if(z(u)&&typeof u.index==="number")c.set(u.index,u);for(let u of Array.isArray(a.universe)?a.universe:[]){if(!z(u)||typeof u.index!=="number"||typeof u.name!=="string"||!Array.isArray(u.tokens))continue;let[f,b]=u.tokens,g=c.get(f),I=c.get(b);if(!g||typeof g.szDecimals!=="number")continue;let O=`${String(g.name)}/${String(I?.name??"?")}`;s({coin:u.name,label:O,asset:Q+u.index,szDecimals:g.szDecimals,kind:"spot",delisted:!1},u.name,O)}return{byName:r,byIndex:n}}function me(e,t){let r=e.byName.get(t);if(!r)throw new d("unknown_asset",t);if(r.delisted)throw new d("asset_delisted",t);return r}function he(e,t){if(t>=F)throw new d("builder_dex_unsupported",String(t));let r=e.byIndex.get(t);if(!r)throw new d("unknown_asset",String(t));return r}async function E(e,t,r={}){let n=r.fetchImpl??fetch;try{let s=await n(Ee[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 ye(e,t={}){let[r,n]=await Promise.all([E({type:"meta"},e,t),E({type:"spotMeta"},e,t)]);if(!r.ok)return r;if(!n.ok)return n;return{ok:!0,data:lt(r.data,n.data)}}async function Ne(e,t={}){let r=await E({type:"allMids"},e,t);if(!r.ok)return r;let n={};if(z(r.data)){for(let[s,i]of Object.entries(r.data))if(typeof i==="string"&&/^\d+(\.\d+)?$/.test(i))n[s]=i}return{ok:!0,data:n}}var ct=["Gtc","Ioc","Alo"],dt=/^0x[0-9a-fA-F]{32}$/,ut=/^0x[0-9a-fA-F]{40}$/;function we(e){let t=e.tif??"Gtc";if(!ct.includes(t))throw new d("bad_tif",String(t));if(e.asset.delisted)throw new d("asset_delisted",e.asset.coin);let r=He(e.sz,e.asset.szDecimals),n=ge(e.px,e.asset.szDecimals,e.asset.kind);if(e.cloid!==void 0&&!dt.test(e.cloid))throw new d("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 be(e){return{type:"order",orders:[we(e)],grouping:"na"}}function Ue(e){let t=Pe(e.mid,e.isBuy,e.slippage??0.05,e.asset.szDecimals,e.asset.kind);return be({asset:e.asset,isBuy:e.isBuy,sz:e.sz,px:t,tif:"Ioc",reduceOnly:e.reduceOnly,cloid:e.cloid})}function oe(e){let t=e.asset.asset;if(!Number.isSafeInteger(t)||t<0)throw new d("unknown_asset",String(t));if(t>=F)throw new d("builder_dex_unsupported",String(t));if(!Number.isSafeInteger(e.oid)||e.oid<0)throw new d("bad_oid",String(e.oid));return{type:"cancel",cancels:[{a:t,o:e.oid}]}}function M(e){let t=e.asset.asset;if(!Number.isSafeInteger(t)||t<0)throw new d("unknown_asset",String(t));if(t>=F)throw new d("builder_dex_unsupported",String(t));if(e.asset.kind==="spot"||t>=Q)throw new d("leverage_spot",e.asset.coin);if(typeof e.isCross!=="boolean")throw new d("bad_leverage","isCross must be true or false");if(!Number.isSafeInteger(e.leverage)||e.leverage<1)throw new d("bad_leverage",String(e.leverage));if(e.asset.maxLeverage!==void 0&&e.leverage>e.asset.maxLeverage)throw new d("leverage_too_high",`${e.leverage}x, max ${e.asset.maxLeverage}x on ${e.asset.coin}`);if(e.isCross&&e.asset.onlyIsolated)throw new d("cross_not_allowed",e.asset.coin);return{type:"updateLeverage",asset:t,isCross:e.isCross,leverage:e.leverage}}function Ce(e){if(!Number.isSafeInteger(e)||e<=0)throw new d("nonce_required",String(e));return e}function ae(e){return{type:"usdClassTransfer",amount:B(e.amount),toPerp:e.toPerp,nonce:Ce(e.nonce)}}function le(e){if(!ut.test(e.destination))throw new d("bad_address",e.destination);return{type:"withdraw3",destination:e.destination.toLowerCase(),amount:B(e.amount),time:Ce(e.time)}}var W=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],L=(e)=>Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join(""),j=(e)=>`0x${L(e)}`;function q(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||!/^[0-9a-fA-F]*$/.test(t))throw new d("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 ce(e){if(e<0n||e>=1n<<256n)throw new d("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 Le(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 d("eip712_value",`${r} not a uint`);if(n<0n||n>=1n<<BigInt(t))throw new d("eip712_range",r);return n}function pt(e,t){switch(e.type){case"string":if(typeof t!=="string")throw new d("eip712_value",`${e.name} not a string`);return m(new TextEncoder().encode(t));case"bytes32":{let r=t instanceof Uint8Array?t:typeof t==="string"?q(t):null;if(!r||r.length!==32)throw new d("eip712_value",`${e.name} not bytes32`);return r}case"address":{if(typeof t!=="string"||!/^0x[0-9a-fA-F]{40}$/.test(t))throw new d("eip712_value",`${e.name} not an address`);return ce(BigInt(t))}case"bool":if(typeof t!=="boolean")throw new d("eip712_value",`${e.name} not a bool`);return ce(t?1n:0n);case"uint64":return ce(Le(t,64,e.name));case"uint256":return ce(Le(t,256,e.name));default:throw new d("eip712_type",String(e.type))}}var ft=(e,t)=>`${e}(${t.map((r)=>`${r.type} ${r.name}`).join(",")})`;function je(e,t,r){let n=[m(new TextEncoder().encode(ft(e,t)))];for(let i of t){if(!(i.name in r))throw new d("eip712_missing",i.name);n.push(pt(i,r[i.name]))}let s=new Uint8Array(n.length*32);return n.forEach((i,o)=>s.set(i,o*32)),m(s)}function V(e){let t=e.types[e.primaryType];if(!t)throw new d("eip712_type",e.primaryType);let r=je("EIP712Domain",W,e.domain),n=je(e.primaryType,t,e.message),s=new Uint8Array(66);return s[0]=25,s[1]=1,s.set(r,2),s.set(n,34),m(s)}class ee extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}var gt=(1n<<64n)-1n,mt=-(1n<<63n);function G(e){let t=[];return de(t,e,"$"),Uint8Array.from(t)}function P(e,t,r){for(let n=r-1;n>=0;n--)e.push(Number(t>>BigInt(8*n)&0xffn))}function qe(e,t,r){if(t>gt||t<mt)throw new ee("msgpack_int_range",r);if(t>=0n){if(t<=0x7fn)e.push(Number(t));else if(t<=0xffn)e.push(204),P(e,t,1);else if(t<=0xffffn)e.push(205),P(e,t,2);else if(t<=0xffffffffn)e.push(206),P(e,t,4);else e.push(207),P(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),P(e,n(8),1);else if(t>=-32768n)e.push(209),P(e,n(16),2);else if(t>=-2147483648n)e.push(210),P(e,n(32),4);else e.push(211),P(e,n(64),8)}function xe(e,t,r,n,s){if(t<=n)e.push(r|t);else if(s[0]!==null&&t<=255)e.push(s[0]),P(e,BigInt(t),1);else if(t<=65535)e.push(s[1]),P(e,BigInt(t),2);else e.push(s[2]),P(e,BigInt(t),4)}function de(e,t,r){if(t===null){e.push(192);return}if(t===void 0)throw new ee("msgpack_undefined",r);if(typeof t==="boolean"){e.push(t?195:194);return}if(typeof t==="bigint"){qe(e,t,r);return}if(typeof t==="number"){if(!Number.isSafeInteger(t))throw new ee("msgpack_float",`${r}=${t}`);qe(e,BigInt(t),r);return}if(typeof t==="string"){let n=new TextEncoder().encode(t);xe(e,n.length,160,31,[217,218,219]);for(let s of n)e.push(s);return}if(Array.isArray(t)){xe(e,t.length,144,15,[null,220,221]),t.forEach((n,s)=>de(e,n,`${r}[${s}]`));return}if(typeof t==="object"&&Object.getPrototypeOf(t)===Object.prototype){let n=Object.keys(t);xe(e,n.length,128,15,[null,222,223]);for(let s of n)de(e,s,r),de(e,t[s],`${r}.${s}`);return}throw new ee("msgpack_type",`${r}: ${typeof t}`)}var ue={mainnet:"https://api.hyperliquid.xyz/exchange",testnet:"https://api.hyperliquid-testnet.xyz/exchange"},$e="0x66eee",ze="0x0000000000000000000000000000000000000000",Me=/^0x[0-9a-fA-F]{40}$/;function Fe(e){let t=BigInt(e);if(t<0n||t>=1n<<64n)throw new d("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 ht(e,t,r,n){let s=[G(e),Fe(r)];if(t===null)s.push(Uint8Array.of(0));else s.push(Uint8Array.of(1),q(t));if(n!==null)s.push(Uint8Array.of(0),Fe(n));let i=new Uint8Array(s.reduce((a,c)=>a+c.length,0)),o=0;for(let a of s)i.set(a,o),o+=a.length;return i}var yt={name:"Exchange",version:"1",chainId:1337,verifyingContract:ze},wt=[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}];function bt(e,t){return{domain:yt,types:{Agent:wt,EIP712Domain:W},primaryType:"Agent",message:{source:t==="mainnet"?"a":"b",connectionId:j(e)}}}var xt={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 $t(e,t,r,n,s=$e){if(!/^0x[0-9a-fA-F]+$/.test(s))throw new d("bad_hex",s);let i={...r,hyperliquidChain:n==="mainnet"?"Mainnet":"Testnet"},o={};for(let a of t){if(!(a.name in i))throw new d("eip712_missing",a.name);o[a.name]=i[a.name]}return{domain:{name:"HyperliquidSignTransaction",version:"1",chainId:Number(BigInt(s)),verifyingContract:ze},types:{[e]:t,EIP712Domain:W},primaryType:e,message:o}}var We=(e,t)=>L(G(e))===L(G(t)),Ve=(e)=>e.type==="order"||e.type==="cancel"||e.type==="updateLeverage";function kt(e,t){let r=he(t,e.a),n=e.t?.limit?.tif;return we({asset:r,isBuy:e.b,sz:e.s,px:e.p,tif:n,reduceOnly:e.r,cloid:e.c})}var At=(e,t)=>{let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.join()===n.join()&&r.every((s)=>We(e[s],t[s]))};function Be(e,t){let{hyperliquidChain:r,signatureChainId:n,...s}=e,i=t.net==="mainnet"?"Mainnet":"Testnet";if(r!==void 0&&r!==i)throw new d("unsupported_action",`hyperliquidChain ${String(r)} on ${t.net}`);let o=(t.signatureChainId??$e).toLowerCase();if(n!==void 0&&String(n).toLowerCase()!==o)throw new d("unsupported_action",`signatureChainId ${String(n)} ≠ ${o}`);return s}function vt(e,t){let r=t.assets;if(!e||typeof e!=="object")throw new d("unsupported_action","not an object");let n,s=e;switch(e.type){case"order":{if(!r)throw new d("meta_required","an order is checked against meta + spotMeta before it is signed");let o=Array.isArray(e.orders)?e.orders:[];if(o.length===0)throw new d("unsupported_action","order with no orders");n={type:"order",orders:o.map((a)=>kt(a,r)),grouping:"na"};break}case"cancel":{let o=e.cancels??[];if(o.length===0)throw new d("unsupported_action","cancel with no cancels");n={type:"cancel",cancels:o.map((a)=>oe({asset:r?he(r,a.a):{asset:a.a},oid:a.o}).cancels[0])};break}case"updateLeverage":{let o=e,a=r&&Number.isSafeInteger(o.asset)&&o.asset<F?r.byIndex.get(o.asset):void 0;if(r&&!a&&Number.isSafeInteger(o.asset)&&o.asset<F)throw new d("unknown_asset",String(o.asset));n=M({asset:a??{asset:o.asset,kind:o.asset>=Q?"spot":"perp",coin:String(o.asset)},leverage:o.leverage,isCross:o.isCross});break}case"usdClassTransfer":{s=Be(e,t);let o=s;if(typeof o.toPerp!=="boolean")throw new d("unsupported_action","toPerp");n=ae({amount:o.amount,toPerp:o.toPerp,nonce:o.nonce});break}case"withdraw3":{s=Be(e,t);let o=s;n=le({destination:o.destination,amount:o.amount,time:o.time});break}default:throw new d("unsupported_action",String(e.type))}if(!(Ve(n)?We(n,s):At(n,s)))throw new d("unsupported_action","action is not in canonical form");return n}function J(e,t){let r=vt(e,t);if(Ve(r)){if(t.nonce===void 0||!Number.isSafeInteger(t.nonce)||t.nonce<0)throw new d("nonce_required");if(t.vaultAddress!==void 0&&!Me.test(t.vaultAddress))throw new d("bad_address",t.vaultAddress);if(t.expiresAfter!==void 0&&(!Number.isSafeInteger(t.expiresAfter)||t.expiresAfter<=0))throw new d("expires_unsupported",String(t.expiresAfter));let c=t.vaultAddress?.toLowerCase()??null,u=t.expiresAfter??null,f=ht(r,c,t.nonce,u),b=m(f),g=bt(b,t.net);return{kind:"l1",network:t.net,action:r,nonce:t.nonce,vaultAddress:c,expiresAfter:u,msgpackHex:L(G(r)),hashInputHex:L(f),connectionId:j(b),typedData:g,digest:j(V(g)),exchangeUrl:ue[t.net],posted:!1}}if(t.vaultAddress!==void 0)throw new d("vault_unsupported",r.type);if(t.expiresAfter!==void 0)throw new d("expires_unsupported",r.type);let n=xt[r.type],s=r[n.nonceField];if(t.nonce!==void 0&&t.nonce!==s)throw new d("nonce_mismatch",`${t.nonce} ≠ ${s}`);let i=t.signatureChainId??$e,o={type:r.type,signatureChainId:i,hyperliquidChain:t.net==="mainnet"?"Mainnet":"Testnet",...Object.fromEntries(Object.entries(r).filter(([c])=>c!=="type"))},a=$t(n.primaryType,n.fields,o,t.net,i);return{kind:"user",network:t.net,action:o,nonce:s,vaultAddress:null,expiresAfter:null,msgpackHex:null,hashInputHex:null,connectionId:null,typedData:a,digest:j(V(a)),exchangeUrl:ue[t.net],posted:!1}}function _t(e){let t=q(e);if(t.length!==65)throw new d("bad_signature",`length ${t.length}`);let r=t[64]<27?t[64]+27:t[64];if(r!==27&&r!==28)throw new d("bad_signature",`v=${t[64]}`);return{r:j(t.slice(0,32)),s:j(t.slice(32,64)),v:r}}function St(e,t){let r=typeof e==="string"?q(e):e,n=(a)=>BigInt(a).toString(16).padStart(64,"0");if(t.v!==27&&t.v!==28)throw new d("bad_signature",`v=${t.v}`);let s=q(`${(t.v-27).toString(16).padStart(2,"0")}${n(t.r)}${n(t.s)}`),i=l.recoverPublicKey(s,r,{prehash:!1}),o=l.Point.fromBytes(i).toBytes(!1);return j(m(o.slice(1)).slice(12))}async function ke(e,t,r,n={}){let s=J(e,t);if(n.expectDigest!==void 0&&n.expectDigest.toLowerCase()!==s.digest)throw new d("signer_mismatch","the digest shown is not the digest being signed");if(!Me.test(r.address))throw new d("bad_address",r.address);let{EIP712Domain:i,...o}=s.typedData.types,a=await r.signTypedData(s.typedData.domain,o,s.typedData.message),c=_t(a),u=St(s.digest,c);if(u!==r.address.toLowerCase())throw new d("signer_mismatch",`recovered ${u}, expected ${r.address}`);return{dry:s,request:{action:s.action,nonce:s.nonce,signature:c,vaultAddress:s.vaultAddress,expiresAfter:s.expiresAfter}}}var pe=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function It(e){if(!pe(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=(pe(t)&&pe(t.data)&&Array.isArray(t.data.statuses)?t.data.statuses:[]).find((s)=>pe(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 Ae(e,t,r={}){let n=r.fetchImpl??fetch;try{let s=await n(ue[t],{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(r.timeoutMs??1e4)}),i=await s.text(),o;try{o=JSON.parse(i)}catch{return{ok:!1,error:"exchange_unavailable",detail:`status_${s.status}: ${i.slice(0,200)}`}}return It(o)}catch(s){return{ok:!1,error:"exchange_unavailable",detail:s.message}}}var ve=/^0x[0-9a-fA-F]{40}$/,N=(e)=>e.testnet?"testnet":"mainnet";function y(e,t,r={}){return{data:{ok:!1,error:e,detail:t,...r}}}class Ze extends Error{code;constructor(e,t){super(t);this.code=e}}function T(e,t={}){if(e instanceof d)return y(e.code,e.detail??e.message,t);let r=e?.code;return y(typeof r==="string"?r:"hl_error",e?.message??String(e),t)}function _e(e,t){let r=C(e),n=C(t),s=(BigInt(e.replace(".",""))*BigInt(t.replace(".",""))).toString().padStart(r+n+1,"0"),i=s.length-(r+n),o=s.slice(i).replace(/0+$/,"");return o?`${s.slice(0,i)}.${o}`:s.slice(0,i)}function Qe(e){let t=q(e.privateKeyHex);return{address:e.address,async signTypedData(r,n,s){let i=Object.keys(n);if(i.length!==1)throw new d("eip712_type",`expected one primary type, got ${i.length}`);let o=V({domain:r,types:{...n,EIP712Domain:W},primaryType:i[0],message:s}),a=l.sign(o,t,{prehash:!1,format:"recovered"}),c=new Uint8Array(65);return c.set(a.slice(1,65),0),c[64]=a[0]+27,`0x${L(c)}`}}}var R=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),K=(e)=>typeof e==="string"&&/^-?\d+(\.\d+)?$/.test(e)?e:null;async function te(e,t,r){let[n,s]=await Promise.all([E({type:"clearinghouseState",user:e},t,{fetchImpl:r.fetchImpl}),E({type:"spotClearinghouseState",user:e},t,{fetchImpl:r.fetchImpl})]);if(!n.ok||!s.ok)return null;let i=R(n.data)?n.data:{},o=R(i.marginSummary)?i.marginSummary:{},a=R(s.data)&&Array.isArray(s.data.balances)?s.data.balances:[];return{perps:{accountValue:K(o.accountValue),withdrawable:K(i.withdrawable)},spot:a.filter(R).map((c)=>({coin:String(c.coin??"?"),total:String(c.total??"?"),hold:String(c.hold??"?")}))}}function ne(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 re(e,t,r){let n=e?.trim();if(n)return ve.test(n)?{ok:!0,address:n}:y("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 y(String(s.error??"wallet_read_failed"),"Could not read your workspace wallet — pass an address.");let o=(Array.isArray(s.addresses)?s.addresses:[]).filter((c)=>c.chain==="evm"&&typeof c.address==="string"&&ve.test(c.address)&&(!t||c.actor===t)),a=[...new Map(o.map((c)=>[c.address.toLowerCase(),c])).values()];if(a.length===0)return y("no_evm_address","Your workspace has no EVM address registered — pass one.");if(a.length>1)return y("ambiguous_address",`Several EVM addresses — pass one, or --actor <id>: ${a.map((c)=>`${c.actor??"?"} ${c.address}`).join(" · ")}`);return{ok:!0,address:a[0].address}}async function $n(e,t){let r=N(e),n=await re(e.address,e.actor,t);if(!(("ok"in n)&&n.ok===!0))return n;let s=await E({type:"clearinghouseState",user:n.address},r,{fetchImpl:t.fetchImpl});if(!s.ok)return y(s.error,s.detail,{network:r});let i=R(s.data)?s.data:{},o=R(i.marginSummary)?i.marginSummary:{},a=(Array.isArray(i.assetPositions)?i.assetPositions:[]).map((c)=>R(c)&&R(c.position)?c.position:null).filter((c)=>c!==null).map((c)=>({coin:String(c.coin??"?"),size:String(c.szi??"?"),entryPx:c.entryPx??null,positionValue:c.positionValue??null,unrealizedPnl:c.unrealizedPnl??null,liquidationPx:c.liquidationPx??null,leverage:R(c.leverage)?c.leverage:null}));return t.say([`${n.address} on ${r} — perps account ${K(o.accountValue)??"—"} USDC, withdrawable ${K(i.withdrawable)??"—"}`,...a.length?a.map((c)=>` ${c.coin.padEnd(8)} ${c.size.startsWith("-")?"short":"long "} ${c.size.replace(/^-/,"")} @ ${String(c.entryPx??"—")} value ${String(c.positionValue??"—")} pnl ${String(c.unrealizedPnl??"—")} liq ${String(c.liquidationPx??"—")}`):[" no open perps positions (spot holdings: one hl balance)"]]),{data:{ok:!0,network:r,address:n.address,accountValue:K(o.accountValue),withdrawable:K(i.withdrawable),positions:a}}}async function kn(e,t){let r=N(e),n=await re(e.address,e.actor,t);if(!(("ok"in n)&&n.ok===!0))return n;let s=await E({type:"openOrders",user:n.address},r,{fetchImpl:t.fetchImpl});if(!s.ok)return y(s.error,s.detail,{network:r});if(!Array.isArray(s.data))return y("hyperliquid_unavailable","openOrders did not answer a list",{network:r});let i=s.data.filter(R).map((o)=>({coin:String(o.coin??"?"),side:o.side==="B"?"buy":o.side==="A"?"sell":String(o.side??"?"),size:String(o.sz??"?"),limitPx:String(o.limitPx??"?"),oid:o.oid??null,timestamp:o.timestamp??null}));return t.say([`${n.address} on ${r} — ${i.length} resting order${i.length===1?"":"s"}`,...i.map((o)=>` ${o.side.padEnd(4)} ${o.size} ${o.coin} @ ${o.limitPx} oid ${String(o.oid)} cancel: one hl cancel ${o.coin} ${String(o.oid)}${r==="testnet"?" --testnet":""}`)]),{data:{ok:!0,network:r,address:n.address,count:i.length,orders:i}}}var Tt="Hyperliquid takes its own trading fee on a fill (maker or taker, by your fee tier); ONE computes none and takes none.";function et(e){if(e===void 0)return 0.05;if(!/^\d{1,4}$/.test(e)||Number(e)<1||Number(e)>2000)return y("bad_slippage","--slippage is basis points, 1–2000 (default 500 = 5%, the python SDK default).");return Number(e)/1e4}var Ht="A perp is its name (BTC, ETH, HYPE); a spot pair is BASE/QUOTE (HYPE/USDC, UBTC/USDC) or its @index.";async function Oe(e,t,r){let n=await ye(t,{fetchImpl:r.fetchImpl});if(!n.ok)return y(n.error,n.detail,{network:t});try{return{table:n.data,info:me(n.data,e)}}catch(s){return T(s,{network:t,next:Ht})}}async function tt(e,t,r){let n=await Ne(t,{fetchImpl:r.fetchImpl});if(!n.ok)return y(n.error,n.detail,{network:t});return n.data[e.coin]??y("mid_unavailable",`allMids has no price for ${e.coin} (${e.label}) — a market order needs one; pass --limit <px>.`,{network:t})}async function An(e,t){let r=N(e),n=e.side.toLowerCase();if(n!=="buy"&&n!=="sell")return y("bad_side","The side is buy or sell.");if(e.tif!==void 0&&e.limit===void 0&&e.tif!=="Ioc")return y("bad_tif","A market order is IOC by construction — --tif needs --limit.");let s=et(e.slippage);if(typeof s!=="number")return s;let i=await Oe(e.coin,r,t);if("data"in i)return i;let o=null;if(e.limit===void 0){let a=await tt(i.info,r,t);if(typeof a!=="string")return a;o=a}return nt({...e,side:n},r,i.table,i.info,o,s)}function nt(e,t,r,n,s,i){let o=e.side,a=o==="buy",c=e.reduceOnly===!0,u=[e.limit!==void 0?`--limit ${e.limit}`:"",e.tif?`--tif ${e.tif}`:"",c?"--reduce-only":"",e.slippage?`--slippage ${e.slippage}`:""].filter(Boolean).join(" ");return{cmdline:`one hl order ${o} ${e.size} ${e.coin}${u?` ${u}`:""}`,build(f){let b=e.limit!==void 0?be({asset:n,isBuy:a,sz:e.size,px:e.limit,tif:e.tif??"Gtc",reduceOnly:c}):Ue({asset:n,isBuy:a,sz:e.size,mid:s,slippage:i,reduceOnly:c}),g=b.orders[0],I=n.kind==="spot"?"spot":"perps",O=_e(g.s,g.p),x=g.t.limit.tif,k=e.limit===void 0?`now, at ${a?"up to":"no less than"} ${g.p} (mid ${s} ${a?"+":"−"} ${i*100}%) — IOC: fills what it can at that cap, cancels the rest`:x==="Gtc"?`at ${g.p} or better — Gtc: rests on the book until filled or cancelled`:x==="Ioc"?`at ${g.p} or better — IOC: fills what it can now, cancels the rest`:`at ${g.p} — Alo (post-only): refused if it would take liquidity`,_=[`${a?"Buy":"Sell"} ${g.s} ${n.label} (${I}, asset ${g.a}) ${k}.`,`${a?"At most":"About"} ${O} USDC notional before fees.`,n.kind==="spot"?a?"Pays USDC from your SPOT balance.":`Sells ${n.label.split("/")[0]} you hold in SPOT for USDC.`:`${c?"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)."}`,Tt];return{action:b,opts:{net:t,nonce:f,assets:r},words:_,facts:{coin:n.coin,label:n.label,kind:n.kind,asset:g.a,side:o,size:g.s,price:g.p,tif:x,reduceOnly:c,notionalUsdc:O,...s?{mid:s,slippageBps:Math.round(i*1e4)}:{}}}}}}async function vn(e,t){let r=N(e);if(!/^\d{1,16}$/.test(e.oid)||!Number.isSafeInteger(Number(e.oid)))return y("bad_oid","The order id is the whole number `one hl orders` prints.");let n=await ye(r,{fetchImpl:t.fetchImpl});if(!n.ok)return y(n.error,n.detail,{network:r});let s;try{s=me(n.data,e.coin)}catch(o){return T(o,{network:r})}let i=Number(e.oid);return{cmdline:`one hl cancel ${e.coin} ${e.oid}`,build(o){return{action:oe({asset:s,oid:i}),opts:{net:r,nonce:o,assets:n.data},words:[`Cancel resting order ${i} 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:i}}}}}async function _n(e,t){let r=N(e),n=(e.to??"").toLowerCase();if(n!=="perps"&&n!=="spot")return y("bad_to","--to perps (spot → perps) or --to spot (perps → spot).");let s=n==="perps";try{B(e.amount)}catch(i){return T(i,{network:r})}return{cmdline:`one hl transfer ${e.amount} --to ${n}`,build(i){let o=ae({amount:e.amount,toPerp:s,nonce:i});return{action:o,opts:{net:r},words:[`Move ${o.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:o.amount,toPerp:s}}}}}async function Sn(e,t,r){let n=N(e);if(e.to!==void 0&&!ve.test(e.to))return y("bad_address","--to is an Arbitrum 0x address of 40 hex characters.");try{B(e.amount)}catch(i){return T(i,{network:n})}let s=null;if(!e.live&&e.to===void 0){let i=await re(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)"}};s=i.address}return{cmdline:`one hl withdraw ${e.amount}${e.to?` --to ${e.to}`:""}`,build(i,o){let a=o??s,c=e.to??a;if(!c)throw new d("bad_address","no destination");let u=a===null||c.toLowerCase()!==a.toLowerCase();if(r&&o!==null&&u)throw new Ze("to_other_refused",`An agent withdraws only to its own address (${o}); ${c} is another. A person signs that one.`);let f=le({destination:c,amount:e.amount,time:i});return{action:f,opts:{net:n},words:[`Send ${f.amount} USDC from the PERPS balance${a?` of ${a}`:""} to ${c} 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:f.amount,destination:f.destination,toOther:u}}}}}function rt(e){if(!/^\d{1,4}$/.test(e.trim()))return y("bad_leverage",`Leverage is a whole number of times (1, 3, 5 …), not ${JSON.stringify(e)}.`);return Number(e.trim())}function st(e,t,r,n,s,i){let o=M({asset:e,leverage:t,isCross:r}),a=r?"cross":"isolated";return{action:o,opts:{net:n,nonce:i,assets:s},words:[`Set ${e.label} (perps, asset ${e.asset}) to ${t}x ${a}${e.maxLeverage!==void 0?` (Hyperliquid allows up to ${e.maxLeverage}x here)`:""}. This moves no money — it sets how the NEXT order on ${e.coin} is margined.`,r?"Cross: margin is shared with every other cross position on this account — a loss here can draw on all of it.":"Isolated: a position's margin is only what you put on it — a liquidation loses that margin and no more.","Hyperliquid may refuse a change while a position on this coin is open (switching cross ↔ isolated, or less leverage than the position needs); its answer is the record."],facts:{coin:e.coin,label:e.label,asset:e.asset,leverage:t,isCross:r,mode:a,...e.maxLeverage!==void 0?{maxLeverage:e.maxLeverage}:{}}}}async function In(e,t){let r=N(e),n=rt(e.leverage);if(typeof n!=="number")return n;let s=await Oe(e.coin,r,t);if("data"in s)return s;let i=e.cross===!0;try{M({asset:s.info,leverage:n,isCross:i})}catch(o){return T(o,{network:r})}return{cmdline:`one hl leverage ${e.coin} ${n}${i?" --cross":""}`,build:(o)=>st(s.info,n,i,r,s.table,o)}}async function Ge(e,t,r,n){let s=await E({type:"activeAssetData",user:e,coin:t},r,{fetchImpl:n.fetchImpl});if(!s.ok||!R(s.data)||!R(s.data.leverage))return null;let i=s.data.leverage;return(i.type==="cross"||i.type==="isolated")&&typeof i.value==="number"?{type:i.type,value:i.value}:null}async function Pt(e,t){let r=N(e),n=e.side.toLowerCase();if(n!=="buy"&&n!=="sell")return y("bad_side","The side is buy or sell.");if(!/^\d+(\.\d+)?$/.test(e.usd)||!(Number(e.usd)>0))return y("bad_usd",`--usd is a dollar amount (20, 12.5), not ${JSON.stringify(e.usd)}.`);let s=null;if(e.lev!==void 0){let _=rt(e.lev);if(typeof _!=="number")return _;s=_}let i=et(e.slippage);if(typeof i!=="number")return i;let o=await Oe(e.coin,r,t);if("data"in o)return o;let{info:a,table:c}=o,u=e.cross===!0;if(s!==null)try{M({asset:a,leverage:s,isCross:u})}catch(_){return T(_,{network:r})}else if(u)return y("cross_needs_lev","--cross sets the margin mode together with the leverage — pass --lev <n> too.",{network:r});let f=await tt(a,r,t);if(typeof f!=="string")return f;let b=s!==null?_e(e.usd,String(s)):e.usd,g=De(b,f,a.szDecimals),I=g===null?"0":_e(g,f),O=s!==null?`$${e.usd} × ${s}x = $${b}`:`$${e.usd}`;if(g===null||Number(I)<ie)return y("below_minimum",`${O} buys ${g??"less than one lot of"} ${a.label}${g?`, worth $${I} at mid ${f}`:""} — under Hyperliquid's $${ie} minimum order value. Nothing was signed and the leverage was not touched.`,{network:r,next:`Ask for more: --usd ${Math.ceil(ie*1.05/(s??1))}${s!==null?` --lev ${s}`:""}`});let x=[`--usd ${e.usd}`,s!==null?`--lev ${s}`:"",u?"--cross":"",e.slippage?`--slippage ${e.slippage}`:""].filter(Boolean).join(" "),k=nt({side:n,size:g,coin:e.coin,slippage:e.slippage},r,c,a,f,i);return{cmdline:`one hl ${n} ${e.coin} ${x}`,side:n,info:a,table:c,usd:e.usd,lev:s,isCross:u,mid:f,size:g,notionalUsdc:I,order:k}}function it(e,t){let r=e.dir??".",n=h(t.env);if(n){let s=t.realpath(r),i=t.realpath(Dt(t.home,".one","agents"));if(!(s!==null&&i!==null&&s.startsWith(i+Rt)))return y("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 y("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 y("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 Se(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 Ie(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 Je(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 Ke(e,t,r){if(!e)return null;let n=await E({type:"userAbstraction",user:e},t,{fetchImpl:r.fetchImpl});return n.ok?n.data:null}async function On(e,t,r,n,s={}){let i=N(t),o=t.live?it(t,n):null;if(o)return{data:{network:i,...o.data}};let a=await r();if("data"in a)return{data:{network:i,...a.data}};if(!t.live){let A,U;try{A=a.build(n.now(),null),U=J(A.action,A.opts)}catch(p){return T(p,{network:i})}let S=s.abstractionFor??null;if(e==="transfer"&&!S){let p=await re(void 0,void 0,n);if("ok"in p&&p.ok===!0)S=p.address}let X=e==="transfer"?await Ke(S,i,n):void 0,se=`${a.cmdline}${i==="testnet"?" --testnet":""} --live --dir <your vault folder>`;return n.say([`DRY RUN — nothing signed, nothing sent · ${e} on ${i}`,...A.words.map((p)=>` ${p}`),...e==="transfer"?[Je(X),...S?[`account ${S}`]:[]]:[],...Se(U),`next ${se}`]),{data:{ok:!0,live:!1,posted:!1,network:i,verb:e,consequence:A.words,...A.facts,...e==="transfer"?{abstraction:X??null,account:S}:{},...Ie(U),next:se}}}let c=await n.unlock(t.dir??".");if("error"in c)return y("vault_unavailable",c.error,{network:i,next:"Name the folder that holds .one/wallet.json: --dir ~/.one/<you>"});let u=c.keys.find((A)=>A.chain==="evm");if(!u)return y("no_evm_key",`The vault at ${t.dir??"."} holds no EVM key.`,{network:i});let f=Qe(u),b,g;try{b=a.build(n.now(),f.address),g=J(b.action,b.opts)}catch(A){return T(A,{network:i,signer:f.address})}let I=await te(f.address,i,n),O=e==="transfer"?await Ke(f.address,i,n):void 0;if(n.say([`LIVE · ${e} on ${i} · signer ${f.address} (the vault's EVM key)`,...ne("before",I),...b.words.map((A)=>` ${A}`),...e==="transfer"?[Je(O)]:[],...Se(g)]),!t.yes){if(!await n.confirm(`Sign this digest with ${f.address} and post it to Hyperliquid ${i}? [y/N] `))return{data:{ok:!1,error:"declined",network:i,signer:f.address,posted:!1,detail:"Nothing signed, nothing sent."}}}let x;try{({request:x}=await ke(b.action,b.opts,f,{expectDigest:g.digest}))}catch(A){return T(A,{network:i,signer:f.address,posted:!1})}let k=await Ae(x,i,{fetchImpl:n.fetchImpl}),_=await te(f.address,i,n);return n.say([`exchange ${JSON.stringify(k.ok?k.response:{error:k.error,detail:k.detail,response:k.response??null})}`,...ne("after ",_)]),{data:{ok:k.ok,...k.ok?{}:{error:k.error,detail:k.detail},live:!0,posted:!0,network:i,verb:e,signer:f.address,...b.facts,...e==="transfer"?{abstraction:O??null}:{},...Ie(g),signature:x.signature,exchange:k.ok?k.response:k.response??null,balanceBefore:I,balanceAfter:_}}}function Xe(e){return{step:e.step,consequence:e.built.words,...Ie(e.dry)}}function Ye(e,t,r){return[`step ${e} of ${t} — ${r.step==="leverage"?"updateLeverage":"order"}`,...r.built.words.map((n)=>` ${n}`),...Se(r.dry)]}var Et=(e)=>e?`${e.value}x ${e.type}`:"not read";async function Dn(e,t,r={}){let n=N(e),s=e.live?it(e,t):null;if(s)return{data:{network:n,...s.data}};let i=await Pt(e,t);if("data"in i)return{data:{network:n,...i.data}};let o=i.isCross?"cross":"isolated",a=(p)=>i.lev!==null&&!(p&&p.value===i.lev&&p.type===o),c=(p,v)=>{let w=[],D=t.now();if(a(p)){let Y=st(i.info,i.lev,i.isCross,n,i.table,D);w.push({step:"leverage",built:Y,dry:J(Y.action,Y.opts)}),D=Math.max(t.now(),D+1)}let H=i.order.build(D,v);return w.push({step:"order",built:H,dry:J(H.action,H.opts)}),w},u=i.lev!==null?(Number(i.notionalUsdc)/i.lev).toFixed(2):null,f=`${i.lev!==null?`$${i.usd} × ${i.lev}x`:`$${i.usd}`} ÷ mid ${i.mid} = ${i.size} ${i.info.label}, worth $${i.notionalUsdc} — floored to ${i.info.szDecimals} decimals, never more than asked${u?`; margin about $${u} USDC at ${i.lev}x`:""}.`,b=(p,v)=>i.lev===null?"leverage unchanged — no --lev, so the order uses whatever this account has set on the coin":a(p)?`leverage now ${Et(p)}${v?` on ${v}`:""}${p?"":" (no answer, or no account to read)"} — asked ${i.lev}x ${o}, so updateLeverage goes FIRST and the order only if it is accepted`:`leverage already ${i.lev}x ${o}${v?` on ${v}`:""} — no updateLeverage step`,g=(p,v)=>({...p[p.length-1].built.facts,verb:i.side,side:i.side,coin:i.info.coin,label:i.info.label,usd:i.usd,leverage:i.lev,mode:i.lev!==null?o:null,mid:i.mid,size:i.size,notionalUsdc:i.notionalUsdc,...u?{marginUsdc:u}:{},leverageStep:p[0].step==="leverage",current:v});if(!e.live){let p=null,v=null;if(i.lev!==null){let H=await re(e.address,e.actor,t);if("ok"in H&&H.ok===!0)p=H.address,v=await Ge(p,i.info.coin,n,t)}let w;try{w=c(v,null)}catch(H){return T(H,{network:n})}let D=`${i.cmdline}${n==="testnet"?" --testnet":""} --live --dir <your vault folder>`;return t.say([`DRY RUN — nothing signed, nothing sent · ${i.side} on ${n}`,` ${f}`,b(v,p),...w.flatMap((H,Y)=>Ye(Y+1,w.length,H)),`next ${D}`]),{data:{ok:!0,live:!1,posted:!1,network:n,...g(w,v),account:p,steps:w.map(Xe),next:D}}}let I=await t.unlock(e.dir??".");if("error"in I)return y("vault_unavailable",I.error,{network:n,next:"Name the folder that holds .one/wallet.json: --dir ~/.one/<you>"});let O=I.keys.find((p)=>p.chain==="evm");if(!O)return y("no_evm_key",`The vault at ${e.dir??"."} holds no EVM key.`,{network:n});let x=Qe(O),k=i.lev!==null?await Ge(x.address,i.info.coin,n,t):null,_;try{_=c(k,x.address)}catch(p){return T(p,{network:n,signer:x.address})}let A=await te(x.address,n,t);t.say([`LIVE · ${i.side} on ${n} · signer ${x.address} (the vault's EVM key)`,...ne("before",A),` ${f}`,b(k,x.address),..._.flatMap((p,v)=>Ye(v+1,_.length,p))]);let U={live:!0,network:n,signer:x.address,...g(_,k)};if(!e.yes){let p=_.length===2?"Sign both steps (leverage, then the order only if Hyperliquid accepts it)":"Sign this order";if(!await t.confirm(`${p} with ${x.address} and post to Hyperliquid ${n}? [y/N] `))return{data:{ok:!1,error:"declined",...U,posted:!1,orderPosted:!1,detail:"Nothing signed, nothing sent."}}}let S=[];for(let p of _){let v;try{({request:v}=await ke(p.built.action,p.built.opts,x,{expectDigest:p.dry.digest}))}catch(D){return T(D,{...U,posted:S.length>0,orderPosted:!1,steps:S})}r.onSign?.(p.step);let w=await Ae(v,n,{fetchImpl:t.fetchImpl});if(t.say([`exchange ${p.step}: ${JSON.stringify(w.ok?w.response:{error:w.error,detail:w.detail,response:w.response??null})}`]),S.push({...Xe(p),signature:v.signature,posted:!0,accepted:w.ok,exchange:w.ok?w.response:w.response??null}),!w.ok){let D=await te(x.address,n,t);if(t.say(ne("after ",D)),p.step==="leverage")return{data:{ok:!1,error:"leverage_refused",detail:w.detail,exchangeError:w.error,...U,posted:!0,orderPosted:!1,steps:S,balanceBefore:A,balanceAfter:D,next:"The order was never signed. Fix what Hyperliquid named (close the position, or keep its mode), or drop --lev to trade at the current setting."}};return{data:{ok:!1,error:w.error,detail:w.detail,...U,posted:!0,orderPosted:!0,steps:S,exchange:w.response??null,balanceBefore:A,balanceAfter:D}}}}let X=await te(x.address,n,t);t.say(ne("after ",X));let se=S[S.length-1];return{data:{ok:!0,...U,posted:!0,orderPosted:!0,steps:S,exchange:se.exchange,balanceBefore:A,balanceAfter:X}}}export{Je as abstractionWords,it as liveGate,vn as prepareCancel,In as prepareLeverage,An as prepareOrder,_n as prepareTransfer,Pt as prepareUsdOrder,Sn as prepareWithdraw,te as readBalance,Ge as readLeverage,re as resolveAccount,On as runAction,kn as runOrders,$n as runPositions,Dn as runUsdOrder,Qe as vaultSigner};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var Re=900000,ae=120000;function X(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 ie(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{Re,ae,X,ie};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{d,a,B,c,p,O,x,de,q,u}from"./index-zrktm90c.js";/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Gt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Lt(t){if(typeof t!=="boolean")throw TypeError(`boolean expected, not ${t}`)}function dt(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 F(t,e,r=""){let n=Gt(t),s=t?.length,f=e!==void 0;if(!n||f&&s!==e){let i=r&&`"${r}" `,l=f?` of length ${e}`:"",h=n?`length=${s}`:`type=${typeof t}`,y=i+"expected Uint8Array"+l+", got "+h;if(!n)throw TypeError(y);throw RangeError(y)}return t}function Et(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 Tt(t,e,r=!1){F(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&&!yt(t))throw Error("invalid output, must be aligned")}function nt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function et(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Dt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var ct=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),Vt=(t)=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var Yt=(t)=>{for(let e=0;e<t.length;e++)t[e]=Vt(t[e]);return t},rt=ct?(t)=>t:Yt;function It(t,e){if(e==null||typeof e!=="object")throw Error("options must be defined");return Object.assign(t,e)}function kt(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 At(t,e,r){let n=e,s=r||(()=>[]),f=(l,h)=>n(h,...s(l)).update(l).digest(),i=n(new Uint8Array(t),...s(new Uint8Array(0)));return f.outputLen=i.outputLen,f.blockLen=i.blockLen,f.create=(l,...h)=>n(l,...h),f}var Rt=(t,e)=>{function r(n,...s){if(F(n,void 0,"key"),t.nonceLength!==void 0){let w=s[0];F(w,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let f=t.tagLength;if(f&&s[1]!==void 0)F(s[1],void 0,"AAD");let i=e(n,...s),l=(w,b)=>{if(b!==void 0){if(w!==2)throw Error("cipher output not supported");F(b,void 0,"output")}},h=!1;return{encrypt(w,b){if(h)throw Error("cannot encrypt() twice with same key + nonce");return h=!0,F(w),l(i.encrypt.length,b),i.encrypt(w,b)},decrypt(w,b){if(F(w),f&&w.length<f)throw Error('"ciphertext" expected length bigger than tagLength='+f);return l(i.decrypt.length,b),i.decrypt(w,b)}}}return Object.assign(r,t),r};function gt(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(F(e,void 0,"output"),e.length!==t)throw Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!yt(e))throw Error("invalid output, must be aligned");return e}function Ct(t,e,r){dt(t),dt(e),Lt(r);let n=new Uint8Array(16),s=Dt(n);return s.setBigUint64(0,BigInt(e),r),s.setBigUint64(8,BigInt(t),r),n}function yt(t){return t.byteOffset%4===0}function wt(t){return Uint8Array.from(F(t))}var St=(t)=>Uint8Array.from(t.split(""),(e)=>e.charCodeAt(0)),qt=(()=>rt(nt(St("expand 16-byte k"))))(),Zt=(()=>rt(nt(St("expand 32-byte k"))))();function _(t,e){return t<<e|t>>>32-e}var xt=64,Qt=16,_t=(()=>4294967295)(),Ot=Uint32Array.of();function Jt(t,e,r,n,s,f,i,l){let h=s.length,y=new Uint8Array(xt),w=nt(y),b=ct&&yt(s)&&yt(f),U=b?nt(s):Ot,L=b?nt(f):Ot;if(!ct){for(let m=0;m<h;i++){if(t(e,r,n,w,i,l),rt(w),i>=_t)throw Error("arx: counter overflow");let E=Math.min(xt,h-m);for(let I=0,T;I<E;I++)T=m+I,f[T]=s[T]^y[I];m+=E}return}for(let m=0;m<h;i++){if(t(e,r,n,w,i,l),i>=_t)throw Error("arx: counter overflow");let E=Math.min(xt,h-m);if(b&&E===xt){let I=m/4;if(m%4!==0)throw Error("arx: invalid block position");for(let T=0,G;T<Qt;T++)G=I+T,L[G]=U[G]^w[T];m+=xt;continue}for(let I=0,T;I<E;I++)T=m+I,f[T]=s[T]^y[I];m+=E}}function Nt(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:f,rounds:i}=It({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!=="function")throw Error("core must be a function");return dt(s),dt(i),Lt(f),Lt(r),(l,h,y,w,b=0)=>{F(l,void 0,"key"),F(h,void 0,"nonce"),F(y,void 0,"data");let U=y.length;if(w=gt(U,w,!1),dt(b),b<0||b>=_t)throw Error("arx: counter overflow");let L=[],m=l.length,E,I;if(m===32)L.push(E=wt(l)),I=Zt;else if(m===16&&r)E=new Uint8Array(32),E.set(l),E.set(l,16),I=qt,L.push(E);else throw F(l,32,"arx key"),Error("invalid key size");if(!ct||!yt(h))L.push(h=wt(h));let T=nt(E);if(n){if(h.length!==24)throw Error("arx: extended nonce must be 24 bytes");let tt=h.subarray(0,16);if(ct)n(I,T,nt(tt),T);else{let it=rt(Uint32Array.from(I));n(it,T,nt(tt),T),et(it),rt(T)}h=h.subarray(16)}else if(!ct)rt(T);let G=16-s;if(G!==h.length)throw Error(`arx: nonce must be ${G} or 16 bytes`);if(G!==12){let tt=new Uint8Array(12);tt.set(h,f?0:12-h.length),h=tt,L.push(h)}let ft=rt(nt(h));try{return Jt(t,I,T,ft,y,w,b,i),w}finally{et(...L)}}}function V(t,e){return t[e++]&255|(t[e++]&255)<<8}class Mt{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=wt(F(t,32,"key"));let e=V(t,0),r=V(t,2),n=V(t,4),s=V(t,6),f=V(t,8),i=V(t,10),l=V(t,12),h=V(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|f<<12)&255,this.r[5]=f>>>1&8190,this.r[6]=(f>>>14|i<<2)&8191,this.r[7]=(i>>>11|l<<5)&8065,this.r[8]=(l>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let y=0;y<8;y++)this.pad[y]=V(t,16+2*y)}process(t,e,r=!1){let n=r?0:2048,{h:s,r:f}=this,i=f[0],l=f[1],h=f[2],y=f[3],w=f[4],b=f[5],U=f[6],L=f[7],m=f[8],E=f[9],I=V(t,e+0),T=V(t,e+2),G=V(t,e+4),ft=V(t,e+6),tt=V(t,e+8),it=V(t,e+10),Y=V(t,e+12),Q=V(t,e+14),k=s[0]+(I&8191),A=s[1]+((I>>>13|T<<3)&8191),R=s[2]+((T>>>10|G<<6)&8191),C=s[3]+((G>>>7|ft<<9)&8191),S=s[4]+((ft>>>4|tt<<12)&8191),N=s[5]+(tt>>>1&8191),M=s[6]+((tt>>>14|it<<2)&8191),v=s[7]+((it>>>11|Y<<5)&8191),K=s[8]+((Y>>>8|Q<<8)&8191),H=s[9]+(Q>>>5|n),g=0,j=g+k*i+A*(5*E)+R*(5*m)+C*(5*L)+S*(5*U);g=j>>>13,j&=8191,j+=N*(5*b)+M*(5*w)+v*(5*y)+K*(5*h)+H*(5*l),g+=j>>>13,j&=8191;let W=g+k*l+A*i+R*(5*E)+C*(5*m)+S*(5*L);g=W>>>13,W&=8191,W+=N*(5*U)+M*(5*b)+v*(5*w)+K*(5*y)+H*(5*h),g+=W>>>13,W&=8191;let X=g+k*h+A*l+R*i+C*(5*E)+S*(5*m);g=X>>>13,X&=8191,X+=N*(5*L)+M*(5*U)+v*(5*b)+K*(5*w)+H*(5*y),g+=X>>>13,X&=8191;let z=g+k*y+A*h+R*l+C*i+S*(5*E);g=z>>>13,z&=8191,z+=N*(5*m)+M*(5*L)+v*(5*U)+K*(5*b)+H*(5*w),g+=z>>>13,z&=8191;let ot=g+k*w+A*y+R*h+C*l+S*i;g=ot>>>13,ot&=8191,ot+=N*(5*E)+M*(5*m)+v*(5*L)+K*(5*U)+H*(5*b),g+=ot>>>13,ot&=8191;let at=g+k*b+A*w+R*y+C*h+S*l;g=at>>>13,at&=8191,at+=N*i+M*(5*E)+v*(5*m)+K*(5*L)+H*(5*U),g+=at>>>13,at&=8191;let ht=g+k*U+A*b+R*w+C*y+S*h;g=ht>>>13,ht&=8191,ht+=N*l+M*i+v*(5*E)+K*(5*m)+H*(5*L),g+=ht>>>13,ht&=8191;let lt=g+k*L+A*U+R*b+C*w+S*y;g=lt>>>13,lt&=8191,lt+=N*h+M*l+v*i+K*(5*E)+H*(5*m),g+=lt>>>13,lt&=8191;let ut=g+k*m+A*L+R*U+C*b+S*w;g=ut>>>13,ut&=8191,ut+=N*y+M*h+v*l+K*i+H*(5*E),g+=ut>>>13,ut&=8191;let pt=g+k*E+A*m+R*L+C*U+S*b;g=pt>>>13,pt&=8191,pt+=N*w+M*y+v*h+K*l+H*i,g+=pt>>>13,pt&=8191,g=(g<<2)+g|0,g=g+j|0,j=g&8191,g=g>>>13,W+=g,s[0]=j,s[1]=W,s[2]=X,s[3]=z,s[4]=ot,s[5]=at,s[6]=ht,s[7]=lt,s[8]=ut,s[9]=pt}finalize(){let{h:t,pad:e}=this,r=new Uint16Array(10),n=t[1]>>>13;t[1]&=8191;for(let i=2;i<10;i++)t[i]+=n,n=t[i]>>>13,t[i]&=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 i=1;i<10;i++)r[i]=t[i]+n,n=r[i]>>>13,r[i]&=8191;r[9]-=8192;let s=(n^1)-1;for(let i=0;i<10;i++)r[i]&=s;s=~s;for(let i=0;i<10;i++)t[i]=t[i]&s|r[i];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 f=t[0]+e[0];t[0]=f&65535;for(let i=1;i<8;i++)f=(t[i]+e[i]|0)+(f>>>16)|0,t[i]=f&65535;et(r)}update(t){Et(this),F(t),t=wt(t);let{buffer:e,blockLen:r}=this,n=t.length;for(let s=0;s<n;){let f=Math.min(r-this.pos,n-s);if(f===r){for(;r<=n-s;s+=r)this.process(t,s);continue}if(e.set(t.subarray(s,s+f),this.pos),this.pos+=f,s+=f,this.pos===r)this.process(e,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,et(this.h,this.r,this.buffer,this.pad)}digestInto(t){Et(this),Tt(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 f=0;f<8;f++)t[s++]=r[f]>>>0,t[s++]=r[f]>>>8}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}}var vt=At(32,(t)=>new Mt(t));function te(t,e,r,n,s,f=20){let i=t[0],l=t[1],h=t[2],y=t[3],w=e[0],b=e[1],U=e[2],L=e[3],m=e[4],E=e[5],I=e[6],T=e[7],G=s,ft=r[0],tt=r[1],it=r[2],Y=i,Q=l,k=h,A=y,R=w,C=b,S=U,N=L,M=m,v=E,K=I,H=T,g=G,j=ft,W=tt,X=it;for(let ot=0;ot<f;ot+=2)Y=Y+R|0,g=_(g^Y,16),M=M+g|0,R=_(R^M,12),Y=Y+R|0,g=_(g^Y,8),M=M+g|0,R=_(R^M,7),Q=Q+C|0,j=_(j^Q,16),v=v+j|0,C=_(C^v,12),Q=Q+C|0,j=_(j^Q,8),v=v+j|0,C=_(C^v,7),k=k+S|0,W=_(W^k,16),K=K+W|0,S=_(S^K,12),k=k+S|0,W=_(W^k,8),K=K+W|0,S=_(S^K,7),A=A+N|0,X=_(X^A,16),H=H+X|0,N=_(N^H,12),A=A+N|0,X=_(X^A,8),H=H+X|0,N=_(N^H,7),Y=Y+C|0,X=_(X^Y,16),K=K+X|0,C=_(C^K,12),Y=Y+C|0,X=_(X^Y,8),K=K+X|0,C=_(C^K,7),Q=Q+S|0,g=_(g^Q,16),H=H+g|0,S=_(S^H,12),Q=Q+S|0,g=_(g^Q,8),H=H+g|0,S=_(S^H,7),k=k+N|0,j=_(j^k,16),M=M+j|0,N=_(N^M,12),k=k+N|0,j=_(j^k,8),M=M+j|0,N=_(N^M,7),A=A+R|0,W=_(W^A,16),v=v+W|0,R=_(R^v,12),A=A+R|0,W=_(W^A,8),v=v+W|0,R=_(R^v,7);let z=0;n[z++]=i+Y|0,n[z++]=l+Q|0,n[z++]=h+k|0,n[z++]=y+A|0,n[z++]=w+R|0,n[z++]=b+C|0,n[z++]=U+S|0,n[z++]=L+N|0,n[z++]=m+M|0,n[z++]=E+v|0,n[z++]=I+K|0,n[z++]=T+H|0,n[z++]=G+g|0,n[z++]=ft+j|0,n[z++]=tt+W|0,n[z++]=it+X|0}var ee=Nt(te,{counterRight:!1,counterLength:4,allowShortKeys:!1});var ne=new Uint8Array(16),Kt=(t,e)=>{t.update(e);let r=e.length%16;if(r)t.update(ne.subarray(r))},re=new Uint8Array(32);function Ht(t,e,r,n,s){if(s!==void 0)F(s,void 0,"AAD");let f=t(e,r,re),i=Ct(n.length,s?s.length:0,!0),l=vt.create(f);if(s)Kt(l,s);Kt(l,n),l.update(i);let h=l.digest();return et(f,i),h}var ie=(t)=>(e,r,n)=>({encrypt(f,i){let l=f.length;i=gt(l+16,i,!1),i.set(f);let h=i.subarray(0,-16);t(e,r,h,h,1);let y=Ht(t,e,r,h,n);return i.set(y,l),et(y),i},decrypt(f,i){i=gt(f.length-16,i,!1);let l=f.subarray(0,-16),h=f.subarray(-16),y=Ht(t,e,r,l,n);if(!kt(h,y))throw et(y),Error("invalid tag");return i.set(f.subarray(0,-16)),t(e,r,i,i,1),et(y),i}}),bt=Rt({blockSize:64,nonceLength:12,tagLength:16},ie(ee));var mt=Uint8Array.of(0),fe=Uint8Array.of();function ce(t,e,r,n=32,s){B(t),d(n,"length"),a(e,void 0,"prk");let f=t.outputLen;if(e.length<f)throw Error('"prk" must be at least HashLen octets');if(n>255*f)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(n/f);if(r===void 0)r=fe;else a(r,void 0,"info");if(!i){if(s)c(e);return new Uint8Array}let l=s&&i===1?e:new Uint8Array(i*f),{iHash:h,oHash:y}=x.create(t,e),w=s?e:new Uint8Array(f),b=i>1?s?.iHash||t.create():void 0;for(let L=0;L<i-1;L++){mt[0]=L+1;let m=h._cloneInto(b);if(L)m.update(w);m.update(r).update(mt).digestInto(w),y._cloneInto(b).update(w).digestInto(w),l.set(w,f*L)}if(mt[0]=i,i>1)h.update(w);if(h.update(r).update(mt).digestInto(w),y.update(w).digestInto(w),l.set(w,f*(i-1)),h.destroy(),y.destroy(),b?.destroy(),w!==l)c(w);if(c(mt),n===l.length)return l;let U=l.slice(0,n);return c(l),U}var P=(t,e,r,n,s)=>{if(B(t),r===void 0)r=new Uint8Array(t.outputLen);let f=x.create(t,r).update(e);return ce(t,f.digest(),n,s,f)};var oe="age-encryption.org/v1",D="-----BEGIN AGE ENCRYPTED FILE-----",J="-----END AGE ENCRYPTED FILE-----",Pt="age-encryption.org/v1/X25519",zt="age",jt="age-secret-key-",Ut=65536,ue=128,Bt=16,ae=new TextEncoder,$t=new TextDecoder,st=(t)=>ae.encode(t);class o extends Error{code;constructor(t,e){super(e);this.code=t,this.name="AgeError"}}function Z(t){if(t.length!==32)throw new o("bad_key","an X25519 public key is 32 bytes");return u.encode(zt,u.toWords(t),!1)}function ge(t){let e=t.trim(),r;try{r=u.decode(e,!1)}catch{throw new o("bad_key","not an age recipient (age1…)")}if(r.prefix!==zt)throw new o("bad_key",`not an age recipient: prefix ${r.prefix}`);let n=u.fromWords(r.words);if(n.length!==32)throw new o("bad_key","an age recipient carries 32 bytes");return n}function se(t){if(t.length!==32)throw new o("bad_key","an X25519 secret is 32 bytes");return u.encode(jt,u.toWords(t),!1).toUpperCase()}function Se(t){let e=t.trim().toLowerCase(),r;try{r=u.decode(e,!1)}catch{throw new o("bad_key","not an age identity (AGE-SECRET-KEY-1…)")}if(r.prefix!==jt)throw new o("bad_key",`not an age identity: prefix ${r.prefix}`);let n=u.fromWords(r.words);if(n.length!==32)throw new o("bad_key","an age identity carries 32 bytes");return n}function Ae(t){return Z(O.getPublicKey(t))}function he(t,e){let r=O.utils.randomSecretKey(),n=null,s=null;try{let f=O.getPublicKey(r);try{n=O.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 i=new Uint8Array(64);i.set(f,0),i.set(e,32),s=P(p,n,i,st(Pt),32);let l=bt(s,new Uint8Array(12)).encrypt(t);return{share:f,body:l}}finally{r.fill(0),n?.fill(0),s?.fill(0)}}function Wt(t,e){let r=P(p,t,new Uint8Array(0),st("header"),32),n=x(p,r,e);return r.fill(0),n}function Xt(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 Ft(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 be(t,e){if(e.length===0)throw new o("bad_key","seal it for at least one recipient");let r=e.map(ge),n=crypto.getRandomValues(new Uint8Array(16));try{let s=[oe];for(let U of r){let{share:L,body:m}=he(n,U);s.push(`-> X25519 ${q.encode(L)}`,q.encode(m))}s.push("---");let f=st(s.join(`
|
|
2
|
+
`)),i=Wt(n,f),l=st(`${s.join(`
|
|
3
|
+
`)} ${q.encode(i)}
|
|
4
|
+
`),h=crypto.getRandomValues(new Uint8Array(16)),y=P(p,n,h,st("payload"),32),w=[l,h],b=Math.max(1,Math.ceil(t.length/Ut));for(let U=0;U<b;U++){let L=t.subarray(U*Ut,Math.min(t.length,(U+1)*Ut));w.push(bt(y,Xt(U,U===b-1)).encrypt(L))}return y.fill(0),Ft(w)}finally{n.fill(0)}}var le=1048576,pe=/^[\x21-\x7e]+$/;function ye(t){let e=Math.min(t.length,le),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 y=$t.decode(t.subarray(r,h));return r=h+1,y};if(n()!==oe)throw new o("malformed","not an age file: missing version line");let s=[],f=null,i=0;while(f===null){i=r;let h=n();if(h.startsWith("---")){f=h;break}if(!h.startsWith("-> "))throw new o("malformed","unexpected header line");let y=h.slice(3).split(" ");if(!y.every((m)=>pe.test(m)))throw new o("malformed","stanza arguments must be non-empty visible ASCII");let[w,...b]=y,U=[];for(;;){let m=n();if(U.push(m),m.length<64)break;if(m.length>64)throw new o("malformed","stanza body line over 64 columns")}let L;try{L=q.decode(U.join(""))}catch{throw new o("malformed","stanza body is not base64")}if(s.push({type:w,args:b,body:L}),s.length>ue)throw new o("unsupported",`sealed for more than ${ue} readers`)}if(!f.startsWith("--- "))throw new o("malformed","header footer must be `--- ` and a MAC");let l;try{l=q.decode(f.slice(4))}catch{throw new o("malformed","header MAC is not base64")}if(l.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:l,upToDashes:t.subarray(0,i+3),payload:t.subarray(r)}}function me(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 we(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:f}=ye(t),i=r.filter((y)=>y.type==="X25519");if(i.length===0){let y=[...new Set(r.map((w)=>w.type))].join(", ")||"none";throw new o("unsupported",`no X25519 recipient in this file (stanzas: ${y})`)}let l=null,h=e.map((y)=>O.getPublicKey(y));for(let y of i){if(y.args.length!==1||y.body.length!==32)throw new o("malformed","bad X25519 stanza");let w;try{w=q.decode(y.args[0])}catch{throw new o("malformed","X25519 share is not base64")}if(w.length!==32)throw new o("malformed","X25519 share is not 32 bytes");for(let b=0;b<e.length;b++){let U;try{U=O.getSharedSecret(e[b],w)}catch{throw new o("malformed","X25519 share is a low-order point")}if(U.every((E)=>E===0))throw new o("malformed","X25519 share is a low-order point");let L=new Uint8Array(64);L.set(w,0),L.set(h[b],32);let m=P(p,U,L,st(Pt),32);U.fill(0);try{l=bt(m,new Uint8Array(12)).decrypt(y.body)}catch{l=null}finally{m.fill(0)}if(l)break}if(l)break}if(!l)throw new o("no_identity","none of your keys opens this");try{if(!me(Wt(l,s),n))throw new o("tampered","header MAC does not match");if(f.length<16)throw new o("malformed","payload shorter than its nonce");let y=f.subarray(0,16),w=P(p,l,y,st("payload"),32);try{let b=f.subarray(16),U=Ut+Bt,L=[],m=0,E=0;for(;;){let I=b.length-E;if(I<Bt)throw new o("malformed","payload chunk shorter than its tag");let T=I<=U,G=T?I:U;if(T&&G===Bt&&m>0)throw new o("malformed","empty final chunk");try{L.push(bt(w,Xt(m,T)).decrypt(b.subarray(E,E+G)))}catch{throw new o("tampered",`payload chunk ${m} does not authenticate`)}if(E+=G,m++,T)break}return Ft(L)}finally{w.fill(0)}}finally{l.fill(0)}}function ke(t){let e=de.encode(t),r=[];for(let n=0;n<e.length;n+=64)r.push(e.slice(n,n+64));return[D,...r,J].join(`
|
|
5
|
+
`)+`
|
|
6
|
+
`}function ve(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]!==D||n[n.length-1]!==J)throw new o("malformed","no armored age block found");let s=n.slice(1,-1);for(let f=0;f<s.length;f++){let i=f===s.length-1;if(s[f].length>64||!i&&s[f].length!==64||s[f].length===0)throw new o("malformed","armor: lines must be 64 columns, the last 1-64");if(!/^[A-Za-z0-9+/=]+$/.test(s[f]))throw new o("malformed","armored body is not base64")}try{return de.decode(s.join(""))}catch{throw new o("malformed","armored body is not base64")}}function xe(t){let e=t.replace(/\r\n?/g,`
|
|
9
|
+
`),r=e.indexOf(D),n=e.indexOf(J,r<0?0:r);if(r<0||n<0)throw new o("malformed","no armored age block found");let s=e.slice(r+D.length,n).split(`
|
|
10
|
+
`).map((f)=>f.trim()).filter((f)=>f.length>0);if(s.length===0)throw new o("malformed","armored block is empty");return[D,...s,J].join(`
|
|
11
|
+
`)}function Ee(t){let e=t.trimStart();return e.startsWith(D)||e.startsWith(oe)}function $e(t,e){return ke(be(st(t),e))}function _e(t,e){let r=t.includes(D)?ve(xe(t)):st(t);return we(r,e)}function Te(t,e){return $t.decode(_e(t,e))}
|
|
12
|
+
export{P,oe,D,J,ue,o,Z,ge,se,Se,Ae,be,ye,we,ke,ve,xe,Ee,$e,_e,Te};
|