@oneie/cli 5.7.4 → 5.7.6

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.
Files changed (60) hide show
  1. package/README.md +15 -0
  2. package/dist/package.json +5 -2
  3. package/dist/src/balances.d.ts +89 -0
  4. package/dist/src/balances.js +202 -0
  5. package/dist/src/hl-run.d.ts +119 -0
  6. package/dist/src/hl-run.js +480 -0
  7. package/dist/src/hl.d.ts +17 -0
  8. package/dist/src/hl.js +148 -0
  9. package/dist/src/index.js +4 -0
  10. package/dist/src/key-sweep.d.ts +19 -3
  11. package/dist/src/key-sweep.js +63 -20
  12. package/dist/src/lib/hl-core/actions.d.ts +99 -0
  13. package/dist/src/lib/hl-core/actions.js +69 -0
  14. package/dist/src/lib/hl-core/eip712.d.ts +33 -0
  15. package/dist/src/lib/hl-core/eip712.js +107 -0
  16. package/dist/src/lib/hl-core/errors.d.ts +10 -0
  17. package/dist/src/lib/hl-core/errors.js +15 -0
  18. package/dist/src/lib/hl-core/exchange.d.ts +24 -0
  19. package/dist/src/lib/hl-core/exchange.js +47 -0
  20. package/dist/src/lib/hl-core/index.d.ts +13 -0
  21. package/dist/src/lib/hl-core/index.js +14 -0
  22. package/dist/src/lib/hl-core/meta.d.ts +57 -0
  23. package/dist/src/lib/hl-core/meta.js +110 -0
  24. package/dist/src/lib/hl-core/msgpack.d.ts +18 -0
  25. package/dist/src/lib/hl-core/msgpack.js +136 -0
  26. package/dist/src/lib/hl-core/net.d.ts +2 -0
  27. package/dist/src/lib/hl-core/net.js +7 -0
  28. package/dist/src/lib/hl-core/signing.d.ts +103 -0
  29. package/dist/src/lib/hl-core/signing.js +295 -0
  30. package/dist/src/lib/hl-core/wire.d.ts +34 -0
  31. package/dist/src/lib/hl-core/wire.js +81 -0
  32. package/dist/src/lib/journey-words.d.ts +54 -3
  33. package/dist/src/lib/journey-words.js +159 -20
  34. package/dist/src/lib/journey.js +1 -1
  35. package/dist/src/lib/key-source.d.ts +9 -0
  36. package/dist/src/lib/key-source.js +33 -0
  37. package/dist/src/lib/network.d.ts +15 -0
  38. package/dist/src/lib/network.js +41 -0
  39. package/dist/src/lib/qr.d.ts +21 -0
  40. package/dist/src/lib/qr.js +402 -0
  41. package/dist/src/lib/sale-card.d.ts +117 -0
  42. package/dist/src/lib/sale-card.js +261 -0
  43. package/dist/src/lib/sui-grpc-send.d.ts +50 -0
  44. package/dist/src/lib/sui-grpc-send.js +89 -0
  45. package/dist/src/lib/swap-core.d.ts +163 -0
  46. package/dist/src/lib/swap-core.js +405 -0
  47. package/dist/src/lib/wallet-money.d.ts +222 -0
  48. package/dist/src/lib/wallet-money.js +578 -0
  49. package/dist/src/lib/wallet-request.d.ts +50 -0
  50. package/dist/src/lib/wallet-request.js +86 -0
  51. package/dist/src/onboard.js +4 -3
  52. package/dist/src/shop.js +38 -1
  53. package/dist/src/staff.js +10 -0
  54. package/dist/src/start.js +14 -6
  55. package/dist/src/swap.d.ts +93 -0
  56. package/dist/src/swap.js +622 -0
  57. package/dist/src/wallet-money.d.ts +152 -0
  58. package/dist/src/wallet-money.js +564 -0
  59. package/dist/src/wallet.js +169 -24
  60. package/package.json +5 -2
@@ -0,0 +1,578 @@
1
+ /**
2
+ * wallet-money.ts — the pure half of `one wallet balances | receive | send | request`:
3
+ * the chain table, the words a person types, the reads, which chain a bare `USDC`
4
+ * means, the plan a send would sign, and the client check (R16) run before it does.
5
+ *
6
+ * Every chain read takes `Fetch` as an argument (tests hand in a fake; the command
7
+ * hands in a fetch with a deadline). A read that fails is null, never 0.
8
+ * Nothing here opens a vault or holds a key.
9
+ */
10
+ import { EVM_CHAINS as MAINNET_EVM_TOKENS, formatUnits } from '../balances.js';
11
+ /** The three EVM chains on each network. Testnet USDC contracts read back `symbol() = USDC` (2026-11-09). */
12
+ export const EVM = {
13
+ ethereum: {
14
+ mainnet: { chainId: 1, rpc: 'https://ethereum-rpc.publicnode.com', usdc: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', explorer: 'https://etherscan.io', label: 'Ethereum' },
15
+ testnet: { chainId: 11155111, rpc: 'https://ethereum-sepolia-rpc.publicnode.com', usdc: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', explorer: 'https://sepolia.etherscan.io', label: 'Ethereum Sepolia' },
16
+ },
17
+ base: {
18
+ mainnet: { chainId: 8453, rpc: 'https://base-rpc.publicnode.com', usdc: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', explorer: 'https://basescan.org', label: 'Base' },
19
+ testnet: { chainId: 84532, rpc: 'https://base-sepolia-rpc.publicnode.com', usdc: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', explorer: 'https://sepolia.basescan.org', label: 'Base Sepolia' },
20
+ },
21
+ arbitrum: {
22
+ mainnet: { chainId: 42161, rpc: 'https://arbitrum-one-rpc.publicnode.com', usdc: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831', explorer: 'https://arbiscan.io', label: 'Arbitrum' },
23
+ testnet: { chainId: 421614, rpc: 'https://arbitrum-sepolia-rpc.publicnode.com', usdc: '0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d', explorer: 'https://sepolia.arbiscan.io', label: 'Arbitrum Sepolia' },
24
+ },
25
+ };
26
+ export const EVM_CHAIN_NAMES = ['ethereum', 'base', 'arbitrum'];
27
+ /** Sui's public JSON-RPC answers "deprecated" on mainnet and testnet (measured 2026-11-09); GraphQL is the public read. */
28
+ export const SUI = {
29
+ mainnet: { graphql: 'https://graphql.mainnet.sui.io/graphql', usdc: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC', explorer: 'https://suiscan.xyz/mainnet', label: 'Sui' },
30
+ testnet: { graphql: 'https://graphql.testnet.sui.io/graphql', usdc: '0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29::usdc::USDC', explorer: 'https://suiscan.xyz/testnet', label: 'Sui testnet' },
31
+ };
32
+ export const SUI_NATIVE = '0x2::sui::SUI';
33
+ export const DECIMALS = { ETH: 18, USDC: 6, SUI: 9 };
34
+ const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
35
+ const SUI_RE = /^0x[0-9a-fA-F]{64}$/;
36
+ export function parseNet(v) {
37
+ return v === 'mainnet' || v === 'testnet' ? v : null;
38
+ }
39
+ /** "0.5" → base units; anything that is not a plain positive decimal within `decimals` places → null. */
40
+ export function parseAmount(input, decimals) {
41
+ const s = input.trim();
42
+ if (!/^(\d+)(\.\d+)?$/.test(s) && !/^\.\d+$/.test(s))
43
+ return null;
44
+ const [w = '', f = ''] = s.split('.');
45
+ if (f.length > decimals)
46
+ return null;
47
+ const v = BigInt((w || '0') + f.padEnd(decimals, '0'));
48
+ return v > 0n ? v : null;
49
+ }
50
+ // ─── the words ────────────────────────────────────────────────────────────────
51
+ const CHAIN_WORDS = {
52
+ eth: 'ethereum', ethereum: 'ethereum', mainnet: 'ethereum', l1: 'ethereum',
53
+ base: 'base', arb: 'arbitrum', arbitrum: 'arbitrum', sui: 'sui',
54
+ };
55
+ /** `ETH` · `USDC@base` · `SUI` — the asset and, when named, the chain. */
56
+ export function parseAssetWord(word) {
57
+ const [a = '', c] = word.trim().split('@');
58
+ const asset = a.toUpperCase();
59
+ if (asset !== 'ETH' && asset !== 'USDC' && asset !== 'SUI') {
60
+ const known = ['SOL', 'BTC', 'USDT', 'FET'].includes(asset);
61
+ return {
62
+ ok: false, error: known ? `no_signer:${asset.toLowerCase()}` : 'unknown_asset',
63
+ message: known ? `This CLI signs ETH, USDC and SUI only. ${asset} has no signer here.` : `Name ETH, USDC or SUI (optionally @ethereum, @base, @arbitrum or @sui), not "${word}".`,
64
+ };
65
+ }
66
+ if (c === undefined)
67
+ return asset === 'SUI' ? { ok: true, asset, chain: 'sui' } : { ok: true, asset };
68
+ const chain = CHAIN_WORDS[c.toLowerCase()];
69
+ if (!chain)
70
+ return { ok: false, error: 'unknown_chain', message: `"${c}" is not a chain this CLI sends on — ethereum, base, arbitrum or sui.` };
71
+ if (asset === 'ETH' && chain === 'sui')
72
+ return { ok: false, error: 'asset_not_on_chain', message: 'ETH does not live on Sui.' };
73
+ if (asset === 'SUI' && chain !== 'sui')
74
+ return { ok: false, error: 'asset_not_on_chain', message: `SUI lives on Sui, not ${chain}.` };
75
+ return { ok: true, asset, chain };
76
+ }
77
+ /** The chains a bare asset could mean, in a fixed order. */
78
+ export function candidateChains(asset) {
79
+ if (asset === 'SUI')
80
+ return ['sui'];
81
+ if (asset === 'ETH')
82
+ return [...EVM_CHAIN_NAMES];
83
+ return [...EVM_CHAIN_NAMES, 'sui'];
84
+ }
85
+ export const familyOf = (chain) => (chain === 'sui' ? 'sui' : 'evm');
86
+ export const chainLabel = (chain, net) => (chain === 'sui' ? SUI[net].label : EVM[chain][net].label);
87
+ export function addressShape(addr) {
88
+ return EVM_RE.test(addr) ? 'evm' : SUI_RE.test(addr) ? 'sui' : null;
89
+ }
90
+ // ─── chain reads (null = not read) ────────────────────────────────────────────
91
+ async function post(f, url, body) {
92
+ const res = await f(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
93
+ if (!res.ok)
94
+ throw new Error('http_error');
95
+ return res.json();
96
+ }
97
+ export async function evmRpc(f, rpc, method, params) {
98
+ const r = (await post(f, rpc, { jsonrpc: '2.0', id: 1, method, params }));
99
+ if (r.error)
100
+ throw new Error(`rpc_error: ${r.error.message ?? 'unknown'}`);
101
+ if (typeof r.result !== 'string')
102
+ throw new Error('bad_answer');
103
+ return r.result;
104
+ }
105
+ const hexNum = (h) => {
106
+ if (!/^0x[0-9a-fA-F]*$/.test(h))
107
+ throw new Error('bad_answer');
108
+ return h === '0x' ? 0n : BigInt(h);
109
+ };
110
+ const padAddr = (a) => a.slice(2).toLowerCase().padStart(64, '0');
111
+ export async function readEvmAsset(f, chain, net, asset, address) {
112
+ const n = EVM[chain][net];
113
+ try {
114
+ if (asset === 'ETH')
115
+ return hexNum(await evmRpc(f, n.rpc, 'eth_getBalance', [address, 'latest']));
116
+ return hexNum(await evmRpc(f, n.rpc, 'eth_call', [{ to: n.usdc, data: `0x70a08231${padAddr(address)}` }, 'latest']));
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
122
+ /** A coin balance on Sui via GraphQL; an address that never held the coin answers a null balance — a real zero. */
123
+ export async function readSuiCoin(f, net, address, coinType) {
124
+ try {
125
+ const r = (await post(f, SUI[net].graphql, {
126
+ query: 'query($a: SuiAddress!, $t: String!) { address(address: $a) { balance(coinType: $t) { totalBalance } } }',
127
+ variables: { a: address, t: coinType },
128
+ }));
129
+ if (r.data?.address && r.data.address.balance === null)
130
+ return 0n;
131
+ const b = r.data?.address?.balance?.totalBalance;
132
+ if (typeof b !== 'string' || !/^\d+$/.test(b))
133
+ return null;
134
+ return BigInt(b);
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ export async function readAsset(f, asset, chain, net, address) {
141
+ if (chain === 'sui')
142
+ return readSuiCoin(f, net, address, asset === 'SUI' ? SUI_NATIVE : SUI[net].usdc);
143
+ if (asset === 'SUI')
144
+ return null;
145
+ return readEvmAsset(f, chain, net, asset, address);
146
+ }
147
+ /** SOL in lamports from a public Solana node (testnet = devnet, where ONE's test money lives). */
148
+ export const SOL_RPC = { mainnet: 'https://api.mainnet-beta.solana.com', testnet: 'https://api.devnet.solana.com' };
149
+ export async function readSol(f, net, address) {
150
+ try {
151
+ const r = (await post(f, SOL_RPC[net], { jsonrpc: '2.0', id: 1, method: 'getBalance', params: [address] }));
152
+ const v = r.result?.value;
153
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null;
154
+ }
155
+ catch {
156
+ return null;
157
+ }
158
+ }
159
+ /** BTC in satoshis from mempool.space: confirmed + unconfirmed, funded minus spent. */
160
+ export const BTC_API = { mainnet: 'https://mempool.space/api', testnet: 'https://mempool.space/testnet4/api' };
161
+ export async function readBtc(f, net, address) {
162
+ try {
163
+ const res = await f(`${BTC_API[net]}/address/${encodeURIComponent(address)}`);
164
+ if (!res.ok)
165
+ return null;
166
+ const j = (await res.json());
167
+ const n = (o, k) => (typeof o?.[k] === 'number' && Number.isSafeInteger(o[k]) ? BigInt(o[k]) : null);
168
+ const parts = [n(j.chain_stats, 'funded_txo_sum'), n(j.chain_stats, 'spent_txo_sum'), n(j.mempool_stats, 'funded_txo_sum'), n(j.mempool_stats, 'spent_txo_sum')];
169
+ if (parts.some((x) => x === null))
170
+ return null;
171
+ const [cf, cs, mf, ms] = parts;
172
+ return cf - cs + mf - ms;
173
+ }
174
+ catch {
175
+ return null;
176
+ }
177
+ }
178
+ /** What a server-given address must look like before it is used, printed or pasted anywhere. */
179
+ export const ADDRESS_SHAPE = {
180
+ evm: EVM_RE,
181
+ sui: SUI_RE,
182
+ solana: /^[1-9A-HJ-NP-Za-km-z]{32,44}$/,
183
+ btc: /^(?:(?:bc1|tb1)[02-9ac-hj-np-z]{11,87}|[13mn2][1-9A-HJ-NP-Za-km-z]{25,34})$/,
184
+ };
185
+ /** wallet:get's rows for one actor → the addresses it holds. A row whose address is not its chain's shape is dropped. */
186
+ export function addressesFor(walletGet, actor) {
187
+ const rows = Array.isArray(walletGet['addresses']) ? walletGet['addresses'] : [];
188
+ const pick = (chain) => {
189
+ const r = rows.find((x) => x['actor'] === actor && x['chain'] === chain && typeof x['address'] === 'string' && ADDRESS_SHAPE[chain].test(x['address']));
190
+ return r ? String(r['address']) : undefined;
191
+ };
192
+ const out = {};
193
+ const evm = pick('evm'), sui = pick('sui'), solana = pick('solana'), btc = pick('btc');
194
+ if (evm)
195
+ out.evm = evm;
196
+ if (sui)
197
+ out.sui = sui;
198
+ if (solana)
199
+ out.solana = solana;
200
+ if (btc)
201
+ out.btc = btc;
202
+ return out;
203
+ }
204
+ const SERVER_ROW = {
205
+ evm: { chain: 'ethereum', asset: 'ETH' }, sui: { chain: 'sui', asset: 'SUI' },
206
+ solana: { chain: 'solana', asset: 'SOL' }, btc: { chain: 'bitcoin', asset: 'BTC' },
207
+ };
208
+ /**
209
+ * Every balance of one actor on ONE network. A wallet:get row is used only when it says
210
+ * it was read on the network asked (a server that ignores `net` answers the deploy's —
211
+ * production's is testnet — and such a row is dropped, never shown under the wrong label).
212
+ * What wallet:get does not read — USDC everywhere, ETH on Base and Arbitrum, USDT on
213
+ * mainnet, and SOL/BTC when the server gave no row — is read from the chains here.
214
+ */
215
+ export async function moneyBalances(args, f, hlRead) {
216
+ const { addresses, net, actor } = args;
217
+ const rows = [];
218
+ let hyperliquid;
219
+ const server = (Array.isArray(args.walletGet?.['balances']) ? args.walletGet['balances'] : [])
220
+ .filter((b) => b['actor'] === actor && b['network'] === net);
221
+ const have = new Set();
222
+ for (const b of server) {
223
+ const chain = String(b['chain']);
224
+ if (chain === 'hyperliquid') {
225
+ const perps = b['perps'];
226
+ const spot = Array.isArray(b['spot']) ? b['spot'].map((s) => ({ coin: s.coin, total: s.total })) : null;
227
+ hyperliquid = b['balance'] === null
228
+ ? { perps: null, withdrawable: null, spot: null, unavailable: 'server_read_failed' }
229
+ : { perps: perps?.accountValue ?? '0', withdrawable: perps?.withdrawable ?? '0', spot: spot ?? [] };
230
+ have.add('hyperliquid');
231
+ continue;
232
+ }
233
+ const m = SERVER_ROW[chain];
234
+ if (!m)
235
+ continue;
236
+ const amount = typeof b['balance'] === 'string' ? b['balance'] : null;
237
+ rows.push({ ...m, amount, ...(amount === null ? { unavailable: 'server_read_failed' } : {}), source: 'wallet:get' });
238
+ have.add(`${m.chain}:${m.asset}`);
239
+ }
240
+ const reads = [];
241
+ const direct = (chain, asset, decimals, read) => {
242
+ if (have.has(`${chain}:${asset}`))
243
+ return;
244
+ reads.push(read().then((v) => (v === null
245
+ ? { chain, asset, amount: null, unavailable: 'read_failed', source: 'chain' }
246
+ : { chain, asset, amount: formatUnits(v, decimals), source: 'chain' })));
247
+ };
248
+ if (addresses.evm) {
249
+ const a = addresses.evm;
250
+ for (const c of EVM_CHAIN_NAMES) {
251
+ direct(c, 'ETH', 18, () => readEvmAsset(f, c, net, 'ETH', a));
252
+ direct(c, 'USDC', 6, () => readEvmAsset(f, c, net, 'USDC', a));
253
+ if (net === 'mainnet') {
254
+ for (const t of MAINNET_EVM_TOKENS.find((x) => x.name === c)?.tokens ?? []) {
255
+ if (t.symbol === 'USDC')
256
+ continue;
257
+ direct(c, t.symbol, t.decimals, async () => {
258
+ try {
259
+ return hexNum(await evmRpc(f, EVM[c][net].rpc, 'eth_call', [{ to: t.contract, data: `0x70a08231${padAddr(a)}` }, 'latest']));
260
+ }
261
+ catch {
262
+ return null;
263
+ }
264
+ });
265
+ }
266
+ }
267
+ }
268
+ if (!have.has('hyperliquid') && hlRead)
269
+ hyperliquid = await hlRead(a);
270
+ }
271
+ if (addresses.sui) {
272
+ const a = addresses.sui;
273
+ direct('sui', 'SUI', 9, () => readSuiCoin(f, net, a, SUI_NATIVE));
274
+ direct('sui', 'USDC', 6, () => readSuiCoin(f, net, a, SUI[net].usdc));
275
+ }
276
+ if (addresses.solana) {
277
+ const a = addresses.solana;
278
+ direct('solana', 'SOL', 9, () => readSol(f, net, a));
279
+ }
280
+ if (addresses.btc) {
281
+ const a = addresses.btc;
282
+ direct('bitcoin', 'BTC', 8, () => readBtc(f, net, a));
283
+ }
284
+ rows.push(...(await Promise.all(reads)));
285
+ return {
286
+ ok: true, network: net, addresses, rows, ...(hyperliquid ? { hyperliquid } : {}),
287
+ note: `${net === 'mainnet' ? 'Mainnet — real money' : 'Testnet — practice money'}. Rows marked wallet:get were read by ONE's server on ${net}; the rest straight from the chains. unavailable is not zero.`,
288
+ };
289
+ }
290
+ export function moneyLines(r) {
291
+ const lines = [`network ${r.network}${r.network === 'mainnet' ? ' (real money)' : ' (practice money)'}`];
292
+ for (const [k, v] of Object.entries(r.addresses))
293
+ lines.push(`${k.padEnd(10)}${v}`);
294
+ let shown = 0;
295
+ for (const x of r.rows) {
296
+ if (x.amount === '0')
297
+ continue;
298
+ shown++;
299
+ lines.push(`${x.chain.padEnd(10)}${x.asset.padEnd(6)}${x.amount === null ? `unavailable (${x.unavailable ?? 'read_failed'})` : x.amount}`);
300
+ }
301
+ if (shown === 0)
302
+ lines.push('(every read answered: nothing here)');
303
+ const h = r.hyperliquid;
304
+ if (h) {
305
+ if (h.unavailable)
306
+ lines.push(`hyperliquid unavailable (${h.unavailable})`);
307
+ else {
308
+ lines.push(`hyperliquid perps ${h.perps ?? '0'} (withdrawable ${h.withdrawable ?? '0'})`);
309
+ lines.push(`hyperliquid spot ${h.spot && h.spot.length ? h.spot.map((b) => `${b.total} ${b.coin}`).join(', ') : 'none'}`);
310
+ lines.push('perps and spot are separate balances; they are not summed');
311
+ }
312
+ }
313
+ return lines;
314
+ }
315
+ const RECEIVE_WORDS = {
316
+ ...CHAIN_WORDS, sol: 'solana', solana: 'solana', btc: 'bitcoin', bitcoin: 'bitcoin', hl: 'hyperliquid', hyperliquid: 'hyperliquid',
317
+ };
318
+ const RECEIVE_ASSETS = {
319
+ ethereum: 'ETH and USDC', base: 'ETH and USDC', arbitrum: 'ETH and USDC', sui: 'SUI and USDC', solana: 'SOL', bitcoin: 'BTC',
320
+ };
321
+ /** Which chains these addresses can receive on — the list a refusal names. */
322
+ export function receivableChains(a) {
323
+ const out = [];
324
+ if (a.evm)
325
+ out.push('ethereum', 'base', 'arbitrum');
326
+ if (a.sui)
327
+ out.push('sui');
328
+ if (a.solana)
329
+ out.push('solana');
330
+ if (a.btc)
331
+ out.push('bitcoin');
332
+ return out;
333
+ }
334
+ /** One chain, one address, one QR payload. No chain = refused: one 0x address is three chains. */
335
+ export function receivePlan(chainWord, a, net) {
336
+ const options = receivableChains(a);
337
+ if (!chainWord)
338
+ return { ok: false, error: 'chain_required', message: `Name the chain with --chain — the same 0x address receives on Ethereum, Base and Arbitrum, and a coin sent on the wrong one is not where you look. Yours: ${options.join(', ') || 'none registered'}.`, options };
339
+ const chain = RECEIVE_WORDS[chainWord.toLowerCase()];
340
+ if (!chain)
341
+ return { ok: false, error: 'unknown_chain', message: `"${chainWord}" is not a chain — ${options.join(', ')}.`, options };
342
+ if (chain === 'hyperliquid')
343
+ return { ok: false, error: 'hyperliquid_not_a_transfer', message: 'A plain transfer to your 0x address does not reach Hyperliquid. Bridge in with: one swap <amount> <coin> hl --live', options };
344
+ const address = chain === 'sui' ? a.sui : chain === 'solana' ? a.solana : chain === 'bitcoin' ? a.btc : a.evm;
345
+ if (!address)
346
+ return { ok: false, error: 'no_address', message: `This wallet has no ${chain} address registered.`, options };
347
+ let uri, label;
348
+ if (chain === 'ethereum' || chain === 'base' || chain === 'arbitrum') {
349
+ uri = `ethereum:${address}@${EVM[chain][net].chainId}`;
350
+ label = EVM[chain][net].label;
351
+ }
352
+ else if (chain === 'sui') {
353
+ uri = address;
354
+ label = SUI[net].label;
355
+ }
356
+ else if (chain === 'solana') {
357
+ uri = `solana:${address}`;
358
+ label = net === 'mainnet' ? 'Solana' : 'Solana devnet';
359
+ }
360
+ else {
361
+ uri = `bitcoin:${address}`;
362
+ label = net === 'mainnet' ? 'Bitcoin' : 'Bitcoin testnet';
363
+ }
364
+ const warning = chain === 'ethereum' || chain === 'base' || chain === 'arbitrum'
365
+ ? `Send only on ${label}. This 0x address also exists on the other EVM chains; a coin sent on another one lands there, not here.`
366
+ : `Send only on ${label}.`;
367
+ return { ok: true, chain, network: net, address, uri, label, accepts: RECEIVE_ASSETS[chain], warning };
368
+ }
369
+ // ─── request ──────────────────────────────────────────────────────────────────
370
+ /** wallet:invoice takes cents: USD or USDC, at most 2 decimals. Anything else is refused by name. */
371
+ export function invoiceCents(amount, asset) {
372
+ const a = asset.toUpperCase();
373
+ if (a !== 'USD' && a !== 'USDC')
374
+ return { ok: false, error: 'invoice_usd_only', message: `wallet:invoice prices in US dollars — request USD or USDC, not ${asset}. The payer chooses the coin on the link.` };
375
+ const units = parseAmount(amount, 2);
376
+ if (units === null)
377
+ return { ok: false, error: 'bad_amount', message: 'Amount must be above zero with at most 2 decimals.' };
378
+ if (units > 100000000n)
379
+ return { ok: false, error: 'bad_amount', message: 'Over $1,000,000 — refused here.' };
380
+ return { ok: true, cents: Number(units) };
381
+ }
382
+ const fail = (error, message, options) => ({ ok: false, error, message, ...(options ? { options } : {}) });
383
+ /** A bare asset → the one chain that holds it. Two → refused with the list; a failed read → refused (it might be a second). */
384
+ export async function pickChain(asset, from, net, f) {
385
+ const cands = candidateChains(asset).filter((c) => (familyOf(c) === 'evm' ? from.evm : from.sui));
386
+ const reads = await Promise.all(cands.map(async (c) => ({ chain: c, units: await readAsset(f, asset, c, net, (familyOf(c) === 'evm' ? from.evm : from.sui)) })));
387
+ const options = reads.map((r) => ({ chain: r.chain, balance: r.units === null ? null : formatUnits(r.units, DECIMALS[asset]) }));
388
+ const unread = reads.filter((r) => r.units === null);
389
+ if (unread.length)
390
+ return { ok: false, error: 'cannot_pick_chain', message: `Could not read ${asset} on ${unread.map((r) => r.chain).join(', ')}, so another chain may hold it too. Name it: ${asset}@<chain>.`, options };
391
+ const held = reads.filter((r) => (r.units ?? 0n) > 0n);
392
+ if (held.length === 0)
393
+ return { ok: false, error: 'not_held', message: `This wallet holds no ${asset} on ${net} (${cands.join(', ')}).`, options };
394
+ if (held.length > 1)
395
+ return { ok: false, error: 'ambiguous_chain', message: `${asset} is on ${held.length} chains: ${held.map((r) => `${r.chain} ${formatUnits(r.units, DECIMALS[asset])}`).join(', ')}. Name one: ${asset}@${held[0].chain}.`, options };
396
+ return { ok: true, chain: held[0].chain, choice: `${held[0].chain} — the only chain this wallet holds ${asset} on` };
397
+ }
398
+ /** Everything a send would sign, read and checked — nothing signed, nothing sent. */
399
+ export async function planSend(intent, deps) {
400
+ const parsed = parseAssetWord(intent.asset);
401
+ if (!parsed.ok)
402
+ return fail(parsed.error, parsed.message);
403
+ const asset = parsed.asset;
404
+ const amountUnits = parseAmount(intent.amount, DECIMALS[asset]);
405
+ if (amountUnits === null)
406
+ return fail('bad_amount', `"${intent.amount}" is not an amount of ${asset} (above zero, at most ${DECIMALS[asset]} decimals).`);
407
+ const f = deps.fetch;
408
+ const net = intent.net;
409
+ let chain, choice;
410
+ if (parsed.chain) {
411
+ chain = parsed.chain;
412
+ choice = `${chain} — named`;
413
+ }
414
+ else {
415
+ const p = await pickChain(asset, deps.from, net, f);
416
+ if (!p.ok)
417
+ return fail(p.error, p.message, p.options);
418
+ chain = p.chain;
419
+ choice = p.choice;
420
+ }
421
+ const family = familyOf(chain);
422
+ const from = family === 'evm' ? deps.from.evm : deps.from.sui;
423
+ if (!from)
424
+ return fail('no_from_address', `This wallet has no ${family} address registered — nothing to send from.`);
425
+ // The recipient: an address of the right shape, or a name resolved to one.
426
+ let to, toSource = 'typed';
427
+ const shape = addressShape(intent.to);
428
+ if (shape) {
429
+ if (shape !== family)
430
+ return fail('wrong_family', `${intent.to} is a ${shape === 'evm' ? '0x Ethereum' : 'Sui'} address, but ${asset} on ${chain} needs a ${family === 'evm' ? '0x Ethereum (40 hex)' : 'Sui (64 hex)'} address.`);
431
+ to = intent.to;
432
+ }
433
+ else if (/^0x/i.test(intent.to)) {
434
+ return fail('bad_address', `${intent.to} is not a whole address (EVM: 0x + 40 hex, Sui: 0x + 64 hex).`);
435
+ }
436
+ else {
437
+ if (!/^[A-Za-z0-9._:-]{1,128}$/.test(intent.to))
438
+ return fail('bad_recipient', 'A recipient is an address, a workspace slug or an agent id.');
439
+ const r = await deps.resolve(intent.to, family);
440
+ if (!r)
441
+ return fail('recipient_unresolved', `No ${family} address found for "${intent.to}". Send to an address instead.`);
442
+ if (addressShape(r.address) !== family)
443
+ return fail('recipient_malformed', `"${intent.to}" resolved to something that is not a ${family} address. Nothing was planned.`);
444
+ to = r.address;
445
+ toSource = r.source;
446
+ }
447
+ if (family === 'evm') {
448
+ if (/^0x0{40}$/.test(to))
449
+ return fail('bad_address', 'That is the zero address — anything sent there is burned.');
450
+ }
451
+ else if (/^0x0{64}$/.test(to))
452
+ return fail('bad_address', 'That is the zero address.');
453
+ if (to.toLowerCase() === from.toLowerCase())
454
+ return fail('to_self', 'The recipient is the sending address itself.');
455
+ if (chain === 'sui') {
456
+ const coinType = asset === 'SUI' ? SUI_NATIVE : SUI[net].usdc;
457
+ const [bal, gas] = await Promise.all([readSuiCoin(f, net, from, coinType), asset === 'SUI' ? Promise.resolve(null) : readSuiCoin(f, net, from, SUI_NATIVE)]);
458
+ if (bal === null || (asset !== 'SUI' && gas === null))
459
+ return fail('balance_unread', 'Could not read the balance on Sui — nothing was planned.');
460
+ if (amountUnits > bal)
461
+ return fail('insufficient', `That is more than this wallet holds: ${formatUnits(bal, DECIMALS[asset])} ${asset} on ${SUI[net].label}.`);
462
+ if (asset === 'SUI' && amountUnits === bal)
463
+ return fail('insufficient_for_gas', 'Leave some SUI for gas — send a little less.');
464
+ if (asset !== 'SUI' && gas === 0n)
465
+ return fail('insufficient_for_gas', 'No SUI to pay gas on Sui.');
466
+ return { ok: true, plan: { network: net, chain, chainLabel: SUI[net].label, asset, amount: intent.amount, amountUnits, from, to, toSource, choice, balanceUnits: bal, coinType, explorer: SUI[net].explorer } };
467
+ }
468
+ const n = EVM[chain][net];
469
+ try {
470
+ const cid = Number(hexNum(await evmRpc(f, n.rpc, 'eth_chainId', [])));
471
+ if (cid !== n.chainId)
472
+ return fail('wrong_chain_rpc', `The ${n.label} node answered chain id ${cid}, not ${n.chainId}. Nothing was planned.`);
473
+ const native = asset === 'ETH';
474
+ const data = native ? '0x' : erc20TransferData(to, amountUnits);
475
+ const txTo = native ? to : n.usdc;
476
+ const value = native ? amountUnits : 0n;
477
+ const [nonceHex, tipHex, block, ethBalHex, tokenBal] = await Promise.all([
478
+ evmRpc(f, n.rpc, 'eth_getTransactionCount', [from, 'pending']),
479
+ evmRpc(f, n.rpc, 'eth_maxPriorityFeePerGas', []),
480
+ post(f, n.rpc, { jsonrpc: '2.0', id: 1, method: 'eth_getBlockByNumber', params: ['latest', false] }),
481
+ evmRpc(f, n.rpc, 'eth_getBalance', [from, 'latest']),
482
+ native ? Promise.resolve(null) : readEvmAsset(f, chain, net, 'USDC', from),
483
+ ]);
484
+ const baseFee = hexNum(String(block.result?.baseFeePerGas ?? 'x'));
485
+ const tip = hexNum(tipHex);
486
+ const maxFeePerGas = baseFee * 2n + tip;
487
+ const ethBal = hexNum(ethBalHex);
488
+ const balanceUnits = native ? ethBal : tokenBal;
489
+ if (balanceUnits === null)
490
+ return fail('balance_unread', `Could not read USDC on ${n.label} — nothing was planned.`);
491
+ if (amountUnits > balanceUnits)
492
+ return fail('insufficient', `That is more than this wallet holds: ${formatUnits(balanceUnits, DECIMALS[asset])} ${asset} on ${n.label}.`);
493
+ // Estimated only once the balance covers it: a node reverts estimateGas for a transfer the sender cannot make.
494
+ const gasLimit = native ? 21000n : (hexNum(await evmRpc(f, n.rpc, 'eth_estimateGas', [{ from, to: txTo, value: '0x0', data }])) * 12n) / 10n;
495
+ const feeMax = gasLimit * maxFeePerGas;
496
+ if (native && amountUnits + feeMax > ethBal)
497
+ return fail('insufficient_for_fee', `Not enough left for the fee (up to ${formatUnits(feeMax, 18)} ETH). Send a little less.`);
498
+ if (!native && feeMax > ethBal)
499
+ return fail('insufficient_for_fee', `Not enough ETH on ${n.label} to pay the fee (up to ${formatUnits(feeMax, 18)} ETH).`);
500
+ return {
501
+ ok: true,
502
+ plan: {
503
+ network: net, chain, chainLabel: n.label, asset, amount: intent.amount, amountUnits, from, to, toSource, choice, balanceUnits,
504
+ tx: { chainId: n.chainId, nonce: hexNum(nonceHex), maxPriorityFeePerGas: tip, maxFeePerGas, gasLimit, to: txTo, value, data },
505
+ feeMaxUnits: feeMax, explorer: n.explorer,
506
+ },
507
+ };
508
+ }
509
+ catch (e) {
510
+ return fail('rpc_failed', `The ${n.label} node did not answer (${e instanceof Error ? e.message : 'read_failed'}) — nothing was planned.`);
511
+ }
512
+ }
513
+ /** ERC-20 transfer(address,uint256) — the same bytes as @oneie/sdk/evm-tx encodeErc20Transfer, kept here so a dry run needs no SDK upgrade. */
514
+ export function erc20TransferData(to, amount) {
515
+ return `0xa9059cbb${padAddr(to)}${amount.toString(16).padStart(64, '0')}`;
516
+ }
517
+ /**
518
+ * R16 — before a key signs, rebuild what the transaction MUST be from the person's own inputs
519
+ * (argv, and the address they confirmed), never from a server answer or the plan's echo, and
520
+ * compare. Any difference refuses.
521
+ */
522
+ export function clientCheck(plan, own) {
523
+ const units = parseAmount(own.amount, DECIMALS[own.asset]);
524
+ if (units === null || units !== plan.amountUnits)
525
+ return { ok: false, field: 'amount' };
526
+ if (plan.asset !== own.asset)
527
+ return { ok: false, field: 'asset' };
528
+ if (plan.chain !== own.chain)
529
+ return { ok: false, field: 'chain' };
530
+ if (plan.network !== own.net)
531
+ return { ok: false, field: 'network' };
532
+ if (plan.to.toLowerCase() !== own.to.toLowerCase())
533
+ return { ok: false, field: 'recipient' };
534
+ if (own.chain === 'sui') {
535
+ const coin = own.asset === 'SUI' ? SUI_NATIVE : SUI[own.net].usdc;
536
+ return plan.coinType === coin ? { ok: true } : { ok: false, field: 'coinType' };
537
+ }
538
+ const n = EVM[own.chain][own.net];
539
+ const tx = plan.tx;
540
+ if (!tx)
541
+ return { ok: false, field: 'tx' };
542
+ if (tx.chainId !== n.chainId)
543
+ return { ok: false, field: 'chainId' };
544
+ const native = own.asset === 'ETH';
545
+ if (tx.to.toLowerCase() !== (native ? own.to : n.usdc).toLowerCase())
546
+ return { ok: false, field: 'tx.to' };
547
+ if (tx.value !== (native ? units : 0n))
548
+ return { ok: false, field: 'tx.value' };
549
+ if (tx.data.toLowerCase() !== (native ? '0x' : erc20TransferData(own.to, units)).toLowerCase())
550
+ return { ok: false, field: 'tx.data' };
551
+ return { ok: true };
552
+ }
553
+ /** What a person reads before anything is signed. */
554
+ export function planLines(p) {
555
+ const lines = [
556
+ `network ${p.network}${p.network === 'mainnet' ? ' — REAL MONEY' : ' — practice money'}`,
557
+ `chain ${p.chainLabel} (${p.choice})`,
558
+ `send ${p.amount} ${p.asset} (${p.amountUnits} base units; you hold ${formatUnits(p.balanceUnits, DECIMALS[p.asset])})`,
559
+ `from ${p.from}`,
560
+ `to ${p.to}${p.toSource === 'typed' ? '' : ` ← resolved by ${p.toSource}; check it`}`,
561
+ ];
562
+ if (p.tx) {
563
+ lines.push(`tx type 2 · chainId ${p.tx.chainId} · nonce ${p.tx.nonce}`, ` to ${p.tx.to}${p.asset === 'USDC' ? ' (the USDC contract)' : ''}`, ` value ${p.tx.value} wei · data ${p.tx.data.length > 20 ? `${p.tx.data.slice(0, 10)}… (transfer to ${p.to}, ${p.amountUnits})` : p.tx.data}`, ` gas ${p.tx.gasLimit} · maxFee ${p.tx.maxFeePerGas} wei · tip ${p.tx.maxPriorityFeePerGas} wei`, `fee at most ${formatUnits(p.feeMaxUnits ?? 0n, 18)} ETH`);
564
+ }
565
+ else {
566
+ lines.push(`coin ${p.coinType}`, 'fee the Sui gas budget is set at signing (a few thousandths of a SUI)');
567
+ }
568
+ return lines;
569
+ }
570
+ /** A plan as JSON-safe values (bigints as decimal strings). */
571
+ export function planJson(p) {
572
+ return JSON.parse(JSON.stringify(p, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)));
573
+ }
574
+ /** The `wallet send … --payment-tx` line that records a broadcast transfer in ONE's ledger. */
575
+ export function recordLine(p, hash, cli) {
576
+ const chain = p.chain === 'sui' ? 'SUI' : p.chain === 'ethereum' ? 'ETH' : p.chain === 'base' ? 'BASE' : 'ARB';
577
+ return `${cli} wallet send ${p.to} --chain ${chain} --amount ${p.amount} --unit token --currency ${p.asset === 'USDC' ? 'USDC' : 'NATIVE'} --payment-tx ${hash}`;
578
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * wallet-request.ts — the agent's half of "an agent asks, the owner's fingerprint decides".
3
+ *
4
+ * The agent builds a SENTENCE the owner's own chat already understands and wraps it in a link:
5
+ * `https://one.ie/chat#money=<sentence>`. Opening it types the sentence as the owner's line and
6
+ * shows the send card they sign with Touch ID. Nothing here signs, holds or opens a key; it only
7
+ * names the agent's own PUBLIC receiving address.
8
+ *
9
+ * The grammar is MIRRORED from one.ie/web/src/lib/chat/money-intent.ts (SEND, amountOk,
10
+ * chainsFor, moneyLink) — copied, never imported: the CLI ships alone. If the web's send pattern
11
+ * moves, tests/wallet-request.test.ts is the place that says so.
12
+ */
13
+ import { type Net, type SendAsset } from './wallet-money.js';
14
+ /** What the web grammar accepts: USDC and SUI on Sui, ETH and USDC on Ethereum and Base. */
15
+ export type RequestChain = 'ethereum' | 'base' | 'sui';
16
+ export type RequestAsset = {
17
+ ok: true;
18
+ asset: SendAsset;
19
+ chain: RequestChain;
20
+ defaulted: boolean;
21
+ } | {
22
+ ok: false;
23
+ error: string;
24
+ message: string;
25
+ };
26
+ /** `USDC` · `SUI` · `ETH@base` · `USDC@ethereum` — anything the web grammar would not read is refused by name. */
27
+ export declare function parseRequestAsset(word: string): RequestAsset;
28
+ /** The web's amountOk: a positive plain decimal, at most 18 places. */
29
+ export declare const amountOk: (a: string) => boolean;
30
+ /** `send 20 USDC on sui to 0x…` — the chain is always said, so the card never has to ask which. */
31
+ export declare const sentenceFor: (amount: string, asset: SendAsset, chain: RequestChain, to: string) => string;
32
+ /** The web's moneyLink: the sentence is capped at 200 characters. */
33
+ export declare const linkFor: (sentence: string, origin?: string) => string;
34
+ /** What the web's `matchMoneyIntent` would make of this sentence, as far as a send goes — or null. */
35
+ export declare function matchSend(text: string): {
36
+ amount: string;
37
+ symbol: SendAsset;
38
+ chain: 'eth' | 'base' | 'sui' | null;
39
+ to: string;
40
+ } | null;
41
+ export declare const shortAddr: (a: string) => string;
42
+ /** The latest transaction that touched `address` on Sui — what an arrival most likely is. Null when it cannot be read. */
43
+ export declare function latestSuiDigest(f: (url: string, init?: {
44
+ method?: string;
45
+ headers?: Record<string, string>;
46
+ body?: string;
47
+ }) => Promise<{
48
+ ok: boolean;
49
+ json: () => Promise<unknown>;
50
+ }>, net: Net, address: string): Promise<string | null>;