@attocash/cli 0.5.0 → 0.7.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.
- package/dist/application/app.d.ts +3 -1
- package/dist/application/app.js +23 -19
- package/dist/application/operations.d.ts +0 -1
- package/dist/application/operations.js +1 -7
- package/dist/cli/cli.js +4 -21
- package/dist/internal-marketplace.d.ts +2 -11
- package/dist/internal-marketplace.js +6 -13
- package/dist/marketplace/approval-preview.js +5 -20
- package/dist/marketplace/connection.d.ts +43 -0
- package/dist/marketplace/{topups.js → connection.js} +18 -213
- package/dist/marketplace/proof-approval.d.ts +1 -1
- package/dist/marketplace/proof-approval.js +10 -119
- package/dist/marketplace/relay.d.ts +58 -0
- package/dist/marketplace/relay.js +122 -0
- package/dist/marketplace/strict-json.d.ts +2 -0
- package/dist/marketplace/strict-json.js +96 -0
- package/dist/spending/atto-x402.d.ts +2 -0
- package/dist/spending/atto-x402.js +1 -1
- package/dist/spending/journal.d.ts +9 -0
- package/dist/spending/journal.js +11 -0
- package/dist/spending/ledger.d.ts +11 -3
- package/dist/spending/ledger.js +42 -7
- package/dist/spending/payments.d.ts +9 -36
- package/dist/spending/payments.js +253 -817
- package/dist/wallet/signing.d.ts +3 -1
- package/dist/wallet/signing.js +25 -17
- package/package.json +1 -1
- package/dist/marketplace/topups.d.ts +0 -82
|
@@ -2,17 +2,18 @@ import { bindDestination } from './destination.js';
|
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
4
|
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
-
import {
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { AttoAmount, AttoOpenBlock, AttoReceiveBlock, AttoSendBlock, AttoSignature, AttoTransaction, AttoUnit, toAttoIndex, } from '@attocash/commons-core';
|
|
6
7
|
import { amountOutput, amountRaw } from '../domain/amount.js';
|
|
7
8
|
import { AttoError } from '../domain/errors.js';
|
|
8
9
|
import { NodeReader, parseAddress, publicModel } from '../network/reader.js';
|
|
9
10
|
import { retryNetwork } from '../network/retry.js';
|
|
10
11
|
import { marketTerms } from '../pricing/terms.js';
|
|
11
|
-
import { derivedSigner, signingWallet } from '../wallet/signing.js';
|
|
12
|
+
import { derivedSigner, signingWallet, publishTransaction } from '../wallet/signing.js';
|
|
12
13
|
import { planPayment } from './pool.js';
|
|
13
14
|
import { reconcileBlock, reconcileSend } from './reconcile.js';
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
15
|
+
import { wireTransaction } from './atto-x402.js';
|
|
16
|
+
import { parseRelayOffer, relayPaymentPayload, relayProofFromHeader, validateRelayProof } from '../marketplace/relay.js';
|
|
16
17
|
const MARKETPLACE_INTENT_SWEEP_TIMEOUT_MS = 1_000;
|
|
17
18
|
const MARKETPLACE_INTENT_SWEEP_CONCURRENCY = 16;
|
|
18
19
|
/** Owns payment selection, reservations, publication and recovery as one workflow. */
|
|
@@ -24,9 +25,7 @@ export class Payments {
|
|
|
24
25
|
work;
|
|
25
26
|
retry;
|
|
26
27
|
onDestination;
|
|
27
|
-
|
|
28
|
-
internalMarketplacePayment;
|
|
29
|
-
constructor(store, ledger, wallet, market, work, retry, onDestination, topUps, internalMarketplacePayment) {
|
|
28
|
+
constructor(store, ledger, wallet, market, work, retry, onDestination) {
|
|
30
29
|
this.store = store;
|
|
31
30
|
this.ledger = ledger;
|
|
32
31
|
this.wallet = wallet;
|
|
@@ -34,8 +33,6 @@ export class Payments {
|
|
|
34
33
|
this.work = work;
|
|
35
34
|
this.retry = retry;
|
|
36
35
|
this.onDestination = onDestination;
|
|
37
|
-
this.topUps = topUps;
|
|
38
|
-
this.internalMarketplacePayment = internalMarketplacePayment;
|
|
39
36
|
}
|
|
40
37
|
reader() { return new NodeReader(this.wallet.settings()); }
|
|
41
38
|
indexes(record) { return record.plan?.indexes ?? [record.index]; }
|
|
@@ -75,776 +72,13 @@ export class Payments {
|
|
|
75
72
|
if (record.plan?.steps.length && !pool.consolidate)
|
|
76
73
|
throw new AttoError('CONSOLIDATION_REQUIRED', 'Approve consolidation before continuing this payment.');
|
|
77
74
|
}
|
|
78
|
-
async marketplaceTopUp(request) {
|
|
79
|
-
const previous = typeof request.requestId === 'string' ? this.ledger.get(request.requestId) : undefined;
|
|
80
|
-
if (previous && this.isLegacyCreditedMarketplaceTopUp(previous)) {
|
|
81
|
-
const raw = amountRaw(request.amount, request.unit);
|
|
82
|
-
if (raw !== previous.raw || (request.index !== undefined && request.index !== previous.index)) {
|
|
83
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a different historical Marketplace payment.');
|
|
84
|
-
}
|
|
85
|
-
return this.legacyMarketplaceTopUpResult(previous);
|
|
86
|
-
}
|
|
87
|
-
this.wallet.requireWrite();
|
|
88
|
-
if (!this.topUps)
|
|
89
|
-
throw new AttoError('MARKETPLACE_NOT_CONNECTED', 'Connect this wallet to Marketplace from a local terminal before using top-ups.');
|
|
90
|
-
if (typeof request.requestId !== 'string' || !request.requestId || request.requestId.length > 128
|
|
91
|
-
|| (request.index !== undefined && (!Number.isSafeInteger(request.index) || request.index < 0 || request.index > 0x7fff_ffff))) {
|
|
92
|
-
throw new AttoError('INVALID_INPUT', 'Marketplace top-ups require a request ID and an optional valid wallet index.');
|
|
93
|
-
}
|
|
94
|
-
const raw = amountRaw(request.amount, request.unit);
|
|
95
|
-
if (raw === '0')
|
|
96
|
-
throw new AttoError('INVALID_INPUT', 'Marketplace top-ups require a positive amount.');
|
|
97
|
-
const connection = this.topUps.connection();
|
|
98
|
-
const settings = this.wallet.settings();
|
|
99
|
-
const network = this.topUpNetwork(settings);
|
|
100
|
-
const paymentIdentifier = marketplacePaymentIdentifier(connection, request.requestId);
|
|
101
|
-
await this.reconcileMarketplaceIntents();
|
|
102
|
-
const existing = this.ledger.get(request.requestId);
|
|
103
|
-
if (existing) {
|
|
104
|
-
this.checkMarketplaceTopUpRequest(existing, request, raw, network, paymentIdentifier);
|
|
105
|
-
return this.resumeMarketplaceTopUp(existing, connection, paymentIdentifier);
|
|
106
|
-
}
|
|
107
|
-
await this.store.withWalletLock(async () => {
|
|
108
|
-
this.wallet.requireWrite();
|
|
109
|
-
this.ledger.assertCanReserve(raw);
|
|
110
|
-
});
|
|
111
|
-
const offered = await this.topUps.challenge(connection, paymentIdentifier, raw);
|
|
112
|
-
const challenge = offered.challenge;
|
|
113
|
-
if (!challenge)
|
|
114
|
-
return this.unreservedMarketplaceStatus(request.requestId, paymentIdentifier, offered.status);
|
|
115
|
-
if (offered.status.state !== 'PENDING')
|
|
116
|
-
return this.unreservedMarketplaceStatus(request.requestId, paymentIdentifier, offered.status);
|
|
117
|
-
const record = await this.reserveMarketplaceTopUp(request, raw, paymentIdentifier, network, connection, challenge);
|
|
118
|
-
return this.store.withAccountLocks([record.index], async () => this.runMarketplaceTopUp(record, connection, paymentIdentifier, challenge.requirement));
|
|
119
|
-
}
|
|
120
|
-
async marketplaceTopUpStatus(requestId) {
|
|
121
|
-
const record = this.ledger.get(requestId);
|
|
122
|
-
if (!record)
|
|
123
|
-
throw new AttoError('JOURNAL_NOT_FOUND', 'This payment request is not in the local journal.');
|
|
124
|
-
if (record.external?.kind !== 'marketplace-topup')
|
|
125
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID does not belong to a Marketplace top-up.');
|
|
126
|
-
if (this.isLegacyCreditedMarketplaceTopUp(record))
|
|
127
|
-
return this.legacyMarketplaceTopUpResult(record);
|
|
128
|
-
if (!this.topUps)
|
|
129
|
-
throw new AttoError('MARKETPLACE_NOT_CONNECTED', 'Connect this wallet to Marketplace from a local terminal before reading top-up status.');
|
|
130
|
-
const connection = this.topUps.connection();
|
|
131
|
-
this.checkMarketplaceOwner(record, connection);
|
|
132
|
-
return this.store.withAccountLocks([record.index], async () => {
|
|
133
|
-
await this.refreshMarketplaceStatus(record.id, connection);
|
|
134
|
-
await this.reconcileMarketplaceSend(this.ledger.get(record.id));
|
|
135
|
-
return this.marketplaceTopUpResult(this.ledger.get(record.id));
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
/** Sign an existing Marketplace x402 intent. This private-child path never creates or submits an intent. */
|
|
139
|
-
async marketplacePayIntent(request) {
|
|
140
|
-
if (!this.internalMarketplacePayment || !this.wallet.mcp) {
|
|
141
|
-
throw new AttoError('INTERNAL_ONLY', 'Existing-intent payment signing is available only to the configured private Marketplace wallet child.');
|
|
142
|
-
}
|
|
143
|
-
this.wallet.requireWrite();
|
|
144
|
-
const { raw, network, requirement } = this.validateMarketplaceIntentRequest(request);
|
|
145
|
-
const candidates = [...this.ledger.pool().indexes];
|
|
146
|
-
const previous = this.ledger.get(request.requestId);
|
|
147
|
-
if (previous?.external?.kind === 'marketplace-intent' && !candidates.includes(previous.index))
|
|
148
|
-
candidates.push(previous.index);
|
|
149
|
-
await this.reconcileMarketplaceIntents(candidates);
|
|
150
|
-
const existing = this.ledger.get(request.requestId);
|
|
151
|
-
if (existing) {
|
|
152
|
-
this.checkMarketplaceIntentBinding(existing, request, raw, network, requirement);
|
|
153
|
-
return this.store.withAccountLocks([existing.index], () => this.prepareMarketplaceIntent(existing, requirement, true));
|
|
154
|
-
}
|
|
155
|
-
await this.store.withWalletLock(async () => {
|
|
156
|
-
this.wallet.requireWrite();
|
|
157
|
-
this.ledger.assertCanReserve(raw);
|
|
158
|
-
});
|
|
159
|
-
const releases = new Map();
|
|
160
|
-
try {
|
|
161
|
-
const snapshot = await this.store.withWalletLock(async () => {
|
|
162
|
-
this.wallet.requireWrite();
|
|
163
|
-
if (`atto:${this.wallet.settings().network.toLowerCase()}` !== network)
|
|
164
|
-
throw new AttoError('NETWORK_MISMATCH', 'The wallet network changed during Marketplace payment setup.');
|
|
165
|
-
const settings = this.wallet.settings();
|
|
166
|
-
const pool = this.ledger.pool();
|
|
167
|
-
if (request.index !== undefined && !pool.indexes.includes(request.index)) {
|
|
168
|
-
throw new AttoError('POOL_APPROVAL_REQUIRED', 'The selected account is outside the approved payment pool.');
|
|
169
|
-
}
|
|
170
|
-
this.ledger.assertCanReserve(raw);
|
|
171
|
-
const pending = new Set(this.ledger.pending().flatMap(record => this.indexes(record)));
|
|
172
|
-
let busy = false;
|
|
173
|
-
let reserved = false;
|
|
174
|
-
const indexes = request.index === undefined ? pool.indexes : [request.index];
|
|
175
|
-
const addresses = indexes.map(index => {
|
|
176
|
-
const address = this.wallet.addresses().find(value => value.index === index);
|
|
177
|
-
if (!address)
|
|
178
|
-
throw new AttoError('ADDRESS_NOT_DERIVED', 'Derive or approve the selected wallet account before paying.');
|
|
179
|
-
if (pending.has(index)) {
|
|
180
|
-
reserved = true;
|
|
181
|
-
return undefined;
|
|
182
|
-
}
|
|
183
|
-
const release = this.store.tryAccountLocks([index]);
|
|
184
|
-
if (!release) {
|
|
185
|
-
busy = true;
|
|
186
|
-
return undefined;
|
|
187
|
-
}
|
|
188
|
-
releases.set(index, release);
|
|
189
|
-
return address;
|
|
190
|
-
}).filter((value) => value !== undefined);
|
|
191
|
-
return { settings, pool, addresses, busy, reserved };
|
|
192
|
-
});
|
|
193
|
-
const candidates = [];
|
|
194
|
-
const reader = new NodeReader(snapshot.settings);
|
|
195
|
-
for (const address of snapshot.addresses) {
|
|
196
|
-
if (address.address === requirement.payTo)
|
|
197
|
-
continue;
|
|
198
|
-
const account = await retryNetwork(() => reader.account(address.address, this.retry?.signal), this.retry);
|
|
199
|
-
if (!account)
|
|
200
|
-
continue;
|
|
201
|
-
this.checkAccount(address, account, snapshot.settings);
|
|
202
|
-
candidates.push({ address, account, workReady: this.work.isReady(account) });
|
|
203
|
-
}
|
|
204
|
-
let chosen;
|
|
205
|
-
try {
|
|
206
|
-
chosen = planPayment(candidates, raw, false);
|
|
207
|
-
}
|
|
208
|
-
catch (error) {
|
|
209
|
-
if (snapshot.busy || snapshot.reserved)
|
|
210
|
-
throw new AttoError('POOL_BUSY', 'Eligible wallet accounts are busy or reserved by another payment.');
|
|
211
|
-
if (snapshot.addresses.length && snapshot.addresses.every(address => address.address === requirement.payTo)) {
|
|
212
|
-
throw new AttoError('SELF_SEND', 'The Marketplace deposit address cannot be a source account.');
|
|
213
|
-
}
|
|
214
|
-
throw error;
|
|
215
|
-
}
|
|
216
|
-
let raced = false;
|
|
217
|
-
const record = await this.store.withWalletLock(async () => {
|
|
218
|
-
this.wallet.requireWrite();
|
|
219
|
-
if (!isDeepStrictEqual(snapshot.settings, this.wallet.settings()) || !isDeepStrictEqual(snapshot.pool, this.ledger.pool())) {
|
|
220
|
-
throw new AttoError('POOL_CHANGED', 'Wallet settings or the approved pool changed during source selection. Retry this request.');
|
|
221
|
-
}
|
|
222
|
-
const prior = this.ledger.get(request.requestId);
|
|
223
|
-
if (prior) {
|
|
224
|
-
raced = true;
|
|
225
|
-
return prior;
|
|
226
|
-
}
|
|
227
|
-
this.ledger.assertCanReserve(raw);
|
|
228
|
-
this.wallet.requireAccountsAvailable?.([chosen.source.address.index]);
|
|
229
|
-
const external = {
|
|
230
|
-
kind: 'marketplace-intent', version: 1, paymentIdentifier: request.paymentIdentifier, network,
|
|
231
|
-
intentId: request.intentId, resourceUrl: request.resourceUrl, requirementHash: requirement.fingerprint,
|
|
232
|
-
intentExpiresAt: request.expiresAt, marketplaceState: 'ISSUED', paymentState: null, nativeState: 'challenged',
|
|
233
|
-
};
|
|
234
|
-
const identity = this.store.get('identity');
|
|
235
|
-
if (!identity?.fingerprint)
|
|
236
|
-
throw new AttoError('WALLET_NOT_INITIALIZED', 'Initialize this wallet profile before signing a Marketplace payment.');
|
|
237
|
-
return this.ledger.reserveExternalChallenge({ id: request.requestId, index: chosen.source.address.index,
|
|
238
|
-
destination: requirement.payTo, raw, sourceAddress: chosen.source.address.address,
|
|
239
|
-
network: snapshot.settings.network, selection: request.index === undefined ? 'automatic' : 'explicit',
|
|
240
|
-
plan: { indexes: [chosen.source.address.index], steps: [] }, createdAt: Date.now(), external }, requirement.rawJson, {
|
|
241
|
-
version: 1, apiUrl: request.apiUrl, audience: request.audience, walletFingerprint: identity.fingerprint,
|
|
242
|
-
});
|
|
243
|
-
});
|
|
244
|
-
this.checkMarketplaceIntentBinding(record, request, raw, network, requirement);
|
|
245
|
-
if (raced) {
|
|
246
|
-
for (const release of releases.values())
|
|
247
|
-
release();
|
|
248
|
-
releases.clear();
|
|
249
|
-
return await this.store.withAccountLocks([record.index], () => this.prepareMarketplaceIntent(record, requirement, true));
|
|
250
|
-
}
|
|
251
|
-
for (const [index, release] of releases)
|
|
252
|
-
if (index !== record.index) {
|
|
253
|
-
release();
|
|
254
|
-
releases.delete(index);
|
|
255
|
-
}
|
|
256
|
-
if (!releases.has(record.index))
|
|
257
|
-
throw new AttoError('POOL_BUSY', 'The selected wallet account is already in use. Retry this request.');
|
|
258
|
-
return await this.prepareMarketplaceIntent(record, requirement, false);
|
|
259
|
-
}
|
|
260
|
-
finally {
|
|
261
|
-
for (const release of releases.values())
|
|
262
|
-
release();
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
/** Private Marketplace child recovery returns the original saved signature and never signs a replacement. */
|
|
266
|
-
async marketplacePayIntentStatus(requestId) {
|
|
267
|
-
if (!this.internalMarketplacePayment || !this.wallet.mcp) {
|
|
268
|
-
throw new AttoError('INTERNAL_ONLY', 'Existing-intent payment recovery is available only to the configured private Marketplace wallet child.');
|
|
269
|
-
}
|
|
270
|
-
const record = this.ledger.get(requestId);
|
|
271
|
-
if (!record)
|
|
272
|
-
return { requestId, paymentState: 'NOT_FOUND' };
|
|
273
|
-
if (record.external?.kind !== 'marketplace-intent')
|
|
274
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID does not belong to an existing Marketplace intent.');
|
|
275
|
-
const secrets = this.ledger.externalSecretsFor(requestId);
|
|
276
|
-
this.checkMarketplaceIntentOwner(record, secrets);
|
|
277
|
-
return this.store.withAccountLocks([record.index], async () => {
|
|
278
|
-
await this.expireUnsignedMarketplaceIntent(requestId);
|
|
279
|
-
await this.reconcileMarketplaceSend(this.ledger.get(requestId));
|
|
280
|
-
const current = this.ledger.get(requestId);
|
|
281
|
-
const requirement = this.savedMarketplaceIntentRequirement(current, secrets);
|
|
282
|
-
if (current.status === 'published' || current.status === 'failed' || current.external?.nativeState === 'rejected') {
|
|
283
|
-
return this.marketplaceIntentResult(current, requirement, true);
|
|
284
|
-
}
|
|
285
|
-
await this.store.withWalletLock(async () => this.requireApproved(current));
|
|
286
|
-
return this.marketplaceIntentResult(current, requirement, true);
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
validateMarketplaceIntentRequest(request) {
|
|
290
|
-
const config = this.internalMarketplacePayment;
|
|
291
|
-
const settings = this.wallet.settings();
|
|
292
|
-
const network = `atto:${settings.network.toLowerCase()}`;
|
|
293
|
-
const raw = amountRaw(request.amountAtomic, 'RAW');
|
|
294
|
-
if (raw === '0' || raw !== request.amountAtomic || request.paymentIdentifier !== request.requestId
|
|
295
|
-
|| request.apiUrl !== config.apiUrl || request.audience !== config.audience
|
|
296
|
-
|| request.audience.trim() !== request.audience || /[\r\n\0]/.test(request.audience)) {
|
|
297
|
-
throw new AttoError('MARKETPLACE_CONFIGURATION', 'The existing intent must match the locally configured Marketplace origin, audience, payment identifier, and positive atomic amount.');
|
|
298
|
-
}
|
|
299
|
-
let apiUrl;
|
|
300
|
-
try {
|
|
301
|
-
apiUrl = validateMarketplaceApiUrl(config.apiUrl, settings.network);
|
|
302
|
-
}
|
|
303
|
-
catch {
|
|
304
|
-
throw new AttoError('MARKETPLACE_CONFIGURATION', 'The configured Marketplace payment origin is invalid for this wallet network.');
|
|
305
|
-
}
|
|
306
|
-
if (apiUrl !== request.apiUrl || request.resourceUrl !== `${apiUrl}/${request.intentId}`) {
|
|
307
|
-
throw new AttoError('MARKETPLACE_RESOURCE_MISMATCH', 'The exact resource URL must be the existing intent under the locally configured Marketplace origin.');
|
|
308
|
-
}
|
|
309
|
-
const expiresAtMs = Date.parse(request.expiresAt);
|
|
310
|
-
if (!Number.isSafeInteger(expiresAtMs) || (expiresAtMs <= Date.now()
|
|
311
|
-
&& this.ledger.get(request.requestId)?.external?.intentExpiresAt !== request.expiresAt)) {
|
|
312
|
-
throw new AttoError('MARKETPLACE_CHALLENGE_EXPIRED', 'The existing Marketplace intent has an invalid or expired deadline.');
|
|
313
|
-
}
|
|
314
|
-
const requirement = parseAttoExactRequirement({ header: request.paymentRequired, apiUrl, intentId: request.intentId, network, amountRaw: raw });
|
|
315
|
-
if (requirement.resourceUrl !== request.resourceUrl || requirement.amountRaw !== raw || requirement.network !== network) {
|
|
316
|
-
throw new AttoError('MARKETPLACE_RESOURCE_MISMATCH', 'The x402 requirement does not match this exact Marketplace intent.');
|
|
317
|
-
}
|
|
318
|
-
return { raw, network, requirement };
|
|
319
|
-
}
|
|
320
|
-
checkMarketplaceIntentBinding(record, request, raw, network, requirement) {
|
|
321
|
-
const external = record.external;
|
|
322
|
-
if (!external || external.kind !== 'marketplace-intent' || record.id !== request.requestId || record.raw !== raw
|
|
323
|
-
|| external.paymentIdentifier !== request.paymentIdentifier || external.intentId !== request.intentId
|
|
324
|
-
|| external.network !== network || external.resourceUrl !== request.resourceUrl
|
|
325
|
-
|| external.intentExpiresAt !== request.expiresAt || external.requirementHash !== requirement.fingerprint
|
|
326
|
-
|| (request.index !== undefined && request.index !== record.index)) {
|
|
327
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID is already bound to a different Marketplace intent, challenge, amount, expiry, network, or source.');
|
|
328
|
-
}
|
|
329
|
-
const secrets = this.ledger.externalSecretsFor(record.id);
|
|
330
|
-
this.checkMarketplaceIntentOwner(record, secrets);
|
|
331
|
-
if (!secrets || secrets.requirementJson !== requirement.rawJson) {
|
|
332
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID received different exact x402 challenge bytes.');
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
checkMarketplaceIntentOwner(record, secrets) {
|
|
336
|
-
const external = record.external;
|
|
337
|
-
const config = this.internalMarketplacePayment;
|
|
338
|
-
if (!secrets || secrets.paymentKind !== 'marketplace-intent' || !external || external.kind !== 'marketplace-intent'
|
|
339
|
-
|| secrets.apiUrl !== config.apiUrl || secrets.audience !== config.audience
|
|
340
|
-
|| external.network !== `atto:${this.wallet.settings().network.toLowerCase()}` || record.network !== this.wallet.settings().network) {
|
|
341
|
-
throw new AttoError('MARKETPLACE_RECONNECT_REQUIRED', 'This payment belongs to a different configured Marketplace origin, audience, wallet, or network.');
|
|
342
|
-
}
|
|
343
|
-
const identity = this.store.get('identity');
|
|
344
|
-
if (!identity || secrets.walletFingerprint !== identity.fingerprint) {
|
|
345
|
-
throw new AttoError('WALLET_MISMATCH', 'The saved Marketplace payment belongs to a different wallet profile.');
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
savedMarketplaceIntentRequirement(record, secrets) {
|
|
349
|
-
const external = record.external;
|
|
350
|
-
if (!external || external.kind !== 'marketplace-intent')
|
|
351
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request is not an existing Marketplace intent.');
|
|
352
|
-
const requirement = parseAttoExactRequirement({ header: Buffer.from(secrets.requirementJson, 'utf8').toString('base64'),
|
|
353
|
-
apiUrl: secrets.apiUrl, intentId: external.intentId, network: external.network, amountRaw: record.raw });
|
|
354
|
-
if (requirement.fingerprint !== external.requirementHash || requirement.resourceUrl !== external.resourceUrl) {
|
|
355
|
-
throw new AttoError('INVALID_STATE', 'The saved exact Marketplace challenge does not match the wallet journal.');
|
|
356
|
-
}
|
|
357
|
-
return requirement;
|
|
358
|
-
}
|
|
359
|
-
async prepareMarketplaceIntent(record, requirement, reused) {
|
|
360
|
-
// The account lock is held: refresh after a concurrent prepare and expire only an unsigned reservation.
|
|
361
|
-
record = await this.expireUnsignedMarketplaceIntent(record.id);
|
|
362
|
-
const secrets = this.ledger.externalSecretsFor(record.id);
|
|
363
|
-
this.checkMarketplaceIntentOwner(record, secrets);
|
|
364
|
-
const currentRequirement = this.savedMarketplaceIntentRequirement(record, secrets);
|
|
365
|
-
if (currentRequirement.rawJson !== requirement.rawJson || currentRequirement.fingerprint !== requirement.fingerprint) {
|
|
366
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID received different exact x402 challenge bytes.');
|
|
367
|
-
}
|
|
368
|
-
if (record.status === 'published' || record.status === 'failed' || record.external?.nativeState === 'rejected') {
|
|
369
|
-
return this.marketplaceIntentResult(record, requirement, true);
|
|
370
|
-
}
|
|
371
|
-
await this.store.withWalletLock(async () => this.requireApproved(record));
|
|
372
|
-
if (secrets.paymentSignature && secrets.transactionJson && record.hash)
|
|
373
|
-
return this.marketplaceIntentResult(record, requirement, true);
|
|
374
|
-
if (record.status !== 'reserved' || record.hash) {
|
|
375
|
-
throw new AttoError('INVALID_STATE', 'The original signed Marketplace payment is incomplete; refusing to sign a replacement.');
|
|
376
|
-
}
|
|
377
|
-
const expiresAtMs = Date.parse(record.external.intentExpiresAt);
|
|
378
|
-
if (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now()) {
|
|
379
|
-
throw new AttoError('MARKETPLACE_CHALLENGE_EXPIRED', 'The existing Marketplace intent expired before its payment was signed.');
|
|
380
|
-
}
|
|
381
|
-
const seed = await this.wallet.seed();
|
|
382
|
-
const settings = this.wallet.settings();
|
|
383
|
-
let execution;
|
|
384
|
-
try {
|
|
385
|
-
const signer = await derivedSigner(seed, record.index);
|
|
386
|
-
if (signer.address.value !== record.sourceAddress)
|
|
387
|
-
throw new AttoError('WALLET_MISMATCH', 'The saved Marketplace payment source does not match its wallet key.');
|
|
388
|
-
execution = await signingWallet(seed, record.index, settings, async (block) => {
|
|
389
|
-
await this.store.withWalletLock(async () => {
|
|
390
|
-
const current = this.ledger.get(record.id);
|
|
391
|
-
this.requireApproved(current);
|
|
392
|
-
if (!(block instanceof AttoSendBlock) || block.address.value !== record.sourceAddress
|
|
393
|
-
|| block.receiverAddress.value !== requirement.payTo || block.amount.toString() !== record.raw
|
|
394
|
-
|| block.network.name !== settings.network) {
|
|
395
|
-
throw new AttoError('TRANSACTION_MISMATCH', 'The signed payment differs from the exact Marketplace requirement.');
|
|
396
|
-
}
|
|
397
|
-
});
|
|
398
|
-
}, this.work.worker(), this.retry);
|
|
399
|
-
const transaction = await execution.wallet.prepareSendByIndex(toAttoIndex(record.index), parseAddress(requirement.payTo), AttoAmount.from(AttoUnit.RAW, record.raw), null);
|
|
400
|
-
const payment = paymentPayload(requirement, record.external.paymentIdentifier, transaction);
|
|
401
|
-
const deadline = paymentDeadline(transaction, requirement.maxTimeoutSeconds, record.external.intentExpiresAt);
|
|
402
|
-
await this.store.withWalletLock(async () => {
|
|
403
|
-
const current = this.ledger.get(record.id);
|
|
404
|
-
this.requireApproved(current);
|
|
405
|
-
const currentSecrets = this.ledger.externalSecretsFor(record.id);
|
|
406
|
-
if (!current.external || current.external.kind !== 'marketplace-intent' || current.hash || current.status !== 'reserved'
|
|
407
|
-
|| current.external.requirementHash !== requirement.fingerprint || !currentSecrets
|
|
408
|
-
|| currentSecrets.requirementJson !== requirement.rawJson || BigInt(Date.now()) >= deadline) {
|
|
409
|
-
throw new AttoError('MARKETPLACE_CHALLENGE_EXPIRED', 'The exact Marketplace challenge or payment deadline changed before it could be saved.');
|
|
410
|
-
}
|
|
411
|
-
this.ledger.externalAttempt(record.id, {
|
|
412
|
-
hash: transaction.hash.toString(), blockJson: transaction.block.toJson(), transactionJson: transaction.toJson(),
|
|
413
|
-
paymentJson: payment.json, paymentSignature: payment.header, attemptedAt: Date.now(),
|
|
414
|
-
});
|
|
415
|
-
});
|
|
416
|
-
return this.marketplaceIntentResult(this.ledger.get(record.id), requirement, reused);
|
|
417
|
-
}
|
|
418
|
-
finally {
|
|
419
|
-
execution?.wallet.close();
|
|
420
|
-
seed.value.fill(0);
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
marketplaceIntentResult(record, requirement, reused) {
|
|
424
|
-
const external = record.external;
|
|
425
|
-
const secrets = this.ledger.externalSecretsFor(record.id);
|
|
426
|
-
this.checkMarketplaceIntentOwner(record, secrets);
|
|
427
|
-
if (!external || external.kind !== 'marketplace-intent' || !secrets)
|
|
428
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request is not an existing Marketplace intent.');
|
|
429
|
-
const identity = { requestId: record.id, intentId: external.intentId, paymentIdentifier: external.paymentIdentifier,
|
|
430
|
-
network: external.network, amountAtomic: record.raw, payer: record.sourceAddress };
|
|
431
|
-
if (record.status === 'failed' || external.nativeState === 'rejected') {
|
|
432
|
-
if (external.nativeState === 'rejected' && record.hash) {
|
|
433
|
-
return { ...identity, hash: record.hash, paymentState: 'FAILED', nativeState: 'rejected',
|
|
434
|
-
failureReason: 'NATIVE_TRANSACTION_REJECTED' };
|
|
435
|
-
}
|
|
436
|
-
if (external.marketplaceState === 'EXPIRED' && external.paymentState === 'FAILED'
|
|
437
|
-
&& external.nativeState === 'challenged' && !record.hash && !record.blockJson
|
|
438
|
-
&& !secrets.transactionJson && !secrets.paymentJson && !secrets.paymentSignature) {
|
|
439
|
-
return { ...identity, hash: null, paymentState: 'FAILED', nativeState: 'challenged',
|
|
440
|
-
failureReason: 'MARKETPLACE_CHALLENGE_EXPIRED' };
|
|
441
|
-
}
|
|
442
|
-
throw new AttoError('INVALID_STATE', 'The terminal Marketplace payment has no conclusive saved outcome.');
|
|
443
|
-
}
|
|
444
|
-
if (secrets.paymentSignature || secrets.transactionJson || secrets.paymentJson || record.hash) {
|
|
445
|
-
if (!secrets.paymentSignature || !secrets.transactionJson || !secrets.paymentJson || !record.hash) {
|
|
446
|
-
throw new AttoError('INVALID_STATE', 'The exact saved Marketplace signature is incomplete; refusing to return or replace it.');
|
|
447
|
-
}
|
|
448
|
-
const transaction = AttoTransaction.fromJson(secrets.transactionJson);
|
|
449
|
-
if (!(transaction.block instanceof AttoSendBlock) || transaction.hash.toString() !== record.hash
|
|
450
|
-
|| transaction.block.address.value !== record.sourceAddress || transaction.block.receiverAddress.value !== requirement.payTo || transaction.block.amount.toString() !== record.raw
|
|
451
|
-
|| transaction.block.network.name !== record.network) {
|
|
452
|
-
throw new AttoError('INVALID_STATE', 'The saved Marketplace signature differs from its approved wallet journal binding.');
|
|
453
|
-
}
|
|
454
|
-
if (!savedPaymentMatches(requirement, external.paymentIdentifier, transaction, secrets.paymentJson, secrets.paymentSignature)) {
|
|
455
|
-
throw new AttoError('INVALID_STATE', 'The saved Marketplace signature does not match the exact challenge and payment journal.');
|
|
456
|
-
}
|
|
457
|
-
if (external.nativeState !== 'unknown' && external.nativeState !== 'confirmed') {
|
|
458
|
-
throw new AttoError('INVALID_STATE', 'A saved Marketplace signature must retain its native attempt state.');
|
|
459
|
-
}
|
|
460
|
-
return { ...identity, hash: record.hash, paymentSignature: secrets.paymentSignature, paymentState: 'READY',
|
|
461
|
-
nativeState: external.nativeState, reused };
|
|
462
|
-
}
|
|
463
|
-
return { requestId: record.id, intentId: external.intentId, network: external.network, amountAtomic: record.raw,
|
|
464
|
-
paymentState: 'PENDING_SIGNATURE', nativeState: 'challenged' };
|
|
465
|
-
}
|
|
466
|
-
topUpNetwork(settings) {
|
|
467
|
-
if (settings.network === 'LIVE')
|
|
468
|
-
return 'atto:live';
|
|
469
|
-
if (settings.network === 'LOCAL')
|
|
470
|
-
return 'atto:local';
|
|
471
|
-
throw new AttoError('MARKETPLACE_NETWORK', 'Marketplace top-ups support the configured LIVE or isolated LOCAL ATTO network only.');
|
|
472
|
-
}
|
|
473
|
-
async reserveMarketplaceTopUp(request, raw, paymentIdentifier, network, connection, challenge) {
|
|
474
|
-
const releases = new Map();
|
|
475
|
-
try {
|
|
476
|
-
const snapshot = await this.store.withWalletLock(async () => {
|
|
477
|
-
this.wallet.requireWrite();
|
|
478
|
-
const prior = this.ledger.get(request.requestId);
|
|
479
|
-
if (prior)
|
|
480
|
-
return { prior };
|
|
481
|
-
const settings = this.wallet.settings();
|
|
482
|
-
if (this.topUpNetwork(settings) !== network)
|
|
483
|
-
throw new AttoError('NETWORK_MISMATCH', 'The wallet network changed during Marketplace top-up setup.');
|
|
484
|
-
const pool = this.ledger.pool();
|
|
485
|
-
const indexes = request.index === undefined ? pool.indexes : [request.index];
|
|
486
|
-
if (request.index !== undefined && !pool.indexes.includes(request.index)) {
|
|
487
|
-
throw new AttoError('POOL_APPROVAL_REQUIRED', 'The selected account is outside the approved payment pool.');
|
|
488
|
-
}
|
|
489
|
-
this.ledger.assertCanReserve(raw);
|
|
490
|
-
const pending = new Set(this.ledger.pending().flatMap(record => this.indexes(record)));
|
|
491
|
-
let busy = false;
|
|
492
|
-
let reserved = false;
|
|
493
|
-
for (const index of indexes) {
|
|
494
|
-
const address = this.wallet.addresses().find(value => value.index === index);
|
|
495
|
-
if (!address)
|
|
496
|
-
throw new AttoError('ADDRESS_NOT_DERIVED', 'Derive or approve the selected wallet account before paying.');
|
|
497
|
-
if (pending.has(index)) {
|
|
498
|
-
reserved = true;
|
|
499
|
-
continue;
|
|
500
|
-
}
|
|
501
|
-
const release = this.store.tryAccountLocks([index]);
|
|
502
|
-
if (!release) {
|
|
503
|
-
busy = true;
|
|
504
|
-
continue;
|
|
505
|
-
}
|
|
506
|
-
releases.set(index, release);
|
|
507
|
-
}
|
|
508
|
-
return { settings, pool, indexes, busy, reserved };
|
|
509
|
-
});
|
|
510
|
-
if ('prior' in snapshot) {
|
|
511
|
-
this.checkMarketplaceTopUpRequest(snapshot.prior, request, raw, network, paymentIdentifier);
|
|
512
|
-
return snapshot.prior;
|
|
513
|
-
}
|
|
514
|
-
const addresses = snapshot.indexes.map(index => this.wallet.addresses().find(value => value.index === index))
|
|
515
|
-
.filter(address => releases.has(address.index));
|
|
516
|
-
const reader = new NodeReader(snapshot.settings);
|
|
517
|
-
const candidates = [];
|
|
518
|
-
for (const address of addresses) {
|
|
519
|
-
const account = await retryNetwork(() => reader.account(address.address, this.retry?.signal), this.retry);
|
|
520
|
-
if (!account)
|
|
521
|
-
continue;
|
|
522
|
-
this.checkAccount(address, account, snapshot.settings);
|
|
523
|
-
candidates.push({ address, account, workReady: this.work.isReady(account) });
|
|
524
|
-
}
|
|
525
|
-
let chosen;
|
|
526
|
-
try {
|
|
527
|
-
if (request.index !== undefined && !candidates.length && !snapshot.busy && !snapshot.reserved) {
|
|
528
|
-
throw new AttoError('ACCOUNT_NOT_OPEN', 'Receive funds to open this account before sending.');
|
|
529
|
-
}
|
|
530
|
-
chosen = planPayment(candidates, raw, false);
|
|
531
|
-
}
|
|
532
|
-
catch (error) {
|
|
533
|
-
if (snapshot.busy || snapshot.reserved)
|
|
534
|
-
throw new AttoError('POOL_BUSY', 'Eligible accounts are busy or reserved by unfinished payments. Retry after those payments settle.');
|
|
535
|
-
throw error;
|
|
536
|
-
}
|
|
537
|
-
const record = await this.store.withWalletLock(async () => {
|
|
538
|
-
this.wallet.requireWrite();
|
|
539
|
-
if (!isDeepStrictEqual(snapshot.settings, this.wallet.settings()) || !isDeepStrictEqual(snapshot.pool, this.ledger.pool())) {
|
|
540
|
-
throw new AttoError('POOL_CHANGED', 'Wallet settings or the approved pool changed during account selection. Retry this request.');
|
|
541
|
-
}
|
|
542
|
-
const prior = this.ledger.get(request.requestId);
|
|
543
|
-
if (prior)
|
|
544
|
-
return prior;
|
|
545
|
-
this.ledger.assertCanReserve(raw);
|
|
546
|
-
const external = {
|
|
547
|
-
kind: 'marketplace-topup', version: 1, paymentIdentifier, network, intentId: challenge.status.intentId,
|
|
548
|
-
resourceUrl: challenge.requirement.resourceUrl, requirementHash: challenge.requirement.fingerprint,
|
|
549
|
-
intentExpiresAt: challenge.status.expiresAt, marketplaceState: challenge.status.state,
|
|
550
|
-
paymentState: challenge.status.paymentState, nativeState: 'challenged', receivePending: challenge.status.receivePending,
|
|
551
|
-
receiveStatus: challenge.status.receiveStatus,
|
|
552
|
-
};
|
|
553
|
-
const reserved = this.ledger.reserve({ id: request.requestId, index: chosen.source.address.index,
|
|
554
|
-
destination: challenge.requirement.payTo, raw, sourceAddress: chosen.source.address.address,
|
|
555
|
-
network: snapshot.settings.network, selection: request.index === undefined ? 'automatic' : 'explicit',
|
|
556
|
-
plan: { indexes: [chosen.source.address.index], steps: [] }, createdAt: Date.now(), external });
|
|
557
|
-
this.ledger.externalChallenge(request.requestId, challenge.requirement.rawJson, {
|
|
558
|
-
version: 1, apiUrl: connection.apiUrl, audience: connection.audience, accountId: connection.accountId, agentId: connection.agentId,
|
|
559
|
-
identityId: connection.identityId, walletFingerprint: connection.walletFingerprint,
|
|
560
|
-
controllerIndex: connection.controllerIndex, controllerAddress: connection.controllerAddress,
|
|
561
|
-
});
|
|
562
|
-
return reserved;
|
|
563
|
-
});
|
|
564
|
-
this.checkMarketplaceTopUpRequest(record, request, raw, network, paymentIdentifier);
|
|
565
|
-
return record;
|
|
566
|
-
}
|
|
567
|
-
finally {
|
|
568
|
-
for (const release of releases.values())
|
|
569
|
-
release();
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
async resumeMarketplaceTopUp(record, connection, paymentIdentifier) {
|
|
573
|
-
if (this.isLegacyCreditedMarketplaceTopUp(record))
|
|
574
|
-
return this.legacyMarketplaceTopUpResult(record);
|
|
575
|
-
const network = this.topUpNetwork(this.wallet.settings());
|
|
576
|
-
this.checkMarketplaceTopUpRequest(record, { requestId: record.id, amount: record.raw, unit: 'RAW' }, record.raw, network, paymentIdentifier);
|
|
577
|
-
this.checkMarketplaceOwner(record, connection);
|
|
578
|
-
if (!this.topUps || !record.external || record.external.kind !== 'marketplace-topup') {
|
|
579
|
-
throw new AttoError('INVALID_STATE', 'The saved Marketplace top-up is incomplete.');
|
|
580
|
-
}
|
|
581
|
-
const secrets = this.ledger.externalSecretsFor(record.id);
|
|
582
|
-
if (record.hash && (!secrets?.transactionJson || !secrets.paymentSignature)) {
|
|
583
|
-
throw new AttoError('INVALID_STATE', 'The exact signed Marketplace payment is unavailable; its account remains reserved for reconciliation.');
|
|
584
|
-
}
|
|
585
|
-
let requirement;
|
|
586
|
-
if (secrets?.requirementJson) {
|
|
587
|
-
requirement = parseAttoExactRequirement({ header: Buffer.from(secrets.requirementJson, 'utf8').toString('base64'),
|
|
588
|
-
apiUrl: connection.apiUrl, intentId: record.external.intentId, network, amountRaw: record.raw });
|
|
589
|
-
}
|
|
590
|
-
else if (!record.hash && record.status !== 'failed') {
|
|
591
|
-
const offered = await this.topUps.challenge(connection, paymentIdentifier, record.raw);
|
|
592
|
-
if (!offered.challenge)
|
|
593
|
-
return this.marketplaceTopUpResult(record);
|
|
594
|
-
if (offered.challenge.requirement.fingerprint !== record.external.requirementHash) {
|
|
595
|
-
throw new AttoError('REQUEST_CONFLICT', 'Marketplace returned a different challenge for this payment ID.');
|
|
596
|
-
}
|
|
597
|
-
requirement = offered.challenge.requirement;
|
|
598
|
-
await this.store.withWalletLock(async () => this.ledger.externalChallenge(record.id, requirement.rawJson, {
|
|
599
|
-
version: 1, apiUrl: connection.apiUrl, audience: connection.audience, accountId: connection.accountId, agentId: connection.agentId,
|
|
600
|
-
identityId: connection.identityId, walletFingerprint: connection.walletFingerprint,
|
|
601
|
-
controllerIndex: connection.controllerIndex, controllerAddress: connection.controllerAddress,
|
|
602
|
-
}));
|
|
603
|
-
}
|
|
604
|
-
return this.store.withAccountLocks([record.index], async () => this.runMarketplaceTopUp(this.ledger.get(record.id), connection, paymentIdentifier, requirement));
|
|
605
|
-
}
|
|
606
|
-
async runMarketplaceTopUp(record, connection, paymentIdentifier, requirement) {
|
|
607
|
-
if (!this.topUps || !record.external || record.external.kind !== 'marketplace-topup') {
|
|
608
|
-
throw new AttoError('INVALID_STATE', 'The saved Marketplace top-up is incomplete.');
|
|
609
|
-
}
|
|
610
|
-
this.checkMarketplaceOwner(record, connection);
|
|
611
|
-
await this.refreshMarketplaceStatus(record.id, connection);
|
|
612
|
-
await this.reconcileMarketplaceSend(this.ledger.get(record.id));
|
|
613
|
-
let current = this.ledger.get(record.id);
|
|
614
|
-
if (current.status === 'failed' || current.external.nativeState === 'rejected'
|
|
615
|
-
|| this.marketplaceFundingUsable(current.external.marketplaceState ?? '', current.external.paymentState)) {
|
|
616
|
-
return this.marketplaceTopUpResult(current);
|
|
617
|
-
}
|
|
618
|
-
if (current.status === 'published' && !this.hasUnconfirmedMarketplacePayment(current))
|
|
619
|
-
return this.marketplaceTopUpResult(current);
|
|
620
|
-
const secrets = this.ledger.externalSecretsFor(current.id);
|
|
621
|
-
if (current.hash) {
|
|
622
|
-
if (!secrets?.transactionJson || !secrets.paymentSignature) {
|
|
623
|
-
throw new AttoError('INVALID_STATE', 'The exact signed Marketplace payment is unavailable; its account remains reserved for reconciliation.');
|
|
624
|
-
}
|
|
625
|
-
const transaction = AttoTransaction.fromJson(secrets.transactionJson);
|
|
626
|
-
if (transaction.hash.toString().toUpperCase() !== current.hash.toUpperCase()) {
|
|
627
|
-
throw new AttoError('INVALID_STATE', 'The saved signed payment does not match its recorded native hash.');
|
|
628
|
-
}
|
|
629
|
-
requirement ??= parseAttoExactRequirement({ header: Buffer.from(secrets.requirementJson, 'utf8').toString('base64'),
|
|
630
|
-
apiUrl: connection.apiUrl, intentId: current.external.intentId, network: current.external.network, amountRaw: current.raw });
|
|
631
|
-
if (BigInt(Date.now()) >= paymentDeadline(transaction, requirement.maxTimeoutSeconds, current.external.intentExpiresAt)) {
|
|
632
|
-
return this.marketplaceTopUpResult(current);
|
|
633
|
-
}
|
|
634
|
-
const status = this.marketplaceStatusProjection(current);
|
|
635
|
-
const updated = await this.topUps.pay(connection, status, paymentIdentifier, secrets.paymentSignature, {
|
|
636
|
-
hash: current.hash, network: current.external.network, payer: current.sourceAddress,
|
|
637
|
-
}, async () => this.store.withWalletLock(async () => {
|
|
638
|
-
this.requireApproved(current, current.status !== 'published');
|
|
639
|
-
}));
|
|
640
|
-
await this.saveMarketplaceStatus(current.id, updated);
|
|
641
|
-
}
|
|
642
|
-
else {
|
|
643
|
-
if (current.external.marketplaceState === 'REJECTED')
|
|
644
|
-
return this.marketplaceTopUpResult(current);
|
|
645
|
-
if (!requirement)
|
|
646
|
-
throw new AttoError('INVALID_STATE', 'The original Marketplace challenge is unavailable; no replacement payment will be signed.');
|
|
647
|
-
current = await this.prepareAndSubmitMarketplaceTopUp(current, connection, paymentIdentifier, requirement);
|
|
648
|
-
}
|
|
649
|
-
await this.reconcileMarketplaceSend(this.ledger.get(record.id));
|
|
650
|
-
return this.marketplaceTopUpResult(this.ledger.get(record.id));
|
|
651
|
-
}
|
|
652
|
-
async prepareAndSubmitMarketplaceTopUp(record, connection, paymentIdentifier, requirement) {
|
|
653
|
-
const secrets = this.ledger.externalSecretsFor(record.id);
|
|
654
|
-
if (!record.external || !secrets || secrets.requirementJson !== requirement.rawJson
|
|
655
|
-
|| record.external.requirementHash !== requirement.fingerprint) {
|
|
656
|
-
throw new AttoError('INVALID_STATE', 'The original Marketplace challenge is unavailable; no replacement payment will be signed.');
|
|
657
|
-
}
|
|
658
|
-
const seed = await this.wallet.seed();
|
|
659
|
-
const settings = this.wallet.settings();
|
|
660
|
-
let execution;
|
|
661
|
-
try {
|
|
662
|
-
await this.store.withWalletLock(async () => this.requireApproved(record));
|
|
663
|
-
const signer = await derivedSigner(seed, record.index);
|
|
664
|
-
if (signer.address.value !== record.sourceAddress)
|
|
665
|
-
throw new AttoError('WALLET_MISMATCH', 'The saved Marketplace top-up source does not match its wallet key.');
|
|
666
|
-
execution = await signingWallet(seed, record.index, settings, async (block) => {
|
|
667
|
-
await this.store.withWalletLock(async () => {
|
|
668
|
-
this.requireApproved(record);
|
|
669
|
-
if (!(block instanceof AttoSendBlock) || block.address.value !== record.sourceAddress
|
|
670
|
-
|| block.receiverAddress.value !== requirement.payTo || block.amount.toString() !== record.raw
|
|
671
|
-
|| block.network.name !== settings.network) {
|
|
672
|
-
throw new AttoError('TRANSACTION_MISMATCH', 'The prepared transaction differs from the offered Marketplace top-up.');
|
|
673
|
-
}
|
|
674
|
-
});
|
|
675
|
-
}, this.work.worker(), this.retry);
|
|
676
|
-
const transaction = await execution.wallet.prepareSendByIndex(toAttoIndex(record.index), parseAddress(requirement.payTo), AttoAmount.from(AttoUnit.RAW, record.raw), null);
|
|
677
|
-
const payment = paymentPayload(requirement, paymentIdentifier, transaction);
|
|
678
|
-
const deadline = paymentDeadline(transaction, requirement.maxTimeoutSeconds, record.external.intentExpiresAt);
|
|
679
|
-
const status = this.marketplaceStatusProjection(record);
|
|
680
|
-
const updated = await this.topUps.pay(connection, status, paymentIdentifier, payment.header, {
|
|
681
|
-
hash: transaction.hash.toString(), network: record.external.network, payer: record.sourceAddress,
|
|
682
|
-
}, async () => this.store.withWalletLock(async () => {
|
|
683
|
-
const current = this.ledger.get(record.id);
|
|
684
|
-
this.requireApproved(current);
|
|
685
|
-
if (!current.external || current.hash || current.status !== 'reserved'
|
|
686
|
-
|| current.external.requirementHash !== requirement.fingerprint
|
|
687
|
-
|| BigInt(Date.now()) >= deadline) {
|
|
688
|
-
throw new AttoError('MARKETPLACE_CHALLENGE_EXPIRED', 'The Marketplace payment deadline expired or its challenge changed before submission.');
|
|
689
|
-
}
|
|
690
|
-
this.ledger.externalAttempt(record.id, {
|
|
691
|
-
hash: transaction.hash.toString(), blockJson: transaction.block.toJson(), transactionJson: transaction.toJson(),
|
|
692
|
-
paymentJson: payment.json, paymentSignature: payment.header, attemptedAt: Date.now(),
|
|
693
|
-
});
|
|
694
|
-
}));
|
|
695
|
-
await this.saveMarketplaceStatus(record.id, updated);
|
|
696
|
-
return this.ledger.get(record.id);
|
|
697
|
-
}
|
|
698
|
-
finally {
|
|
699
|
-
execution?.wallet.close();
|
|
700
|
-
seed.value.fill(0);
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
async refreshMarketplaceStatus(requestId, connection) {
|
|
704
|
-
const record = this.ledger.get(requestId);
|
|
705
|
-
if (!record?.external || !this.topUps)
|
|
706
|
-
return;
|
|
707
|
-
this.checkMarketplaceOwner(record, connection);
|
|
708
|
-
const expected = record.hash
|
|
709
|
-
? { hash: record.hash, payer: record.sourceAddress ?? '' }
|
|
710
|
-
: undefined;
|
|
711
|
-
if (record.hash && !expected?.payer) {
|
|
712
|
-
throw new AttoError('INVALID_STATE', 'The saved Marketplace payment has no source address; its account remains reserved for reconciliation.');
|
|
713
|
-
}
|
|
714
|
-
const status = await this.topUps.status(connection, record.external.intentId, record.external.paymentIdentifier, record.raw, record.external.network, expected);
|
|
715
|
-
await this.saveMarketplaceStatus(requestId, status);
|
|
716
|
-
const current = this.ledger.get(requestId);
|
|
717
|
-
if (!current.hash && current.status === 'reserved' && status.state === 'REJECTED') {
|
|
718
|
-
await this.store.withWalletLock(async () => this.ledger.fail(requestId));
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
async saveMarketplaceStatus(requestId, status) {
|
|
722
|
-
await this.store.withWalletLock(async () => this.ledger.externalStatus(requestId, {
|
|
723
|
-
marketplaceState: status.state, paymentState: status.paymentState, receivePending: status.receivePending,
|
|
724
|
-
receiveStatus: status.receiveStatus,
|
|
725
|
-
}));
|
|
726
|
-
}
|
|
727
|
-
async reconcileMarketplaceSend(record, timeoutMs = 10_000) {
|
|
728
|
-
if (!record.external || !record.hash || ['published', 'failed'].includes(record.status))
|
|
729
|
-
return;
|
|
730
|
-
const outcome = await reconcileSend(this.reader(), record, timeoutMs);
|
|
731
|
-
if (outcome.status === 'unresolved')
|
|
732
|
-
return;
|
|
733
|
-
await this.store.withWalletLock(async () => {
|
|
734
|
-
const current = this.ledger.get(record.id);
|
|
735
|
-
if (current.status === 'published' || current.status === 'failed')
|
|
736
|
-
return;
|
|
737
|
-
if (outcome.status === 'rejected') {
|
|
738
|
-
this.ledger.rejectExternal(record.id, { status: 'rejected', hash: record.hash });
|
|
739
|
-
}
|
|
740
|
-
else {
|
|
741
|
-
this.ledger.completeExternal(record.id, { status: 'published', hash: record.hash }, Number(outcome.transaction.block.timestamp.toEpochMilliseconds()));
|
|
742
|
-
}
|
|
743
|
-
});
|
|
744
|
-
if (outcome.status === 'published')
|
|
745
|
-
this.work.prepareConfirmed(outcome.transaction.block);
|
|
746
|
-
}
|
|
747
|
-
/** Caller holds this account's lock; the wallet lock makes the no-candidate check and release atomic. */
|
|
748
|
-
async expireUnsignedMarketplaceIntent(requestId) {
|
|
749
|
-
return this.store.withWalletLock(async () => {
|
|
750
|
-
this.ledger.expireExternalChallenge(requestId, Date.now());
|
|
751
|
-
return this.ledger.get(requestId);
|
|
752
|
-
});
|
|
753
|
-
}
|
|
754
|
-
async reconcileMarketplaceIntents(candidateIndexes = this.ledger.pool().indexes) {
|
|
755
|
-
const candidates = new Set(candidateIndexes);
|
|
756
|
-
const records = this.ledger.pending().filter(record => record.external?.kind === 'marketplace-intent'
|
|
757
|
-
&& (record.hash === undefined || candidates.has(record.index)));
|
|
758
|
-
let cursor = 0;
|
|
759
|
-
const worker = async () => {
|
|
760
|
-
while (cursor < records.length) {
|
|
761
|
-
const record = records[cursor++];
|
|
762
|
-
const release = this.store.tryAccountLocks([record.index]);
|
|
763
|
-
if (!release)
|
|
764
|
-
continue;
|
|
765
|
-
try {
|
|
766
|
-
const current = await this.expireUnsignedMarketplaceIntent(record.id);
|
|
767
|
-
if (current.external?.kind === 'marketplace-intent') {
|
|
768
|
-
await this.reconcileMarketplaceSend(current, MARKETPLACE_INTENT_SWEEP_TIMEOUT_MS);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
finally {
|
|
772
|
-
release();
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
};
|
|
776
|
-
await Promise.all(Array.from({ length: Math.min(MARKETPLACE_INTENT_SWEEP_CONCURRENCY, records.length) }, worker));
|
|
777
|
-
}
|
|
778
|
-
hasUnconfirmedMarketplacePayment(record) {
|
|
779
|
-
return record.external !== undefined && (record.external.kind === 'market-topup' || record.external.kind === 'market-intent'
|
|
780
|
-
|| !this.marketplaceFundingUsable(record.external.marketplaceState ?? '', record.external.paymentState));
|
|
781
|
-
}
|
|
782
|
-
marketplaceFundingUsable(marketplaceState, paymentState) {
|
|
783
|
-
return ['ACCEPTED', 'SETTLED'].includes(marketplaceState) || ['ACCEPTED', 'SETTLED'].includes(paymentState ?? '');
|
|
784
|
-
}
|
|
785
|
-
marketplaceStatusProjection(record) {
|
|
786
|
-
const external = record.external;
|
|
787
|
-
if (!external || (external.kind !== 'marketplace-topup' && external.kind !== 'marketplace-intent')) {
|
|
788
|
-
throw new AttoError('INVALID_STATE', 'The payment is not a current Marketplace payment.');
|
|
789
|
-
}
|
|
790
|
-
const marketplaceState = ['PENDING', 'ACCEPTED', 'SETTLED', 'REJECTED']
|
|
791
|
-
.includes(external.marketplaceState) ? external.marketplaceState : 'PENDING';
|
|
792
|
-
const paymentState = ['PENDING', 'ACCEPTED', 'SETTLED', 'REJECTED']
|
|
793
|
-
.includes(external.paymentState ?? '') ? external.paymentState : null;
|
|
794
|
-
return { intentId: external.intentId, asset: 'ATTO', network: external.network, amountAtomic: record.raw,
|
|
795
|
-
state: marketplaceState, expiresAt: external.intentExpiresAt, sendHash: record.hash ?? null,
|
|
796
|
-
payer: record.sourceAddress ?? null, paymentState,
|
|
797
|
-
receivePending: external.receivePending ?? null, discrepancy: null, receiveStatus: external.receiveStatus ?? null };
|
|
798
|
-
}
|
|
799
|
-
marketplaceTopUpResult(record) {
|
|
800
|
-
const external = record.external;
|
|
801
|
-
if (!external)
|
|
802
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID does not belong to a Marketplace top-up.');
|
|
803
|
-
const status = this.marketplaceStatusProjection(record);
|
|
804
|
-
return { requestId: record.id, status: record.status, nativeState: external.nativeState,
|
|
805
|
-
marketplaceState: status.state, paymentState: status.paymentState, receivePending: status.receivePending,
|
|
806
|
-
receiveStatus: status.receiveStatus,
|
|
807
|
-
intentId: external.intentId, network: external.network, amount: amountOutput(record.raw), index: record.index,
|
|
808
|
-
sourceAddress: record.sourceAddress ?? null, destination: record.destination, hash: record.hash ?? null,
|
|
809
|
-
sendHash: record.hash ?? null, payer: record.sourceAddress ?? null, expiresAt: external.intentExpiresAt };
|
|
810
|
-
}
|
|
811
|
-
isLegacyCreditedMarketplaceTopUp(record) {
|
|
812
|
-
return record.external?.kind === 'marketplace-topup' && record.external.marketplaceState === 'CREDITED';
|
|
813
|
-
}
|
|
814
|
-
legacyMarketplaceTopUpResult(record) {
|
|
815
|
-
return { ...this.marketplaceTopUpResult(record), historicalOnly: true, currentMarketplaceBalance: 'unverified',
|
|
816
|
-
message: 'This wallet journal records a historical Marketplace credit. It was not replayed and does not establish a balance in the current Marketplace database.' };
|
|
817
|
-
}
|
|
818
|
-
unreservedMarketplaceStatus(requestId, paymentIdentifier, status) {
|
|
819
|
-
return { requestId, status: 'not_submitted', nativeState: 'not_submitted', marketplaceState: status.state,
|
|
820
|
-
paymentState: status.paymentState, receivePending: status.receivePending, receiveStatus: status.receiveStatus,
|
|
821
|
-
intentId: status.intentId,
|
|
822
|
-
network: status.network, amount: amountOutput(status.amountAtomic), sendHash: status.sendHash, payer: status.payer,
|
|
823
|
-
expiresAt: status.expiresAt, paymentIdentifier };
|
|
824
|
-
}
|
|
825
|
-
checkMarketplaceTopUpRequest(record, request, raw, network, paymentIdentifier) {
|
|
826
|
-
if (!record.external || record.external.kind !== 'marketplace-topup' || record.raw !== raw || record.external.paymentIdentifier !== paymentIdentifier
|
|
827
|
-
|| record.external.network !== network || record.network !== this.wallet.settings().network
|
|
828
|
-
|| (request.index !== undefined && record.index !== request.index)) {
|
|
829
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a different Marketplace top-up. Keep its original amount, network, and source account.');
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
checkMarketplaceOwner(record, connection) {
|
|
833
|
-
const secrets = this.ledger.externalSecretsFor(record.id);
|
|
834
|
-
if (secrets && (secrets.apiUrl !== connection.apiUrl || secrets.audience !== connection.audience
|
|
835
|
-
|| secrets.accountId !== connection.accountId || secrets.agentId !== connection.agentId || secrets.identityId !== connection.identityId
|
|
836
|
-
|| secrets.walletFingerprint !== connection.walletFingerprint
|
|
837
|
-
|| secrets.controllerIndex !== connection.controllerIndex || secrets.controllerAddress !== connection.controllerAddress)) {
|
|
838
|
-
throw new AttoError('MARKETPLACE_RECONNECT_REQUIRED', 'This payment belongs to a different Marketplace account or controller. Reconnect using its original wallet profile.');
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
75
|
async send(request) {
|
|
842
76
|
const binding = bindDestination(this.store, this.ledger, this.wallet.settings().network, request);
|
|
843
77
|
request = { ...request, destination: binding.address };
|
|
844
78
|
this.onDestination?.(binding);
|
|
845
79
|
const existing = this.ledger.get(request.requestId);
|
|
846
|
-
if (existing?.external)
|
|
847
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a
|
|
80
|
+
if (existing?.external || existing?.relay)
|
|
81
|
+
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a different saved payment and cannot authorize a new send.');
|
|
848
82
|
if (existing)
|
|
849
83
|
return this.resume(existing, request);
|
|
850
84
|
await this.reconcile();
|
|
@@ -988,8 +222,8 @@ export class Payments {
|
|
|
988
222
|
}
|
|
989
223
|
}
|
|
990
224
|
async resume(record, request) {
|
|
991
|
-
if (record.external)
|
|
992
|
-
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a
|
|
225
|
+
if (record.external || record.relay)
|
|
226
|
+
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a different saved payment and cannot authorize a new send.');
|
|
993
227
|
this.checkRequest(record, request);
|
|
994
228
|
if (record.status === 'published')
|
|
995
229
|
return record.result;
|
|
@@ -1002,36 +236,43 @@ export class Payments {
|
|
|
1002
236
|
return current.result;
|
|
1003
237
|
if (current.status === 'failed')
|
|
1004
238
|
throw new AttoError('REQUEST_FAILED', 'The payment was excluded from the account chain. Inspect its journal before creating a new request.');
|
|
1005
|
-
if (
|
|
239
|
+
if (!current.plan && !current.hash)
|
|
1006
240
|
this.uncertain(current);
|
|
1007
241
|
return this.execute(current);
|
|
1008
242
|
});
|
|
1009
243
|
}
|
|
1010
244
|
uncertain(record) {
|
|
1011
|
-
|
|
245
|
+
const missing = [record, ...(record.plan?.steps ?? [])].some(value => value.hash && value.status !== 'published' && !value.transactionJson);
|
|
246
|
+
throw new AttoError('PUBLICATION_UNCERTAIN', missing
|
|
247
|
+
? 'Publication is unresolved. This historical journal lacks the original signed transaction and work, so exact replay is unavailable. Reuse this request ID for canonical reconciliation; preserve the journal.'
|
|
248
|
+
: 'Publication is unresolved. Reuse this request ID to reconcile or replay the retained payment.', { requestId: record.id, hash: record.hash, steps: record.plan?.steps.map(({ id, hash, status }) => ({ id, hash, status })) });
|
|
1012
249
|
}
|
|
1013
250
|
async execute(record) {
|
|
1014
251
|
let seed;
|
|
1015
252
|
try {
|
|
1016
253
|
await this.store.withWalletLock(async () => this.requireApproved(record));
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
const
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
254
|
+
const prepareSeed = async () => {
|
|
255
|
+
if (seed)
|
|
256
|
+
return seed;
|
|
257
|
+
seed = await this.wallet.seed();
|
|
258
|
+
// Derive only for fresh preparation; replay never needs keys or new work.
|
|
259
|
+
for (const index of this.indexes(record)) {
|
|
260
|
+
const signer = await derivedSigner(seed, index);
|
|
261
|
+
const expected = index === record.index ? record.sourceAddress : record.plan?.steps.find(step => step.index === index)?.sourceAddress;
|
|
262
|
+
if (expected && signer.address.value !== expected)
|
|
263
|
+
throw new AttoError('WALLET_MISMATCH', 'A planned source does not match its wallet key.');
|
|
264
|
+
}
|
|
265
|
+
return seed;
|
|
266
|
+
};
|
|
267
|
+
for (const planned of record.plan?.steps ?? []) {
|
|
268
|
+
const current = this.ledger.get(record.id);
|
|
269
|
+
const step = current.plan.steps.find(value => value.id === planned.id);
|
|
1027
270
|
if (step.status === 'published')
|
|
1028
271
|
continue;
|
|
1029
|
-
|
|
1030
|
-
this.uncertain(record);
|
|
1031
|
-
await this.executeStep(record, step, seed);
|
|
272
|
+
await this.executeStep(current, step, step.hash ? undefined : await prepareSeed());
|
|
1032
273
|
}
|
|
1033
274
|
const current = this.ledger.get(record.id);
|
|
1034
|
-
const transaction = await this.publish(current, current.index,
|
|
275
|
+
const transaction = current.hash ? await this.replay(current) : await this.publish(current, current.index, await prepareSeed());
|
|
1035
276
|
const result = this.paymentResult(this.ledger.get(record.id), transaction);
|
|
1036
277
|
await this.store.withWalletLock(async () => this.ledger.complete(record.id, result, Number(transaction.block.timestamp.toEpochMilliseconds())));
|
|
1037
278
|
return result;
|
|
@@ -1059,7 +300,7 @@ export class Payments {
|
|
|
1059
300
|
}
|
|
1060
301
|
async executeStep(record, step, seed) {
|
|
1061
302
|
try {
|
|
1062
|
-
const transaction = await this.publish(record, step.index, seed, step);
|
|
303
|
+
const transaction = step.hash ? await this.replay(record, step) : await this.publish(record, step.index, seed, step);
|
|
1063
304
|
await this.store.withWalletLock(async () => this.ledger.stepComplete(record.id, step.id, this.result(transaction), Number(transaction.block.timestamp.toEpochMilliseconds())));
|
|
1064
305
|
}
|
|
1065
306
|
catch (error) {
|
|
@@ -1080,25 +321,24 @@ export class Payments {
|
|
|
1080
321
|
}
|
|
1081
322
|
const execution = await signingWallet(seed, index, settings, async (block) => {
|
|
1082
323
|
await this.store.withWalletLock(async () => {
|
|
1083
|
-
this.requireApproved(record);
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
this.ledger.stepSigned(record.id, step.id, block.hash.toString(), block.toJson());
|
|
324
|
+
this.requireApproved(this.ledger.get(record.id));
|
|
325
|
+
this.checkBlock(record, block, step);
|
|
326
|
+
});
|
|
327
|
+
}, this.work.worker(), this.retry, async (transaction) => {
|
|
328
|
+
if (!await transaction.isValid())
|
|
329
|
+
throw new AttoError('INVALID_TRANSACTION', 'The signed transaction is invalid.');
|
|
330
|
+
await this.store.withWalletLock(async () => {
|
|
331
|
+
const current = this.ledger.get(record.id);
|
|
332
|
+
this.requireApproved(current);
|
|
333
|
+
const currentStep = step && current.plan.steps.find(value => value.id === step.id);
|
|
334
|
+
this.checkBlock(current, transaction.block, currentStep);
|
|
335
|
+
const args = [transaction.hash.toString(), transaction.block.toJson(), transaction.toJson(), this.candidateBinding(current, currentStep)];
|
|
336
|
+
if (currentStep)
|
|
337
|
+
this.ledger.stepSigned(record.id, currentStep.id, ...args);
|
|
1098
338
|
else
|
|
1099
|
-
this.ledger.signed(record.id,
|
|
339
|
+
this.ledger.signed(record.id, ...args);
|
|
1100
340
|
});
|
|
1101
|
-
}
|
|
341
|
+
});
|
|
1102
342
|
try {
|
|
1103
343
|
if (step?.kind === 'receive') {
|
|
1104
344
|
const receivable = await this.pendingReceivable(step.destination, sendHash);
|
|
@@ -1117,6 +357,207 @@ export class Payments {
|
|
|
1117
357
|
execution.wallet.close();
|
|
1118
358
|
}
|
|
1119
359
|
}
|
|
360
|
+
candidateBinding(record, step) {
|
|
361
|
+
// Bind retained bytes to the original request, quote and already-selected plan.
|
|
362
|
+
return createHash('sha256').update(JSON.stringify({ id: record.id, index: record.index,
|
|
363
|
+
sourceAddress: record.sourceAddress, network: record.network, destination: record.destination, raw: record.raw,
|
|
364
|
+
createdAt: record.createdAt, metadata: record.metadata, quote: record.quote,
|
|
365
|
+
destinationBinding: record.destinationBinding, selection: record.selection,
|
|
366
|
+
plan: record.plan && { indexes: record.plan.indexes, steps: record.plan.steps.map(({ id, kind, index, sourceAddress, destination, raw, sourceStepId }) => ({ id, kind, index, sourceAddress, destination, raw, sourceStepId })) },
|
|
367
|
+
stepId: step?.id, sourceHash: step?.kind === 'receive' ? record.plan.steps.find(value => value.id === step.sourceStepId)?.hash : undefined,
|
|
368
|
+
...(record.relay ? { relay: { ...record.relay, paymentSignature: undefined } } : {}), })).digest('hex');
|
|
369
|
+
}
|
|
370
|
+
checkBlock(record, block, step) {
|
|
371
|
+
const source = step?.sourceAddress ?? record.sourceAddress;
|
|
372
|
+
const index = step?.index ?? record.index;
|
|
373
|
+
if (!block.isValid() || block.network.name !== record.network || !source || block.address.value !== source
|
|
374
|
+
|| this.wallet.addresses().find(value => value.index === index)?.address !== source) {
|
|
375
|
+
throw new AttoError('TRANSACTION_MISMATCH', 'The transaction source or network differs from the payment plan.');
|
|
376
|
+
}
|
|
377
|
+
if (step && record.plan.steps.slice(0, record.plan.steps.findIndex(value => value.id === step.id)).some(value => value.status !== 'published')) {
|
|
378
|
+
throw new AttoError('SEND_STATE', 'Complete the previous consolidation steps first.');
|
|
379
|
+
}
|
|
380
|
+
if (step?.kind === 'receive') {
|
|
381
|
+
const send = record.plan.steps.find(value => value.id === step.sourceStepId);
|
|
382
|
+
if (!send?.hash || send.status !== 'published' || send.raw !== step.raw
|
|
383
|
+
|| !(block instanceof AttoReceiveBlock || block instanceof AttoOpenBlock) || block.sendHash.toString() !== send.hash) {
|
|
384
|
+
throw new AttoError('TRANSACTION_MISMATCH', 'The receive differs from the planned consolidation transfer.');
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
else if (!(block instanceof AttoSendBlock) || block.amount.toString() !== (step?.raw ?? record.raw)
|
|
388
|
+
|| block.receiverAddress.value !== (step?.destination ?? record.destination)) {
|
|
389
|
+
throw new AttoError('TRANSACTION_MISMATCH', 'The transaction differs from the payment plan.');
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
async retainedTransaction(record, step) {
|
|
393
|
+
const retained = step ?? record;
|
|
394
|
+
if (!retained.transactionJson)
|
|
395
|
+
this.uncertain(record);
|
|
396
|
+
let transaction;
|
|
397
|
+
try {
|
|
398
|
+
transaction = AttoTransaction.fromJson(retained.transactionJson);
|
|
399
|
+
if (!await transaction.isValid() || transaction.toJson() !== retained.transactionJson
|
|
400
|
+
|| transaction.hash.toString() !== retained.hash || transaction.block.toJson() !== retained.blockJson
|
|
401
|
+
|| retained.candidateBinding !== this.candidateBinding(record, step))
|
|
402
|
+
throw new Error();
|
|
403
|
+
this.checkBlock(record, transaction.block, step);
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
throw new AttoError('INVALID_STATE', 'The retained native candidate is invalid or differs from its original payment. Preserve the journal; no replacement was signed.');
|
|
407
|
+
}
|
|
408
|
+
return transaction;
|
|
409
|
+
}
|
|
410
|
+
async replay(record, step) {
|
|
411
|
+
const retained = step ?? record;
|
|
412
|
+
const transaction = await this.retainedTransaction(record, step);
|
|
413
|
+
await publishTransaction(transaction, this.wallet.settings(), async () => {
|
|
414
|
+
await this.store.withWalletLock(async () => {
|
|
415
|
+
const current = this.ledger.get(record.id);
|
|
416
|
+
this.requireApproved(current);
|
|
417
|
+
const currentRetained = step ? current.plan.steps.find(value => value.id === step.id) : current;
|
|
418
|
+
if (currentRetained.transactionJson !== retained.transactionJson || currentRetained.candidateBinding !== retained.candidateBinding
|
|
419
|
+
|| this.candidateBinding(current, step ? currentRetained : undefined) !== retained.candidateBinding) {
|
|
420
|
+
throw new AttoError('INVALID_STATE', 'The retained payment changed before publication.');
|
|
421
|
+
}
|
|
422
|
+
this.checkBlock(current, transaction.block, step ? currentRetained : undefined);
|
|
423
|
+
});
|
|
424
|
+
}, this.retry);
|
|
425
|
+
this.work.prepareConfirmed(transaction.block);
|
|
426
|
+
return transaction;
|
|
427
|
+
}
|
|
428
|
+
async prepareRelay(input) {
|
|
429
|
+
const parsed = z.strictObject({ requestId: z.string().uuid(), origin: z.string(), audience: z.string(), terms: z.record(z.string(), z.unknown()),
|
|
430
|
+
paymentRequired: z.string(), index: z.number().int().min(0).max(0x7fff_ffff) }).parse(input);
|
|
431
|
+
const request = parsed;
|
|
432
|
+
const prior = this.ledger.get(request.requestId);
|
|
433
|
+
const offer = parseRelayOffer(request, Boolean(prior?.hash));
|
|
434
|
+
if (offer.terms.asset !== 'ATTO' || offer.terms.network !== `atto:${this.wallet.settings().network.toLowerCase()}`
|
|
435
|
+
|| this.wallet.addresses().find(value => value.index === request.index)?.address !== offer.terms.senderAddress
|
|
436
|
+
|| parseAddress(offer.terms.recipientAddress).value !== offer.terms.recipientAddress
|
|
437
|
+
|| offer.terms.senderAddress === offer.terms.recipientAddress)
|
|
438
|
+
throw new AttoError('NETWORK_MISMATCH', 'The relay sender, destination or network differs from the selected wallet.');
|
|
439
|
+
// Market may have confirmed an older relay while this wallet process was offline.
|
|
440
|
+
// Canonical observation releases only completed/competing candidates; it never publishes.
|
|
441
|
+
await this.reconcile();
|
|
442
|
+
return this.store.withAccountLocks([request.index], async () => {
|
|
443
|
+
const record = await this.store.withWalletLock(async () => {
|
|
444
|
+
this.wallet.requireWrite();
|
|
445
|
+
const existing = this.ledger.get(request.requestId);
|
|
446
|
+
if (existing && !existing.relay)
|
|
447
|
+
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to another native operation.');
|
|
448
|
+
if (!existing)
|
|
449
|
+
this.ledger.assertAccountAvailable(request.index);
|
|
450
|
+
if (existing?.relay && existing.relay.paymentRequired !== request.paymentRequired)
|
|
451
|
+
this.ledger.refreshUnusedRelay(existing.id, { ...request, version: 1 });
|
|
452
|
+
const saved = this.ledger.reserve({ id: request.requestId, index: request.index, destination: offer.terms.recipientAddress,
|
|
453
|
+
raw: offer.terms.amountAtomic, sourceAddress: offer.terms.senderAddress, network: this.wallet.settings().network,
|
|
454
|
+
selection: 'explicit', createdAt: existing?.createdAt ?? Date.now(), relay: { ...request, version: 1 } });
|
|
455
|
+
this.requireApproved(saved);
|
|
456
|
+
return saved;
|
|
457
|
+
});
|
|
458
|
+
if (record.status === 'failed')
|
|
459
|
+
throw new AttoError('REQUEST_FAILED', 'Recover this original rejected native payment; no replacement was prepared.');
|
|
460
|
+
if (!record.hash) {
|
|
461
|
+
const seed = await this.wallet.seed();
|
|
462
|
+
let wallet;
|
|
463
|
+
try {
|
|
464
|
+
const execution = await signingWallet(seed, request.index, this.wallet.settings(), async (block) => {
|
|
465
|
+
await this.store.withWalletLock(async () => {
|
|
466
|
+
const current = this.ledger.get(record.id);
|
|
467
|
+
this.requireApproved(current);
|
|
468
|
+
this.checkBlock(current, block);
|
|
469
|
+
if (!(block instanceof AttoSendBlock) || BigInt(block.height.toString()) <= BigInt(offer.terms.baselineHeight)
|
|
470
|
+
|| (BigInt(block.height.toString()) === BigInt(offer.terms.baselineHeight) + 1n
|
|
471
|
+
&& offer.terms.baselineFrontier !== null && block instanceof AttoSendBlock
|
|
472
|
+
&& block.previous.toString().toLowerCase() !== offer.terms.baselineFrontier.toLowerCase())) {
|
|
473
|
+
throw new AttoError('TRANSACTION_MISMATCH', 'The candidate predates the frozen sender baseline.');
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
}, this.work.worker(), this.retry);
|
|
477
|
+
wallet = execution.wallet;
|
|
478
|
+
const transaction = await wallet.prepareSendByIndex(toAttoIndex(request.index), parseAddress(record.destination), AttoAmount.from(AttoUnit.RAW, record.raw), null);
|
|
479
|
+
await this.store.withWalletLock(async () => {
|
|
480
|
+
const current = this.ledger.get(record.id);
|
|
481
|
+
this.requireApproved(current);
|
|
482
|
+
this.checkBlock(current, transaction.block);
|
|
483
|
+
parseRelayOffer(current.relay);
|
|
484
|
+
this.ledger.signed(record.id, transaction.hash.toString(), transaction.block.toJson(), transaction.toJson(), this.candidateBinding(current));
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
finally {
|
|
488
|
+
wallet?.close();
|
|
489
|
+
seed.value.fill(0);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return this.relayResult(this.ledger.get(record.id));
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
async relayResult(record) {
|
|
496
|
+
if (!record.relay)
|
|
497
|
+
throw new AttoError('REQUEST_CONFLICT', 'This request belongs to another wallet operation.');
|
|
498
|
+
const transaction = record.hash ? await this.retainedTransaction(record) : undefined;
|
|
499
|
+
if (record.relay.paymentSignature && transaction) {
|
|
500
|
+
const offer = parseRelayOffer(record.relay, true), proof = relayProofFromHeader(record.relay.paymentSignature);
|
|
501
|
+
validateRelayProof(offer, transaction.hash.toString(), record.relay.audience, proof, true);
|
|
502
|
+
if (relayPaymentPayload(offer, record.id, { transaction: wireTransaction(transaction) }, proof) !== record.relay.paymentSignature
|
|
503
|
+
|| !await AttoSignature.Companion.parse(proof.signature).isValidMessage(transaction.address.publicKey, Int8Array.from(Buffer.from(proof.message)))) {
|
|
504
|
+
throw new AttoError('INVALID_STATE', 'The retained relay payload differs from its original authorization.');
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return { requestId: record.id, network: record.relay.terms.network, sourceAddress: record.sourceAddress,
|
|
508
|
+
destination: record.destination, amountAtomic: record.raw, hash: record.hash ?? null, state: record.status,
|
|
509
|
+
paymentRequired: record.relay.paymentRequired, paymentSignature: record.relay.paymentSignature ?? null };
|
|
510
|
+
}
|
|
511
|
+
async relayStatus(input) {
|
|
512
|
+
const { requestId, index } = z.strictObject({ requestId: z.string().uuid(), index: z.number().int().min(0).max(0x7fff_ffff).optional() }).parse(input), record = this.ledger.get(requestId);
|
|
513
|
+
if (!record)
|
|
514
|
+
return { requestId, state: 'NOT_FOUND' };
|
|
515
|
+
if (index !== undefined && index !== record.index)
|
|
516
|
+
throw new AttoError('REQUEST_CONFLICT', 'The original relay belongs to another selected wallet account.');
|
|
517
|
+
return this.store.withAccountLocks([record.index], async () => {
|
|
518
|
+
if (!record.relay)
|
|
519
|
+
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to another native operation.');
|
|
520
|
+
await this.reconcileRecord(record);
|
|
521
|
+
return this.relayResult(this.ledger.get(requestId));
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
async authorizeRelay(input) {
|
|
525
|
+
const { requestId, index, proof: suppliedProof } = z.strictObject({ requestId: z.string().uuid(), index: z.number().int().min(0).max(0x7fff_ffff).optional(), proof: z.strictObject({ challengeId: z.string().uuid(), message: z.string(), signature: z.string().optional() }) }).parse(input);
|
|
526
|
+
const record = this.ledger.get(requestId);
|
|
527
|
+
if (!record?.relay || !record.hash)
|
|
528
|
+
throw new AttoError('REQUEST_CONFLICT', 'Prepare this original relay payment first.');
|
|
529
|
+
if (index !== undefined && index !== record.index)
|
|
530
|
+
throw new AttoError('REQUEST_CONFLICT', 'The original relay belongs to another selected wallet account.');
|
|
531
|
+
return this.store.withAccountLocks([record.index], async () => {
|
|
532
|
+
if (record.relay.paymentSignature)
|
|
533
|
+
return this.relayResult(record);
|
|
534
|
+
const transaction = await this.retainedTransaction(record), offer = parseRelayOffer(record.relay);
|
|
535
|
+
// Validate the complete typed frame before key access. This authorizes no general message signing.
|
|
536
|
+
validateRelayProof(offer, record.hash, record.relay.audience, { ...suppliedProof, signature: suppliedProof.signature ?? '0'.repeat(128) });
|
|
537
|
+
let signature = suppliedProof.signature;
|
|
538
|
+
if (!signature) {
|
|
539
|
+
await this.store.withWalletLock(async () => this.requireApproved(this.ledger.get(record.id)));
|
|
540
|
+
const seed = await this.wallet.seed();
|
|
541
|
+
try {
|
|
542
|
+
const signer = await derivedSigner(seed, record.index);
|
|
543
|
+
if (signer.address.value !== record.sourceAddress)
|
|
544
|
+
throw new AttoError('WALLET_MISMATCH', 'The payment proof signer differs from its retained sender.');
|
|
545
|
+
signature = (await signer.signMessage(Int8Array.from(Buffer.from(suppliedProof.message)))).toString();
|
|
546
|
+
}
|
|
547
|
+
finally {
|
|
548
|
+
seed.value.fill(0);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
const proof = { ...suppliedProof, signature };
|
|
552
|
+
validateRelayProof(offer, record.hash, record.relay.audience, proof);
|
|
553
|
+
if (!await AttoSignature.Companion.parse(proof.signature).isValidMessage(transaction.address.publicKey, Int8Array.from(Buffer.from(proof.message)))) {
|
|
554
|
+
throw new AttoError('PAYMENT_PROTOCOL', 'Invalid wallet proof for this payment.');
|
|
555
|
+
}
|
|
556
|
+
const paymentSignature = relayPaymentPayload(offer, record.id, { transaction: wireTransaction(transaction) }, proof);
|
|
557
|
+
await this.store.withWalletLock(async () => { this.requireApproved(this.ledger.get(record.id)); this.ledger.authorizeRelay(record.id, paymentSignature); });
|
|
558
|
+
return this.relayResult(this.ledger.get(record.id));
|
|
559
|
+
});
|
|
560
|
+
}
|
|
1120
561
|
async pendingReceivable(address, hash) {
|
|
1121
562
|
const done = new AbortController();
|
|
1122
563
|
let found;
|
|
@@ -1130,7 +571,6 @@ export class Payments {
|
|
|
1130
571
|
return found;
|
|
1131
572
|
}
|
|
1132
573
|
async reconcile(candidateIndexes) {
|
|
1133
|
-
await this.reconcileMarketplaceIntents(candidateIndexes);
|
|
1134
574
|
for (const record of this.ledger.pending()) {
|
|
1135
575
|
if (record.external)
|
|
1136
576
|
continue;
|
|
@@ -1148,6 +588,8 @@ export class Payments {
|
|
|
1148
588
|
async reconcileRecord(record) {
|
|
1149
589
|
if (record.external)
|
|
1150
590
|
return;
|
|
591
|
+
if (record.relay && !record.hash)
|
|
592
|
+
return;
|
|
1151
593
|
if (record.status === 'published' || record.status === 'failed')
|
|
1152
594
|
return;
|
|
1153
595
|
for (const step of record.plan?.steps ?? []) {
|
|
@@ -1199,9 +641,3 @@ export class Payments {
|
|
|
1199
641
|
available: amountOutput(accounts.reduce((sum, account) => sum + (account.busy ? 0n : BigInt(account.balance.raw)), 0n).toString()) };
|
|
1200
642
|
}
|
|
1201
643
|
}
|
|
1202
|
-
function marketplacePaymentIdentifier(connection, requestId) {
|
|
1203
|
-
return createHash('sha256').update(JSON.stringify([
|
|
1204
|
-
connection.apiUrl, connection.audience, connection.accountId, connection.agentId, connection.identityId,
|
|
1205
|
-
connection.walletFingerprint, requestId,
|
|
1206
|
-
]), 'utf8').digest('base64url');
|
|
1207
|
-
}
|