@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,139 @@
|
|
|
1
|
+
import { decodeFunctionResult, encodeFunctionData } from 'viem';
|
|
2
|
+
import { TasraError } from '../errors.js';
|
|
3
|
+
import { headFollowerOf } from './headFollower.js';
|
|
4
|
+
import { thresholdRandomBeaconAbi } from './abis/thresholdRandomBeacon.js';
|
|
5
|
+
/**
|
|
6
|
+
* D8 (2026-10-09): a paid verification epoch is admissible iff it was current or previous at
|
|
7
|
+
* the reservation's stored quote block (`Settlement.prepaidAssignmentBlock`), the window the
|
|
8
|
+
* accountant quorum enforced when it signed the reservation. Mirrors Rust
|
|
9
|
+
* `keykeeper_eth::paid_epoch` in its constants and decisions; keep the two in step.
|
|
10
|
+
* An unpaid draw is not judged here: it keeps the live `{latest, latest - 1}` window.
|
|
11
|
+
*/
|
|
12
|
+
/** Longest a creator's payment intent may live (`expires - now`). Rust `PAYMENT_INTENT_MAX_LIFETIME_SECS`. */
|
|
13
|
+
export const PAYMENT_INTENT_MAX_LIFETIME_SECS = 3600n;
|
|
14
|
+
/** Oldest quote block a reservation signer approves over. Rust `RESERVATION_QUOTE_MAX_AGE_SECS`. */
|
|
15
|
+
export const RESERVATION_QUOTE_MAX_AGE_SECS = 30n;
|
|
16
|
+
/**
|
|
17
|
+
* Signed submission window (`deadline = min(quote_ts + this, expires)`), enforced by the signers
|
|
18
|
+
* and `Settlement` only; not derivable from the assignment block and not re-proved here.
|
|
19
|
+
* Rust `RESERVATION_SUBMISSION_WINDOW_SECS`.
|
|
20
|
+
*/
|
|
21
|
+
export const RESERVATION_SUBMISSION_WINDOW_SECS = 120n;
|
|
22
|
+
/** How far a fresh observation's block time may lead the consumer clock. Rust `OBSERVATION_MAX_FUTURE_SKEW_SECS`. */
|
|
23
|
+
export const OBSERVATION_MAX_FUTURE_SKEW_SECS = 2n;
|
|
24
|
+
/**
|
|
25
|
+
* Upper bound on (observation time - quote block time) for using a purchased assignment (3632 s).
|
|
26
|
+
* Derived, not chosen; it bounds use, not quote signing or mining freshness. Rust `MAX_ASSIGNMENT_AGE_SECS`.
|
|
27
|
+
*/
|
|
28
|
+
export const MAX_ASSIGNMENT_AGE_SECS = PAYMENT_INTENT_MAX_LIFETIME_SECS + RESERVATION_QUOTE_MAX_AGE_SECS + OBSERVATION_MAX_FUTURE_SKEW_SECS;
|
|
29
|
+
const ZERO32 = `0x${'0'.repeat(64)}`;
|
|
30
|
+
const HEX32 = /^0x[0-9a-f]{64}$/i;
|
|
31
|
+
const ADDRESS = /^0x[0-9a-f]{40}$/i;
|
|
32
|
+
/**
|
|
33
|
+
* A paid epoch could not be admitted. `paid_epoch_unavailable` (retryable): the quote block or
|
|
34
|
+
* its historical state could not be read (unknown block, pruned state, RPC failure); it is never
|
|
35
|
+
* an admission and never falls back to the live head. `paid_epoch_refused` (not retryable): a
|
|
36
|
+
* definite answer about the payment (a reorganised or substituted quote block, or an epoch
|
|
37
|
+
* outside the quote block's `{E_a, E_a - 1}`).
|
|
38
|
+
*/
|
|
39
|
+
export class PaidEpochError extends TasraError {
|
|
40
|
+
/** Stable failure code. */
|
|
41
|
+
code;
|
|
42
|
+
constructor(code, message, cause) {
|
|
43
|
+
super(message, { retryable: code === 'paid_epoch_unavailable', cause });
|
|
44
|
+
this.code = code;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const refuse = (message) => new PaidEpochError('paid_epoch_refused', message);
|
|
48
|
+
const unavailable = (message, cause) => new PaidEpochError('paid_epoch_unavailable', message, cause);
|
|
49
|
+
/** Throws a definite {@link PaidEpochError} unless `verificationEpoch` was current or previous at the receipt's quote block. */
|
|
50
|
+
export function requirePaidEpoch(verificationEpoch, receipt, anchor, headEpoch) {
|
|
51
|
+
if (receipt.assignmentBlock.toLowerCase() === ZERO32)
|
|
52
|
+
throw refuse('paid epoch has no on-chain assignment block');
|
|
53
|
+
if (anchor.blockHash.toLowerCase() !== receipt.assignmentBlock.toLowerCase())
|
|
54
|
+
throw refuse("paid epoch anchor is not the reservation's assignment block");
|
|
55
|
+
if (anchor.blockNumber > receipt.blockNumber || anchor.blockTimestamp > receipt.blockTimestamp)
|
|
56
|
+
throw refuse('paid epoch assignment block is after the observation');
|
|
57
|
+
if (receipt.blockTimestamp - anchor.blockTimestamp > MAX_ASSIGNMENT_AGE_SECS)
|
|
58
|
+
throw refuse('paid epoch assignment block is older than the payment lifetime');
|
|
59
|
+
// The beacon epoch never moves back; a head behind the anchor is not this chain's history.
|
|
60
|
+
if (headEpoch < anchor.beaconEpoch)
|
|
61
|
+
throw refuse('beacon head is behind the paid epoch assignment block');
|
|
62
|
+
if (verificationEpoch !== anchor.beaconEpoch && !(anchor.beaconEpoch > 0n && verificationEpoch === anchor.beaconEpoch - 1n)) {
|
|
63
|
+
throw refuse('paid verification epoch was not current or previous at its assignment block');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Run one RPC read; any failure (unknown block, pruned state, transport) is retryable, never an admission. */
|
|
67
|
+
async function readOrUnavailable(what, read) {
|
|
68
|
+
try {
|
|
69
|
+
return await read();
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw unavailable(`${what} unavailable`, error);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Most anchors kept per client (one per paid operation in flight is plenty). */
|
|
76
|
+
const MAX_CACHED_ANCHORS = 256;
|
|
77
|
+
const anchors = new WeakMap();
|
|
78
|
+
function cachedAnchor(client, key) {
|
|
79
|
+
const known = anchors.get(client), value = known?.get(key);
|
|
80
|
+
if (value && known) {
|
|
81
|
+
known.delete(key);
|
|
82
|
+
known.set(key, value);
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
function keepAnchor(client, key, value) {
|
|
87
|
+
let known = anchors.get(client);
|
|
88
|
+
if (!known)
|
|
89
|
+
anchors.set(client, known = new Map());
|
|
90
|
+
known.delete(key);
|
|
91
|
+
if (known.size >= MAX_CACHED_ANCHORS)
|
|
92
|
+
known.delete(known.keys().next().value);
|
|
93
|
+
known.set(key, value);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* `beacon.epoch()` at `assignmentBlock` (EIP-1898 `requireCanonical`), plus a by-number canonical
|
|
97
|
+
* recheck. A missing block or unservable state is retryable `paid_epoch_unavailable`; a known
|
|
98
|
+
* block that is not canonical (or answers for another hash) is a definite `paid_epoch_refused`.
|
|
99
|
+
* There is no fallback to the head or to logs.
|
|
100
|
+
*
|
|
101
|
+
* The block's number and time and the epoch at that HASH are immutable, so once read they are
|
|
102
|
+
* kept per client (bounded) and the paid operation's later approvals read only the canonical
|
|
103
|
+
* recheck, which is never kept. A failed or refused read keeps nothing.
|
|
104
|
+
*/
|
|
105
|
+
export async function readAssignmentEpoch(client, beacon, assignmentBlock) {
|
|
106
|
+
if (!HEX32.test(assignmentBlock) || assignmentBlock.toLowerCase() === ZERO32
|
|
107
|
+
|| !ADDRESS.test(beacon) || /^0x0{40}$/i.test(beacon))
|
|
108
|
+
throw refuse('paid epoch anchor needs a nonzero assignment block and beacon');
|
|
109
|
+
const anchor = assignmentBlock.toLowerCase(), key = `${beacon.toLowerCase()}|${anchor}`;
|
|
110
|
+
let atHash = cachedAnchor(client, key), fresh;
|
|
111
|
+
if (!atHash) {
|
|
112
|
+
// The header first: nothing is read at a hash the node does not serve as this block.
|
|
113
|
+
const block = await readOrUnavailable('paid epoch assignment block', () => client.getBlock({ blockHash: assignmentBlock }));
|
|
114
|
+
if (block.hash?.toLowerCase() !== anchor || block.number === null)
|
|
115
|
+
throw refuse('assignment block hash mismatch');
|
|
116
|
+
const beaconEpoch = await readOrUnavailable('beacon epoch at the paid epoch assignment block', async () => {
|
|
117
|
+
const data = encodeFunctionData({ abi: thresholdRandomBeaconAbi, functionName: 'epoch' });
|
|
118
|
+
const result = await client.call({ to: beacon, data, blockHash: assignmentBlock, requireCanonical: true, batch: false });
|
|
119
|
+
if (result.data === undefined)
|
|
120
|
+
throw new Error('empty beacon epoch response');
|
|
121
|
+
return decodeFunctionResult({ abi: thresholdRandomBeaconAbi, functionName: 'epoch', data: result.data });
|
|
122
|
+
});
|
|
123
|
+
fresh = { blockNumber: block.number, blockTimestamp: block.timestamp, beaconEpoch };
|
|
124
|
+
atHash = fresh;
|
|
125
|
+
}
|
|
126
|
+
const number = atHash.blockNumber;
|
|
127
|
+
// The paid-epoch anchor is re-proven at every use: the canonical recheck by number is skipped
|
|
128
|
+
// only when the head follower vouches for this exact block (finalized, in its gap-free chain).
|
|
129
|
+
const proven = headFollowerOf(client)?.isCanonical({ blockNumber: number, blockHash: assignmentBlock, blockTimestamp: atHash.blockTimestamp }) === true;
|
|
130
|
+
if (!proven) {
|
|
131
|
+
const canonical = await readOrUnavailable('paid epoch assignment block number', () => client.getBlock({ blockNumber: number }));
|
|
132
|
+
if (canonical.hash?.toLowerCase() !== anchor)
|
|
133
|
+
throw refuse('assignment block is not canonical');
|
|
134
|
+
}
|
|
135
|
+
// Kept only once the whole read succeeded.
|
|
136
|
+
if (fresh)
|
|
137
|
+
keepAnchor(client, key, fresh);
|
|
138
|
+
return { blockHash: assignmentBlock, blockNumber: number, blockTimestamp: atHash.blockTimestamp, beaconEpoch: atHash.beaconEpoch };
|
|
139
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { PaidAgentHttpResponse } from './paidAgentTransport.js';
|
|
2
|
+
/** First backoff when the server gives no usable hint, ms. */
|
|
3
|
+
export declare const PAID_FIRST_BACKOFF_MS = 500;
|
|
4
|
+
/** Backoff doubling stops here, ms. */
|
|
5
|
+
export declare const PAID_MAX_BACKOFF_MS = 8000;
|
|
6
|
+
/** Longest server hint honoured, ms (the accountant's reservation admission window is 120 s). */
|
|
7
|
+
export declare const PAID_MAX_WAIT_MS = 120000;
|
|
8
|
+
/** Attempt ceiling independent of the deadline. */
|
|
9
|
+
export declare const PAID_MAX_ATTEMPTS = 64;
|
|
10
|
+
/**
|
|
11
|
+
* Time source for paced paid requests. `now` is wall-clock milliseconds (the same epoch as
|
|
12
|
+
* `Date.now()`), because deadlines derive from signed Unix-second expiries. Inject one in tests.
|
|
13
|
+
*/
|
|
14
|
+
export interface PaidPacingClock {
|
|
15
|
+
/** Current wall-clock time in ms. */
|
|
16
|
+
now(): number;
|
|
17
|
+
/** Resolve after `ms`; reject with the signal's reason when it aborts. */
|
|
18
|
+
sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
19
|
+
/** Extra wait added ON TOP of `baseMs` (never shortens a hint), in `0..=baseMs/4`. */
|
|
20
|
+
jitter(baseMs: number): number;
|
|
21
|
+
}
|
|
22
|
+
/** Wall clock, timers and `Math.random` jitter. */
|
|
23
|
+
export declare const systemPacingClock: PaidPacingClock;
|
|
24
|
+
/**
|
|
25
|
+
* The server's requested wait from `Retry-After` and/or `x-ratelimit-after` (tower_governor), each
|
|
26
|
+
* parsed STRICTLY as one integer-seconds value of at most six digits. When both are valid the longer
|
|
27
|
+
* wins. Anything else (absent, repeated and therefore comma-joined, signed, fractional, padded, an
|
|
28
|
+
* HTTP-date, oversized) is ignored and the caller's own backoff applies.
|
|
29
|
+
* @param retryAfter Raw `Retry-After` value, if any.
|
|
30
|
+
* @param rateLimitAfter Raw `x-ratelimit-after` value, if any.
|
|
31
|
+
* @returns The wait in ms, or undefined.
|
|
32
|
+
*/
|
|
33
|
+
export declare function paidServerWaitMs(retryAfter?: string | null, rateLimitAfter?: string | null): number | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* The strict hint of a paid-agent reply. Transports that report the raw headers are parsed strictly;
|
|
36
|
+
* a transport that only reports `retryAfterMs` counts when it is a whole number of seconds within the
|
|
37
|
+
* same bound (an HTTP-date or fractional value is ignored).
|
|
38
|
+
* @param response Reply from a paid-agent transport.
|
|
39
|
+
*/
|
|
40
|
+
export declare function paidResponseWaitMs(response: PaidAgentHttpResponse): number | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* One operation's retry state: create it once per logical request (one route, one deadline). Call
|
|
43
|
+
* {@link PaidBackoff.readyToSend} immediately before EVERY send and {@link PaidBackoff.wait} after
|
|
44
|
+
* each refusal the caller has decided is repeatable.
|
|
45
|
+
*
|
|
46
|
+
* `attemptBudgetMs` is the longest one attempt can take (provider check + HTTP timeout). A repeated
|
|
47
|
+
* attempt starts only with at least that much time left, so a resend can never run past the
|
|
48
|
+
* deadline. A first attempt needs only a deadline not yet reached (the single-attempt behaviour).
|
|
49
|
+
*/
|
|
50
|
+
export declare class PaidBackoff {
|
|
51
|
+
#private;
|
|
52
|
+
readonly clock: PaidPacingClock;
|
|
53
|
+
readonly route: string;
|
|
54
|
+
readonly deadlineMs: number;
|
|
55
|
+
readonly attemptBudgetMs: number;
|
|
56
|
+
/**
|
|
57
|
+
* @param clock Time source.
|
|
58
|
+
* @param route Route label for errors, without identifiers.
|
|
59
|
+
* @param deadlineMs Existing wall-clock deadline in ms; never extended.
|
|
60
|
+
* @param attemptBudgetMs Longest single attempt, ms.
|
|
61
|
+
*/
|
|
62
|
+
constructor(clock: PaidPacingClock, route: string, deadlineMs: number, attemptBudgetMs: number);
|
|
63
|
+
/** Refusals waited out so far. */
|
|
64
|
+
get retries(): number;
|
|
65
|
+
/**
|
|
66
|
+
* Re-reads the clock right before a send and returns the time left in ms. Refuses typed
|
|
67
|
+
* (`no_time_to_send`) when the deadline passed, or when less than one attempt's budget is left
|
|
68
|
+
* for a repeated attempt: an overrunning sleep is caught here, never sent through.
|
|
69
|
+
*/
|
|
70
|
+
readyToSend(): number;
|
|
71
|
+
/**
|
|
72
|
+
* Sleeps before the next attempt after `status`, or fails typed WITHOUT sleeping when the attempt
|
|
73
|
+
* ceiling is spent, the server asks for more than {@link PAID_MAX_WAIT_MS}, or the wait plus one
|
|
74
|
+
* attempt's budget would reach the deadline. The wait is never shorter than a valid hint; jitter
|
|
75
|
+
* only lengthens it, within the slack that still leaves one attempt's budget.
|
|
76
|
+
* @param status Refusal status.
|
|
77
|
+
* @param hintMs Strict server hint, if any.
|
|
78
|
+
* @param signal Cancellation of the sleep.
|
|
79
|
+
*/
|
|
80
|
+
wait(status: number, hintMs: number | undefined, signal?: AbortSignal): Promise<void>;
|
|
81
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Bounded, deadline-respecting backoff for paid requests a server refused with a definite
|
|
2
|
+
// "not now" (HTTP 429 / 503) before acting on them.
|
|
3
|
+
//
|
|
4
|
+
// Only callers that know the request is safely repeatable use this: the paid verifier-agent reads,
|
|
5
|
+
// the byte-identical retained approval, the presentation continuation (429 only) and the accountant
|
|
6
|
+
// reservation `prepare` (nothing is on chain yet). A transport error carries no status and is NEVER
|
|
7
|
+
// paced here: its outcome is unknown, so the caller keeps its read-to-reconcile rule.
|
|
8
|
+
//
|
|
9
|
+
// The wait is `max(server hint, current backoff)` plus non-negative jitter: a valid server hint is a
|
|
10
|
+
// FLOOR and is never shortened. A hint above MAX_WAIT_MS fails typed instead of being cut down. The
|
|
11
|
+
// caller's existing deadline is never extended: a wait that, plus one attempt's budget, would reach
|
|
12
|
+
// it fails WITHOUT sleeping, and the deadline is re-read immediately before every send, so an
|
|
13
|
+
// overrunning sleep never leads to a late send. Mirrors `tasra-cli`'s `payment/retry.rs`.
|
|
14
|
+
import { PaidBackoffError } from '../errors.js';
|
|
15
|
+
/** First backoff when the server gives no usable hint, ms. */
|
|
16
|
+
export const PAID_FIRST_BACKOFF_MS = 500;
|
|
17
|
+
/** Backoff doubling stops here, ms. */
|
|
18
|
+
export const PAID_MAX_BACKOFF_MS = 8_000;
|
|
19
|
+
/** Longest server hint honoured, ms (the accountant's reservation admission window is 120 s). */
|
|
20
|
+
export const PAID_MAX_WAIT_MS = 120_000;
|
|
21
|
+
/** Attempt ceiling independent of the deadline. */
|
|
22
|
+
export const PAID_MAX_ATTEMPTS = 64;
|
|
23
|
+
/** A delay-seconds hint with more digits than this is garbage (over 11 days). */
|
|
24
|
+
const MAX_HINT_DIGITS = 6;
|
|
25
|
+
/** Wall clock, timers and `Math.random` jitter. */
|
|
26
|
+
export const systemPacingClock = Object.freeze({
|
|
27
|
+
now: () => Date.now(),
|
|
28
|
+
sleep: (ms, signal) => new Promise((resolve, reject) => {
|
|
29
|
+
signal?.throwIfAborted();
|
|
30
|
+
const done = () => { signal?.removeEventListener('abort', abort); resolve(); };
|
|
31
|
+
const timer = setTimeout(done, ms);
|
|
32
|
+
const abort = () => { clearTimeout(timer); reject(signal.reason); };
|
|
33
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
34
|
+
}),
|
|
35
|
+
jitter: (baseMs) => Math.floor(Math.random() * (Math.floor(baseMs / 4) + 1)),
|
|
36
|
+
});
|
|
37
|
+
function seconds(value) {
|
|
38
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_HINT_DIGITS || !/^[0-9]+$/.test(value))
|
|
39
|
+
return undefined;
|
|
40
|
+
return Number(value) * 1000;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The server's requested wait from `Retry-After` and/or `x-ratelimit-after` (tower_governor), each
|
|
44
|
+
* parsed STRICTLY as one integer-seconds value of at most six digits. When both are valid the longer
|
|
45
|
+
* wins. Anything else (absent, repeated and therefore comma-joined, signed, fractional, padded, an
|
|
46
|
+
* HTTP-date, oversized) is ignored and the caller's own backoff applies.
|
|
47
|
+
* @param retryAfter Raw `Retry-After` value, if any.
|
|
48
|
+
* @param rateLimitAfter Raw `x-ratelimit-after` value, if any.
|
|
49
|
+
* @returns The wait in ms, or undefined.
|
|
50
|
+
*/
|
|
51
|
+
export function paidServerWaitMs(retryAfter, rateLimitAfter) {
|
|
52
|
+
const a = seconds(retryAfter), b = seconds(rateLimitAfter);
|
|
53
|
+
return a !== undefined && b !== undefined ? Math.max(a, b) : a ?? b;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The strict hint of a paid-agent reply. Transports that report the raw headers are parsed strictly;
|
|
57
|
+
* a transport that only reports `retryAfterMs` counts when it is a whole number of seconds within the
|
|
58
|
+
* same bound (an HTTP-date or fractional value is ignored).
|
|
59
|
+
* @param response Reply from a paid-agent transport.
|
|
60
|
+
*/
|
|
61
|
+
export function paidResponseWaitMs(response) {
|
|
62
|
+
if (response.retryAfter !== undefined || response.rateLimitAfter !== undefined)
|
|
63
|
+
return paidServerWaitMs(response.retryAfter, response.rateLimitAfter);
|
|
64
|
+
const ms = response.retryAfterMs;
|
|
65
|
+
return ms !== undefined && Number.isSafeInteger(ms) && ms >= 0 && ms % 1000 === 0 && ms < 10 ** MAX_HINT_DIGITS * 1000 ? ms : undefined;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* One operation's retry state: create it once per logical request (one route, one deadline). Call
|
|
69
|
+
* {@link PaidBackoff.readyToSend} immediately before EVERY send and {@link PaidBackoff.wait} after
|
|
70
|
+
* each refusal the caller has decided is repeatable.
|
|
71
|
+
*
|
|
72
|
+
* `attemptBudgetMs` is the longest one attempt can take (provider check + HTTP timeout). A repeated
|
|
73
|
+
* attempt starts only with at least that much time left, so a resend can never run past the
|
|
74
|
+
* deadline. A first attempt needs only a deadline not yet reached (the single-attempt behaviour).
|
|
75
|
+
*/
|
|
76
|
+
export class PaidBackoff {
|
|
77
|
+
clock;
|
|
78
|
+
route;
|
|
79
|
+
deadlineMs;
|
|
80
|
+
attemptBudgetMs;
|
|
81
|
+
#next = PAID_FIRST_BACKOFF_MS;
|
|
82
|
+
#attempts = 0;
|
|
83
|
+
/**
|
|
84
|
+
* @param clock Time source.
|
|
85
|
+
* @param route Route label for errors, without identifiers.
|
|
86
|
+
* @param deadlineMs Existing wall-clock deadline in ms; never extended.
|
|
87
|
+
* @param attemptBudgetMs Longest single attempt, ms.
|
|
88
|
+
*/
|
|
89
|
+
constructor(clock, route, deadlineMs, attemptBudgetMs) {
|
|
90
|
+
this.clock = clock;
|
|
91
|
+
this.route = route;
|
|
92
|
+
this.deadlineMs = deadlineMs;
|
|
93
|
+
this.attemptBudgetMs = attemptBudgetMs;
|
|
94
|
+
}
|
|
95
|
+
/** Refusals waited out so far. */
|
|
96
|
+
get retries() { return this.#attempts; }
|
|
97
|
+
/**
|
|
98
|
+
* Re-reads the clock right before a send and returns the time left in ms. Refuses typed
|
|
99
|
+
* (`no_time_to_send`) when the deadline passed, or when less than one attempt's budget is left
|
|
100
|
+
* for a repeated attempt: an overrunning sleep is caught here, never sent through.
|
|
101
|
+
*/
|
|
102
|
+
readyToSend() {
|
|
103
|
+
const remaining = Math.max(0, this.deadlineMs - this.clock.now());
|
|
104
|
+
const needed = this.#attempts === 0 ? 0 : this.attemptBudgetMs;
|
|
105
|
+
if (remaining <= 0 || remaining < needed) {
|
|
106
|
+
throw new PaidBackoffError({ code: 'no_time_to_send', route: this.route, remainingMs: remaining, neededMs: needed, attempts: this.#attempts });
|
|
107
|
+
}
|
|
108
|
+
return remaining;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Sleeps before the next attempt after `status`, or fails typed WITHOUT sleeping when the attempt
|
|
112
|
+
* ceiling is spent, the server asks for more than {@link PAID_MAX_WAIT_MS}, or the wait plus one
|
|
113
|
+
* attempt's budget would reach the deadline. The wait is never shorter than a valid hint; jitter
|
|
114
|
+
* only lengthens it, within the slack that still leaves one attempt's budget.
|
|
115
|
+
* @param status Refusal status.
|
|
116
|
+
* @param hintMs Strict server hint, if any.
|
|
117
|
+
* @param signal Cancellation of the sleep.
|
|
118
|
+
*/
|
|
119
|
+
async wait(status, hintMs, signal) {
|
|
120
|
+
this.#attempts++;
|
|
121
|
+
const base = { route: this.route, httpStatus: status, attempts: this.#attempts, ...(hintMs !== undefined ? { retryAfterMs: hintMs } : {}) };
|
|
122
|
+
if (this.#attempts >= PAID_MAX_ATTEMPTS)
|
|
123
|
+
throw new PaidBackoffError({ ...base, code: 'attempts_exhausted' });
|
|
124
|
+
if (hintMs !== undefined && hintMs > PAID_MAX_WAIT_MS)
|
|
125
|
+
throw new PaidBackoffError({ ...base, code: 'server_wait_too_long' });
|
|
126
|
+
const wait = hintMs === undefined ? this.#next : Math.max(hintMs, this.#next);
|
|
127
|
+
const remaining = Math.max(0, this.deadlineMs - this.clock.now());
|
|
128
|
+
const needed = wait + this.attemptBudgetMs;
|
|
129
|
+
if (needed >= remaining)
|
|
130
|
+
throw new PaidBackoffError({ ...base, code: 'deadline_exceeded', remainingMs: remaining, neededMs: needed });
|
|
131
|
+
const extra = this.clock.jitter(wait);
|
|
132
|
+
const jitter = Number.isSafeInteger(extra) && extra > 0 ? Math.min(extra, remaining - needed) : 0;
|
|
133
|
+
await this.clock.sleep(wait + jitter, signal);
|
|
134
|
+
this.#next = Math.min(this.#next * 2, PAID_MAX_BACKOFF_MS);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type Address, type Hex, type PublicClient } from 'viem';
|
|
2
|
+
/** Multicall3's canonical, deterministic-deployment address. */
|
|
3
|
+
export declare const CANONICAL_MULTICALL3: Address;
|
|
4
|
+
/**
|
|
5
|
+
* keccak256 of the canonical Multicall3 runtime code (3808 bytes), as read with `eth_getCode` from
|
|
6
|
+
* the canonical address on Avalanche Fuji and Avalanche C-Chain. Any other code is not trusted.
|
|
7
|
+
*/
|
|
8
|
+
export declare const MULTICALL3_CODE_HASH: Hex;
|
|
9
|
+
/** Most calls in one aggregate; a queue that reaches it is sent at once. */
|
|
10
|
+
export declare const MAX_AGGREGATE_CALLS = 64;
|
|
11
|
+
/** The finalized head is read at most once per this interval per client (about one block). */
|
|
12
|
+
export declare const FINALIZED_REFRESH_MS = 1000;
|
|
13
|
+
/** A canonical block every read of one observation is pinned to. */
|
|
14
|
+
export interface PinnedBlock {
|
|
15
|
+
/** Block number. */
|
|
16
|
+
blockNumber: bigint;
|
|
17
|
+
/** Block hash. */
|
|
18
|
+
blockHash: Hex;
|
|
19
|
+
/** Block timestamp, Unix seconds. */
|
|
20
|
+
blockTimestamp: bigint;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Internal: choose the Multicall3 address pinned reads of `client` may batch through (`false`
|
|
24
|
+
* disables batching). The code hash is checked either way.
|
|
25
|
+
* @param client Client created for one deployment.
|
|
26
|
+
* @param multicall3 Address to probe, or false.
|
|
27
|
+
*/
|
|
28
|
+
export declare function configurePinnedReads(client: PublicClient, multicall3: Address | false | undefined): void;
|
|
29
|
+
/**
|
|
30
|
+
* One `eth_call` of `data` on `to` at `blockHash` (canonical required), answering exactly what
|
|
31
|
+
* `client.call({..., blockHash, requireCanonical: true}).data` answers, success or error.
|
|
32
|
+
* Reads issued together at the same block share one Multicall3 aggregate where that is verified.
|
|
33
|
+
* @param client Trusted client.
|
|
34
|
+
* @param blockHash Canonical block every read is pinned to.
|
|
35
|
+
* @param to Contract address.
|
|
36
|
+
* @param data Encoded calldata.
|
|
37
|
+
*/
|
|
38
|
+
export declare function pinnedCall(client: PublicClient, blockHash: Hex, to: Address, data: Hex): Promise<Hex | undefined>;
|
|
39
|
+
/**
|
|
40
|
+
* A registry read at `at`: from the finalized-block cache, else shared with an identical read in
|
|
41
|
+
* flight, else batched. With `cache`, a successful non-empty result is kept once `at` is confirmed
|
|
42
|
+
* finalized; everything else (errors, empty answers) is never kept.
|
|
43
|
+
* @param client Trusted client.
|
|
44
|
+
* @param at Canonical observation the read is pinned to.
|
|
45
|
+
* @param to Contract address.
|
|
46
|
+
* @param data Encoded calldata.
|
|
47
|
+
* @param cache Use and fill the finalized-block cache (a fresh head observation only).
|
|
48
|
+
*/
|
|
49
|
+
export declare function pinnedRegistryCall(client: PublicClient, at: PinnedBlock, to: Address, data: Hex, cache: boolean): Promise<Hex | undefined>;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// Block-pinned contract reads on the paid operation path, with fewer requests and the same answers.
|
|
2
|
+
//
|
|
3
|
+
// Every read here is an `eth_call` at one block HASH with `requireCanonical: true` (EIP-1898).
|
|
4
|
+
// viem's own call batching cannot carry that: `call()` skips its Multicall3 scheduler whenever a
|
|
5
|
+
// `blockHash` is given (viem 2.56), so `batch: false` alone never batched anything. Instead:
|
|
6
|
+
//
|
|
7
|
+
// - Reads issued together at the same block hash are queued for one macrotask and sent as ONE
|
|
8
|
+
// Multicall3 `aggregate3` eth_call, at that block hash with `requireCanonical: true`. A read is
|
|
9
|
+
// never moved to a block number or `latest`.
|
|
10
|
+
// - Multicall3 is used only where its runtime code hash at a pinned block equals the canonical
|
|
11
|
+
// deployment's. Anything else at that address, an absent contract or a failed probe means plain
|
|
12
|
+
// individual calls (which an HTTP JSON-RPC batch transport may still group).
|
|
13
|
+
// - Each batched call allows failure. A failed item, a failed or undecodable aggregate and every
|
|
14
|
+
// item of it are read again individually, exactly as before, so a revert or RPC error surfaces
|
|
15
|
+
// with the same type and message as an unbatched read.
|
|
16
|
+
// - Results of registry reads at a block the client has confirmed FINALIZED are kept in a short,
|
|
17
|
+
// bounded per-client cache. Errors, empty responses, `latest` reads, reservation reads and
|
|
18
|
+
// freshness rechecks are never cached; only finalized-pinned registry reads come here.
|
|
19
|
+
import { headFollowerOf } from './headFollower.js';
|
|
20
|
+
import { decodeFunctionResult, encodeFunctionData, keccak256, multicall3Abi } from 'viem';
|
|
21
|
+
import { ExpiringCache, SingleFlight } from '../internal/bounded.js';
|
|
22
|
+
/** Multicall3's canonical, deterministic-deployment address. */
|
|
23
|
+
export const CANONICAL_MULTICALL3 = '0xcA11bde05977b3631167028862bE2a173976CA11';
|
|
24
|
+
/**
|
|
25
|
+
* keccak256 of the canonical Multicall3 runtime code (3808 bytes), as read with `eth_getCode` from
|
|
26
|
+
* the canonical address on Avalanche Fuji and Avalanche C-Chain. Any other code is not trusted.
|
|
27
|
+
*/
|
|
28
|
+
export const MULTICALL3_CODE_HASH = '0xd5c15df687b16f2ff992fc8d767b4216323184a2bbc6ee2f9c398c318e770891';
|
|
29
|
+
/** Most calls in one aggregate; a queue that reaches it is sent at once. */
|
|
30
|
+
export const MAX_AGGREGATE_CALLS = 64;
|
|
31
|
+
/** Most calldata bytes in one aggregate (the same cap as `readMany`). */
|
|
32
|
+
const MAX_AGGREGATE_BYTES = 32_768;
|
|
33
|
+
/** Most distinct block hashes queued at once per client; beyond it a read runs alone. */
|
|
34
|
+
const MAX_QUEUES = 256;
|
|
35
|
+
/** A failed or negative Multicall3 probe is retried no sooner than this. */
|
|
36
|
+
const PROBE_RETRY_MS = 60_000;
|
|
37
|
+
/** The finalized head is read at most once per this interval per client (about one block). */
|
|
38
|
+
export const FINALIZED_REFRESH_MS = 1_000;
|
|
39
|
+
/** Most finalized-pinned registry results cached per client. */
|
|
40
|
+
const MAX_CACHED_READS = 4_096;
|
|
41
|
+
/** A cached block-pinned result is useless once no fresh observation can use its block (30 s + 2 s skew). */
|
|
42
|
+
const CACHE_TTL_AFTER_BLOCK_MS = 32_000;
|
|
43
|
+
/** Most identical in-flight registry reads shared per client (unchanged from before). */
|
|
44
|
+
const MAX_SHARED_REGISTRY_READS = 1_024;
|
|
45
|
+
const states = new WeakMap();
|
|
46
|
+
function state(client) {
|
|
47
|
+
let s = states.get(client);
|
|
48
|
+
if (!s)
|
|
49
|
+
states.set(client, s = { multicall: CANONICAL_MULTICALL3, retryAt: 0, queues: new Map(), finalizedAt: -Infinity,
|
|
50
|
+
cache: new ExpiringCache(MAX_CACHED_READS), shared: new SingleFlight(MAX_SHARED_REGISTRY_READS) });
|
|
51
|
+
return s;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Internal: choose the Multicall3 address pinned reads of `client` may batch through (`false`
|
|
55
|
+
* disables batching). The code hash is checked either way.
|
|
56
|
+
* @param client Client created for one deployment.
|
|
57
|
+
* @param multicall3 Address to probe, or false.
|
|
58
|
+
*/
|
|
59
|
+
export function configurePinnedReads(client, multicall3) {
|
|
60
|
+
state(client).multicall = multicall3 ?? CANONICAL_MULTICALL3;
|
|
61
|
+
}
|
|
62
|
+
/** The unbatched read: what every pinned read was before batching, and the fallback for any failure. */
|
|
63
|
+
async function direct(client, blockHash, to, data) {
|
|
64
|
+
return (await client.call({ to, data, blockHash, requireCanonical: true, batch: false })).data;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* One `eth_call` of `data` on `to` at `blockHash` (canonical required), answering exactly what
|
|
68
|
+
* `client.call({..., blockHash, requireCanonical: true}).data` answers, success or error.
|
|
69
|
+
* Reads issued together at the same block share one Multicall3 aggregate where that is verified.
|
|
70
|
+
* @param client Trusted client.
|
|
71
|
+
* @param blockHash Canonical block every read is pinned to.
|
|
72
|
+
* @param to Contract address.
|
|
73
|
+
* @param data Encoded calldata.
|
|
74
|
+
*/
|
|
75
|
+
export function pinnedCall(client, blockHash, to, data) {
|
|
76
|
+
const s = state(client);
|
|
77
|
+
if (s.multicall === false)
|
|
78
|
+
return direct(client, blockHash, to, data);
|
|
79
|
+
const key = blockHash.toLowerCase();
|
|
80
|
+
let queue = s.queues.get(key);
|
|
81
|
+
if (!queue) {
|
|
82
|
+
if (s.queues.size >= MAX_QUEUES)
|
|
83
|
+
return direct(client, blockHash, to, data);
|
|
84
|
+
const created = { calls: [], bytes: 0, sent: false };
|
|
85
|
+
created.timer = setTimeout(() => send(client, s, key, blockHash, created), 0);
|
|
86
|
+
s.queues.set(key, queue = created);
|
|
87
|
+
}
|
|
88
|
+
const target = queue;
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
target.calls.push({ to, data, resolve, reject });
|
|
91
|
+
target.bytes += (data.length - 2) / 2 + 20;
|
|
92
|
+
if (target.calls.length >= MAX_AGGREGATE_CALLS || target.bytes >= MAX_AGGREGATE_BYTES)
|
|
93
|
+
send(client, s, key, blockHash, target);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
function send(client, s, key, blockHash, queue) {
|
|
97
|
+
if (queue.sent)
|
|
98
|
+
return;
|
|
99
|
+
queue.sent = true;
|
|
100
|
+
if (queue.timer !== undefined)
|
|
101
|
+
clearTimeout(queue.timer);
|
|
102
|
+
if (s.queues.get(key) === queue)
|
|
103
|
+
s.queues.delete(key);
|
|
104
|
+
// run() settles every call; an unexpected throw must still settle the rest, never leave one pending.
|
|
105
|
+
run(client, s, blockHash, queue.calls).catch((error) => { for (const call of queue.calls)
|
|
106
|
+
call.reject(error); });
|
|
107
|
+
}
|
|
108
|
+
function settle(call, read) {
|
|
109
|
+
read.then(call.resolve, call.reject);
|
|
110
|
+
}
|
|
111
|
+
async function run(client, s, blockHash, calls) {
|
|
112
|
+
const alone = () => { for (const call of calls)
|
|
113
|
+
settle(call, direct(client, blockHash, call.to, call.data)); };
|
|
114
|
+
if (calls.length === 1)
|
|
115
|
+
return alone();
|
|
116
|
+
const address = await multicallAt(client, s, blockHash);
|
|
117
|
+
if (!address)
|
|
118
|
+
return alone();
|
|
119
|
+
let results;
|
|
120
|
+
try {
|
|
121
|
+
const data = encodeFunctionData({ abi: multicall3Abi, functionName: 'aggregate3',
|
|
122
|
+
args: [calls.map(call => ({ target: call.to, allowFailure: true, callData: call.data }))] });
|
|
123
|
+
const answer = await direct(client, blockHash, address, data);
|
|
124
|
+
results = answer === undefined ? undefined : decodeFunctionResult({ abi: multicall3Abi, functionName: 'aggregate3', data: answer });
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// Any aggregate-level failure (RPC error, a non-canonical block, gas, garbage) is decided by
|
|
128
|
+
// the individual reads below, which report it exactly as an unbatched read would.
|
|
129
|
+
results = undefined;
|
|
130
|
+
}
|
|
131
|
+
if (!results || results.length !== calls.length)
|
|
132
|
+
return alone();
|
|
133
|
+
calls.forEach((call, i) => {
|
|
134
|
+
const result = results[i];
|
|
135
|
+
if (result.success)
|
|
136
|
+
call.resolve(result.returnData === '0x' ? undefined : result.returnData);
|
|
137
|
+
else
|
|
138
|
+
settle(call, direct(client, blockHash, call.to, call.data));
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/** The verified Multicall3 address for reads at `blockHash`, or null to read individually. */
|
|
142
|
+
async function multicallAt(client, s, blockHash) {
|
|
143
|
+
const address = s.multicall;
|
|
144
|
+
if (address === false)
|
|
145
|
+
return null;
|
|
146
|
+
if (s.verified === true)
|
|
147
|
+
return address;
|
|
148
|
+
if (s.verified === false && Date.now() < s.retryAt)
|
|
149
|
+
return null;
|
|
150
|
+
s.probe ??= (async () => {
|
|
151
|
+
try {
|
|
152
|
+
const code = await client.getCode({ address, blockHash, requireCanonical: true });
|
|
153
|
+
// An absent contract or any code other than the canonical Multicall3 is never batched through.
|
|
154
|
+
s.verified = code !== undefined && code !== '0x' && keccak256(code) === MULTICALL3_CODE_HASH;
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
s.verified = false;
|
|
158
|
+
}
|
|
159
|
+
if (!s.verified)
|
|
160
|
+
s.retryAt = Date.now() + PROBE_RETRY_MS;
|
|
161
|
+
return s.verified;
|
|
162
|
+
})().finally(() => { s.probe = undefined; });
|
|
163
|
+
return (await s.probe) ? address : null;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* A registry read at `at`: from the finalized-block cache, else shared with an identical read in
|
|
167
|
+
* flight, else batched. With `cache`, a successful non-empty result is kept once `at` is confirmed
|
|
168
|
+
* finalized; everything else (errors, empty answers) is never kept.
|
|
169
|
+
* @param client Trusted client.
|
|
170
|
+
* @param at Canonical observation the read is pinned to.
|
|
171
|
+
* @param to Contract address.
|
|
172
|
+
* @param data Encoded calldata.
|
|
173
|
+
* @param cache Use and fill the finalized-block cache (a fresh head observation only).
|
|
174
|
+
*/
|
|
175
|
+
export async function pinnedRegistryCall(client, at, to, data, cache) {
|
|
176
|
+
const s = state(client);
|
|
177
|
+
const key = `${at.blockHash.toLowerCase()}|${to.toLowerCase()}|${data.toLowerCase()}`;
|
|
178
|
+
// A block the head follower proves canonical under instant finality is as fixed as a finalized
|
|
179
|
+
// one: its pinned results (and the follower's pre-reads of them) are served from the cache.
|
|
180
|
+
const followed = headFollowerOf(client)?.isCanonical(at) === true;
|
|
181
|
+
const cached = cache || followed ? s.cache.get(key) : undefined;
|
|
182
|
+
if (cached !== undefined)
|
|
183
|
+
return cached;
|
|
184
|
+
const result = await s.shared.run(key, () => pinnedCall(client, at.blockHash, to, data));
|
|
185
|
+
if (result !== undefined) {
|
|
186
|
+
const expiresAt = Number(at.blockTimestamp) * 1000 + CACHE_TTL_AFTER_BLOCK_MS;
|
|
187
|
+
if (followed)
|
|
188
|
+
s.cache.set(key, result, expiresAt);
|
|
189
|
+
else if (cache)
|
|
190
|
+
void finalizedBlock(client, s, at).then(final => { if (final)
|
|
191
|
+
s.cache.set(key, result, expiresAt); });
|
|
192
|
+
}
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Whether `at` is the finalized block: the client's finalized head, read at most once per
|
|
197
|
+
* {@link FINALIZED_REFRESH_MS} and shared, names exactly this number and hash. A head past it
|
|
198
|
+
* proves nothing about this hash, so it is conservatively not finalized. Never throws.
|
|
199
|
+
*/
|
|
200
|
+
async function finalizedBlock(client, s, at) {
|
|
201
|
+
const known = () => s.finalized && s.finalized.number >= at.blockNumber
|
|
202
|
+
? s.finalized.number === at.blockNumber && s.finalized.hash.toLowerCase() === at.blockHash.toLowerCase()
|
|
203
|
+
: undefined;
|
|
204
|
+
const first = known();
|
|
205
|
+
if (first !== undefined)
|
|
206
|
+
return first;
|
|
207
|
+
if (!s.finalizedRead) {
|
|
208
|
+
if (Date.now() - s.finalizedAt < FINALIZED_REFRESH_MS)
|
|
209
|
+
return false;
|
|
210
|
+
s.finalizedAt = Date.now();
|
|
211
|
+
s.finalizedRead = client.getBlock({ blockTag: 'finalized' }).then(block => {
|
|
212
|
+
if (block.number !== null && block.hash !== null && (!s.finalized || block.number > s.finalized.number))
|
|
213
|
+
s.finalized = { number: block.number, hash: block.hash };
|
|
214
|
+
}, () => undefined).finally(() => { s.finalizedRead = undefined; });
|
|
215
|
+
}
|
|
216
|
+
await s.finalizedRead;
|
|
217
|
+
return known() ?? false;
|
|
218
|
+
}
|