@t3foundry/tasra-sdk 0.3.1 → 0.4.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/CHANGELOG.md +1067 -28
- package/README.md +15 -0
- package/dist/app/approvals.d.ts +66 -4
- package/dist/app/approvals.js +153 -16
- package/dist/app/authorization.d.ts +1 -1
- package/dist/app/authorization.js +1 -1
- package/dist/app/browser.d.ts +63 -0
- package/dist/app/browser.js +242 -0
- package/dist/app/client.d.ts +114 -13
- package/dist/app/client.js +302 -76
- package/dist/app/identity.js +21 -9
- package/dist/app/index.d.ts +28 -3
- package/dist/app/index.js +16 -1
- package/dist/app/memory-store.d.ts +7 -0
- package/dist/app/memory-store.js +55 -0
- package/dist/app/node.d.ts +34 -6
- package/dist/app/node.js +387 -64
- package/dist/app/paid-allowance.d.ts +325 -0
- package/dist/app/paid-allowance.js +1290 -0
- package/dist/app/paid-approval.d.ts +122 -0
- package/dist/app/paid-approval.js +379 -0
- package/dist/app/paid-journal.d.ts +51 -0
- package/dist/app/paid-journal.js +117 -0
- package/dist/app/paid-keys.d.ts +12 -0
- package/dist/app/paid-keys.js +20 -0
- package/dist/app/paid-operation.d.ts +821 -0
- package/dist/app/paid-operation.js +1720 -0
- package/dist/app/paid-reservation.d.ts +157 -0
- package/dist/app/paid-reservation.js +323 -0
- package/dist/app/paid-session.d.ts +147 -0
- package/dist/app/paid-session.js +578 -0
- package/dist/app/payer-queue.d.ts +11 -0
- package/dist/app/payer-queue.js +27 -0
- package/dist/app/policy-bootstrap.d.ts +342 -0
- package/dist/app/policy-bootstrap.js +365 -0
- package/dist/app/policy-operation.d.ts +47 -0
- package/dist/app/policy-operation.js +101 -0
- package/dist/app/ready-slot.d.ts +12 -0
- package/dist/app/ready-slot.js +5 -2
- package/dist/app/rotation-lock.d.ts +38 -0
- package/dist/app/rotation-lock.js +42 -0
- package/dist/app/session-decrypt.d.ts +135 -0
- package/dist/app/session-decrypt.js +335 -0
- package/dist/app/session-grants.d.ts +349 -0
- package/dist/app/session-grants.js +811 -0
- package/dist/app/signing-intents.d.ts +78 -0
- package/dist/app/signing-intents.js +95 -0
- package/dist/app/store-commit.d.ts +63 -0
- package/dist/app/store-commit.js +126 -0
- package/dist/app/store-errors.d.ts +8 -0
- package/dist/app/store-errors.js +11 -0
- package/dist/app/tasra-client.d.ts +2 -0
- package/dist/app/tasra-client.js +1 -1
- package/dist/app/wallet.js +4 -1
- package/dist/auth/holderProof.d.ts +3 -0
- package/dist/auth/holderProof.js +8 -7
- package/dist/auth/verifier.d.ts +4 -2
- package/dist/auth/verifier.js +5 -2
- package/dist/chain/abis/index.d.ts +6178 -4101
- package/dist/chain/abis/index.js +3 -0
- package/dist/chain/abis/keyRegistry.d.ts +256 -0
- package/dist/chain/abis/keyRegistry.js +333 -0
- package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
- package/dist/chain/abis/prepaidFaultOracle.js +413 -0
- package/dist/chain/abis/settlement.d.ts +2203 -703
- package/dist/chain/abis/settlement.js +2685 -764
- package/dist/chain/allowance.d.ts +358 -0
- package/dist/chain/allowance.js +800 -0
- package/dist/chain/billing.d.ts +85 -0
- package/dist/chain/billing.js +197 -0
- package/dist/chain/chainId.d.ts +13 -0
- package/dist/chain/chainId.js +26 -0
- package/dist/chain/client.d.ts +15 -1
- package/dist/chain/client.js +57 -1
- package/dist/chain/commitmentRecovery.d.ts +51 -0
- package/dist/chain/commitmentRecovery.js +38 -0
- package/dist/chain/committeeClient.d.ts +17 -10
- package/dist/chain/committeeClient.js +64 -16
- package/dist/chain/committeeDraw.d.ts +12 -0
- package/dist/chain/committeeDraw.js +56 -0
- package/dist/chain/custodyHealth.d.ts +212 -0
- package/dist/chain/custodyHealth.js +365 -0
- package/dist/chain/deployments.js +2 -0
- package/dist/chain/events.js +2 -0
- package/dist/chain/headFollower.d.ts +77 -0
- package/dist/chain/headFollower.js +219 -0
- package/dist/chain/headPrefetch.d.ts +23 -0
- package/dist/chain/headPrefetch.js +67 -0
- package/dist/chain/index.d.ts +50 -8
- package/dist/chain/index.js +28 -3
- package/dist/chain/keeperExecution.d.ts +44 -0
- package/dist/chain/keeperExecution.js +127 -0
- package/dist/chain/keeperRecovery.d.ts +78 -0
- package/dist/chain/keeperRecovery.js +91 -0
- package/dist/chain/node.d.ts +24 -1
- package/dist/chain/node.js +88 -43
- package/dist/chain/offchain.d.ts +2 -0
- package/dist/chain/paidAgentTransport.d.ts +38 -0
- package/dist/chain/paidAgentTransport.js +1 -0
- package/dist/chain/paidEpoch.d.ts +66 -0
- package/dist/chain/paidEpoch.js +139 -0
- package/dist/chain/paidPacing.d.ts +81 -0
- package/dist/chain/paidPacing.js +136 -0
- package/dist/chain/pinnedReads.d.ts +49 -0
- package/dist/chain/pinnedReads.js +218 -0
- package/dist/chain/prepaid.d.ts +383 -0
- package/dist/chain/prepaid.js +1046 -0
- package/dist/chain/prepaidEscape.d.ts +274 -0
- package/dist/chain/prepaidEscape.js +432 -0
- package/dist/chain/prepaidFault.d.ts +94 -0
- package/dist/chain/prepaidFault.js +148 -0
- package/dist/chain/receipt.d.ts +24 -0
- package/dist/chain/receipt.js +82 -0
- package/dist/chain/registeredAgent.d.ts +68 -3
- package/dist/chain/registeredAgent.js +143 -42
- package/dist/chain/registeredOperation.d.ts +10 -1
- package/dist/chain/registeredOperation.js +18 -3
- package/dist/chain/registeredPaidAgent.d.ts +254 -0
- package/dist/chain/registeredPaidAgent.js +889 -0
- package/dist/chain/registeredRelay.d.ts +31 -1
- package/dist/chain/registeredRelay.js +164 -43
- package/dist/chain/relayVoucher.d.ts +64 -0
- package/dist/chain/relayVoucher.js +69 -0
- package/dist/chain/reservation.d.ts +239 -0
- package/dist/chain/reservation.js +746 -0
- package/dist/chain/reshareRoster.d.ts +64 -0
- package/dist/chain/reshareRoster.js +85 -0
- package/dist/chain/revertReason.d.ts +8 -0
- package/dist/chain/revertReason.js +2 -1
- package/dist/chain/rotationLock.d.ts +130 -0
- package/dist/chain/rotationLock.js +168 -0
- package/dist/chain/serviceRequestPolicy.d.ts +47 -0
- package/dist/chain/serviceRequestPolicy.js +86 -0
- package/dist/chain/services.d.ts +7 -0
- package/dist/chain/services.js +44 -4
- package/dist/chain/slotClient.js +11 -2
- package/dist/chain/slotHandoff.d.ts +81 -0
- package/dist/chain/slotHandoff.js +166 -0
- package/dist/chain/slotSeed.d.ts +47 -5
- package/dist/chain/slotSeed.js +173 -42
- package/dist/chain/verifierSnapshot.d.ts +36 -0
- package/dist/chain/verifierSnapshot.js +197 -0
- package/dist/chain/write.d.ts +111 -21
- package/dist/chain/write.js +378 -146
- package/dist/committee/blsSharing.d.ts +53 -0
- package/dist/committee/blsSharing.js +90 -0
- package/dist/committee/client.d.ts +62 -23
- package/dist/committee/client.js +288 -72
- package/dist/committee/dual-operation.d.ts +165 -0
- package/dist/committee/dual-operation.js +229 -0
- package/dist/committee/dual-sign.d.ts +26 -1
- package/dist/committee/dual-sign.js +85 -7
- package/dist/committee/ecdsa.d.ts +38 -0
- package/dist/committee/ecdsa.js +87 -15
- package/dist/committee/evidence.d.ts +30 -0
- package/dist/committee/evidence.js +65 -0
- package/dist/committee/execution.d.ts +414 -0
- package/dist/committee/execution.js +446 -0
- package/dist/committee/extraction.js +33 -26
- package/dist/committee/index.d.ts +30 -7
- package/dist/committee/index.js +18 -6
- package/dist/committee/keeperExecution.d.ts +37 -0
- package/dist/committee/keeperExecution.js +141 -0
- package/dist/committee/oauth.d.ts +14 -4
- package/dist/committee/oauth.js +17 -5
- package/dist/committee/payment.d.ts +369 -0
- package/dist/committee/payment.js +339 -0
- package/dist/committee/recovery.d.ts +136 -0
- package/dist/committee/recovery.js +204 -0
- package/dist/committee/recoveryJson.d.ts +2 -0
- package/dist/committee/recoveryJson.js +87 -0
- package/dist/committee/request.d.ts +63 -27
- package/dist/committee/request.js +77 -66
- package/dist/committee/session-grant.d.ts +320 -0
- package/dist/committee/session-grant.js +397 -0
- package/dist/committee/status-refresh.d.ts +257 -0
- package/dist/committee/status-refresh.js +619 -0
- package/dist/committee/token.d.ts +163 -15
- package/dist/committee/token.js +247 -10
- package/dist/crypto/bn254.d.ts +70 -0
- package/dist/crypto/bn254.js +222 -0
- package/dist/crypto/ibe.d.ts +32 -0
- package/dist/crypto/ibe.js +56 -8
- package/dist/crypto/index.d.ts +1 -1
- package/dist/crypto/index.js +1 -1
- package/dist/crypto/kem.d.ts +31 -0
- package/dist/crypto/kem.js +113 -7
- package/dist/crypto/recipient.d.ts +75 -0
- package/dist/crypto/recipient.js +107 -0
- package/dist/decryption/client.d.ts +10 -16
- package/dist/decryption/client.js +8 -76
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/decryption/sealed.d.ts +72 -0
- package/dist/decryption/sealed.js +147 -0
- package/dist/decryption/session.d.ts +115 -0
- package/dist/decryption/session.js +358 -0
- package/dist/errors.d.ts +406 -1
- package/dist/errors.js +400 -5
- package/dist/index.d.ts +9 -2
- package/dist/index.js +6 -1
- package/dist/internal/bounded.d.ts +66 -0
- package/dist/internal/bounded.js +126 -0
- package/dist/internal/network.d.ts +4 -0
- package/dist/internal/network.js +40 -0
- package/dist/internal/retryAfter.d.ts +8 -0
- package/dist/internal/retryAfter.js +28 -0
- package/dist/internal/sleep.d.ts +6 -0
- package/dist/internal/sleep.js +15 -0
- package/dist/internal/typedData.d.ts +13 -0
- package/dist/internal/typedData.js +77 -0
- package/dist/internal/viemErrors.d.ts +26 -0
- package/dist/internal/viemErrors.js +49 -0
- package/dist/oid4vp/binding.d.ts +27 -1
- package/dist/oid4vp/binding.js +36 -1
- package/dist/oid4vp/jose.d.ts +4 -2
- package/dist/oid4vp/jose.js +39 -7
- package/dist/oid4vp/request-object.d.ts +61 -4
- package/dist/oid4vp/request-object.js +140 -5
- package/dist/oid4vp/verifier-agent.d.ts +18 -8
- package/dist/oid4vp/verifier-agent.js +48 -6
- package/dist/oid4vp/wallet.d.ts +2 -4
- package/dist/oid4vp/wallet.js +1 -0
- package/dist/retry.d.ts +78 -0
- package/dist/retry.js +137 -0
- package/dist/signing/frost.d.ts +1 -1
- package/dist/verifier-agent/index.d.ts +41 -5
- package/dist/verifier-agent/index.js +124 -9
- package/dist/verifier-agent/payment.d.ts +7 -0
- package/dist/verifier-agent/payment.js +17 -0
- package/docs/api.md +8 -2
- package/docs/application-api.md +25 -2
- package/docs/chain.md +155 -9
- package/docs/consumer-migrations.md +61 -0
- package/docs/encrypted-notes.md +3 -2
- package/docs/encryption.md +4 -2
- package/docs/errors.md +14 -1
- package/docs/flows.md +2 -2
- package/docs/funding.md +902 -0
- package/docs/native-approvals.md +63 -0
- package/docs/reference/README.md +9 -8
- package/docs/reference/app-browser.md +232 -0
- package/docs/reference/app-node.md +38 -8
- package/docs/reference/app.md +4621 -805
- package/docs/reference/chain-node.md +74 -16
- package/docs/reference/chain.md +6740 -1592
- package/docs/reference/committee.md +5630 -987
- package/docs/reference/main.md +1439 -140
- package/docs/reference/oid4vp.md +297 -144
- package/docs/reference/verifier-agent.md +77 -35
- package/docs/signing.md +6 -0
- package/examples/encrypted-notes.ts +21 -6
- package/examples/getting-started.ts +2 -7
- package/examples/live-config.ts +24 -17
- package/package.json +17 -5
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { type Account, type Address, type Chain, type Hex, type PublicClient, type Transport, type WalletClient } from 'viem';
|
|
2
|
+
import { reservePaidOperation, type ReservePaidOperationOptions, type PaidReservationResolution } from '../chain/reservation.js';
|
|
3
|
+
import type { ExpectedPaidOperation, PrepaidDeployment } from '../chain/prepaid.js';
|
|
4
|
+
import { type PaymentIntentWire } from '../committee/payment.js';
|
|
5
|
+
import { type PaidReservationSession } from './paid-journal.js';
|
|
6
|
+
import type { ApplicationStore } from './ready-slot.js';
|
|
7
|
+
/** Durable application reservation controls, shared by every use of this gas payer. */
|
|
8
|
+
export interface ApplicationReservationOptions extends Omit<ReservePaidOperationOptions, 'persist'> {
|
|
9
|
+
/** Private atomic store whose locks coordinate all participating processes or tabs. */
|
|
10
|
+
store: ApplicationStore;
|
|
11
|
+
/** Original presentation random and independently approved audience. */
|
|
12
|
+
session: PaidReservationSession;
|
|
13
|
+
}
|
|
14
|
+
/** Another reservation may have consumed this payer's nonce; reconcile it before proceeding. */
|
|
15
|
+
export declare class ApplicationPayerRecoveryError extends Error {
|
|
16
|
+
readonly requestId: Hex;
|
|
17
|
+
constructor(/** Original reservation that must be reconciled. */ requestId: Hex);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Reserve one operation while exclusively coordinating its gas payer across the application.
|
|
21
|
+
* The same private store must cover all reservation callers, including different deployments
|
|
22
|
+
* on one chain. Use a dedicated payer: unrelated wallet/CLI transactions are not coordinated.
|
|
23
|
+
* Any uncertainty after preparation retains a durable payer claim; elapsed time never clears it.
|
|
24
|
+
* An `options.signal` abort before the durable preparation refuses with
|
|
25
|
+
* `PaidReservationAbortedError` (code `aborted`; no journal, no payer claim, nothing sent).
|
|
26
|
+
* After it the broadcast cannot be cancelled: an abort ends only the receipt wait, as
|
|
27
|
+
* `PaidReservationUncertainError`, and the payer stays claimed until reconciled.
|
|
28
|
+
* @param client - Trusted bounded RPC client; submission retries disabled.
|
|
29
|
+
* @param wallet - Dedicated account-bound gas payer.
|
|
30
|
+
* @param deployment - Independently approved prepaid deployment.
|
|
31
|
+
* @param original - Fixed creator intent from verified assignment and session discovery.
|
|
32
|
+
* @param expected - Independently derived operation.
|
|
33
|
+
* @param options - Durable store, original session, endpoints and explicit gas limits.
|
|
34
|
+
*/
|
|
35
|
+
export declare function reserveApplicationPayment(client: PublicClient, wallet: WalletClient<Transport, Chain, Account>, deployment: PrepaidDeployment, original: PaymentIntentWire, expected: ExpectedPaidOperation, options: ApplicationReservationOptions): ReturnType<typeof reservePaidOperation>;
|
|
36
|
+
/**
|
|
37
|
+
* Release an application's pending gas payer only after verifying the original mined transaction.
|
|
38
|
+
* Success and revert both consume the nonce. Missing/replaced/reorganized transactions retain
|
|
39
|
+
* the claim. This does not resubmit, delete the original journal or authorize keeper work.
|
|
40
|
+
* @param client - Trusted bounded RPC client with historical canonical reads.
|
|
41
|
+
* @param store - Same durable private store used for reservation.
|
|
42
|
+
* @param deployment - Independently approved original deployment.
|
|
43
|
+
* @param requestId - Original operation ID retained in the private journal.
|
|
44
|
+
* @param expected - Independently selected original operation.
|
|
45
|
+
* @param transactionHash - Saved or independently located candidate; its full identity is verified.
|
|
46
|
+
* @param confirmations - Required canonical inclusion depth, 1..64 (default 1).
|
|
47
|
+
*/
|
|
48
|
+
export declare function reconcileApplicationPayment(client: PublicClient, store: ApplicationStore, deployment: PrepaidDeployment, requestId: Hex, expected: ExpectedPaidOperation, transactionHash: Hex, confirmations?: number): Promise<PaidReservationResolution>;
|
|
49
|
+
/** Where an application reservation stands, from the journal, the payer claim and the chain. */
|
|
50
|
+
export type ApplicationReservationState =
|
|
51
|
+
/** Nothing was ever prepared for this request (no journal, no payer claim) and the chain holds no reservation. */
|
|
52
|
+
'none'
|
|
53
|
+
/** The chain holds a reservation for this request ID (whoever's transaction mined it). */
|
|
54
|
+
| 'reserved'
|
|
55
|
+
/** The original prepared attempt can never reserve: its quote deadline has passed on chain without a reservation. Final. */
|
|
56
|
+
| 'not-reserved'
|
|
57
|
+
/** The outcome cannot be proven yet; nothing may be reserved again. Reconcile later. */
|
|
58
|
+
| 'uncertain';
|
|
59
|
+
/** Outcome of {@link reconcileApplicationReservation}. */
|
|
60
|
+
export interface ApplicationReservationStatus {
|
|
61
|
+
/** Proven state; only `none` permits a first reservation. */
|
|
62
|
+
state: ApplicationReservationState;
|
|
63
|
+
/** Original request identity. */
|
|
64
|
+
requestId: Hex;
|
|
65
|
+
/** Whether this request still holds its gas payer's durable claim after reconciliation. */
|
|
66
|
+
payerLocked: boolean;
|
|
67
|
+
/** Hash journaled or reported for the original attempt, when known. */
|
|
68
|
+
transactionHash?: Hex;
|
|
69
|
+
/** Why the state is `uncertain` or `not-reserved`; safe to log. */
|
|
70
|
+
reason?: string;
|
|
71
|
+
/** Canonical block the chain observation was made at. */
|
|
72
|
+
observedAt: {
|
|
73
|
+
blockNumber: bigint;
|
|
74
|
+
blockHash: Hex;
|
|
75
|
+
blockTimestamp: bigint;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Options for {@link reconcileApplicationReservation}. */
|
|
79
|
+
export interface ReconcileApplicationReservationOptions {
|
|
80
|
+
/**
|
|
81
|
+
* Gas payer the request would use. Needed when no journal exists, to prove the payer holds no
|
|
82
|
+
* claim for it; with a journal the payer is read from the journaled transaction.
|
|
83
|
+
*/
|
|
84
|
+
payer?: Address;
|
|
85
|
+
/** Observation depth below the head, 1..64 (default 1). */
|
|
86
|
+
confirmations?: number;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Reconcile an application reservation by its deterministic request ID and the payer's nonce,
|
|
90
|
+
* without submitting, replacing or reserving anything. Works without a transaction hash, e.g.
|
|
91
|
+
* after a crash between broadcast and the `submitted` checkpoint.
|
|
92
|
+
*
|
|
93
|
+
* - No journal and no payer claim: `none` (nothing was prepared, so nothing was broadcast),
|
|
94
|
+
* unless the chain already holds the reservation (`reserved`).
|
|
95
|
+
* - Chain holds the reservation: `reserved`.
|
|
96
|
+
* - Not reserved and a canonical block past the quote deadline: `not-reserved` (the contract
|
|
97
|
+
* refuses the original signed quote from then on). Final for this attempt.
|
|
98
|
+
* - Otherwise `uncertain`; the original transaction may still be mined.
|
|
99
|
+
*
|
|
100
|
+
* The payer claim is released only when the journaled nonce is consumed on chain, or when the
|
|
101
|
+
* attempt is provably dead and no transaction at that nonce is known to the RPC (the floor then
|
|
102
|
+
* stays at that nonce). Every other case keeps the payer locked.
|
|
103
|
+
* @param client - Trusted bounded RPC client with canonical reads.
|
|
104
|
+
* @param store - Same private store used for the reservation.
|
|
105
|
+
* @param deployment - Independently approved original deployment.
|
|
106
|
+
* @param payment - Original creator payment intent (its request ID is the reservation key).
|
|
107
|
+
* @param expected - Independently selected original operation.
|
|
108
|
+
* @param options - Gas payer for the no-journal case and observation depth.
|
|
109
|
+
*/
|
|
110
|
+
export declare function reconcileApplicationReservation(client: PublicClient, store: ApplicationStore, deployment: PrepaidDeployment, payment: PaymentIntentWire, expected: ExpectedPaidOperation, options?: ReconcileApplicationReservationOptions): Promise<ApplicationReservationStatus>;
|
|
111
|
+
/** Options for {@link selectApplicationGasPayer}. */
|
|
112
|
+
export interface SelectApplicationGasPayerOptions {
|
|
113
|
+
/**
|
|
114
|
+
* Resuming this paid operation: return the gas payer its journal recorded, whatever its claim
|
|
115
|
+
* state (a reserving operation usually holds that payer's claim itself; resume reconciles it).
|
|
116
|
+
* Throws when the recorded payer is not in the pool. Falls back to normal selection for an
|
|
117
|
+
* operation journaled before payers were recorded, or with no journal.
|
|
118
|
+
*/
|
|
119
|
+
resume?: Hex;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Pick a gas payer from a small pool of dedicated payers for the next paid operation.
|
|
123
|
+
* Payers holding an unresolved durable reservation claim are skipped (reconcile them); among
|
|
124
|
+
* the rest, ones idle in this process come first, rotating round-robin per pool so work is
|
|
125
|
+
* spread fairly. Returns undefined when every payer holds a claim. Selection is advisory: a
|
|
126
|
+
* payer claimed meanwhile still refuses safely (`ApplicationPayerRecoveryError`). With
|
|
127
|
+
* `resume`, the payer recorded by that operation's journal is returned instead.
|
|
128
|
+
* @param store - Private store shared by every process using these payers.
|
|
129
|
+
* @param wallets - Distinct account- and chain-bound dedicated gas payers (1..64).
|
|
130
|
+
* @param options - Operation being resumed, to honour its recorded payer.
|
|
131
|
+
*/
|
|
132
|
+
export declare function selectApplicationGasPayer<W extends WalletClient<Transport, Chain, Account>>(store: ApplicationStore, wallets: readonly W[], options?: SelectApplicationGasPayerOptions): Promise<W | undefined>;
|
|
133
|
+
/**
|
|
134
|
+
* Internal (prepaid allowance reservations): run one gas-payer transaction under the same durable
|
|
135
|
+
* payer claim as {@link reserveApplicationPayment}. `claim(nonce)` must be awaited from the
|
|
136
|
+
* caller's `prepared` checkpoint, before broadcast: it refuses a nonce below the durable floor and
|
|
137
|
+
* records the pending claim. On success the floor advances past the claimed nonce; on failure
|
|
138
|
+
* after a claim the payer stays claimed until {@link releaseApplicationPayerClaim} proves it free.
|
|
139
|
+
* @param store - Private store shared by every user of this payer.
|
|
140
|
+
* @param chainId - Payer chain.
|
|
141
|
+
* @param payer - Dedicated gas payer.
|
|
142
|
+
* @param claimId - 32-byte identity of the transaction (an allowance id).
|
|
143
|
+
* @param run - The reservation, given the claim hook.
|
|
144
|
+
*/
|
|
145
|
+
export declare function withApplicationPayerClaim<T>(store: ApplicationStore, chainId: number, payer: Address, claimId: Hex, run: (claim: (nonce: number) => Promise<void>) => Promise<T>): Promise<T>;
|
|
146
|
+
/**
|
|
147
|
+
* Internal: release a payer claim held by `claimId` once the chain proves it free: the claimed
|
|
148
|
+
* nonce is consumed at the head (floor = nonce + 1), or `dead` (the claimed transaction can never
|
|
149
|
+
* apply) and no transaction at that nonce is pending (floor = nonce). Otherwise it stays claimed.
|
|
150
|
+
* @param client - Trusted RPC client.
|
|
151
|
+
* @param store - The same store.
|
|
152
|
+
* @param chainId - Payer chain.
|
|
153
|
+
* @param payer - Gas payer.
|
|
154
|
+
* @param claimId - Identity that holds the claim.
|
|
155
|
+
* @param dead - The caller proved the claimed transaction can never apply.
|
|
156
|
+
*/
|
|
157
|
+
export declare function releaseApplicationPayerClaim(client: PublicClient, store: ApplicationStore, chainId: number, payer: Address, claimId: Hex, dead: boolean): Promise<boolean>;
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { decodeFunctionResult, encodeFunctionData } from 'viem';
|
|
2
|
+
import { settlementAbi } from '../chain/abis/settlement.js';
|
|
3
|
+
import { reservePaidOperation, reconcilePaidReservation, PaidReservationAbortedError } from '../chain/reservation.js';
|
|
4
|
+
import { prepaidRequestId } from '../committee/payment.js';
|
|
5
|
+
import { createPaidReservationJournal, loadPaidReservationJournal } from './paid-journal.js';
|
|
6
|
+
import { dedicatedPayerBusy } from './payer-queue.js';
|
|
7
|
+
import { recordedPaidOperationPayer } from './paid-keys.js';
|
|
8
|
+
import { chainIdOf } from '../chain/chainId.js';
|
|
9
|
+
/** Another reservation may have consumed this payer's nonce; reconcile it before proceeding. */
|
|
10
|
+
export class ApplicationPayerRecoveryError extends Error {
|
|
11
|
+
requestId;
|
|
12
|
+
constructor(/** Original reservation that must be reconciled. */ requestId) {
|
|
13
|
+
super('gas payer has an unresolved reservation; reconcile its original transaction');
|
|
14
|
+
this.requestId = requestId;
|
|
15
|
+
this.name = 'ApplicationPayerRecoveryError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
19
|
+
function payerKey(chainId, payer) {
|
|
20
|
+
if (!Number.isSafeInteger(chainId) || chainId <= 0 || !/^0x[0-9a-f]{40}$/i.test(payer) || /^0x0{40}$/i.test(payer))
|
|
21
|
+
throw new Error('invalid reservation gas payer');
|
|
22
|
+
return `prepaid-payer-${chainId}-${payer.toLowerCase()}`;
|
|
23
|
+
}
|
|
24
|
+
async function loadPayer(store, chainId, payer) {
|
|
25
|
+
const value = await store.load(payerKey(chainId, payer));
|
|
26
|
+
if (value === undefined)
|
|
27
|
+
return { schema: 1, chainId, payer, nextNonce: 0 };
|
|
28
|
+
if (!value || value.schema !== 1 || value.chainId !== chainId || typeof value.payer !== 'string' || !same(value.payer, payer)
|
|
29
|
+
|| !Number.isSafeInteger(value.nextNonce) || value.nextNonce < 0
|
|
30
|
+
|| (value.pending !== undefined && (!value.pending || typeof value.pending.requestId !== 'string' || !/^0x[0-9a-f]{64}$/i.test(value.pending.requestId)
|
|
31
|
+
|| !Number.isSafeInteger(value.pending.nonce) || value.pending.nonce < value.nextNonce || value.pending.nonce >= Number.MAX_SAFE_INTEGER)))
|
|
32
|
+
throw new Error('invalid durable reservation payer state');
|
|
33
|
+
return structuredClone(value);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Reserve one operation while exclusively coordinating its gas payer across the application.
|
|
37
|
+
* The same private store must cover all reservation callers, including different deployments
|
|
38
|
+
* on one chain. Use a dedicated payer: unrelated wallet/CLI transactions are not coordinated.
|
|
39
|
+
* Any uncertainty after preparation retains a durable payer claim; elapsed time never clears it.
|
|
40
|
+
* An `options.signal` abort before the durable preparation refuses with
|
|
41
|
+
* `PaidReservationAbortedError` (code `aborted`; no journal, no payer claim, nothing sent).
|
|
42
|
+
* After it the broadcast cannot be cancelled: an abort ends only the receipt wait, as
|
|
43
|
+
* `PaidReservationUncertainError`, and the payer stays claimed until reconciled.
|
|
44
|
+
* @param client - Trusted bounded RPC client; submission retries disabled.
|
|
45
|
+
* @param wallet - Dedicated account-bound gas payer.
|
|
46
|
+
* @param deployment - Independently approved prepaid deployment.
|
|
47
|
+
* @param original - Fixed creator intent from verified assignment and session discovery.
|
|
48
|
+
* @param expected - Independently derived operation.
|
|
49
|
+
* @param options - Durable store, original session, endpoints and explicit gas limits.
|
|
50
|
+
*/
|
|
51
|
+
export async function reserveApplicationPayment(client, wallet, deployment, original, expected, options) {
|
|
52
|
+
const payment = structuredClone(original), d = { ...deployment }, operation = { ...expected };
|
|
53
|
+
const payerWallet = { ...wallet, account: { ...wallet.account }, chain: { ...wallet.chain } };
|
|
54
|
+
const { store, session, ...limits } = { ...options, session: structuredClone(options.session), accountantUrls: [...options.accountantUrls] };
|
|
55
|
+
const payer = payerWallet.account.address, name = payerKey(d.chainId, payer);
|
|
56
|
+
const journal = createPaidReservationJournal(store, payment, session), signal = limits.signal;
|
|
57
|
+
const refuseIfAborted = () => { if (signal?.aborted)
|
|
58
|
+
throw new PaidReservationAbortedError(journal.requestId, signal.reason); };
|
|
59
|
+
refuseIfAborted();
|
|
60
|
+
return store.withLock(name, async () => {
|
|
61
|
+
refuseIfAborted();
|
|
62
|
+
const state = await loadPayer(store, d.chainId, payer);
|
|
63
|
+
if (state.pending)
|
|
64
|
+
throw new ApplicationPayerRecoveryError(state.pending.requestId);
|
|
65
|
+
if (await journal.load())
|
|
66
|
+
throw new Error('reservation already journaled; reconcile the original attempt');
|
|
67
|
+
let claimedNonce;
|
|
68
|
+
const result = await reservePaidOperation(client, payerWallet, d, payment, operation, { ...limits, persist: async (checkpoint) => {
|
|
69
|
+
if (checkpoint.phase === 'prepared') {
|
|
70
|
+
const tx = checkpoint.record.transaction;
|
|
71
|
+
if (!same(tx.from, payer) || tx.chainId !== d.chainId || !Number.isSafeInteger(tx.nonce)
|
|
72
|
+
|| tx.nonce < state.nextNonce || tx.nonce >= Number.MAX_SAFE_INTEGER)
|
|
73
|
+
throw new Error('reservation RPC nonce is below the durable payer floor or invalid');
|
|
74
|
+
// Journal first: a crash before the payer claim cannot have broadcast. Every
|
|
75
|
+
// existing journal still refuses retry; persist must finish before submission.
|
|
76
|
+
await journal.persist(checkpoint);
|
|
77
|
+
await store.save(name, { ...state, pending: { requestId: journal.requestId, nonce: tx.nonce } });
|
|
78
|
+
claimedNonce = tx.nonce;
|
|
79
|
+
}
|
|
80
|
+
else
|
|
81
|
+
await journal.persist(checkpoint);
|
|
82
|
+
} });
|
|
83
|
+
if (claimedNonce === undefined)
|
|
84
|
+
throw new Error('reservation completed without a durable payer claim');
|
|
85
|
+
await store.save(name, { schema: 1, chainId: d.chainId, payer, nextNonce: claimedNonce + 1 });
|
|
86
|
+
return result;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Release an application's pending gas payer only after verifying the original mined transaction.
|
|
91
|
+
* Success and revert both consume the nonce. Missing/replaced/reorganized transactions retain
|
|
92
|
+
* the claim. This does not resubmit, delete the original journal or authorize keeper work.
|
|
93
|
+
* @param client - Trusted bounded RPC client with historical canonical reads.
|
|
94
|
+
* @param store - Same durable private store used for reservation.
|
|
95
|
+
* @param deployment - Independently approved original deployment.
|
|
96
|
+
* @param requestId - Original operation ID retained in the private journal.
|
|
97
|
+
* @param expected - Independently selected original operation.
|
|
98
|
+
* @param transactionHash - Saved or independently located candidate; its full identity is verified.
|
|
99
|
+
* @param confirmations - Required canonical inclusion depth, 1..64 (default 1).
|
|
100
|
+
*/
|
|
101
|
+
export async function reconcileApplicationPayment(client, store, deployment, requestId, expected, transactionHash, confirmations = 1) {
|
|
102
|
+
const d = { ...deployment }, operation = { ...expected };
|
|
103
|
+
const journal = await loadPaidReservationJournal(store, requestId);
|
|
104
|
+
if (!journal)
|
|
105
|
+
throw new Error('reservation has no durable application journal');
|
|
106
|
+
const tx = journal.record.transaction, name = payerKey(d.chainId, tx.from);
|
|
107
|
+
return store.withLock(name, async () => {
|
|
108
|
+
const state = await loadPayer(store, d.chainId, tx.from);
|
|
109
|
+
if (!state.pending || !same(state.pending.requestId, requestId) || state.pending.nonce !== tx.nonce)
|
|
110
|
+
throw new Error('reservation does not own the pending gas payer');
|
|
111
|
+
if (journal.transactionHash && !same(journal.transactionHash, transactionHash))
|
|
112
|
+
throw new Error('candidate differs from the saved reservation hash');
|
|
113
|
+
const resolution = await reconcilePaidReservation(client, d, journal.record, operation, transactionHash, confirmations);
|
|
114
|
+
// Keep the located hash and canonical evidence even when the original submission
|
|
115
|
+
// died before returning a hash. A failed evidence write must not release the payer.
|
|
116
|
+
await store.save(`prepaid-recovery-${requestId.toLowerCase()}`, resolution);
|
|
117
|
+
await store.save(name, { schema: 1, chainId: d.chainId, payer: tx.from, nextNonce: tx.nonce + 1 });
|
|
118
|
+
return resolution;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
const HEX32 = /^0x[0-9a-f]{64}$/i;
|
|
122
|
+
async function observeReservation(client, d, slot, requestId, confirmations) {
|
|
123
|
+
if (await chainIdOf(client) !== d.chainId)
|
|
124
|
+
throw new Error('reservation reconciliation chain mismatch');
|
|
125
|
+
const head = await client.getBlock({ blockTag: 'latest' });
|
|
126
|
+
const now = BigInt(Math.floor(Date.now() / 1000));
|
|
127
|
+
if (head.number === null || head.hash === null || !HEX32.test(head.hash) || now - head.timestamp > 30n || head.timestamp - now > 2n)
|
|
128
|
+
throw new Error('reservation reconciliation head is stale or unavailable');
|
|
129
|
+
const block = confirmations === 1 ? head : await client.getBlock({ blockNumber: head.number - BigInt(confirmations - 1) });
|
|
130
|
+
const blockHash = block.hash;
|
|
131
|
+
if (block.number === null || blockHash === null || !HEX32.test(blockHash))
|
|
132
|
+
throw new Error('reservation reconciliation block unavailable');
|
|
133
|
+
const read = async (functionName) => {
|
|
134
|
+
const result = await client.call({ to: d.settlement, data: encodeFunctionData({ abi: settlementAbi, functionName, args: [slot, requestId] }),
|
|
135
|
+
blockHash, requireCanonical: true, batch: false });
|
|
136
|
+
if (result.data === undefined)
|
|
137
|
+
throw new Error(`empty ${functionName} observation`);
|
|
138
|
+
return decodeFunctionResult({ abi: settlementAbi, functionName, data: result.data });
|
|
139
|
+
};
|
|
140
|
+
const [cost, assignment] = await Promise.all([read('prepaidCost'), read('prepaidAssignmentBlock')]);
|
|
141
|
+
return { at: { blockNumber: block.number, blockHash, blockTimestamp: block.timestamp }, cost: cost, assignment: assignment };
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Reconcile an application reservation by its deterministic request ID and the payer's nonce,
|
|
145
|
+
* without submitting, replacing or reserving anything. Works without a transaction hash, e.g.
|
|
146
|
+
* after a crash between broadcast and the `submitted` checkpoint.
|
|
147
|
+
*
|
|
148
|
+
* - No journal and no payer claim: `none` (nothing was prepared, so nothing was broadcast),
|
|
149
|
+
* unless the chain already holds the reservation (`reserved`).
|
|
150
|
+
* - Chain holds the reservation: `reserved`.
|
|
151
|
+
* - Not reserved and a canonical block past the quote deadline: `not-reserved` (the contract
|
|
152
|
+
* refuses the original signed quote from then on). Final for this attempt.
|
|
153
|
+
* - Otherwise `uncertain`; the original transaction may still be mined.
|
|
154
|
+
*
|
|
155
|
+
* The payer claim is released only when the journaled nonce is consumed on chain, or when the
|
|
156
|
+
* attempt is provably dead and no transaction at that nonce is known to the RPC (the floor then
|
|
157
|
+
* stays at that nonce). Every other case keeps the payer locked.
|
|
158
|
+
* @param client - Trusted bounded RPC client with canonical reads.
|
|
159
|
+
* @param store - Same private store used for the reservation.
|
|
160
|
+
* @param deployment - Independently approved original deployment.
|
|
161
|
+
* @param payment - Original creator payment intent (its request ID is the reservation key).
|
|
162
|
+
* @param expected - Independently selected original operation.
|
|
163
|
+
* @param options - Gas payer for the no-journal case and observation depth.
|
|
164
|
+
*/
|
|
165
|
+
export async function reconcileApplicationReservation(client, store, deployment, payment, expected, options = {}) {
|
|
166
|
+
const d = { ...deployment }, original = structuredClone(payment), confirmations = options.confirmations ?? 1;
|
|
167
|
+
if (!Number.isSafeInteger(confirmations) || confirmations < 1 || confirmations > 64)
|
|
168
|
+
throw new Error('invalid reservation reconciliation confirmations');
|
|
169
|
+
if (original.chain_id !== d.chainId || !same(original.settlement, d.settlement) || !same(original.slot, expected.slot)
|
|
170
|
+
|| original.action !== expected.action || !same(original.payload_digest, expected.payloadDigest))
|
|
171
|
+
throw new Error('reservation reconciliation deployment or operation mismatch');
|
|
172
|
+
const requestId = prepaidRequestId(original);
|
|
173
|
+
const payer = (await loadPaidReservationJournal(store, requestId))?.record.transaction.from ?? options.payer;
|
|
174
|
+
const work = async () => {
|
|
175
|
+
// Re-read under the payer lock: a reservation journals and claims the payer under it.
|
|
176
|
+
const journal = await loadPaidReservationJournal(store, requestId);
|
|
177
|
+
if (journal && payer && !same(journal.record.transaction.from, payer))
|
|
178
|
+
throw new Error('reservation journal names another gas payer');
|
|
179
|
+
const state = payer ? await loadPayer(store, d.chainId, payer) : undefined;
|
|
180
|
+
const owns = state?.pending !== undefined && same(state.pending.requestId, requestId);
|
|
181
|
+
const observed = await observeReservation(client, d, original.slot, requestId, confirmations);
|
|
182
|
+
const reserved = observed.cost !== 0n;
|
|
183
|
+
const base = { requestId, observedAt: observed.at };
|
|
184
|
+
if (!journal) {
|
|
185
|
+
// A payer claim is only ever written after the journal; one without it is not explainable.
|
|
186
|
+
if (owns)
|
|
187
|
+
return { ...base, state: 'uncertain', payerLocked: true, reason: 'gas payer claims this request but no reservation journal exists' };
|
|
188
|
+
return reserved ? { ...base, state: 'reserved', payerLocked: false } : { ...base, state: 'none', payerLocked: false };
|
|
189
|
+
}
|
|
190
|
+
const tx = journal.record.transaction, deadline = BigInt(journal.record.quote.deadline);
|
|
191
|
+
const transactionHash = journal.transactionHash;
|
|
192
|
+
let result;
|
|
193
|
+
if (reserved)
|
|
194
|
+
result = { ...base, state: 'reserved', payerLocked: owns };
|
|
195
|
+
else if (journal.phase === 'confirmed')
|
|
196
|
+
result = { ...base, state: 'uncertain', payerLocked: owns, reason: 'confirmed reservation is no longer observed on the canonical chain' };
|
|
197
|
+
else if (observed.at.blockTimestamp > deadline)
|
|
198
|
+
result = { ...base, state: 'not-reserved', payerLocked: owns, reason: 'quote deadline passed without a reservation' };
|
|
199
|
+
else
|
|
200
|
+
result = { ...base, state: 'uncertain', payerLocked: owns, reason: 'original reservation may still be mined until its quote deadline' };
|
|
201
|
+
if (transactionHash)
|
|
202
|
+
result.transactionHash = transactionHash;
|
|
203
|
+
if (owns && state?.pending?.nonce === tx.nonce) {
|
|
204
|
+
const mined = await client.getTransactionCount({ address: tx.from, blockNumber: observed.at.blockNumber });
|
|
205
|
+
let nextNonce;
|
|
206
|
+
if (mined > tx.nonce)
|
|
207
|
+
nextNonce = tx.nonce + 1;
|
|
208
|
+
else if (result.state === 'not-reserved' && await client.getTransactionCount({ address: tx.from, blockTag: 'pending' }) <= tx.nonce)
|
|
209
|
+
nextNonce = tx.nonce;
|
|
210
|
+
if (nextNonce !== undefined) {
|
|
211
|
+
await store.save(payerKey(d.chainId, tx.from), { schema: 1, chainId: d.chainId, payer: tx.from, nextNonce });
|
|
212
|
+
result.payerLocked = false;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return result;
|
|
216
|
+
};
|
|
217
|
+
return payer ? store.withLock(payerKey(d.chainId, payer), work) : work();
|
|
218
|
+
}
|
|
219
|
+
const cursors = new Map();
|
|
220
|
+
/**
|
|
221
|
+
* Pick a gas payer from a small pool of dedicated payers for the next paid operation.
|
|
222
|
+
* Payers holding an unresolved durable reservation claim are skipped (reconcile them); among
|
|
223
|
+
* the rest, ones idle in this process come first, rotating round-robin per pool so work is
|
|
224
|
+
* spread fairly. Returns undefined when every payer holds a claim. Selection is advisory: a
|
|
225
|
+
* payer claimed meanwhile still refuses safely (`ApplicationPayerRecoveryError`). With
|
|
226
|
+
* `resume`, the payer recorded by that operation's journal is returned instead.
|
|
227
|
+
* @param store - Private store shared by every process using these payers.
|
|
228
|
+
* @param wallets - Distinct account- and chain-bound dedicated gas payers (1..64).
|
|
229
|
+
* @param options - Operation being resumed, to honour its recorded payer.
|
|
230
|
+
*/
|
|
231
|
+
export async function selectApplicationGasPayer(store, wallets, options = {}) {
|
|
232
|
+
if (!wallets.length || wallets.length > 64)
|
|
233
|
+
throw new Error('supply 1..64 dedicated gas payers');
|
|
234
|
+
const ids = wallets.map(w => `${w.chain.id}-${w.account.address.toLowerCase()}`);
|
|
235
|
+
if (new Set(ids).size !== ids.length)
|
|
236
|
+
throw new Error('duplicate gas payer in pool');
|
|
237
|
+
if (options.resume !== undefined) {
|
|
238
|
+
const recorded = await recordedPaidOperationPayer(store, options.resume);
|
|
239
|
+
if (recorded !== undefined) {
|
|
240
|
+
const wallet = wallets.find(w => w.chain.id === recorded.chainId && same(w.account.address, recorded.address));
|
|
241
|
+
if (!wallet)
|
|
242
|
+
throw new Error('the gas payer this operation recorded is not in the pool');
|
|
243
|
+
return wallet;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const pool = ids.slice().sort().join(','), start = cursors.get(pool) ?? 0;
|
|
247
|
+
const free = [];
|
|
248
|
+
for (let i = 0; i < wallets.length; i++) {
|
|
249
|
+
const index = (start + i) % wallets.length, wallet = wallets[index];
|
|
250
|
+
const state = await loadPayer(store, wallet.chain.id, wallet.account.address);
|
|
251
|
+
if (!state.pending)
|
|
252
|
+
free.push({ wallet, index, busy: dedicatedPayerBusy(ids[index]) });
|
|
253
|
+
}
|
|
254
|
+
const chosen = free.find(c => !c.busy) ?? free[0];
|
|
255
|
+
if (!chosen)
|
|
256
|
+
return undefined;
|
|
257
|
+
cursors.set(pool, (chosen.index + 1) % wallets.length);
|
|
258
|
+
return chosen.wallet;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Internal (prepaid allowance reservations): run one gas-payer transaction under the same durable
|
|
262
|
+
* payer claim as {@link reserveApplicationPayment}. `claim(nonce)` must be awaited from the
|
|
263
|
+
* caller's `prepared` checkpoint, before broadcast: it refuses a nonce below the durable floor and
|
|
264
|
+
* records the pending claim. On success the floor advances past the claimed nonce; on failure
|
|
265
|
+
* after a claim the payer stays claimed until {@link releaseApplicationPayerClaim} proves it free.
|
|
266
|
+
* @param store - Private store shared by every user of this payer.
|
|
267
|
+
* @param chainId - Payer chain.
|
|
268
|
+
* @param payer - Dedicated gas payer.
|
|
269
|
+
* @param claimId - 32-byte identity of the transaction (an allowance id).
|
|
270
|
+
* @param run - The reservation, given the claim hook.
|
|
271
|
+
*/
|
|
272
|
+
export async function withApplicationPayerClaim(store, chainId, payer, claimId, run) {
|
|
273
|
+
if (!HEX32.test(claimId))
|
|
274
|
+
throw new Error('invalid payer claim identity');
|
|
275
|
+
const name = payerKey(chainId, payer);
|
|
276
|
+
return store.withLock(name, async () => {
|
|
277
|
+
const state = await loadPayer(store, chainId, payer);
|
|
278
|
+
if (state.pending)
|
|
279
|
+
throw new ApplicationPayerRecoveryError(state.pending.requestId);
|
|
280
|
+
let claimed;
|
|
281
|
+
const result = await run(async (nonce) => {
|
|
282
|
+
if (claimed !== undefined || !Number.isSafeInteger(nonce) || nonce < state.nextNonce || nonce >= Number.MAX_SAFE_INTEGER)
|
|
283
|
+
throw new Error('payer nonce is below the durable floor or invalid');
|
|
284
|
+
await store.save(name, { ...state, pending: { requestId: claimId, nonce } });
|
|
285
|
+
claimed = nonce;
|
|
286
|
+
});
|
|
287
|
+
if (claimed === undefined)
|
|
288
|
+
throw new Error('payer transaction completed without a durable payer claim');
|
|
289
|
+
await store.save(name, { schema: 1, chainId, payer, nextNonce: claimed + 1 });
|
|
290
|
+
return result;
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Internal: release a payer claim held by `claimId` once the chain proves it free: the claimed
|
|
295
|
+
* nonce is consumed at the head (floor = nonce + 1), or `dead` (the claimed transaction can never
|
|
296
|
+
* apply) and no transaction at that nonce is pending (floor = nonce). Otherwise it stays claimed.
|
|
297
|
+
* @param client - Trusted RPC client.
|
|
298
|
+
* @param store - The same store.
|
|
299
|
+
* @param chainId - Payer chain.
|
|
300
|
+
* @param payer - Gas payer.
|
|
301
|
+
* @param claimId - Identity that holds the claim.
|
|
302
|
+
* @param dead - The caller proved the claimed transaction can never apply.
|
|
303
|
+
*/
|
|
304
|
+
export async function releaseApplicationPayerClaim(client, store, chainId, payer, claimId, dead) {
|
|
305
|
+
const name = payerKey(chainId, payer);
|
|
306
|
+
return store.withLock(name, async () => {
|
|
307
|
+
const state = await loadPayer(store, chainId, payer);
|
|
308
|
+
if (!state.pending)
|
|
309
|
+
return true;
|
|
310
|
+
if (!same(state.pending.requestId, claimId))
|
|
311
|
+
return false;
|
|
312
|
+
const nonce = state.pending.nonce;
|
|
313
|
+
let nextNonce;
|
|
314
|
+
if (await client.getTransactionCount({ address: payer, blockTag: 'latest' }) > nonce)
|
|
315
|
+
nextNonce = nonce + 1;
|
|
316
|
+
else if (dead && await client.getTransactionCount({ address: payer, blockTag: 'pending' }) <= nonce)
|
|
317
|
+
nextNonce = nonce;
|
|
318
|
+
if (nextNonce === undefined)
|
|
319
|
+
return false;
|
|
320
|
+
await store.save(name, { schema: 1, chainId, payer, nextNonce });
|
|
321
|
+
return true;
|
|
322
|
+
});
|
|
323
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { type ClientApprovedPresentation, type PaidRetainedPresentation, type RegisteredPaidAgentSession } from '../chain/registeredPaidAgent.js';
|
|
2
|
+
import type { PaidVerifierWitness } from '../chain/prepaid.js';
|
|
3
|
+
import type { DpopSigner } from '../auth/dpop.js';
|
|
4
|
+
import type { VerifiedRequestObject } from '../oid4vp/request-object.js';
|
|
5
|
+
import { type SessionStatusResult } from '../verifier-agent/index.js';
|
|
6
|
+
import type { ApplicationStore } from './ready-slot.js';
|
|
7
|
+
/** A presentation the client's own wallet built: the approved body and the encrypted form it posts. */
|
|
8
|
+
export interface PaidWalletPresentation {
|
|
9
|
+
/** Complete presentation the client accepts for credential verification. */
|
|
10
|
+
approved: ClientApprovedPresentation;
|
|
11
|
+
/** Encrypted `direct_post.jwt` form fields; must carry `response`. */
|
|
12
|
+
form: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
/** Where a holder fetches the session's request object: the request URI and its `openid4vp://` QR/deep-link payload. */
|
|
15
|
+
export interface PaidSessionRequestLink {
|
|
16
|
+
/** Agent-hosted request URI (`<endpoint>/v1/request/<session>`). */
|
|
17
|
+
requestUri: string;
|
|
18
|
+
/** `openid4vp://?client_id=…&request_uri=…`, for a QR code or deep link. */
|
|
19
|
+
qrPayload: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* What an OAuth holder's token must bind, derived locally from the original session:
|
|
23
|
+
* the access token's `aud` must include `platformAudience`, and the DPoP proof is minted over
|
|
24
|
+
* `POST dpopHtu` with `nonce` by the key the token's `cnf.jkt` names. Public values only.
|
|
25
|
+
*/
|
|
26
|
+
export interface PaidOAuthContext {
|
|
27
|
+
/** Original locally derived session identity. */
|
|
28
|
+
sessionId: string;
|
|
29
|
+
/** Derived presentation nonce the DPoP proof must carry. */
|
|
30
|
+
nonce: string;
|
|
31
|
+
/** The session's OAuth response URL, the proof's `htu`. */
|
|
32
|
+
dpopHtu: string;
|
|
33
|
+
/** The audience the access token must name. */
|
|
34
|
+
platformAudience: string;
|
|
35
|
+
}
|
|
36
|
+
/** A DPoP-bound access token and the signer holding the key it is bound to. */
|
|
37
|
+
export interface PaidOAuthCredential {
|
|
38
|
+
/** Compact JWS access token with `cnf.jkt`; a bearer token is refused. Never logged by the SDK. */
|
|
39
|
+
accessToken: string;
|
|
40
|
+
/** Signs the session's DPoP proof with the token's bound key. */
|
|
41
|
+
signer: DpopSigner;
|
|
42
|
+
}
|
|
43
|
+
/** How the holder answers the session's request object. */
|
|
44
|
+
export type PaidSessionHolder = {
|
|
45
|
+
/** The client holds the credential and posts the presentation itself (SDK wallet). */
|
|
46
|
+
kind: 'local';
|
|
47
|
+
/** Observe the verified request and its link (e.g. to log or hand off); not billable, shown again on resume. */
|
|
48
|
+
present?(request: {
|
|
49
|
+
request: VerifiedRequestObject;
|
|
50
|
+
} & PaidSessionRequestLink): void | Promise<void>;
|
|
51
|
+
/** Build the presentation for the verified request; called once, before anything is disclosed. Receives the request link too. */
|
|
52
|
+
makePresentation(request: VerifiedRequestObject, link: PaidSessionRequestLink): PaidWalletPresentation | Promise<PaidWalletPresentation>;
|
|
53
|
+
/** Post the encrypted presentation to the agent's response URI. Called once; never repeated. */
|
|
54
|
+
submit(request: VerifiedRequestObject, presentation: PaidWalletPresentation): Promise<void>;
|
|
55
|
+
} | {
|
|
56
|
+
/** An external wallet (phone, Hovi) scans the request; the client approves what the agent retained. */
|
|
57
|
+
kind: 'external';
|
|
58
|
+
/** Show the verified request to the holder (render `qrPayload`). Called once. */
|
|
59
|
+
present(request: {
|
|
60
|
+
request: VerifiedRequestObject;
|
|
61
|
+
requestUri: string;
|
|
62
|
+
qrPayload: string;
|
|
63
|
+
}): void | Promise<void>;
|
|
64
|
+
/** Accept or refuse the complete presentation the agent retained from the wallet callback. */
|
|
65
|
+
accept(candidate: PaidRetainedPresentation, request: VerifiedRequestObject): boolean | Promise<boolean>;
|
|
66
|
+
} | {
|
|
67
|
+
/**
|
|
68
|
+
* The client presents a DPoP-bound OAuth access token itself: no wallet request
|
|
69
|
+
* object, no JAR stages. The SDK builds the proof, verifies audience, nonce, session, htm,
|
|
70
|
+
* htu, ath and key binding locally, journals the exact presentation privately BEFORE its one
|
|
71
|
+
* submission, and approves the drawn verifiers' credential work on that retained presentation.
|
|
72
|
+
*/
|
|
73
|
+
kind: 'oauth';
|
|
74
|
+
/**
|
|
75
|
+
* Supply the token for this session. Called at most once per session, before anything is
|
|
76
|
+
* disclosed; never again once the presentation is journaled (a resumed drive reuses the
|
|
77
|
+
* retained original and never asks for a refreshed token, even when it has expired).
|
|
78
|
+
*/
|
|
79
|
+
credential(context: PaidOAuthContext): PaidOAuthCredential | Promise<PaidOAuthCredential>;
|
|
80
|
+
};
|
|
81
|
+
/** Inputs to {@link drivePaidSession}. */
|
|
82
|
+
export interface PaidSessionDriverOptions {
|
|
83
|
+
/** Prepared session from prepareRegisteredPaidSession. */
|
|
84
|
+
session: RegisteredPaidAgentSession;
|
|
85
|
+
/** Anchored drawn verifier witnesses the session was prepared with. */
|
|
86
|
+
members: readonly PaidVerifierWitness[];
|
|
87
|
+
/** Private durable store with exclusive locks. */
|
|
88
|
+
store: ApplicationStore;
|
|
89
|
+
/** Cancellation for the whole drive. */
|
|
90
|
+
signal: AbortSignal;
|
|
91
|
+
/** Holder strategy. */
|
|
92
|
+
holder: PaidSessionHolder;
|
|
93
|
+
/**
|
|
94
|
+
* Wait between polls when nothing else signals progress; receives the agent's Retry-After hint
|
|
95
|
+
* when it sent one. While committee work is in flight (phase `verifying`) the driver holds a
|
|
96
|
+
* status poll instead (`?wait=1`) and continues as soon as the agent answers a change; right
|
|
97
|
+
* after it approved new proposals it continues at once.
|
|
98
|
+
*/
|
|
99
|
+
wait(retryAfterMs?: number): Promise<void>;
|
|
100
|
+
/** Observe the verified request before any credential is disclosed (receives a detached copy). */
|
|
101
|
+
observeRequest?(request: VerifiedRequestObject): void | Promise<void>;
|
|
102
|
+
/**
|
|
103
|
+
* Resume a previous drive from the store: confirmed writes are skipped (creation is
|
|
104
|
+
* reconciled by an authenticated read). Unknown creation can also be confirmed by a
|
|
105
|
+
* verified read of the original session; every other unknown write still refuses. Default false: any
|
|
106
|
+
* retained write refuses, so a first drive can never collide with an earlier attempt.
|
|
107
|
+
*/
|
|
108
|
+
resume?: boolean;
|
|
109
|
+
/** Journal key prefix; default `wallet-` (compatible with records written by earlier drivers). */
|
|
110
|
+
journalPrefix?: string;
|
|
111
|
+
}
|
|
112
|
+
/** A retained write's outcome is unknown, or a resumed write differs from its original. */
|
|
113
|
+
export declare class PaidSessionRecoveryError extends Error {
|
|
114
|
+
readonly key: string;
|
|
115
|
+
constructor(/** Journal entry that blocks the drive. */ key: string, message: string);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* SDK-internal: entries the caller journals with the drive's FIRST durable write (creation's
|
|
119
|
+
* `prepared`), under the extra locks and after the check, in the same commit. paid-operation.ts
|
|
120
|
+
* publishes the execution consent (`certified`) this way: a session's identity derives from that
|
|
121
|
+
* consent, so creation's record and the consent are useful only together, and nothing bound to the
|
|
122
|
+
* consent is sent before that commit. `published` is set once the commit resolved.
|
|
123
|
+
*/
|
|
124
|
+
export declare const FIRST_COMMIT: unique symbol;
|
|
125
|
+
/** See {@link FIRST_COMMIT}. */
|
|
126
|
+
export interface FirstCommit {
|
|
127
|
+
lock: readonly string[];
|
|
128
|
+
check(): Promise<void>;
|
|
129
|
+
entries: readonly (readonly [string, unknown])[];
|
|
130
|
+
published?: boolean;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Retry a read-only discovery while the verifier and accountant snapshots for the current epoch
|
|
134
|
+
* are not yet anchored. Only those two explicit outcomes are retried, before any reservation,
|
|
135
|
+
* consent or delivery; every other failure is final.
|
|
136
|
+
* @param read Discovery to run.
|
|
137
|
+
* @param signal Bounds the total wait.
|
|
138
|
+
* @param wait Delay between attempts.
|
|
139
|
+
*/
|
|
140
|
+
export declare function waitForPaidSnapshot<T>(read: () => Promise<T>, signal: AbortSignal, wait: () => Promise<void>): Promise<T>;
|
|
141
|
+
/**
|
|
142
|
+
* Drive one prepared paid session to a completed, verified committee token.
|
|
143
|
+
* Creation, request-object approval, presentation, continuation and credential approvals are
|
|
144
|
+
* each journaled before sending; an unknown outcome is never redelivered.
|
|
145
|
+
* @param options Session, anchored witnesses, store, holder strategy and pacing.
|
|
146
|
+
*/
|
|
147
|
+
export declare function drivePaidSession(options: PaidSessionDriverOptions): Promise<SessionStatusResult>;
|