@attocash/cli 0.2.3 → 0.3.1

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 (137) hide show
  1. package/README.md +148 -7
  2. package/dist/application/app.d.ts +34 -3
  3. package/dist/application/app.js +138 -126
  4. package/dist/application/operations.d.ts +3 -0
  5. package/dist/application/operations.js +30 -8
  6. package/dist/cli/cli.d.ts +1 -0
  7. package/dist/cli/cli.js +101 -13
  8. package/dist/cli/onboarding.d.ts +13 -0
  9. package/dist/cli/onboarding.js +99 -2
  10. package/dist/cli/output.js +18 -2
  11. package/dist/doctor/profile.js +2 -1
  12. package/dist/internal-marketplace.d.ts +25 -0
  13. package/dist/internal-marketplace.js +50 -0
  14. package/dist/marketplace/approval-files.d.ts +3 -0
  15. package/dist/marketplace/approval-files.js +97 -0
  16. package/dist/marketplace/approval-preview.d.ts +2 -0
  17. package/dist/marketplace/approval-preview.js +86 -0
  18. package/dist/marketplace/proof-approval.d.ts +82 -0
  19. package/dist/marketplace/proof-approval.js +671 -0
  20. package/dist/marketplace/topups.d.ts +82 -0
  21. package/dist/marketplace/topups.js +485 -0
  22. package/dist/network/batching.d.ts +2 -0
  23. package/dist/network/batching.js +23 -0
  24. package/dist/network/entry.d.ts +2 -0
  25. package/dist/network/entry.js +35 -0
  26. package/dist/network/reader.d.ts +2 -0
  27. package/dist/network/reader.js +125 -37
  28. package/dist/spending/approval.d.ts +5 -0
  29. package/dist/spending/approval.js +2 -0
  30. package/dist/spending/atto-x402.d.ts +31 -0
  31. package/dist/spending/atto-x402.js +174 -0
  32. package/dist/spending/ledger.d.ts +74 -2
  33. package/dist/spending/ledger.js +298 -7
  34. package/dist/spending/payments.d.ts +105 -5
  35. package/dist/spending/payments.js +795 -11
  36. package/dist/storage/recovery-seed.d.ts +13 -0
  37. package/dist/storage/recovery-seed.js +93 -0
  38. package/dist/storage/state.d.ts +4 -0
  39. package/dist/storage/state.js +32 -2
  40. package/dist/wallet/receive.d.ts +39 -0
  41. package/dist/wallet/receive.js +264 -0
  42. package/dist/wallet/signing.d.ts +1 -0
  43. package/dist/wallet/signing.js +37 -21
  44. package/dist/wallet/types.d.ts +1 -0
  45. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs +1922 -1918
  46. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs.map +1 -1
  47. package/node_modules/@attocash/commons-core/README.md +9 -0
  48. package/node_modules/@attocash/commons-core/commons-commons-core.d.mts +10 -0
  49. package/node_modules/@attocash/commons-core/commons-commons-core.mjs +2543 -2434
  50. package/node_modules/@attocash/commons-core/commons-commons-core.mjs.map +1 -1
  51. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs +4695 -4227
  52. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs.map +1 -1
  53. package/node_modules/@attocash/commons-core/kotlin_org_jetbrains_kotlin_kotlin_dom_api_compat.mjs.map +1 -1
  54. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs +60 -60
  55. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs.map +1 -1
  56. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs +651 -631
  57. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs.map +1 -1
  58. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs +2294 -2295
  59. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs.map +1 -1
  60. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  61. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  62. package/node_modules/@attocash/commons-core/package.json +1 -1
  63. package/node_modules/@attocash/commons-node/commons-commons-node.d.mts +1 -0
  64. package/node_modules/@attocash/commons-node/commons-commons-node.mjs +873 -847
  65. package/node_modules/@attocash/commons-node/commons-commons-node.mjs.map +1 -1
  66. package/node_modules/@attocash/commons-node/kotlin-logging.mjs +109 -109
  67. package/node_modules/@attocash/commons-node/kotlin-logging.mjs.map +1 -1
  68. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  69. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  70. package/node_modules/@attocash/commons-node/package.json +3 -3
  71. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.d.mts +1 -0
  72. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs +674 -640
  73. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs.map +1 -1
  74. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs +109 -109
  75. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs.map +1 -1
  76. package/node_modules/@attocash/commons-node-remote/kotlinx-browser.mjs.map +1 -1
  77. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  78. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  79. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  80. package/node_modules/@attocash/commons-node-remote/package.json +4 -4
  81. package/node_modules/@attocash/commons-transport/commons-commons-transport.d.mts +1 -0
  82. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs +52 -51
  83. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs.map +1 -1
  84. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs +13 -13
  85. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs.map +1 -1
  86. package/node_modules/@attocash/commons-transport/kotlinx-browser.mjs.map +1 -1
  87. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs +2639 -2608
  88. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs.map +1 -1
  89. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  90. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  91. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  92. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs +411 -196
  93. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs.map +1 -1
  94. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs +2115 -1976
  95. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs.map +1 -1
  96. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs +7 -7
  97. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs.map +1 -1
  98. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs +385 -384
  99. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs.map +1 -1
  100. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs +1261 -1185
  101. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs.map +1 -1
  102. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs +668 -656
  103. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs.map +1 -1
  104. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs +89 -0
  105. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs.map +1 -0
  106. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs +9 -9
  107. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs.map +1 -1
  108. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs +120 -128
  109. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs.map +1 -1
  110. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs +46 -49
  111. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs.map +1 -1
  112. package/node_modules/@attocash/commons-transport/ktor-ktor-sse.mjs.map +1 -1
  113. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs +1041 -985
  114. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs.map +1 -1
  115. package/node_modules/@attocash/commons-transport/ktor-ktor-websocket-serialization.mjs.map +1 -1
  116. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs +530 -455
  117. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs.map +1 -1
  118. package/node_modules/@attocash/commons-transport/package.json +4 -4
  119. package/node_modules/@attocash/commons-worker/commons-commons-worker.d.mts +1 -0
  120. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs +230 -226
  121. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs.map +1 -1
  122. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs +109 -109
  123. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs.map +1 -1
  124. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  125. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  126. package/node_modules/@attocash/commons-worker/package.json +3 -3
  127. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.d.mts +1 -0
  128. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs +91 -86
  129. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs.map +1 -1
  130. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs +109 -109
  131. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs.map +1 -1
  132. package/node_modules/@attocash/commons-worker-remote/kotlinx-browser.mjs.map +1 -1
  133. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  134. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  135. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  136. package/node_modules/@attocash/commons-worker-remote/package.json +4 -4
  137. package/package.json +9 -5
@@ -0,0 +1,13 @@
1
+ import { type WalletProfile } from './profiles.js';
2
+ /** Public source binding only. The original profile and credential namespace stay authoritative. */
3
+ export interface MarketplaceRecoverySource extends WalletProfile {
4
+ identityAddress: string;
5
+ }
6
+ /** Trusted Marketplace library boundary, never an MCP operation or key export.
7
+ * Hold the existing lifecycle read lease while validating the credential and
8
+ * consuming its temporary BIP39 seed. Opening read-only avoids initializing a
9
+ * missing source or changing its public state and journals. */
10
+ export declare function withMarketplaceRecoverySeed<T>(source: string | MarketplaceRecoverySource, action: (seed: Uint8Array, source: MarketplaceRecoverySource) => T | Promise<T>): Promise<T>;
11
+ /** Offline initialization for an explicitly selected Marketplace recovery root.
12
+ * Recovery words remain in the existing protected terminal workflow. */
13
+ export declare function initializeMarketplaceRecoveryWallet(directory: string): Promise<MarketplaceRecoverySource>;
@@ -0,0 +1,93 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { inspectWalletProfile } from './profiles.js';
5
+ import { OsSecretStore } from './secrets.js';
6
+ import { mnemonicSeed } from '../wallet/signing.js';
7
+ import { privateKeyToSigner, toAttoIndex } from '@attocash/commons-core';
8
+ import { AttoError } from '../domain/errors.js';
9
+ import { AttoApplication } from '../application/app.js';
10
+ import { requireTerminal, terminalPrompt, hiddenPrompt, showRecovery } from '../cli/terminal.js';
11
+ /** Trusted Marketplace library boundary, never an MCP operation or key export.
12
+ * Hold the existing lifecycle read lease while validating the credential and
13
+ * consuming its temporary BIP39 seed. Opening read-only avoids initializing a
14
+ * missing source or changing its public state and journals. */
15
+ export async function withMarketplaceRecoverySeed(source, action) {
16
+ const profile = inspectWalletProfile(typeof source === 'string' ? source : source.directory);
17
+ if (typeof source !== 'string' && (profile.directory !== source.directory ||
18
+ profile.credentialAccount !== source.credentialAccount || profile.credentialService !== source.credentialService)) {
19
+ throw new AttoError('WALLET_MISMATCH', 'The selected recovery source no longer matches its original profile.');
20
+ }
21
+ if (!existsSync(join(profile.directory, 'state.sqlite')) || !existsSync(join(profile.directory, 'lifecycle.sqlite'))) {
22
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'The selected recovery source is unavailable. Restore the original wallet before continuing.');
23
+ }
24
+ const lifecycle = new DatabaseSync(join(profile.directory, 'lifecycle.sqlite'), { readOnly: true });
25
+ let state;
26
+ try {
27
+ lifecycle.exec('PRAGMA busy_timeout = 0; BEGIN; SELECT COUNT(*) FROM lease;');
28
+ state = new DatabaseSync(join(profile.directory, 'state.sqlite'), { readOnly: true });
29
+ const read = (key) => {
30
+ const row = state.prepare('SELECT value FROM settings WHERE key = ?').get(key);
31
+ return row ? JSON.parse(row.value) : undefined;
32
+ };
33
+ if (read('wallet.reset'))
34
+ throw new AttoError('WALLET_RESET_REQUIRED', 'Finish the interrupted recovery source reset before continuing.');
35
+ const identity = read('identity');
36
+ if (!identity || typeof identity.address !== 'string')
37
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'The selected recovery source is not initialized.');
38
+ const binding = { ...profile, identityAddress: identity.address };
39
+ if (typeof source !== 'string' && source.identityAddress !== binding.identityAddress) {
40
+ throw new AttoError('WALLET_MISMATCH', 'The selected recovery source identity changed. Restore the original wallet before continuing.');
41
+ }
42
+ const phrase = await new OsSecretStore(profile.credentialAccount, profile.credentialService).get();
43
+ if (!phrase)
44
+ throw new AttoError('WALLET_CREDENTIAL_MISSING', 'The OS password store has no recovery phrase for the selected source. Unlock or restore that original credential.');
45
+ const seed = await mnemonicSeed(phrase);
46
+ try {
47
+ const identityKey = await seed.toPrivateKey(toAttoIndex(0));
48
+ try {
49
+ if ((await privateKeyToSigner(identityKey)).address.value !== binding.identityAddress)
50
+ throw new AttoError('WALLET_MISMATCH', 'The recovery credential does not match the selected wallet.');
51
+ }
52
+ finally {
53
+ identityKey.value.fill(0);
54
+ }
55
+ // Int8Array and Uint8Array share the same zeroized backing allocation.
56
+ const bytes = new Uint8Array(seed.value.buffer, seed.value.byteOffset, seed.value.byteLength);
57
+ return await action(bytes, binding);
58
+ }
59
+ finally {
60
+ seed.value.fill(0);
61
+ }
62
+ }
63
+ finally {
64
+ state?.close();
65
+ lifecycle.close();
66
+ }
67
+ }
68
+ /** Offline initialization for an explicitly selected Marketplace recovery root.
69
+ * Recovery words remain in the existing protected terminal workflow. */
70
+ export async function initializeMarketplaceRecoveryWallet(directory) {
71
+ requireTerminal();
72
+ const profile = inspectWalletProfile(directory);
73
+ // Existing source failures must never become an implicit replacement wallet.
74
+ if (existsSync(join(profile.directory, 'state.sqlite')))
75
+ return withMarketplaceRecoverySeed(profile.directory, (_seed, binding) => binding);
76
+ const method = await terminalPrompt('Recovery phrase: [1] Create new (default), [2] Import existing: ') || '1';
77
+ if (method !== '1' && method !== '2')
78
+ throw new AttoError('INVALID_INPUT', 'Choose 1 or 2.');
79
+ if (await terminalPrompt('Type yes to store this shared recovery phrase in the OS password store: ') !== 'yes') {
80
+ throw new AttoError('CANCELLED', 'No approval was granted.');
81
+ }
82
+ const imported = method === '2' ? await hiddenPrompt('Recovery phrase (hidden): ') : undefined;
83
+ const application = new AttoApplication({ directory });
84
+ try {
85
+ await application.createWallet(imported);
86
+ if (method === '1')
87
+ showRecovery(await application.backupMnemonic());
88
+ }
89
+ finally {
90
+ await application.close();
91
+ }
92
+ return withMarketplaceRecoverySeed(directory, (_seed, binding) => binding);
93
+ }
@@ -13,6 +13,10 @@ export declare class StateStore {
13
13
  get busy(): boolean;
14
14
  constructor(directory: string);
15
15
  get<T>(key: string): T | undefined;
16
+ entries<T>(prefix: string): Array<{
17
+ key: string;
18
+ value: T;
19
+ }>;
16
20
  set(key: string, value: unknown): void;
17
21
  /** Only synchronous state work belongs here; network work uses withWalletLock. */
18
22
  transaction<T>(fn: () => T): T;
@@ -57,9 +57,34 @@ export class StateStore {
57
57
  this.state = open('state.sqlite');
58
58
  this.state.exec('PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;');
59
59
  const version = this.state.prepare('PRAGMA user_version').get()?.user_version;
60
- if (version !== 0 && version !== 1)
60
+ if (version !== 0 && version !== 1 && version !== 2)
61
61
  throw new AttoError('STATE_VERSION', 'This wallet state requires a newer Atto CLI.');
62
- this.state.exec('CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL); PRAGMA user_version = 1;');
62
+ if (version === 1) {
63
+ // x402 adds durable request semantics that older binaries must not
64
+ // reinterpret. Migrate only when no process already owns this profile.
65
+ this.lifecycle.exec('ROLLBACK;');
66
+ try {
67
+ this.lifecycle.exec('BEGIN EXCLUSIVE;');
68
+ }
69
+ catch (error) {
70
+ const code = error.errcode;
71
+ if (code === 5 || code === 6)
72
+ throw new AttoError('WALLET_BUSY', 'Close other sessions using this wallet before upgrading its payment journal.');
73
+ throw error;
74
+ }
75
+ try {
76
+ this.state.exec('PRAGMA user_version = 2;');
77
+ }
78
+ finally {
79
+ this.lifecycle.exec('COMMIT; BEGIN; SELECT COUNT(*) FROM lease;');
80
+ }
81
+ }
82
+ else if (version === 0) {
83
+ this.state.exec('CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL); PRAGMA user_version = 2;');
84
+ }
85
+ else {
86
+ this.state.exec('CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);');
87
+ }
63
88
  this.coordination = open('coordination.sqlite');
64
89
  this.coordination.exec('PRAGMA busy_timeout = 0;');
65
90
  }
@@ -81,6 +106,11 @@ export class StateStore {
81
106
  const row = this.state.prepare('SELECT value FROM settings WHERE key = ?').get(key);
82
107
  return row ? JSON.parse(row.value) : undefined;
83
108
  }
109
+ entries(prefix) {
110
+ this.requireOpen();
111
+ return this.state.prepare('SELECT key, value FROM settings WHERE key >= ? AND key < ? ORDER BY key')
112
+ .all(prefix, `${prefix}\uffff`).map(row => ({ key: row.key, value: JSON.parse(row.value) }));
113
+ }
84
114
  set(key, value) {
85
115
  this.requireOpen();
86
116
  const json = JSON.stringify(value);
@@ -0,0 +1,39 @@
1
+ import { AttoSeed } from '@attocash/commons-core';
2
+ import { NodeReader } from '../network/reader.js';
3
+ import type { StateStore } from '../storage/state.js';
4
+ import type { ReceiveRequest, WalletAddress, WalletSettings } from './types.js';
5
+ import type { WalletWork } from './work.js';
6
+ /** Owns receive candidates, recovery, and the account fence shared with payments. */
7
+ export declare class WalletReceiver {
8
+ private readonly context;
9
+ constructor(context: {
10
+ store: StateStore;
11
+ settings: () => WalletSettings;
12
+ address: (index: number, requireActive?: boolean) => WalletAddress;
13
+ reader: () => NodeReader;
14
+ seed: () => Promise<AttoSeed>;
15
+ requireMcpWrite: () => void;
16
+ requireAccountAvailable: (index: number) => void;
17
+ work: WalletWork;
18
+ receivingAllowed: () => boolean;
19
+ internalMarketplaceReceiveSafety: boolean;
20
+ });
21
+ private result;
22
+ private pendingReceivable;
23
+ requireReceivesResolved(indexes: number[], allowedHash?: string): void;
24
+ private privateReceiveBinding;
25
+ private savedReceiveAmount;
26
+ /** Older standalone records retain their shape; signed SEND history supplies missing metadata. */
27
+ private recoverReceiveAmount;
28
+ receive(request: ReceiveRequest, automatic?: boolean): Promise<{}>;
29
+ receiveAll(input: {
30
+ index?: number;
31
+ limit?: number;
32
+ timeoutMs?: number;
33
+ representative?: string;
34
+ }): Promise<{
35
+ limitReached?: boolean | undefined;
36
+ results: unknown[];
37
+ timedOut: boolean;
38
+ }>;
39
+ }
@@ -0,0 +1,264 @@
1
+ import { AttoOpenBlock, AttoReceiveBlock, AttoSendBlock, AttoTransaction } from '@attocash/commons-core';
2
+ import { amountOutput, amountRaw } from '../domain/amount.js';
3
+ import { AttoError } from '../domain/errors.js';
4
+ import { parseAddress, publicModel } from '../network/reader.js';
5
+ import { signingWallet } from './signing.js';
6
+ /** Owns receive candidates, recovery, and the account fence shared with payments. */
7
+ export class WalletReceiver {
8
+ context;
9
+ constructor(context) {
10
+ this.context = context;
11
+ }
12
+ result(transaction, status = 'published') {
13
+ return { status, hash: transaction.hash.toString(), transaction: publicModel(transaction) };
14
+ }
15
+ async pendingReceivable(address, hash) {
16
+ let found;
17
+ const controller = new AbortController();
18
+ const timer = setTimeout(() => controller.abort(), 2000);
19
+ try {
20
+ await this.context.reader().stream({ event: 'receivable', addresses: [address], minAmountRaw: '1' }, model => {
21
+ const receivable = model;
22
+ if (receivable.hash.toString().toUpperCase() === hash.toUpperCase()) {
23
+ found = receivable;
24
+ controller.abort();
25
+ }
26
+ }, controller.signal);
27
+ }
28
+ catch (error) {
29
+ if (!controller.signal.aborted)
30
+ throw error;
31
+ }
32
+ finally {
33
+ clearTimeout(timer);
34
+ }
35
+ if (!found && controller.signal.aborted) {
36
+ throw new AttoError('RECEIVABLE_LOOKUP_TIMEOUT', 'Checking the pending payment timed out. Retry receiving it; its absence has not been confirmed.');
37
+ }
38
+ return found;
39
+ }
40
+ requireReceivesResolved(indexes, allowedHash) {
41
+ if (!this.context.internalMarketplaceReceiveSafety)
42
+ return;
43
+ const prefix = `receive.${this.context.settings().network}.`;
44
+ for (const { key, value } of this.context.store.entries(prefix)) {
45
+ if (!value || !Number.isSafeInteger(value.index) || value.index < 0 || value.index > 0x7fff_ffff
46
+ || !/^[A-F0-9]{64}$/.test(value.hash) || !/^[A-F0-9]{64}$/.test(value.blockHash) || key !== `${prefix}${value.hash}`) {
47
+ throw new AttoError('INVALID_STATE', 'The saved receive candidate is invalid. Preserve and restore its original wallet state.');
48
+ }
49
+ if (indexes.includes(value.index) && !value.result && value.hash !== allowedHash) {
50
+ throw new AttoError('SOURCE_FENCED', 'Recover the original pending RECEIVE before creating another native operation.');
51
+ }
52
+ }
53
+ }
54
+ privateReceiveBinding(record, index, hash) {
55
+ const network = this.context.settings().network;
56
+ const address = this.context.address(index).address;
57
+ const hasPrivateBinding = record.sourceAddress !== undefined || record.network !== undefined;
58
+ if (record.hash !== hash || record.index !== index || !/^[A-F0-9]{64}$/.test(record.blockHash)
59
+ || hasPrivateBinding && (record.sourceAddress !== address || record.network !== network)) {
60
+ throw new AttoError('INVALID_STATE', 'The saved receive candidate does not match this wallet account and network.');
61
+ }
62
+ return { hash: record.blockHash, index, sendHash: hash, sourceAddress: address, network };
63
+ }
64
+ savedReceiveAmount(record) {
65
+ const checked = (value) => {
66
+ try {
67
+ if (typeof value !== 'string' || amountRaw(value, 'RAW') !== value)
68
+ throw new Error();
69
+ return value;
70
+ }
71
+ catch {
72
+ throw new AttoError('INVALID_STATE', 'The saved receive amount is invalid.');
73
+ }
74
+ };
75
+ const candidate = record.amountAtomic === undefined ? undefined : checked(record.amountAtomic);
76
+ let completed;
77
+ if (record.result !== undefined) {
78
+ if (!record.result || typeof record.result !== 'object' || Array.isArray(record.result)) {
79
+ throw new AttoError('INVALID_STATE', 'The saved receive result is invalid.');
80
+ }
81
+ const amount = record.result.amount;
82
+ if (amount !== undefined) {
83
+ if (!amount || typeof amount !== 'object' || Array.isArray(amount)) {
84
+ throw new AttoError('INVALID_STATE', 'The saved receive amount is invalid.');
85
+ }
86
+ completed = checked(amount.raw);
87
+ }
88
+ }
89
+ if (candidate !== undefined && completed !== undefined && candidate !== completed) {
90
+ throw new AttoError('INVALID_STATE', 'The saved receive amounts disagree.');
91
+ }
92
+ return candidate ?? completed;
93
+ }
94
+ /** Older standalone records retain their shape; signed SEND history supplies missing metadata. */
95
+ async recoverReceiveAmount(hash, address) {
96
+ const unavailable = () => new AttoError('RECEIVE_RECOVERY_UNAVAILABLE', 'The original SEND amount is unavailable. Retry receive with the same incoming SEND hash; its candidate is unchanged.');
97
+ let source;
98
+ try {
99
+ source = await this.context.reader().transaction(hash);
100
+ }
101
+ catch (error) {
102
+ if (error instanceof AttoError && error.code === 'INVALID_NODE_RESPONSE') {
103
+ throw new AttoError('TRANSACTION_MISMATCH', 'The original SEND history is invalid.');
104
+ }
105
+ if (error instanceof AttoError && ['NODE_UNAVAILABLE', 'NODE_TIMEOUT', 'NODE_HTTP_ERROR', 'CANCELLED'].includes(error.code)) {
106
+ throw unavailable();
107
+ }
108
+ throw error;
109
+ }
110
+ if (!source)
111
+ throw unavailable();
112
+ const block = source.block;
113
+ if (source.hash.toString() !== hash || !await source.isValid() || !(block instanceof AttoSendBlock)
114
+ || block.network.name !== this.context.settings().network || block.receiverAddress.value !== address) {
115
+ throw new AttoError('TRANSACTION_MISMATCH', 'The original SEND does not match this receive.');
116
+ }
117
+ return amountRaw(block.amount.toString(), 'RAW');
118
+ }
119
+ async receive(request, automatic = false) {
120
+ if (automatic && !this.context.receivingAllowed())
121
+ throw new AttoError('AUTO_RECEIVE_DISABLED', 'Automatic receiving is stopping.');
122
+ const index = request.index ?? 0;
123
+ const operation = async () => {
124
+ await this.context.store.withWalletLock(async () => {
125
+ this.context.requireMcpWrite();
126
+ this.context.requireAccountAvailable(index);
127
+ this.requireReceivesResolved([index], request.hash.toUpperCase());
128
+ });
129
+ if (automatic && !this.context.settings().autoReceive)
130
+ throw new AttoError('AUTO_RECEIVE_DISABLED', 'Automatic receiving is disabled.');
131
+ const address = this.context.address(index, automatic);
132
+ const hash = request.hash.toUpperCase();
133
+ const key = `receive.${this.context.settings().network}.${hash}`;
134
+ const prior = this.context.store.get(key);
135
+ if (prior && prior.index !== index)
136
+ throw new AttoError('WRONG_RECEIVER', 'This receivable belongs to a different address.');
137
+ if (prior && this.context.internalMarketplaceReceiveSafety) {
138
+ const binding = this.privateReceiveBinding(prior, index, hash);
139
+ const savedAmount = this.savedReceiveAmount(prior);
140
+ let transaction;
141
+ if (prior.result) {
142
+ try {
143
+ transaction = AttoTransaction.fromJson(JSON.stringify(prior.result.transaction));
144
+ }
145
+ catch {
146
+ throw new AttoError('TRANSACTION_MISMATCH', 'The saved transaction does not match the original receive candidate.');
147
+ }
148
+ }
149
+ else {
150
+ try {
151
+ transaction = await this.context.reader().transaction(prior.blockHash);
152
+ }
153
+ catch {
154
+ transaction = null;
155
+ }
156
+ }
157
+ if (transaction) {
158
+ const block = transaction.block;
159
+ if (transaction.hash.toString() !== prior.blockHash || !await transaction.isValid()
160
+ || !(block instanceof AttoOpenBlock || block instanceof AttoReceiveBlock)
161
+ || block.address.value !== address.address || block.network.name !== this.context.settings().network || block.sendHash.toString() !== hash
162
+ || prior.result && (typeof prior.result.hash !== 'string'
163
+ || prior.result.hash.toUpperCase() !== prior.blockHash)) {
164
+ throw new AttoError('TRANSACTION_MISMATCH', 'The observed transaction does not match the original receive candidate.');
165
+ }
166
+ }
167
+ const amount = savedAmount ?? await this.recoverReceiveAmount(hash, address.address);
168
+ if (!transaction)
169
+ return { status: 'unknown', ...binding, amountAtomic: amount };
170
+ if (prior.result) {
171
+ return prior.result.amount === undefined
172
+ ? { ...prior.result, amount: amountOutput(amount) } : prior.result;
173
+ }
174
+ const result = { ...this.result(transaction, 'received'), index, amount: amountOutput(amount) };
175
+ this.context.store.set(key, { ...prior, result });
176
+ this.context.work.prepareConfirmed(transaction.block);
177
+ return result;
178
+ }
179
+ if (prior?.result)
180
+ return prior.result;
181
+ if (prior) {
182
+ const transaction = await this.context.reader().transaction(prior.blockHash);
183
+ if (transaction && transaction.hash.toString() === prior.blockHash && await transaction.isValid()) {
184
+ const result = this.result(transaction, 'received');
185
+ this.context.store.set(key, { ...prior, result });
186
+ this.context.work.prepareConfirmed(transaction.block);
187
+ return result;
188
+ }
189
+ // Refresh pending state below: an unconsumed send permits retrying receive
190
+ // against the current frontier without risking a second debit.
191
+ }
192
+ const receivable = await this.pendingReceivable(address.address, hash);
193
+ if (!receivable)
194
+ throw new AttoError('RECEIVABLE_NOT_PENDING', 'The payment is not pending for this address; it may already have been received.');
195
+ if (receivable.receiverAddress.value !== address.address)
196
+ throw new AttoError('WRONG_RECEIVER', 'The payment belongs to a different address.');
197
+ if (automatic && BigInt(receivable.amount.toString()) < BigInt(this.context.settings().minReceiveRaw)) {
198
+ throw new AttoError('RECEIVABLE_BELOW_MINIMUM', 'The payment is below the current automatic receiving minimum.');
199
+ }
200
+ const seed = await this.context.seed();
201
+ let wallet;
202
+ try {
203
+ const execution = await signingWallet(seed, index, this.context.settings(), async (block) => {
204
+ await this.context.store.withWalletLock(async () => {
205
+ this.context.requireMcpWrite();
206
+ this.context.requireAccountAvailable(index);
207
+ if (automatic && !this.context.settings().autoReceive)
208
+ throw new AttoError('AUTO_RECEIVE_DISABLED', 'Automatic receiving is disabled.');
209
+ this.context.store.set(key, { hash, index, blockHash: block.hash.toString(),
210
+ ...(this.context.internalMarketplaceReceiveSafety ? { sourceAddress: address.address, network: this.context.settings().network,
211
+ amountAtomic: receivable.amount.toString() } : {}) });
212
+ });
213
+ }, this.context.work.worker());
214
+ wallet = execution.wallet;
215
+ const transaction = await wallet.receive(receivable, parseAddress(request.representative ?? this.context.settings().representative), null);
216
+ const result = { ...this.result(transaction, 'received'), index, amount: amountOutput(receivable.amount.toString()) };
217
+ this.context.store.set(key, { hash, index, blockHash: transaction.hash.toString(), result,
218
+ ...(this.context.internalMarketplaceReceiveSafety ? { sourceAddress: address.address, network: this.context.settings().network,
219
+ amountAtomic: receivable.amount.toString() } : {}) });
220
+ this.context.work.prepareConfirmed(transaction.block);
221
+ return result;
222
+ }
223
+ catch (error) {
224
+ if (this.context.internalMarketplaceReceiveSafety) {
225
+ this.context.requireMcpWrite();
226
+ const candidate = this.context.store.get(key);
227
+ if (candidate && !candidate.result) {
228
+ const binding = this.privateReceiveBinding(candidate, index, hash);
229
+ const amount = this.savedReceiveAmount(candidate) ?? await this.recoverReceiveAmount(hash, address.address);
230
+ return { status: 'unknown', ...binding, amountAtomic: amount };
231
+ }
232
+ }
233
+ throw error;
234
+ }
235
+ finally {
236
+ wallet?.close();
237
+ seed.value.fill(0);
238
+ }
239
+ };
240
+ if (!automatic)
241
+ return this.context.store.withAccountLocks([index], operation);
242
+ // A busy account must not stall receiving for the rest of the wallet or
243
+ // prevent this session from stopping. The receiver will retry this item.
244
+ const release = this.context.store.tryAccountLocks([index]);
245
+ if (!release)
246
+ throw new AttoError('WALLET_BUSY', 'This account is busy. Automatic receiving will retry it.');
247
+ try {
248
+ return await operation();
249
+ }
250
+ finally {
251
+ release();
252
+ }
253
+ }
254
+ async receiveAll(input) {
255
+ const index = input.index ?? 0;
256
+ const address = this.context.address(index).address;
257
+ const list = await this.context.reader().list({ event: 'receivable', addresses: [address], limit: input.limit ?? 100, timeoutMs: input.timeoutMs ?? 2000 });
258
+ const results = [];
259
+ for (const item of list.items) {
260
+ results.push(await this.receive({ index, hash: item.hash, representative: input.representative }));
261
+ }
262
+ return { results, timedOut: list.timedOut, ...(list.limitReached ? { limitReached: true } : {}) };
263
+ }
264
+ }
@@ -7,6 +7,7 @@ export declare function derivedSigner(seed: AttoSeed, index: number): Promise<At
7
7
  export declare function signingWallet(seed: AttoSeed, index: number, settings: WalletSettings, beforeSign: (block: AttoBlock) => void | Promise<void>, suppliedWorker?: BlockWorker, retry?: SendRetry): Promise<{
8
8
  wallet: {
9
9
  sendByIndex(value: AttoKeyIndex, destination: AttoAddress, amount: AttoAmount, timestamp?: AttoInstant | null): Promise<AttoTransaction>;
10
+ prepareSendByIndex(value: AttoKeyIndex, destination: AttoAddress, amount: AttoAmount, timestamp?: AttoInstant | null): Promise<AttoTransaction>;
10
11
  receive(receivable: AttoReceivable, representative?: AttoAddress | null, timestamp?: AttoInstant | null): Promise<AttoTransaction>;
11
12
  change(value: AttoKeyIndex, representative: AttoAddress, timestamp?: AttoInstant | null): Promise<AttoTransaction>;
12
13
  getAccountByIndex(value: AttoKeyIndex): Promise<AttoAccount | null>;
@@ -49,28 +49,40 @@ export async function signingWallet(seed, index, settings, beforeSign, suppliedW
49
49
  throw new AttoError('ACCOUNT_NOT_OPEN', 'Receive funds to open this account before sending.');
50
50
  return account;
51
51
  }
52
- async function perform(build, timestamp) {
52
+ async function serialized(operation) {
53
53
  const previous = queue;
54
54
  let release;
55
55
  queue = new Promise(resolve => { release = resolve; });
56
56
  await previous;
57
57
  try {
58
- if (!signer)
59
- throw new AttoError('WALLET_CLOSED', 'This signing operation is closed.');
60
- const update = build((timestamp ?? await retryNetwork(() => client.now(), retry)).toString());
61
- const block = update.block;
62
- if (block.address.value !== address.value)
63
- throw new AttoError('ACCOUNT_MISMATCH', 'The constructed block belongs to a different wallet account.');
64
- if (block.network.name !== settings.network)
65
- throw new AttoError('NETWORK_MISMATCH', 'Account network differs from the configured wallet network.');
66
- if (!block.isValid())
67
- throw new AttoError('INVALID_TRANSACTION', 'The constructed transaction is invalid.');
68
- await beforeSign(block);
69
- const signature = await signer.signBlock(block);
70
- const work = await retryNetwork(() => suppliedWorker ? suppliedWorker.workBlock(block, retry?.signal) : worker.workBlock(block), retry);
71
- const transaction = new AttoTransaction(block, signature, work);
72
- if (!await transaction.isValid())
73
- throw new AttoError('INVALID_TRANSACTION', 'The signed transaction is invalid.');
58
+ return await operation();
59
+ }
60
+ finally {
61
+ release();
62
+ }
63
+ }
64
+ async function prepareTransaction(build, timestamp) {
65
+ if (!signer)
66
+ throw new AttoError('WALLET_CLOSED', 'This signing operation is closed.');
67
+ const update = build((timestamp ?? await retryNetwork(() => client.now(), retry)).toString());
68
+ const block = update.block;
69
+ if (block.address.value !== address.value)
70
+ throw new AttoError('ACCOUNT_MISMATCH', 'The constructed block belongs to a different wallet account.');
71
+ if (block.network.name !== settings.network)
72
+ throw new AttoError('NETWORK_MISMATCH', 'Account network differs from the configured wallet network.');
73
+ if (!block.isValid())
74
+ throw new AttoError('INVALID_TRANSACTION', 'The constructed transaction is invalid.');
75
+ await beforeSign(block);
76
+ const signature = await signer.signBlock(block);
77
+ const work = await retryNetwork(() => suppliedWorker ? suppliedWorker.workBlock(block, retry?.signal) : worker.workBlock(block), retry);
78
+ const transaction = new AttoTransaction(block, signature, work);
79
+ if (!await transaction.isValid())
80
+ throw new AttoError('INVALID_TRANSACTION', 'The signed transaction is invalid.');
81
+ return { update, block, transaction };
82
+ }
83
+ async function perform(build, timestamp) {
84
+ return serialized(async () => {
85
+ const { update, block, transaction } = await prepareTransaction(build, timestamp);
74
86
  let attempted = false;
75
87
  await retryNetwork(async () => {
76
88
  if (attempted) {
@@ -93,10 +105,10 @@ export async function signingWallet(seed, index, settings, beforeSign, suppliedW
93
105
  }, retry);
94
106
  account = update.account;
95
107
  return transaction;
96
- }
97
- finally {
98
- release();
99
- }
108
+ });
109
+ }
110
+ async function prepareOnly(build, timestamp) {
111
+ return serialized(async () => (await prepareTransaction(build, timestamp)).transaction);
100
112
  }
101
113
  // Commons' wallet builder calls its private Kotlin worker interface directly.
102
114
  // Compose its public block, signing, validation, and publication APIs so the
@@ -106,6 +118,10 @@ export async function signingWallet(seed, index, settings, beforeSign, suppliedW
106
118
  requireIndex(value);
107
119
  return perform(time => attoAccountSend(requireAccount(), destination, amount, time), timestamp);
108
120
  },
121
+ async prepareSendByIndex(value, destination, amount, timestamp) {
122
+ requireIndex(value);
123
+ return prepareOnly(time => attoAccountSend(requireAccount(), destination, amount, time), timestamp);
124
+ },
109
125
  async receive(receivable, representative, timestamp) {
110
126
  if (receivable.receiverAddress.value !== address.value)
111
127
  throw new AttoError('WRONG_RECEIVER', 'The payment belongs to a different address.');
@@ -20,6 +20,7 @@ export interface AccountPool {
20
20
  export interface WalletSettings {
21
21
  network: NetworkName;
22
22
  nodeUrl: string;
23
+ nodeBatchSize?: number | null;
23
24
  workerUrl: string;
24
25
  representative: string;
25
26
  autoReceive: boolean;