oneie 5.7.4 → 5.7.5

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.
@@ -0,0 +1,622 @@
1
+ /**
2
+ * `one swap` and `one hl` — swap any coin to any coin, or send it into Hyperliquid
3
+ * (text/swap-plan.md § CLI (A)).
4
+ *
5
+ * one swap 0.01 BTC hl dry price (default — R11)
6
+ * one swap 10 USDC@base to hl --live a real deposit address, checked with 1Click
7
+ * one swap status <depositAddress> where is it; --watch polls until it lands
8
+ * one swap assets every alias, chain, decimals and signer
9
+ * one hl balance [0x…] a Hyperliquid account: perps and spot, never summed
10
+ *
11
+ * THIS COMMAND NEVER SIGNS AND HOLDS NO KEY. The server only quotes and reads status. On
12
+ * --live, nothing printed as a send instruction comes from the ONE server unchecked: the CLI
13
+ * reads the quote back from 1Click DIRECTLY (a plain fetch to a fixed host) and runs the client
14
+ * check (R16) against its OWN values — asset ids from its own table, the amount from its own
15
+ * parseUnits, its own slippage — then builds the send line and the wallet URI itself from
16
+ * 1Click's record. A mismatch prints `quote_mismatch` and no send line.
17
+ *
18
+ * Everything goes over ask() — no new @oneie/sdk import (R2). Every exit closes with
19
+ * out(cmd, data): one JSON line under --json, an `error <name>` + the reason otherwise, exit 1
20
+ * on ok:false; `status --watch` exits 2 when it stops at its poll cap.
21
+ */
22
+ import { Command } from 'commander';
23
+ import { createInterface } from 'node:readline';
24
+ import { askPath } from './lib/api-path.js';
25
+ import { authHeaders, jsonMode, out, resolveBase, resolveKey } from './lib/client.js';
26
+ import { isAgentEnvironment } from './lib/agent-env.js';
27
+ import { mergeEnv } from './env.js';
28
+ import { HL_ADDRESS, assetLines, checkQuote, depositAddressFits, depositLink, formatUnits, hlLines, oneClickStatusUrl, pageOrigin, parseMine, parseSlippage, parseSwapWords, parseUnits, quoteLines, resolveAlias, rowById, sameAddress, sendUri, statusLines, stillSendable, storedRecord, swapLink, } from './lib/swap-core.js';
29
+ const DEFAULT_API = 'https://api.one.ie';
30
+ /** `--watch` polls every 5 s and stops after 360 polls (30 min) — then exits 2, still not final. */
31
+ export const WATCH_INTERVAL_MS = 5000;
32
+ export const WATCH_MAX_POLLS = 360;
33
+ const refusal = (error, next, extra = {}) => ({ data: { ok: false, error, network: 'mainnet', next, ...extra } });
34
+ export async function runSwap(args, deps) {
35
+ const w = parseSwapWords(args.words);
36
+ if (!w.ok)
37
+ return refusal(w.error, w.next);
38
+ const slip = parseSlippage(args.slippage);
39
+ if (!slip.ok)
40
+ return refusal('bad_slippage', '--slippage is whole basis points from 1 to 500 (100 = 1%).');
41
+ const exact = args.exactOut ? 'out' : 'in';
42
+ const live = args.live === true;
43
+ const mine = parseMine(args.mine);
44
+ // The CLI's own reading of the assets — the ids the client check holds 1Click to.
45
+ const lf = resolveAlias(w.from, 'from');
46
+ const lt = resolveAlias(w.to, 'to');
47
+ for (const [side, r] of [['from', lf], ['to', lt]]) {
48
+ if (r.ok)
49
+ continue;
50
+ if (r.error === 'ambiguous_asset')
51
+ return refusal('ambiguous_asset', `${side === 'from' ? w.from : w.to} is on several chains — name one: ${r.options.join(', ')}.`, { options: r.options });
52
+ if (r.error === 'not_a_destination')
53
+ return refusal('not_a_destination', `${r.asset.alias} cannot be received; pick another destination.`);
54
+ // unknown: a dry quote lets the server answer with its whole table; live never guesses.
55
+ if (live)
56
+ return refusal('unknown_asset', `${side === 'from' ? w.from : w.to} is not an alias this CLI knows, so it cannot check a live quote. Run: one swap assets`);
57
+ }
58
+ const from = lf.ok ? lf.asset : undefined;
59
+ const to = lt.ok ? lt.asset : undefined;
60
+ let amountBase = null;
61
+ if (from && to) {
62
+ const exactAsset = exact === 'out' ? to : from;
63
+ amountBase = parseUnits(w.amount, exactAsset.decimals);
64
+ if (amountBase === null || amountBase <= 0n)
65
+ return refusal('bad_amount', `amount is a decimal in ${exactAsset.alias} with at most ${exactAsset.decimals} decimals.`);
66
+ if (from.assetId === to.assetId)
67
+ return refusal('same_asset', 'from and to are the same asset.');
68
+ if (live && !from.origin)
69
+ return refusal('hyperliquid_origin_unsupported', 'Swapping out of Hyperliquid is a dry price only in v1 — there is no signer for Hyperliquid actions.');
70
+ }
71
+ // Off a TTY with no --mine a live send line can never be printed (see below), so refuse before
72
+ // the mint: a deposit address nobody can use spends one of the 30 live quotes an hour.
73
+ if (live && !mine.length && !deps.interactive) {
74
+ return refusal('mine_required', 'Off a terminal (agents, scripts, --json) a live quote needs --mine <your addresses>, comma-separated: the deposit must deliver and refund to them. Nothing was minted.');
75
+ }
76
+ const request = { from: w.from, to: w.to, amount: w.amount, dry: !live };
77
+ if (exact === 'out')
78
+ request['exact'] = 'out';
79
+ if (args.sendTo) {
80
+ request['recipient'] = args.sendTo;
81
+ request['toOther'] = true;
82
+ }
83
+ if (slip.bps !== undefined)
84
+ request['slippageBps'] = slip.bps;
85
+ // R19: name the addresses yourself. Where ONE cannot sign, the server will not pick one from a
86
+ // wallet row, so the matching --mine entry rides as recipient / refundTo — the person's assertion.
87
+ if (live && from && to && mine.length) {
88
+ const rec = args.sendTo ? [] : mineOn(mine, to.chain);
89
+ const ref = mineOn(mine, from.chain);
90
+ for (const [list, chain] of [[rec, to.chain], [ref, from.chain]]) {
91
+ if (list.length > 1)
92
+ return refusal('ambiguous_mine', `--mine has several ${chain} addresses (${list.join(', ')}); keep only the one to use. Nothing was minted.`, { options: list });
93
+ }
94
+ if (rec.length === 1)
95
+ request['recipient'] = rec[0];
96
+ if (ref.length === 1)
97
+ request['refundTo'] = ref[0];
98
+ }
99
+ const r = await deps.ask('swap:quote', request);
100
+ if (r['ok'] !== true) {
101
+ const named = r['error'] === 'recipient_must_be_named' ? to?.chain : r['error'] === 'refund_must_be_named' ? from?.chain : undefined;
102
+ if (named)
103
+ return { data: { network: 'mainnet', ...r, ok: false, next: `ONE cannot sign on ${named}, so name the address yourself: add your ${named} address (one whose key or 24 words you hold) to --mine.` } };
104
+ return { data: { network: 'mainnet', ...r, ok: false } };
105
+ }
106
+ // The server must have read the same assets the CLI did.
107
+ const sf = r['from']?.['assetId'];
108
+ const st = r['to']?.['assetId'];
109
+ if (from && sf !== from.assetId)
110
+ return refusal('quote_mismatch', `ONE priced a different origin (${String(sf)}) than ${from.alias}. Do not use this quote.`, { field: 'from' });
111
+ if (to && st !== to.assetId)
112
+ return refusal('quote_mismatch', `ONE priced a different destination (${String(st)}) than ${to.alias}. Do not use this quote.`, { field: 'to' });
113
+ const origin = pageOrigin(r['link']);
114
+ const fromAlias = from?.alias ?? w.from;
115
+ const toAlias = to?.alias ?? w.to;
116
+ const { send: _send, next: _next, link: _link, ...quote } = r;
117
+ if (!live) {
118
+ const link = swapLink(origin, { from: fromAlias, to: toAlias, amount: w.amount, exact });
119
+ const sendToEcho = args.sendTo ? { sendTo: args.sendTo } : {};
120
+ const data = {
121
+ ...quote,
122
+ ...sendToEcho,
123
+ link,
124
+ next: `A price only — nothing was minted. Open ${link} to send from your own browser wallet, or run again with --live for a deposit address.`,
125
+ };
126
+ deps.say([
127
+ ...quoteLines(data),
128
+ ...addressLines(quote, args.sendTo),
129
+ `${'link'.padEnd(10)}${link}`,
130
+ `${'next'.padEnd(10)}price only — add --live for a deposit address, or open the link to sign in your browser`,
131
+ ]);
132
+ if (deps.interactive && from && to && from.origin && (await deps.confirm('Get a deposit address (mainnet — real funds)? [y/N] '))) {
133
+ return runSwap({ ...args, live: true }, { ...deps, interactive: deps.interactive });
134
+ }
135
+ return { data };
136
+ }
137
+ // ── live: the client check (R16) before any send line exists ──
138
+ const fromRow = from;
139
+ const toRow = to;
140
+ const dep = r['depositAddress'];
141
+ if (!depositAddressFits(dep))
142
+ return refusal('quote_refused', 'ONE answered a live quote without a usable deposit address. Nothing to send.');
143
+ const recipient = args.sendTo ?? (typeof r['recipient'] === 'string' ? r['recipient'] : '');
144
+ const refundTo = typeof r['refundTo'] === 'string' ? r['refundTo'] : '';
145
+ const checkUrl = oneClickStatusUrl(dep);
146
+ const quotedLocal = deps.now();
147
+ const got = await deps.oneClick(checkUrl);
148
+ if (!got.ok) {
149
+ return refusal('oneclick_check_failed', `Could not read the quote back from 1Click (${got.error}), so nothing was verified — do NOT send. Retry: one swap status ${dep} --mine <your addresses>${exact === 'in' ? ` --amount ${w.amount}` : ''}`, { depositAddress: dep });
150
+ }
151
+ let maxAmountInBase;
152
+ if (exact === 'out') {
153
+ // No independent cap exists for exact-out: the cap is the input this quote showed you.
154
+ const cap = typeof r['amountIn'] === 'string' ? parseUnits(r['amountIn'], fromRow.decimals) : null;
155
+ if (cap === null)
156
+ return refusal('quote_mismatch', 'ONE showed no input amount for an exact-out quote. Do not send.', { field: 'amountIn' });
157
+ maxAmountInBase = cap.toString();
158
+ }
159
+ const check = checkQuote(got.body, {
160
+ depositAddress: dep,
161
+ recipient,
162
+ refundTo,
163
+ originAsset: fromRow.assetId,
164
+ destinationAsset: toRow.assetId,
165
+ exact,
166
+ amountBase: amountBase.toString(),
167
+ ...(maxAmountInBase ? { maxAmountInBase } : {}),
168
+ ...(slip.bps !== undefined ? { slippageBps: slip.bps } : {}),
169
+ });
170
+ if (!check.ok) {
171
+ return refusal('quote_mismatch', `1Click's own record does not match what you asked for (${check.field}). Do NOT send to ${dep}.`, { field: check.field, depositAddress: dep });
172
+ }
173
+ const rec = storedRecord(got.body);
174
+ if (mine.length) {
175
+ const inMine = (a) => mine.some((m) => sameAddress(m, a));
176
+ if (!args.sendTo && !inMine(rec.recipient))
177
+ return refusal('quote_mismatch', `1Click will deliver to ${rec.recipient}, which is not in --mine. Do NOT send.`, { field: 'recipient', depositAddress: dep });
178
+ if (!inMine(rec.refundTo))
179
+ return refusal('quote_mismatch', `1Click will refund to ${rec.refundTo}, which is not in --mine. Do NOT send.`, { field: 'refundTo', depositAddress: dep });
180
+ }
181
+ // Skew is applied only in the cautious direction (this clock BEHIND 1Click's). A clock ahead
182
+ // is never corrected, so an old quote replayed near its deadline cannot pass as fresh.
183
+ const rawSkew = rec.quotedAt && !Number.isNaN(Date.parse(rec.quotedAt)) ? quotedLocal.getTime() - Date.parse(rec.quotedAt) : 0;
184
+ const skew = Math.min(0, rawSkew);
185
+ if (!stillSendable(rec.refundAfter, deps.now(), skew)) {
186
+ return refusal('quote_expired', 'Too close to (or past) the refund deadline to send safely. Run the command again for a new quote.', { depositAddress: dep, refundAfter: rec.refundAfter });
187
+ }
188
+ // Without --mine and with nobody at a TTY to confirm, recipient and refundTo are only ONE's
189
+ // own claim, which 1Click's record merely echoes — that proves nothing (R16). So no send line:
190
+ // the status door shows it once the person names their addresses (R18).
191
+ if (!mine.length && !deps.interactive) {
192
+ return refusal('mine_required', `Checked with 1Click, but nobody confirmed the addresses are yours. Run: one swap status ${dep} --mine <your addresses>${exact === 'in' ? ` --amount ${w.amount}` : ''} (or add --mine to this command)`, {
193
+ depositAddress: dep, recipient: rec.recipient, refundTo: rec.refundTo, refundAfter: rec.refundAfter,
194
+ });
195
+ }
196
+ const sendBase = BigInt(rec.amountInBase ?? '0');
197
+ const amount = formatUnits(sendBase, fromRow.decimals);
198
+ const uri = sendUri(fromRow, dep, sendBase);
199
+ const link = depositLink(origin, dep);
200
+ // Every number shown beside a send line is 1Click's, read back and checked — not ONE's.
201
+ const checkedAmounts = {
202
+ amountIn: amount,
203
+ ...(rec.amountOutBase !== undefined ? { amountOut: formatUnits(BigInt(rec.amountOutBase), toRow.decimals) } : {}),
204
+ ...(rec.minAmountOutBase !== undefined ? { minAmountOut: formatUnits(BigInt(rec.minAmountOutBase), toRow.decimals) } : {}),
205
+ };
206
+ const sendLine = `Send exactly ${amount} ${fromRow.alias} on ${fromRow.chain} to ${dep} as a plain transfer before ${rec.refundAfter}`;
207
+ const data = {
208
+ ...quote,
209
+ ...checkedAmounts,
210
+ depositAddress: dep,
211
+ recipient: rec.recipient,
212
+ refundTo: rec.refundTo,
213
+ refundAfter: rec.refundAfter,
214
+ ...(rec.addressExpires ? { addressExpires: rec.addressExpires } : {}),
215
+ ...(args.sendTo ? { sendTo: args.sendTo } : {}),
216
+ verified: {
217
+ by: '1click',
218
+ url: checkUrl,
219
+ checked: 'depositAddress recipient refundTo originAsset destinationAsset depositType refundType recipientType slippageTolerance appFees depositMode memo swapType amount amountIn',
220
+ mine: mine.length > 0,
221
+ note: mine.length ? 'recipient and refundTo are in --mine' : 'recipient and refundTo were read back from 1Click — confirm both are yours',
222
+ },
223
+ send: {
224
+ how: fromRow.signer === 'browser' ? 'browser' : 'external',
225
+ to: dep,
226
+ amount,
227
+ amountBase: sendBase.toString(),
228
+ asset: fromRow.alias,
229
+ chain: fromRow.chain,
230
+ ...(uri ? { uri } : {}),
231
+ before: rec.refundAfter,
232
+ line: sendLine,
233
+ },
234
+ link,
235
+ status: `one swap status ${dep}`,
236
+ next: `${sendLine}, then run: one swap status ${dep} --watch`,
237
+ };
238
+ const lines = [
239
+ ...quoteLines(data),
240
+ `${'checked'.padEnd(10)}read back from 1Click directly — recipient, refund, assets, amount, slippage and fees match`,
241
+ `${'recipient'.padEnd(10)}${rec.recipient}${args.sendTo ? ' (someone else — you chose it)' : ''}`,
242
+ `${'refundTo'.padEnd(10)}${rec.refundTo}`,
243
+ ];
244
+ if (deps.interactive && !mine.length) {
245
+ deps.say(lines);
246
+ const yours = args.sendTo ? 'Is the refund address yours?' : 'Are the recipient and refund addresses both yours?';
247
+ if (!(await deps.confirm(`${yours} [y/N] `))) {
248
+ return refusal('not_confirmed', 'Nothing to send — the deposit address expires unused and no funds moved.', { depositAddress: dep });
249
+ }
250
+ lines.length = 0;
251
+ }
252
+ deps.say([
253
+ ...lines,
254
+ `${'send'.padEnd(10)}${sendLine}`,
255
+ `${''.padEnd(10)}No bridge. An exchange withdrawal that deducts its fee arrives short and is refunded minus the refund fee.`,
256
+ ...(uri ? [`${'uri'.padEnd(10)}${uri}`] : []),
257
+ `${'link'.padEnd(10)}${link}`,
258
+ `${'then'.padEnd(10)}one swap status ${dep} --watch`,
259
+ ]);
260
+ return { data };
261
+ }
262
+ const CHAIN_ADDRESS = {
263
+ ethereum: /^0x[0-9a-fA-F]{40}$/,
264
+ base: /^0x[0-9a-fA-F]{40}$/,
265
+ arbitrum: /^0x[0-9a-fA-F]{40}$/,
266
+ hyperliquid: /^0x[0-9a-fA-F]{40}$/,
267
+ sui: /^0x[0-9a-fA-F]{64}$/,
268
+ solana: /^[1-9A-HJ-NP-Za-km-z]{32,44}$/,
269
+ bitcoin: /^(bc1[02-9ac-hj-np-z]{11,71}|[13][1-9A-HJ-NP-Za-km-z]{25,34})$/,
270
+ };
271
+ /** The --mine entries shaped like an address on this chain (several = the person must pick). */
272
+ export function mineOn(mine, chain) {
273
+ return mine.filter((m) => CHAIN_ADDRESS[chain].test(m));
274
+ }
275
+ function addressLines(q, sendTo) {
276
+ const own = (q['ownership'] ?? {});
277
+ const lines = [];
278
+ if (typeof q['recipient'] === 'string')
279
+ lines.push(`${'recipient'.padEnd(10)}${q['recipient']} (${String(own['recipient'] ?? '?')}${sendTo ? ', someone else — you chose it' : ''})`);
280
+ if (typeof q['refundTo'] === 'string')
281
+ lines.push(`${'refundTo'.padEnd(10)}${q['refundTo']} (${String(own['refundTo'] ?? '?')})`);
282
+ return lines;
283
+ }
284
+ export async function runStatus(args, deps) {
285
+ const dep = args.depositAddress.trim();
286
+ if (!depositAddressFits(dep))
287
+ return refusal('bad_address', 'Pass the deposit address `one swap` printed.');
288
+ const mine = parseMine(args.mine);
289
+ const slip = parseSlippage(args.slippage);
290
+ if (!slip.ok)
291
+ return refusal('bad_slippage', '--slippage is whole basis points from 1 to 500 (100 = 1%).');
292
+ const max = args.maxPolls ?? WATCH_MAX_POLLS;
293
+ let polls = 0;
294
+ let last = {};
295
+ let lastStatus;
296
+ let sendSection;
297
+ for (;;) {
298
+ const r = await deps.ask('swap:get', { depositAddress: dep, ...(args.tx && polls === 0 ? { txHash: args.tx } : {}) });
299
+ polls++;
300
+ if (r['ok'] !== true)
301
+ return { data: { network: 'mainnet', ...r, ok: false } };
302
+ last = r;
303
+ if (polls === 1) {
304
+ sendSection = await sendSectionFor(dep, r, mine, deps, slip.bps, args.amount);
305
+ deps.say([...statusLines(r), ...sendSection['lines']]);
306
+ }
307
+ else if (r['status'] !== lastStatus) {
308
+ deps.say([`${'status'.padEnd(10)}${String(r['status'])}${r['explain'] ? ` — ${String(r['explain'])}` : ''}`]);
309
+ }
310
+ lastStatus = r['status'];
311
+ if (!args.watch || r['terminal'] === true)
312
+ break;
313
+ if (polls >= max) {
314
+ deps.say([`stopped watching after ${max} polls; still ${String(r['status'])}`]);
315
+ const { lines: _l, ...send } = sendSection ?? {};
316
+ return { data: { ...r, ...send, polls, stopped: true, next: `Still ${String(r['status'])}. Run again: one swap status ${dep} --watch` }, exitCode: 2 };
317
+ }
318
+ await deps.sleep(WATCH_INTERVAL_MS);
319
+ }
320
+ if (args.watch && polls > 1)
321
+ deps.say(statusLines(last).slice(1));
322
+ const { lines: _l, ...send } = sendSection ?? {};
323
+ return { data: { ...last, ...send, ...(args.watch ? { polls } : {}) } };
324
+ }
325
+ /**
326
+ * R18 + R16: a send instruction only when 1Click's OWN record delivers to and refunds to addresses
327
+ * the person named as theirs (--mine), the refund deadline has not passed, AND the record passes
328
+ * the same client check the live path runs: both assets from this CLI's table, a plain EXACT_INPUT
329
+ * deposit (ORIGIN_CHAIN / DESTINATION_CHAIN types, SIMPLE, no memo), the slippage you asked for
330
+ * and no fee row past the pinned caps, AND the amount you name (--amount) — otherwise the record
331
+ * would only be checked against itself. A deposit address is public, so a crafted quote naming your
332
+ * own addresses and an amount you never chose must never print as your swap.
333
+ */
334
+ async function sendSectionFor(dep, r, mine, deps, slippageBps, asked) {
335
+ if (r['status'] !== 'PENDING_DEPOSIT')
336
+ return { sendable: false, lines: [] };
337
+ const got = await deps.oneClick(oneClickStatusUrl(dep));
338
+ if (!got.ok)
339
+ return { sendable: false, sendReason: 'oneclick_check_failed', lines: [`${'send'.padEnd(10)}hidden — could not read 1Click's own record (${got.error}); do not send`] };
340
+ const rec = storedRecord(got.body);
341
+ const where = `delivers to ${rec.recipient ?? '?'}, refunds to ${rec.refundTo ?? '?'}`;
342
+ if (!mine.length) {
343
+ return { sendable: false, sendReason: 'mine_not_given', lines: [`${'send'.padEnd(10)}hidden — ${where}. Pass --mine <your addresses> to see the send instruction`] };
344
+ }
345
+ const recipient = mine.find((m) => sameAddress(m, rec.recipient));
346
+ const refundTo = mine.find((m) => sameAddress(m, rec.refundTo));
347
+ if (!recipient || !refundTo)
348
+ return { sendable: false, sendReason: 'not_yours', lines: [`${'send'.padEnd(10)}not your swap — ${where}`] };
349
+ if (!stillSendable(rec.refundAfter, deps.now())) {
350
+ return { sendable: false, sendReason: 'expired', lines: [`${'send'.padEnd(10)}too late — refunds begin ${rec.refundAfter}; get a new quote`] };
351
+ }
352
+ const row = rowById(rec.originAsset);
353
+ const toRow = rowById(rec.destinationAsset);
354
+ if (!row || !toRow || rec.amountInBase === undefined) {
355
+ return { sendable: false, sendReason: 'unknown_asset', lines: [`${'send'.padEnd(10)}hidden — the origin or destination asset is not in this CLI's table`] };
356
+ }
357
+ if (rec.swapType === 'EXACT_OUTPUT') {
358
+ // No independent input cap exists here: the only cap would be the record's own amountIn.
359
+ return { sendable: false, sendReason: 'exact_out_unverifiable', lines: [`${'send'.padEnd(10)}hidden — an exact-out record has no input cap this CLI can check; get a new quote with --live`] };
360
+ }
361
+ if (asked === undefined || !asked.trim()) {
362
+ return { sendable: false, sendReason: 'amount_not_given', lines: [`${'send'.padEnd(10)}hidden — pass --amount <what you asked to swap, in ${row.alias}> so the record is checked against your number, not its own`] };
363
+ }
364
+ const askedBase = parseUnits(asked.trim(), row.decimals);
365
+ if (askedBase === null || askedBase <= 0n) {
366
+ return { sendable: false, sendReason: 'bad_amount', lines: [`${'send'.padEnd(10)}hidden — --amount is a decimal in ${row.alias} with at most ${row.decimals} decimals`] };
367
+ }
368
+ if (rec.amountBase !== askedBase.toString()) {
369
+ return { sendable: false, sendReason: 'amount_mismatch', field: 'amount', lines: [`${'send'.padEnd(10)}hidden — 1Click's record is not for ${asked.trim()} ${row.alias}; do NOT send to ${dep}`] };
370
+ }
371
+ const check = checkQuote(got.body, {
372
+ depositAddress: dep,
373
+ recipient,
374
+ refundTo,
375
+ originAsset: row.assetId,
376
+ destinationAsset: toRow.assetId,
377
+ exact: 'in',
378
+ amountBase: askedBase.toString(),
379
+ ...(slippageBps !== undefined ? { slippageBps } : {}),
380
+ });
381
+ if (!check.ok) {
382
+ return { sendable: false, sendReason: 'quote_mismatch', field: check.field, lines: [`${'send'.padEnd(10)}hidden — 1Click's record is not a plain swap you asked for (${check.field}); do NOT send to ${dep}`] };
383
+ }
384
+ const base = BigInt(rec.amountInBase);
385
+ const amount = formatUnits(base, row.decimals);
386
+ const uri = sendUri(row, dep, base);
387
+ const line = `Send exactly ${amount} ${row.alias} on ${row.chain} to ${dep} as a plain transfer before ${rec.refundAfter}`;
388
+ return {
389
+ sendable: true,
390
+ send: { to: dep, amount, amountBase: base.toString(), asset: row.alias, chain: row.chain, ...(uri ? { uri } : {}), before: rec.refundAfter, line },
391
+ ...(rec.amountOutBase !== undefined ? { amountOutChecked: formatUnits(BigInt(rec.amountOutBase), toRow.decimals) } : {}),
392
+ ...(rec.minAmountOutBase !== undefined ? { minAmountOutChecked: formatUnits(BigInt(rec.minAmountOutBase), toRow.decimals) } : {}),
393
+ lines: [
394
+ `${'checked'.padEnd(10)}read back from 1Click directly — recipient, refund, assets, amount, slippage and fees match`,
395
+ ...(rec.minAmountOutBase !== undefined ? [`${'minOut'.padEnd(10)}${formatUnits(BigInt(rec.minAmountOutBase), toRow.decimals)} ${toRow.alias} (1Click's record)`] : []),
396
+ `${'send'.padEnd(10)}${line}`,
397
+ ...(uri ? [`${'uri'.padEnd(10)}${uri}`] : []),
398
+ ],
399
+ };
400
+ }
401
+ // ─── one swap assets ──────────────────────────────────────────────────────────
402
+ /** The server's whole table, read from an `unknown_asset` refusal (R2 — no assets receiver). */
403
+ export async function runAssets(deps) {
404
+ // Keyless on purpose: an attested caller's refusal warns swap:quote, and listing the table is not a failed swap.
405
+ const r = await deps.ask('swap:quote', { from: '?', to: 'hl', amount: '1' }, { anonymous: true });
406
+ const assets = Array.isArray(r['assets']) ? r['assets'] : null;
407
+ if (!assets)
408
+ return { data: { network: 'mainnet', ...r, ok: false, error: typeof r['error'] === 'string' && r['error'] !== 'unknown_asset' ? r['error'] : 'no_table' } };
409
+ deps.say([...assetLines(assets), `${assets.length} assets (the whole table, never paged) · signer: browser = ONE's browser wallet signs · external = any wallet + QR · none = price only`]);
410
+ return { data: { ok: true, network: 'mainnet', count: assets.length, assets } };
411
+ }
412
+ export async function runHlBalance(args, deps) {
413
+ let addr = args.address?.trim();
414
+ if (addr && !HL_ADDRESS.test(addr))
415
+ return refusal('bad_address', 'A Hyperliquid account is a 0x address of 40 hex characters.');
416
+ if (!addr) {
417
+ const w = await deps.ask('wallet:get', {});
418
+ if (typeof w['error'] === 'string' || w['ok'] === false)
419
+ return { data: { network: 'mainnet', ...w, ok: false, error: w['error'] ?? 'wallet_read_failed', next: 'Pass an address: one hl balance 0x…' } };
420
+ const rows = Array.isArray(w['addresses']) ? w['addresses'] : [];
421
+ const evm = rows.filter((x) => x.chain === 'evm' && typeof x.address === 'string' && HL_ADDRESS.test(x.address) && (!args.actor || x.actor === args.actor));
422
+ const distinct = [...new Map(evm.map((x) => [x.address.toLowerCase(), x])).values()];
423
+ if (distinct.length === 0)
424
+ return refusal('no_evm_address', 'Your workspace has no EVM address registered. Pass one: one hl balance 0x…');
425
+ if (distinct.length > 1) {
426
+ const options = distinct.map((x) => `${x.actor ?? '?'} ${x.address}`);
427
+ return refusal('ambiguous_address', `Several EVM addresses — pass one, or --actor <id>: ${options.join(' · ')}`, { options });
428
+ }
429
+ addr = distinct[0].address;
430
+ }
431
+ const r = await deps.ask('swap:get', { hyperliquid: addr, ...(args.testnet ? { net: 'testnet' } : {}) });
432
+ if (r['ok'] !== true)
433
+ return { data: { network: args.testnet ? 'testnet' : 'mainnet', ...r, ok: false } };
434
+ const h = (r['hyperliquid'] ?? null);
435
+ if (!h)
436
+ return refusal('hyperliquid_unavailable', 'Hyperliquid did not answer; try again.');
437
+ deps.say(hlLines(h));
438
+ return { data: { ...r, network: String(h['network'] ?? (args.testnet ? 'testnet' : 'mainnet')) } };
439
+ }
440
+ // ─── wiring ───────────────────────────────────────────────────────────────────
441
+ async function askOnce(base, key, receiver, data) {
442
+ let res;
443
+ try {
444
+ res = await fetch(askPath(base, receiver), {
445
+ method: 'POST',
446
+ headers: authHeaders(key ? { key } : {}),
447
+ body: JSON.stringify({ data }),
448
+ });
449
+ }
450
+ catch {
451
+ return { ok: false, error: 'api_unreachable', network: 'mainnet', next: `Could not reach ${base}; check --api.` };
452
+ }
453
+ const text = await res.text();
454
+ let body;
455
+ try {
456
+ body = text ? JSON.parse(text) : undefined;
457
+ }
458
+ catch {
459
+ body = undefined;
460
+ }
461
+ if (!res.ok && !body)
462
+ return { ok: false, error: `http_${res.status}`, detail: text.slice(0, 300) };
463
+ const env = body ?? {};
464
+ if (env['outcome'] !== undefined && env['outcome'] !== 'result') {
465
+ const inner = (env['result'] ?? {});
466
+ const dissolved = env['outcome'] === 'dissolved' ? { next: `${base} did not route ${receiver} — that server may not have it deployed yet; try --api https://one.ie or a dev server` } : {};
467
+ return { ...dissolved, ...inner, ok: false, error: inner['error'] ?? env['error'] ?? `${receiver}_${String(env['outcome'])}` };
468
+ }
469
+ const result = (env['result'] ?? env);
470
+ if (!res.ok)
471
+ return { ok: false, error: `http_${res.status}`, ...result };
472
+ return result;
473
+ }
474
+ async function oneClickFetch(url) {
475
+ const ac = new AbortController();
476
+ const t = setTimeout(() => ac.abort(), 8000);
477
+ try {
478
+ const res = await fetch(url, { headers: { accept: 'application/json' }, signal: ac.signal });
479
+ if (res.status === 404)
480
+ return { ok: false, error: 'address_unknown', status: 404 };
481
+ if (!res.ok)
482
+ return { ok: false, error: 'oneclick_unavailable', status: res.status };
483
+ return { ok: true, body: await res.json() };
484
+ }
485
+ catch (e) {
486
+ return { ok: false, error: e.name === 'AbortError' ? 'oneclick_timeout' : 'oneclick_unavailable' };
487
+ }
488
+ finally {
489
+ clearTimeout(t);
490
+ }
491
+ }
492
+ function ttyConfirm(question) {
493
+ return new Promise((resolve) => {
494
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
495
+ rl.question(question, (a) => { rl.close(); resolve(/^y(es)?$/i.test(a.trim())); });
496
+ });
497
+ }
498
+ function liveDeps(cmd, opts) {
499
+ const base = resolveBase({ api: opts.api }, DEFAULT_API);
500
+ // Same order as wallet.ts resolveAuth: --key > a folder's .env/.env.local (what `one init
501
+ // --write-env` writes) > the canonical ladder. Without it a live quote went out anonymous.
502
+ const env = mergeEnv(process.cwd());
503
+ const key = opts.key ?? env.ONEIE_API_KEY ?? env.ONE_API_KEY ?? (resolveKey() || undefined);
504
+ const json = jsonMode(cmd);
505
+ return {
506
+ ask: (receiver, data, o) => askOnce(base, o?.anonymous ? undefined : key, receiver, data),
507
+ oneClick: oneClickFetch,
508
+ now: () => new Date(),
509
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
510
+ interactive: !json && !!process.stdin.isTTY && !!process.stdout.isTTY && !isAgentEnvironment(),
511
+ confirm: ttyConfirm,
512
+ say: (lines) => { if (!json)
513
+ for (const l of lines)
514
+ process.stdout.write(l + '\n'); },
515
+ };
516
+ }
517
+ /** Close the loop: out() for --json and the error head, the reason lines on stderr, the exit code last. */
518
+ export function emit(cmd, res) {
519
+ const d = res.data;
520
+ out(cmd, d);
521
+ if (!jsonMode(cmd) && d['ok'] === false) {
522
+ for (const k of ['field', 'detail', 'minimum'])
523
+ if (d[k] !== undefined)
524
+ process.stderr.write(`${k.padEnd(7)}${String(d[k])}\n`);
525
+ if (Array.isArray(d['options']))
526
+ process.stderr.write(`options ${d['options'].join(', ')}\n`);
527
+ if (typeof d['next'] === 'string')
528
+ process.stderr.write(`next ${d['next']}\n`);
529
+ }
530
+ if (res.exitCode !== undefined)
531
+ process.exitCode = res.exitCode;
532
+ }
533
+ /** Human mode already printed its lines through say(); out() would add a k=v dump. */
534
+ function close(cmd, res) {
535
+ if (jsonMode(cmd) || res.data['ok'] === false)
536
+ emit(cmd, res);
537
+ else if (res.exitCode !== undefined)
538
+ process.exitCode = res.exitCode;
539
+ }
540
+ /**
541
+ * `swap status X --mine … --api …`: the parent `swap` defines the same option names, so commander
542
+ * hands them to the parent and the subcommand sees only its defaults (status then read api.one.ie
543
+ * with no --mine). Take every option the person actually typed (source 'cli'), wherever it landed.
544
+ */
545
+ function typedOpts(sub) {
546
+ const out = { ...sub.opts() };
547
+ const parent = sub.parent;
548
+ if (parent) {
549
+ for (const [k, v] of Object.entries(parent.opts())) {
550
+ if (parent.getOptionValueSource(k) === 'cli' && sub.getOptionValueSource(k) !== 'cli')
551
+ out[k] = v;
552
+ }
553
+ }
554
+ return out;
555
+ }
556
+ export function swapCmd(deps) {
557
+ const make = deps ?? liveDeps;
558
+ const cmd = new Command('swap')
559
+ .description('Swap any coin to any coin, or into Hyperliquid — dry price by default, --live for a deposit address your OWN wallet sends to. Never signs; ONE never holds funds. Quotes are mainnet (1Click has no testnet)')
560
+ .argument('[words...]', 'amount, from and to, in any order — the amount is the plain decimal: `0.01 BTC hl`, `10 USDC@base to hl`, `SUI ETH 25`')
561
+ .option('--live', 'Mint a real deposit address (mainnet, real funds), read it back from 1Click and check it before printing the send line')
562
+ .option('--send-to <addr>', 'Deliver to someone else\'s address on purpose (sets recipient + toOther, echoed back). The refund is always yours')
563
+ .option('--exact-out', 'The amount is what you RECEIVE (in the to asset); slippage applies to the input')
564
+ .option('--slippage <bps>', 'Max slippage in basis points, 1–500 (default 100 = 1%)')
565
+ .option('--mine <addrs>', 'Your own addresses, comma-separated — a live quote must deliver and refund to them or no send line is printed')
566
+ .option('--api <url>', 'API base URL', DEFAULT_API)
567
+ .option('--key <key>', 'API key (a live quote needs one; dry works without)')
568
+ .addHelpText('after', [
569
+ '',
570
+ 'Examples:',
571
+ ' one swap 0.01 BTC hl price BTC into your Hyperliquid perps balance',
572
+ ' one swap 10 USDC@base to hl --live deposit address, checked with 1Click',
573
+ ' one swap 25 SUI ETH SUI to ETH on ethereum',
574
+ ' one swap status <depositAddress> --watch',
575
+ ' one swap assets every alias and who can sign it',
576
+ ' one hl balance 0x… Hyperliquid perps + spot',
577
+ ].join('\n'))
578
+ .action(async (words, opts) => {
579
+ if (!words.length) {
580
+ cmd.help();
581
+ return;
582
+ }
583
+ close(cmd, await runSwap({ words, live: opts.live, sendTo: opts.sendTo, exactOut: opts.exactOut, slippage: opts.slippage, mine: opts.mine }, make(cmd, opts)));
584
+ });
585
+ cmd.command('status <depositAddress>')
586
+ .description('Track a swap by its deposit address until it lands or refunds (swap:get). A send line shows only when 1Click\'s own record is yours (--mine) and before the deadline')
587
+ .option('--tx <hash>', 'Your deposit tx hash — forwarded to 1Click to speed matching (not a verification)')
588
+ .option('--watch', `Poll every ${WATCH_INTERVAL_MS / 1000} s until final; stops after ${WATCH_MAX_POLLS} polls with exit 2`)
589
+ .option('--mine <addrs>', 'Your own addresses, comma-separated — needed to show the send instruction')
590
+ .option('--slippage <bps>', 'The slippage you minted with, if not the default 100 — the record must match it')
591
+ .option('--amount <n>', 'The amount you asked to swap, in the from asset — needed with --mine to show the send instruction')
592
+ .option('--api <url>', 'API base URL', DEFAULT_API)
593
+ .option('--key <key>', 'API key (optional)')
594
+ .action(async function (depositAddress) {
595
+ const opts = typedOpts(this);
596
+ close(this, await runStatus({ depositAddress, tx: opts.tx, watch: opts.watch, mine: opts.mine, slippage: opts.slippage, amount: opts.amount }, make(this, opts)));
597
+ });
598
+ cmd.command('assets')
599
+ .description('Every alias swap knows — chain, decimals, and who can sign a deposit (browser · external · none)')
600
+ .option('--api <url>', 'API base URL', DEFAULT_API)
601
+ .option('--key <key>', 'API key (optional)')
602
+ .action(async function () {
603
+ close(this, await runAssets(make(this, typedOpts(this))));
604
+ });
605
+ return cmd;
606
+ }
607
+ export function hlCmd(deps) {
608
+ const make = deps ?? liveDeps;
609
+ const cmd = new Command('hl')
610
+ .alias('hyperliquid')
611
+ .description('Hyperliquid — read an account (send into it with: one swap <amount> <from> hl)');
612
+ cmd.command('balance [address]')
613
+ .description('Perps and spot balances of a Hyperliquid account, never summed. No address = your workspace\'s EVM address (wallet:get)')
614
+ .option('--testnet', 'Read api.hyperliquid-testnet.xyz instead of mainnet')
615
+ .option('--actor <id>', 'Pick this actor\'s EVM address when the workspace has several')
616
+ .option('--api <url>', 'API base URL', DEFAULT_API)
617
+ .option('--key <key>', 'API key (needed only without an address)')
618
+ .action(async function (address, opts) {
619
+ close(this, await runHlBalance({ address, testnet: opts.testnet, actor: opts.actor }, make(this, opts)));
620
+ });
621
+ return cmd;
622
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oneie",
3
- "version": "5.7.4",
3
+ "version": "5.7.5",
4
4
  "description": "ONE agent CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "commander": "^12.0.0",
23
- "@oneie/sdk": "^0.17.5"
23
+ "@oneie/sdk": "^0.17.6"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@oneie/evals": "^0.2.0",