oneie 5.7.3 → 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,405 @@
1
+ /**
2
+ * swap-core — the pure half of `one swap` (text/swap-plan.md § CLI).
3
+ *
4
+ * The CLI cannot import one.ie/web code and must not import a new @oneie/sdk export
5
+ * (R2: packages/cli/node_modules resolves another tree's SDK, so a new subpath would pass
6
+ * hollow). So the four things the client check needs are ported here, verbatim in behaviour,
7
+ * and tests/swap-parity.test.ts runs them against the web originals so the copy cannot drift:
8
+ *
9
+ * SWAP_TABLE + resolveAlias ← one.ie/web/src/lib/swap/assets.ts (SWAP_ASSETS, resolveAsset)
10
+ * parseUnits + formatUnits ← one.ie/web/src/lib/units.ts
11
+ * checkQuote ← one.ie/web/src/lib/swap/core.ts (R16, incl. 3fef1b14c fields)
12
+ * sendUri ← one.ie/web/src/lib/swap/core.ts
13
+ *
14
+ * Nothing here touches the network, and nothing here ever signs. No Number cast touches an amount.
15
+ */
16
+ export const HL_USDC_ASSET_ID = '1cs_v1:hypercore:hip1:0x6d1e7cde53ba9467b783cb7c530ce054';
17
+ /** Copied from one.ie/web/src/lib/swap/assets.ts — tests/swap-parity.test.ts pins it row by row. */
18
+ export const SWAP_TABLE = [
19
+ { alias: 'BTC', chain: 'bitcoin', symbol: 'BTC', assetId: 'nep141:btc.omft.near', decimals: 8, contract: null, signer: 'external', origin: true, destination: true },
20
+ { alias: 'ETH@ethereum', chain: 'ethereum', symbol: 'ETH', assetId: 'nep141:eth.omft.near', decimals: 18, contract: null, signer: 'browser', origin: true, destination: true },
21
+ { alias: 'ETH@base', chain: 'base', symbol: 'ETH', assetId: 'nep141:base.omft.near', decimals: 18, contract: null, signer: 'browser', origin: true, destination: true },
22
+ { alias: 'ETH@arbitrum', chain: 'arbitrum', symbol: 'ETH', assetId: 'nep141:arb.omft.near', decimals: 18, contract: null, signer: 'external', origin: true, destination: true },
23
+ { alias: 'USDC@ethereum', chain: 'ethereum', symbol: 'USDC', assetId: 'nep141:eth-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.omft.near', decimals: 6, contract: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', signer: 'browser', origin: true, destination: true },
24
+ { alias: 'USDC@base', chain: 'base', symbol: 'USDC', assetId: 'nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near', decimals: 6, contract: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', signer: 'browser', origin: true, destination: true },
25
+ { alias: 'USDC@arbitrum', chain: 'arbitrum', symbol: 'USDC', assetId: 'nep141:arb-0xaf88d065e77c8cc2239327c5edb3a432268e5831.omft.near', decimals: 6, contract: '0xaf88d065e77c8cc2239327c5edb3a432268e5831', signer: 'external', origin: true, destination: true },
26
+ { alias: 'USDT@ethereum', chain: 'ethereum', symbol: 'USDT', assetId: 'nep141:eth-0xdac17f958d2ee523a2206206994597c13d831ec7.omft.near', decimals: 6, contract: '0xdac17f958d2ee523a2206206994597c13d831ec7', signer: 'external', origin: true, destination: true },
27
+ { alias: 'USDT0@arbitrum', chain: 'arbitrum', symbol: 'USDT0', assetId: 'nep141:arb-0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9.omft.near', decimals: 6, contract: '0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9', signer: 'external', origin: true, destination: true },
28
+ { alias: 'SOL', chain: 'solana', symbol: 'SOL', assetId: 'nep141:sol.omft.near', decimals: 9, contract: null, signer: 'external', origin: true, destination: true },
29
+ { alias: 'USDC@solana', chain: 'solana', symbol: 'USDC', assetId: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near', decimals: 6, contract: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', signer: 'external', origin: true, destination: true },
30
+ { alias: 'SUI', chain: 'sui', symbol: 'SUI', assetId: 'nep141:sui.omft.near', decimals: 9, contract: null, signer: 'browser', origin: true, destination: true },
31
+ { alias: 'USDC@sui', chain: 'sui', symbol: 'USDC', assetId: 'nep141:sui-c1b81ecaf27933252d31a963bc5e9458f13c18ce.omft.near', decimals: 6, contract: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC', signer: 'browser', origin: true, destination: true },
32
+ { alias: 'USDC@hyperliquid', chain: 'hyperliquid', symbol: 'USDC', assetId: HL_USDC_ASSET_ID, decimals: 8, contract: '0x6d1e7cde53ba9467b783cb7c530ce054', signer: 'none', origin: false, destination: true },
33
+ ];
34
+ const CHAIN_SYNONYMS = {
35
+ ethereum: 'ethereum', eth: 'ethereum', 'ethereum-mainnet': 'ethereum',
36
+ base: 'base',
37
+ arbitrum: 'arbitrum', arb: 'arbitrum',
38
+ solana: 'solana', sol: 'solana',
39
+ sui: 'sui',
40
+ bitcoin: 'bitcoin', btc: 'bitcoin',
41
+ hyperliquid: 'hyperliquid', hl: 'hyperliquid', hypercore: 'hyperliquid',
42
+ };
43
+ const DEST_DEFAULT = { ETH: 'ETH@ethereum', USDC: 'USDC@base', USDT: 'USDT@ethereum' };
44
+ const byAlias = new Map(SWAP_TABLE.map((a) => [a.alias.toLowerCase(), a]));
45
+ /** Same rules as the web resolveAsset — a parity test compares every alias both ways. */
46
+ export function resolveAlias(input, side) {
47
+ const raw = typeof input === 'string' ? input.trim() : '';
48
+ if (!raw)
49
+ return { ok: false, error: 'unknown_asset' };
50
+ const lower = raw.toLowerCase();
51
+ let asset;
52
+ if (lower === 'hl' || lower === 'hyperliquid' || lower === 'hypercore') {
53
+ asset = byAlias.get('usdc@hyperliquid');
54
+ }
55
+ else if (lower.includes('@')) {
56
+ const [sym, ch] = lower.split('@', 2);
57
+ const chain = CHAIN_SYNONYMS[ch];
58
+ if (!chain)
59
+ return { ok: false, error: 'unknown_asset' };
60
+ asset = SWAP_TABLE.find((a) => a.symbol.toLowerCase() === sym && a.chain === chain);
61
+ }
62
+ else {
63
+ const rows = SWAP_TABLE.filter((a) => a.symbol.toLowerCase() === lower);
64
+ if (rows.length === 1)
65
+ asset = rows[0];
66
+ else if (rows.length > 1) {
67
+ if (side === 'to')
68
+ asset = byAlias.get((DEST_DEFAULT[raw.toUpperCase()] ?? '').toLowerCase());
69
+ if (!asset)
70
+ return { ok: false, error: 'ambiguous_asset', options: rows.map((r) => r.alias) };
71
+ }
72
+ }
73
+ if (!asset)
74
+ return { ok: false, error: 'unknown_asset' };
75
+ if (side === 'to' && !asset.destination)
76
+ return { ok: false, error: 'not_a_destination', asset };
77
+ return { ok: true, asset };
78
+ }
79
+ export function rowById(assetId) {
80
+ return SWAP_TABLE.find((a) => a.assetId === assetId);
81
+ }
82
+ // ─── units (verbatim from one.ie/web/src/lib/units.ts) ─────────────────────────
83
+ export function parseUnits(input, decimals) {
84
+ const s = input.trim();
85
+ if (s !== input || !/^(\d+\.?\d*|\.\d+)$/.test(s))
86
+ return null;
87
+ const [whole, frac = ''] = s.split('.');
88
+ if (frac.length > decimals)
89
+ return null;
90
+ return BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt((frac + '0'.repeat(decimals)).slice(0, decimals) || '0');
91
+ }
92
+ export function formatUnits(value, decimals) {
93
+ const neg = value < 0n;
94
+ const v = neg ? -value : value;
95
+ const base = 10n ** BigInt(decimals);
96
+ const whole = v / base;
97
+ const frac = (v % base).toString().padStart(decimals, '0').replace(/0+$/, '');
98
+ return `${neg ? '-' : ''}${whole}${frac ? `.${frac}` : ''}`;
99
+ }
100
+ // ─── grammar ──────────────────────────────────────────────────────────────────
101
+ /** The one rule (plan § CLI): the amount is the token that looks like a plain decimal. */
102
+ export const AMOUNT_TOKEN = /^\d+(\.\d+)?$/;
103
+ const USAGE = 'one swap <amount> <from> [to] <to> — e.g. one swap 0.01 BTC hl · one swap 10 USDC@base to hl';
104
+ /**
105
+ * `one swap 0.01 BTC hl` = `one swap 0.01 BTC to hl` = `one swap BTC hl 0.01`.
106
+ * Exactly one plain-decimal amount (nonzero), a literal `to` dropped, two asset words left
107
+ * in order (from, to). `1e3`, `0x10`, `-1`, `.5` and `0` are refused here, before any call.
108
+ */
109
+ export function parseSwapWords(words) {
110
+ const kept = words.filter((w) => w.toLowerCase() !== 'to');
111
+ const amounts = kept.filter((w) => AMOUNT_TOKEN.test(w));
112
+ const rest = kept.filter((w) => !AMOUNT_TOKEN.test(w));
113
+ if (amounts.length === 0) {
114
+ return { ok: false, error: 'bad_amount', next: `No amount found — write it as a plain decimal like 10 or 0.01 (never 1e3, -1 or .5). ${USAGE}` };
115
+ }
116
+ if (amounts.length > 1)
117
+ return { ok: false, error: 'usage', next: `Two amounts given (${amounts.join(', ')}); give one. ${USAGE}` };
118
+ const amount = amounts[0];
119
+ if (!/[1-9]/.test(amount))
120
+ return { ok: false, error: 'bad_amount', next: 'The amount must be more than zero.' };
121
+ if (rest.length !== 2)
122
+ return { ok: false, error: 'usage', next: `Name exactly two assets, what you pay and what you get. ${USAGE}` };
123
+ return { ok: true, amount, from: rest[0], to: rest[1] };
124
+ }
125
+ /** --slippage <bps>: an integer 1..500, read by regex and parseInt, never a Number cast. */
126
+ export function parseSlippage(s) {
127
+ if (s === undefined)
128
+ return { ok: true };
129
+ if (!/^\d{1,3}$/.test(s))
130
+ return { ok: false };
131
+ const bps = Number.parseInt(s, 10);
132
+ return bps >= 1 && bps <= 500 ? { ok: true, bps } : { ok: false };
133
+ }
134
+ /** --mine a,b,c → the caller's own addresses, as typed. */
135
+ export function parseMine(s) {
136
+ if (!s)
137
+ return [];
138
+ return s.split(/[\s,]+/).map((x) => x.trim()).filter(Boolean);
139
+ }
140
+ // ─── the client check (R16) — verbatim from one.ie/web/src/lib/swap/core.ts ────
141
+ export const ONECLICK = 'https://1click.chaindefuser.com';
142
+ export const ONECLICK_PROTOCOL_RECIPIENT = '5880ad2b362620fadf759cbceb1cd5737ce8c6ed7fb8e9942881e6731f9247dd';
143
+ export const DEFAULT_SLIPPAGE_BPS = 100;
144
+ /** ONE's app fee, pinned in client code (null = none, so any non-1Click fee row fails). Same as core.ts. */
145
+ export const ONE_APP_FEE = null;
146
+ /** Cap on summed 1Click protocol rows — measured 0/1/20 bps over 74 keyless routes (max 20), 25 = the documented no-key 0.25%. Same as core.ts. */
147
+ export const PROTOCOL_FEE_CAP_BPS = 25;
148
+ /** 1Click's own status URL for a deposit address — a fixed host, the address in URLSearchParams. */
149
+ export function oneClickStatusUrl(depositAddress) {
150
+ return `${ONECLICK}/v0/status?${new URLSearchParams({ depositAddress }).toString()}`;
151
+ }
152
+ const DEPOSIT_RE = /^[A-Za-z0-9:._-]{20,128}$/;
153
+ export function depositAddressFits(addr) {
154
+ return typeof addr === 'string' && DEPOSIT_RE.test(addr);
155
+ }
156
+ export const HL_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
157
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
158
+ function bigOf(s) {
159
+ if (typeof s === 'number' && Number.isInteger(s) && s >= 0)
160
+ return BigInt(s);
161
+ if (typeof s !== 'string' || !/^\d+$/.test(s))
162
+ return null;
163
+ return BigInt(s);
164
+ }
165
+ export function sameAddress(a, b) {
166
+ if (typeof a !== 'string' || typeof b !== 'string' || !a || !b)
167
+ return false;
168
+ if (a.startsWith('0x') && b.startsWith('0x'))
169
+ return a.toLowerCase() === b.toLowerCase();
170
+ return a === b;
171
+ }
172
+ export function checkQuote(stored, mine) {
173
+ const fail = (field) => ({ ok: false, error: 'quote_mismatch', field });
174
+ if (!isObj(stored))
175
+ return fail('stored');
176
+ const qr = isObj(stored['quoteResponse']) ? stored['quoteResponse'] : stored;
177
+ const req = isObj(qr['quoteRequest']) ? qr['quoteRequest'] : null;
178
+ const q = isObj(qr['quote']) ? qr['quote'] : null;
179
+ if (!req || !q)
180
+ return fail('stored');
181
+ if (!sameAddress(q['depositAddress'], mine.depositAddress))
182
+ return fail('depositAddress');
183
+ if (!sameAddress(req['recipient'], mine.recipient))
184
+ return fail('recipient');
185
+ if (!sameAddress(req['refundTo'], mine.refundTo))
186
+ return fail('refundTo');
187
+ if (req['originAsset'] !== mine.originAsset)
188
+ return fail('originAsset');
189
+ if (req['destinationAsset'] !== mine.destinationAsset)
190
+ return fail('destinationAsset');
191
+ if (req['depositType'] !== 'ORIGIN_CHAIN')
192
+ return fail('depositType');
193
+ if (req['refundType'] !== 'ORIGIN_CHAIN')
194
+ return fail('refundType');
195
+ if (req['recipientType'] !== 'DESTINATION_CHAIN')
196
+ return fail('recipientType');
197
+ if (req['slippageTolerance'] !== (mine.slippageBps ?? DEFAULT_SLIPPAGE_BPS))
198
+ return fail('slippageTolerance');
199
+ const fees = req['appFees'] === undefined || req['appFees'] === null ? [] : req['appFees'];
200
+ if (!Array.isArray(fees))
201
+ return fail('appFees');
202
+ const payee = mine.appFeeRecipient ?? ONE_APP_FEE?.recipient;
203
+ let other = 0;
204
+ let protocol = 0;
205
+ for (const f of fees) {
206
+ if (!isObj(f) || typeof f['fee'] !== 'number' || !Number.isFinite(f['fee']) || f['fee'] < 0)
207
+ return fail('appFees');
208
+ if (f['recipient'] === ONECLICK_PROTOCOL_RECIPIENT) {
209
+ protocol += f['fee'];
210
+ continue;
211
+ }
212
+ if (payee !== undefined && f['recipient'] !== payee)
213
+ return fail('appFees');
214
+ other += f['fee'];
215
+ }
216
+ if (protocol > (mine.protocolFeeCapBps ?? PROTOCOL_FEE_CAP_BPS))
217
+ return fail('appFees');
218
+ if (other > (mine.appFeeCapBps ?? ONE_APP_FEE?.bps ?? 0))
219
+ return fail('appFees');
220
+ if (req['depositMode'] !== undefined && req['depositMode'] !== 'SIMPLE')
221
+ return fail('depositMode');
222
+ if (q['depositMemo'] !== undefined && q['depositMemo'] !== null && q['depositMemo'] !== '')
223
+ return fail('memo');
224
+ const wantType = mine.exact === 'out' ? 'EXACT_OUTPUT' : 'EXACT_INPUT';
225
+ if (req['swapType'] !== wantType)
226
+ return fail('swapType');
227
+ if (String(req['amount'] ?? '') !== mine.amountBase)
228
+ return fail('amount');
229
+ if (mine.exact === 'in') {
230
+ if (String(q['amountIn'] ?? '') !== mine.amountBase)
231
+ return fail('amountIn');
232
+ }
233
+ else {
234
+ const cap = bigOf(mine.maxAmountInBase);
235
+ const got = bigOf(q['amountIn']);
236
+ if (cap === null || got === null || got > cap)
237
+ return fail('amountIn');
238
+ }
239
+ return { ok: true };
240
+ }
241
+ export function storedRecord(body) {
242
+ if (!isObj(body))
243
+ return {};
244
+ const qr = isObj(body['quoteResponse']) ? body['quoteResponse'] : body;
245
+ const req = isObj(qr['quoteRequest']) ? qr['quoteRequest'] : {};
246
+ const q = isObj(qr['quote']) ? qr['quote'] : {};
247
+ const s = (v) => (typeof v === 'string' && v ? v : undefined);
248
+ const amountIn = bigOf(q['amountIn']);
249
+ const amountOut = bigOf(q['amountOut']);
250
+ const minOut = bigOf(q['minAmountOut']);
251
+ return {
252
+ recipient: s(req['recipient']),
253
+ refundTo: s(req['refundTo']),
254
+ originAsset: s(req['originAsset']),
255
+ destinationAsset: s(req['destinationAsset']),
256
+ amountInBase: amountIn === null ? undefined : amountIn.toString(),
257
+ amountOutBase: amountOut === null ? undefined : amountOut.toString(),
258
+ minAmountOutBase: minOut === null ? undefined : minOut.toString(),
259
+ swapType: s(req['swapType']),
260
+ amountBase: bigOf(req['amount'])?.toString(),
261
+ // refundAfter is quoteRequest.deadline (1Click starts refunding), NOT quote.deadline (~72 h).
262
+ refundAfter: s(req['deadline']),
263
+ addressExpires: s(q['timeWhenInactive']) ?? s(q['deadline']),
264
+ quotedAt: s(qr['timestamp']),
265
+ status: s(body['status']),
266
+ };
267
+ }
268
+ /** Never print a send line inside the last five minutes before refunds begin. */
269
+ export const SEND_MARGIN_MS = 5 * 60_000;
270
+ /**
271
+ * Is there still time to send? `quotedAt` (1Click's clock) corrects this machine's skew:
272
+ * skew = localNowAtQuote − quotedAt; 1Click's now ≈ localNow − skew.
273
+ */
274
+ export function stillSendable(refundAfter, now, skewMs = 0) {
275
+ if (!refundAfter)
276
+ return false;
277
+ const t = Date.parse(refundAfter);
278
+ if (Number.isNaN(t))
279
+ return false;
280
+ return now.getTime() - skewMs < t - SEND_MARGIN_MS;
281
+ }
282
+ // ─── send instruction (verbatim from core.sendUri) ─────────────────────────────
283
+ const EVM_CHAIN_ID = { ethereum: 1, base: 8453, arbitrum: 42161 };
284
+ export function sendUri(asset, to, amountBase) {
285
+ const dec = formatUnits(amountBase, asset.decimals);
286
+ if (asset.chain === 'bitcoin')
287
+ return `bitcoin:${to}?amount=${dec}`;
288
+ if (asset.chain === 'solana')
289
+ return `solana:${to}?amount=${dec}${asset.contract ? `&spl-token=${asset.contract}` : ''}`;
290
+ const id = EVM_CHAIN_ID[asset.chain];
291
+ if (!id)
292
+ return undefined;
293
+ if (!asset.contract)
294
+ return `ethereum:${to}@${id}?value=${amountBase.toString()}`;
295
+ return `ethereum:${asset.contract}@${id}/transfer?address=${to}&uint256=${amountBase.toString()}`;
296
+ }
297
+ // ─── links ─────────────────────────────────────────────────────────────────────
298
+ const LOCAL_ORIGIN = /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
299
+ /**
300
+ * The page origin a link points at. The server's own link is only trusted for its ORIGIN, and
301
+ * only when that origin is https://one.ie or localhost — a gateway call can come back as
302
+ * https://api.one.ie/swap, which is no page. The query is always built here, never copied.
303
+ */
304
+ export function pageOrigin(serverLink) {
305
+ if (typeof serverLink !== 'string')
306
+ return 'https://one.ie';
307
+ try {
308
+ const o = new URL(serverLink).origin;
309
+ return o === 'https://one.ie' || LOCAL_ORIGIN.test(o) ? o : 'https://one.ie';
310
+ }
311
+ catch {
312
+ return 'https://one.ie';
313
+ }
314
+ }
315
+ export function swapLink(origin, q) {
316
+ const p = new URLSearchParams({ from: q.from, to: q.to, amount: q.amount });
317
+ if (q.exact === 'out')
318
+ p.set('exact', 'out');
319
+ return `${origin}/swap?${p.toString()}`;
320
+ }
321
+ export function depositLink(origin, depositAddress) {
322
+ return `${origin}/swap?${new URLSearchParams({ deposit: depositAddress }).toString()}`;
323
+ }
324
+ // ─── human lines ───────────────────────────────────────────────────────────────
325
+ const pad = (k) => k.padEnd(10);
326
+ /** The quote, one fact per line. `network: mainnet` is always the first line. */
327
+ export function quoteLines(r) {
328
+ const from = isObj(r['from']) ? r['from'] : {};
329
+ const to = isObj(r['to']) ? r['to'] : {};
330
+ const lines = [];
331
+ lines.push(`${pad('network')}${r['dry'] === false ? 'mainnet — real funds' : 'mainnet (1Click has no testnet; this is a price only)'}`);
332
+ if (r['amountIn'] !== undefined)
333
+ lines.push(`${pad('you send')}${r['amountIn']} ${from['alias'] ?? ''}${from['chain'] ? ` on ${from['chain']}` : ''}${r['amountInUsd'] ? ` (~$${r['amountInUsd']})` : ''}`);
334
+ if (r['minAmountIn'] !== undefined && r['minAmountIn'] !== r['amountIn'])
335
+ lines.push(`${pad('min send')}${r['minAmountIn']} ${from['alias'] ?? ''}`);
336
+ if (r['amountOut'] !== undefined)
337
+ lines.push(`${pad('you get')}${r['amountOut']} ${to['alias'] ?? ''}${r['amountOutUsd'] ? ` (~$${r['amountOutUsd']})` : ''}`);
338
+ if (r['minAmountOut'] !== undefined)
339
+ lines.push(`${pad('min recv')}${r['minAmountOut']} ${to['alias'] ?? ''} (after slippage)`);
340
+ const fees = Array.isArray(r['fees']) ? r['fees'] : [];
341
+ for (const f of fees) {
342
+ const amt = f.amount ? `${f.amount} ${f.asset ?? ''}`.trim() : '';
343
+ const bps = typeof f.bps === 'number' ? `${f.bps} bps` : '';
344
+ lines.push(`${pad('fee')}${[f.kind, [amt, bps].filter(Boolean).join(' · '), f.note ? `— ${f.note}` : ''].filter(Boolean).join(' ')}`);
345
+ }
346
+ if (r['costUsd'] !== undefined)
347
+ lines.push(`${pad('cost')}$${r['costUsd']} (value in − value out, read from the live quote)`);
348
+ if (typeof r['timeEstimateSec'] === 'number')
349
+ lines.push(`${pad('eta')}~${r['timeEstimateSec']} s after the deposit confirms`);
350
+ const route = isObj(r['route']) ? r['route'] : {};
351
+ if (route['credits'] === 'perps')
352
+ lines.push(`${pad('lands in')}your Hyperliquid PERPS balance`);
353
+ const warnings = Array.isArray(r['warnings']) ? r['warnings'] : [];
354
+ for (const w of warnings)
355
+ lines.push(`${pad('warning')}${w}`);
356
+ return lines;
357
+ }
358
+ export function statusLines(r) {
359
+ const lines = [`${pad('network')}mainnet`];
360
+ if (r['status'] !== undefined)
361
+ lines.push(`${pad('status')}${r['status']}${r['terminal'] ? ' (final)' : ''}`);
362
+ if (r['explain'])
363
+ lines.push(`${pad('means')}${r['explain']}`);
364
+ if (r['from'] || r['to'])
365
+ lines.push(`${pad('swap')}${r['from'] ?? '?'} → ${r['to'] ?? '?'}`);
366
+ if (r['amountIn'] !== undefined)
367
+ lines.push(`${pad('deposited')}${r['amountIn']}`);
368
+ if (r['amountOut'] !== undefined)
369
+ lines.push(`${pad('delivered')}${r['amountOut']}${r['amountOutUsd'] ? ` (~$${r['amountOutUsd']})` : ''}`);
370
+ if (r['refundedAmount'] !== undefined && r['refundedAmount'] !== '0')
371
+ lines.push(`${pad('refunded')}${r['refundedAmount']}${r['refundReason'] ? ` — ${r['refundReason']}` : ''}`);
372
+ for (const key of ['originTxs', 'destinationTxs']) {
373
+ const txs = Array.isArray(r[key]) ? r[key] : [];
374
+ for (const t of txs)
375
+ lines.push(`${pad(key === 'originTxs' ? 'deposit tx' : 'deliver tx')}${t.explorerUrl ?? t.hash ?? ''}`);
376
+ }
377
+ if (r['submitted'] === true)
378
+ lines.push(`${pad('tx hash')}forwarded to 1Click to speed matching (not a verification)`);
379
+ if (r['refundAfter'])
380
+ lines.push(`${pad('refunds')}begin ${r['refundAfter']} if not filled`);
381
+ if (isObj(r['hyperliquid']))
382
+ lines.push(...hlLines(r['hyperliquid']));
383
+ return lines;
384
+ }
385
+ /** Perps and spot, side by side — never summed (unified accounts show everything in spot). */
386
+ export function hlLines(h) {
387
+ const perps = isObj(h['perps']) ? h['perps'] : {};
388
+ const spot = Array.isArray(h['spot']) ? h['spot'] : [];
389
+ const lines = [
390
+ `${pad('hl')}${h['address'] ?? ''} on ${h['network'] ?? 'mainnet'}`,
391
+ `${pad('perps')}account value $${perps['accountValue'] ?? '0'} · withdrawable $${perps['withdrawable'] ?? '0'}`,
392
+ ];
393
+ if (!spot.length)
394
+ lines.push(`${pad('spot')}(empty)`);
395
+ for (const s of spot)
396
+ lines.push(`${pad('spot')}${s.total ?? '0'} ${s.coin ?? ''}${s.hold && s.hold !== '0' && s.hold !== '0.0' ? ` (${s.hold} on hold)` : ''}`);
397
+ if (h['firstDeposit'] === true)
398
+ lines.push(`${pad('note')}empty account — Hyperliquid MAY take a one-time ~1 USDC activation (unverified)`);
399
+ lines.push(`${pad('note')}perps and spot are separate balances; they are not summed`);
400
+ return lines;
401
+ }
402
+ export function assetLines(assets) {
403
+ const head = `${'alias'.padEnd(18)}${'chain'.padEnd(13)}${'decimals'.padEnd(10)}${'signer'.padEnd(10)}from to`;
404
+ return [head, ...assets.map((a) => `${String(a['alias'] ?? '').padEnd(18)}${String(a['chain'] ?? '').padEnd(13)}${String(a['decimals'] ?? '').padEnd(10)}${String(a['signer'] ?? '').padEnd(10)}${a['origin'] ? 'yes ' : 'dry '} ${a['destination'] ? 'yes' : 'no'}`)];
405
+ }
@@ -95,8 +95,8 @@ export interface GiveSdk {
95
95
  * Swappable in tests (the message-seal.ts `loaders` shape): the cli resolves `@oneie/sdk` through
96
96
  * its own node_modules, which can be a published or main-tree SDK older than `./secrets-give`;
97
97
  * a test serves the source. `oneVault` is the reader of ONE's vault and the ONLY source of ONE's
98
- * lock — the IC#7 fixture until C14 reaches testnet, which answers no lock, so a give refuses
99
- * `no_one_lock`. Nothing in the environment or on disk can name another lock (C8 repair 3); a
98
+ * lock — C14 reached testnet 2026-11-08: the fixture is the SDK's mirror of ONE's testnet vault
99
+ * (ONE_VAULT_ID), pinned equal to the chain by one-vault-chain.test.ts. Nothing in the environment or on disk can name another lock (C8 repair 3); a
100
100
  * test injects a reader by assigning this field. `fetch` is the one network call.
101
101
  */
102
102
  export declare const giveLoaders: {
@@ -47,8 +47,8 @@ const GIVE_SPEC = '@oneie/sdk/secrets-give'; // a variable, so a bundler/vite do
47
47
  * Swappable in tests (the message-seal.ts `loaders` shape): the cli resolves `@oneie/sdk` through
48
48
  * its own node_modules, which can be a published or main-tree SDK older than `./secrets-give`;
49
49
  * a test serves the source. `oneVault` is the reader of ONE's vault and the ONLY source of ONE's
50
- * lock — the IC#7 fixture until C14 reaches testnet, which answers no lock, so a give refuses
51
- * `no_one_lock`. Nothing in the environment or on disk can name another lock (C8 repair 3); a
50
+ * lock — C14 reached testnet 2026-11-08: the fixture is the SDK's mirror of ONE's testnet vault
51
+ * (ONE_VAULT_ID), pinned equal to the chain by one-vault-chain.test.ts. Nothing in the environment or on disk can name another lock (C8 repair 3); a
52
52
  * test injects a reader by assigning this field. `fetch` is the one network call.
53
53
  */
54
54
  export const giveLoaders = {
@@ -0,0 +1,27 @@
1
+ /**
2
+ * secrets-list.ts — `one secrets list`: your secrets desk from the terminal (text/secrets.md
3
+ * § What an agent sees; the `secrets:list` receiver, C15).
4
+ *
5
+ * Read only. One POST to secrets:list through ask(); the web side reads WHO from the session or
6
+ * the API key and D1 — this command sends nothing about the caller. Names and meters only: the
7
+ * receiver never returns a value, and this prints only what it returned.
8
+ *
9
+ * Lending and Stop are not here. A person signs a grant or a Stop with a passkey on the seal
10
+ * page, in a window of its own (plan D11, § Signatures); an agent may sign with its own ed25519
11
+ * key, but no vault holds a grant-signer list until the D37 package is published (D46), so an
12
+ * agent-signed grant has nothing to verify against yet.
13
+ */
14
+ import { Command } from 'commander';
15
+ /** Swappable in tests. `fetch` is the one network call. */
16
+ export declare const listLoaders: {
17
+ fetch: (input: string, init: RequestInit) => Promise<Response>;
18
+ };
19
+ type Rec = Record<string, unknown>;
20
+ /** The desk in a few human lines — never a value, never a full id where a short one reads. */
21
+ export declare function deskLines(r: Rec): string[];
22
+ export declare function listAction(o: {
23
+ api?: string;
24
+ }, c: Command): Promise<void>;
25
+ /** The `list` subcommand, fresh per call (a Command has one parent). */
26
+ export declare function buildList(): Command;
27
+ export {};
@@ -0,0 +1,84 @@
1
+ /**
2
+ * secrets-list.ts — `one secrets list`: your secrets desk from the terminal (text/secrets.md
3
+ * § What an agent sees; the `secrets:list` receiver, C15).
4
+ *
5
+ * Read only. One POST to secrets:list through ask(); the web side reads WHO from the session or
6
+ * the API key and D1 — this command sends nothing about the caller. Names and meters only: the
7
+ * receiver never returns a value, and this prints only what it returned.
8
+ *
9
+ * Lending and Stop are not here. A person signs a grant or a Stop with a passkey on the seal
10
+ * page, in a window of its own (plan D11, § Signatures); an agent may sign with its own ed25519
11
+ * key, but no vault holds a grant-signer list until the D37 package is published (D46), so an
12
+ * agent-signed grant has nothing to verify against yet.
13
+ */
14
+ import { Command } from 'commander';
15
+ import { askPath } from './lib/api-path.js';
16
+ import { authHeaders, jsonMode, out, resolveBase } from './lib/client.js';
17
+ /** Swappable in tests. `fetch` is the one network call. */
18
+ export const listLoaders = {
19
+ fetch: (input, init) => fetch(input, init),
20
+ };
21
+ /** D51: an "unlimited" lend signs this ceiling (UNLIMITED_PER_DAY in @oneie/sdk/secrets; kept here so the CLI runs on a published SDK that predates it). */
22
+ const UNLIMITED_PER_DAY = 1_000_000;
23
+ const leftLine = (l) => {
24
+ const per = Number(l['perDay']);
25
+ if (per === UNLIMITED_PER_DAY)
26
+ return `${per - Number(l['left_today'] ?? per)} today · no daily limit (ceiling 1,000,000)`;
27
+ return `${String(l['left_today'] ?? '?')}/${String(l['perDay'] ?? '?')} left today`;
28
+ };
29
+ const arr = (v) => (Array.isArray(v) ? v : []);
30
+ /** The desk in a few human lines — never a value, never a full id where a short one reads. */
31
+ export function deskLines(r) {
32
+ const lines = [];
33
+ const keys = arr(r['keys']);
34
+ const lent = arr(r['lentToMe']);
35
+ lines.push(`ok keys=${keys.length} lent_to_me=${lent.length} vaults=${arr(r['vaults']).length}${r['capped'] === true ? ' capped=true' : ''}`);
36
+ for (const k of keys) {
37
+ const grants = arr(k['grants']);
38
+ const live = grants.filter((g) => g['stopped'] !== true).length;
39
+ lines.push(`key ${String(k['name'] ?? '?')} ${String(k['provider'] ?? '?')} …${String(k['last4'] ?? '')} grants=${live} live/${grants.length}${k['flagged'] ? ` flagged=${String(k['flagged'])}` : ''}`);
40
+ }
41
+ for (const l of lent) {
42
+ lines.push(`lent ${String(l['name'] ?? '?')} ${String(l['provider'] ?? '?')} from ${String(l['from'] ?? '?')} ${leftLine(l)} until ${String(l['until'] ?? '?')}${l['stopped'] === true ? ' STOPPED' : l['accepted'] === true ? '' : ' not accepted'}`);
43
+ }
44
+ for (const c of arr(r['composio'])) {
45
+ if (!c['requireGrants'])
46
+ lines.push(`composio ${String(c['group'] ?? '?')} running without a grant today=${String(c['noGrantToday'] ?? 0)}`);
47
+ }
48
+ return lines;
49
+ }
50
+ export async function listAction(o, c) {
51
+ const base = resolveBase({ api: o.api });
52
+ let res;
53
+ try {
54
+ res = await listLoaders.fetch(askPath(base, 'secrets:list'), { method: 'POST', headers: authHeaders(), body: JSON.stringify({ data: {} }) });
55
+ }
56
+ catch {
57
+ return out(c, { ok: false, error: `could not reach ${base}`, code: 'unreachable' });
58
+ }
59
+ let json = {};
60
+ try {
61
+ json = (await res.json());
62
+ }
63
+ catch {
64
+ /* the status speaks */
65
+ }
66
+ const r = json['result'] ?? json;
67
+ if (!res.ok || r['ok'] !== true) {
68
+ const code = String(r['refused'] ?? r['error'] ?? `http_${res.status}`);
69
+ const why = code === 'opener_unbound' ? ' — the opener is not live on this host yet; nothing was read' : '';
70
+ return out(c, { ok: false, error: `secrets:list refused: ${code}${why}`, code });
71
+ }
72
+ if (jsonMode(c)) {
73
+ process.stdout.write(JSON.stringify(r) + '\n');
74
+ return;
75
+ }
76
+ process.stdout.write(deskLines(r).join('\n') + '\n');
77
+ }
78
+ /** The `list` subcommand, fresh per call (a Command has one parent). */
79
+ export function buildList() {
80
+ return new Command('list')
81
+ .description('Your secrets desk — the keys you gave ONE, who uses them, keys lent to you. Names and meters, never values')
82
+ .option('--api <url>', 'API base (default: ONE_API_URL or https://one.ie)')
83
+ .action(listAction);
84
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * secrets.ts — `one secrets seal | run | add-device | give`: the sealed .env.
2
+ * secrets.ts — `one secrets seal | run | add-device | give | list`: the sealed .env.
3
3
  * (text/secrets.md deliverables 1 and 5; text/secrets-todo.md § C1.)
4
4
  *
5
5
  * `seal` is the one verb built here. It turns a plaintext .env into `.env.sealed` v1 —
@@ -17,7 +17,8 @@
17
17
  * `run` and `hash` live in secrets-run.ts (C2). `add-device` (secrets-device.ts, C3) makes this
18
18
  * Mac a reader; a Secure Enclave lock among the readers seals through the `age` program
19
19
  * (lib/age-plugin.ts). `give` (secrets-give.ts, C8) hands a key to ONE, sealed to the lock ONE's
20
- * vault names and signed by an agent's own key.
20
+ * vault names and signed by an agent's own key. `list` (secrets-list.ts, C15) reads the desk —
21
+ * secrets:list, names and meters, never values.
21
22
  */
22
23
  import { Command } from 'commander';
23
24
  import { type Fail } from './lib/message-seal.js';
@@ -1,5 +1,5 @@
1
1
  /**
2
- * secrets.ts — `one secrets seal | run | add-device | give`: the sealed .env.
2
+ * secrets.ts — `one secrets seal | run | add-device | give | list`: the sealed .env.
3
3
  * (text/secrets.md deliverables 1 and 5; text/secrets-todo.md § C1.)
4
4
  *
5
5
  * `seal` is the one verb built here. It turns a plaintext .env into `.env.sealed` v1 —
@@ -17,7 +17,8 @@
17
17
  * `run` and `hash` live in secrets-run.ts (C2). `add-device` (secrets-device.ts, C3) makes this
18
18
  * Mac a reader; a Secure Enclave lock among the readers seals through the `age` program
19
19
  * (lib/age-plugin.ts). `give` (secrets-give.ts, C8) hands a key to ONE, sealed to the lock ONE's
20
- * vault names and signed by an agent's own key.
20
+ * vault names and signed by an agent's own key. `list` (secrets-list.ts, C15) reads the desk —
21
+ * secrets:list, names and meters, never values.
21
22
  */
22
23
  import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
23
24
  import { homedir } from 'node:os';
@@ -29,6 +30,7 @@ import { ageModule, loadSecretsKey, MAX_INPUT_BYTES } from './lib/message-seal.j
29
30
  import { AgePluginError, isPluginLock, PLUGIN_LOCK_RE, requireAge } from './lib/age-plugin.js';
30
31
  import { addDeviceAction } from './secrets-device.js';
31
32
  import { buildGive } from './secrets-give.js';
33
+ import { buildList } from './secrets-list.js';
32
34
  import { buildHash, buildRun } from './secrets-run.js';
33
35
  export function fail(cmd, f) {
34
36
  if (jsonMode(cmd))
@@ -193,5 +195,6 @@ export function secretsCmd() {
193
195
  .option('--name <label>', 'A name for this Mac (default: its hostname)')
194
196
  .option('--replace', 'Make a new key even though one exists (the old one stops being a reader)')
195
197
  .action(addDeviceAction))
196
- .addCommand(buildGive());
198
+ .addCommand(buildGive())
199
+ .addCommand(buildList());
197
200
  }