@t3foundry/tasra-sdk 0.3.1-next.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,1046 @@
|
|
|
1
|
+
import { decodeFunctionResult, encodeFunctionData, keccak256, recoverTypedDataAddress, toHex } from 'viem';
|
|
2
|
+
import { ed25519 } from '@noble/curves/ed25519';
|
|
3
|
+
import { randomBytes } from '@noble/hashes/utils';
|
|
4
|
+
import { UnderfundedSlotError } from '../errors.js';
|
|
5
|
+
import { hexToBytes } from '../crypto/hex.js';
|
|
6
|
+
import { assertPaymentIntentWire, keeperAssignmentCommitment, paymentIntentHash, paymentIntentTypedData, prepaidRequestId } from '../committee/payment.js';
|
|
7
|
+
import { settlementAbi } from './abis/settlement.js';
|
|
8
|
+
import { keyRegistryAbi } from './abis/keyRegistry.js';
|
|
9
|
+
import { nodeRegistryAbi } from './abis/nodeRegistry.js';
|
|
10
|
+
import { thresholdRandomBeaconAbi } from './abis/thresholdRandomBeacon.js';
|
|
11
|
+
import { verifierSetRegistryAbi } from './abis/verifierSetRegistry.js';
|
|
12
|
+
import { accountantSetRegistryAbi } from './abis/accountantSetRegistry.js';
|
|
13
|
+
import { paidExecutionReportSigningHash, verifyPaidExecutionEvidence } from '../committee/recovery.js';
|
|
14
|
+
import { selectVerifierCommittee, verifierLeaf, verifyMerkleProof } from '../committee/token.js';
|
|
15
|
+
import { protocolHex } from '../committee/receipts.js';
|
|
16
|
+
import { BillingModeError, isPrepaidSettlementVersion, readBillingMode } from './billing.js';
|
|
17
|
+
import { readAssignmentEpoch, requirePaidEpoch } from './paidEpoch.js';
|
|
18
|
+
import { systemPacingClock } from './paidPacing.js';
|
|
19
|
+
import { SingleFlight } from '../internal/bounded.js';
|
|
20
|
+
import { pinnedCall, pinnedRegistryCall } from './pinnedReads.js';
|
|
21
|
+
import { headFollowerOf } from './headFollower.js';
|
|
22
|
+
import { registerHeadPrefetch } from './headPrefetch.js';
|
|
23
|
+
import { chainIdOf } from './chainId.js';
|
|
24
|
+
import { readAccountantGroupKey, verifyDebitVoucher } from './allowance.js';
|
|
25
|
+
/**
|
|
26
|
+
* Read canonical mined credit, creator, beacon and verifier policy before approving work.
|
|
27
|
+
* All registry calls use the receipt's EIP-1898 block hash; no latest/number fallback.
|
|
28
|
+
* The paid verification epoch alone is judged at the reservation's stored quote block
|
|
29
|
+
* (`prepaidAssignmentBlock`, EIP-1898 `requireCanonical` plus a by-number recheck): it must be
|
|
30
|
+
* that block's `{epoch, epoch - 1}`. An unreadable quote block or state rejects with a retryable
|
|
31
|
+
* `PaidEpochError` (`paid_epoch_unavailable`), never an admission or a live-head fallback; a
|
|
32
|
+
* reorganised quote block or out-of-window epoch is a definite `paid_epoch_refused`.
|
|
33
|
+
* A target additionally proves drawn membership and current registered verifier standing.
|
|
34
|
+
* @param client Trusted RPC client for the independently selected deployment.
|
|
35
|
+
* @param deployment Approved contracts and explicit default verification policy.
|
|
36
|
+
* @param payment Original locally retained creator intent, never copied from a proposal.
|
|
37
|
+
* @param expected Application-selected slot, action and payload digest.
|
|
38
|
+
* @param target Optional drawn verifier whose work is about to be approved.
|
|
39
|
+
*/
|
|
40
|
+
export async function readClientExecutionPolicy(client, deployment, payment, expected, target) {
|
|
41
|
+
deployment = structuredClone(deployment);
|
|
42
|
+
payment = structuredClone(payment);
|
|
43
|
+
expected = { ...expected };
|
|
44
|
+
target = target && structuredClone(target);
|
|
45
|
+
if ([deployment.verifierSet, deployment.beacon].some(a => !ADDRESS.test(a) || /^0x0{40}$/i.test(a)))
|
|
46
|
+
throw new Error('invalid execution registry deployment');
|
|
47
|
+
requirePaidOperation(deployment, payment, expected);
|
|
48
|
+
// ONE fresh canonical observation for the whole decision. Every read below is pinned to its block
|
|
49
|
+
// hash, and the reservation, the policy reads and (for a target) the verifier's standing are
|
|
50
|
+
// independent of each other there, so they are issued together and judged in the order a
|
|
51
|
+
// sequential read would judge them. The target is read at the NodeRegistry this client last saw
|
|
52
|
+
// the KeyRegistry point to; the pointer read at THIS block decides, and a different one is read
|
|
53
|
+
// again at it. One canonicality and freshness recheck follows all of them.
|
|
54
|
+
const member = target !== undefined && drawnMember(payment, target);
|
|
55
|
+
return decideAtFreshHead(client, await observe(client, deployment), async (at) => {
|
|
56
|
+
// Only a target that is locally a member of the draw is read early; any other is refused below.
|
|
57
|
+
const hinted = member ? nodeRegistryHint(client, deployment.keyRegistry) : undefined;
|
|
58
|
+
// The quote block's epoch read (header, beacon epoch, and its canonical recheck by number: one
|
|
59
|
+
// RPC round once the block is older than the head follower's window) needs the receipt's
|
|
60
|
+
// assignment block. The block this payment's backing named when this client last judged it is a
|
|
61
|
+
// HINT: its read starts now, beside the reads at `at`, and counts only when the receipt read at
|
|
62
|
+
// THIS block names the same assignment block; otherwise it is read again for the one it names.
|
|
63
|
+
const anchorHint = assignmentHint(client, deployment.settlement, payment);
|
|
64
|
+
const earlyAnchor = anchorHint !== undefined ? readAssignmentEpoch(client, deployment.beacon, anchorHint) : undefined;
|
|
65
|
+
earlyAnchor?.catch(() => { });
|
|
66
|
+
const verifierStanding = (nodes) => Promise.all([
|
|
67
|
+
registryRead(client, at, nodes, nodeRegistryAbi, 'nodeOf', [target.operator]),
|
|
68
|
+
registryRead(client, at, nodes, nodeRegistryAbi, 'hasTag', [target.operator, keccak256(toHex('verifier'))]),
|
|
69
|
+
]);
|
|
70
|
+
const [reads, policyReads, early] = await Promise.allSettled([
|
|
71
|
+
receiptReads(client, deployment, at, payment),
|
|
72
|
+
Promise.all([
|
|
73
|
+
registryRead(client, at, deployment.keyRegistry, keyRegistryAbi, 'getKeySlot', [payment.slot]),
|
|
74
|
+
registryRead(client, at, deployment.keyRegistry, keyRegistryAbi, 'randomBeacon'),
|
|
75
|
+
registryRead(client, at, deployment.verifierSet, verifierSetRegistryAbi, 'beacon'),
|
|
76
|
+
registryRead(client, at, deployment.beacon, thresholdRandomBeaconAbi, 'epoch'),
|
|
77
|
+
registryRead(client, at, deployment.beacon, thresholdRandomBeaconAbi, 'seedAt', [BigInt(payment.verification_epoch)]),
|
|
78
|
+
registryRead(client, at, deployment.verifierSet, verifierSetRegistryAbi, 'snapshotAt', [BigInt(payment.verification_epoch)]),
|
|
79
|
+
registryRead(client, at, deployment.keyRegistry, keyRegistryAbi, 'verifierPolicy', [payment.slot]),
|
|
80
|
+
registryRead(client, at, deployment.keyRegistry, keyRegistryAbi, 'nodeRegistry'),
|
|
81
|
+
]),
|
|
82
|
+
hinted ? verifierStanding(hinted) : Promise.resolve(undefined),
|
|
83
|
+
]);
|
|
84
|
+
if (reads.status === 'rejected')
|
|
85
|
+
throw reads.reason;
|
|
86
|
+
const receipt = checkReceiptReads(at, payment, reads.value);
|
|
87
|
+
if (receipt.settled || BigInt(payment.expires) <= time())
|
|
88
|
+
throw new Error('payment cannot approve new work after settlement or expiry');
|
|
89
|
+
if (policyReads.status === 'rejected')
|
|
90
|
+
throw policyReads.reason;
|
|
91
|
+
const [slot, keyBeacon, setBeacon, latest, seed, snapshot, verifierPolicy, nodes] = policyReads.value;
|
|
92
|
+
// A standing read at the hinted registry counts only when the pointer at THIS block names it;
|
|
93
|
+
// otherwise the standing is read again at the registry the pointer names.
|
|
94
|
+
const hintHolds = hinted !== undefined && hinted.toLowerCase() === nodes.toLowerCase();
|
|
95
|
+
const standingRead = member && !hintHolds && ADDRESS.test(nodes) && !/^0x0{40}$/i.test(nodes) ? verifierStanding(nodes) : undefined;
|
|
96
|
+
// Still to read: the quote block's epoch (its header and value are kept per client; its canonical
|
|
97
|
+
// recheck is not) and the recheck of `at`, which starts only once every read at `at` has settled.
|
|
98
|
+
// Both run beside the checks below; their answers are judged in the original order.
|
|
99
|
+
const anchorRead = earlyAnchor !== undefined && anchorHint.toLowerCase() === receipt.assignmentBlock.toLowerCase()
|
|
100
|
+
? earlyAnchor : readAssignmentEpoch(client, deployment.beacon, receipt.assignmentBlock);
|
|
101
|
+
const finishRead = (async () => { await standingRead?.catch(() => { }); await finishObservation(client, at); })();
|
|
102
|
+
anchorRead.catch(() => { });
|
|
103
|
+
finishRead.catch(() => { });
|
|
104
|
+
const epoch = BigInt(payment.verification_epoch);
|
|
105
|
+
const [committee, quorum] = verifierPolicy[0] === 0 && verifierPolicy[1] === 0
|
|
106
|
+
? [deployment.defaultVerificationPolicy?.committee, deployment.defaultVerificationPolicy?.quorum] : verifierPolicy;
|
|
107
|
+
if (!slot.exists || slot.cancelled || (slot.expiry !== 0n && slot.expiry <= at.blockTimestamp)
|
|
108
|
+
|| !ADDRESS.test(slot.creator) || /^0x0{40}$/i.test(slot.creator)
|
|
109
|
+
|| [keyBeacon, setBeacon].some(pointer => pointer.toLowerCase() !== deployment.beacon.toLowerCase())
|
|
110
|
+
|| seed.toLowerCase() !== payment.verification_seed.toLowerCase()
|
|
111
|
+
|| snapshot[0].toLowerCase() !== payment.verification_root.toLowerCase()
|
|
112
|
+
|| snapshot[1] !== payment.verification_registry_size
|
|
113
|
+
|| committee !== payment.verification_committee || quorum !== payment.verification_quorum)
|
|
114
|
+
throw reversible(new Error('payment verification context differs from canonical chain policy'));
|
|
115
|
+
// D8: the epoch window is judged at the reservation's stored quote block, where the
|
|
116
|
+
// accountant quorum judged it, not at this later observation (which may be past a boundary).
|
|
117
|
+
requirePaidEpoch(epoch, receipt, await anchorRead, latest);
|
|
118
|
+
rememberAssignment(client, deployment.settlement, payment, receipt.assignmentBlock);
|
|
119
|
+
if (target) {
|
|
120
|
+
if (!member || !ADDRESS.test(nodes) || /^0x0{40}$/i.test(nodes))
|
|
121
|
+
throw new Error('verifier is not an authenticated member of the paid draw');
|
|
122
|
+
rememberNodeRegistry(client, deployment.keyRegistry, nodes);
|
|
123
|
+
let standing;
|
|
124
|
+
if (hintHolds) {
|
|
125
|
+
if (early.status === 'rejected')
|
|
126
|
+
throw early.reason;
|
|
127
|
+
standing = early.value;
|
|
128
|
+
}
|
|
129
|
+
else
|
|
130
|
+
standing = await standingRead;
|
|
131
|
+
const [node, tagged] = standing;
|
|
132
|
+
if (!node.active || tagged !== true || node.operator.toLowerCase() !== target.operator.toLowerCase()
|
|
133
|
+
|| node.pubkey.toLowerCase() !== target.publicKey.toLowerCase())
|
|
134
|
+
throw reversible(new Error('drawn verifier no longer has its registered key and standing'));
|
|
135
|
+
}
|
|
136
|
+
await finishRead;
|
|
137
|
+
// The recheck started beside the checks above; judge freshness again now, at the decision.
|
|
138
|
+
requireFresh(at);
|
|
139
|
+
const nowSecs = Number(time());
|
|
140
|
+
if (nowSecs >= payment.expires)
|
|
141
|
+
throw new Error('payment expired during client policy discovery');
|
|
142
|
+
if (slot.expiry !== 0n && slot.expiry <= BigInt(nowSecs))
|
|
143
|
+
throw new Error('slot expired during client policy discovery');
|
|
144
|
+
return { blockNumber: at.blockNumber, blockHash: at.blockHash, blockTimestamp: at.blockTimestamp,
|
|
145
|
+
policy: { chainId: deployment.chainId, settlement: deployment.settlement, keyRegistry: deployment.keyRegistry,
|
|
146
|
+
creator: slot.creator, paymentHash: paymentIntentHash(payment), cost: receipt.cost, nowSecs } };
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
/** Whether `target` is in the payment's recomputed draw with a valid inclusion proof (local only). */
|
|
150
|
+
function drawnMember(payment, target) {
|
|
151
|
+
const drawn = selectVerifierCommittee(protocolHex(payment.slot, 32, 'slot'), payment.verification_epoch, protocolHex(payment.verification_seed, 32, 'seed'), payment.verification_registry_size, payment.verification_committee);
|
|
152
|
+
return Number.isSafeInteger(target.index) && drawn.includes(target.index) && target.proof.length <= 32
|
|
153
|
+
&& verifyMerkleProof(verifierLeaf(target.index, protocolHex(target.operator, 20, 'operator'), protocolHex(target.publicKey, 32, 'verifier key')), target.proof.map(p => protocolHex(p, 32, 'proof')), protocolHex(payment.verification_root, 32, 'snapshot root'));
|
|
154
|
+
}
|
|
155
|
+
// The assignment block each payment's backing named when this client last judged it (an allowance's
|
|
156
|
+
// is the same for every request it funds; a reservation's is its own): a HINT that only starts the
|
|
157
|
+
// quote block's epoch read early, never a substitute for the receipt read at the observed block.
|
|
158
|
+
// Bounded per client.
|
|
159
|
+
const MAX_ASSIGNMENT_HINTS = 256;
|
|
160
|
+
const assignmentHints = new WeakMap();
|
|
161
|
+
function assignmentHintKey(settlement, payment) {
|
|
162
|
+
return `${settlement.toLowerCase()}|${payment.slot.toLowerCase()}|${(payment.allowance_id ?? prepaidRequestId(payment)).toLowerCase()}`;
|
|
163
|
+
}
|
|
164
|
+
function assignmentHint(client, settlement, payment) {
|
|
165
|
+
return assignmentHints.get(client)?.get(assignmentHintKey(settlement, payment));
|
|
166
|
+
}
|
|
167
|
+
function rememberAssignment(client, settlement, payment, block) {
|
|
168
|
+
let hints = assignmentHints.get(client);
|
|
169
|
+
if (!hints)
|
|
170
|
+
assignmentHints.set(client, hints = new Map());
|
|
171
|
+
const key = assignmentHintKey(settlement, payment);
|
|
172
|
+
hints.delete(key);
|
|
173
|
+
if (hints.size >= MAX_ASSIGNMENT_HINTS)
|
|
174
|
+
hints.delete(hints.keys().next().value);
|
|
175
|
+
hints.set(key, block);
|
|
176
|
+
}
|
|
177
|
+
// The NodeRegistry each KeyRegistry pointed to when this client last read it: a HINT that lets a
|
|
178
|
+
// verifier's standing be read beside the pointer, never a substitute for the pointer read at the
|
|
179
|
+
// observed block. Bounded per client.
|
|
180
|
+
const MAX_NODE_REGISTRY_HINTS = 64;
|
|
181
|
+
const nodeRegistryHints = new WeakMap();
|
|
182
|
+
function nodeRegistryHint(client, keyRegistry) {
|
|
183
|
+
return nodeRegistryHints.get(client)?.get(keyRegistry.toLowerCase());
|
|
184
|
+
}
|
|
185
|
+
function rememberNodeRegistry(client, keyRegistry, nodes) {
|
|
186
|
+
let hints = nodeRegistryHints.get(client);
|
|
187
|
+
if (!hints)
|
|
188
|
+
nodeRegistryHints.set(client, hints = new Map());
|
|
189
|
+
const key = keyRegistry.toLowerCase();
|
|
190
|
+
hints.delete(key);
|
|
191
|
+
if (hints.size >= MAX_NODE_REGISTRY_HINTS)
|
|
192
|
+
hints.delete(hints.keys().next().value);
|
|
193
|
+
hints.set(key, nodes);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Authenticate completed keeper evidence using canonical original creator, fee and roster reads.
|
|
197
|
+
* Every contract call uses the report's original EIP-1898 hash with requireCanonical; missing
|
|
198
|
+
* history fails closed. Current expiry, ownership or payout never replaces the original state.
|
|
199
|
+
* This performs no transaction, keeper request or fresh work admission.
|
|
200
|
+
* @param client Trusted bounded RPC client for the independently approved deployment.
|
|
201
|
+
* @param deployment Approved chain and contracts, never taken from a received report.
|
|
202
|
+
* @param payment Original creator payment retained before the operation.
|
|
203
|
+
* @param expected Independently intended slot, action and digest.
|
|
204
|
+
* @param target Original client key and independently selected assigned keeper stage/key.
|
|
205
|
+
* @param execution Untrusted public completed evidence, authenticated against the same history.
|
|
206
|
+
* @param transport Explicit local HTTP allowance for the historical registered endpoint.
|
|
207
|
+
*/
|
|
208
|
+
export async function readKeeperExecutionRecoveryPolicy(client, deployment, payment, expected, target, execution, transport = {}) {
|
|
209
|
+
// Validate the full report before using its block hash as an RPC selector.
|
|
210
|
+
const hash = paidExecutionReportSigningHash(payment, execution.report);
|
|
211
|
+
deployment = { ...deployment };
|
|
212
|
+
payment = structuredClone(payment);
|
|
213
|
+
expected = { ...expected };
|
|
214
|
+
target = { ...target };
|
|
215
|
+
execution = structuredClone(execution);
|
|
216
|
+
transport = { ...transport };
|
|
217
|
+
validateDeployment(deployment);
|
|
218
|
+
if (payment.chain_id !== deployment.chainId || payment.settlement.toLowerCase() !== deployment.settlement.toLowerCase()
|
|
219
|
+
|| payment.key_registry.toLowerCase() !== deployment.keyRegistry.toLowerCase())
|
|
220
|
+
throw new Error('recovery payment deployment mismatch');
|
|
221
|
+
// ADR-0090: an allowance-backed operation has no per-request reservation at its admission block
|
|
222
|
+
// (its backing is the voucher); historical recovery of one is not built and fails closed here.
|
|
223
|
+
if (payment.allowance_id !== undefined)
|
|
224
|
+
throw new Error('recovery of allowance-backed keeper work is not supported yet');
|
|
225
|
+
if (payment.slot.toLowerCase() !== expected.slot.toLowerCase() || payment.action !== expected.action
|
|
226
|
+
|| payment.payload_digest.toLowerCase() !== expected.payloadDigest.toLowerCase())
|
|
227
|
+
throw new Error('recovery payment operation mismatch');
|
|
228
|
+
if ((target.stage !== 'coordinator' && target.stage !== 'contributor') || execution.report.stage !== target.stage
|
|
229
|
+
|| toHex(Uint8Array.from(execution.report.operator_key)).toLowerCase() !== target.operatorKey.toLowerCase())
|
|
230
|
+
throw new Error('recovery requires the intended keeper stage');
|
|
231
|
+
const key = protocolHex(target.operatorKey, 32, 'original keeper key'), point = ed25519.Point.fromHex(key, false);
|
|
232
|
+
if (point.isSmallOrder() || !point.isTorsionFree()
|
|
233
|
+
|| !ed25519.verify(protocolHex(execution.signature, 64, 'original keeper report signature'), protocolHex(hash, 32, 'report hash'), key, { zip215: false }))
|
|
234
|
+
throw new Error('invalid original keeper report signature');
|
|
235
|
+
if (await chainIdOf(client) !== deployment.chainId)
|
|
236
|
+
throw new Error('recovery RPC chain mismatch');
|
|
237
|
+
const blockHash = toHex(Uint8Array.from(execution.report.reservation_block));
|
|
238
|
+
const block = await client.getBlock({ blockHash });
|
|
239
|
+
const accepted = execution.consent.verified_at;
|
|
240
|
+
if (block.number === null || block.hash?.toLowerCase() !== blockHash.toLowerCase() || block.timestamp < 0n
|
|
241
|
+
|| !Number.isSafeInteger(accepted) || accepted <= 0 || BigInt(accepted) - block.timestamp > MAX_AGE
|
|
242
|
+
|| block.timestamp - BigInt(accepted) > FUTURE_SKEW || BigInt(accepted) > time() + FUTURE_SKEW)
|
|
243
|
+
throw new Error('original keeper admission block or clock mismatch');
|
|
244
|
+
const at = { blockNumber: block.number, blockHash, blockTimestamp: block.timestamp };
|
|
245
|
+
const requestId = prepaidRequestId(payment);
|
|
246
|
+
const [enabled, cost, settled, refunded, assignmentBlock, directory] = await Promise.all([
|
|
247
|
+
readAt(client, deployment.settlement, at, 'prepaidEnabled', payment.slot),
|
|
248
|
+
readAt(client, deployment.settlement, at, 'prepaidCost', payment.slot, requestId),
|
|
249
|
+
readAt(client, deployment.settlement, at, 'prepaidSettled', payment.slot, requestId),
|
|
250
|
+
readAt(client, deployment.settlement, at, 'prepaidRefunded', payment.slot, requestId),
|
|
251
|
+
readAt(client, deployment.settlement, at, 'prepaidAssignmentBlock', payment.slot, requestId),
|
|
252
|
+
keeperDirectory(client, at, deployment.keyRegistry, payment.slot, BigInt(accepted)),
|
|
253
|
+
]);
|
|
254
|
+
if (enabled !== true || settled !== false || refunded !== 0n || typeof cost !== 'bigint' || cost <= 0n || cost > BigInt(payment.max_cost)
|
|
255
|
+
|| cost !== BigInt(toHex(Uint8Array.from(execution.report.cost))) || typeof assignmentBlock !== 'string'
|
|
256
|
+
|| !HEX32.test(assignmentBlock) || assignmentBlock.toLowerCase() === ZERO32)
|
|
257
|
+
throw new Error('original keeper admission has no valid reserved TASRA backing');
|
|
258
|
+
const { slot, members } = directory, assignment = payment.keeper_assignment;
|
|
259
|
+
if (slot.epoch !== BigInt(assignment.key_epoch) || slot.committeeVersion !== BigInt(assignment.committee_version)
|
|
260
|
+
|| slot.threshold.k !== assignment.threshold || (slot.expiry !== 0n && slot.expiry <= BigInt(accepted)))
|
|
261
|
+
throw new Error('original keeper sharing or slot lifetime mismatch');
|
|
262
|
+
for (const assigned of [assignment.coordinator, ...assignment.contributors]) {
|
|
263
|
+
if (!members.get(toHex(Uint8Array.from(assigned)))?.eligible)
|
|
264
|
+
throw new Error('original payment names an ineligible assigned keeper');
|
|
265
|
+
}
|
|
266
|
+
const keeper = keeperEndpoint(members, target.operatorKey.toLowerCase(), deployment.chainId, transport);
|
|
267
|
+
const policy = { chainId: deployment.chainId, settlement: deployment.settlement, keyRegistry: deployment.keyRegistry,
|
|
268
|
+
creator: slot.creator, paymentHash: paymentIntentHash(payment), cost, nowSecs: accepted };
|
|
269
|
+
await verifyPaidExecutionEvidence({ payment, policy, target, execution });
|
|
270
|
+
// Historical freshness is measured at accepted, never against today's latest head.
|
|
271
|
+
const canonical = await client.getBlock({ blockNumber: at.blockNumber });
|
|
272
|
+
if (canonical.hash?.toLowerCase() !== blockHash.toLowerCase() || canonical.timestamp !== at.blockTimestamp)
|
|
273
|
+
throw new Error('original keeper history reorganized during recovery');
|
|
274
|
+
if (BigInt(accepted) > time() + FUTURE_SKEW)
|
|
275
|
+
throw new Error('original keeper work clock is in the future');
|
|
276
|
+
return { ...at, policy, keeper, groupPublicKey: slot.publicKey, mode: slot.mode };
|
|
277
|
+
}
|
|
278
|
+
const ANCHOR_WAIT_MS = 20_000, ANCHOR_POLL_MS = 1_000;
|
|
279
|
+
function anchorWaitPolicy(wait = {}) {
|
|
280
|
+
const timeoutMs = wait.timeoutMs ?? ANCHOR_WAIT_MS, pollMs = wait.pollMs ?? ANCHOR_POLL_MS, clock = wait.clock ?? systemPacingClock;
|
|
281
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 120_000 || !Number.isSafeInteger(pollMs) || pollMs < 100 || pollMs > 10_000)
|
|
282
|
+
throw new Error('invalid anchor wait');
|
|
283
|
+
return { timeoutMs, pollMs, clock };
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* The pinned verifier epoch ({@link PaidContextOptions.verificationEpoch}) is no longer the beacon's
|
|
287
|
+
* latest or previous epoch. Nothing was signed or reserved: refresh the session grant (or present
|
|
288
|
+
* again) and discover anew.
|
|
289
|
+
*/
|
|
290
|
+
export class PaidDrawMovedError extends Error {
|
|
291
|
+
pinnedEpoch;
|
|
292
|
+
beaconEpoch;
|
|
293
|
+
/** Stable reason. */
|
|
294
|
+
code = 'draw-moved';
|
|
295
|
+
constructor(
|
|
296
|
+
/** The pinned verifier epoch. */
|
|
297
|
+
pinnedEpoch,
|
|
298
|
+
/** The beacon's latest epoch as read. */
|
|
299
|
+
beaconEpoch) {
|
|
300
|
+
super(`payment discovery: verifier epoch ${pinnedEpoch} is no longer current or previous (beacon at ${beaconEpoch})`);
|
|
301
|
+
this.pinnedEpoch = pinnedEpoch;
|
|
302
|
+
this.beaconEpoch = beaconEpoch;
|
|
303
|
+
this.name = 'PaidDrawMovedError';
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* The context's intent fields, refused for an undrawn context: the one path from a context to a
|
|
308
|
+
* payment intent. Throws rather than ever returning zero or missing draw fields.
|
|
309
|
+
*/
|
|
310
|
+
export function drawnIntentFields(context) {
|
|
311
|
+
if (context.undrawn === true || !('verification_epoch' in context.intentFields))
|
|
312
|
+
throw new Error('an undrawn payment context has no verifier draw; discover again');
|
|
313
|
+
return context.intentFields;
|
|
314
|
+
}
|
|
315
|
+
const ZERO32 = `0x${'00'.repeat(32)}`;
|
|
316
|
+
const ADDRESS = /^0x[0-9a-f]{40}$/i;
|
|
317
|
+
const HEX32 = /^0x[0-9a-f]{64}$/i;
|
|
318
|
+
const MAX_AGE = 30n;
|
|
319
|
+
const FUTURE_SKEW = 2n;
|
|
320
|
+
function validateDeployment(d) {
|
|
321
|
+
if (!Number.isSafeInteger(d.chainId) || d.chainId <= 0)
|
|
322
|
+
throw new Error('invalid prepaid chain ID');
|
|
323
|
+
for (const address of [d.settlement, d.keyRegistry]) {
|
|
324
|
+
if (!ADDRESS.test(address) || /^0x0{40}$/i.test(address))
|
|
325
|
+
throw new Error('invalid prepaid deployment address');
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function time() { return BigInt(Math.floor(Date.now() / 1000)); }
|
|
329
|
+
function requireFresh(at) {
|
|
330
|
+
const now = time();
|
|
331
|
+
if (now - at.blockTimestamp > MAX_AGE || at.blockTimestamp - now > FUTURE_SKEW) {
|
|
332
|
+
throw new Error('prepaid observation is stale or future-dated');
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
// Concurrent operations on one client share one in-flight `latest` head read. Only the pending
|
|
336
|
+
// request is shared: a head is never reused once answered, so each later observation reads again.
|
|
337
|
+
const sharedHeads = new WeakMap();
|
|
338
|
+
function latestHead(client) {
|
|
339
|
+
let shared = sharedHeads.get(client);
|
|
340
|
+
if (!shared)
|
|
341
|
+
sharedHeads.set(client, shared = new SingleFlight(1));
|
|
342
|
+
return shared.run('latest', () => client.getBlock({ blockTag: 'latest' }));
|
|
343
|
+
}
|
|
344
|
+
async function observe(client, d, atLeastBlock) {
|
|
345
|
+
validateDeployment(d);
|
|
346
|
+
// A live head follower's tip replaces the `latest` read (the same head, delivered by subscription
|
|
347
|
+
// or poll instead of asked for); a follower that is not live falls back to the RPC read. So does a
|
|
348
|
+
// tip older than a block the caller already saw mined: it cannot show that transaction's effects.
|
|
349
|
+
const tip = headFollowerOf(client)?.tip();
|
|
350
|
+
if (tip && (atLeastBlock === undefined || tip.blockNumber >= atLeastBlock)) {
|
|
351
|
+
if (await chainIdOf(client) !== d.chainId)
|
|
352
|
+
throw new Error('prepaid RPC chain mismatch');
|
|
353
|
+
const at = { blockNumber: tip.blockNumber, blockHash: tip.blockHash, blockTimestamp: tip.blockTimestamp };
|
|
354
|
+
requireFresh(at);
|
|
355
|
+
followedObservations.add(at);
|
|
356
|
+
return at;
|
|
357
|
+
}
|
|
358
|
+
// The chain check and the head read are independent; a mismatch is still refused first.
|
|
359
|
+
const [chain, head] = await Promise.allSettled([chainIdOf(client), latestHead(client)]);
|
|
360
|
+
if (chain.status === 'rejected')
|
|
361
|
+
throw chain.reason;
|
|
362
|
+
if (chain.value !== d.chainId)
|
|
363
|
+
throw new Error('prepaid RPC chain mismatch');
|
|
364
|
+
if (head.status === 'rejected')
|
|
365
|
+
throw head.reason;
|
|
366
|
+
const block = head.value;
|
|
367
|
+
if (block.number === null || block.hash === null || !HEX32.test(block.hash) || block.hash === ZERO32 || block.timestamp < 0n) {
|
|
368
|
+
throw new Error('prepaid canonical head unavailable');
|
|
369
|
+
}
|
|
370
|
+
const at = { blockNumber: block.number, blockHash: block.hash, blockTimestamp: block.timestamp };
|
|
371
|
+
requireFresh(at);
|
|
372
|
+
return at;
|
|
373
|
+
}
|
|
374
|
+
// A followed tip may be one block behind a state the caller already saw elsewhere: another client,
|
|
375
|
+
// or a transaction another code path mined (a key publish, a reshare, a reservation or allowance).
|
|
376
|
+
// A positive answer at that tip stands (the follower's tip is as fresh as a `latest` read within
|
|
377
|
+
// its liveness bound). A REFUSAL that a newer block could reverse is checked once more at a fresh
|
|
378
|
+
// `latest` read by RPC - never the follower's tip, never a shared or remembered head - before it is
|
|
379
|
+
// reported. When `latest` is the same block (or behind the tip), the refusal stands unchanged.
|
|
380
|
+
const followedObservations = new WeakSet();
|
|
381
|
+
const staleRefusals = new WeakSet();
|
|
382
|
+
/** Mark a refusal that a block newer than the observation could reverse. */
|
|
383
|
+
function reversible(error) {
|
|
384
|
+
staleRefusals.add(error);
|
|
385
|
+
return error;
|
|
386
|
+
}
|
|
387
|
+
/** As {@link observeLatest}, after the deployment and chain checks {@link observe} makes. */
|
|
388
|
+
async function observeFresh(client, d) {
|
|
389
|
+
validateDeployment(d);
|
|
390
|
+
const [chain, head] = await Promise.allSettled([chainIdOf(client), observeLatest(client)]);
|
|
391
|
+
if (chain.status === 'rejected')
|
|
392
|
+
throw chain.reason;
|
|
393
|
+
if (chain.value !== d.chainId)
|
|
394
|
+
throw new Error('prepaid RPC chain mismatch');
|
|
395
|
+
if (head.status === 'rejected')
|
|
396
|
+
throw head.reason;
|
|
397
|
+
return head.value;
|
|
398
|
+
}
|
|
399
|
+
/** A `latest` head read by RPC for this decision alone: not the followed tip, not shared with another read. */
|
|
400
|
+
async function observeLatest(client) {
|
|
401
|
+
const block = await client.getBlock({ blockTag: 'latest' });
|
|
402
|
+
if (block.number === null || block.hash === null || !HEX32.test(block.hash) || block.hash === ZERO32 || block.timestamp < 0n) {
|
|
403
|
+
throw new Error('prepaid canonical head unavailable');
|
|
404
|
+
}
|
|
405
|
+
const at = { blockNumber: block.number, blockHash: block.hash, blockTimestamp: block.timestamp };
|
|
406
|
+
requireFresh(at);
|
|
407
|
+
return at;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Decide at `at`; when `at` is a followed tip and the decision is a reversible refusal, decide once
|
|
411
|
+
* more at a fresh `latest` that is newer than the tip. Any other outcome is returned or thrown as is.
|
|
412
|
+
*/
|
|
413
|
+
async function decideAtFreshHead(client, at, decide) {
|
|
414
|
+
try {
|
|
415
|
+
return await decide(at);
|
|
416
|
+
}
|
|
417
|
+
catch (error) {
|
|
418
|
+
if (!followedObservations.has(at) || typeof error !== 'object' || error === null || !staleRefusals.has(error))
|
|
419
|
+
throw error;
|
|
420
|
+
const latest = await observeLatest(client);
|
|
421
|
+
if (latest.blockNumber <= at.blockNumber)
|
|
422
|
+
throw error;
|
|
423
|
+
// Later observations read the RPC head until the follower reaches this block (never this head itself).
|
|
424
|
+
headFollowerOf(client)?.noteMinedBlock(latest.blockNumber);
|
|
425
|
+
return decide(latest);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
async function readAt(client, settlement, at, name, slot, requestId) {
|
|
429
|
+
const data = requestId === undefined
|
|
430
|
+
? encodeFunctionData({ abi: settlementAbi, functionName: name, args: [slot] })
|
|
431
|
+
: encodeFunctionData({ abi: settlementAbi, functionName: name, args: [slot, requestId] });
|
|
432
|
+
// Same canonical block-hash read, batched with the other reads at this block where possible. Never
|
|
433
|
+
// shared with another operation's read, except at a block the head follower vouches for, whose
|
|
434
|
+
// pinned answers (and pre-reads) are fixed facts served from the block-hash cache.
|
|
435
|
+
const result = { data: headFollowerOf(client)?.isCanonical(at) === true
|
|
436
|
+
? await pinnedRegistryCall(client, at, settlement, data, false) : await pinnedCall(client, at.blockHash, settlement, data) };
|
|
437
|
+
if (result.data === undefined)
|
|
438
|
+
throw new Error(`empty prepaid ${name} response`);
|
|
439
|
+
return decodeFunctionResult({ abi: settlementAbi, functionName: name, data: result.data });
|
|
440
|
+
}
|
|
441
|
+
async function legacyVersionAt(client, settlement, at) {
|
|
442
|
+
try {
|
|
443
|
+
const data = encodeFunctionData({ abi: settlementAbi, functionName: 'version' });
|
|
444
|
+
const result = await client.call({ to: settlement, data, blockHash: at.blockHash, requireCanonical: true, batch: false });
|
|
445
|
+
return result.data !== undefined && decodeFunctionResult({ abi: settlementAbi, functionName: 'version', data: result.data }) === '1';
|
|
446
|
+
}
|
|
447
|
+
catch {
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/** Refuse a paid operation on a slot that is not prepaid, naming the detected billing. */
|
|
452
|
+
async function refuseUnlessPrepaid(client, deployment, slot) {
|
|
453
|
+
const observed = await readBillingMode(client, deployment, slot);
|
|
454
|
+
if (observed.mode !== 'prepaid')
|
|
455
|
+
throw new BillingModeError({ ...observed, mode: observed.mode });
|
|
456
|
+
}
|
|
457
|
+
async function finishObservation(client, at) {
|
|
458
|
+
// Recheck canonicality after all calls as well as requiring it on each individual call.
|
|
459
|
+
// Never fall back to latest or a block number when EIP-1898 is unsupported. A head follower that
|
|
460
|
+
// proves `at` canonical (instant finality, live, gap-free, same hash) answers the recheck; any
|
|
461
|
+
// other answer (a gap, not live, another hash, probabilistic finality) keeps the RPC recheck.
|
|
462
|
+
if (headFollowerOf(client)?.isCanonical(at) === true) {
|
|
463
|
+
requireFresh(at);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const current = await client.getBlock({ blockNumber: at.blockNumber });
|
|
467
|
+
if (current.hash?.toLowerCase() !== at.blockHash.toLowerCase())
|
|
468
|
+
throw new Error('prepaid observation reorganized during reads');
|
|
469
|
+
requireFresh(at);
|
|
470
|
+
}
|
|
471
|
+
// Concurrent operations on one client often read the same registry value at the same block
|
|
472
|
+
// (the keeper directory above all). A read pinned to a block hash has one answer: identical
|
|
473
|
+
// in-flight reads share one request, and a result at a block the client has confirmed finalized
|
|
474
|
+
// is kept briefly (bounded) for later operations at that block. Errors are never reused, and
|
|
475
|
+
// `latest` reads, reservation reads and rechecks never come here (see pinnedReads.ts).
|
|
476
|
+
// Observations of a fresh `latest` head made for a paid keeper operation. Only their registry
|
|
477
|
+
// reads use the finalized-block cache; historical and discovery reads never do.
|
|
478
|
+
const operationHeads = new WeakSet();
|
|
479
|
+
async function registryRead(client, at, address, abi, name, args = []) {
|
|
480
|
+
const data = encodeFunctionData({ abi, functionName: name, args });
|
|
481
|
+
const result = { data: await pinnedRegistryCall(client, at, address, data, operationHeads.has(at)) };
|
|
482
|
+
if (result.data === undefined)
|
|
483
|
+
throw new Error(`empty registry ${name} response`);
|
|
484
|
+
return decodeFunctionResult({ abi, functionName: name, data: result.data });
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* The beacon's current epoch at a fresh observed head (the followed tip when live, else `latest`),
|
|
488
|
+
* through the same block-pinned read discovery uses. Performs no transaction.
|
|
489
|
+
* @param client - Trusted bounded Viem RPC client for the selected deployment.
|
|
490
|
+
* @param deployment - Independently approved chain and contract addresses, the beacon included.
|
|
491
|
+
* @param options - `fresh`: read at an RPC `latest` head of its own, never a followed tip. For a
|
|
492
|
+
* decision a tip lagging the chain would get wrong (confirming that a grant left the window: a
|
|
493
|
+
* keeper judged it at a newer head; C21, two beacon pushes in a second).
|
|
494
|
+
*/
|
|
495
|
+
export async function readCurrentBeaconEpoch(client, deployment, options = {}) {
|
|
496
|
+
const at = options.fresh ? await observeFresh(client, deployment) : await observe(client, deployment);
|
|
497
|
+
const epoch = await registryRead(client, at, deployment.beacon, thresholdRandomBeaconAbi, 'epoch');
|
|
498
|
+
if (typeof epoch !== 'bigint')
|
|
499
|
+
throw new Error('invalid beacon epoch');
|
|
500
|
+
return epoch;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* The beacon's latest epoch and its draw epoch ({@link BeaconDrawState}) at ONE fresh observed head
|
|
504
|
+
* (the followed tip when live, else `latest`), through the block-pinned reads discovery uses. The
|
|
505
|
+
* previous epoch's snapshot is read only while the latest one is not anchored. Performs no transaction.
|
|
506
|
+
* @param client - Trusted bounded Viem RPC client for the selected deployment.
|
|
507
|
+
* @param deployment - Independently approved chain and contract addresses, the beacon and verifier set included.
|
|
508
|
+
*/
|
|
509
|
+
export async function readBeaconDrawState(client, deployment) {
|
|
510
|
+
deployment = { ...deployment };
|
|
511
|
+
const at = await observe(client, deployment);
|
|
512
|
+
const latest = await registryRead(client, at, deployment.beacon, thresholdRandomBeaconAbi, 'epoch');
|
|
513
|
+
if (typeof latest !== 'bigint' || latest < 0n)
|
|
514
|
+
throw new Error('invalid beacon epoch');
|
|
515
|
+
const anchored = async (epoch) => {
|
|
516
|
+
const [root, size] = await registryRead(client, at, deployment.verifierSet, verifierSetRegistryAbi, 'snapshotAt', [epoch]);
|
|
517
|
+
return typeof root === 'string' && HEX32.test(root) && root.toLowerCase() !== ZERO32 && size > 0;
|
|
518
|
+
};
|
|
519
|
+
if (await anchored(latest))
|
|
520
|
+
return { latest, draw: latest };
|
|
521
|
+
if (latest > 0n && await anchored(latest - 1n))
|
|
522
|
+
return { latest, draw: latest - 1n };
|
|
523
|
+
return { latest };
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Read available, reserved and total slot TASRA at one fresh canonical block. Performs no transaction.
|
|
527
|
+
* @param client - Trusted bounded Viem RPC client for the selected deployment.
|
|
528
|
+
* @param deployment - Independently approved chain and contract addresses.
|
|
529
|
+
* @param slot - Slot whose TASRA balances are required.
|
|
530
|
+
*/
|
|
531
|
+
export async function readSlotFunding(client, deployment, slot) {
|
|
532
|
+
deployment = { ...deployment };
|
|
533
|
+
if (!HEX32.test(slot))
|
|
534
|
+
throw new Error('invalid funding slot');
|
|
535
|
+
const at = await observe(client, deployment);
|
|
536
|
+
let enabled, available, reserved;
|
|
537
|
+
try {
|
|
538
|
+
;
|
|
539
|
+
[enabled, available, reserved] = await Promise.all([
|
|
540
|
+
readAt(client, deployment.settlement, at, 'prepaidEnabled', slot),
|
|
541
|
+
readAt(client, deployment.settlement, at, 'balanceOf', slot),
|
|
542
|
+
readAt(client, deployment.settlement, at, 'reservedBalanceOf', slot),
|
|
543
|
+
]);
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
// A legacy (version 1) Settlement has no prepaid getters. Report its balance only when the
|
|
547
|
+
// same block positively reads version "1"; any other failure stays a failure.
|
|
548
|
+
if (await legacyVersionAt(client, deployment.settlement, at) !== true)
|
|
549
|
+
throw error;
|
|
550
|
+
const balance = await readAt(client, deployment.settlement, at, 'balanceOf', slot);
|
|
551
|
+
if (typeof balance !== 'bigint')
|
|
552
|
+
throw new Error('invalid slot funding response', { cause: error });
|
|
553
|
+
await finishObservation(client, at);
|
|
554
|
+
return { ...at, slot, enabled: false, available: balance, reserved: 0n, total: balance, settlementVersion: '1' };
|
|
555
|
+
}
|
|
556
|
+
if (typeof enabled !== 'boolean' || typeof available !== 'bigint' || typeof reserved !== 'bigint')
|
|
557
|
+
throw new Error('invalid slot funding response');
|
|
558
|
+
await finishObservation(client, at);
|
|
559
|
+
return { ...at, slot, enabled, available, reserved, total: available + reserved };
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Require mined backing for an independently selected operation, without spending or performing it.
|
|
563
|
+
* A completed reservation remains inspectable. This result never authorizes another execution;
|
|
564
|
+
* the keeper must independently verify the holder, current assignment and durable operation journal.
|
|
565
|
+
* @param client - Trusted bounded Viem RPC client for the selected deployment.
|
|
566
|
+
* @param deployment - Independently approved chain and contract addresses.
|
|
567
|
+
* @param payment - Fixed creator-signed intent for the existing reservation.
|
|
568
|
+
* @param expected - Slot, action and digest derived from the operation the application intends.
|
|
569
|
+
* @param options - `atLeastBlock`: a block the caller saw its own transaction mined in; an older
|
|
570
|
+
* followed tip is not used (it cannot show that transaction), the RPC head is read instead.
|
|
571
|
+
*/
|
|
572
|
+
export async function readPaidOperationReceipt(client, deployment, payment, expected, options = {}) {
|
|
573
|
+
deployment = { ...deployment };
|
|
574
|
+
payment = structuredClone(payment);
|
|
575
|
+
expected = { ...expected };
|
|
576
|
+
requirePaidOperation(deployment, payment, expected);
|
|
577
|
+
return decideAtFreshHead(client, await observe(client, deployment, options.atLeastBlock), async (at) => {
|
|
578
|
+
const receipt = checkReceiptReads(at, payment, await receiptReads(client, deployment, at, payment));
|
|
579
|
+
await finishObservation(client, at);
|
|
580
|
+
return receipt;
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
/** Refuse an intent for another deployment or operation before any read. */
|
|
584
|
+
function requirePaidOperation(deployment, payment, expected) {
|
|
585
|
+
validateDeployment(deployment);
|
|
586
|
+
assertPaymentIntentWire(payment);
|
|
587
|
+
if (payment.chain_id !== deployment.chainId || payment.settlement.toLowerCase() !== deployment.settlement.toLowerCase()
|
|
588
|
+
|| payment.key_registry.toLowerCase() !== deployment.keyRegistry.toLowerCase())
|
|
589
|
+
throw new Error('payment deployment mismatch');
|
|
590
|
+
if (payment.slot.toLowerCase() !== expected.slot.toLowerCase() || payment.action !== expected.action
|
|
591
|
+
|| payment.payload_digest.toLowerCase() !== expected.payloadDigest.toLowerCase())
|
|
592
|
+
throw new Error('payment operation mismatch');
|
|
593
|
+
}
|
|
594
|
+
function receiptReads(client, deployment, at, payment) {
|
|
595
|
+
const requestId = prepaidRequestId(payment);
|
|
596
|
+
if (payment.allowance_id !== undefined) {
|
|
597
|
+
const voucher = payment.debit_voucher;
|
|
598
|
+
if (!voucher)
|
|
599
|
+
return Promise.reject(new Error('allowance-backed payment carries no debit voucher'));
|
|
600
|
+
const allowance = allowanceRead(client, deployment.settlement, at, 'prepaidAllowance', payment.allowance_id);
|
|
601
|
+
const version = settlementVersionAt(client, at, deployment.settlement);
|
|
602
|
+
// ADR-0092 (Settlement "5"): a range-settled allowance advances its settled seq and writes no
|
|
603
|
+
// per-request records, so the request's own `prepaidSettled` stays false. The settled seq is
|
|
604
|
+
// read at the same block, and consulted only when the version read there is "5" (an older
|
|
605
|
+
// version has no getter: the read reverts, is never cached, and cost one more round each time).
|
|
606
|
+
const settledSeq = settledSeqAt(client, deployment.settlement, at, payment.allowance_id, version);
|
|
607
|
+
return Promise.all([readAt(client, deployment.settlement, at, 'prepaidEnabled', payment.slot), allowance,
|
|
608
|
+
readAt(client, deployment.settlement, at, 'prepaidCost', payment.slot, requestId), readAt(client, deployment.settlement, at, 'prepaidSettled', payment.slot, requestId),
|
|
609
|
+
readAt(client, deployment.settlement, at, 'prepaidRefunded', payment.slot, requestId), verifyDebitVoucher(client, deployment, voucher),
|
|
610
|
+
version, settledSeq]).then(reads => ({ kind: 'allowance', reads }));
|
|
611
|
+
}
|
|
612
|
+
const names = ['prepaidEnabled', 'prepaidCost', 'prepaidSettled', 'prepaidRefunded', 'prepaidAssignmentBlock'];
|
|
613
|
+
return Promise.all(names.map(name => readAt(client, deployment.settlement, at, name, payment.slot, name === 'prepaidEnabled' ? undefined : requestId))).then(reads => ({ kind: 'reservation', reads }));
|
|
614
|
+
}
|
|
615
|
+
/** A settled-seq read that was not made: the version at the same block is not "5", so it is never consulted. */
|
|
616
|
+
const SETTLED_SEQ_NOT_READ = Object.freeze({ error: new Error('settled seq not read: Settlement version is not "5"') });
|
|
617
|
+
/**
|
|
618
|
+
* The allowance's settled seq at `at`, as `{value}` or `{error}`, for a decision that consults it
|
|
619
|
+
* only when `version` (read at the same block) is "5". Scheduling only, never an answer: while the
|
|
620
|
+
* last version this client read from `settlement` was "5" (or none was read yet) the getter is read
|
|
621
|
+
* beside `version`, in the same round; otherwise it is read after `version`, and only when that
|
|
622
|
+
* version is "5" (an upgrade the hint missed costs one more round, once).
|
|
623
|
+
*/
|
|
624
|
+
function settledSeqAt(client, settlement, at, allowanceId, version) {
|
|
625
|
+
const read = () => allowanceRead(client, settlement, at, 'prepaidAllowanceSettledSeq', allowanceId).then(value => ({ value }), (error) => ({ error }));
|
|
626
|
+
const hint = settlementVersionHint(client, settlement);
|
|
627
|
+
if (hint === undefined || hint === '5')
|
|
628
|
+
return read();
|
|
629
|
+
return version.then(v => v === '5' ? read() : SETTLED_SEQ_NOT_READ, () => SETTLED_SEQ_NOT_READ);
|
|
630
|
+
}
|
|
631
|
+
/** One allowance-keyed Settlement read at `at` (block-hash cached only where the head follower vouches). */
|
|
632
|
+
function allowanceRead(client, settlement, at, name, allowanceId) {
|
|
633
|
+
const data = encodeFunctionData({ abi: settlementAbi, functionName: name, args: [allowanceId] });
|
|
634
|
+
return (headFollowerOf(client)?.isCanonical(at) === true
|
|
635
|
+
? pinnedRegistryCall(client, at, settlement, data, false) : pinnedCall(client, at.blockHash, settlement, data))
|
|
636
|
+
.then(result => { if (result === undefined)
|
|
637
|
+
throw new Error(`empty ${name} response`); return decodeFunctionResult({ abi: settlementAbi, functionName: name, data: result }); });
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Pre-read one in-flight paid operation's own settlement state (its request's cost, settlement,
|
|
641
|
+
* refund and assignment block; for an allowance-backed one also the allowance record) at every
|
|
642
|
+
* new followed head until the payment expires, so the receipt, client policy and keeper target
|
|
643
|
+
* checks at that head find it cached. Without a head follower this does nothing.
|
|
644
|
+
* @param client Trusted client with a head follower attached.
|
|
645
|
+
* @param deployment Approved deployment.
|
|
646
|
+
* @param payment The operation's creator-signed intent.
|
|
647
|
+
*/
|
|
648
|
+
export function followPaidRequest(client, deployment, payment) {
|
|
649
|
+
if (!headFollowerOf(client))
|
|
650
|
+
return;
|
|
651
|
+
const d = { ...deployment }, slot = payment.slot, requestId = prepaidRequestId(payment), allowanceId = payment.allowance_id;
|
|
652
|
+
const epoch = BigInt(payment.verification_epoch);
|
|
653
|
+
registerHeadPrefetch(client, `paid-request:${d.settlement}:${requestId}`.toLowerCase(), tip => {
|
|
654
|
+
const at = { blockNumber: tip.blockNumber, blockHash: tip.blockHash, blockTimestamp: tip.blockTimestamp };
|
|
655
|
+
const names = ['prepaidCost', 'prepaidSettled', 'prepaidRefunded', 'prepaidAssignmentBlock'];
|
|
656
|
+
const version = allowanceId ? settlementVersionAt(client, at, d.settlement) : undefined;
|
|
657
|
+
version?.catch(() => { });
|
|
658
|
+
return Promise.allSettled([readAt(client, d.settlement, at, 'prepaidEnabled', slot), ...names.map(name => readAt(client, d.settlement, at, name, slot, requestId)),
|
|
659
|
+
...(allowanceId && version ? [allowanceRead(client, d.settlement, at, 'prepaidAllowance', allowanceId), version,
|
|
660
|
+
settledSeqAt(client, d.settlement, at, allowanceId, version)] : []),
|
|
661
|
+
// The client execution policy's reads at the payment's own draw epoch (an allowance's draw is
|
|
662
|
+
// older than the slot pre-read's latest/previous epochs): its seed and verifier snapshot.
|
|
663
|
+
...(d.beacon && d.verifierSet ? [registryRead(client, at, d.beacon, thresholdRandomBeaconAbi, 'seedAt', [epoch]),
|
|
664
|
+
registryRead(client, at, d.verifierSet, verifierSetRegistryAbi, 'snapshotAt', [epoch])] : [])]);
|
|
665
|
+
}, payment.expires * 1000);
|
|
666
|
+
}
|
|
667
|
+
function checkReceiptReads(at, payment, observed) {
|
|
668
|
+
if (observed.kind === 'allowance')
|
|
669
|
+
return checkAllowanceBacking(at, payment, observed.reads);
|
|
670
|
+
const [enabled, cost, settled, refunded, assignmentBlock] = observed.reads;
|
|
671
|
+
if (enabled !== true || typeof cost !== 'bigint' || cost <= 0n || cost > BigInt(payment.max_cost)
|
|
672
|
+
|| typeof settled !== 'boolean' || typeof refunded !== 'bigint' || refunded < 0n || refunded > cost
|
|
673
|
+
|| (!settled && refunded !== 0n) || typeof assignmentBlock !== 'string' || !HEX32.test(assignmentBlock) || assignmentBlock === ZERO32) {
|
|
674
|
+
throw reversible(new Error('operation has no valid reserved TASRA fee'));
|
|
675
|
+
}
|
|
676
|
+
return { ...at, requestId: prepaidRequestId(payment), cost, settled, refunded, assignmentBlock: assignmentBlock };
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Allowance backing, from the client side: the allowance is mined and canonical at `at`, for this slot,
|
|
680
|
+
* open, unexpired and funding the action; the (already signature-verified) voucher debits THIS
|
|
681
|
+
* request within the per-operation cap and the escrow; the request is not per-operation reserved
|
|
682
|
+
* (`prepaidCost` is 0 until the allowance settle writes the voucher's cost). The voucher's cost and
|
|
683
|
+
* the allowance's immutable assignment block stand in for a reservation's.
|
|
684
|
+
*/
|
|
685
|
+
function checkAllowanceBacking(at, payment, reads) {
|
|
686
|
+
const [enabled, record, reservedCost, perRequestSettled, refunded, , version, settledSeqRead] = reads;
|
|
687
|
+
// The backing is judged per Settlement version at this block: "5" adds range settlement (ADR-0092),
|
|
688
|
+
// under which a voucher at or below the allowance's settled seq is settled even though its
|
|
689
|
+
// per-request records were never written. Any other version is refused here.
|
|
690
|
+
if (!isPrepaidSettlementVersion(version))
|
|
691
|
+
throw new Error('operation backing read at an unknown Settlement version');
|
|
692
|
+
let settled = perRequestSettled;
|
|
693
|
+
if (version === '5') {
|
|
694
|
+
if ('error' in settledSeqRead)
|
|
695
|
+
throw settledSeqRead.error;
|
|
696
|
+
const settledSeq = settledSeqRead.value;
|
|
697
|
+
if (typeof settledSeq !== 'bigint' || typeof perRequestSettled !== 'boolean')
|
|
698
|
+
throw new Error('operation has no valid allowance-backed TASRA debit');
|
|
699
|
+
settled = perRequestSettled || BigInt(payment.debit_voucher.seq) <= settledSeq;
|
|
700
|
+
}
|
|
701
|
+
const voucher = payment.debit_voucher;
|
|
702
|
+
const [slotId, assignmentBlock, amount, , maxOpCost, expiresAt, , actions, closed] = record;
|
|
703
|
+
const cost = BigInt(voucher.cost);
|
|
704
|
+
const bit = { 'sign': 0, 'decrypt': 1, 'eoa-sign': 2, 'ibe-extract': 3, 'dual-approve': 6 }[payment.action];
|
|
705
|
+
if (enabled !== true || !HEX32.test(assignmentBlock) || assignmentBlock.toLowerCase() === ZERO32 || amount === 0n || slotId.toLowerCase() !== payment.slot.toLowerCase()
|
|
706
|
+
|| closed || at.blockTimestamp >= expiresAt || (actions & (1 << bit)) === 0 || cost > maxOpCost || cost > BigInt(payment.max_cost) || BigInt(voucher.cumulative) > amount
|
|
707
|
+
|| typeof reservedCost !== 'bigint' || (reservedCost !== 0n && reservedCost !== cost) || typeof settled !== 'boolean' || typeof refunded !== 'bigint'
|
|
708
|
+
|| refunded < 0n || refunded > cost || (!settled && (refunded !== 0n || reservedCost !== 0n))) {
|
|
709
|
+
throw reversible(new Error('operation has no valid allowance-backed TASRA debit'));
|
|
710
|
+
}
|
|
711
|
+
return { ...at, requestId: prepaidRequestId(payment), cost, settled: settled, refunded, assignmentBlock };
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Resolve only the signed coordinator after checking mined backing, creator consent and current sharing.
|
|
715
|
+
* Does not contact any keeper, submit a transaction, mint a credential grant or execute work.
|
|
716
|
+
* @param client - Trusted bounded Viem RPC client for the selected deployment.
|
|
717
|
+
* @param deployment - Independently approved chain and contract addresses.
|
|
718
|
+
* @param payment - Creator-signed intent for the existing reservation.
|
|
719
|
+
* @param expected - Independently derived slot, action and exact payload digest.
|
|
720
|
+
* @param transport - Explicit local HTTP allowance; defaults to HTTPS only.
|
|
721
|
+
*/
|
|
722
|
+
export async function resolvePaidKeeperTarget(client, deployment, payment, expected, transport = {}) {
|
|
723
|
+
deployment = { ...deployment };
|
|
724
|
+
payment = structuredClone(payment);
|
|
725
|
+
expected = { ...expected };
|
|
726
|
+
transport = { ...transport };
|
|
727
|
+
requirePaidOperation(deployment, payment, expected);
|
|
728
|
+
return decideAtFreshHead(client, await observe(client, deployment), async (at) => {
|
|
729
|
+
operationHeads.add(at);
|
|
730
|
+
// The reservation and the keeper directory are independent reads at the same block: issue them
|
|
731
|
+
// together, then judge them in the order a sequential read would have (same refusals, same order).
|
|
732
|
+
const [reads, directory] = await Promise.allSettled([receiptReads(client, deployment, at, payment),
|
|
733
|
+
keeperDirectory(client, at, deployment.keyRegistry, payment.slot)]);
|
|
734
|
+
if (reads.status === 'rejected')
|
|
735
|
+
throw reads.reason;
|
|
736
|
+
const receipt = checkReceiptReads(at, payment, reads.value);
|
|
737
|
+
// One canonicality and freshness recheck after ALL reads at `at` (both groups have settled).
|
|
738
|
+
await finishObservation(client, at);
|
|
739
|
+
if (receipt.settled)
|
|
740
|
+
throw new Error('payment already settled; it cannot start another keeper operation');
|
|
741
|
+
if (BigInt(payment.expires) <= time())
|
|
742
|
+
throw new Error('payment expired; reconcile before starting another operation');
|
|
743
|
+
if (directory.status === 'rejected')
|
|
744
|
+
throw directory.reason;
|
|
745
|
+
const { slot, members } = directory.value;
|
|
746
|
+
const assignment = payment.keeper_assignment;
|
|
747
|
+
if (slot.epoch !== BigInt(assignment.key_epoch) || slot.committeeVersion !== BigInt(assignment.committee_version) || slot.threshold.k !== assignment.threshold)
|
|
748
|
+
throw reversible(new Error('payment keeper sharing or threshold changed'));
|
|
749
|
+
const creator = await recoverTypedDataAddress({ ...paymentIntentTypedData(payment), signature: payment.signature });
|
|
750
|
+
if (creator.toLowerCase() !== slot.creator.toLowerCase())
|
|
751
|
+
throw reversible(new Error('payment is not signed by the slot creator'));
|
|
752
|
+
const endpoint = (key) => keeperEndpoint(members, key, deployment.chainId, transport);
|
|
753
|
+
const contributors = assignment.contributors.map(key => endpoint(toHex(Uint8Array.from(key))));
|
|
754
|
+
const coordinator = endpoint(toHex(Uint8Array.from(assignment.coordinator)));
|
|
755
|
+
if (BigInt(payment.expires) <= time())
|
|
756
|
+
throw new Error('payment expired during coordinator discovery');
|
|
757
|
+
return { ...coordinator, receipt, contributors, groupPublicKey: slot.publicKey, mode: slot.mode };
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
async function keeperDirectory(client, at, registry, slotId, acceptedTime = at.blockTimestamp) {
|
|
761
|
+
const [slot, assigned, nodes] = await Promise.all([
|
|
762
|
+
registryRead(client, at, registry, keyRegistryAbi, 'getKeySlot', [slotId]),
|
|
763
|
+
registryRead(client, at, registry, keyRegistryAbi, 'assignedNodes', [slotId]),
|
|
764
|
+
registryRead(client, at, registry, keyRegistryAbi, 'nodeRegistry'),
|
|
765
|
+
]);
|
|
766
|
+
if (!slot.exists || slot.cancelled || (slot.expiry !== 0n && slot.expiry <= acceptedTime) || slot.publicKey === '0x')
|
|
767
|
+
throw reversible(new Error('paid slot is inactive or has no published key'));
|
|
768
|
+
if (!ADDRESS.test(nodes) || /^0x0{40}$/i.test(nodes) || assigned.length === 0 || assigned.length > 256
|
|
769
|
+
|| assigned.length !== slot.threshold.n || slot.threshold.k === 0 || slot.threshold.k > slot.threshold.n
|
|
770
|
+
|| new Set(assigned.map(a => a.toLowerCase())).size !== assigned.length || assigned.some(a => /^0x0{40}$/i.test(a)))
|
|
771
|
+
throw new Error('invalid assigned keeper roster');
|
|
772
|
+
const members = new Map();
|
|
773
|
+
const ids = new Set();
|
|
774
|
+
// Bound RPC fanout even on maximum-size slots. Do not silently drop unreadable members.
|
|
775
|
+
for (let offset = 0; offset < assigned.length; offset += 8) {
|
|
776
|
+
const batch = await Promise.all(assigned.slice(offset, offset + 8).map(async (operator) => {
|
|
777
|
+
const [node, id, tagged] = await Promise.all([
|
|
778
|
+
registryRead(client, at, nodes, nodeRegistryAbi, 'nodeOf', [operator]),
|
|
779
|
+
registryRead(client, at, nodes, nodeRegistryAbi, 'operatorIdOf', [operator]),
|
|
780
|
+
registryRead(client, at, nodes, nodeRegistryAbi, 'hasTag', [operator, keccak256(toHex('keykeeper'))]),
|
|
781
|
+
]);
|
|
782
|
+
if (node.operator.toLowerCase() !== operator.toLowerCase() || !HEX32.test(node.pubkey) || node.pubkey === ZERO32 || id <= 0n || id >= 1n << 64n)
|
|
783
|
+
throw new Error('invalid registered keeper identity');
|
|
784
|
+
ed25519.ExtendedPoint.fromHex(hexToBytes(node.pubkey));
|
|
785
|
+
return { key: node.pubkey.toLowerCase(), id, operator, url: node.url, eligible: node.active && tagged };
|
|
786
|
+
}));
|
|
787
|
+
for (const member of batch) {
|
|
788
|
+
if (ids.has(member.id) || members.has(member.key))
|
|
789
|
+
throw new Error('ambiguous registered keeper identity');
|
|
790
|
+
ids.add(member.id);
|
|
791
|
+
members.set(member.key, member);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return { slot, members };
|
|
795
|
+
}
|
|
796
|
+
function keeperEndpoint(members, key, chainId, transport) {
|
|
797
|
+
const member = members.get(key);
|
|
798
|
+
if (!member?.eligible)
|
|
799
|
+
throw reversible(new Error('paid contributor is not an eligible assigned keeper'));
|
|
800
|
+
const url = new URL(member.url);
|
|
801
|
+
if (url.username || url.password || url.search || url.hash
|
|
802
|
+
|| (url.protocol !== 'https:' && !(transport.allowLocalHttp === true && chainId === 43112 && url.protocol === 'http:')))
|
|
803
|
+
throw new Error('invalid paid keeper URL or transport');
|
|
804
|
+
return { operator: member.operator, publicKey: key, url: url.toString().replace(/\/$/, '') };
|
|
805
|
+
}
|
|
806
|
+
function safeInteger(value, name) {
|
|
807
|
+
if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER))
|
|
808
|
+
throw new Error(`${name} exceeds the JSON integer range`);
|
|
809
|
+
return Number(value);
|
|
810
|
+
}
|
|
811
|
+
function settlementVersionAt(client, at, settlement) {
|
|
812
|
+
return pinnedRegistryCall(client, at, settlement, encodeFunctionData({ abi: settlementAbi, functionName: 'version' }), false)
|
|
813
|
+
.then(data => {
|
|
814
|
+
if (data === undefined)
|
|
815
|
+
throw new Error('empty Settlement version response');
|
|
816
|
+
const version = decodeFunctionResult({ abi: settlementAbi, functionName: 'version', data });
|
|
817
|
+
if (typeof version === 'string')
|
|
818
|
+
rememberSettlementVersion(client, settlement, version);
|
|
819
|
+
return version;
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
// The Settlement version each settlement answered this client last: a HINT that only decides
|
|
823
|
+
// whether a version-dependent read is issued beside the version read or after it, never an answer
|
|
824
|
+
// (every decision judges the version read at its own block). Bounded per client.
|
|
825
|
+
const MAX_SETTLEMENT_VERSION_HINTS = 64;
|
|
826
|
+
const settlementVersionHints = new WeakMap();
|
|
827
|
+
function settlementVersionHint(client, settlement) {
|
|
828
|
+
return settlementVersionHints.get(client)?.get(settlement.toLowerCase());
|
|
829
|
+
}
|
|
830
|
+
function rememberSettlementVersion(client, settlement, version) {
|
|
831
|
+
let hints = settlementVersionHints.get(client);
|
|
832
|
+
if (!hints)
|
|
833
|
+
settlementVersionHints.set(client, hints = new Map());
|
|
834
|
+
const key = settlement.toLowerCase();
|
|
835
|
+
if (hints.get(key) === version)
|
|
836
|
+
return;
|
|
837
|
+
hints.delete(key);
|
|
838
|
+
if (hints.size >= MAX_SETTLEMENT_VERSION_HINTS)
|
|
839
|
+
hints.delete(hints.keys().next().value);
|
|
840
|
+
hints.set(key, version);
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Every block-pinned read discovery makes for `slotId` at `at` (also the head follower's pre-read).
|
|
844
|
+
* The latest epoch's anchors depend only on that epoch, not on the keeper directory: they are read
|
|
845
|
+
* beside its second step. Callers judge the answers in the original order.
|
|
846
|
+
*/
|
|
847
|
+
function slotReads(client, deployment, slotId, at) {
|
|
848
|
+
const seedAt = (epoch) => registryRead(client, at, deployment.beacon, thresholdRandomBeaconAbi, 'seedAt', [epoch]);
|
|
849
|
+
const snapshotAt = (epoch) => registryRead(client, at, deployment.verifierSet, verifierSetRegistryAbi, 'snapshotAt', [epoch]);
|
|
850
|
+
const accountantAt = (epoch) => registryRead(client, at, deployment.accountantSet, accountantSetRegistryAbi, 'snapshotAt', [epoch]);
|
|
851
|
+
const latestEpoch = registryRead(client, at, deployment.beacon, thresholdRandomBeaconAbi, 'epoch');
|
|
852
|
+
const latestAnchors = latestEpoch.then(epoch => Promise.all([seedAt(epoch), snapshotAt(epoch), accountantAt(epoch)]));
|
|
853
|
+
latestAnchors.catch(() => { });
|
|
854
|
+
const reads = Promise.all([
|
|
855
|
+
registryRead(client, at, deployment.keyRegistry, keyRegistryAbi, 'randomBeacon'),
|
|
856
|
+
registryRead(client, at, deployment.verifierSet, verifierSetRegistryAbi, 'beacon'),
|
|
857
|
+
registryRead(client, at, deployment.accountantSet, accountantSetRegistryAbi, 'beacon'),
|
|
858
|
+
latestEpoch,
|
|
859
|
+
registryRead(client, at, deployment.keyRegistry, keyRegistryAbi, 'verifierPolicy', [slotId]),
|
|
860
|
+
readAt(client, deployment.settlement, at, 'prepaidEnabled', slotId),
|
|
861
|
+
readAt(client, deployment.settlement, at, 'balanceOf', slotId),
|
|
862
|
+
keeperDirectory(client, at, deployment.keyRegistry, slotId),
|
|
863
|
+
// The billing check (what requirePrepaidSlot read in its own rounds before discovery): the
|
|
864
|
+
// Settlement version at this same block. Only "2" | "3" | "4" bill prepaid.
|
|
865
|
+
settlementVersionAt(client, at, deployment.settlement),
|
|
866
|
+
]);
|
|
867
|
+
return { seedAt, snapshotAt, accountantAt, latestEpoch, latestAnchors, reads };
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Pre-read `slotId`'s discovery state at every new followed head (the current and previous
|
|
871
|
+
* epoch's anchors and the accountant group key included), so an operation at that head reads it from the cache. Errors are
|
|
872
|
+
* dropped: the operation's own read surfaces them.
|
|
873
|
+
*/
|
|
874
|
+
function followPaidSlot(client, deployment, slotId) {
|
|
875
|
+
const d = { ...deployment };
|
|
876
|
+
registerHeadPrefetch(client, `paid-slot:${d.settlement}:${slotId}`.toLowerCase(), async (tip) => {
|
|
877
|
+
const at = { blockNumber: tip.blockNumber, blockHash: tip.blockHash, blockTimestamp: tip.blockTimestamp };
|
|
878
|
+
const { seedAt, snapshotAt, accountantAt, latestEpoch, latestAnchors, reads } = slotReads(client, d, slotId, at);
|
|
879
|
+
// The accountant group key at this head: an allowance debit quoted here verifies its voucher against it.
|
|
880
|
+
const current = Promise.allSettled([reads, latestAnchors, readAccountantGroupKey(client, d, at.blockHash)]);
|
|
881
|
+
const epoch = await latestEpoch.catch(() => undefined);
|
|
882
|
+
await Promise.allSettled([current, ...(epoch ? [seedAt(epoch - 1n), snapshotAt(epoch - 1n), accountantAt(epoch - 1n)] : [])]);
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
export async function discoverPaidOperationContext(client, deployment, slotId, options = {}) {
|
|
886
|
+
// The injected clock is a live object; everything else is pinned by value before any read.
|
|
887
|
+
const { anchorWait, ...pinned } = options;
|
|
888
|
+
deployment = { ...deployment };
|
|
889
|
+
options = { ...structuredClone(pinned), ...(anchorWait ? { anchorWait } : {}) };
|
|
890
|
+
const wait = anchorWaitPolicy(anchorWait);
|
|
891
|
+
validateDeployment(deployment);
|
|
892
|
+
if (!HEX32.test(slotId) || [deployment.verifierSet, deployment.accountantSet, deployment.beacon, ...(options.coordinator ? [options.coordinator] : [])]
|
|
893
|
+
.some(address => !ADDRESS.test(address) || /^0x0{40}$/i.test(address)))
|
|
894
|
+
throw new Error('invalid payment discovery identity');
|
|
895
|
+
const complete = (seed, root, size, accountant) => seed !== ZERO32 && root !== ZERO32 && size > 0 && accountant[0] !== ZERO32 && accountant[1] > 0 && accountant[1] <= 65535;
|
|
896
|
+
const deadline = wait.clock.now() + wait.timeoutMs;
|
|
897
|
+
const undrawnOk = options.undrawnDuringAnchorGap === true && options.fundedByAllowance === true && options.verificationEpoch === undefined;
|
|
898
|
+
// The billing check reads its own head. At a followed tip whose refusal is decided again at a
|
|
899
|
+
// newer `latest`, it is left to that decision (or, when none follows, run once before refusing).
|
|
900
|
+
let billing = 'none';
|
|
901
|
+
const judgeBilling = async (at, error) => {
|
|
902
|
+
if (followedObservations.has(at) && (error === undefined || (typeof error === 'object' && error !== null && staleRefusals.has(error)))) {
|
|
903
|
+
if (billing === 'none')
|
|
904
|
+
billing = 'deferred';
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
billing = 'judged';
|
|
908
|
+
await refuseUnlessPrepaid(client, deployment, slotId);
|
|
909
|
+
};
|
|
910
|
+
const attempt = async (at) => {
|
|
911
|
+
const { seedAt, snapshotAt, accountantAt, latestAnchors, reads } = slotReads(client, deployment, slotId, at);
|
|
912
|
+
// On a failed read, a legacy or unreadable billing mode is the clearer refusal.
|
|
913
|
+
const [keyBeacon, snapshotBeacon, accountantBeacon, latest, policy, enabled, available, directory, version] = await reads.catch(async (error) => {
|
|
914
|
+
await judgeBilling(at, error);
|
|
915
|
+
throw error;
|
|
916
|
+
});
|
|
917
|
+
// An unknown version is never guessed prepaid, even with prepaidEnabled set: the typed refusal names it.
|
|
918
|
+
if (!isPrepaidSettlementVersion(version)) {
|
|
919
|
+
await refuseUnlessPrepaid(client, deployment, slotId);
|
|
920
|
+
throw new Error('payment discovery Settlement version is not prepaid');
|
|
921
|
+
}
|
|
922
|
+
if (enabled !== true) {
|
|
923
|
+
// Every outcome below is a refusal (reversible unless a beacon pointer differs).
|
|
924
|
+
await judgeBilling(at);
|
|
925
|
+
// Prepaid from genesis but never funded: the first funding activates it.
|
|
926
|
+
if (available === 0n)
|
|
927
|
+
throw reversible(new UnderfundedSlotError({ slotId, availableTasraUnits: 0n,
|
|
928
|
+
message: 'payment discovery requires an activated TASRA-funded slot' }));
|
|
929
|
+
}
|
|
930
|
+
if ([keyBeacon, snapshotBeacon, accountantBeacon].some(pointer => pointer.toLowerCase() !== deployment.beacon.toLowerCase()))
|
|
931
|
+
throw new Error('payment discovery beacon pointers differ');
|
|
932
|
+
if (enabled !== true || typeof available !== 'bigint' || available < 0n)
|
|
933
|
+
throw reversible(new Error('payment discovery requires an activated TASRA-funded slot'));
|
|
934
|
+
if (available === 0n && options.fundedByAllowance !== true)
|
|
935
|
+
throw reversible(new UnderfundedSlotError({ slotId, availableTasraUnits: available,
|
|
936
|
+
message: 'payment discovery requires an activated TASRA-funded slot' }));
|
|
937
|
+
let epoch = latest;
|
|
938
|
+
let [seed, [root, size], accountant] = await latestAnchors;
|
|
939
|
+
if (seed === ZERO32)
|
|
940
|
+
throw new Error('current beacon seed unavailable');
|
|
941
|
+
const pinned = options.verificationEpoch;
|
|
942
|
+
if (pinned !== undefined) {
|
|
943
|
+
// A session grant's draw: the latest epoch (its anchors may still be landing: wait), or the
|
|
944
|
+
// previous one, never anything older (no keeper admits that grant) or newer. A grant one epoch
|
|
945
|
+
// AHEAD of this head was drawn at a newer block than this one: a newer head may admit it.
|
|
946
|
+
if (pinned !== latest && pinned !== latest - 1n) {
|
|
947
|
+
const moved = new PaidDrawMovedError(pinned, latest);
|
|
948
|
+
throw pinned === latest + 1n ? reversible(moved) : moved;
|
|
949
|
+
}
|
|
950
|
+
if (pinned !== latest) {
|
|
951
|
+
epoch = pinned;
|
|
952
|
+
[seed, [root, size], accountant] = await Promise.all([seedAt(epoch), snapshotAt(epoch), accountantAt(epoch)]);
|
|
953
|
+
if (!complete(seed, root, size, accountant))
|
|
954
|
+
throw new Error('pinned verifier epoch has no complete anchors');
|
|
955
|
+
}
|
|
956
|
+
else if (!complete(seed, root, size, accountant))
|
|
957
|
+
return { wait: 'pinned verifier epoch anchors are not complete yet' };
|
|
958
|
+
return { at, policy, available, directory, epoch, seed, root, size, latest };
|
|
959
|
+
}
|
|
960
|
+
if (!complete(seed, root, size, accountant)) {
|
|
961
|
+
if (epoch === 0n)
|
|
962
|
+
throw new Error('no anchored verifier and accountant snapshots');
|
|
963
|
+
epoch--;
|
|
964
|
+
[seed, [root, size], accountant] = await Promise.all([seedAt(epoch), snapshotAt(epoch), accountantAt(epoch)]);
|
|
965
|
+
// A new epoch's anchors have not landed yet (see PaidAnchorWait): wait and observe again.
|
|
966
|
+
if (!complete(seed, root, size, accountant)) {
|
|
967
|
+
// An allowance-funded caller pays the allowance's draw: the keeper sharing read here is all it needs.
|
|
968
|
+
if (undrawnOk)
|
|
969
|
+
return { at, policy, available, directory, epoch: 0n, seed: ZERO32, root: ZERO32, size: 0, latest, undrawn: true };
|
|
970
|
+
return { wait: 'no current or previous anchored verifier and accountant snapshots' };
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
return { at, policy, available, directory, epoch, seed, root, size, latest };
|
|
974
|
+
};
|
|
975
|
+
// One fresh canonical observation per attempt; an attempt that finds no admissible complete
|
|
976
|
+
// epoch waits (bounded) and observes again at a newer head, never re-reads an old one. A
|
|
977
|
+
// reversible refusal at a followed tip is decided once more at a newer RPC `latest`.
|
|
978
|
+
const observed = await (async () => {
|
|
979
|
+
for (;;) {
|
|
980
|
+
const head = await observe(client, deployment);
|
|
981
|
+
if (headFollowerOf(client))
|
|
982
|
+
followPaidSlot(client, deployment, slotId);
|
|
983
|
+
billing = 'none';
|
|
984
|
+
const result = await decideAtFreshHead(client, head, attempt).catch(async (error) => {
|
|
985
|
+
if (billing === 'deferred') {
|
|
986
|
+
billing = 'judged';
|
|
987
|
+
await refuseUnlessPrepaid(client, deployment, slotId);
|
|
988
|
+
}
|
|
989
|
+
throw error;
|
|
990
|
+
});
|
|
991
|
+
if (!('wait' in result))
|
|
992
|
+
return result;
|
|
993
|
+
if (wait.clock.now() + wait.pollMs > deadline)
|
|
994
|
+
throw new Error(result.wait);
|
|
995
|
+
await wait.clock.sleep(wait.pollMs);
|
|
996
|
+
}
|
|
997
|
+
})();
|
|
998
|
+
const { at, policy, available, directory, epoch, seed, root, size, latest, undrawn } = observed;
|
|
999
|
+
const [onChainCommittee, onChainQuorum] = policy;
|
|
1000
|
+
if (onChainCommittee === 0 && onChainQuorum !== 0)
|
|
1001
|
+
throw new Error('invalid on-chain verifier policy');
|
|
1002
|
+
const approved = onChainCommittee === 0
|
|
1003
|
+
? options.defaultVerificationPolicy ?? { committee: 0, quorum: 0 }
|
|
1004
|
+
: { committee: onChainCommittee, quorum: onChainQuorum };
|
|
1005
|
+
// Undrawn: no draw to size the policy against; the verification fields stay zero (refused by every reader).
|
|
1006
|
+
if (!Number.isInteger(approved.committee) || !Number.isInteger(approved.quorum) || approved.quorum <= 0 || approved.quorum > approved.committee || approved.committee > 4096
|
|
1007
|
+
|| (!undrawn && approved.committee > size))
|
|
1008
|
+
throw new Error('missing or invalid approved verifier policy');
|
|
1009
|
+
const { committee, quorum } = undrawn ? { committee: 0, quorum: 0 } : approved;
|
|
1010
|
+
const members = [...directory.members.values()].filter(member => member.eligible).sort((a, b) => a.id < b.id ? -1 : 1);
|
|
1011
|
+
const selected = options.coordinator
|
|
1012
|
+
? members.find(member => member.operator.toLowerCase() === options.coordinator.toLowerCase())
|
|
1013
|
+
: drawKeeper(members);
|
|
1014
|
+
if (!selected)
|
|
1015
|
+
throw new Error('requested coordinator is not an eligible assigned keeper');
|
|
1016
|
+
const contributors = members.map(member => member.key).sort();
|
|
1017
|
+
const assignment = { key_epoch: safeInteger(directory.slot.epoch, 'keeper epoch'), committee_version: safeInteger(directory.slot.committeeVersion, 'committee version'),
|
|
1018
|
+
threshold: directory.slot.threshold.k, coordinator: [...hexToBytes(selected.key)], contributors: contributors.map(key => [...hexToBytes(key)]) };
|
|
1019
|
+
keeperAssignmentCommitment(assignment);
|
|
1020
|
+
const endpoints = contributors.map(key => keeperEndpoint(directory.members, key, deployment.chainId, options));
|
|
1021
|
+
const coordinator = keeperEndpoint(directory.members, selected.key, deployment.chainId, options);
|
|
1022
|
+
const sharing = { chain_id: deployment.chainId, settlement: deployment.settlement, key_registry: deployment.keyRegistry, slot: slotId, keeper_assignment: assignment };
|
|
1023
|
+
await finishObservation(client, at);
|
|
1024
|
+
const base = { ...at, creator: directory.slot.creator, mode: directory.slot.mode, groupPublicKey: directory.slot.publicKey, coordinator, contributors: endpoints, available,
|
|
1025
|
+
ruleCommitment: directory.slot.ruleCommitment, ruleVersion: Number(directory.slot.ruleVersion), beaconEpoch: latest };
|
|
1026
|
+
// Undrawn: no verification fields at all (not zeroed ones), so no intent can be built from it.
|
|
1027
|
+
if (undrawn)
|
|
1028
|
+
return { ...base, intentFields: sharing, undrawn };
|
|
1029
|
+
const intentFields = { ...sharing,
|
|
1030
|
+
verification_epoch: safeInteger(epoch, 'verification epoch'), verification_seed: seed, verification_root: root, verification_registry_size: size,
|
|
1031
|
+
verification_committee: committee, verification_quorum: quorum };
|
|
1032
|
+
return { ...base, intentFields };
|
|
1033
|
+
}
|
|
1034
|
+
// readKeeperDirectory bounds a slot to 256 members. Reject the excess range so
|
|
1035
|
+
// every eligible keeper has the same chance, including with non-power-of-two rosters.
|
|
1036
|
+
// This is a fresh-context default, never a redraw of an existing signed assignment.
|
|
1037
|
+
function drawKeeper(members) {
|
|
1038
|
+
if (!members.length)
|
|
1039
|
+
return undefined;
|
|
1040
|
+
const limit = 256 - 256 % members.length;
|
|
1041
|
+
let sample;
|
|
1042
|
+
do {
|
|
1043
|
+
sample = randomBytes(1)[0];
|
|
1044
|
+
} while (sample >= limit);
|
|
1045
|
+
return members[sample % members.length];
|
|
1046
|
+
}
|