oneie 5.9.0 → 5.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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. **Five wallets** from that key: Sui, Ethereum and Base, Solana,
13
- Bitcoin, ASI.
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,8 @@ 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 (--owner must be a key this SSH agent holds)
115
+ one agent keys --caller K --ssh K --sui K --owner-keys gh # the same, with the owner's public keys read from GitHub (gh ssh-key list + gh api user/keys) or a file of .pub lines; the owner's keys need not be in this agent
114
116
  one skill new | import <ref> | publish
115
117
  one init --name N --email E # zero-to-live: register + workspace + agent + skills
116
118
  one dev # boot the local CF stack: build → D1 migrate → wrangler dev
@@ -118,6 +120,15 @@ one connect telegram --token T # connect a channel by pasting its credential
118
120
  one trail <tag,tag> # ranked next-best tasks for a tag combination
119
121
  ```
120
122
 
123
+ ### An agent's own keys — money and SSH, never the owner's
124
+
125
+ ```bash
126
+ one wallet send 0.001 SUI <0x…> --chip <key> --owner-keys gh --net testnet # DRY: the chip key's Sui address and what would be signed; asks nothing of ONE
127
+ one wallet send 0.001 SUI <0x…> --chip <key> --owner-keys gh --net testnet --live --yes # signed in the chip (a P-256 key the SSH agent holds), checked against the key before the node sees it; SUI to a typed address, testnet only until a vault limit stands behind it
128
+ one ssh <user>@<host> [--minutes 5] [--ca SHA256:…] [-- <command>] # a key made in memory, a pass from ONE (secrets:ssh-pass) for <user>@<host> alone, minutes long, no forwarding; checked here, used once through a throwaway agent, then gone
129
+ one ssh <user>@<host> --print # ask for the pass and show what it allows; runs nothing
130
+ ```
131
+
121
132
  ## Your workspace's name — one.ie/u/<name>
122
133
 
123
134
  ```bash
@@ -178,6 +189,22 @@ is kept as a new version (`~/.one/browser/paths/`, `--sync` also as a workflow:
178
189
  steps). Live verbs need the verbs viewer (`one-view --caps` says `verbs`); until it is installed,
179
190
  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
191
 
192
+ ## Directories — file a business in ONE's Browser, you press submit
193
+
194
+ ```bash
195
+ one directories list --category general --free # the registry (306 directories)
196
+ one directories start acme google-business-profile elocal # queue a run: a frozen pack per directory
197
+ one directories run acme --batch 10 # fill the queued forms in acme's agent tab; you submit
198
+ one directories done acme <row-id> --live <listing-url> # record a row: submitted, then live
199
+ ```
200
+
201
+ Each client gets its own agent tab and cookie jar (`--profile agent-dir-<workspace>`). The hand types only
202
+ what it is sure of (business name, phone, email, website, address, city, tagline, description) and
203
+ leaves the rest to you by name: dropdowns, uploads, consent boxes, anything ambiguous, and the submit.
204
+ It never solves a challenge, makes an account or keeps a password. A directory filled once is kept
205
+ as a path and replays for the next client with no model. Until the verbs viewer is installed, `run`
206
+ prints the plan and opens nothing. Spec: `text/directory-browser-plan.md`.
207
+
181
208
  ## Tasks — see, sequence, act
182
209
 
183
210
  ```bash
@@ -222,6 +249,19 @@ one login --key <key> # or paste a key directly
222
249
 
223
250
  **When the class matters:** keys minted by `one init`/`onboard`/`setup` are *agent-class* and are categorically blocked from the human-management receivers (`manage_actors`, `manage_lifecycle`, `manage_members`, …) — the error is `forbidden` with `callerRole: "agent"`. If you hit that wall, `one login` is the fix. Full model: `text/api-keys-docs.md § Two key classes`.
224
251
 
252
+ **Reading a refusal.** `one signal` / `ask` / `mark` / `warn`, `one tasks …` and `one client …` read the
253
+ `WWW-Authenticate` challenge and say which of three it is, exit 1:
254
+
255
+ | Refusal | Prints |
256
+ |---|---|
257
+ | 401 `invalid_token` | your key expired or was revoked — run `oneie login`, or re-register (see https://one.ie/auth.md) |
258
+ | 401, no key | sign in first — run `oneie login` |
259
+ | 403 `insufficient_scope` | this key lacks `<scope>` — claim the agent to unlock it |
260
+
261
+ Each also prints the `resource_metadata` URL. Under `--json` the line is
262
+ `{"ok":false,"error":"invalid_token","status":401,"resource_metadata":"…","hint":"…","body":<one.ie's raw body>}` on stdout.
263
+ A plain 403 (a real key refused for that workspace) is unchanged — it needs a key with authority there, not a new one.
264
+
225
265
  Workspace operations use a Bearer token `<slug>:<key>`. Override the API base per command with `--api` (default `https://api.one.ie`, the gateway).
226
266
 
227
267
  ## Join an existing group
@@ -244,7 +284,7 @@ A key is 24 words you write on paper. ONE never holds it and cannot recover it.
244
284
  one key new # mint 24 words, printed ONCE, for paper (v2: standard BIP-44 paths — what one.ie mints)
245
285
  one key new --derivation v1 # the original ONE derivation (HKDF labels)
246
286
  one key recover # rebuild from your words — prints BOTH address sets
247
- one key public # the public identity + four chain addresses; both sets unless you name --derivation
287
+ one key public # the public identity + its addresses (five under v2, four under v1); both sets unless you name --derivation
248
288
  one key verify # compare this key's public identity with the server: locked | verified | mismatch | unregistered
249
289
  ```
250
290
 
@@ -309,10 +349,26 @@ one wallet register --from keys.json --workspace <slug> # register the PU
309
349
  one wallet transactions --workspace <slug> --limit 50 # unified feed across every settlement rail
310
350
  one wallet faucet <address> --chain sui # fund from testnet — sui/sol auto-fund, others return a manual URL
311
351
  one wallet send <to> --chain SUI --amount 5 --payment-tx <hash> --workspace <slug>
352
+ 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)
353
+ 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
354
+ 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
355
  one wallet keygen # mint a self-hosted 4-chain wallet locally (a fresh one is v2), offline
313
356
  one wallet paper # reprint the 24 words for paper — terminal only, same refusals as `one key new`
314
357
  ```
315
358
 
359
+ ### Two keys for a destructive act — `one two-key`
360
+
361
+ Deleting a group, removing an owner, repointing where money lands: one admin proposes the exact act, a different admin approves it with their own key, on Sui. Dry unless `--live`; each signs with your own vault in `--dir`.
362
+
363
+ ```bash
364
+ one two-key propose --door world:remove-group --group acme --target group:acme --board 0x… --package 0x… --hours 24
365
+ one two-key approve <proposal> --door world:remove-group --group acme --target group:acme --board 0x… --package 0x… # name the act: the hash is rebuilt from it
366
+ one two-key cancel <proposal> --board 0x… --package 0x… # any admin, at once
367
+ one two-key status <proposal> # keyless
368
+ one ceiling raise <ceilingId> --per-tx 50 # a raise waits a day; apply-raise lands it, cancel-raise stops it
369
+ one move seal <upgradeCap> --dir <vault> # make a package immutable; reads the cap back as gone
370
+ ```
371
+
316
372
  ### Swap — any coin, or straight into Hyperliquid
317
373
 
318
374
  ```bash
@@ -325,6 +381,18 @@ one swap assets # every alias, chain, decimals and wh
325
381
  one hl balance 0x… # Hyperliquid perps + spot (never summed); no address = your EVM wallet
326
382
  ```
327
383
 
384
+ ### Trade Hyperliquid — in dollars, with leverage
385
+
386
+ ```bash
387
+ one hl leverage BTC 3 # set BTC to 3x isolated (dry: the action + digest; nothing sent)
388
+ one hl leverage ETH 5 --cross --live # sign with your vault and post; moves no money
389
+ one hl buy BTC --usd 20 --lev 5 # $20 at 5x: size = 20 × 5 ÷ mid, floored; leverage first if it differs
390
+ one hl sell ETH --usd 25 # $25 short at the account's current leverage
391
+ one hl buy BTC --usd 20 --lev 5 --live --dir ~/.one/you
392
+ ```
393
+
394
+ 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.
395
+
328
396
  `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
397
 
330
398
  `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 +409,12 @@ one finance pnl [--months N] # the P&L by month; open rul
341
409
  one ramp status # add money / cash out: open or not, every reason, what comes next (anyone)
342
410
  one front-desk set <slug> --file playbook.json # a client's AI front desk playbook: answers, qualifying questions, booking rules, hand-off (owner)
343
411
  one front-desk get <slug> # read the playbook back as written (owner)
412
+ one alerts show <slug> # who a visitor's "I want a person" reaches: your team, then the agency above (owner)
413
+ one alerts set <slug> --email a@b.com --phone +1555… # set the emails and phones the alert goes to; --clear returns to the derived team
414
+ one alerts whatsapp <slug> <number> [--start --agree|--off] # the alert on your own WhatsApp: shows the words you agree to, then a link that proves the number is yours
415
+ one sms send <to> <body> --purpose marketing [--workspace S] [--campaign ID] # one text from your workspace's own Twilio number, behind the consent gate
416
+ one mail claim [handle] | address | inbox | send <to> <subject> <text> # your own address on inbox.one.ie; mail to it lands in your inbox, read-only
417
+ 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
418
  one workflow list --slug S # list workflows for a workspace
345
419
  one workflow pull <id> --slug S [--out D] # round-trip a workflow's step graph to a local file
346
420
  one workflow push <id> <file> --slug S [--commit] # apply a diff — simulates first, --commit persists
@@ -353,12 +427,38 @@ one broadcast list | send <id> # blasts to a workspace au
353
427
  one segment list | preview <id> # audience segments — live count + sample
354
428
  one newsletter pull <id> | push <id> <file> # round-trip newsletter content as a local file
355
429
  one social list --group G | create --group G ... # draft/publish/list social posts
430
+ one social queue [--group G] # what waits for approval; an owner/admin approves on the social page
356
431
  one fn run <name> '{json}' | list # call an allowlisted analytics/routing RPC
357
432
  one coordinate recall [about] | reputation [uid] # cross-session memory and reputation
358
433
  one group bulk-create --csv # idempotent batch client provisioning
359
434
  one shop init [--facts F] [--workspace S] # seed the twelve-page shop pack; a fact left out stays a VISIBLE placeholder
360
435
  ```
361
436
 
437
+ 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.
438
+
439
+ `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).
440
+
441
+ ## Secrets — `one secrets` and `one reset`
442
+
443
+ 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.
444
+
445
+ ```bash
446
+ 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
447
+ one secrets add-device [--name L] [--replace] # make this Mac a reader — a Secure Enclave key opened by Touch ID
448
+ 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
449
+ one secrets hash [file] # the sha256 of a sealed file, to set on your vault
450
+ 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
451
+ one secrets list # your desk: the keys you gave ONE, who uses them, keys lent to you — names and meters, never values
452
+ 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
453
+ one reset [--dir D] [--yes] # set .one aside (renamed .one.bak-<time>) so the next `oneie` is a first run; never deletes
454
+ ```
455
+
456
+ `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.
457
+
458
+ `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>`.
459
+
460
+ `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.
461
+
362
462
  ## Your own endpoints — a tenant's HTTPS, called by a workflow
363
463
 
364
464
  Register an HTTPS endpoint you own and let a workflow `tool` step call it. The
@@ -377,6 +477,25 @@ one endpoint call <name> --input '{json}' # the same door a workflow `tool` st
377
477
  `--workspace` on any of these is a workspace you must already control: one you
378
478
  may not write is **refused**, never silently downgraded to your own.
379
479
 
480
+ ### The one door the other way — your inbound webhook
481
+
482
+ Every workspace can have **one** inbound URL that any tool POSTs JSON events to
483
+ (Supermove's Invoke Webhook, a booking tool, a Zapier step). `lead` lands a lead,
484
+ `booked` marks the matching contact booked with its job value, and anything else
485
+ is kept as a signal and answered `unhandled`. The secret is in the path, so the
486
+ URL is printed **once**; minting again stops the old one.
487
+
488
+ ```bash
489
+ one endpoint inbound [--workspace S] # make it, or rotate it (the old URL answers 401 from that moment)
490
+ one endpoint inbound --status # mint nothing: is one live, and when did a tool last call it
491
+ one lead cost [--variants] [--workspace S] # cost per booked move: ad spend per campaign against its bookings
492
+ ```
493
+
494
+ The event a tool sends: `{ "event": "booked", "phone": "+15550100", "job_value_cents": 189900,
495
+ "booked_at": 1795000000, "source": "supermove", "external_id": "job-77" }`. The answer is
496
+ `{ ok, event, matched, action }`; a booking that matches nobody answers `unmatched`. A `booked`
497
+ event needs `external_id` or `booked_at`, or it is refused (`external_id_or_booked_at_required`).
498
+
380
499
  An endpoint is reachable **two** ways, and the second one is why an outside
381
500
  agent can join at all. A workflow `tool` step names it —
382
501
  `{ 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.9.0",
3
+ "version": "5.10.1",
4
4
  "description": "Give your agent financial superpowers. One command makes a key on your machine, five wallets, a shop and a test sale — your agent can sell and be paid in USDC, and asks you before real money moves.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -48,7 +48,7 @@
48
48
  "@noble/curves": "^2.2.0",
49
49
  "@noble/hashes": "^2.2.0",
50
50
  "@oneie/evals": "^0.2.0",
51
- "@oneie/sdk": "^0.17.6",
51
+ "@oneie/sdk": "^0.17.10",
52
52
  "@types/node": "^25.6.0",
53
53
  "commander": "^12.0.0",
54
54
  "tsx": "^4.0.0",
@@ -0,0 +1 @@
1
+ import{sn,Be,Ht,In,c,zt,jn,an,Mn,Fn,Nn,Pn,Un,Ln,Dn,Bn,Kn,Hn,qn,zn}from"./index-sdgefh6q.js";export{Be as AGE_ARMOR_BEGIN,Ht as AGE_ARMOR_END,sn as AGE_VERSION_LINE,c as AgeError,In as MAX_STANZAS,Ln as armor,Dn as dearmor,Mn as decodeIdentity,jn as decodeRecipient,Un as decrypt,an as encodeIdentity,zt as encodeRecipient,Nn as encrypt,Bn as extractArmored,Kn as looksLikeAge,qn as openBytes,zn as openText,Pn as parseHeader,Fn as recipientOf,Hn as sealText};
@@ -0,0 +1 @@
1
+ import{o,i,s,n,e}from"./index-abbkxz62.js";export{s as authHeaders,n as jsonMode,e as out,o as resolveBase,i as resolveKey};
@@ -1 +1 @@
1
- import{d,R}from"./index-st6k9vhc.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(R(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 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 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 l(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 b(e,t){let r=R(c([Uint8Array.of(2),u(l(e))])),n=d.sign(r,t,{prehash:!1,format:"recovered"}),o=n[0],p=n.slice(1,33),x=n.slice(33,65),g=u([...l(e),s(o),s(BigInt(`0x${i(p)}`)),s(BigInt(`0x${i(x)}`))]);return`0x02${i(g)}`}function U(e){return`0x${i(R(a(e)))}`}function E(e){let t=d.getPublicKey(e,!1);return h(`0x${i(R(t.slice(1)).slice(12))}`)}function k(e,t){return`0xa9059cbb${e.toLowerCase().replace(/^0x/,"").padStart(64,"0")}${t.toString(16).padStart(64,"0")}`}export{h as checksumAddress,k as encodeErc20Transfer,E as evmAddressFromKey,w as evmRecipientProblem,U as evmTxHash,a as hexToBytes,u as rlpEncode,b as signEip1559};
1
+ import{h,R}from"./index-abbkxz62.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 d(e){let t=e.toLowerCase().replace(/^0x/,""),r=i(R(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 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()&&d(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 l(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 b(e,t){let r=R(c([Uint8Array.of(2),u(l(e))])),n=h.sign(r,t,{prehash:!1,format:"recovered"}),o=n[0],p=n.slice(1,33),x=n.slice(33,65),g=u([...l(e),s(o),s(BigInt(`0x${i(p)}`)),s(BigInt(`0x${i(x)}`))]);return`0x02${i(g)}`}function U(e){return`0x${i(R(a(e)))}`}function E(e){let t=h.getPublicKey(e,!1);return d(`0x${i(R(t.slice(1)).slice(12))}`)}function k(e,t){return`0xa9059cbb${e.toLowerCase().replace(/^0x/,"").padStart(64,"0")}${t.toString(16).padStart(64,"0")}`}export{d as checksumAddress,k as encodeErc20Transfer,E as evmAddressFromKey,w as evmRecipientProblem,U as evmTxHash,a as hexToBytes,u as rlpEncode,b as signEip1559};
@@ -0,0 +1 @@
1
+ import{T,h,R}from"./index-abbkxz62.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 c 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 c("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 c("size_zero");if(C(r)>t)throw new c("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 c("price_zero");if(at(n))return n;if(Re(n)>5)throw new c("price_sig_figs",`${n} has ${Re(n)} significant figures, max 5`);let s=Te[r]-t;if(C(n)>s)throw new c("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 c("amount_zero");if(C(t)>6)throw new c("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 c("price_zero","mid");if(!(r>=0&&r<1))throw new c("bad_slippage",String(r));let o=i*(t?1+r:1-r),a=Number(o.toPrecision(5)),l=Math.max(0,Te[s]-n);return ge(Z(a.toFixed(l),"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=(d,...p)=>{n.set(d.asset,d);for(let y of p)if(!r.has(y))r.set(y,d)},i=z(e)?e:{};(Array.isArray(i.universe)?i.universe:[]).forEach((d,p)=>{if(!z(d)||typeof d.name!=="string"||typeof d.szDecimals!=="number")return;s({coin:d.name,label:d.name,asset:p,szDecimals:d.szDecimals,kind:"perp",delisted:d.isDelisted===!0,...typeof d.maxLeverage==="number"?{maxLeverage:d.maxLeverage}:{},...d.onlyIsolated===!0?{onlyIsolated:!0}:{}},d.name)});let a=z(t)?t:{},l=new Map;for(let d of Array.isArray(a.tokens)?a.tokens:[])if(z(d)&&typeof d.index==="number")l.set(d.index,d);for(let d of Array.isArray(a.universe)?a.universe:[]){if(!z(d)||typeof d.index!=="number"||typeof d.name!=="string"||!Array.isArray(d.tokens))continue;let[p,y]=d.tokens,f=l.get(p),_=l.get(y);if(!f||typeof f.szDecimals!=="number")continue;let S=`${String(f.name)}/${String(_?.name??"?")}`;s({coin:d.name,label:S,asset:Q+d.index,szDecimals:f.szDecimals,kind:"spot",delisted:!1},d.name,S)}return{byName:r,byIndex:n}}function me(e,t){let r=e.byName.get(t);if(!r)throw new c("unknown_asset",t);if(r.delisted)throw new c("asset_delisted",t);return r}function he(e,t){if(t>=F)throw new c("builder_dex_unsupported",String(t));let r=e.byIndex.get(t);if(!r)throw new c("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 c("bad_tif",String(t));if(e.asset.delisted)throw new c("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 c("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 c("unknown_asset",String(t));if(t>=F)throw new c("builder_dex_unsupported",String(t));if(!Number.isSafeInteger(e.oid)||e.oid<0)throw new c("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 c("unknown_asset",String(t));if(t>=F)throw new c("builder_dex_unsupported",String(t));if(e.asset.kind==="spot"||t>=Q)throw new c("leverage_spot",e.asset.coin);if(typeof e.isCross!=="boolean")throw new c("bad_leverage","isCross must be true or false");if(!Number.isSafeInteger(e.leverage)||e.leverage<1)throw new c("bad_leverage",String(e.leverage));if(e.asset.maxLeverage!==void 0&&e.leverage>e.asset.maxLeverage)throw new c("leverage_too_high",`${e.leverage}x, max ${e.asset.maxLeverage}x on ${e.asset.coin}`);if(e.isCross&&e.asset.onlyIsolated)throw new c("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 c("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 c("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 c("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 c("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 c("eip712_value",`${r} not a uint`);if(n<0n||n>=1n<<BigInt(t))throw new c("eip712_range",r);return n}function pt(e,t){switch(e.type){case"string":if(typeof t!=="string")throw new c("eip712_value",`${e.name} not a string`);return R(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 c("eip712_value",`${e.name} not bytes32`);return r}case"address":{if(typeof t!=="string"||!/^0x[0-9a-fA-F]{40}$/.test(t))throw new c("eip712_value",`${e.name} not an address`);return ce(BigInt(t))}case"bool":if(typeof t!=="boolean")throw new c("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 c("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=[R(new TextEncoder().encode(ft(e,t)))];for(let i of t){if(!(i.name in r))throw new c("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)),R(s)}function V(e){let t=e.types[e.primaryType];if(!t)throw new c("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),R(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 c("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,l)=>a+l.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 c("bad_hex",s);let i={...r,hyperliquidChain:n==="mainnet"?"Mainnet":"Testnet"},o={};for(let a of t){if(!(a.name in i))throw new c("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 c("unsupported_action",`hyperliquidChain ${String(r)} on ${t.net}`);let o=(t.signatureChainId??$e).toLowerCase();if(n!==void 0&&String(n).toLowerCase()!==o)throw new c("unsupported_action",`signatureChainId ${String(n)} ≠ ${o}`);return s}function vt(e,t){let r=t.assets;if(!e||typeof e!=="object")throw new c("unsupported_action","not an object");let n,s=e;switch(e.type){case"order":{if(!r)throw new c("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 c("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 c("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 c("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 c("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 c("unsupported_action",String(e.type))}if(!(Ve(n)?We(n,s):At(n,s)))throw new c("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 c("nonce_required");if(t.vaultAddress!==void 0&&!Me.test(t.vaultAddress))throw new c("bad_address",t.vaultAddress);if(t.expiresAfter!==void 0&&(!Number.isSafeInteger(t.expiresAfter)||t.expiresAfter<=0))throw new c("expires_unsupported",String(t.expiresAfter));let l=t.vaultAddress?.toLowerCase()??null,d=t.expiresAfter??null,p=ht(r,l,t.nonce,d),y=R(p),f=bt(y,t.net);return{kind:"l1",network:t.net,action:r,nonce:t.nonce,vaultAddress:l,expiresAfter:d,msgpackHex:L(G(r)),hashInputHex:L(p),connectionId:j(y),typedData:f,digest:j(V(f)),exchangeUrl:ue[t.net],posted:!1}}if(t.vaultAddress!==void 0)throw new c("vault_unsupported",r.type);if(t.expiresAfter!==void 0)throw new c("expires_unsupported",r.type);let n=xt[r.type],s=r[n.nonceField];if(t.nonce!==void 0&&t.nonce!==s)throw new c("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(([l])=>l!=="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 c("bad_signature",`length ${t.length}`);let r=t[64]<27?t[64]+27:t[64];if(r!==27&&r!==28)throw new c("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 c("bad_signature",`v=${t.v}`);let s=q(`${(t.v-27).toString(16).padStart(2,"0")}${n(t.r)}${n(t.s)}`),i=h.recoverPublicKey(s,r,{prehash:!1}),o=h.Point.fromBytes(i).toBytes(!1);return j(R(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 c("signer_mismatch","the digest shown is not the digest being signed");if(!Me.test(r.address))throw new c("bad_address",r.address);let{EIP712Domain:i,...o}=s.typedData.types,a=await r.signTypedData(s.typedData.domain,o,s.typedData.message),l=_t(a),d=St(s.digest,l);if(d!==r.address.toLowerCase())throw new c("signer_mismatch",`recovered ${d}, expected ${r.address}`);return{dry:s,request:{action:s.action,nonce:s.nonce,signature:l,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 g(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 D(e,t={}){if(e instanceof c)return g(e.code,e.detail??e.message,t);let r=e?.code;return g(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 c("eip712_type",`expected one primary type, got ${i.length}`);let o=V({domain:r,types:{...n,EIP712Domain:W},primaryType:i[0],message:s}),a=h.sign(o,t,{prehash:!1,format:"recovered"}),l=new Uint8Array(65);return l.set(a.slice(1,65),0),l[64]=a[0]+27,`0x${L(l)}`}}}var O=(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=O(n.data)?n.data:{},o=O(i.marginSummary)?i.marginSummary:{},a=O(s.data)&&Array.isArray(s.data.balances)?s.data.balances:[];return{perps:{accountValue:K(o.accountValue),withdrawable:K(i.withdrawable)},spot:a.filter(O).map((l)=>({coin:String(l.coin??"?"),total:String(l.total??"?"),hold:String(l.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}:g("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 g(String(s.error??"wallet_read_failed"),"Could not read your workspace wallet — pass an address.");let o=(Array.isArray(s.addresses)?s.addresses:[]).filter((l)=>l.chain==="evm"&&typeof l.address==="string"&&ve.test(l.address)&&(!t||l.actor===t)),a=[...new Map(o.map((l)=>[l.address.toLowerCase(),l])).values()];if(a.length===0)return g("no_evm_address","Your workspace has no EVM address registered — pass one.");if(a.length>1)return g("ambiguous_address",`Several EVM addresses — pass one, or --actor <id>: ${a.map((l)=>`${l.actor??"?"} ${l.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 g(s.error,s.detail,{network:r});let i=O(s.data)?s.data:{},o=O(i.marginSummary)?i.marginSummary:{},a=(Array.isArray(i.assetPositions)?i.assetPositions:[]).map((l)=>O(l)&&O(l.position)?l.position:null).filter((l)=>l!==null).map((l)=>({coin:String(l.coin??"?"),size:String(l.szi??"?"),entryPx:l.entryPx??null,positionValue:l.positionValue??null,unrealizedPnl:l.unrealizedPnl??null,liquidationPx:l.liquidationPx??null,leverage:O(l.leverage)?l.leverage:null}));return t.say([`${n.address} on ${r} — perps account ${K(o.accountValue)??"—"} USDC, withdrawable ${K(i.withdrawable)??"—"}`,...a.length?a.map((l)=>` ${l.coin.padEnd(8)} ${l.size.startsWith("-")?"short":"long "} ${l.size.replace(/^-/,"")} @ ${String(l.entryPx??"—")} value ${String(l.positionValue??"—")} pnl ${String(l.unrealizedPnl??"—")} liq ${String(l.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 g(s.error,s.detail,{network:r});if(!Array.isArray(s.data))return g("hyperliquid_unavailable","openOrders did not answer a list",{network:r});let i=s.data.filter(O).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 g("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 g(n.error,n.detail,{network:t});try{return{table:n.data,info:me(n.data,e)}}catch(s){return D(s,{network:t,next:Ht})}}async function tt(e,t,r){let n=await Ne(t,{fetchImpl:r.fetchImpl});if(!n.ok)return g(n.error,n.detail,{network:t});return n.data[e.coin]??g("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 g("bad_side","The side is buy or sell.");if(e.tif!==void 0&&e.limit===void 0&&e.tif!=="Ioc")return g("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",l=e.reduceOnly===!0,d=[e.limit!==void 0?`--limit ${e.limit}`:"",e.tif?`--tif ${e.tif}`:"",l?"--reduce-only":"",e.slippage?`--slippage ${e.slippage}`:""].filter(Boolean).join(" ");return{cmdline:`one hl order ${o} ${e.size} ${e.coin}${d?` ${d}`:""}`,build(p){let y=e.limit!==void 0?be({asset:n,isBuy:a,sz:e.size,px:e.limit,tif:e.tif??"Gtc",reduceOnly:l}):Ue({asset:n,isBuy:a,sz:e.size,mid:s,slippage:i,reduceOnly:l}),f=y.orders[0],_=n.kind==="spot"?"spot":"perps",S=_e(f.s,f.p),w=f.t.limit.tif,b=e.limit===void 0?`now, at ${a?"up to":"no less than"} ${f.p} (mid ${s} ${a?"+":"−"} ${i*100}%) — IOC: fills what it can at that cap, cancels the rest`:w==="Gtc"?`at ${f.p} or better — Gtc: rests on the book until filled or cancelled`:w==="Ioc"?`at ${f.p} or better — IOC: fills what it can now, cancels the rest`:`at ${f.p} — Alo (post-only): refused if it would take liquidity`,A=[`${a?"Buy":"Sell"} ${f.s} ${n.label} (${_}, asset ${f.a}) ${b}.`,`${a?"At most":"About"} ${S} 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.`:`${l?"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:y,opts:{net:t,nonce:p,assets:r},words:A,facts:{coin:n.coin,label:n.label,kind:n.kind,asset:f.a,side:o,size:f.s,price:f.p,tif:w,reduceOnly:l,notionalUsdc:S,...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 g("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 g(n.error,n.detail,{network:r});let s;try{s=me(n.data,e.coin)}catch(o){return D(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 g("bad_to","--to perps (spot → perps) or --to spot (perps → spot).");let s=n==="perps";try{B(e.amount)}catch(i){return D(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 g("bad_address","--to is an Arbitrum 0x address of 40 hex characters.");try{B(e.amount)}catch(i){return D(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,l=e.to??a;if(!l)throw new c("bad_address","no destination");let d=a===null||l.toLowerCase()!==a.toLowerCase();if(r&&o!==null&&d)throw new Ze("to_other_refused",`An agent withdraws only to its own address (${o}); ${l} is another. A person signs that one.`);let p=le({destination:l,amount:e.amount,time:i});return{action:p,opts:{net:n},words:[`Send ${p.amount} USDC from the PERPS balance${a?` of ${a}`:""} to ${l} on Arbitrum.${d?" THIS IS SOMEONE ELSE'S ADDRESS (toOther) — a withdrawal cannot be undone.":" That is the same key on Arbitrum — your own address."}`,"Hyperliquid documents a 1 USDC withdrawal fee (unverified here): what lands is in its answer and the Arbitrum receipt, not computed by ONE.","Withdrawals leave from PERPS on a split account (move spot USDC first: one hl transfer <amount> --to perps); a unified account may withdraw from its one balance — unverified, the exchange's answer is the record.","ONE's Arbitrum signer is external: ONE cannot send it on from Arbitrum. Open that address in MetaMask or Rabby (same key)."],facts:{amount:p.amount,destination:p.destination,toOther:d}}}}}function rt(e){if(!/^\d{1,4}$/.test(e.trim()))return g("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 D(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||!O(s.data)||!O(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 g("bad_side","The side is buy or sell.");if(!/^\d+(\.\d+)?$/.test(e.usd)||!(Number(e.usd)>0))return g("bad_usd",`--usd is a dollar amount (20, 12.5), not ${JSON.stringify(e.usd)}.`);let s=null;if(e.lev!==void 0){let A=rt(e.lev);if(typeof A!=="number")return A;s=A}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:l}=o,d=e.cross===!0;if(s!==null)try{M({asset:a,leverage:s,isCross:d})}catch(A){return D(A,{network:r})}else if(d)return g("cross_needs_lev","--cross sets the margin mode together with the leverage — pass --lev <n> too.",{network:r});let p=await tt(a,r,t);if(typeof p!=="string")return p;let y=s!==null?_e(e.usd,String(s)):e.usd,f=De(y,p,a.szDecimals),_=f===null?"0":_e(f,p),S=s!==null?`$${e.usd} × ${s}x = $${y}`:`$${e.usd}`;if(f===null||Number(_)<ie)return g("below_minimum",`${S} buys ${f??"less than one lot of"} ${a.label}${f?`, worth $${_} at mid ${p}`:""} — 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 w=[`--usd ${e.usd}`,s!==null?`--lev ${s}`:"",d?"--cross":"",e.slippage?`--slippage ${e.slippage}`:""].filter(Boolean).join(" "),b=nt({side:n,size:f,coin:e.coin,slippage:e.slippage},r,l,a,p,i);return{cmdline:`one hl ${n} ${e.coin} ${w}`,side:n,info:a,table:l,usd:e.usd,lev:s,isCross:d,mid:p,size:f,notionalUsdc:_,order:b}}function it(e,t){let r=e.dir??".",n=T(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 g("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 g("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 g("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 x,U;try{x=a.build(n.now(),null),U=J(x.action,x.opts)}catch(u){return D(u,{network:i})}let v=s.abstractionFor??null;if(e==="transfer"&&!v){let u=await re(void 0,void 0,n);if("ok"in u&&u.ok===!0)v=u.address}let X=e==="transfer"?await Ke(v,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}`,...x.words.map((u)=>` ${u}`),...e==="transfer"?[Je(X),...v?[`account ${v}`]:[]]:[],...Se(U),`next ${se}`]),{data:{ok:!0,live:!1,posted:!1,network:i,verb:e,consequence:x.words,...x.facts,...e==="transfer"?{abstraction:X??null,account:v}:{},...Ie(U),next:se}}}let l=await n.unlock(t.dir??".");if("error"in l)return g("vault_unavailable",l.error,{network:i,next:"Name the folder that holds .one/wallet.json: --dir ~/.one/<you>"});let d=l.keys.find((x)=>x.chain==="evm");if(!d)return g("no_evm_key",`The vault at ${t.dir??"."} holds no EVM key.`,{network:i});let p=Qe(d),y,f;try{y=a.build(n.now(),p.address),f=J(y.action,y.opts)}catch(x){return D(x,{network:i,signer:p.address})}let _=await te(p.address,i,n),S=e==="transfer"?await Ke(p.address,i,n):void 0;if(n.say([`LIVE · ${e} on ${i} · signer ${p.address} (the vault's EVM key)`,...ne("before",_),...y.words.map((x)=>` ${x}`),...e==="transfer"?[Je(S)]:[],...Se(f)]),!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 w;try{({request:w}=await ke(y.action,y.opts,p,{expectDigest:f.digest}))}catch(x){return D(x,{network:i,signer:p.address,posted:!1})}let b=await Ae(w,i,{fetchImpl:n.fetchImpl}),A=await te(p.address,i,n);return n.say([`exchange ${JSON.stringify(b.ok?b.response:{error:b.error,detail:b.detail,response:b.response??null})}`,...ne("after ",A)]),{data:{ok:b.ok,...b.ok?{}:{error:b.error,detail:b.detail},live:!0,posted:!0,network:i,verb:e,signer:p.address,...y.facts,...e==="transfer"?{abstraction:S??null}:{},...Ie(f),signature:w.signature,exchange:b.ok?b.response:b.response??null,balanceBefore:_,balanceAfter:A}}}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=(u)=>i.lev!==null&&!(u&&u.value===i.lev&&u.type===o),l=(u,k)=>{let m=[],I=t.now();if(a(u)){let Y=st(i.info,i.lev,i.isCross,n,i.table,I);m.push({step:"leverage",built:Y,dry:J(Y.action,Y.opts)}),I=Math.max(t.now(),I+1)}let H=i.order.build(I,k);return m.push({step:"order",built:H,dry:J(H.action,H.opts)}),m},d=i.lev!==null?(Number(i.notionalUsdc)/i.lev).toFixed(2):null,p=`${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${d?`; margin about $${d} USDC at ${i.lev}x`:""}.`,y=(u,k)=>i.lev===null?"leverage unchanged — no --lev, so the order uses whatever this account has set on the coin":a(u)?`leverage now ${Et(u)}${k?` on ${k}`:""}${u?"":" (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}${k?` on ${k}`:""} — no updateLeverage step`,f=(u,k)=>({...u[u.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,...d?{marginUsdc:d}:{},leverageStep:u[0].step==="leverage",current:k});if(!e.live){let u=null,k=null;if(i.lev!==null){let H=await re(e.address,e.actor,t);if("ok"in H&&H.ok===!0)u=H.address,k=await Ge(u,i.info.coin,n,t)}let m;try{m=l(k,null)}catch(H){return D(H,{network:n})}let I=`${i.cmdline}${n==="testnet"?" --testnet":""} --live --dir <your vault folder>`;return t.say([`DRY RUN — nothing signed, nothing sent · ${i.side} on ${n}`,` ${p}`,y(k,u),...m.flatMap((H,Y)=>Ye(Y+1,m.length,H)),`next ${I}`]),{data:{ok:!0,live:!1,posted:!1,network:n,...f(m,k),account:u,steps:m.map(Xe),next:I}}}let _=await t.unlock(e.dir??".");if("error"in _)return g("vault_unavailable",_.error,{network:n,next:"Name the folder that holds .one/wallet.json: --dir ~/.one/<you>"});let S=_.keys.find((u)=>u.chain==="evm");if(!S)return g("no_evm_key",`The vault at ${e.dir??"."} holds no EVM key.`,{network:n});let w=Qe(S),b=i.lev!==null?await Ge(w.address,i.info.coin,n,t):null,A;try{A=l(b,w.address)}catch(u){return D(u,{network:n,signer:w.address})}let x=await te(w.address,n,t);t.say([`LIVE · ${i.side} on ${n} · signer ${w.address} (the vault's EVM key)`,...ne("before",x),` ${p}`,y(b,w.address),...A.flatMap((u,k)=>Ye(k+1,A.length,u))]);let U={live:!0,network:n,signer:w.address,...f(A,b)};if(!e.yes){let u=A.length===2?"Sign both steps (leverage, then the order only if Hyperliquid accepts it)":"Sign this order";if(!await t.confirm(`${u} with ${w.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 v=[];for(let u of A){let k;try{({request:k}=await ke(u.built.action,u.built.opts,w,{expectDigest:u.dry.digest}))}catch(I){return D(I,{...U,posted:v.length>0,orderPosted:!1,steps:v})}r.onSign?.(u.step);let m=await Ae(k,n,{fetchImpl:t.fetchImpl});if(t.say([`exchange ${u.step}: ${JSON.stringify(m.ok?m.response:{error:m.error,detail:m.detail,response:m.response??null})}`]),v.push({...Xe(u),signature:k.signature,posted:!0,accepted:m.ok,exchange:m.ok?m.response:m.response??null}),!m.ok){let I=await te(w.address,n,t);if(t.say(ne("after ",I)),u.step==="leverage")return{data:{ok:!1,error:"leverage_refused",detail:m.detail,exchangeError:m.error,...U,posted:!0,orderPosted:!1,steps:v,balanceBefore:x,balanceAfter:I,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:m.error,detail:m.detail,...U,posted:!0,orderPosted:!0,steps:v,exchange:m.response??null,balanceBefore:x,balanceAfter:I}}}}let X=await te(w.address,n,t);t.say(ne("after ",X));let se=v[v.length-1];return{data:{ok:!0,...U,posted:!0,orderPosted:!0,steps:v,exchange:se.exchange,balanceBefore:x,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};