mppx 0.17.6 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/dist/Currency.d.ts +59 -0
- package/dist/Currency.js +60 -0
- package/dist/Errors.d.ts +13 -0
- package/dist/Errors.js +15 -6
- package/dist/cli/cli.js +138 -138
- package/dist/cli/plugins/index.js +12 -12
- package/dist/cli/plugins/tempo.js +13 -1
- package/dist/client/Mppx.js +13 -4
- package/dist/client/internal/Fetch.d.ts +5 -0
- package/dist/client/internal/Fetch.js +16 -5
- package/dist/cloudflare/ChannelStore.d.ts +1 -2
- package/dist/cloudflare/ChannelStore.js +14 -20
- package/dist/cloudflare/Channels.d.ts +20 -2
- package/dist/cloudflare/Channels.js +47 -4
- package/dist/cloudflare/index.d.ts +1 -1
- package/dist/cloudflare/index.js +1 -1
- package/dist/discovery/Discovery.d.ts +116 -9
- package/dist/discovery/Discovery.js +169 -0
- package/dist/evm/server/Charge.js +2 -3
- package/dist/evm/server/Methods.d.ts +1 -1
- package/dist/evm/server/Methods.js +3 -2
- package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.d.ts +4 -1
- package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.js +4 -1
- package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.d.ts +5 -5
- package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.js +1 -1
- package/dist/extensions/identity/{email-otp/internal/Attestation.d.ts → attestation/Token.d.ts} +40 -26
- package/dist/extensions/identity/{email-otp/internal/Attestation.js → attestation/Token.js} +18 -3
- package/dist/extensions/identity/{email-otp/internal → attestation}/Types.d.ts +14 -14
- package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
- package/dist/extensions/identity/attestation/client/index.js +273 -0
- package/dist/extensions/identity/attestation/index.d.ts +20 -0
- package/dist/extensions/identity/attestation/index.js +18 -0
- package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
- package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
- package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
- package/dist/extensions/identity/attestation/server/index.js +119 -0
- package/dist/extensions/identity/email-otp/Constants.d.ts +5 -5
- package/dist/extensions/identity/email-otp/Constants.js +6 -5
- package/dist/extensions/identity/email-otp/Types.d.ts +4 -4
- package/dist/extensions/identity/email-otp/client/index.d.ts +22 -15
- package/dist/extensions/identity/email-otp/client/index.js +21 -9
- package/dist/extensions/identity/email-otp/index.d.ts +3 -8
- package/dist/extensions/identity/email-otp/index.js +3 -8
- package/dist/extensions/identity/email-otp/server/index.d.ts +16 -16
- package/dist/extensions/identity/email-otp/server/index.js +17 -14
- package/dist/extensions/identity/index.d.ts +6 -0
- package/dist/extensions/identity/index.js +6 -0
- package/dist/extensions/identity/internal/Verification.js +9 -5
- package/dist/extensions/identity/link/Constants.d.ts +102 -0
- package/dist/extensions/identity/link/Constants.js +16 -0
- package/dist/extensions/identity/link/client/index.d.ts +80 -0
- package/dist/extensions/identity/link/client/index.js +211 -0
- package/dist/extensions/identity/link/index.d.ts +12 -0
- package/dist/extensions/identity/link/index.js +12 -0
- package/dist/extensions/identity/link/server/index.d.ts +124 -0
- package/dist/extensions/identity/link/server/index.js +518 -0
- package/dist/extensions/identity/persona/Constants.d.ts +24 -0
- package/dist/extensions/identity/persona/Constants.js +24 -0
- package/dist/extensions/identity/persona/Did.d.ts +24 -0
- package/dist/extensions/identity/persona/Did.js +24 -0
- package/dist/extensions/identity/persona/Types.d.ts +21 -0
- package/dist/extensions/identity/persona/Types.js +2 -0
- package/dist/extensions/identity/persona/index.d.ts +10 -0
- package/dist/extensions/identity/persona/index.js +9 -0
- package/dist/extensions/identity/persona/server/index.d.ts +152 -0
- package/dist/extensions/identity/persona/server/index.js +263 -0
- package/dist/identity/Callback.d.ts +24 -5
- package/dist/identity/Callback.js +35 -11
- package/dist/identity/Client.d.ts +78 -5
- package/dist/identity/Client.js +165 -48
- package/dist/identity/Headers.d.ts +21 -0
- package/dist/identity/Headers.js +24 -0
- package/dist/identity/Server.d.ts +159 -37
- package/dist/identity/Server.js +309 -138
- package/dist/identity/Status.d.ts +14 -0
- package/dist/identity/Status.js +19 -0
- package/dist/identity/Types.d.ts +166 -65
- package/dist/identity/index.d.ts +2 -0
- package/dist/identity/index.js +2 -0
- package/dist/identity/internal/Requirements.d.ts +28 -0
- package/dist/identity/internal/Requirements.js +78 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/integrations/x402/Evm.d.ts +1 -0
- package/dist/internal/env.d.ts +14 -0
- package/dist/internal/env.js +38 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/proxy/internal/Headers.d.ts +1 -1
- package/dist/proxy/internal/Headers.js +11 -7
- package/dist/server/Mppx.d.ts +14 -6
- package/dist/server/Mppx.js +256 -149
- package/dist/server/internal/challengeMeta.d.ts +0 -6
- package/dist/server/internal/challengeMeta.js +3 -17
- package/dist/stripe/server/internal/html.gen.js +1 -1
- package/dist/tempo/client/Charge.d.ts +11 -8
- package/dist/tempo/client/Charge.js +53 -6
- package/dist/tempo/index.d.ts +4 -0
- package/dist/tempo/index.js +4 -0
- package/dist/tempo/internal/auto-swap.d.ts +6 -5
- package/dist/tempo/internal/auto-swap.js +17 -2
- package/dist/tempo/internal/currencies.d.ts +5 -4
- package/dist/tempo/internal/currencies.js +13 -9
- package/dist/tempo/internal/defaults.d.ts +7 -0
- package/dist/tempo/internal/defaults.js +7 -0
- package/dist/tempo/internal/fee-payer.js +8 -2
- package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
- package/dist/tempo/internal/machine-token-charge.js +82 -1
- package/dist/tempo/server/Charge.d.ts +14 -9
- package/dist/tempo/server/Charge.js +64 -3
- package/dist/tempo/server/Methods.d.ts +1 -1
- package/dist/tempo/server/Methods.js +4 -1
- package/dist/tempo/server/Subscription.d.ts +8 -0
- package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
- package/dist/tempo/server/internal/fallback-store.js +12 -3
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/transport.d.ts +1 -1
- package/dist/tempo/server/internal/transport.js +9 -16
- package/dist/tempo/session/client/CredentialState.js +31 -0
- package/dist/tempo/session/client/Session.d.ts +12 -6
- package/dist/tempo/session/client/Session.js +64 -18
- package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
- package/dist/tempo/session/server/ChannelStore.js +58 -8
- package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
- package/dist/tempo/session/server/CloseSupervisor.js +110 -12
- package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
- package/dist/tempo/session/server/CredentialVerification.js +6 -32
- package/dist/tempo/session/server/Session.d.ts +5 -1
- package/dist/tempo/session/server/Session.js +6 -3
- package/dist/tempo/session/server/Settlement.d.ts +7 -0
- package/dist/tempo/session/server/Settlement.js +36 -6
- package/dist/tempo/session/server/Sse.d.ts +2 -0
- package/dist/tempo/session/server/Sse.js +12 -12
- package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
- package/dist/tempo/subscription/KeyAuthorization.js +1 -1
- package/dist/x402/Assets.d.ts +14 -5
- package/dist/x402/Assets.js +11 -16
- package/package.json +19 -3
- package/dist/extensions/identity/email-otp/internal/Prover.d.ts +0 -46
- package/dist/extensions/identity/email-otp/internal/Prover.js +0 -168
- package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +0 -56
- package/dist/extensions/identity/email-otp/internal/Verifier.js +0 -116
- /package/dist/extensions/identity/{email-otp/internal → attestation}/Types.js +0 -0
|
@@ -4,7 +4,7 @@ import { VerificationFailedError } from '../../../Errors.js';
|
|
|
4
4
|
import * as Chain from '../precompile/Chain.js';
|
|
5
5
|
import { escrowAbi } from '../precompile/escrow.abi.js';
|
|
6
6
|
import * as ChannelStore from './ChannelStore.js';
|
|
7
|
-
import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, resolveChannelStore, } from './Settlement.js';
|
|
7
|
+
import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, resolveChannelStore, SettlementCheckpointError, trackSendAttempts, } from './Settlement.js';
|
|
8
8
|
/** Escrow event every close and withdrawal emits, with the amount paid to the payee. */
|
|
9
9
|
const channelClosedEvent = getAbiItem({ abi: escrowAbi, name: 'ChannelClosed' });
|
|
10
10
|
/** Channels whose escrow states one call reads, bounding its calldata and response size. */
|
|
@@ -145,7 +145,7 @@ async function superviseChannel(parameters, store, channel, state, blocks) {
|
|
|
145
145
|
: previous !== undefined && previous > since
|
|
146
146
|
? previous
|
|
147
147
|
: since;
|
|
148
|
-
const paid = await findSettledToPayee(parameters, channel, {
|
|
148
|
+
const paid = await findSettledToPayee(parameters, store, channel, {
|
|
149
149
|
fromBlock: fromBlock > 0n ? fromBlock : 0n,
|
|
150
150
|
toBlock: blocks.pinned.number,
|
|
151
151
|
});
|
|
@@ -173,8 +173,60 @@ async function superviseChannel(parameters, store, channel, state, blocks) {
|
|
|
173
173
|
? { ...current, closeSupervisedFromBlock: blocks.pinned.number }
|
|
174
174
|
: current);
|
|
175
175
|
if (state.closeRequestedAt === 0) {
|
|
176
|
-
if (channel.closeRequestedAt === 0n)
|
|
177
|
-
|
|
176
|
+
if (channel.closeRequestedAt === 0n) {
|
|
177
|
+
if (!parameters.closeUnsettled)
|
|
178
|
+
return settleDue(parameters, store, channel);
|
|
179
|
+
// Freeze spend atomically before exposing a close transaction. Its expiry bounds how long
|
|
180
|
+
// an ambiguous send can land, so later supervision can safely clear an expired marker.
|
|
181
|
+
const now = BigInt(Math.floor(Date.now() / 1000) || 1);
|
|
182
|
+
let claimed = false;
|
|
183
|
+
const closing = await store.updateChannel(channelId, (current) => {
|
|
184
|
+
claimed = false;
|
|
185
|
+
if (!current || current.finalized || current.closeRequestedAt !== 0n)
|
|
186
|
+
return current;
|
|
187
|
+
if (current.settledOnChain > state.settled)
|
|
188
|
+
return current;
|
|
189
|
+
if (Object.keys(current.prepaidRefunds ?? {}).length > 0)
|
|
190
|
+
return current;
|
|
191
|
+
const lease = current.scheduledSettlementLease;
|
|
192
|
+
if ((lease &&
|
|
193
|
+
lease.expiresAt > Date.now() &&
|
|
194
|
+
lease.owner !== parameters.settlementLeaseOwner) ||
|
|
195
|
+
(current.pendingSettlement && current.pendingSettlement.expiresAt > Date.now()))
|
|
196
|
+
return current;
|
|
197
|
+
const { pendingSettlement, ...rest } = current;
|
|
198
|
+
const onChain = ChannelStore.mergeActiveOnChainState(current, state);
|
|
199
|
+
current = {
|
|
200
|
+
...rest,
|
|
201
|
+
...onChain,
|
|
202
|
+
...(pendingSettlement && pendingSettlement.amount > onChain.settledOnChain
|
|
203
|
+
? { pendingSettlement }
|
|
204
|
+
: {}),
|
|
205
|
+
...(current.retainedVouchers
|
|
206
|
+
? {
|
|
207
|
+
retainedVouchers: current.retainedVouchers.filter((voucher) => voucher.cumulativeAmount > onChain.settledOnChain),
|
|
208
|
+
}
|
|
209
|
+
: {}),
|
|
210
|
+
};
|
|
211
|
+
if (current.spent <= current.settledOnChain ||
|
|
212
|
+
ChannelStore.resolveSettleableVoucher(current))
|
|
213
|
+
return current;
|
|
214
|
+
const next = ChannelStore.markPendingClose({
|
|
215
|
+
closeRequestedAt: now,
|
|
216
|
+
cumulativeAmount: current.highestVoucher?.cumulativeAmount ?? 0n,
|
|
217
|
+
current,
|
|
218
|
+
onChainDeposit: state.deposit,
|
|
219
|
+
onChainSettled: state.settled,
|
|
220
|
+
}).state;
|
|
221
|
+
claimed = true;
|
|
222
|
+
return next;
|
|
223
|
+
});
|
|
224
|
+
if (!closing || closing.finalized)
|
|
225
|
+
return { outcome: 'finalized' };
|
|
226
|
+
if (!claimed || !ChannelStore.isPrecompileState(closing))
|
|
227
|
+
return { outcome: closing.spent <= closing.settledOnChain ? 'settled' : 'open' };
|
|
228
|
+
return closeAtSpend(parameters, store, closing, state);
|
|
229
|
+
}
|
|
178
230
|
// A pinned read without a request means the payer cancelled it, unless the record holds a
|
|
179
231
|
// server close that may still land: those expire before they are cleared.
|
|
180
232
|
const cleared = {};
|
|
@@ -223,6 +275,8 @@ async function settleDue(parameters, store, channel) {
|
|
|
223
275
|
async function closeAtSpend(parameters, store, channel, state) {
|
|
224
276
|
const { client } = parameters;
|
|
225
277
|
const { channelId } = channel;
|
|
278
|
+
const send = trackSendAttempts(client);
|
|
279
|
+
let reverted = false;
|
|
226
280
|
try {
|
|
227
281
|
const voucher = channel.highestVoucher;
|
|
228
282
|
if (!voucher)
|
|
@@ -243,26 +297,42 @@ async function closeAtSpend(parameters, store, channel, state) {
|
|
|
243
297
|
payee: channel.payee,
|
|
244
298
|
sender: account?.address,
|
|
245
299
|
});
|
|
246
|
-
const
|
|
300
|
+
const validity = state.closeRequestedAt !== 0 || channel.pendingCloseAt === undefined
|
|
301
|
+
? {}
|
|
302
|
+
: { validBefore: Number(channel.pendingCloseAt) + ChannelStore.pendingCloseValiditySeconds };
|
|
303
|
+
const txHash = await Chain.closeOnChain(send.client, channel.descriptor, voucher.cumulativeAmount, capture, voucher.signature, channel.escrowContract, account
|
|
247
304
|
? {
|
|
248
305
|
account,
|
|
306
|
+
...validity,
|
|
249
307
|
candidateFeeTokens: parameters.candidateFeeTokens ?? [channel.token],
|
|
250
308
|
...(parameters.feePayer ? { feePayer: parameters.feePayer } : {}),
|
|
251
309
|
...(parameters.feePayerPolicy ? { feePayerPolicy: parameters.feePayerPolicy } : {}),
|
|
252
310
|
...(parameters.feeToken ? { feeToken: parameters.feeToken } : {}),
|
|
253
311
|
}
|
|
254
|
-
:
|
|
255
|
-
|
|
312
|
+
: validity).catch((error) => {
|
|
313
|
+
reverted = error instanceof VerificationFailedError;
|
|
314
|
+
throw error;
|
|
315
|
+
});
|
|
316
|
+
const receipt = await Chain.waitForSuccessfulReceipt(client, txHash).catch((error) => {
|
|
317
|
+
reverted = error instanceof VerificationFailedError;
|
|
318
|
+
throw error;
|
|
319
|
+
});
|
|
256
320
|
const { refundedToPayer, settledToPayee } = Chain.readChannelClosedReceiptFields(Chain.getChannelEvent(receipt, 'ChannelClosed', channelId));
|
|
257
|
-
if (settledToPayee > capture ||
|
|
321
|
+
if (settledToPayee > capture ||
|
|
322
|
+
(state.closeRequestedAt !== 0 && settledToPayee + refundedToPayer > state.deposit))
|
|
258
323
|
throw new VerificationFailedError({ reason: 'ChannelClosed amounts do not match state' });
|
|
259
|
-
|
|
324
|
+
let checkpointError;
|
|
325
|
+
await store
|
|
326
|
+
.updateChannel(channelId, (current) => ChannelStore.finalizeClosedChannelState({
|
|
260
327
|
captureAmount: settledToPayee,
|
|
261
328
|
channelId,
|
|
262
329
|
cumulativeAmount: voucher.cumulativeAmount,
|
|
263
330
|
current,
|
|
264
331
|
signature: voucher.signature,
|
|
265
|
-
}))
|
|
332
|
+
}))
|
|
333
|
+
.catch((cause) => {
|
|
334
|
+
checkpointError = { cause };
|
|
335
|
+
});
|
|
266
336
|
if (parameters.onSessionSettlement) {
|
|
267
337
|
try {
|
|
268
338
|
await parameters.onSessionSettlement(Object.freeze({
|
|
@@ -277,9 +347,24 @@ async function closeAtSpend(parameters, store, channel, state) {
|
|
|
277
347
|
// Errors are isolated: observers cannot break the close.
|
|
278
348
|
}
|
|
279
349
|
}
|
|
350
|
+
if (checkpointError)
|
|
351
|
+
throw new SettlementCheckpointError({ cause: checkpointError.cause, txHash });
|
|
280
352
|
return { outcome: 'closed', txHash };
|
|
281
353
|
}
|
|
282
354
|
catch (error) {
|
|
355
|
+
if (state.closeRequestedAt === 0 &&
|
|
356
|
+
channel.pendingCloseAt !== undefined &&
|
|
357
|
+
(!send.tracked.attempted || reverted)) {
|
|
358
|
+
await store.updateChannel(channelId, (current) => current &&
|
|
359
|
+
current.pendingCloseAt === channel.pendingCloseAt &&
|
|
360
|
+
current.closeRequestedAt === channel.pendingCloseAt
|
|
361
|
+
? {
|
|
362
|
+
...current,
|
|
363
|
+
closeRequestedAt: current.onChainCloseRequestedAt ?? 0n,
|
|
364
|
+
pendingCloseAt: undefined,
|
|
365
|
+
}
|
|
366
|
+
: current);
|
|
367
|
+
}
|
|
283
368
|
await reportSessionSettlementFailure(parameters.onSessionSettlementFailure, {
|
|
284
369
|
chainId: channel.chainId,
|
|
285
370
|
channelId,
|
|
@@ -290,9 +375,13 @@ async function closeAtSpend(parameters, store, channel, state) {
|
|
|
290
375
|
}
|
|
291
376
|
}
|
|
292
377
|
/** Amount paid to the payee when the channel closed within the blocks, if it did. */
|
|
293
|
-
async function findSettledToPayee(parameters, channel, range) {
|
|
378
|
+
async function findSettledToPayee(parameters, store, channel, range) {
|
|
294
379
|
const step = parameters.logBlockRange ?? defaultLogBlockRange;
|
|
295
|
-
|
|
380
|
+
const cursor = channel.closeSearchFromBlock;
|
|
381
|
+
const start = cursor !== undefined && cursor >= range.fromBlock && cursor <= range.toBlock
|
|
382
|
+
? cursor
|
|
383
|
+
: range.fromBlock;
|
|
384
|
+
for (let from = start; from <= range.toBlock; from += step) {
|
|
296
385
|
const to = from + step - 1n < range.toBlock ? from + step - 1n : range.toBlock;
|
|
297
386
|
const logs = await getLogs(parameters.client, {
|
|
298
387
|
address: channel.escrowContract,
|
|
@@ -304,7 +393,16 @@ async function findSettledToPayee(parameters, channel, range) {
|
|
|
304
393
|
const paid = logs.find((log) => !log.removed)?.args.settledToPayee;
|
|
305
394
|
if (paid !== undefined)
|
|
306
395
|
return paid;
|
|
396
|
+
// Resume after successful empty ranges if a later RPC call fails or the worker is interrupted.
|
|
397
|
+
await store.updateChannel(channel.channelId, (current) => current && !current.finalized
|
|
398
|
+
? {
|
|
399
|
+
...current,
|
|
400
|
+
closeSearchFromBlock: to + 1n,
|
|
401
|
+
}
|
|
402
|
+
: current);
|
|
307
403
|
}
|
|
404
|
+
// Empty logs can reflect a lagging RPC index. Retry from the original anchor next time.
|
|
405
|
+
await store.updateChannel(channel.channelId, (current) => current && !current.finalized ? { ...current, closeSearchFromBlock: undefined } : current);
|
|
308
406
|
return undefined;
|
|
309
407
|
}
|
|
310
408
|
//# sourceMappingURL=CloseSupervisor.js.map
|
|
@@ -89,6 +89,8 @@ export type BroadcastCredentialPayloadParameters = {
|
|
|
89
89
|
voucherStateMaxAge?: number | undefined;
|
|
90
90
|
/** Request price a voucher credential pays in the same store update that accepts it. */
|
|
91
91
|
chargeAmount?: bigint | undefined;
|
|
92
|
+
/** Durable delivery key for an SSE request charged before its first item. */
|
|
93
|
+
prepaidRefundKey?: string | undefined;
|
|
92
94
|
/** Called with the stored channel after `chargeAmount` was charged. */
|
|
93
95
|
onCharged?: ((channel: ChannelStore.State) => void) | undefined;
|
|
94
96
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isAddress, isAddressEqual, zeroAddress, } from 'viem';
|
|
2
2
|
import { AmountExceedsDepositError, ChannelClosedError, ChannelNotFoundError, DeltaTooSmallError, InsufficientBalanceError, InvalidSignatureError, VerificationFailedError, } from '../../../Errors.js';
|
|
3
3
|
import * as Chain from '../precompile/Chain.js';
|
|
4
4
|
import { readChannelClosedReceiptFields } from '../precompile/Chain.js';
|
|
@@ -7,7 +7,7 @@ import { createSessionReceipt, uint96, } from '../precompile/Protocol.js';
|
|
|
7
7
|
import * as Voucher from '../precompile/Voucher.js';
|
|
8
8
|
import * as ChannelStore from './ChannelStore.js';
|
|
9
9
|
import { getChallengePaymentFields } from './RequestState.js';
|
|
10
|
-
import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, } from './Settlement.js';
|
|
10
|
+
import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, trackSendAttempts, } from './Settlement.js';
|
|
11
11
|
/** Returns the effective voucher signer for a TIP-1034 descriptor. */
|
|
12
12
|
export function authorizedSigner(descriptor) {
|
|
13
13
|
return isAddressEqual(descriptor.authorizedSigner, zeroAddress)
|
|
@@ -699,6 +699,7 @@ async function handleVoucherCredential(parameters) {
|
|
|
699
699
|
channelState: storedChannelState(channel),
|
|
700
700
|
methodDetails: { chainId, escrowContract: escrow },
|
|
701
701
|
chargeAmount,
|
|
702
|
+
prepaidRefundKey: parameters.prepaidRefundKey,
|
|
702
703
|
onCharged,
|
|
703
704
|
});
|
|
704
705
|
}
|
|
@@ -726,6 +727,7 @@ async function handleVoucherCredential(parameters) {
|
|
|
726
727
|
methodDetails: { chainId, escrowContract: escrow },
|
|
727
728
|
verifiedAt: startedAt,
|
|
728
729
|
chargeAmount,
|
|
730
|
+
prepaidRefundKey: parameters.prepaidRefundKey,
|
|
729
731
|
onCharged,
|
|
730
732
|
});
|
|
731
733
|
}
|
|
@@ -772,6 +774,7 @@ async function acceptVoucherInOneUpdate(parameters, voucher, descriptor) {
|
|
|
772
774
|
const acceptance = ChannelStore.planVoucherAcceptance({
|
|
773
775
|
accepted: ChannelStore.acceptVoucherStateUpdate({ channelState, current, voucher }),
|
|
774
776
|
chargeAmount,
|
|
777
|
+
prepaidRefundKey: parameters.prepaidRefundKey,
|
|
775
778
|
});
|
|
776
779
|
return { op: 'set', value: acceptance.channel, result: acceptance };
|
|
777
780
|
});
|
|
@@ -796,12 +799,7 @@ async function recordPendingClose(parameters, channelId, channelState) {
|
|
|
796
799
|
const closing = await store.updateChannel(channelId, (current) => current
|
|
797
800
|
? {
|
|
798
801
|
...current,
|
|
799
|
-
|
|
800
|
-
? channelState.settled
|
|
801
|
-
: current.settledOnChain,
|
|
802
|
-
closeRequestedAt: BigInt(channelState.closeRequestedAt) > current.closeRequestedAt
|
|
803
|
-
? BigInt(channelState.closeRequestedAt)
|
|
804
|
-
: current.closeRequestedAt,
|
|
802
|
+
...ChannelStore.mergeActiveOnChainState(current, channelState),
|
|
805
803
|
}
|
|
806
804
|
: current);
|
|
807
805
|
if (closing && !closing.finalized && channelState.deposit > 0n)
|
|
@@ -839,30 +837,6 @@ function recordOnChainReadInBackground(parameters, channelId, read) {
|
|
|
839
837
|
})
|
|
840
838
|
.catch(() => { });
|
|
841
839
|
}
|
|
842
|
-
const sendMethods = new Set([
|
|
843
|
-
'eth_sendRawTransaction',
|
|
844
|
-
'eth_sendRawTransactionSync',
|
|
845
|
-
'eth_sendTransaction',
|
|
846
|
-
]);
|
|
847
|
-
/** Wraps a client so a failed close can tell whether its transaction was handed to the node. */
|
|
848
|
-
function trackSendAttempts(client) {
|
|
849
|
-
const tracked = { attempted: false };
|
|
850
|
-
const trackedClient = createClient({
|
|
851
|
-
account: client.account,
|
|
852
|
-
chain: client.chain,
|
|
853
|
-
pollingInterval: client.pollingInterval,
|
|
854
|
-
transport: custom({
|
|
855
|
-
request(parameters) {
|
|
856
|
-
if (sendMethods.has(parameters.method))
|
|
857
|
-
tracked.attempted = true;
|
|
858
|
-
return client.request(parameters);
|
|
859
|
-
},
|
|
860
|
-
},
|
|
861
|
-
// The wrapped client already owns retries.
|
|
862
|
-
{ retryCount: 0 }),
|
|
863
|
-
});
|
|
864
|
-
return { client: trackedClient, tracked };
|
|
865
|
-
}
|
|
866
840
|
async function handleCloseCredential(parameters) {
|
|
867
841
|
const { store, client, challenge, payload, chainId, escrow } = parameters;
|
|
868
842
|
const request = getChallengePaymentFields(challenge);
|
|
@@ -193,7 +193,11 @@ export declare namespace session {
|
|
|
193
193
|
*
|
|
194
194
|
* Session mutations must be linearizable across instances so spent,
|
|
195
195
|
* highest-voucher, top-up, and close/finalization updates cannot race.
|
|
196
|
-
*
|
|
196
|
+
*
|
|
197
|
+
* If omitted, this throws in production (`NODE_ENV=production`), on
|
|
198
|
+
* multi-instance platforms and on Cloudflare Workers, and otherwise warns
|
|
199
|
+
* and falls back to an in-memory store. Pass `Store.memory()` explicitly
|
|
200
|
+
* for tests or local single-process usage.
|
|
197
201
|
*/
|
|
198
202
|
store?: Store.AtomicStore | undefined;
|
|
199
203
|
/** Enable SSE streaming. Pass `true` for defaults or an options object to configure SSE. */
|
|
@@ -363,6 +363,8 @@ export function session(p) {
|
|
|
363
363
|
minVoucherDelta: parameters.minVoucherDelta,
|
|
364
364
|
request,
|
|
365
365
|
});
|
|
366
|
+
const prepaidRefundKey = parameters.sse ? `stream:${globalThis.crypto.randomUUID()}` : undefined;
|
|
367
|
+
const markPrepaidReceipt = (receipt) => Transport.markPrepaidSessionTick(receipt, prepaidRefundKey);
|
|
366
368
|
const chargeAmount = (parameters.chargeOnAcceptance || parameters.sse) &&
|
|
367
369
|
shouldChargeVoucherOnAcceptance({
|
|
368
370
|
capturedRequest: envelope?.capturedRequest,
|
|
@@ -388,6 +390,7 @@ export function session(p) {
|
|
|
388
390
|
account,
|
|
389
391
|
challenge,
|
|
390
392
|
chargeAmount,
|
|
393
|
+
prepaidRefundKey,
|
|
391
394
|
onCharged: (channel) => {
|
|
392
395
|
acceptance.charged = channel;
|
|
393
396
|
},
|
|
@@ -424,7 +427,7 @@ export function session(p) {
|
|
|
424
427
|
...sessionReceipt,
|
|
425
428
|
...(settlementTxHash ? { txHash: settlementTxHash } : {}),
|
|
426
429
|
};
|
|
427
|
-
return parameters.sse ?
|
|
430
|
+
return parameters.sse ? markPrepaidReceipt(receipt) : receipt;
|
|
428
431
|
}
|
|
429
432
|
return applyVerifiedHttpAccounting({
|
|
430
433
|
capturedRequest: envelope?.capturedRequest,
|
|
@@ -432,9 +435,9 @@ export function session(p) {
|
|
|
432
435
|
receipt: sessionReceipt,
|
|
433
436
|
getRequestAmount: () => BigInt(context.request.amount ?? challenge.request.amount),
|
|
434
437
|
sseEnabled: Boolean(parameters.sse),
|
|
435
|
-
markPrepaidReceipt
|
|
438
|
+
markPrepaidReceipt,
|
|
436
439
|
unitType: context.request.unitType,
|
|
437
|
-
charge: (channelId, requestAmount) => chargeSessionChannel({ store, channelId, amount: requestAmount }),
|
|
440
|
+
charge: (channelId, requestAmount) => chargeSessionChannel({ store, channelId, amount: requestAmount, prepaidRefundKey }),
|
|
438
441
|
settleCharged: settleAcceptedCharge,
|
|
439
442
|
});
|
|
440
443
|
};
|
|
@@ -282,4 +282,11 @@ export declare function settleBatch(store: SessionStoreInput, client: Chain.Tran
|
|
|
282
282
|
export declare function ignoreRetryableSettlementFailure(error: unknown): undefined;
|
|
283
283
|
/** @internal Reports a settlement failure without letting observer errors replace it. */
|
|
284
284
|
export declare function reportSessionSettlementFailure(onSessionSettlementFailure: OnSessionSettlementFailure | undefined, context: SessionSettlementFailureContext): Promise<void>;
|
|
285
|
+
/** Wraps a client so a failed close can tell whether its transaction was handed to the node. */
|
|
286
|
+
export declare function trackSendAttempts(client: Chain.TransactionClient): {
|
|
287
|
+
client: Chain.TransactionClient;
|
|
288
|
+
tracked: {
|
|
289
|
+
attempted: boolean;
|
|
290
|
+
};
|
|
291
|
+
};
|
|
285
292
|
//# sourceMappingURL=Settlement.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { BaseError as viem_BaseError, ExecutionRevertedError, HttpRequestError, InternalRpcError, isAddress, isAddressEqual, LimitExceededRpcError, parseUnits, ResourceUnavailableRpcError, RpcRequestError, SocketClosedError, TimeoutError, WaitForTransactionReceiptTimeoutError, WebSocketRequestError, zeroAddress, } from 'viem';
|
|
2
|
-
import { BadRequestError, ChannelClosedError, ChannelNotFoundError,
|
|
1
|
+
import { BaseError as viem_BaseError, createClient, custom, ExecutionRevertedError, HttpRequestError, InternalRpcError, isAddress, isAddressEqual, LimitExceededRpcError, parseUnits, ResourceUnavailableRpcError, RpcRequestError, SocketClosedError, TimeoutError, WaitForTransactionReceiptTimeoutError, WebSocketRequestError, zeroAddress, } from 'viem';
|
|
2
|
+
import { BadRequestError, ChannelClosedError, ChannelNotFoundError, VerificationFailedError, } from '../../../Errors.js';
|
|
3
3
|
import { isSessionContentRequest } from '../../server/internal/request-body.js';
|
|
4
4
|
import * as Chain from '../precompile/Chain.js';
|
|
5
5
|
import { readSettledReceiptFields } from '../precompile/Chain.js';
|
|
@@ -126,6 +126,8 @@ export async function claimScheduledSettlement(parameters) {
|
|
|
126
126
|
claimed = false;
|
|
127
127
|
if (!current || !isSettlementDue(current, schedule))
|
|
128
128
|
return current;
|
|
129
|
+
if (ChannelStore.hasPendingClose(current, now))
|
|
130
|
+
return current;
|
|
129
131
|
const lease = current.scheduledSettlementLease;
|
|
130
132
|
if (lease && lease.expiresAt > now)
|
|
131
133
|
return current;
|
|
@@ -202,11 +204,12 @@ export async function applyVerifiedHttpAccounting(parameters) {
|
|
|
202
204
|
}
|
|
203
205
|
/** Atomically deducts spend from a channel and maps store failures to typed session errors. */
|
|
204
206
|
export async function chargeSessionChannel(parameters) {
|
|
205
|
-
const { store, channelId, amount, idempotencyKey, retention } = parameters;
|
|
207
|
+
const { store, channelId, amount, idempotencyKey, retention, prepaidRefundKey } = parameters;
|
|
206
208
|
ChannelStore.assertIdempotencyOptions({ idempotencyKey, retention });
|
|
207
209
|
let result;
|
|
208
210
|
try {
|
|
209
211
|
result = await ChannelStore.deductFromChannel(store, channelId, amount, {
|
|
212
|
+
prepaidRefundKey,
|
|
210
213
|
idempotencyKey,
|
|
211
214
|
retention,
|
|
212
215
|
});
|
|
@@ -222,9 +225,7 @@ export async function chargeSessionChannel(parameters) {
|
|
|
222
225
|
if (result.channel.closeRequestedAt !== 0n)
|
|
223
226
|
throw new ChannelClosedError({ reason: 'channel has a pending close request' });
|
|
224
227
|
const available = result.channel.highestVoucherAmount - result.channel.spent;
|
|
225
|
-
throw
|
|
226
|
-
reason: `requested ${amount}, available ${available}`,
|
|
227
|
-
});
|
|
228
|
+
throw ChannelStore.insufficientBalance(result.channel, `requested ${amount}, available ${available}`);
|
|
228
229
|
}
|
|
229
230
|
return result.channel;
|
|
230
231
|
}
|
|
@@ -338,6 +339,11 @@ export async function settle(store_, client, channelId_, options) {
|
|
|
338
339
|
// Choosing the voucher and raising the credit floor in one update keeps a concurrent credit from
|
|
339
340
|
// lowering spent below what this transaction captures.
|
|
340
341
|
await store.updateChannel(channelId, (current) => {
|
|
342
|
+
if (current && ChannelStore.hasPendingClose(current)) {
|
|
343
|
+
claim.channel = undefined;
|
|
344
|
+
claim.voucher = undefined;
|
|
345
|
+
return current;
|
|
346
|
+
}
|
|
341
347
|
claim.channel = current ?? undefined;
|
|
342
348
|
claim.voucher = (current && ChannelStore.resolveSettleableVoucher(current)) ?? undefined;
|
|
343
349
|
if (!current || !claim.voucher)
|
|
@@ -520,4 +526,28 @@ async function emitSessionSettlement(onSessionSettlement, context) {
|
|
|
520
526
|
// Errors are isolated — observers cannot break the settlement flow.
|
|
521
527
|
}
|
|
522
528
|
}
|
|
529
|
+
const sendMethods = new Set([
|
|
530
|
+
'eth_sendRawTransaction',
|
|
531
|
+
'eth_sendRawTransactionSync',
|
|
532
|
+
'eth_sendTransaction',
|
|
533
|
+
]);
|
|
534
|
+
/** Wraps a client so a failed close can tell whether its transaction was handed to the node. */
|
|
535
|
+
export function trackSendAttempts(client) {
|
|
536
|
+
const tracked = { attempted: false };
|
|
537
|
+
const trackedClient = createClient({
|
|
538
|
+
account: client.account,
|
|
539
|
+
chain: client.chain,
|
|
540
|
+
pollingInterval: client.pollingInterval,
|
|
541
|
+
transport: custom({
|
|
542
|
+
request(parameters) {
|
|
543
|
+
if (sendMethods.has(parameters.method))
|
|
544
|
+
tracked.attempted = true;
|
|
545
|
+
return client.request(parameters);
|
|
546
|
+
},
|
|
547
|
+
},
|
|
548
|
+
// The wrapped client already owns retries.
|
|
549
|
+
{ retryCount: 0 }),
|
|
550
|
+
});
|
|
551
|
+
return { client: trackedClient, tracked };
|
|
552
|
+
}
|
|
523
553
|
//# sourceMappingURL=Settlement.js.map
|
|
@@ -29,6 +29,8 @@ export declare class PrepaidRefundError extends Error {
|
|
|
29
29
|
}
|
|
30
30
|
/** Maximum retained automatic refund operations per channel. Never evict live retry keys. */
|
|
31
31
|
export declare const maxPrepaidRefunds = 128;
|
|
32
|
+
/** Releases a completed prepaid delivery so automatic channel closure can proceed. */
|
|
33
|
+
export declare function clearPrepaidRefund(store: ChannelStore.ChannelStore, channelId: Hex, key: string): Promise<void>;
|
|
32
34
|
/**
|
|
33
35
|
* Persist a delivery obligation before returning a managed response. Failed hook deliveries remain
|
|
34
36
|
* in `channel.prepaidRefunds` for a merchant worker. Pending entries require manual delivery
|
|
@@ -14,6 +14,16 @@ export class PrepaidRefundError extends Error {
|
|
|
14
14
|
}
|
|
15
15
|
/** Maximum retained automatic refund operations per channel. Never evict live retry keys. */
|
|
16
16
|
export const maxPrepaidRefunds = 128;
|
|
17
|
+
/** Releases a completed prepaid delivery so automatic channel closure can proceed. */
|
|
18
|
+
export async function clearPrepaidRefund(store, channelId, key) {
|
|
19
|
+
await store.updateChannel(channelId, (current) => {
|
|
20
|
+
if (!current?.prepaidRefunds?.[key])
|
|
21
|
+
return current;
|
|
22
|
+
const prepaidRefunds = { ...current.prepaidRefunds };
|
|
23
|
+
delete prepaidRefunds[key];
|
|
24
|
+
return { ...current, prepaidRefunds };
|
|
25
|
+
});
|
|
26
|
+
}
|
|
17
27
|
/**
|
|
18
28
|
* Persist a delivery obligation before returning a managed response. Failed hook deliveries remain
|
|
19
29
|
* in `channel.prepaidRefunds` for a merchant worker. Pending entries require manual delivery
|
|
@@ -101,20 +111,10 @@ export function serve(options) {
|
|
|
101
111
|
const refundIdempotencyKey = options.refundIdempotencyKey ?? `stream:${globalThis.crypto.randomUUID()}`;
|
|
102
112
|
ChannelStore.assertIdempotencyOptions({ idempotencyKey: refundIdempotencyKey });
|
|
103
113
|
const refundOptions = { ...options, refundIdempotencyKey };
|
|
104
|
-
const clearObligation =
|
|
105
|
-
if (!options.autoCreditPrepaid)
|
|
106
|
-
return;
|
|
107
|
-
await store.updateChannel(channelId, (current) => {
|
|
108
|
-
if (!current?.prepaidRefunds?.[refundIdempotencyKey])
|
|
109
|
-
return current;
|
|
110
|
-
const prepaidRefunds = { ...current.prepaidRefunds };
|
|
111
|
-
delete prepaidRefunds[refundIdempotencyKey];
|
|
112
|
-
return { ...current, prepaidRefunds };
|
|
113
|
-
});
|
|
114
|
-
};
|
|
114
|
+
const clearObligation = () => clearPrepaidRefund(store, channelId, refundIdempotencyKey);
|
|
115
115
|
const creditFailedDelivery = async () => {
|
|
116
116
|
if (!options.autoCreditPrepaid)
|
|
117
|
-
return;
|
|
117
|
+
return clearObligation();
|
|
118
118
|
if (undeliveredPrepaidUnits === 0 || tickCost === 0n) {
|
|
119
119
|
await clearObligation();
|
|
120
120
|
return;
|
|
@@ -135,7 +135,7 @@ export async function signSubscriptionKeyAuthorization(parameters) {
|
|
|
135
135
|
hash: KeyAuthorization.getSignPayload(authorization),
|
|
136
136
|
});
|
|
137
137
|
const signatureEnvelope = SignatureEnvelope.from(signature);
|
|
138
|
-
if (signatureEnvelope.type === 'keychain' || signatureEnvelope.type === '
|
|
138
|
+
if (signatureEnvelope.type === 'keychain' || signatureEnvelope.type === 'configurable') {
|
|
139
139
|
throw new VerificationFailedError({
|
|
140
140
|
reason: 'keyAuthorization must use a primitive signature',
|
|
141
141
|
});
|
package/dist/x402/Assets.d.ts
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
import type { Token } from 'viem/tokens';
|
|
2
|
+
import * as Currency_ from '../Currency.js';
|
|
2
3
|
import type { Asset, EvmNetwork, ExactTransfer } from './Types.js';
|
|
3
4
|
declare const knownAsset: unique symbol;
|
|
4
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Known x402 asset metadata: a token resolved to one chain, as `ousd(4217)` is, with the
|
|
7
|
+
* transfer metadata that EIP-3009 and Permit2 signing need.
|
|
8
|
+
*/
|
|
5
9
|
export type KnownAsset = Asset & {
|
|
6
10
|
readonly [knownAsset]: true;
|
|
11
|
+
/** Chain ID of `network`. */
|
|
12
|
+
chainId: number;
|
|
7
13
|
network: EvmNetwork;
|
|
8
14
|
};
|
|
9
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* Viem token metadata from `viem/tokens`.
|
|
17
|
+
* @deprecated Use `Token` from `viem/tokens`.
|
|
18
|
+
*/
|
|
10
19
|
export type ViemToken = Token;
|
|
11
|
-
/** Currency
|
|
12
|
-
export type Currency =
|
|
20
|
+
/** Currency accepted by EVM and x402 payment config: any mppx `Currency`, or a known asset. */
|
|
21
|
+
export type Currency = Currency_.Currency | KnownAsset;
|
|
13
22
|
/** Creates typed x402 asset metadata for custom tokens. */
|
|
14
23
|
export declare function define(parameters: define.Parameters): KnownAsset;
|
|
15
24
|
export declare namespace define {
|
|
@@ -55,7 +64,7 @@ export declare const celoSepolia: {
|
|
|
55
64
|
/** Returns true when a value is known x402 asset metadata. */
|
|
56
65
|
export declare function isAsset(value: unknown): value is KnownAsset;
|
|
57
66
|
/** Returns true when a value is a `viem/tokens` token definition. */
|
|
58
|
-
export declare
|
|
67
|
+
export declare const isToken: (value: unknown) => value is Token;
|
|
59
68
|
/** Returns true when a currency is a raw address without chain metadata. */
|
|
60
69
|
export declare function isRawAddress(currency: Currency): currency is `0x${string}`;
|
|
61
70
|
/** Resolves currency metadata for an EVM network. */
|
package/dist/x402/Assets.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { getAddress } from 'viem';
|
|
2
|
+
import * as Currency_ from '../Currency.js';
|
|
2
3
|
const knownAsset = Symbol('mppx.x402.asset');
|
|
3
4
|
/** Creates typed x402 asset metadata for custom tokens. */
|
|
4
5
|
export function define(parameters) {
|
|
5
6
|
return {
|
|
6
7
|
[knownAsset]: true,
|
|
7
8
|
address: parameters.address,
|
|
9
|
+
chainId: toChainId(parameters.network),
|
|
8
10
|
decimals: parameters.decimals,
|
|
9
11
|
network: parameters.network,
|
|
10
12
|
transfer: parameters.transfer,
|
|
@@ -93,11 +95,7 @@ export function isAsset(value) {
|
|
|
93
95
|
return value[knownAsset] === true;
|
|
94
96
|
}
|
|
95
97
|
/** Returns true when a value is a `viem/tokens` token definition. */
|
|
96
|
-
export
|
|
97
|
-
return (typeof value === 'function' &&
|
|
98
|
-
typeof value.addresses === 'object' &&
|
|
99
|
-
typeof value.decimals === 'number');
|
|
100
|
-
}
|
|
98
|
+
export const isToken = Currency_.isToken;
|
|
101
99
|
/** Returns true when a currency is a raw address without chain metadata. */
|
|
102
100
|
export function isRawAddress(currency) {
|
|
103
101
|
return typeof currency === 'string';
|
|
@@ -113,18 +111,15 @@ export function resolve(currency, network) {
|
|
|
113
111
|
transfer: currency.transfer,
|
|
114
112
|
};
|
|
115
113
|
}
|
|
116
|
-
if (
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
return
|
|
121
|
-
address,
|
|
122
|
-
decimals: currency.decimals,
|
|
123
|
-
name: currency.name,
|
|
124
|
-
};
|
|
125
|
-
}
|
|
114
|
+
if (typeof currency === 'string')
|
|
115
|
+
return { address: currency };
|
|
116
|
+
const resolved = Currency_.resolve(currency, { chainId: toChainId(network) });
|
|
117
|
+
if (!resolved)
|
|
118
|
+
return undefined;
|
|
126
119
|
return {
|
|
127
|
-
address:
|
|
120
|
+
address: resolved.address,
|
|
121
|
+
decimals: resolved.decimals,
|
|
122
|
+
name: resolved.name,
|
|
128
123
|
};
|
|
129
124
|
}
|
|
130
125
|
/** Returns true when a currency resolves to the accepted address on the network. */
|