openclaw-messagebox-plugin 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +44 -5
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +85 -14
  4. package/dist/index.js.map +1 -1
  5. package/dist/src/client.d.ts +11 -4
  6. package/dist/src/client.d.ts.map +1 -1
  7. package/dist/src/client.js +94 -13
  8. package/dist/src/client.js.map +1 -1
  9. package/dist/src/core/config.d.ts +12 -0
  10. package/dist/src/core/config.d.ts.map +1 -0
  11. package/dist/src/core/config.js +14 -0
  12. package/dist/src/core/config.js.map +1 -0
  13. package/dist/src/core/index.d.ts +26 -0
  14. package/dist/src/core/index.d.ts.map +1 -0
  15. package/dist/src/core/index.js +27 -0
  16. package/dist/src/core/index.js.map +1 -0
  17. package/dist/src/core/payment.d.ts +17 -0
  18. package/dist/src/core/payment.d.ts.map +1 -0
  19. package/dist/src/core/payment.js +95 -0
  20. package/dist/src/core/payment.js.map +1 -0
  21. package/dist/src/core/types.d.ts +95 -0
  22. package/dist/src/core/types.d.ts.map +1 -0
  23. package/dist/src/core/types.js +5 -0
  24. package/dist/src/core/types.js.map +1 -0
  25. package/dist/src/core/verify.d.ts +29 -0
  26. package/dist/src/core/verify.d.ts.map +1 -0
  27. package/dist/src/core/verify.js +105 -0
  28. package/dist/src/core/verify.js.map +1 -0
  29. package/dist/src/core/wallet.d.ts +100 -0
  30. package/dist/src/core/wallet.d.ts.map +1 -0
  31. package/dist/src/core/wallet.js +225 -0
  32. package/dist/src/core/wallet.js.map +1 -0
  33. package/index.ts +95 -14
  34. package/openclaw.plugin.json +3 -2
  35. package/package.json +7 -6
  36. package/src/client.ts +106 -14
  37. package/src/core/config.d.ts +12 -0
  38. package/src/core/config.ts +21 -0
  39. package/src/core/index.ts +42 -0
  40. package/src/core/payment.d.ts +17 -0
  41. package/src/core/payment.ts +111 -0
  42. package/src/core/types.d.ts +95 -0
  43. package/src/core/types.ts +102 -0
  44. package/src/core/verify.d.ts +29 -0
  45. package/src/core/verify.ts +119 -0
  46. package/src/core/wallet.d.ts +100 -0
  47. package/src/core/wallet.ts +289 -0
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @a2a-bsv/core — Type definitions for agent-to-agent BSV payments.
3
+ */
4
+
5
+ /** Wallet configuration for creating or loading an agent wallet. */
6
+ export interface WalletConfig {
7
+ /** BSV network to use. */
8
+ network: 'mainnet' | 'testnet';
9
+ /** Directory path for SQLite wallet persistence. */
10
+ storageDir: string;
11
+ /** Optional: pre-existing root private key hex. If omitted on create(), a new one is generated. */
12
+ rootKeyHex?: string;
13
+ /** Optional TAAL API key for ARC broadcasting. Falls back to public default. */
14
+ taalApiKey?: string;
15
+ /** Optional fee model in sat/KB. Falls back to BSV_FEE_MODEL env var or default 100 sat/KB. */
16
+ feeModel?: number;
17
+ }
18
+
19
+ /** Parameters for building a payment transaction. */
20
+ export interface PaymentParams {
21
+ /** Recipient's compressed public key (hex) or BSV address. */
22
+ to: string;
23
+ /** Amount to pay in satoshis. */
24
+ satoshis: number;
25
+ /** Human-readable description (5-50 chars per BRC-100). */
26
+ description?: string;
27
+ /** Optional metadata embedded as OP_RETURN (future use). */
28
+ metadata?: {
29
+ taskId?: string;
30
+ protocol?: string;
31
+ };
32
+ }
33
+
34
+ /** Result from building a payment. */
35
+ export interface PaymentResult {
36
+ /** Base64-encoded Atomic BEEF transaction data. */
37
+ beef: string;
38
+ /** Transaction ID (hex). */
39
+ txid: string;
40
+ /** Amount paid in satoshis. */
41
+ satoshis: number;
42
+ /** BRC-29 derivation prefix (base64). Needed by recipient to internalize. */
43
+ derivationPrefix: string;
44
+ /** BRC-29 derivation suffix (base64). Needed by recipient to internalize. */
45
+ derivationSuffix: string;
46
+ /** Sender's identity key (compressed hex). Needed by recipient to internalize. */
47
+ senderIdentityKey: string;
48
+ }
49
+
50
+ /** Parameters for verifying an incoming payment. */
51
+ export interface VerifyParams {
52
+ /** Base64-encoded Atomic BEEF data. */
53
+ beef: string;
54
+ /** Expected payment amount in satoshis. */
55
+ expectedAmount?: number;
56
+ /** Expected sender identity key (optional). */
57
+ expectedSender?: string;
58
+ }
59
+
60
+ /** Result from verifying a payment. */
61
+ export interface VerifyResult {
62
+ /** Whether the payment passes all checks. */
63
+ valid: boolean;
64
+ /** Transaction ID (hex). */
65
+ txid: string;
66
+ /** Number of outputs found in the transaction. */
67
+ outputCount: number;
68
+ /** Errors encountered during verification. */
69
+ errors: string[];
70
+ }
71
+
72
+ /** Parameters for accepting (internalizing) a verified payment. */
73
+ export interface AcceptParams {
74
+ /** Base64-encoded Atomic BEEF data. */
75
+ beef: string;
76
+ /** The output index to internalize (default: 0). */
77
+ vout?: number;
78
+ /** BRC-29 derivation prefix from the PaymentResult. */
79
+ derivationPrefix: string;
80
+ /** BRC-29 derivation suffix from the PaymentResult. */
81
+ derivationSuffix: string;
82
+ /** Sender's identity key from the PaymentResult. */
83
+ senderIdentityKey: string;
84
+ /** Human-readable description for wallet records (5-50 chars). */
85
+ description?: string;
86
+ }
87
+
88
+ /** Result from accepting a payment. */
89
+ export interface AcceptResult {
90
+ /** Whether the payment was accepted. */
91
+ accepted: boolean;
92
+ }
93
+
94
+ /** Serializable wallet identity info, persisted alongside the SQLite database. */
95
+ export interface WalletIdentity {
96
+ /** The root private key (hex). Guard this carefully. */
97
+ rootKeyHex: string;
98
+ /** The wallet's public identity key (compressed hex). */
99
+ identityKey: string;
100
+ /** Network this wallet targets. */
101
+ network: 'mainnet' | 'testnet';
102
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @a2a-bsv/core — Payment verification and acceptance helpers.
3
+ *
4
+ * Verification: parse the Atomic BEEF, validate structure.
5
+ * Acceptance: internalize the payment into the recipient wallet via BRC-29
6
+ * wallet payment protocol.
7
+ */
8
+ import type { SetupWallet } from '@bsv/wallet-toolbox';
9
+ import type { VerifyParams, VerifyResult, AcceptParams, AcceptResult } from './types.js';
10
+ /**
11
+ * Verify an incoming Atomic BEEF payment.
12
+ *
13
+ * This performs structural validation:
14
+ * - Decodes the base64 BEEF
15
+ * - Checks the BEEF is parseable
16
+ * - Checks there is at least one transaction
17
+ * - Runs SPV verification via tx.verify()
18
+ * - Optionally checks the sender identity key
19
+ */
20
+ export declare function verifyPayment(params: VerifyParams): Promise<VerifyResult>;
21
+ /**
22
+ * Accept (internalize) a verified BRC-29 payment into the recipient's wallet.
23
+ *
24
+ * This calls wallet.internalizeAction with the 'wallet payment' protocol,
25
+ * providing the BRC-29 derivation info so the wallet can derive the correct
26
+ * key and claim the output.
27
+ */
28
+ export declare function acceptPayment(setup: SetupWallet, params: AcceptParams): Promise<AcceptResult>;
29
+ //# sourceMappingURL=verify.d.ts.map
@@ -0,0 +1,119 @@
1
+ /**
2
+ * @a2a-bsv/core — Payment verification and acceptance helpers.
3
+ *
4
+ * Verification: parse the Atomic BEEF, validate structure.
5
+ * Acceptance: internalize the payment into the recipient wallet via BRC-29
6
+ * wallet payment protocol.
7
+ */
8
+
9
+ import { Beef, Utils } from '@bsv/sdk';
10
+ import type { SetupWallet } from '@bsv/wallet-toolbox';
11
+ import type { VerifyParams, VerifyResult, AcceptParams, AcceptResult } from './types.js';
12
+ import type { InternalizeActionArgs } from '@bsv/sdk';
13
+
14
+ /**
15
+ * Verify an incoming Atomic BEEF payment.
16
+ *
17
+ * This performs structural validation:
18
+ * - Decodes the base64 BEEF
19
+ * - Checks the BEEF is parseable
20
+ * - Checks there is at least one transaction
21
+ * - Runs SPV verification via tx.verify()
22
+ * - Optionally checks the sender identity key
23
+ */
24
+ export async function verifyPayment(params: VerifyParams): Promise<VerifyResult> {
25
+ const errors: string[] = [];
26
+ let txid = '';
27
+ let outputCount = 0;
28
+
29
+ try {
30
+ const binary = Utils.toArray(params.beef, 'base64');
31
+ const beef = Beef.fromBinary(binary);
32
+
33
+ if (beef.txs.length === 0) {
34
+ errors.push('BEEF contains no transactions');
35
+ } else {
36
+ const lastTx = beef.txs[beef.txs.length - 1];
37
+ txid = lastTx.txid;
38
+
39
+ // Parse the atomic transaction to count outputs
40
+ const tx = beef.findAtomicTransaction(txid);
41
+ if (tx) {
42
+ outputCount = tx.outputs.length;
43
+
44
+ // Run SPV verification
45
+ try {
46
+ await tx.verify();
47
+ } catch (err: unknown) {
48
+ const message = err instanceof Error ? err.message : String(err);
49
+ errors.push(`SPV verification failed: ${message}`);
50
+ }
51
+ } else {
52
+ errors.push('Could not find atomic transaction in BEEF');
53
+ }
54
+ }
55
+
56
+ } catch (err: unknown) {
57
+ const message = err instanceof Error ? err.message : String(err);
58
+ errors.push(`BEEF parse error: ${message}`);
59
+ }
60
+
61
+ // Sender validation is independent of BEEF parsing
62
+ if (params.expectedSender) {
63
+ if (!/^0[23][0-9a-fA-F]{64}$/.test(params.expectedSender)) {
64
+ errors.push('expectedSender is not a valid compressed public key');
65
+ }
66
+ }
67
+
68
+ return {
69
+ valid: errors.length === 0,
70
+ txid,
71
+ outputCount,
72
+ errors,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Accept (internalize) a verified BRC-29 payment into the recipient's wallet.
78
+ *
79
+ * This calls wallet.internalizeAction with the 'wallet payment' protocol,
80
+ * providing the BRC-29 derivation info so the wallet can derive the correct
81
+ * key and claim the output.
82
+ */
83
+ export async function acceptPayment(
84
+ setup: SetupWallet,
85
+ params: AcceptParams,
86
+ ): Promise<AcceptResult> {
87
+ const desc = normalizeDescription(params.description ?? 'received payment');
88
+ const vout = params.vout ?? 0;
89
+
90
+ const binary = Utils.toArray(params.beef, 'base64');
91
+
92
+ const args: InternalizeActionArgs = {
93
+ tx: binary,
94
+ outputs: [
95
+ {
96
+ outputIndex: vout,
97
+ protocol: 'wallet payment',
98
+ paymentRemittance: {
99
+ derivationPrefix: params.derivationPrefix,
100
+ derivationSuffix: params.derivationSuffix,
101
+ senderIdentityKey: params.senderIdentityKey,
102
+ },
103
+ },
104
+ ],
105
+ description: desc,
106
+ };
107
+
108
+ const result = await setup.wallet.internalizeAction(args);
109
+
110
+ return {
111
+ accepted: result.accepted,
112
+ };
113
+ }
114
+
115
+ function normalizeDescription(desc: string): string {
116
+ if (desc.length < 5) return desc.padEnd(5, ' ');
117
+ if (desc.length > 50) return desc.slice(0, 50);
118
+ return desc;
119
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @a2a-bsv/core — BSVAgentWallet
3
+ *
4
+ * High-level wallet class for AI agent-to-agent BSV payments.
5
+ * Wraps @bsv/wallet-toolbox's Wallet + StorageKnex with a clean,
6
+ * minimal API surface designed for automated agent use.
7
+ */
8
+ import type { SetupWallet } from '@bsv/wallet-toolbox';
9
+ import type { WalletConfig, PaymentParams, PaymentResult, VerifyParams, VerifyResult, AcceptParams, AcceptResult } from './types.js';
10
+ /**
11
+ * BSVAgentWallet — the primary class for agent-to-agent BSV payments.
12
+ *
13
+ * Usage:
14
+ * ```ts
15
+ * // Create a new wallet (generates keys)
16
+ * const wallet = await BSVAgentWallet.load({ network: 'testnet', storageDir: './agent-wallet' });
17
+ *
18
+ * // Load an existing wallet
19
+ * const wallet = await BSVAgentWallet.load({ network: 'testnet', storageDir: './agent-wallet' });
20
+ *
21
+ * // Make a payment
22
+ * const payment = await wallet.createPayment({ to: recipientPubKey, satoshis: 500 });
23
+ *
24
+ * // Verify and accept a payment
25
+ * const verification = wallet.verifyPayment({ beef: payment.beef });
26
+ * if (verification.valid) {
27
+ * await wallet.acceptPayment({ beef: payment.beef, ...derivationInfo });
28
+ * }
29
+ * ```
30
+ */
31
+ export declare class BSVAgentWallet {
32
+ /** @internal — exposed for advanced operations (e.g. direct internalizeAction) */
33
+ readonly _setup: SetupWallet;
34
+ private constructor();
35
+ /**
36
+ * Create a new agent wallet. Generates a fresh root key and persists it.
37
+ * The SQLite database and identity file are written to `config.storageDir`.
38
+ */
39
+ private static create;
40
+ /**
41
+ * Load an existing agent wallet from its storage directory.
42
+ * Reads the persisted identity file and re-initializes the wallet.
43
+ */
44
+ static load(config: WalletConfig): Promise<BSVAgentWallet>;
45
+ /**
46
+ * Get this wallet's public identity key (compressed hex, 33 bytes).
47
+ * This is the key other agents use to send payments to you.
48
+ */
49
+ getIdentityKey(): Promise<string>;
50
+ /**
51
+ * Get the wallet's current balance in satoshis.
52
+ *
53
+ * Uses the BRC-100 wallet's balance method which sums spendable outputs
54
+ * in the default basket.
55
+ */
56
+ getBalance(): Promise<number>;
57
+ /**
58
+ * Cleanly shut down the wallet, releasing database connections and
59
+ * stopping the background monitor.
60
+ */
61
+ destroy(): Promise<void>;
62
+ /**
63
+ * Build a BRC-29 payment to another agent.
64
+ *
65
+ * The transaction is created with `noSend: true` — the sender does NOT
66
+ * broadcast it. Instead, the Atomic BEEF and derivation metadata are
67
+ * returned so they can be transmitted to the recipient, who will
68
+ * verify and internalize (broadcast) the payment.
69
+ *
70
+ * @param params.to — Recipient's compressed public key (hex).
71
+ * @param params.satoshis — Amount in satoshis.
72
+ * @param params.description — Optional human-readable note.
73
+ */
74
+ createPayment(params: PaymentParams): Promise<PaymentResult>;
75
+ /**
76
+ * Verify an incoming Atomic BEEF payment.
77
+ *
78
+ * This performs structural validation and SPV verification via tx.verify().
79
+ */
80
+ verifyPayment(params: VerifyParams): Promise<VerifyResult>;
81
+ /**
82
+ * Accept (internalize) a verified payment into this wallet.
83
+ *
84
+ * Uses the BRC-29 wallet payment protocol to derive the correct key
85
+ * and claim the output. This triggers SPV verification and, if the
86
+ * transaction hasn't been broadcast yet, broadcasts it.
87
+ */
88
+ acceptPayment(params: AcceptParams): Promise<AcceptResult>;
89
+ /** Get the underlying wallet-toolbox SetupWallet for advanced operations. */
90
+ getSetup(): SetupWallet;
91
+ /**
92
+ * Internal: manually construct a BRC-100 wallet backed by SQLite.
93
+ *
94
+ * We build this by hand instead of using Setup.createWalletSQLite because
95
+ * the toolbox has a bug where its internal randomBytesHex is a stub.
96
+ * We use the same components but wire them up correctly.
97
+ */
98
+ private static buildSetup;
99
+ }
100
+ //# sourceMappingURL=wallet.d.ts.map
@@ -0,0 +1,289 @@
1
+ /**
2
+ * @a2a-bsv/core — BSVAgentWallet
3
+ *
4
+ * High-level wallet class for AI agent-to-agent BSV payments.
5
+ * Wraps @bsv/wallet-toolbox's Wallet + StorageKnex with a clean,
6
+ * minimal API surface designed for automated agent use.
7
+ */
8
+
9
+ import { PrivateKey, CachedKeyDeriver } from '@bsv/sdk';
10
+ import {
11
+ Wallet,
12
+ WalletStorageManager,
13
+ Services,
14
+ Monitor,
15
+ StorageKnex,
16
+ randomBytesHex,
17
+ ChaintracksServiceClient,
18
+ } from '@bsv/wallet-toolbox';
19
+ import type { SetupWallet } from '@bsv/wallet-toolbox';
20
+ import knexLib from 'knex';
21
+ import * as path from 'node:path';
22
+ import * as fs from 'node:fs';
23
+
24
+ import type {
25
+ WalletConfig,
26
+ WalletIdentity,
27
+ PaymentParams,
28
+ PaymentResult,
29
+ VerifyParams,
30
+ VerifyResult,
31
+ AcceptParams,
32
+ AcceptResult,
33
+ } from './types.js';
34
+ import { toChain, DEFAULT_TAAL_API_KEYS, DEFAULT_DB_NAME } from './config.js';
35
+ import { buildPayment } from './payment.js';
36
+ import { verifyPayment, acceptPayment } from './verify.js';
37
+
38
+ /** Filename for the persisted wallet identity JSON. */
39
+ const IDENTITY_FILE = 'wallet-identity.json';
40
+
41
+ /**
42
+ * BSVAgentWallet — the primary class for agent-to-agent BSV payments.
43
+ *
44
+ * Usage:
45
+ * ```ts
46
+ * // Create a new wallet (generates keys)
47
+ * const wallet = await BSVAgentWallet.load({ network: 'testnet', storageDir: './agent-wallet' });
48
+ *
49
+ * // Load an existing wallet
50
+ * const wallet = await BSVAgentWallet.load({ network: 'testnet', storageDir: './agent-wallet' });
51
+ *
52
+ * // Make a payment
53
+ * const payment = await wallet.createPayment({ to: recipientPubKey, satoshis: 500 });
54
+ *
55
+ * // Verify and accept a payment
56
+ * const verification = wallet.verifyPayment({ beef: payment.beef });
57
+ * if (verification.valid) {
58
+ * await wallet.acceptPayment({ beef: payment.beef, ...derivationInfo });
59
+ * }
60
+ * ```
61
+ */
62
+ export class BSVAgentWallet {
63
+ /** @internal — exposed for advanced operations (e.g. direct internalizeAction) */
64
+ public readonly _setup: SetupWallet;
65
+
66
+ private constructor(setup: SetupWallet) {
67
+ this._setup = setup;
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Factory methods
72
+ // ---------------------------------------------------------------------------
73
+
74
+ /**
75
+ * Create a new agent wallet. Generates a fresh root key and persists it.
76
+ * The SQLite database and identity file are written to `config.storageDir`.
77
+ */
78
+ private static async create(config: WalletConfig): Promise<BSVAgentWallet> {
79
+ // Generate a new root key (or use one provided in config)
80
+ const rootKeyHex = config.rootKeyHex ?? PrivateKey.fromRandom().toHex();
81
+ const rootKey = PrivateKey.fromHex(rootKeyHex);
82
+ const identityKey = rootKey.toPublicKey().toString();
83
+
84
+ // Ensure the storage directory exists
85
+ fs.mkdirSync(config.storageDir, { recursive: true });
86
+
87
+ // Persist identity for later loading
88
+ const identity: WalletIdentity = {
89
+ rootKeyHex,
90
+ identityKey,
91
+ network: config.network,
92
+ };
93
+ const identityPath = path.join(config.storageDir, IDENTITY_FILE);
94
+ fs.writeFileSync(identityPath, JSON.stringify(identity, null, 2), 'utf-8');
95
+
96
+ // Build the wallet
97
+ const setup = await BSVAgentWallet.buildSetup(config, rootKeyHex);
98
+
99
+ return new BSVAgentWallet(setup);
100
+ }
101
+
102
+ /**
103
+ * Load an existing agent wallet from its storage directory.
104
+ * Reads the persisted identity file and re-initializes the wallet.
105
+ */
106
+ static async load(config: WalletConfig): Promise<BSVAgentWallet> {
107
+ const identityPath = path.join(config.storageDir, IDENTITY_FILE);
108
+ if (!fs.existsSync(identityPath)) {
109
+ return this.create(config);
110
+ }
111
+
112
+ const identity: WalletIdentity = JSON.parse(
113
+ fs.readFileSync(identityPath, 'utf-8'),
114
+ );
115
+
116
+ const rootKeyHex = config.rootKeyHex ?? identity.rootKeyHex;
117
+ const setup = await BSVAgentWallet.buildSetup(config, rootKeyHex);
118
+
119
+ return new BSVAgentWallet(setup);
120
+ }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Wallet lifecycle
124
+ // ---------------------------------------------------------------------------
125
+
126
+ /**
127
+ * Get this wallet's public identity key (compressed hex, 33 bytes).
128
+ * This is the key other agents use to send payments to you.
129
+ */
130
+ async getIdentityKey(): Promise<string> {
131
+ return this._setup.identityKey;
132
+ }
133
+
134
+ /**
135
+ * Get the wallet's current balance in satoshis.
136
+ *
137
+ * Uses the BRC-100 wallet's balance method which sums spendable outputs
138
+ * in the default basket.
139
+ */
140
+ async getBalance(): Promise<number> {
141
+ return await this._setup.wallet.balance();
142
+ }
143
+
144
+ /**
145
+ * Cleanly shut down the wallet, releasing database connections and
146
+ * stopping the background monitor.
147
+ */
148
+ async destroy(): Promise<void> {
149
+ await this._setup.wallet.destroy();
150
+ }
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // Payment creation (sender/payer side)
154
+ // ---------------------------------------------------------------------------
155
+
156
+ /**
157
+ * Build a BRC-29 payment to another agent.
158
+ *
159
+ * The transaction is created with `noSend: true` — the sender does NOT
160
+ * broadcast it. Instead, the Atomic BEEF and derivation metadata are
161
+ * returned so they can be transmitted to the recipient, who will
162
+ * verify and internalize (broadcast) the payment.
163
+ *
164
+ * @param params.to — Recipient's compressed public key (hex).
165
+ * @param params.satoshis — Amount in satoshis.
166
+ * @param params.description — Optional human-readable note.
167
+ */
168
+ async createPayment(params: PaymentParams): Promise<PaymentResult> {
169
+ return buildPayment(this._setup, params);
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Payment verification & acceptance (receiver/merchant side)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * Verify an incoming Atomic BEEF payment.
178
+ *
179
+ * This performs structural validation and SPV verification via tx.verify().
180
+ */
181
+ async verifyPayment(params: VerifyParams): Promise<VerifyResult> {
182
+ return await verifyPayment(params);
183
+ }
184
+
185
+ /**
186
+ * Accept (internalize) a verified payment into this wallet.
187
+ *
188
+ * Uses the BRC-29 wallet payment protocol to derive the correct key
189
+ * and claim the output. This triggers SPV verification and, if the
190
+ * transaction hasn't been broadcast yet, broadcasts it.
191
+ */
192
+ async acceptPayment(params: AcceptParams): Promise<AcceptResult> {
193
+ return acceptPayment(this._setup, params);
194
+ }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // Access to underlying toolbox objects (for advanced use)
198
+ // ---------------------------------------------------------------------------
199
+
200
+ /** Get the underlying wallet-toolbox SetupWallet for advanced operations. */
201
+ getSetup(): SetupWallet {
202
+ return this._setup;
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Private helpers
207
+ // ---------------------------------------------------------------------------
208
+
209
+ /**
210
+ * Internal: manually construct a BRC-100 wallet backed by SQLite.
211
+ *
212
+ * We build this by hand instead of using Setup.createWalletSQLite because
213
+ * the toolbox has a bug where its internal randomBytesHex is a stub.
214
+ * We use the same components but wire them up correctly.
215
+ */
216
+ private static async buildSetup(
217
+ config: WalletConfig,
218
+ rootKeyHex: string,
219
+ ): Promise<SetupWallet> {
220
+ const chain = toChain(config.network);
221
+ const taalApiKey = config.taalApiKey ?? DEFAULT_TAAL_API_KEYS[chain];
222
+
223
+ const rootKey = PrivateKey.fromHex(rootKeyHex);
224
+ const identityKey = rootKey.toPublicKey().toString();
225
+
226
+ // 1. Key derivation
227
+ const keyDeriver = new CachedKeyDeriver(rootKey);
228
+
229
+ // 2. Storage manager (empty initially)
230
+ const storage = new WalletStorageManager(identityKey);
231
+
232
+ // 3. Network services (ARC broadcasting, chain tracking, etc.)
233
+ const serviceOptions = Services.createDefaultOptions(chain);
234
+ const chaintracksUrl = process.env.BSV_CHAINTRACKS_URL || 'https://chaintracks-us-1.bsvb.tech';
235
+ const arcUrl = process.env.BSV_ARC_URL;
236
+
237
+ serviceOptions.chaintracks = new ChaintracksServiceClient(chain, chaintracksUrl);
238
+ if (arcUrl) {
239
+ serviceOptions.arcUrl = arcUrl;
240
+ }
241
+
242
+ serviceOptions.taalApiKey = taalApiKey;
243
+ const services = new Services(serviceOptions);
244
+
245
+ // 4. Background monitor
246
+ const monopts = Monitor.createDefaultWalletMonitorOptions(chain, storage, services);
247
+ const monitor = new Monitor(monopts);
248
+ monitor.addDefaultTasks();
249
+
250
+ // 5. The BRC-100 Wallet
251
+ const wallet = new Wallet({ chain, keyDeriver, storage, services, monitor });
252
+
253
+ // 6. SQLite storage via knex
254
+ const filePath = path.join(config.storageDir, `${DEFAULT_DB_NAME}.sqlite`);
255
+ const knex = knexLib({
256
+ client: 'sqlite3',
257
+ connection: { filename: filePath },
258
+ useNullAsDefault: true,
259
+ });
260
+
261
+ // Fee model: configurable via BSV_FEE_MODEL env var (default: 100 sat/KB)
262
+ const feeModelValue = config.feeModel ??
263
+ (process.env.BSV_FEE_MODEL ? parseInt(process.env.BSV_FEE_MODEL, 10) : 100);
264
+
265
+ const activeStorage = new StorageKnex({
266
+ chain,
267
+ knex,
268
+ commissionSatoshis: 0,
269
+ commissionPubKeyHex: undefined,
270
+ feeModel: { model: 'sat/kb', value: feeModelValue },
271
+ });
272
+
273
+ await activeStorage.migrate(DEFAULT_DB_NAME, randomBytesHex(33));
274
+ await activeStorage.makeAvailable();
275
+ await storage.addWalletStorageProvider(activeStorage);
276
+ await activeStorage.findOrInsertUser(identityKey);
277
+
278
+ return {
279
+ rootKey,
280
+ identityKey,
281
+ keyDeriver,
282
+ chain,
283
+ storage,
284
+ services,
285
+ monitor,
286
+ wallet,
287
+ };
288
+ }
289
+ }