@attocash/cli 0.3.1 → 0.4.0

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.
@@ -3,6 +3,7 @@ import { isAbsolute, join, resolve } from 'node:path';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
4
  import { AttoApplication } from '../application/app.js';
5
5
  import { amountRaw } from '../domain/amount.js';
6
+ import { formatSpendingPolicy as formatPolicy } from '../marketplace/wallet-setup.js';
6
7
  import { AttoError } from '../domain/errors.js';
7
8
  import { defaultCliDirectory, dedicatedMcpDirectory, resolveWalletProfile } from '../storage/profiles.js';
8
9
  import { hiddenPrompt, requireTerminal, showRecovery, terminalPrompt } from './terminal.js';
@@ -22,13 +23,6 @@ async function choose(prompt) {
22
23
  throw new AttoError('INVALID_INPUT', 'Choose 1 or 2.');
23
24
  return answer;
24
25
  }
25
- function formatPolicy(policy) {
26
- const perPayment = policy.perRequest ? `${policy.perRequest.amount} ${policy.perRequest.unit}` : 'Unlimited';
27
- const rolling = policy.rolling.length
28
- ? policy.rolling.map(rule => `${rule.amount} ${rule.unit} / ${rule.days} day${rule.days === 1 ? '' : 's'}`).join(', ')
29
- : 'Unlimited';
30
- return `Per payment: ${perPayment}; rolling: ${rolling}`;
31
- }
32
26
  function showProposal(review) {
33
27
  const { proposal } = review;
34
28
  process.stderr.write([
@@ -217,6 +211,9 @@ export async function setupMarketplaceWallet({ directory, controllerIndex, reuse
217
211
  const messageSigningIndexes = typedControllerApprovals ? usage.messageSigningIndexes : reuseExisting
218
212
  ? [...new Set([...usage.messageSigningIndexes, controllerIndex])].sort((a, b) => a - b) : [controllerIndex];
219
213
  const proposal = reuseExisting ? await application.store.withWalletLock(async () => {
214
+ if (application.store.get('wallet.reset')) {
215
+ throw new AttoError('WALLET_RESET_REQUIRED', 'Finish wallet reset before configuring Marketplace.');
216
+ }
220
217
  // Fail rather than replacing authority changed by another CLI/MCP session
221
218
  // while the user was answering terminal prompts.
222
219
  if (!isDeepStrictEqual(usage, {
@@ -226,13 +223,16 @@ export async function setupMarketplaceWallet({ directory, controllerIndex, reuse
226
223
  || !isDeepStrictEqual(status.identity, application.store.get('identity'))) {
227
224
  throw new AttoError('PROPOSAL_STALE', 'The shared wallet settings or authority changed during setup. Review the current wallet and run setup again.');
228
225
  }
226
+ if (isDeepStrictEqual(usage, { policy, access: 'spend', pool, messageSigningIndexes }))
227
+ return null;
229
228
  return application.ledger.proposePolicy(policy, 'spend', {
230
229
  directory: profile.directory, walletFingerprint: status.identity.fingerprint, network: status.settings.network,
231
230
  }, pool, messageSigningIndexes);
232
231
  }) : (await application.call('limits_propose', {
233
232
  policy, access: 'spend', pool, messageSigningIndexes,
234
233
  })).proposal;
235
- await approve(application, proposal.id);
234
+ if (proposal)
235
+ await approve(application, proposal.id);
236
236
  return { directory: profile.directory, address: controller.address, index: controller.index };
237
237
  }
238
238
  finally {
@@ -23,3 +23,4 @@ export declare function signMarketplaceAttoController(options: {
23
23
  request: unknown;
24
24
  terminalConfirmed: true;
25
25
  }): Promise<import("./marketplace/proof-approval.js").MarketplaceProofApprovalResponse>;
26
+ export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup, type MarketplaceWalletSetupSnapshot } from './marketplace/wallet-setup.js';
@@ -48,3 +48,4 @@ export async function signMarketplaceAttoController(options) {
48
48
  await application.close();
49
49
  }
50
50
  }
51
+ export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup } from './marketplace/wallet-setup.js';
@@ -0,0 +1,35 @@
1
+ import { type LimitsProposal, type McpAccess } from '../spending/ledger.js';
2
+ import { type WalletProfile } from '../storage/profiles.js';
3
+ import type { AccountPool, NetworkName, SpendingPolicy, WalletAddress, WalletIdentity, WalletSettings } from '../wallet/types.js';
4
+ /** Public saved state only. Recovery credentials and payment journals never enter this snapshot. */
5
+ export interface MarketplaceWalletSetupSnapshot {
6
+ directory: string;
7
+ profile: WalletProfile;
8
+ address: string;
9
+ index: number;
10
+ fingerprint: string;
11
+ network: `atto:${Lowercase<NetworkName>}`;
12
+ identity: WalletIdentity;
13
+ settings: WalletSettings;
14
+ addresses: WalletAddress[];
15
+ access: McpAccess;
16
+ policy: SpendingPolicy;
17
+ pool: AccountPool;
18
+ messageSigningIndexes: number[];
19
+ authorityRevision: number;
20
+ proposal: LimitsProposal | null;
21
+ formattedLimits: string;
22
+ }
23
+ export declare function formatSpendingPolicy(policy: SpendingPolicy): string;
24
+ /** Short saved-state inspection; the wallet lock is released before terminal questions. */
25
+ export declare function inspectMarketplaceWalletSetup(options: {
26
+ directory: string;
27
+ index: number;
28
+ }): Promise<MarketplaceWalletSetupSnapshot>;
29
+ /** Persist Marketplace-owned selections only while the reviewed shared wallet remains unchanged. */
30
+ export declare function withUnchangedMarketplaceWalletSetup<T>(options: {
31
+ directory: string;
32
+ index: number;
33
+ expected: MarketplaceWalletSetupSnapshot;
34
+ terminalConfirmed: true;
35
+ }, action: () => Promise<T>): Promise<T>;
@@ -0,0 +1,109 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { AttoAddress } from '@attocash/commons-core';
6
+ import { requireTerminal } from '../cli/terminal.js';
7
+ import { AttoError } from '../domain/errors.js';
8
+ import { SpendLedger } from '../spending/ledger.js';
9
+ import { inspectWalletProfile } from '../storage/profiles.js';
10
+ import { StateStore } from '../storage/state.js';
11
+ export function formatSpendingPolicy(policy) {
12
+ const perPayment = policy.perRequest ? `${policy.perRequest.amount} ${policy.perRequest.unit}` : 'Unlimited';
13
+ const rolling = policy.rolling.length
14
+ ? policy.rolling.map(rule => `${rule.amount} ${rule.unit} / ${rule.days} day${rule.days === 1 ? '' : 's'}`).join(', ')
15
+ : 'Unlimited';
16
+ return `Per payment: ${perPayment}; rolling: ${rolling}`;
17
+ }
18
+ function snapshot(store, index) {
19
+ if (store.get('wallet.reset'))
20
+ throw new AttoError('WALLET_RESET_REQUIRED', 'Finish wallet reset before configuring Marketplace.');
21
+ const identity = store.get('identity');
22
+ const settings = store.get('settings');
23
+ if (!identity || typeof identity.address !== 'string' || typeof identity.fingerprint !== 'string' || !settings) {
24
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'Choose an initialized existing CLI wallet or use advanced wallet setup.');
25
+ }
26
+ if (!['LIVE', 'BETA', 'DEV', 'LOCAL'].includes(settings.network)) {
27
+ throw new AttoError('INVALID_STATE', 'The selected wallet network is invalid. Review it in the Atto CLI before setup.');
28
+ }
29
+ const addresses = store.get('addresses') ?? [];
30
+ if (!Array.isArray(addresses))
31
+ throw new AttoError('INVALID_STATE', 'The saved wallet addresses are invalid.');
32
+ const address = addresses.find(value => value?.index === index);
33
+ if (!address) {
34
+ throw new AttoError('MARKETPLACE_ADVANCED_SETUP_REQUIRED', 'This account index has no saved wallet address. Derive it in advanced Atto CLI wallet setup before selecting it for Marketplace.');
35
+ }
36
+ try {
37
+ if (!/^[0-9a-f]{64}$/.test(identity.fingerprint)
38
+ || AttoAddress.parse(identity.address).value !== identity.address
39
+ || AttoAddress.parse(address.address).value !== address.address)
40
+ throw new Error();
41
+ }
42
+ catch {
43
+ throw new AttoError('INVALID_STATE', 'The saved wallet identity or account address is invalid. Review it in the Atto CLI before setup.');
44
+ }
45
+ const ledger = new SpendLedger(store);
46
+ const policy = ledger.policy();
47
+ const authorityRevision = store.get('spending.policyRevision') ?? 0;
48
+ if (!Number.isSafeInteger(authorityRevision) || authorityRevision < 0 || authorityRevision === Number.MAX_SAFE_INTEGER) {
49
+ throw new AttoError('INVALID_STATE', 'The saved spending-policy revision is invalid.');
50
+ }
51
+ return {
52
+ directory: store.directory, profile: inspectWalletProfile(store.directory), address: address.address, index,
53
+ fingerprint: identity.fingerprint, network: `atto:${settings.network.toLowerCase()}`,
54
+ identity, settings, addresses, policy, access: ledger.mcpAccess(), pool: ledger.pool(),
55
+ messageSigningIndexes: ledger.messageSigningIndexes(), authorityRevision, proposal: ledger.proposal(),
56
+ formattedLimits: formatSpendingPolicy(policy),
57
+ };
58
+ }
59
+ async function withExistingWallet(options, action) {
60
+ requireTerminal();
61
+ if (!options.directory || !isAbsolute(options.directory)) {
62
+ throw new AttoError('INVALID_INPUT', 'Marketplace setup requires an explicit absolute existing wallet directory.');
63
+ }
64
+ if (!Number.isSafeInteger(options.index) || options.index < 0 || options.index > 0x7fff_ffff) {
65
+ throw new AttoError('INVALID_INPUT', 'The Marketplace account index must be a nonnegative integer.');
66
+ }
67
+ const profile = inspectWalletProfile(options.directory);
68
+ if (!existsSync(join(profile.directory, 'state.sqlite'))) {
69
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'Choose an initialized existing CLI wallet or use advanced wallet setup.');
70
+ }
71
+ // Compact setup must not implicitly upgrade or repair an older profile.
72
+ const inspection = new DatabaseSync(join(profile.directory, 'state.sqlite'), { readOnly: true });
73
+ try {
74
+ const version = inspection.prepare('PRAGMA user_version').get()?.user_version;
75
+ const table = inspection.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'settings'").get();
76
+ if (version !== 2 || !table) {
77
+ throw new AttoError('STATE_VERSION', 'Open and review this wallet in the current Atto CLI before using compact Marketplace setup.');
78
+ }
79
+ }
80
+ finally {
81
+ inspection.close();
82
+ }
83
+ // Reuse the normal wallet lifecycle lease and mutation lock. Unlike opening
84
+ // AttoApplication, this never initializes settings, accesses credentials,
85
+ // derives addresses, or reconciles financial records.
86
+ const store = new StateStore(profile.directory);
87
+ try {
88
+ return await store.withWalletLock(() => action(store));
89
+ }
90
+ finally {
91
+ store.close();
92
+ }
93
+ }
94
+ /** Short saved-state inspection; the wallet lock is released before terminal questions. */
95
+ export function inspectMarketplaceWalletSetup(options) {
96
+ return withExistingWallet(options, async (store) => snapshot(store, options.index));
97
+ }
98
+ /** Persist Marketplace-owned selections only while the reviewed shared wallet remains unchanged. */
99
+ export async function withUnchangedMarketplaceWalletSetup(options, action) {
100
+ requireTerminal();
101
+ if (options.terminalConfirmed !== true)
102
+ throw new AttoError('LOCAL_APPROVAL_REQUIRED', 'Local terminal approval is required.');
103
+ return withExistingWallet(options, async (store) => {
104
+ if (!isDeepStrictEqual(options.expected, snapshot(store, options.index))) {
105
+ throw new AttoError('PROPOSAL_STALE', 'The shared wallet settings, identity, or authority changed during setup. Review it and run setup again.');
106
+ }
107
+ return action();
108
+ });
109
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@attocash/cli",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Atto wallet CLI and reusable wallet engine with local key custody and shared spending limits",
5
5
  "license": "BSD-3-Clause",
6
6
  "type": "module",