oneie 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.
- package/README.md +15 -0
- package/dist/package.json +5 -2
- package/dist/src/balances.d.ts +89 -0
- package/dist/src/balances.js +202 -0
- package/dist/src/hl-run.d.ts +119 -0
- package/dist/src/hl-run.js +480 -0
- package/dist/src/hl.d.ts +17 -0
- package/dist/src/hl.js +148 -0
- package/dist/src/index.js +4 -0
- package/dist/src/key-sweep.d.ts +19 -3
- package/dist/src/key-sweep.js +63 -20
- package/dist/src/lib/hl-core/actions.d.ts +99 -0
- package/dist/src/lib/hl-core/actions.js +69 -0
- package/dist/src/lib/hl-core/eip712.d.ts +33 -0
- package/dist/src/lib/hl-core/eip712.js +107 -0
- package/dist/src/lib/hl-core/errors.d.ts +10 -0
- package/dist/src/lib/hl-core/errors.js +15 -0
- package/dist/src/lib/hl-core/exchange.d.ts +24 -0
- package/dist/src/lib/hl-core/exchange.js +47 -0
- package/dist/src/lib/hl-core/index.d.ts +13 -0
- package/dist/src/lib/hl-core/index.js +14 -0
- package/dist/src/lib/hl-core/meta.d.ts +57 -0
- package/dist/src/lib/hl-core/meta.js +110 -0
- package/dist/src/lib/hl-core/msgpack.d.ts +18 -0
- package/dist/src/lib/hl-core/msgpack.js +136 -0
- package/dist/src/lib/hl-core/net.d.ts +2 -0
- package/dist/src/lib/hl-core/net.js +7 -0
- package/dist/src/lib/hl-core/signing.d.ts +103 -0
- package/dist/src/lib/hl-core/signing.js +295 -0
- package/dist/src/lib/hl-core/wire.d.ts +34 -0
- package/dist/src/lib/hl-core/wire.js +81 -0
- package/dist/src/lib/journey-words.d.ts +54 -3
- package/dist/src/lib/journey-words.js +159 -20
- package/dist/src/lib/journey.js +1 -1
- package/dist/src/lib/key-source.d.ts +9 -0
- package/dist/src/lib/key-source.js +33 -0
- package/dist/src/lib/network.d.ts +15 -0
- package/dist/src/lib/network.js +41 -0
- package/dist/src/lib/qr.d.ts +21 -0
- package/dist/src/lib/qr.js +402 -0
- package/dist/src/lib/sale-card.d.ts +117 -0
- package/dist/src/lib/sale-card.js +261 -0
- package/dist/src/lib/sui-grpc-send.d.ts +50 -0
- package/dist/src/lib/sui-grpc-send.js +89 -0
- package/dist/src/lib/swap-core.d.ts +163 -0
- package/dist/src/lib/swap-core.js +405 -0
- package/dist/src/lib/wallet-money.d.ts +222 -0
- package/dist/src/lib/wallet-money.js +578 -0
- package/dist/src/lib/wallet-request.d.ts +50 -0
- package/dist/src/lib/wallet-request.js +86 -0
- package/dist/src/onboard.js +4 -3
- package/dist/src/shop.js +38 -1
- package/dist/src/staff.js +10 -0
- package/dist/src/start.js +14 -6
- package/dist/src/swap.d.ts +93 -0
- package/dist/src/swap.js +622 -0
- package/dist/src/wallet-money.d.ts +152 -0
- package/dist/src/wallet-money.js +564 -0
- package/dist/src/wallet.js +169 -24
- package/package.json +5 -2
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* wallet-money.ts — the loaded wallet's money, one command away:
|
|
3
|
+
*
|
|
4
|
+
* one wallet balances [--net mainnet|testnet] every chain, wallet:get first, chains for the rest
|
|
5
|
+
* one wallet receive --chain base one address, one QR, never ambiguous
|
|
6
|
+
* one wallet send 1 USDC@base 0x… DRY: exactly what would be signed, fees, the chain
|
|
7
|
+
* one wallet send 0.0004 ETH@ethereum 0x… --live --dir ~/.one/tony
|
|
8
|
+
* one wallet request 25 USD a wallet:invoice payment link
|
|
9
|
+
* one wallet request 5 USDC --wait a link the owner opens and signs with Touch ID
|
|
10
|
+
*
|
|
11
|
+
* THE SERVER SIGNS NOTHING (R19). A --live send opens the sealed vault in --dir on THIS
|
|
12
|
+
* machine (Touch ID or a typed passphrase), signs here, broadcasts to a public node, and
|
|
13
|
+
* drops the key. Before the key opens: the gate (an agent shell signs only with its OWN
|
|
14
|
+
* vault and --yes), and the client check (R16) — the transaction is rebuilt from the
|
|
15
|
+
* person's own words and compared, never trusted from an echo.
|
|
16
|
+
*
|
|
17
|
+
* `balances` is the dev session's command (src/balances.ts, kept byte-identical so the two
|
|
18
|
+
* merge cleanly); `upgradeBalances` adds --net and the wallet:get fan-out to it in place.
|
|
19
|
+
*/
|
|
20
|
+
import { Command } from 'commander';
|
|
21
|
+
import { createInterface } from 'node:readline';
|
|
22
|
+
import { suiAddressFromPubkey } from '@oneie/sdk/wallet';
|
|
23
|
+
import { readHyperliquid, readBalances, balanceLines, isEvmAddress, isSuiAddress } from './balances.js';
|
|
24
|
+
import { agentType } from './lib/agent-env.js';
|
|
25
|
+
import { cliPrefix } from './lib/invoked-as.js';
|
|
26
|
+
import { qrTerminal } from './lib/qr.js';
|
|
27
|
+
import { spawnSync } from 'node:child_process';
|
|
28
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
29
|
+
import { join } from 'node:path';
|
|
30
|
+
import { amountOk, latestSuiDigest, linkFor, parseRequestAsset, sentenceFor, shortAddr } from './lib/wallet-request.js';
|
|
31
|
+
import { suiSendGrpc, SuiSendError, mistToSui } from './lib/sui-grpc-send.js';
|
|
32
|
+
import { readVaultFolder, vaultPath } from './lib/vaultfile.js';
|
|
33
|
+
import { addressesFor, addressShape, chainLabel, clientCheck, DECIMALS, EVM, evmRpc, invoiceCents, parseAmount, readAsset, moneyBalances, moneyLines, parseAssetWord, parseNet, planJson, planLines, planSend, receivePlan, recordLine, SUI_NATIVE, } from './lib/wallet-money.js';
|
|
34
|
+
/** fetch with a deadline: a node that hangs is a failed read, not a hung CLI. */
|
|
35
|
+
export const deadlineFetch = (ms = 10_000) => async (url, init) => {
|
|
36
|
+
const ctl = new AbortController();
|
|
37
|
+
const t = setTimeout(() => ctl.abort(), ms);
|
|
38
|
+
try {
|
|
39
|
+
const r = await fetch(url, { ...init, signal: ctl.signal });
|
|
40
|
+
return { ok: r.ok, json: () => r.json() };
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
clearTimeout(t);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
/** A word safe to paste into a shell: plain words as they are, anything else single-quoted. */
|
|
47
|
+
export const shq = (w) => (/^[A-Za-z0-9@._:\/=-]+$/.test(w) ? w : `'${w.replace(/'/g, `'\\''`)}'`);
|
|
48
|
+
const isJson = (c) => Boolean(c.optsWithGlobals().json);
|
|
49
|
+
function emit(c, data, lines) {
|
|
50
|
+
if (data['ok'] === false)
|
|
51
|
+
process.exitCode = 1;
|
|
52
|
+
if (isJson(c)) {
|
|
53
|
+
process.stdout.write(JSON.stringify(data) + '\n');
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (data['ok'] === false) {
|
|
57
|
+
process.stderr.write(`✗ ${String(data['error'] ?? 'failed')}: ${String(data['message'] ?? '')}\n`);
|
|
58
|
+
if (lines?.length)
|
|
59
|
+
process.stderr.write(lines.join('\n') + '\n');
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (lines)
|
|
63
|
+
console.log(lines.join('\n'));
|
|
64
|
+
else
|
|
65
|
+
console.log('✓', Object.entries(data).filter(([k]) => k !== 'ok').map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(' '));
|
|
66
|
+
}
|
|
67
|
+
async function confirm(prompt) {
|
|
68
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
69
|
+
try {
|
|
70
|
+
const a = await new Promise((r) => rl.question(prompt, r));
|
|
71
|
+
return /^y(es)?$/i.test(a.trim());
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
rl.close();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Is the vault in `dir` an AGENT's own? Its Sui address (from the public authPub, no unlock)
|
|
79
|
+
* must be the attested caller's registered address on a wallet row tagged `agent`, and the
|
|
80
|
+
* sending address must be on that same row. Read from the server by the caller's own key.
|
|
81
|
+
*/
|
|
82
|
+
async function agentOwnVault(a, d) {
|
|
83
|
+
const vaultSui = d.vaultSuiAddress(a.dir);
|
|
84
|
+
if (!vaultSui)
|
|
85
|
+
return { ok: false, error: 'no_vault', message: `No sealed wallet at ${vaultPath(a.dir)}.` };
|
|
86
|
+
let me, w;
|
|
87
|
+
try {
|
|
88
|
+
me = await d.ask('wallet:challenge', {});
|
|
89
|
+
// An agent's row sits in its owner's workspace (--workspace), not in the agent's own: ask
|
|
90
|
+
// for this caller's own row there; wallet:get answers an agent key that one row and no other.
|
|
91
|
+
w = await d.ask('wallet:get', { workspace: a.workspace ?? String(me['workspace'] ?? ''), actor: String(me['actor'] ?? '') });
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
return { ok: false, error: 'caller_unread', message: `Could not read who this key is (${e instanceof Error ? e.message : 'failed'}). Nothing was opened.` };
|
|
95
|
+
}
|
|
96
|
+
const rows = Array.isArray(w['wallets']) ? w['wallets'] : [];
|
|
97
|
+
const row = rows.find((r) => r['actor'] === me['actor']);
|
|
98
|
+
const tags = Array.isArray(row?.['tags']) ? row['tags'].map(String) : [];
|
|
99
|
+
const same = (x, y) => typeof x === 'string' && x.toLowerCase() === y.toLowerCase();
|
|
100
|
+
if (!row || !tags.includes('agent') || !same(row['sui_address'], vaultSui)) {
|
|
101
|
+
return { ok: false, error: 'not_the_agents_vault', message: `The vault in ${a.dir} is not the agent's own (${String(me['actor'] ?? '?')}).` };
|
|
102
|
+
}
|
|
103
|
+
if (!same(row['evm_address'], a.plan.from) && !same(row['sui_address'], a.plan.from)) {
|
|
104
|
+
return { ok: false, error: 'not_the_agents_money', message: `${a.plan.from} is not on this agent's wallet row. Nothing was opened.` };
|
|
105
|
+
}
|
|
106
|
+
return { ok: true };
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Before any key opens. `--yes` skips the prompt ONLY for a vault proven to be an agent's
|
|
110
|
+
* own (agentOwnVault) — never on an env marker alone, which a shell can simply not set, and
|
|
111
|
+
* never for a person's vault: the Keychain read behind "Touch ID" is `security -w`, which
|
|
112
|
+
* the OS may answer silently. A person's vault is opened only after a y/N typed at a terminal,
|
|
113
|
+
* every time. A shell an agent drives never opens anything but its own vault. A recipient
|
|
114
|
+
* found by name must be pinned with --to-address whenever nobody reads it at a prompt.
|
|
115
|
+
*/
|
|
116
|
+
export async function liveGate(a, d) {
|
|
117
|
+
const p = a.plan;
|
|
118
|
+
const resolved = p.toSource !== 'typed';
|
|
119
|
+
if (resolved && a.toAddress !== undefined && a.toAddress.toLowerCase() !== p.to.toLowerCase()) {
|
|
120
|
+
return { ok: false, error: 'recipient_mismatch', message: `--to-address ${a.toAddress} is not the resolved ${p.to}. Nothing was signed.` };
|
|
121
|
+
}
|
|
122
|
+
const agent = agentType(a.env);
|
|
123
|
+
if (agent && !a.yes)
|
|
124
|
+
return { ok: false, error: 'agent_needs_yes', message: `This shell is driven by ${agent}. An agent signs only with its own vault, and only with --yes. Nothing was opened.` };
|
|
125
|
+
if (a.yes) {
|
|
126
|
+
if (resolved && a.toAddress === undefined)
|
|
127
|
+
return { ok: false, error: 'pin_recipient', message: `The recipient was resolved by ${p.toSource}: with --yes, pass --to-address ${p.to} to pin it. Nothing was opened.` };
|
|
128
|
+
const own = await agentOwnVault(a, d);
|
|
129
|
+
if (own.ok)
|
|
130
|
+
return own;
|
|
131
|
+
if (agent || !a.interactive) {
|
|
132
|
+
return { ok: false, error: own.error, message: `${own.message} --yes signs only with an agent's own vault; a person's vault needs a y/N typed at a terminal. Nothing was opened.` };
|
|
133
|
+
}
|
|
134
|
+
// A person at a terminal who typed --yes: --yes does not cover a person's vault — ask.
|
|
135
|
+
}
|
|
136
|
+
if (!a.interactive)
|
|
137
|
+
return { ok: false, error: 'confirm_needed', message: 'A person\'s vault opens only after a y/N typed at a terminal. Run it yourself, in a terminal. Nothing was opened.' };
|
|
138
|
+
const ok = await d.confirm(`Sign and send ${p.amount} ${p.asset} on ${p.chainLabel} to ${p.to}${resolved ? ` (found by ${p.toSource})` : ''}? [y/N] `);
|
|
139
|
+
return ok ? { ok: true } : { ok: false, error: 'cancelled', message: 'Nothing was signed.' };
|
|
140
|
+
}
|
|
141
|
+
const loadEvmDefault = async () => {
|
|
142
|
+
try {
|
|
143
|
+
return (await import('@oneie/sdk/evm-tx'));
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
throw new Error('evm_signer_unavailable: this @oneie/sdk has no evm-tx — update oneie');
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
export const suiSendDefault = (r) => suiSendGrpc(r);
|
|
150
|
+
/**
|
|
151
|
+
* Sign and broadcast ONE plan. The client check runs first, against the person's own
|
|
152
|
+
* words; then the vault opens; then its key must derive `from`. One broadcast, never
|
|
153
|
+
* re-sent: on a failure after signing the locally computed hash is returned so the
|
|
154
|
+
* person can look before trying again.
|
|
155
|
+
*/
|
|
156
|
+
export async function executeSend(plan, own, d) {
|
|
157
|
+
const check = clientCheck(plan, own);
|
|
158
|
+
if (!check.ok)
|
|
159
|
+
return { ok: false, error: 'client_check_failed', field: check.field, message: `The transaction does not match what you typed (${check.field}). Nothing was signed.` };
|
|
160
|
+
let evm;
|
|
161
|
+
if (plan.tx) {
|
|
162
|
+
try {
|
|
163
|
+
evm = await (d.loadEvm ?? loadEvmDefault)();
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
return { ok: false, error: 'evm_signer_unavailable', message: e.message };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const opened = await d.unlock();
|
|
170
|
+
if ('error' in opened)
|
|
171
|
+
return { ok: false, error: 'vault_locked', message: opened.error };
|
|
172
|
+
const want = plan.chain === 'sui' ? 'sui' : 'evm';
|
|
173
|
+
const key = opened.keys.find((k) => k.chain === want && k.address.toLowerCase() === plan.from.toLowerCase());
|
|
174
|
+
if (!key)
|
|
175
|
+
return { ok: false, error: 'vault_not_sender', message: `This vault does not hold ${plan.from}. Open the vault that does (--dir). Nothing was signed.` };
|
|
176
|
+
if (plan.chain === 'sui') {
|
|
177
|
+
try {
|
|
178
|
+
const done = await (d.suiSend ?? suiSendDefault)({ asset: plan.asset, coinType: plan.coinType ?? SUI_NATIVE, from: plan.from, to: plan.to, amountUnits: plan.amountUnits, privateKeyHex: key.privateKeyHex, rpc: own.suiRpc, net: plan.network });
|
|
179
|
+
const { digest, gasMist, finalMs } = typeof done === 'string' ? { digest: done, gasMist: undefined, finalMs: undefined } : done;
|
|
180
|
+
return {
|
|
181
|
+
ok: true, sent: true, chain: 'sui', network: plan.network, digest, explorer: `${plan.explorer}/tx/${digest}`,
|
|
182
|
+
...(gasMist !== undefined ? { gasSui: mistToSui(gasMist) } : {}), ...(finalMs !== undefined ? { finalMs } : {}),
|
|
183
|
+
next: recordLine(plan, digest, cliPrefix()),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
const code = e instanceof SuiSendError ? e.code : 'sui_send_failed';
|
|
188
|
+
const dg = e instanceof SuiSendError ? e.digest : undefined;
|
|
189
|
+
return { ok: false, error: code, ...(dg ? { digest: dg, explorer: `${plan.explorer}/tx/${dg}` } : {}), message: `${e.message}. Check ${dg ? `${plan.explorer}/tx/${dg}` : `${plan.explorer}/account/${plan.from}`} before trying again. Nothing was re-sent.` };
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const n = EVM[plan.chain][plan.network];
|
|
193
|
+
const keyBytes = evm.hexToBytes(key.privateKeyHex.replace(/^0x/, ''));
|
|
194
|
+
try {
|
|
195
|
+
if (evm.evmAddressFromKey(keyBytes).toLowerCase() !== plan.from.toLowerCase())
|
|
196
|
+
return { ok: false, error: 'vault_not_sender', message: 'The vault key does not derive the sending address. Nothing was signed.' };
|
|
197
|
+
const cid = Number(BigInt(await evmRpc(d.fetch, n.rpc, 'eth_chainId', [])));
|
|
198
|
+
if (cid !== plan.tx.chainId)
|
|
199
|
+
return { ok: false, error: 'wrong_chain_rpc', message: `The node answered chain id ${cid}, not ${plan.tx.chainId}. Nothing was signed.` };
|
|
200
|
+
const raw = evm.signEip1559(plan.tx, keyBytes);
|
|
201
|
+
const hash = evm.evmTxHash(raw);
|
|
202
|
+
const explorer = `${n.explorer}/tx/${hash}`;
|
|
203
|
+
let answered;
|
|
204
|
+
try {
|
|
205
|
+
answered = await evmRpc(d.fetch, n.rpc, 'eth_sendRawTransaction', [raw]);
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
return { ok: false, error: 'broadcast_unconfirmed', hash, explorer, message: `The node did not accept it cleanly (${e.message}). It may still land — look at ${explorer} before trying again. Nothing was re-sent.` };
|
|
209
|
+
}
|
|
210
|
+
if (answered.toLowerCase() !== hash.toLowerCase())
|
|
211
|
+
return { ok: false, error: 'hash_mismatch', hash, answered, explorer, message: 'The node reported a different hash than the one signed. Look at both before doing anything else.' };
|
|
212
|
+
let status = 'pending';
|
|
213
|
+
const sleep = d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
214
|
+
for (let i = 0; i < (d.polls ?? 24); i++) {
|
|
215
|
+
await sleep(5000);
|
|
216
|
+
try {
|
|
217
|
+
const r = (await (await d.fetch(n.rpc, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getTransactionReceipt', params: [hash] }) })).json());
|
|
218
|
+
if (r.result?.status) {
|
|
219
|
+
status = r.result.status === '0x1' ? 'mined' : 'reverted';
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
catch { /* a missed poll is not a result */ }
|
|
224
|
+
}
|
|
225
|
+
return { ok: status !== 'reverted', sent: true, status, chain: plan.chain, network: plan.network, hash, explorer, ...(status === 'reverted' ? { error: 'reverted', message: 'Mined, but the transaction reverted.' } : {}), next: recordLine(plan, hash, cliPrefix()) };
|
|
226
|
+
}
|
|
227
|
+
finally {
|
|
228
|
+
keyBytes.fill(0);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
export const actingLine = (w) => (w ? `acting as: ${w.actor ?? 'unknown (the key could not be read)'} · key from ${w.from}` : undefined);
|
|
232
|
+
/**
|
|
233
|
+
* `no_from_address` from a folder-local key that is NOT the global login is the folder changing the
|
|
234
|
+
* answer: name both, and the way out. Any other refusal keeps its own words.
|
|
235
|
+
*/
|
|
236
|
+
export async function noFromCause(io, o, me, family, workspace) {
|
|
237
|
+
if (!me?.local || !io.identity)
|
|
238
|
+
return undefined;
|
|
239
|
+
const global = await io.identity(o, 'machine').catch(() => null);
|
|
240
|
+
if (!global || global.actor === me.actor)
|
|
241
|
+
return undefined;
|
|
242
|
+
return `this folder's key (${me.from}) acts as ${me.actor ?? 'an actor that could not be read'}, which has no ${family} address in workspace ${workspace}; the global login acts as ${global.actor ?? 'another actor'}. Run from another folder or pass --key.`;
|
|
243
|
+
}
|
|
244
|
+
function common(c, defaultApi) {
|
|
245
|
+
return c
|
|
246
|
+
.option('--workspace <slug>', 'Workspace (defaults to AGENCY_SLUG)')
|
|
247
|
+
.option('--actor <id>', 'Actor within the workspace (defaults to workspace)')
|
|
248
|
+
.option('--api <url>', 'API base URL', defaultApi)
|
|
249
|
+
.option('--key <key>', 'API key (overrides ONEIE_API_KEY env)');
|
|
250
|
+
}
|
|
251
|
+
const netOf = (raw) => (raw === undefined ? 'mainnet' : parseNet(raw));
|
|
252
|
+
const BAD_NET = { ok: false, error: 'bad_net', message: '--net must be mainnet or testnet' };
|
|
253
|
+
/** The loaded wallet: wallet:get for the workspace (and actor), reduced to its addresses. */
|
|
254
|
+
async function loaded(io, o, net, self) {
|
|
255
|
+
const workspace = io.workspace(o.workspace);
|
|
256
|
+
const who = o.actor ?? workspace;
|
|
257
|
+
const walletGet = await io.ask(o, 'wallet:get', { workspace, ...(o.actor ? { actor: o.actor } : {}), ...(net ? { net } : {}) });
|
|
258
|
+
// An agent key does not control its owner's workspace, only itself: read its own row there.
|
|
259
|
+
if (walletGet['error'] === 'forbidden' && !o.actor && self) {
|
|
260
|
+
const own = await io.ask(o, 'wallet:get', { workspace, actor: self, ...(net ? { net } : {}) });
|
|
261
|
+
if (!own['error'])
|
|
262
|
+
return { who: self, walletGet: own, addresses: addressesFor(own, self) };
|
|
263
|
+
}
|
|
264
|
+
return { who, walletGet, addresses: addressesFor(walletGet, who) };
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Give the dev session's `balances` (src/balances.ts) the network word and the server
|
|
268
|
+
* fan-out. Its explicit-address form on mainnet is left to its own reader, unchanged.
|
|
269
|
+
*/
|
|
270
|
+
export function upgradeBalances(balances, io) {
|
|
271
|
+
// Guarded: commander throws on a duplicate flag at startup, which would take every `one` command down.
|
|
272
|
+
if (!balances.options.some((x) => x.long === '--net'))
|
|
273
|
+
balances.option('--net <network>', 'mainnet (default — real money) | testnet');
|
|
274
|
+
balances
|
|
275
|
+
.description('Every balance of your wallet on one network: ETH + USDC on Ethereum, Base, Arbitrum; SUI + USDC; SOL; BTC; Hyperliquid perps and spot. wallet:get first, the chains for what it does not read. A failed read says unavailable, never 0')
|
|
276
|
+
.action(async function (address, o) {
|
|
277
|
+
const f = io.fetch ?? deadlineFetch();
|
|
278
|
+
const net = netOf(o.net);
|
|
279
|
+
if (!net)
|
|
280
|
+
return emit(this, BAD_NET);
|
|
281
|
+
if (address) {
|
|
282
|
+
const a = address.trim();
|
|
283
|
+
if (!isEvmAddress(a) && !isSuiAddress(a))
|
|
284
|
+
return emit(this, { ok: false, error: 'bad_address', message: 'Pass a 0x EVM address (40 hex) or a Sui address (64 hex).' });
|
|
285
|
+
const addrs = isEvmAddress(a) ? { evm: a } : { sui: a };
|
|
286
|
+
if (net === 'mainnet') {
|
|
287
|
+
const r = await readBalances(addrs, f);
|
|
288
|
+
return emit(this, { ...r, addresses: addrs }, balanceLines(r, addrs));
|
|
289
|
+
}
|
|
290
|
+
const r = await moneyBalances({ walletGet: null, actor: '', addresses: addrs, net }, f);
|
|
291
|
+
return emit(this, { ...r }, moneyLines(r));
|
|
292
|
+
}
|
|
293
|
+
let l;
|
|
294
|
+
try {
|
|
295
|
+
l = await loaded(io, o, net);
|
|
296
|
+
}
|
|
297
|
+
catch (e) {
|
|
298
|
+
return emit(this, { ok: false, error: 'wallet_read_failed', message: `${e.message} — or pass an address: one wallet balances 0x…` });
|
|
299
|
+
}
|
|
300
|
+
if (!Object.keys(l.addresses).length)
|
|
301
|
+
return emit(this, { ok: false, error: 'no_address', message: `${l.who} has no wallet address registered. Pass one: one wallet balances 0x…` });
|
|
302
|
+
const hl = net === 'mainnet' ? (a) => readHyperliquid(a, f) : undefined;
|
|
303
|
+
const r = await moneyBalances({ walletGet: l.walletGet, actor: l.who, addresses: l.addresses, net }, f, hl);
|
|
304
|
+
emit(this, { ...r }, moneyLines(r));
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
export function receiveCmd(io) {
|
|
308
|
+
return common(new Command('receive'), io.defaultApi)
|
|
309
|
+
.description('Your address on ONE chain, with a QR to scan — the same 0x address is three chains, so --chain is required')
|
|
310
|
+
.option('--chain <chain>', 'ethereum | base | arbitrum | sui | solana | bitcoin')
|
|
311
|
+
.option('--net <network>', 'mainnet (default) | testnet — sets the chain id in the QR')
|
|
312
|
+
.option('--no-qr', 'Print the address only')
|
|
313
|
+
.action(async function (o) {
|
|
314
|
+
const net = netOf(o.net);
|
|
315
|
+
if (!net)
|
|
316
|
+
return emit(this, BAD_NET);
|
|
317
|
+
let l;
|
|
318
|
+
try {
|
|
319
|
+
l = await loaded(io, o);
|
|
320
|
+
}
|
|
321
|
+
catch (e) {
|
|
322
|
+
return emit(this, { ok: false, error: 'wallet_read_failed', message: e.message });
|
|
323
|
+
}
|
|
324
|
+
const r = receivePlan(o.chain, l.addresses, net);
|
|
325
|
+
if (!r.ok)
|
|
326
|
+
return emit(this, { ...r });
|
|
327
|
+
const lines = [`${r.label} (${net}) — receives ${r.accepts}`, r.address, ...(o.qr ? ['', qrTerminal(r.uri), ` ${r.uri}`, ''] : []), r.warning];
|
|
328
|
+
emit(this, { ...r, actor: l.who }, lines);
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/** The agent's own PUBLIC addresses: authPub gives Sui with no unlock; `addresses.json` beside the vault gives the rest. Never opens a key. */
|
|
332
|
+
function publicAddresses(dir) {
|
|
333
|
+
const out = {};
|
|
334
|
+
const p = join(dir, 'addresses.json');
|
|
335
|
+
try {
|
|
336
|
+
if (existsSync(p)) {
|
|
337
|
+
const j = JSON.parse(readFileSync(p, 'utf8'));
|
|
338
|
+
if (typeof j.agent === 'string')
|
|
339
|
+
out.agent = j.agent;
|
|
340
|
+
if (typeof j.addresses?.['sui'] === 'string' && addressShape(j.addresses['sui']) === 'sui')
|
|
341
|
+
out.sui = j.addresses['sui'];
|
|
342
|
+
if (typeof j.addresses?.['evm'] === 'string' && addressShape(j.addresses['evm']) === 'evm')
|
|
343
|
+
out.evm = j.addresses['evm'];
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
catch { /* a sidecar that does not parse is no sidecar */ }
|
|
347
|
+
const fromVault = vaultSuiAddressOf(dir);
|
|
348
|
+
if (fromVault)
|
|
349
|
+
out.sui = fromVault;
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
/** `request <amount> <asset>[@chain]`: a link the OWNER opens, and a fingerprint only they can give. */
|
|
353
|
+
async function requestMoney(c, io, amount, assetWord, o) {
|
|
354
|
+
const a = parseRequestAsset(assetWord);
|
|
355
|
+
if (!a.ok)
|
|
356
|
+
return emit(c, { ...a });
|
|
357
|
+
const units = amountOk(amount) ? parseAmount(amount, DECIMALS[a.asset]) : null;
|
|
358
|
+
if (units === null)
|
|
359
|
+
return emit(c, { ok: false, error: 'bad_amount', message: `"${amount}" is not an amount of ${a.asset} (above zero, at most ${DECIMALS[a.asset]} decimals).` });
|
|
360
|
+
const net = netOf(o.net);
|
|
361
|
+
if (!net)
|
|
362
|
+
return emit(c, BAD_NET);
|
|
363
|
+
let seconds = 0;
|
|
364
|
+
if (o.wait !== undefined) {
|
|
365
|
+
seconds = o.wait === true ? 300 : Number(o.wait);
|
|
366
|
+
if (!Number.isInteger(seconds) || seconds < 1)
|
|
367
|
+
return emit(c, { ok: false, error: 'bad_wait', message: '--wait takes whole seconds, e.g. --wait 120 (default 300).' });
|
|
368
|
+
}
|
|
369
|
+
const mine = publicAddresses(o.dir);
|
|
370
|
+
let to = a.chain === 'sui' ? mine.sui : mine.evm;
|
|
371
|
+
if (!to && a.chain !== 'sui') {
|
|
372
|
+
try {
|
|
373
|
+
to = (await loaded(io, o)).addresses.evm;
|
|
374
|
+
}
|
|
375
|
+
catch { /* the refusal below names where to look */ }
|
|
376
|
+
}
|
|
377
|
+
if (!to)
|
|
378
|
+
return emit(c, { ok: false, error: 'no_address', message: `No ${a.chain === 'sui' ? 'Sui' : 'EVM'} address found for this wallet: ${a.chain === 'sui' ? `no sealed vault at ${vaultPath(o.dir)}` : `no addresses.json in ${o.dir} and none registered with the workspace`}. Pass --dir <the agent's folder>. Nothing was asked.` });
|
|
379
|
+
const who = mine.agent ?? (await io.identity?.(o, 'resolved').catch(() => null))?.actor ?? 'this wallet';
|
|
380
|
+
const sentence = sentenceFor(amount, a.asset, a.chain, to);
|
|
381
|
+
const link = linkFor(sentence);
|
|
382
|
+
const label = chainLabel(a.chain, 'mainnet');
|
|
383
|
+
const base = { ok: true, who, amount, asset: a.asset, chain: a.chain, to, sentence, link };
|
|
384
|
+
const block = [
|
|
385
|
+
`${who} asks for ${amount} ${a.asset} on ${label}.`,
|
|
386
|
+
`to ${shortAddr(to)}${a.defaulted ? ` (USDC defaults to Sui; say USDC@base for Base)` : ''}`,
|
|
387
|
+
'',
|
|
388
|
+
link,
|
|
389
|
+
'',
|
|
390
|
+
'Open it and press Touch ID. Nothing moves until you do.',
|
|
391
|
+
];
|
|
392
|
+
if (o.open) {
|
|
393
|
+
if (process.platform === 'darwin')
|
|
394
|
+
spawnSync('open', [link], { stdio: 'ignore' });
|
|
395
|
+
else
|
|
396
|
+
block.push('(--open works on macOS only — open the link yourself.)');
|
|
397
|
+
}
|
|
398
|
+
if (!seconds)
|
|
399
|
+
return emit(c, base, block);
|
|
400
|
+
// Waiting: the human block goes to stderr under --json, so stdout stays one object.
|
|
401
|
+
if (isJson(c))
|
|
402
|
+
process.stderr.write(block.join('\n') + '\n');
|
|
403
|
+
else
|
|
404
|
+
console.log(block.join('\n'));
|
|
405
|
+
const f = io.fetch ?? deadlineFetch();
|
|
406
|
+
const sleep = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
407
|
+
const chain = a.chain;
|
|
408
|
+
const before = await readAsset(f, a.asset, chain, net, to);
|
|
409
|
+
if (before === null)
|
|
410
|
+
return emit(c, { ...base, ok: false, error: 'balance_unreadable', message: `Could not read ${shortAddr(to)}'s ${a.asset} balance on ${chainLabel(chain, net)} to watch it. The link above still works; nothing was waited on.` });
|
|
411
|
+
process.stderr.write(`Watching ${chainLabel(chain, net)} for up to ${seconds} s…\n`);
|
|
412
|
+
const deadline = Date.now() + seconds * 1000;
|
|
413
|
+
while (Date.now() < deadline) {
|
|
414
|
+
await sleep(Math.min(5000, Math.max(0, deadline - Date.now())));
|
|
415
|
+
const now = await readAsset(f, a.asset, chain, net, to);
|
|
416
|
+
if (now !== null && now >= before + units) {
|
|
417
|
+
const digest = chain === 'sui' ? await latestSuiDigest(f, net, to) : null;
|
|
418
|
+
return emit(c, { ...base, received: { amount, asset: a.asset, ...(digest ? { digest } : {}) } }, [`Received ${amount} ${a.asset}.`, ...(digest ? [`digest ${digest}`] : [])]);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
emit(c, { ...base, ok: false, error: 'timeout', message: `Nothing arrived within ${seconds} s. The link still works.` }, ['', link]);
|
|
422
|
+
process.exitCode = 75;
|
|
423
|
+
}
|
|
424
|
+
export function requestCmd(io) {
|
|
425
|
+
return common(new Command('request').alias('ask'), io.defaultApi)
|
|
426
|
+
.description('Ask to be paid. `request 5 USDC` (or SUI, ETH@base …) prints a link YOUR OWNER opens — it types the ask into ONE\'s chat and shows the send card they approve with Touch ID; --wait watches for the money. `request 25 USD` (or --invoice) mints a wallet:invoice payment link instead: the payer picks card or coin')
|
|
427
|
+
.argument('<amount>', 'e.g. 5, 0.01 or 9.99')
|
|
428
|
+
.argument('<asset>', 'USDC | SUI | ETH@base … (an owner link) · USD (an invoice link)')
|
|
429
|
+
.option('--from <slug>', '(invoice) Who you are asking — named in the output; wallet:invoice has no payer field, so you hand them the link')
|
|
430
|
+
.option('--invoice', 'USDC as a wallet:invoice payment link (cents) instead of an owner link')
|
|
431
|
+
.option('--dir <path>', 'The agent\'s folder: its sealed vault\'s PUBLIC address is read — the key never opens', '.')
|
|
432
|
+
.option('--net <network>', 'Which network --wait watches: mainnet (default) | testnet. The link itself carries none')
|
|
433
|
+
.option('--wait [seconds]', 'Poll the chain until the balance rises by the amount (default 300 s); exit 75 on timeout')
|
|
434
|
+
.option('--open', 'Open the link in the default browser (macOS)')
|
|
435
|
+
.action(async function (amount, asset, o) {
|
|
436
|
+
const word = asset.trim().split('@')[0].toUpperCase();
|
|
437
|
+
if (word !== 'USD' && !o.invoice)
|
|
438
|
+
return requestMoney(this, io, amount, asset, o);
|
|
439
|
+
const c = invoiceCents(amount, asset);
|
|
440
|
+
if (!c.ok)
|
|
441
|
+
return emit(this, { ...c });
|
|
442
|
+
const workspace = io.workspace(o.workspace);
|
|
443
|
+
const actor = o.actor ?? workspace;
|
|
444
|
+
let r;
|
|
445
|
+
try {
|
|
446
|
+
r = await io.ask(o, 'wallet:invoice', { workspace, actor, amountCents: c.cents });
|
|
447
|
+
}
|
|
448
|
+
catch (e) {
|
|
449
|
+
return emit(this, { ok: false, error: 'invoice_refused', message: e.message });
|
|
450
|
+
}
|
|
451
|
+
if (typeof r['url'] !== 'string')
|
|
452
|
+
return emit(this, { ok: false, error: String(r['error'] ?? 'no_link'), message: 'wallet:invoice minted no link.', result: r });
|
|
453
|
+
const data = {
|
|
454
|
+
ok: true, url: r['url'], linkId: r['linkId'], custody: r['custody'], amountCents: c.cents, actor,
|
|
455
|
+
network: 'the deploy\'s — one.ie production pays on TESTNET today',
|
|
456
|
+
...(o.from ? { from: o.from, note: `wallet:invoice has no payer field: send ${o.from} this link yourself (one message, a sealed note, or chat).` } : {}),
|
|
457
|
+
};
|
|
458
|
+
emit(this, data, [`Pay ${actor} $${(c.cents / 100).toFixed(2)}: ${String(r['url'])}`, `network ${data.network}`, ...(o.from ? [data.note] : [])]);
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
export function sendCmd(io) {
|
|
462
|
+
return common(new Command('send'), io.defaultApi)
|
|
463
|
+
.description('Send from your wallet: `send <amount> <asset>[@chain] <to>` — DRY by default (prints exactly what would be signed, the fee, the chain picked); --live signs with the sealed vault in --dir. ETH + USDC on Ethereum, Base, Arbitrum; SUI + USDC on Sui. <to> = an address, a workspace slug or an agent id. The old form `send <to> --chain --amount --payment-tx` still records a transfer you signed elsewhere')
|
|
464
|
+
.argument('<words...>', '<amount> <asset>[@chain] <to> (or <to> with --payment-tx)')
|
|
465
|
+
.option('--net <network>', 'mainnet (default — real money) | testnet')
|
|
466
|
+
.option('--live', 'Sign and broadcast. Without it nothing is signed')
|
|
467
|
+
.option('--yes', 'Skip the y/N prompt. Required in an agent shell, where only the agent\'s own vault may sign')
|
|
468
|
+
.option('--dir <path>', 'The folder whose sealed vault (.one/wallet.json) signs', '.')
|
|
469
|
+
.option('--to-address <addr>', 'Your own copy of a recipient found by name — must equal what was resolved')
|
|
470
|
+
.option('--rpc <url>', 'Sui gRPC base URL for a --live Sui send (default: Mysten\'s public fullnode for --net)')
|
|
471
|
+
.option('--chain <chain>', '(relay form) SUI | ETH | BASE | ARB | OPT | SOL | BTC')
|
|
472
|
+
.option('--amount <n>', '(relay form) amount')
|
|
473
|
+
.option('--payment-tx <hash>', '(relay form) the hash of a transfer you already signed and broadcast — records it, signs nothing')
|
|
474
|
+
.option('--unit <unit>', '(relay form) usd | token', 'usd')
|
|
475
|
+
.option('--currency <currency>', '(relay form) NATIVE | USDC', 'NATIVE')
|
|
476
|
+
.option('--user-address <address>', '(relay form) sender address')
|
|
477
|
+
.option('--memo <text>', '(relay form) payment memo')
|
|
478
|
+
.action(async function (words, o) {
|
|
479
|
+
if (o.paymentTx !== undefined) {
|
|
480
|
+
if (words.length !== 1 || !o.chain || !o.amount)
|
|
481
|
+
return emit(this, { ok: false, error: 'relay_form', message: 'Recording a signed transfer: send <to> --chain <c> --amount <n> --payment-tx <hash>' });
|
|
482
|
+
return io.relay(this, words[0], o);
|
|
483
|
+
}
|
|
484
|
+
if (words.length !== 3)
|
|
485
|
+
return emit(this, { ok: false, error: 'usage', message: 'send <amount> <asset>[@chain] <to> e.g. send 1 USDC@base 0x…' });
|
|
486
|
+
const [amount, assetWord, to] = words;
|
|
487
|
+
const net = netOf(o.net);
|
|
488
|
+
if (!net)
|
|
489
|
+
return emit(this, BAD_NET);
|
|
490
|
+
const f = io.fetch ?? deadlineFetch();
|
|
491
|
+
// Who this key is comes first: a folder key scoped to another workspace makes wallet:get refuse, and that refusal must still say whose key it was.
|
|
492
|
+
const me = await io.identity?.(o, 'resolved').catch(() => null);
|
|
493
|
+
const header = actingLine(me);
|
|
494
|
+
const who = me ? { actingAs: me.actor ?? null, keyFrom: me.from } : {};
|
|
495
|
+
let l;
|
|
496
|
+
try {
|
|
497
|
+
l = await loaded(io, o, undefined, me?.actor ?? undefined);
|
|
498
|
+
}
|
|
499
|
+
catch (e) {
|
|
500
|
+
return emit(this, { ok: false, error: 'wallet_read_failed', message: e.message, ...who }, header ? [header] : undefined);
|
|
501
|
+
}
|
|
502
|
+
const resolve = async (name, family) => {
|
|
503
|
+
const pick = (a) => (family === 'evm' ? a.evm : a.sui);
|
|
504
|
+
const mine = pick(addressesFor(l.walletGet, name));
|
|
505
|
+
if (mine)
|
|
506
|
+
return { address: mine, source: 'wallet:get' };
|
|
507
|
+
try {
|
|
508
|
+
const v = pick(addressesFor(await io.ask(o, 'wallet:get', { workspace: name }), name));
|
|
509
|
+
if (v)
|
|
510
|
+
return { address: v, source: 'wallet:get' };
|
|
511
|
+
}
|
|
512
|
+
catch { /* not a workspace this key reads */ }
|
|
513
|
+
try {
|
|
514
|
+
const r = await io.ask(o, 'identity:address', { uid: name });
|
|
515
|
+
const v = String(r['address'] ?? '');
|
|
516
|
+
if (addressShape(v) === family)
|
|
517
|
+
return { address: v, source: 'identity:address' };
|
|
518
|
+
}
|
|
519
|
+
catch { /* no identity row */ }
|
|
520
|
+
return null;
|
|
521
|
+
};
|
|
522
|
+
const planned = await planSend({ amount, asset: assetWord, to, net }, { fetch: f, from: l.addresses, resolve });
|
|
523
|
+
if (!planned.ok) {
|
|
524
|
+
const cause = planned.error === 'no_from_address' ? await noFromCause(io, o, me, /no sui address/.test(planned.message) ? 'sui' : 'evm', l.who) : undefined;
|
|
525
|
+
return emit(this, { ...planned, ...(cause ? { message: cause } : {}), dry: true, ...who }, header ? [header] : undefined);
|
|
526
|
+
}
|
|
527
|
+
const plan = planned.plan;
|
|
528
|
+
const lines = [...(header ? [header] : []), ...planLines(plan)];
|
|
529
|
+
if (!o.live) {
|
|
530
|
+
const pin = plan.toSource !== 'typed' ? ` --to-address ${plan.to}` : '';
|
|
531
|
+
const liveCmd = `${cliPrefix()} wallet send ${shq(amount)} ${plan.asset}@${plan.chain} ${shq(to)} --net ${net} --live --dir <your vault folder>${pin}`;
|
|
532
|
+
return emit(this, { ok: true, dry: true, plan: planJson(plan), next: liveCmd, ...who }, [...lines, '', 'DRY RUN — nothing was signed or sent.', `To send it: ${liveCmd}`]);
|
|
533
|
+
}
|
|
534
|
+
if (!isJson(this))
|
|
535
|
+
console.error(lines.join('\n'));
|
|
536
|
+
const gate = await liveGate({ env: process.env, yes: Boolean(o.yes), interactive: Boolean(process.stdin.isTTY), dir: o.dir, plan, toAddress: o.toAddress, workspace: o.workspace ? io.workspace(o.workspace) : undefined }, { ask: (r, d) => io.ask(o, r, d), vaultSuiAddress: vaultSuiAddressOf, confirm });
|
|
537
|
+
if (!gate.ok)
|
|
538
|
+
return emit(this, { ...gate, ...who });
|
|
539
|
+
const parsed = parseAssetWord(assetWord);
|
|
540
|
+
const own = { amount, asset: plan.asset, chain: parsed.ok && parsed.chain ? parsed.chain : plan.chain, to: plan.toSource === 'typed' ? to : (o.toAddress ?? plan.to), net, suiRpc: o.rpc };
|
|
541
|
+
const r = await executeSend(plan, own, { fetch: f, unlock: () => io.unlock(o.dir) });
|
|
542
|
+
emit(this, r, r['ok'] ? sentLines(r) : undefined);
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
/** What a landed send prints: where to look, what it cost, how long it took — Sui adds gas and the time to finality. */
|
|
546
|
+
function sentLines(r) {
|
|
547
|
+
const out = [`sent ${String(r['explorer'])}`];
|
|
548
|
+
if (r['digest'] && r['chain'] === 'sui')
|
|
549
|
+
out.push(`digest ${String(r['digest'])}`);
|
|
550
|
+
if (r['gasSui'] !== undefined)
|
|
551
|
+
out.push(`gas ${String(r['gasSui'])} SUI`);
|
|
552
|
+
if (r['finalMs'] !== undefined)
|
|
553
|
+
out.push(`final in ${String(r['finalMs'])} ms`);
|
|
554
|
+
out.push(`status ${String(r['status'] ?? (r['chain'] === 'sui' ? 'final' : 'submitted'))}`, `record it in ONE: ${String(r['next'])}`);
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
/** The vault's Sui address from its PUBLIC authPub — read without opening it. */
|
|
558
|
+
export function vaultSuiAddressOf(dir) {
|
|
559
|
+
const blob = readVaultFolder(dir);
|
|
560
|
+
const hex = typeof blob?.authPub === 'string' ? blob.authPub.replace(/^0x/, '') : '';
|
|
561
|
+
if (!/^[0-9a-fA-F]{64}$/.test(hex))
|
|
562
|
+
return null;
|
|
563
|
+
return suiAddressFromPubkey(Uint8Array.from((hex.match(/.{2}/g) ?? []).map((x) => parseInt(x, 16))));
|
|
564
|
+
}
|