@attocash/cli 0.2.3 → 0.3.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/README.md +148 -7
- package/dist/application/app.d.ts +34 -3
- package/dist/application/app.js +138 -126
- package/dist/application/operations.d.ts +3 -0
- package/dist/application/operations.js +30 -8
- package/dist/cli/cli.d.ts +1 -0
- package/dist/cli/cli.js +101 -13
- package/dist/cli/onboarding.d.ts +13 -0
- package/dist/cli/onboarding.js +99 -2
- package/dist/cli/output.js +18 -2
- package/dist/doctor/profile.js +2 -1
- package/dist/internal-marketplace.d.ts +25 -0
- package/dist/internal-marketplace.js +50 -0
- package/dist/marketplace/approval-files.d.ts +3 -0
- package/dist/marketplace/approval-files.js +97 -0
- package/dist/marketplace/approval-preview.d.ts +2 -0
- package/dist/marketplace/approval-preview.js +86 -0
- package/dist/marketplace/proof-approval.d.ts +82 -0
- package/dist/marketplace/proof-approval.js +671 -0
- package/dist/marketplace/topups.d.ts +82 -0
- package/dist/marketplace/topups.js +485 -0
- package/dist/network/batching.d.ts +2 -0
- package/dist/network/batching.js +23 -0
- package/dist/network/entry.d.ts +2 -0
- package/dist/network/entry.js +35 -0
- package/dist/network/reader.d.ts +2 -0
- package/dist/network/reader.js +125 -37
- package/dist/spending/approval.d.ts +5 -0
- package/dist/spending/approval.js +2 -0
- package/dist/spending/atto-x402.d.ts +31 -0
- package/dist/spending/atto-x402.js +174 -0
- package/dist/spending/ledger.d.ts +74 -2
- package/dist/spending/ledger.js +298 -7
- package/dist/spending/payments.d.ts +105 -5
- package/dist/spending/payments.js +795 -11
- package/dist/storage/recovery-seed.d.ts +13 -0
- package/dist/storage/recovery-seed.js +93 -0
- package/dist/storage/state.d.ts +4 -0
- package/dist/storage/state.js +32 -2
- package/dist/wallet/receive.d.ts +39 -0
- package/dist/wallet/receive.js +264 -0
- package/dist/wallet/signing.d.ts +1 -0
- package/dist/wallet/signing.js +37 -21
- package/dist/wallet/types.d.ts +1 -0
- package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs +1922 -1918
- package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/README.md +9 -0
- package/node_modules/@attocash/commons-core/commons-commons-core.d.mts +10 -0
- package/node_modules/@attocash/commons-core/commons-commons-core.mjs +2543 -2434
- package/node_modules/@attocash/commons-core/commons-commons-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs +4695 -4227
- package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlin_org_jetbrains_kotlin_kotlin_dom_api_compat.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs +60 -60
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs +651 -631
- package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs +2294 -2295
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-core/package.json +1 -1
- package/node_modules/@attocash/commons-node/commons-commons-node.d.mts +1 -0
- package/node_modules/@attocash/commons-node/commons-commons-node.mjs +873 -847
- package/node_modules/@attocash/commons-node/commons-commons-node.mjs.map +1 -1
- package/node_modules/@attocash/commons-node/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-node/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-node/package.json +3 -3
- package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.d.mts +1 -0
- package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs +674 -640
- package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlinx-browser.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-node-remote/package.json +4 -4
- package/node_modules/@attocash/commons-transport/commons-commons-transport.d.mts +1 -0
- package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs +52 -51
- package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs +13 -13
- package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-browser.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs +2639 -2608
- package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs +411 -196
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs +2115 -1976
- package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs +7 -7
- package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs +385 -384
- package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs +1261 -1185
- package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs +668 -656
- package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs +89 -0
- package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs.map +1 -0
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs +9 -9
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs +120 -128
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs +46 -49
- package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-sse.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs +1041 -985
- package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-websocket-serialization.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs +530 -455
- package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs.map +1 -1
- package/node_modules/@attocash/commons-transport/package.json +4 -4
- package/node_modules/@attocash/commons-worker/commons-commons-worker.d.mts +1 -0
- package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs +230 -226
- package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-worker/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker/package.json +3 -3
- package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.d.mts +1 -0
- package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs +91 -86
- package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs +109 -109
- package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlinx-browser.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
- package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
- package/node_modules/@attocash/commons-worker-remote/package.json +4 -4
- package/package.json +9 -5
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { bindDestination } from './destination.js';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
4
|
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
-
import { AttoAmount, AttoOpenBlock, AttoReceiveBlock, AttoSendBlock, AttoUnit, toAttoIndex, } from '@attocash/commons-core';
|
|
5
|
+
import { AttoAmount, AttoOpenBlock, AttoReceiveBlock, AttoSendBlock, AttoTransaction, AttoUnit, toAttoIndex, } from '@attocash/commons-core';
|
|
5
6
|
import { amountOutput, amountRaw } from '../domain/amount.js';
|
|
6
7
|
import { AttoError } from '../domain/errors.js';
|
|
7
8
|
import { NodeReader, parseAddress, publicModel } from '../network/reader.js';
|
|
@@ -10,6 +11,10 @@ import { marketTerms } from '../pricing/terms.js';
|
|
|
10
11
|
import { derivedSigner, signingWallet } from '../wallet/signing.js';
|
|
11
12
|
import { planPayment } from './pool.js';
|
|
12
13
|
import { reconcileBlock, reconcileSend } from './reconcile.js';
|
|
14
|
+
import { validateMarketplaceApiUrl } from '../marketplace/topups.js';
|
|
15
|
+
import { parseAttoExactRequirement, paymentDeadline, paymentPayload, savedPaymentMatches } from './atto-x402.js';
|
|
16
|
+
const MARKETPLACE_INTENT_SWEEP_TIMEOUT_MS = 1_000;
|
|
17
|
+
const MARKETPLACE_INTENT_SWEEP_CONCURRENCY = 16;
|
|
13
18
|
/** Owns payment selection, reservations, publication and recovery as one workflow. */
|
|
14
19
|
export class Payments {
|
|
15
20
|
store;
|
|
@@ -19,7 +24,9 @@ export class Payments {
|
|
|
19
24
|
work;
|
|
20
25
|
retry;
|
|
21
26
|
onDestination;
|
|
22
|
-
|
|
27
|
+
topUps;
|
|
28
|
+
internalMarketplacePayment;
|
|
29
|
+
constructor(store, ledger, wallet, market, work, retry, onDestination, topUps, internalMarketplacePayment) {
|
|
23
30
|
this.store = store;
|
|
24
31
|
this.ledger = ledger;
|
|
25
32
|
this.wallet = wallet;
|
|
@@ -27,6 +34,8 @@ export class Payments {
|
|
|
27
34
|
this.work = work;
|
|
28
35
|
this.retry = retry;
|
|
29
36
|
this.onDestination = onDestination;
|
|
37
|
+
this.topUps = topUps;
|
|
38
|
+
this.internalMarketplacePayment = internalMarketplacePayment;
|
|
30
39
|
}
|
|
31
40
|
reader() { return new NodeReader(this.wallet.settings()); }
|
|
32
41
|
indexes(record) { return record.plan?.indexes ?? [record.index]; }
|
|
@@ -51,30 +60,791 @@ export class Payments {
|
|
|
51
60
|
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a different payment. Keep the original destination, amount, source and metadata.');
|
|
52
61
|
}
|
|
53
62
|
}
|
|
54
|
-
requireApproved(record) {
|
|
63
|
+
requireApproved(record, requireReservation = true) {
|
|
55
64
|
this.wallet.requireWrite();
|
|
56
|
-
this.
|
|
65
|
+
this.wallet.requireAccountsAvailable?.(this.indexes(record));
|
|
66
|
+
if (requireReservation)
|
|
67
|
+
this.ledger.assertReservationAllowed(record.id);
|
|
57
68
|
if (record.network && record.network !== this.wallet.settings().network)
|
|
58
69
|
throw new AttoError('NETWORK_MISMATCH', 'The payment belongs to a different network.');
|
|
59
70
|
const pool = this.ledger.pool();
|
|
60
|
-
if ((this.wallet.mcp || record.selection === 'automatic' || record.plan?.steps.length)
|
|
71
|
+
if ((this.wallet.mcp || record.external?.kind === 'marketplace-topup' || record.external?.kind === 'marketplace-intent' || record.selection === 'automatic' || record.plan?.steps.length)
|
|
61
72
|
&& this.indexes(record).some(index => !pool.indexes.includes(index))) {
|
|
62
73
|
throw new AttoError('POOL_APPROVAL_REQUIRED', 'The payment uses an account outside the approved pool. Review the pool in a local terminal.');
|
|
63
74
|
}
|
|
64
75
|
if (record.plan?.steps.length && !pool.consolidate)
|
|
65
76
|
throw new AttoError('CONSOLIDATION_REQUIRED', 'Approve consolidation before continuing this payment.');
|
|
66
77
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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
|
+
}
|
|
72
840
|
}
|
|
73
841
|
async send(request) {
|
|
74
842
|
const binding = bindDestination(this.store, this.ledger, this.wallet.settings().network, request);
|
|
75
843
|
request = { ...request, destination: binding.address };
|
|
76
844
|
this.onDestination?.(binding);
|
|
77
845
|
const existing = this.ledger.get(request.requestId);
|
|
846
|
+
if (existing?.external)
|
|
847
|
+
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a Marketplace top-up. Resume it with marketplace_topup using the original request ID.');
|
|
78
848
|
if (existing)
|
|
79
849
|
return this.resume(existing, request);
|
|
80
850
|
await this.reconcile();
|
|
@@ -177,6 +947,7 @@ export class Payments {
|
|
|
177
947
|
if (!isDeepStrictEqual(snapshot.settings, this.wallet.settings()) || !isDeepStrictEqual(snapshot.pool, this.ledger.pool())) {
|
|
178
948
|
throw new AttoError('POOL_CHANGED', 'Wallet configuration changed during account selection. Retry this request.');
|
|
179
949
|
}
|
|
950
|
+
this.wallet.requireAccountsAvailable?.(chosen.plan.indexes);
|
|
180
951
|
return this.ledger.reserve({ id: request.requestId, index: chosen.source.address.index, destination, raw,
|
|
181
952
|
sourceAddress: chosen.source.address.address, network: snapshot.settings.network,
|
|
182
953
|
selection: request.index === undefined ? 'automatic' : 'explicit', plan: chosen.plan,
|
|
@@ -217,6 +988,8 @@ export class Payments {
|
|
|
217
988
|
}
|
|
218
989
|
}
|
|
219
990
|
async resume(record, request) {
|
|
991
|
+
if (record.external)
|
|
992
|
+
throw new AttoError('REQUEST_CONFLICT', 'This request ID belongs to a Marketplace top-up. Resume it with marketplace_topup using the original request ID.');
|
|
220
993
|
this.checkRequest(record, request);
|
|
221
994
|
if (record.status === 'published')
|
|
222
995
|
return record.result;
|
|
@@ -356,8 +1129,11 @@ export class Payments {
|
|
|
356
1129
|
}, AbortSignal.any([done.signal, AbortSignal.timeout(2000)]));
|
|
357
1130
|
return found;
|
|
358
1131
|
}
|
|
359
|
-
async reconcile() {
|
|
1132
|
+
async reconcile(candidateIndexes) {
|
|
1133
|
+
await this.reconcileMarketplaceIntents(candidateIndexes);
|
|
360
1134
|
for (const record of this.ledger.pending()) {
|
|
1135
|
+
if (record.external)
|
|
1136
|
+
continue;
|
|
361
1137
|
const release = this.store.tryAccountLocks(this.indexes(record));
|
|
362
1138
|
if (!release)
|
|
363
1139
|
continue;
|
|
@@ -370,6 +1146,8 @@ export class Payments {
|
|
|
370
1146
|
}
|
|
371
1147
|
}
|
|
372
1148
|
async reconcileRecord(record) {
|
|
1149
|
+
if (record.external)
|
|
1150
|
+
return;
|
|
373
1151
|
if (record.status === 'published' || record.status === 'failed')
|
|
374
1152
|
return;
|
|
375
1153
|
for (const step of record.plan?.steps ?? []) {
|
|
@@ -421,3 +1199,9 @@ export class Payments {
|
|
|
421
1199
|
available: amountOutput(accounts.reduce((sum, account) => sum + (account.busy ? 0n : BigInt(account.balance.raw)), 0n).toString()) };
|
|
422
1200
|
}
|
|
423
1201
|
}
|
|
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
|
+
}
|