@t3foundry/tasra-sdk 0.0.0-stage → 0.3.1-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +148 -0
- package/LICENSE +202 -0
- package/NOTICE +94 -0
- package/README.md +137 -2
- package/SECURITY.md +115 -0
- package/dist/app/approvals.d.ts +50 -0
- package/dist/app/approvals.js +90 -0
- package/dist/app/authorization.d.ts +19 -0
- package/dist/app/authorization.js +20 -0
- package/dist/app/client.d.ts +231 -0
- package/dist/app/client.js +272 -0
- package/dist/app/creation.d.ts +73 -0
- package/dist/app/creation.js +77 -0
- package/dist/app/deployment.d.ts +36 -0
- package/dist/app/deployment.js +18 -0
- package/dist/app/identity.d.ts +211 -0
- package/dist/app/identity.js +287 -0
- package/dist/app/index.d.ts +22 -0
- package/dist/app/index.js +12 -0
- package/dist/app/manifest.d.ts +74 -0
- package/dist/app/manifest.js +120 -0
- package/dist/app/node.d.ts +30 -0
- package/dist/app/node.js +159 -0
- package/dist/app/ready-slot.d.ts +157 -0
- package/dist/app/ready-slot.js +199 -0
- package/dist/app/tasra-client.d.ts +125 -0
- package/dist/app/tasra-client.js +79 -0
- package/dist/app/viem.d.ts +10 -0
- package/dist/app/viem.js +32 -0
- package/dist/app/wallet.d.ts +126 -0
- package/dist/app/wallet.js +137 -0
- package/dist/auth/dpop.d.ts +86 -0
- package/dist/auth/dpop.js +142 -0
- package/dist/auth/holderProof.d.ts +102 -0
- package/dist/auth/holderProof.js +161 -0
- package/dist/auth/identityScope.d.ts +19 -0
- package/dist/auth/identityScope.js +82 -0
- package/dist/auth/index.d.ts +11 -0
- package/dist/auth/index.js +13 -0
- package/dist/auth/oid4vp.d.ts +230 -0
- package/dist/auth/oid4vp.js +780 -0
- package/dist/auth/rego/wasm/PINS.json +11 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm.d.ts +76 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm.js +379 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm_bg.wasm +0 -0
- package/dist/auth/rego.d.ts +192 -0
- package/dist/auth/rego.js +492 -0
- package/dist/auth/verifier.d.ts +166 -0
- package/dist/auth/verifier.js +211 -0
- package/dist/chain/abis/accountantSetRegistry.d.ts +441 -0
- package/dist/chain/abis/accountantSetRegistry.js +574 -0
- package/dist/chain/abis/accountantSlashing.d.ts +2071 -0
- package/dist/chain/abis/accountantSlashing.js +2670 -0
- package/dist/chain/abis/bondingCurve.d.ts +398 -0
- package/dist/chain/abis/bondingCurve.js +521 -0
- package/dist/chain/abis/equivocationSlasher.d.ts +292 -0
- package/dist/chain/abis/equivocationSlasher.js +379 -0
- package/dist/chain/abis/fixedTasraPriceOracle.d.ts +52 -0
- package/dist/chain/abis/fixedTasraPriceOracle.js +72 -0
- package/dist/chain/abis/index.d.ts +12801 -0
- package/dist/chain/abis/index.js +64 -0
- package/dist/chain/abis/keeperShareRegistry.d.ts +519 -0
- package/dist/chain/abis/keeperShareRegistry.js +675 -0
- package/dist/chain/abis/keyRegistry.d.ts +2421 -0
- package/dist/chain/abis/keyRegistry.js +3114 -0
- package/dist/chain/abis/livenessRegistry.d.ts +402 -0
- package/dist/chain/abis/livenessRegistry.js +524 -0
- package/dist/chain/abis/mockEurc.d.ts +210 -0
- package/dist/chain/abis/mockEurc.js +276 -0
- package/dist/chain/abis/nodeRegistry.d.ts +1630 -0
- package/dist/chain/abis/nodeRegistry.js +2113 -0
- package/dist/chain/abis/platformExecutor.d.ts +328 -0
- package/dist/chain/abis/platformExecutor.js +429 -0
- package/dist/chain/abis/prevrandaoSaltBeacon.d.ts +16 -0
- package/dist/chain/abis/prevrandaoSaltBeacon.js +24 -0
- package/dist/chain/abis/serviceRegistry.d.ts +556 -0
- package/dist/chain/abis/serviceRegistry.js +719 -0
- package/dist/chain/abis/settlement.d.ts +1624 -0
- package/dist/chain/abis/settlement.js +2096 -0
- package/dist/chain/abis/tasraSwapRouter.d.ts +92 -0
- package/dist/chain/abis/tasraSwapRouter.js +122 -0
- package/dist/chain/abis/tasraToken.d.ts +455 -0
- package/dist/chain/abis/tasraToken.js +599 -0
- package/dist/chain/abis/tasraVestingVault.d.ts +165 -0
- package/dist/chain/abis/tasraVestingVault.js +215 -0
- package/dist/chain/abis/thresholdRandomBeacon.d.ts +378 -0
- package/dist/chain/abis/thresholdRandomBeacon.js +494 -0
- package/dist/chain/abis/treasury.d.ts +301 -0
- package/dist/chain/abis/treasury.js +390 -0
- package/dist/chain/abis/verifierSetRegistry.d.ts +445 -0
- package/dist/chain/abis/verifierSetRegistry.js +579 -0
- package/dist/chain/client.d.ts +212 -0
- package/dist/chain/client.js +576 -0
- package/dist/chain/commitmentRecovery.d.ts +21 -0
- package/dist/chain/commitmentRecovery.js +44 -0
- package/dist/chain/committeeClient.d.ts +102 -0
- package/dist/chain/committeeClient.js +137 -0
- package/dist/chain/deployments.d.ts +56 -0
- package/dist/chain/deployments.js +269 -0
- package/dist/chain/discovery.d.ts +49 -0
- package/dist/chain/discovery.js +107 -0
- package/dist/chain/events.d.ts +58 -0
- package/dist/chain/events.js +125 -0
- package/dist/chain/format.d.ts +25 -0
- package/dist/chain/format.js +51 -0
- package/dist/chain/index.d.ts +41 -0
- package/dist/chain/index.js +56 -0
- package/dist/chain/manifest.d.ts +165 -0
- package/dist/chain/manifest.js +132 -0
- package/dist/chain/network-profiles.json +75 -0
- package/dist/chain/networks.d.ts +73 -0
- package/dist/chain/networks.js +62 -0
- package/dist/chain/node.d.ts +44 -0
- package/dist/chain/node.js +176 -0
- package/dist/chain/offchain.d.ts +149 -0
- package/dist/chain/offchain.js +73 -0
- package/dist/chain/provisionRule.d.ts +164 -0
- package/dist/chain/provisionRule.js +212 -0
- package/dist/chain/registeredAgent.d.ts +64 -0
- package/dist/chain/registeredAgent.js +140 -0
- package/dist/chain/registeredOperation.d.ts +49 -0
- package/dist/chain/registeredOperation.js +136 -0
- package/dist/chain/registeredRelay.d.ts +206 -0
- package/dist/chain/registeredRelay.js +312 -0
- package/dist/chain/revertReason.d.ts +14 -0
- package/dist/chain/revertReason.js +62 -0
- package/dist/chain/ruleAmendment.d.ts +80 -0
- package/dist/chain/ruleAmendment.js +195 -0
- package/dist/chain/ruleAmendmentCore.d.ts +129 -0
- package/dist/chain/ruleAmendmentCore.js +152 -0
- package/dist/chain/ruleInput.d.ts +10 -0
- package/dist/chain/ruleInput.js +13 -0
- package/dist/chain/serviceIdentity.d.ts +176 -0
- package/dist/chain/serviceIdentity.js +237 -0
- package/dist/chain/serviceProfiles.d.ts +39 -0
- package/dist/chain/serviceProfiles.js +74 -0
- package/dist/chain/services.d.ts +141 -0
- package/dist/chain/services.js +79 -0
- package/dist/chain/slotClient.d.ts +55 -0
- package/dist/chain/slotClient.js +62 -0
- package/dist/chain/slotSeed.d.ts +31 -0
- package/dist/chain/slotSeed.js +98 -0
- package/dist/chain/write.d.ts +431 -0
- package/dist/chain/write.js +958 -0
- package/dist/client/client.d.ts +112 -0
- package/dist/client/client.js +111 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +2 -0
- package/dist/client/session.d.ts +67 -0
- package/dist/client/session.js +238 -0
- package/dist/committee/client.d.ts +284 -0
- package/dist/committee/client.js +351 -0
- package/dist/committee/dual-sign.d.ts +110 -0
- package/dist/committee/dual-sign.js +202 -0
- package/dist/committee/ecdsa.d.ts +36 -0
- package/dist/committee/ecdsa.js +45 -0
- package/dist/committee/extraction.d.ts +82 -0
- package/dist/committee/extraction.js +96 -0
- package/dist/committee/index.d.ts +19 -0
- package/dist/committee/index.js +13 -0
- package/dist/committee/oauth.d.ts +51 -0
- package/dist/committee/oauth.js +90 -0
- package/dist/committee/receipts.d.ts +51 -0
- package/dist/committee/receipts.js +59 -0
- package/dist/committee/request.d.ts +264 -0
- package/dist/committee/request.js +305 -0
- package/dist/committee/token.d.ts +274 -0
- package/dist/committee/token.js +418 -0
- package/dist/crypto/constants.d.ts +10 -0
- package/dist/crypto/constants.js +32 -0
- package/dist/crypto/detect.d.ts +20 -0
- package/dist/crypto/detect.js +44 -0
- package/dist/crypto/envelope.d.ts +60 -0
- package/dist/crypto/envelope.js +243 -0
- package/dist/crypto/frost.d.ts +49 -0
- package/dist/crypto/frost.js +152 -0
- package/dist/crypto/hex.d.ts +7 -0
- package/dist/crypto/hex.js +24 -0
- package/dist/crypto/ibe-blob.d.ts +114 -0
- package/dist/crypto/ibe-blob.js +208 -0
- package/dist/crypto/ibe.d.ts +88 -0
- package/dist/crypto/ibe.js +262 -0
- package/dist/crypto/index.d.ts +12 -0
- package/dist/crypto/index.js +12 -0
- package/dist/crypto/kem.d.ts +55 -0
- package/dist/crypto/kem.js +241 -0
- package/dist/decryption/client.d.ts +64 -0
- package/dist/decryption/client.js +82 -0
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/errors.d.ts +124 -0
- package/dist/errors.js +167 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +98 -0
- package/dist/keys/index.d.ts +1 -0
- package/dist/keys/index.js +4 -0
- package/dist/keys/node-client.d.ts +27 -0
- package/dist/keys/node-client.js +97 -0
- package/dist/oid4vp/binding.d.ts +76 -0
- package/dist/oid4vp/binding.js +118 -0
- package/dist/oid4vp/did-web.d.ts +49 -0
- package/dist/oid4vp/did-web.js +57 -0
- package/dist/oid4vp/index.d.ts +9 -0
- package/dist/oid4vp/index.js +10 -0
- package/dist/oid4vp/jose.d.ts +166 -0
- package/dist/oid4vp/jose.js +242 -0
- package/dist/oid4vp/jwe.d.ts +30 -0
- package/dist/oid4vp/jwe.js +93 -0
- package/dist/oid4vp/oid4vci.d.ts +84 -0
- package/dist/oid4vp/oid4vci.js +85 -0
- package/dist/oid4vp/request-object.d.ts +109 -0
- package/dist/oid4vp/request-object.js +96 -0
- package/dist/oid4vp/sd-jwt.d.ts +177 -0
- package/dist/oid4vp/sd-jwt.js +208 -0
- package/dist/oid4vp/verifier-agent.d.ts +161 -0
- package/dist/oid4vp/verifier-agent.js +132 -0
- package/dist/oid4vp/wallet.d.ts +116 -0
- package/dist/oid4vp/wallet.js +108 -0
- package/dist/recipient/store.d.ts +67 -0
- package/dist/recipient/store.js +98 -0
- package/dist/signing/ecdsa.d.ts +49 -0
- package/dist/signing/ecdsa.js +79 -0
- package/dist/signing/frost.d.ts +88 -0
- package/dist/signing/frost.js +145 -0
- package/dist/signing/index.d.ts +4 -0
- package/dist/signing/index.js +3 -0
- package/dist/slots/faucet.d.ts +23 -0
- package/dist/slots/faucet.js +35 -0
- package/dist/slots/index.d.ts +2 -0
- package/dist/slots/index.js +4 -0
- package/dist/verifier-agent/index.d.ts +241 -0
- package/dist/verifier-agent/index.js +411 -0
- package/docs/DEVELOPER-EXPERIENCE.md +62 -0
- package/docs/README.md +33 -0
- package/docs/access-control.md +76 -0
- package/docs/ai-development.md +292 -0
- package/docs/api.md +338 -0
- package/docs/application-api.md +335 -0
- package/docs/architecture.md +65 -0
- package/docs/basics.md +48 -0
- package/docs/capabilities.md +86 -0
- package/docs/chain.md +153 -0
- package/docs/compatibility.md +36 -0
- package/docs/consumer-migrations.md +80 -0
- package/docs/create-slot.md +104 -0
- package/docs/document-signing.md +243 -0
- package/docs/encrypted-notes.md +129 -0
- package/docs/encryption.md +100 -0
- package/docs/errors.md +76 -0
- package/docs/flows.md +289 -0
- package/docs/fuji.md +127 -0
- package/docs/funding.md +126 -0
- package/docs/getting-started.md +94 -0
- package/docs/glossary.md +44 -0
- package/docs/installation.md +132 -0
- package/docs/manage-slot.md +95 -0
- package/docs/native-approvals.md +124 -0
- package/docs/prerequisites.md +137 -0
- package/docs/read-slot.md +41 -0
- package/docs/reference/README.md +30 -0
- package/docs/reference/app-node.md +102 -0
- package/docs/reference/app.md +1737 -0
- package/docs/reference/chain-node.md +159 -0
- package/docs/reference/chain.md +3609 -0
- package/docs/reference/committee.md +2176 -0
- package/docs/reference/main.md +4068 -0
- package/docs/reference/oid4vp.md +2547 -0
- package/docs/reference/verifier-agent.md +498 -0
- package/docs/shared-account.md +168 -0
- package/docs/signing-and-encryption.md +52 -0
- package/docs/signing.md +172 -0
- package/examples/committee-slot.ts +16 -0
- package/examples/connect-fuji.ts +41 -0
- package/examples/connect-network.ts +14 -0
- package/examples/credential-approvals.ts +46 -0
- package/examples/document-signing/README.md +59 -0
- package/examples/document-signing/backend.ts +132 -0
- package/examples/document-signing/build.mjs +19 -0
- package/examples/document-signing/config.ts +34 -0
- package/examples/document-signing/gitignore.template +9 -0
- package/examples/document-signing/model.ts +140 -0
- package/examples/document-signing/network.ts +58 -0
- package/examples/document-signing/package.json +25 -0
- package/examples/document-signing/public/index.html +27 -0
- package/examples/document-signing/public/sample.pdf +31 -0
- package/examples/document-signing/public/styles.css +531 -0
- package/examples/document-signing/server.ts +358 -0
- package/examples/document-signing/setup.ts +111 -0
- package/examples/document-signing/store.ts +105 -0
- package/examples/document-signing/tsconfig.json +24 -0
- package/examples/document-signing/verify.ts +24 -0
- package/examples/document-signing/web/app.ts +312 -0
- package/examples/document-signing/web/preview.ts +67 -0
- package/examples/document-signing/web/wallet.ts +146 -0
- package/examples/document-signing/workflow.test.ts +228 -0
- package/examples/document-signing/workflow.ts +241 -0
- package/examples/document-signing.ts +96 -0
- package/examples/encrypted-notes.ts +86 -0
- package/examples/ethers-signer.ts +204 -0
- package/examples/fund-slot.ts +73 -0
- package/examples/getting-started.ts +25 -0
- package/examples/learning-authorize.ts +23 -0
- package/examples/learning-cancel-slot.ts +11 -0
- package/examples/learning-context.ts +28 -0
- package/examples/learning-create-slot.ts +25 -0
- package/examples/learning-read-slot.ts +8 -0
- package/examples/learning-renew-slot.ts +12 -0
- package/examples/learning-sign.ts +8 -0
- package/examples/live-config.ts +71 -0
- package/examples/minimal.ts +6 -0
- package/examples/native-approvals.ts +57 -0
- package/examples/network.ts +58 -0
- package/examples/offline.ts +16 -0
- package/examples/personal-vault.ts +20 -0
- package/examples/provision-slot.ts +47 -0
- package/examples/shared-account.ts +46 -0
- package/examples/slot-address.ts +13 -0
- package/examples/slot-creation.ts +9 -0
- package/examples/tutorial-negative.ts +26 -0
- package/examples/tutorial-support.ts +76 -0
- package/examples/viem-account.ts +203 -0
- package/package.json +303 -4
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { decodeEventLog, encodeFunctionData, hashTypedData, parseAbi } from 'viem';
|
|
2
|
+
import { authenticateApprovedService } from './serviceIdentity.js';
|
|
3
|
+
import { SERVICE_TYPES } from './services.js';
|
|
4
|
+
import { revertError } from './revertReason.js';
|
|
5
|
+
/**
|
|
6
|
+
* Forwarder ABI used to submit requests, read nonces and verify execution events.
|
|
7
|
+
*/
|
|
8
|
+
export const relayForwarderAbi = parseAbi([
|
|
9
|
+
'function nonces(address owner) view returns (uint256)',
|
|
10
|
+
'function execute((address from, address to, uint256 value, uint256 gas, uint48 deadline, bytes data, bytes signature) request) payable',
|
|
11
|
+
'event ExecutedForwardRequest(address indexed signer, uint256 nonce, bool success)',
|
|
12
|
+
]);
|
|
13
|
+
const types = { ForwardRequest: [
|
|
14
|
+
{ name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'value', type: 'uint256' },
|
|
15
|
+
{ name: 'gas', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint48' }, { name: 'data', type: 'bytes' },
|
|
16
|
+
] };
|
|
17
|
+
/**
|
|
18
|
+
* A relay request has no verified terminal result and must be reconciled before replacement.
|
|
19
|
+
*/
|
|
20
|
+
export class RelayOutcomeUnknownError extends Error {
|
|
21
|
+
attempt;
|
|
22
|
+
constructor(/** Persisted signed relay attempt whose execution outcome remains unknown. */ attempt, reason = 'No verified chain result before the relay deadline') {
|
|
23
|
+
super(`${reason}; reconcile request ${attempt.id} before signing another operation`);
|
|
24
|
+
this.attempt = attempt;
|
|
25
|
+
this.name = 'RelayOutcomeUnknownError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function typed(attempt) {
|
|
29
|
+
const r = attempt.request;
|
|
30
|
+
return { domain: { name: 'KeykeeperForwarder', version: '1', chainId: attempt.chainId, verifyingContract: attempt.forwarder },
|
|
31
|
+
types, primaryType: 'ForwardRequest',
|
|
32
|
+
message: { from: r.from, to: r.to, value: 0n, gas: BigInt(r.gas), nonce: BigInt(r.nonce), deadline: r.deadline, data: r.data } };
|
|
33
|
+
}
|
|
34
|
+
function executeData(attempt) {
|
|
35
|
+
const r = attempt.request;
|
|
36
|
+
return encodeFunctionData({ abi: relayForwarderAbi, functionName: 'execute', args: [{ ...r, value: 0n, gas: BigInt(r.gas) }] });
|
|
37
|
+
}
|
|
38
|
+
function scope(timeoutMs) {
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
const timer = setTimeout(() => controller.abort(new Error('Relay deadline exceeded')), timeoutMs);
|
|
41
|
+
return { signal: controller.signal, close: () => { clearTimeout(timer); controller.abort(); },
|
|
42
|
+
async run(work) {
|
|
43
|
+
controller.signal.throwIfAborted();
|
|
44
|
+
let abort = () => { };
|
|
45
|
+
try {
|
|
46
|
+
return await Promise.race([work(), new Promise((_, reject) => {
|
|
47
|
+
abort = () => reject(controller.signal.reason);
|
|
48
|
+
controller.signal.addEventListener('abort', abort, { once: true });
|
|
49
|
+
})]);
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
controller.signal.removeEventListener('abort', abort);
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
async function verifiedReceipt(chain, attempt, hash, budget) {
|
|
58
|
+
const tx = await budget.run(() => chain.client.getTransaction({ hash }));
|
|
59
|
+
if (tx.to?.toLowerCase() !== attempt.forwarder.toLowerCase() || tx.value !== 0n || tx.input.toLowerCase() !== executeData(attempt).toLowerCase())
|
|
60
|
+
return;
|
|
61
|
+
const receipt = await budget.run(() => chain.client.getTransactionReceipt({ hash }));
|
|
62
|
+
if (receipt.status !== 'success')
|
|
63
|
+
return;
|
|
64
|
+
const matches = receipt.logs.some(log => {
|
|
65
|
+
if (log.address.toLowerCase() !== attempt.forwarder.toLowerCase())
|
|
66
|
+
return false;
|
|
67
|
+
try {
|
|
68
|
+
const event = decodeEventLog({ abi: relayForwarderAbi, eventName: 'ExecutedForwardRequest', data: log.data, topics: log.topics });
|
|
69
|
+
return event.args.signer.toLowerCase() === attempt.request.from.toLowerCase() && event.args.nonce === BigInt(attempt.request.nonce) && event.args.success;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
if (!matches)
|
|
76
|
+
return;
|
|
77
|
+
return { id: attempt.id, txHash: hash, gasUsed: Number(receipt.gasUsed), costWei: (receipt.gasUsed * receipt.effectiveGasPrice).toString() };
|
|
78
|
+
}
|
|
79
|
+
async function reconcile(chain, attempt, budget) {
|
|
80
|
+
if (await budget.run(() => chain.client.getChainId()) !== attempt.chainId || hashTypedData(typed(attempt)) !== attempt.id)
|
|
81
|
+
throw new Error('Relay reconciliation domain or request mismatch');
|
|
82
|
+
const head = await budget.run(() => chain.client.getBlock({ blockTag: 'latest' }));
|
|
83
|
+
const nonce = await budget.run(() => chain.client.readContract({ address: attempt.forwarder, abi: relayForwarderAbi, functionName: 'nonces', args: [attempt.request.from], blockNumber: head.number }));
|
|
84
|
+
if (nonce < BigInt(attempt.request.nonce))
|
|
85
|
+
throw new RelayOutcomeUnknownError(attempt, 'Forwarder nonce moved backwards');
|
|
86
|
+
if (nonce > BigInt(attempt.request.nonce)) {
|
|
87
|
+
const start = BigInt(attempt.fromBlock);
|
|
88
|
+
// OUT OF RANGE IS TERMINAL, not TRANSIENT. The nonce is already consumed, so this exact
|
|
89
|
+
// request can never execute again whatever took it - the forwarder rejects a spent nonce.
|
|
90
|
+
// All that is lost is WHICH request consumed it, and no amount of waiting recovers that:
|
|
91
|
+
// every new block moves `start` further outside the window. Throwing here made callers
|
|
92
|
+
// retry forever and permanently wedged a deployment's entire write path.
|
|
93
|
+
if (start < 0n || head.number - start > 10000n)
|
|
94
|
+
return { expired: false, unresolvable: true };
|
|
95
|
+
for (let from = start; from <= head.number; from += 2000n) {
|
|
96
|
+
const logs = await budget.run(() => chain.client.getLogs({ address: attempt.forwarder,
|
|
97
|
+
event: relayForwarderAbi[2], args: { signer: attempt.request.from }, fromBlock: from,
|
|
98
|
+
toBlock: from + 1999n < head.number ? from + 1999n : head.number, strict: true }));
|
|
99
|
+
for (const log of logs) {
|
|
100
|
+
if (log.args.nonce !== BigInt(attempt.request.nonce) || !log.args.success)
|
|
101
|
+
continue;
|
|
102
|
+
const receipt = await verifiedReceipt(chain, attempt, log.transactionHash, budget);
|
|
103
|
+
if (receipt)
|
|
104
|
+
return { receipt, expired: false };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
throw new RelayOutcomeUnknownError(attempt, 'Nonce consumed without a matching successful forward request');
|
|
108
|
+
}
|
|
109
|
+
return { expired: head.timestamp > BigInt(attempt.request.deadline) };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Recover from a lost HTTP response or process restart using the trusted RPC, without broadcasting.
|
|
113
|
+
* @param chain Trusted reader for the chain on which the forward request may have executed.
|
|
114
|
+
* @param attempt Persisted signed request and original log-scan start block.
|
|
115
|
+
* @param timeoutMs Maximum reconciliation duration in milliseconds; defaults to 30000.
|
|
116
|
+
*/
|
|
117
|
+
export async function reconcileRelayAttempt(chain, attempt, timeoutMs = 30_000) {
|
|
118
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000)
|
|
119
|
+
throw new Error('Invalid reconciliation timeout');
|
|
120
|
+
const budget = scope(timeoutMs);
|
|
121
|
+
try {
|
|
122
|
+
return await reconcile(chain, attempt, budget);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
budget.close();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* One signer per instance. Serializes nonces and blocks new signatures after an uncertain result.
|
|
130
|
+
* @param chain Trusted chain reader used for nonce and receipt verification.
|
|
131
|
+
* @param config Approved relay providers, pinned forwarder and recovery controls.
|
|
132
|
+
* @param wallet Account-bound and chain-bound wallet that signs forward requests.
|
|
133
|
+
* @param options Optional durable callback invoked before submitting a signed request.
|
|
134
|
+
*/
|
|
135
|
+
export function createRegisteredRelaySubmitter(chain, config, wallet, options = {}) {
|
|
136
|
+
if (!Array.isArray(config.approvals) || typeof config.transport?.request !== 'function' || typeof config.transport?.relayRequest !== 'function') {
|
|
137
|
+
throw new Error('Relay requires approved registry profiles and a guarded RelayTransport; a URL alone is insufficient');
|
|
138
|
+
}
|
|
139
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(config.forwarder) || /^0x0{40}$/.test(config.forwarder))
|
|
140
|
+
throw new Error('Invalid pinned relay forwarder');
|
|
141
|
+
const cfg = { ...config, approvals: config.approvals.map(a => Object.freeze({ ...a })) };
|
|
142
|
+
const timeout = cfg.timeoutMs ?? 120_000, pollMs = cfg.pollMs ?? 1_500, attemptMs = cfg.attemptMs ?? 10_000;
|
|
143
|
+
const attempts = cfg.maxAttempts ?? Math.min(3, cfg.approvals.length);
|
|
144
|
+
if (!cfg.approvals.length || cfg.approvals.length > 16 || cfg.approvals.some(a => a.serviceType !== SERVICE_TYPES.gasRelayer) ||
|
|
145
|
+
!Number.isInteger(attempts) || attempts < 1 || attempts > 3 || attempts > cfg.approvals.length ||
|
|
146
|
+
!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120_000 || !Number.isSafeInteger(pollMs) || pollMs < 10 ||
|
|
147
|
+
!Number.isSafeInteger(attemptMs) || attemptMs < 1 || attemptMs > 30_000)
|
|
148
|
+
throw new Error('Invalid registered relayer policy');
|
|
149
|
+
let serial = Promise.resolve();
|
|
150
|
+
let pending;
|
|
151
|
+
async function submit(to, data, label) {
|
|
152
|
+
const previous = serial;
|
|
153
|
+
let release = () => { };
|
|
154
|
+
serial = new Promise(resolve => { release = resolve; });
|
|
155
|
+
await previous;
|
|
156
|
+
const budget = scope(timeout);
|
|
157
|
+
let attempt;
|
|
158
|
+
try {
|
|
159
|
+
if (pending)
|
|
160
|
+
throw new RelayOutcomeUnknownError(pending);
|
|
161
|
+
const chainId = await budget.run(() => chain.client.getChainId());
|
|
162
|
+
if (chainId !== wallet.chain.id || cfg.approvals.some(a => a.chainId !== chainId))
|
|
163
|
+
throw new Error('Relay chain mismatch');
|
|
164
|
+
const from = wallet.account.address;
|
|
165
|
+
const previousAttempt = await budget.run(async () => cfg.resumeAttempt?.({ chainId, forwarder: cfg.forwarder, from, to, data, label: label ?? cfg.label ?? '' }));
|
|
166
|
+
if (previousAttempt) {
|
|
167
|
+
if (previousAttempt.chainId !== chainId || previousAttempt.forwarder.toLowerCase() !== cfg.forwarder.toLowerCase() ||
|
|
168
|
+
previousAttempt.request.from.toLowerCase() !== from.toLowerCase() || previousAttempt.request.to.toLowerCase() !== to.toLowerCase() ||
|
|
169
|
+
previousAttempt.request.data.toLowerCase() !== data.toLowerCase())
|
|
170
|
+
throw new Error('Persisted relay operation does not match this request');
|
|
171
|
+
const result = await reconcile(chain, previousAttempt, budget);
|
|
172
|
+
if (result.receipt)
|
|
173
|
+
return result.receipt;
|
|
174
|
+
// `unresolvable` must not resume and must not block. Its nonce is spent, so replaying
|
|
175
|
+
// the stored attempt is guaranteed to be rejected; but blocking on it never clears
|
|
176
|
+
// either, because the scan window only recedes. Fall through and sign a FRESH request
|
|
177
|
+
// at the current nonce - the caller was told (via the journal) that the old one is
|
|
178
|
+
// terminal-with-unknown-outcome and is responsible for not redoing work that landed.
|
|
179
|
+
if (result.unresolvable)
|
|
180
|
+
pending = undefined;
|
|
181
|
+
else if (!result.expired) {
|
|
182
|
+
pending = previousAttempt;
|
|
183
|
+
throw new RelayOutcomeUnknownError(previousAttempt);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const fromBlock = await budget.run(() => chain.client.getBlockNumber({ cacheTime: 0 }));
|
|
187
|
+
const nonce = await budget.run(() => chain.client.readContract({ address: cfg.forwarder, abi: relayForwarderAbi, functionName: 'nonces', args: [from] }));
|
|
188
|
+
// The inner call is estimated without an ABI, so viem cannot name a custom error; decode it, or a
|
|
189
|
+
// deployment that refuses the write (CommitRevealRequired(), say) reads as an unexplained revert.
|
|
190
|
+
const estimate = await budget.run(() => chain.client.estimateGas({ account: from, to, data }))
|
|
191
|
+
.catch(e => { throw revertError(e, 'relay: the inner call reverts at estimation'); });
|
|
192
|
+
const gas = estimate + estimate / 4n + 10000n;
|
|
193
|
+
if (nonce > BigInt(Number.MAX_SAFE_INTEGER) || gas > BigInt(Number.MAX_SAFE_INTEGER))
|
|
194
|
+
throw new Error('Relay nonce or gas exceeds the exact JSON integer range');
|
|
195
|
+
const request = { from, to, value: '0', gas: Number(gas), nonce: Number(nonce), deadline: Math.floor(Date.now() / 1000) + 300, data, signature: '0x', label: label ?? cfg.label ?? '' };
|
|
196
|
+
const unsigned = { chainId, forwarder: cfg.forwarder, request };
|
|
197
|
+
request.signature = await budget.run(() => wallet.signTypedData({ account: wallet.account, ...typed(unsigned) }));
|
|
198
|
+
attempt = Object.freeze({ ...unsigned, request: Object.freeze(request), fromBlock: fromBlock.toString(), id: hashTypedData(typed(unsigned)) });
|
|
199
|
+
const body = new TextEncoder().encode(JSON.stringify(request));
|
|
200
|
+
if (body.length > 65_536)
|
|
201
|
+
throw new Error('Relay request too large');
|
|
202
|
+
// The application can durably store this handle before any endpoint receives it.
|
|
203
|
+
const persist = cfg.persistAttempt ?? options.persistAttempt;
|
|
204
|
+
if (persist)
|
|
205
|
+
await budget.run(() => persist(attempt));
|
|
206
|
+
let contacted = false;
|
|
207
|
+
for (const approval of cfg.approvals.slice(0, attempts)) {
|
|
208
|
+
if (contacted) {
|
|
209
|
+
const result = await reconcile(chain, attempt, budget);
|
|
210
|
+
if (result.receipt) {
|
|
211
|
+
pending = undefined;
|
|
212
|
+
return result.receipt;
|
|
213
|
+
}
|
|
214
|
+
if (result.expired) {
|
|
215
|
+
pending = undefined;
|
|
216
|
+
throw new Error('Forward request expired without execution');
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
let endpoint;
|
|
220
|
+
try {
|
|
221
|
+
const authenticated = await budget.run(() => authenticateApprovedService(chain, approval, {
|
|
222
|
+
request: (url, opts) => cfg.transport.request(url, { ...opts, signal: AbortSignal.any([opts.signal, budget.signal]) }),
|
|
223
|
+
}));
|
|
224
|
+
if (!authenticated.manifest.capabilities.includes('relay-forward'))
|
|
225
|
+
throw new Error('Service does not advertise relay-forward');
|
|
226
|
+
endpoint = authenticated.record.endpoint;
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
budget.signal.throwIfAborted();
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
pending = attempt;
|
|
233
|
+
contacted = true;
|
|
234
|
+
try {
|
|
235
|
+
await budget.run(() => cfg.transport.relayRequest(endpoint + '/v1/relay/forward', { body, maxBytes: 4_096, signal: budget.signal }));
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
budget.signal.throwIfAborted();
|
|
239
|
+
}
|
|
240
|
+
const until = Date.now() + attemptMs;
|
|
241
|
+
do {
|
|
242
|
+
// A lost POST response still has a deterministic status ID.
|
|
243
|
+
try {
|
|
244
|
+
const bytes = await budget.run(() => cfg.transport.relayRequest(endpoint + '/v1/relay/' + attempt.id, { maxBytes: 4_096, signal: budget.signal }));
|
|
245
|
+
if (bytes.length > 4_096)
|
|
246
|
+
throw new Error('Relay status too large');
|
|
247
|
+
const status = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
248
|
+
if (status.id !== attempt.id)
|
|
249
|
+
throw new Error('Relay status request mismatch');
|
|
250
|
+
if (status.state === 'mined' && /^0x[0-9a-fA-F]{64}$/.test(status.tx_hash ?? '')) {
|
|
251
|
+
const receipt = await verifiedReceipt(chain, attempt, status.tx_hash, budget);
|
|
252
|
+
if (receipt) {
|
|
253
|
+
pending = undefined;
|
|
254
|
+
return receipt;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (['failed', 'rejected', 'unknown'].includes(status.state))
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
budget.signal.throwIfAborted();
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
const result = await reconcile(chain, attempt, budget);
|
|
265
|
+
if (result.receipt) {
|
|
266
|
+
pending = undefined;
|
|
267
|
+
return result.receipt;
|
|
268
|
+
}
|
|
269
|
+
if (result.expired) {
|
|
270
|
+
pending = undefined;
|
|
271
|
+
throw new Error('Forward request expired without execution');
|
|
272
|
+
}
|
|
273
|
+
await budget.run(() => new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(1, until - Date.now())))));
|
|
274
|
+
} while (Date.now() < until);
|
|
275
|
+
}
|
|
276
|
+
if (!contacted)
|
|
277
|
+
throw new Error('No approved relayer authenticated');
|
|
278
|
+
const result = await reconcile(chain, attempt, budget);
|
|
279
|
+
if (result.receipt) {
|
|
280
|
+
pending = undefined;
|
|
281
|
+
return result.receipt;
|
|
282
|
+
}
|
|
283
|
+
if (result.expired) {
|
|
284
|
+
pending = undefined;
|
|
285
|
+
throw new Error('Forward request expired without execution');
|
|
286
|
+
}
|
|
287
|
+
throw new RelayOutcomeUnknownError(attempt);
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
if (pending)
|
|
291
|
+
throw new RelayOutcomeUnknownError(pending, error instanceof Error ? error.message : undefined);
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
budget.close();
|
|
296
|
+
release();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return { submit, pendingAttempt: () => pending,
|
|
300
|
+
async reconcile() {
|
|
301
|
+
if (!pending)
|
|
302
|
+
return undefined;
|
|
303
|
+
const current = pending;
|
|
304
|
+
const result = await reconcileRelayAttempt(chain, current);
|
|
305
|
+
// `unresolvable` frees the signer too: the nonce is spent, so holding the slot blocks
|
|
306
|
+
// every future write for an attempt that can never complete.
|
|
307
|
+
if (pending === current && (result.receipt || result.expired || result.unresolvable))
|
|
308
|
+
pending = undefined;
|
|
309
|
+
return result;
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `CommitRevealRequired()`, or `InsufficientFilteredPool(3, 5)`, for an error carrying revert data
|
|
3
|
+
* this package's ABIs can decode; `undefined` when there is no data, or when it belongs to a
|
|
4
|
+
* contract outside them (a token's own error, say). Never throws.
|
|
5
|
+
* @param error RPC or viem error whose nested causes may contain revert data.
|
|
6
|
+
*/
|
|
7
|
+
export declare function describeRevert(error: unknown): string | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* `prefix`, then the decoded revert when there is one and viem's message when there is not. Keeps
|
|
10
|
+
* the original as `cause`, so a caller that wants the raw error still has it.
|
|
11
|
+
* @param error Underlying error carrying any revert details.
|
|
12
|
+
* @param prefix Context prepended to the readable error message.
|
|
13
|
+
*/
|
|
14
|
+
export declare function revertError(error: unknown, prefix: string): Error;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Name a revert that viem could not.
|
|
2
|
+
//
|
|
3
|
+
// viem decodes a custom error only when it knows which ABI the call belongs to. A raw
|
|
4
|
+
// `estimateGas` - what the relay path does before asking a relayer to forward a call - carries no
|
|
5
|
+
// ABI, so viem reports every custom error as "Execution reverted for an unknown reason." and the
|
|
6
|
+
// four bytes that say what actually happened are left inside the error chain. A caller then sees a
|
|
7
|
+
// deployment refuse a write with no way to learn why: `createSlot` on a genesis that requires
|
|
8
|
+
// commit-reveal reverts `CommitRevealRequired()`, which reads as an unexplained failure.
|
|
9
|
+
//
|
|
10
|
+
// Every Tasra contract's errors are in `CONTRACT_ABIS`, so the selector can be decoded back
|
|
11
|
+
// into the name and arguments the contract meant.
|
|
12
|
+
import { decodeErrorResult } from 'viem';
|
|
13
|
+
import { CONTRACT_ABIS } from './abis/index.js';
|
|
14
|
+
/** Every `error` item of every contract this package knows. */
|
|
15
|
+
const ERROR_ITEMS = Object.values(CONTRACT_ABIS)
|
|
16
|
+
.flatMap(abi => abi)
|
|
17
|
+
.filter(item => item?.type === 'error');
|
|
18
|
+
/**
|
|
19
|
+
* The revert data viem kept somewhere in the error's `cause` chain. RPC transports differ on where
|
|
20
|
+
* they put it (`EstimateGasExecutionError` to `ExecutionRevertedError` to `RpcRequestError.data` on
|
|
21
|
+
* an Avalanche C-chain node), so walk the chain rather than guess a shape.
|
|
22
|
+
*/
|
|
23
|
+
function revertData(error) {
|
|
24
|
+
const seen = new Set();
|
|
25
|
+
for (let e = error; e && typeof e === 'object' && !seen.has(e); e = e.cause) {
|
|
26
|
+
seen.add(e);
|
|
27
|
+
const data = e.data;
|
|
28
|
+
// A bare selector is 10 characters; anything shorter cannot name an error.
|
|
29
|
+
if (typeof data === 'string' && /^0x[0-9a-fA-F]{8,}$/.test(data))
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* `CommitRevealRequired()`, or `InsufficientFilteredPool(3, 5)`, for an error carrying revert data
|
|
36
|
+
* this package's ABIs can decode; `undefined` when there is no data, or when it belongs to a
|
|
37
|
+
* contract outside them (a token's own error, say). Never throws.
|
|
38
|
+
* @param error RPC or viem error whose nested causes may contain revert data.
|
|
39
|
+
*/
|
|
40
|
+
export function describeRevert(error) {
|
|
41
|
+
const data = revertData(error);
|
|
42
|
+
if (!data)
|
|
43
|
+
return undefined;
|
|
44
|
+
try {
|
|
45
|
+
const { errorName, args } = decodeErrorResult({ abi: ERROR_ITEMS, data });
|
|
46
|
+
return `${errorName}(${(args ?? []).map(a => String(a)).join(', ')})`;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* `prefix`, then the decoded revert when there is one and viem's message when there is not. Keeps
|
|
54
|
+
* the original as `cause`, so a caller that wants the raw error still has it.
|
|
55
|
+
* @param error Underlying error carrying any revert details.
|
|
56
|
+
* @param prefix Context prepended to the readable error message.
|
|
57
|
+
*/
|
|
58
|
+
export function revertError(error, prefix) {
|
|
59
|
+
const named = describeRevert(error);
|
|
60
|
+
const detail = named ?? String(error?.message ?? error).slice(0, 240);
|
|
61
|
+
return new Error(`${prefix}: ${detail}`, { cause: error });
|
|
62
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { Address, Hex } from 'viem';
|
|
2
|
+
import type { TasraChainClient } from './client.js';
|
|
3
|
+
import { type ProposeRuleArgs, type SlotAuthType, type TasraWriteClient } from './write.js';
|
|
4
|
+
import type { TypedDataSigner } from '../oid4vp/verifier-agent.js';
|
|
5
|
+
export { RuleAmendmentError } from './ruleAmendmentCore.js';
|
|
6
|
+
export type { RuleAmendmentErrorCode } from './ruleAmendmentCore.js';
|
|
7
|
+
/** A slot's rule and amendment state as the chain records it. */
|
|
8
|
+
export interface RuleAmendmentStatus {
|
|
9
|
+
/** Salted commitment of the ACTIVE rule. */
|
|
10
|
+
ruleCommitment: Hex;
|
|
11
|
+
/** Version of the active rule. */
|
|
12
|
+
ruleVersion: number;
|
|
13
|
+
/** Authorization family recorded at creation. */
|
|
14
|
+
authType: SlotAuthType;
|
|
15
|
+
/** Who may amend the rule and how slowly; `null` means the rule is immutable. */
|
|
16
|
+
policy: {
|
|
17
|
+
admin: Address;
|
|
18
|
+
guardian?: Address;
|
|
19
|
+
timelockSecs: number;
|
|
20
|
+
} | null;
|
|
21
|
+
/** The pending amendment with its keeper adoption votes, or `null` when none is pending. */
|
|
22
|
+
pending: {
|
|
23
|
+
version: number;
|
|
24
|
+
ruleCommitment: Hex;
|
|
25
|
+
notBefore: number;
|
|
26
|
+
adoptions: number;
|
|
27
|
+
needed: number;
|
|
28
|
+
} | null;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Read a slot's active rule commitment, amendment policy and pending amendment, including the
|
|
32
|
+
* keeper adoption votes and the votes activation needs.
|
|
33
|
+
* @param chain Reader for the deployment that owns the slot.
|
|
34
|
+
* @param slotId Slot to read; a missing or cancelled slot throws `RuleAmendmentError` code `no-slot`.
|
|
35
|
+
*/
|
|
36
|
+
export declare function readRuleAmendment(chain: TasraChainClient, slotId: Hex): Promise<RuleAmendmentStatus>;
|
|
37
|
+
/** Progress points `amendSlotRule` reports, in order. */
|
|
38
|
+
export type AmendmentPhase = 'proposed' | 'delivered' | 'adopted' | 'endorsed' | 'activated';
|
|
39
|
+
/** Arguments of {@link amendSlotRule}: the amendment, who delivers it, and optional guardian endorsement. */
|
|
40
|
+
export type AmendSlotRuleArgs = ProposeRuleArgs & {
|
|
41
|
+
/** Signs the rule delivery to the keepers: the slot creator or the rule admin. */
|
|
42
|
+
deliverer: TypedDataSigner;
|
|
43
|
+
/** The guardian's write client; when given, it endorses the amendment to waive the remaining delay. */
|
|
44
|
+
guardian?: TasraWriteClient;
|
|
45
|
+
/** Called at each completed phase with that phase's result. */
|
|
46
|
+
onPhase?: (p: AmendmentPhase, d?: unknown) => void;
|
|
47
|
+
/** Milliseconds allowed from delivery to activation (default: the slot's timelock plus 10 minutes). */
|
|
48
|
+
maxWaitMs?: number;
|
|
49
|
+
/** Cancels waiting and keeper requests. */
|
|
50
|
+
signal?: AbortSignal;
|
|
51
|
+
};
|
|
52
|
+
/** Outcome of {@link amendSlotRule}. */
|
|
53
|
+
export interface AmendSlotRuleResult {
|
|
54
|
+
/** Rule version now active. */
|
|
55
|
+
version: number;
|
|
56
|
+
/** Salted commitment of the rule now active. */
|
|
57
|
+
ruleCommitment: Hex;
|
|
58
|
+
/** Proposal transaction; absent when the proposal already existed (a resumed run). */
|
|
59
|
+
proposeTx?: Hex;
|
|
60
|
+
/** Activation transaction; absent when the rule was already active or another party activated it. */
|
|
61
|
+
activateTx?: Hex;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Amend a slot's rule end to end: propose (as the rule admin), deliver the rule to the keepers,
|
|
65
|
+
* wait for their adoption votes, endorse when a guardian client is given, wait for chain time to
|
|
66
|
+
* pass `notBefore`, activate, and confirm the active commitment on chain.
|
|
67
|
+
*
|
|
68
|
+
* Resumable: a proposal already pending with this rule is not proposed again, and a rule already
|
|
69
|
+
* active returns at once. Every refusal it can know in advance is raised before anything is signed.
|
|
70
|
+
* It never activates on a timer alone: activation needs the observed votes AND chain time.
|
|
71
|
+
*
|
|
72
|
+
* An amendable rule means whoever holds the admin key can change who may sign with this key,
|
|
73
|
+
* without changing the key. Keep the admin key as safe as the slot itself. The guardian can veto
|
|
74
|
+
* during the delay; without a guardian nobody can. Slots created without a rule admin can never
|
|
75
|
+
* become amendable.
|
|
76
|
+
* @param writer Write client of the slot's rule admin; it proposes and activates.
|
|
77
|
+
* @param chain Reader for the deployment that owns the slot.
|
|
78
|
+
* @param a The amendment, its deliverer, an optional guardian client and wait controls.
|
|
79
|
+
*/
|
|
80
|
+
export declare function amendSlotRule(writer: TasraWriteClient, chain: TasraChainClient, a: AmendSlotRuleArgs): Promise<AmendSlotRuleResult>;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Read a slot's rule-amendment state, and drive one amendment end to end.
|
|
2
|
+
//
|
|
3
|
+
// Amending a rule is five steps owned by three parties: the rule ADMIN proposes the new salted
|
|
4
|
+
// commitment on chain; the rule text and salt are DELIVERED to each keeper (by the creator, a
|
|
5
|
+
// creator delegate, or the admin); the keepers vote ADOPTION themselves once they hold it; the
|
|
6
|
+
// GUARDIAN may veto or endorse (endorsing waives the remaining delay); and anyone ACTIVATES once
|
|
7
|
+
// chain time has passed `notBefore` and the votes reach `ruleAdoptionThreshold` (n - k + 1).
|
|
8
|
+
//
|
|
9
|
+
// `amendSlotRule` is resumable: every step first reads the chain, so a run interrupted after the
|
|
10
|
+
// proposal (or after activation) picks up where the chain is instead of proposing twice. It never
|
|
11
|
+
// activates on a timer alone - activation needs OBSERVED votes and OBSERVED chain time.
|
|
12
|
+
import { requireAddress } from './deployments.js';
|
|
13
|
+
import { provisionRule } from './provisionRule.js';
|
|
14
|
+
import { amendmentPreflight, resolveAmendmentRule, ruleCommitment, slotAuthTypeOf, } from './write.js';
|
|
15
|
+
import { AMENDMENT_ZERO_ADDRESS, RuleAmendmentError, abortableDelay, immutableError, pendingError, readAmendmentOnChain, sameAddress, } from './ruleAmendmentCore.js';
|
|
16
|
+
import { TasraError } from '../errors.js';
|
|
17
|
+
export { RuleAmendmentError } from './ruleAmendmentCore.js';
|
|
18
|
+
/**
|
|
19
|
+
* Read a slot's active rule commitment, amendment policy and pending amendment, including the
|
|
20
|
+
* keeper adoption votes and the votes activation needs.
|
|
21
|
+
* @param chain Reader for the deployment that owns the slot.
|
|
22
|
+
* @param slotId Slot to read; a missing or cancelled slot throws `RuleAmendmentError` code `no-slot`.
|
|
23
|
+
*/
|
|
24
|
+
export async function readRuleAmendment(chain, slotId) {
|
|
25
|
+
const s = await readAmendmentOnChain(chain.client.readContract, requireAddress(chain.addresses, 'KeyRegistry'), slotId, { withVotes: true });
|
|
26
|
+
const amendable = !sameAddress(s.admin, AMENDMENT_ZERO_ADDRESS);
|
|
27
|
+
const hasGuardian = !sameAddress(s.guardian, AMENDMENT_ZERO_ADDRESS);
|
|
28
|
+
return {
|
|
29
|
+
ruleCommitment: s.ruleCommitment,
|
|
30
|
+
ruleVersion: s.ruleVersion,
|
|
31
|
+
authType: slotAuthTypeOf(s.authOrdinal),
|
|
32
|
+
policy: amendable ? { admin: s.admin, ...(hasGuardian ? { guardian: s.guardian } : {}), timelockSecs: s.timelockSecs } : null,
|
|
33
|
+
pending: s.pending
|
|
34
|
+
? {
|
|
35
|
+
version: s.pending.version,
|
|
36
|
+
ruleCommitment: s.pending.ruleCommitment,
|
|
37
|
+
notBefore: s.pending.notBefore,
|
|
38
|
+
adoptions: s.pending.adoptions ?? 0,
|
|
39
|
+
needed: s.pending.needed ?? 0,
|
|
40
|
+
}
|
|
41
|
+
: null,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Poll spacing for keeper adoption and chain time. */
|
|
45
|
+
const AMENDMENT_POLL_MS = 5_000;
|
|
46
|
+
/**
|
|
47
|
+
* Amend a slot's rule end to end: propose (as the rule admin), deliver the rule to the keepers,
|
|
48
|
+
* wait for their adoption votes, endorse when a guardian client is given, wait for chain time to
|
|
49
|
+
* pass `notBefore`, activate, and confirm the active commitment on chain.
|
|
50
|
+
*
|
|
51
|
+
* Resumable: a proposal already pending with this rule is not proposed again, and a rule already
|
|
52
|
+
* active returns at once. Every refusal it can know in advance is raised before anything is signed.
|
|
53
|
+
* It never activates on a timer alone: activation needs the observed votes AND chain time.
|
|
54
|
+
*
|
|
55
|
+
* An amendable rule means whoever holds the admin key can change who may sign with this key,
|
|
56
|
+
* without changing the key. Keep the admin key as safe as the slot itself. The guardian can veto
|
|
57
|
+
* during the delay; without a guardian nobody can. Slots created without a rule admin can never
|
|
58
|
+
* become amendable.
|
|
59
|
+
* @param writer Write client of the slot's rule admin; it proposes and activates.
|
|
60
|
+
* @param chain Reader for the deployment that owns the slot.
|
|
61
|
+
* @param a The amendment, its deliverer, an optional guardian client and wait controls.
|
|
62
|
+
*/
|
|
63
|
+
export async function amendSlotRule(writer, chain, a) {
|
|
64
|
+
const what = 'amendSlotRule';
|
|
65
|
+
const { slotId, signal } = a;
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
for (const [field, value] of [['slotId', a.slotId], ['ruleSalt', a.ruleSalt]]) {
|
|
68
|
+
if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(value))
|
|
69
|
+
throw new TasraError(`${what}: ${field} must be 0x-prefixed 32-byte hex`);
|
|
70
|
+
}
|
|
71
|
+
if (a.maxWaitMs !== undefined && (!Number.isSafeInteger(a.maxWaitMs) || a.maxWaitMs < 1)) {
|
|
72
|
+
throw new TasraError(`${what}: maxWaitMs must be a positive integer, got ${String(a.maxWaitMs)}`);
|
|
73
|
+
}
|
|
74
|
+
const rule = await resolveAmendmentRule(a, what);
|
|
75
|
+
const commitment = ruleCommitment(a.ruleSalt, rule);
|
|
76
|
+
const keyRegistry = requireAddress(chain.addresses, 'KeyRegistry');
|
|
77
|
+
const state = await readAmendmentOnChain(chain.client.readContract, keyRegistry, slotId, { withVotes: true });
|
|
78
|
+
// ── pre-flight: everything knowable before the first signature ──
|
|
79
|
+
if (sameAddress(state.ruleCommitment, commitment) && !state.pending) {
|
|
80
|
+
return { version: state.ruleVersion, ruleCommitment: commitment };
|
|
81
|
+
}
|
|
82
|
+
if (sameAddress(state.admin, AMENDMENT_ZERO_ADDRESS))
|
|
83
|
+
throw immutableError(slotId);
|
|
84
|
+
if (!sameAddress(a.deliverer.address, state.creator) && !sameAddress(a.deliverer.address, state.admin)) {
|
|
85
|
+
throw new RuleAmendmentError('not-deliverer', slotId, `${what}: the deliverer ${a.deliverer.address} is neither the creator ${state.creator} nor the rule admin ` +
|
|
86
|
+
`${state.admin} of slot ${slotId}, so no keeper would store the rule it signs`);
|
|
87
|
+
}
|
|
88
|
+
if (a.guardian && (sameAddress(state.guardian, AMENDMENT_ZERO_ADDRESS) || !sameAddress(a.guardian.address, state.guardian))) {
|
|
89
|
+
throw new RuleAmendmentError('not-guardian', slotId, `${what}: the guardian client signs as ${a.guardian.address}, but slot ${slotId} has rule guardian ` +
|
|
90
|
+
`${sameAddress(state.guardian, AMENDMENT_ZERO_ADDRESS) ? 'none' : state.guardian}`, { hasGuardian: !sameAddress(state.guardian, AMENDMENT_ZERO_ADDRESS) });
|
|
91
|
+
}
|
|
92
|
+
if (state.pending && !sameAddress(state.pending.ruleCommitment, commitment))
|
|
93
|
+
throw pendingError(slotId, state);
|
|
94
|
+
await amendmentPreflight(rule, state, slotId, what);
|
|
95
|
+
// ── 1. propose, unless this exact proposal is already pending (a resumed run) ──
|
|
96
|
+
let proposeTx;
|
|
97
|
+
if (!state.pending) {
|
|
98
|
+
const proposed = await writer.proposeRuleUpdate(a);
|
|
99
|
+
proposeTx = proposed.txHash;
|
|
100
|
+
a.onPhase?.('proposed', proposed);
|
|
101
|
+
}
|
|
102
|
+
const deadline = Date.now() + (a.maxWaitMs ?? state.timelockSecs * 1000 + 600_000);
|
|
103
|
+
const checkDeadline = (phase) => {
|
|
104
|
+
signal?.throwIfAborted();
|
|
105
|
+
if (Date.now() >= deadline) {
|
|
106
|
+
throw new RuleAmendmentError('timeout', slotId, `${what}: slot ${slotId} did not reach '${phase}' within maxWaitMs; the amendment stays pending - ` +
|
|
107
|
+
'call amendSlotRule again with the same rule to resume', { phase });
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
/** Re-read the amendment; `null` means it is no longer pending because THIS rule is active. */
|
|
111
|
+
const ownPending = async () => {
|
|
112
|
+
const st = await readRuleAmendment(chain, slotId);
|
|
113
|
+
if (st.pending && sameAddress(st.pending.ruleCommitment, commitment))
|
|
114
|
+
return st.pending;
|
|
115
|
+
if (!st.pending && sameAddress(st.ruleCommitment, commitment))
|
|
116
|
+
return null;
|
|
117
|
+
throw new RuleAmendmentError('pending-changed', slotId, `${what}: the pending amendment of slot ${slotId} is no longer this rule (vetoed, superseded or activated ` +
|
|
118
|
+
'differently); re-read readRuleAmendment before proposing again', st.pending ? { pendingVersion: st.pending.version, pendingCommitment: st.pending.ruleCommitment } : {});
|
|
119
|
+
};
|
|
120
|
+
// ── 2. deliver ──
|
|
121
|
+
checkDeadline('delivered');
|
|
122
|
+
let results;
|
|
123
|
+
try {
|
|
124
|
+
results = (await provisionRule(chain, { slotId, rule, ruleSalt: a.ruleSalt, signer: a.deliverer, expect: 'pending', signal })).results;
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
if (e instanceof RuleAmendmentError)
|
|
128
|
+
throw e;
|
|
129
|
+
const partial = e.results;
|
|
130
|
+
if (!partial)
|
|
131
|
+
throw e;
|
|
132
|
+
// Activation needs only n - k + 1 keepers holding the rule; enough is enough.
|
|
133
|
+
const holding = partial.filter(r => r.ok && r.pending === true).length;
|
|
134
|
+
const pend = await ownPending();
|
|
135
|
+
if (pend && holding < pend.needed)
|
|
136
|
+
throw e;
|
|
137
|
+
results = partial;
|
|
138
|
+
}
|
|
139
|
+
a.onPhase?.('delivered', results);
|
|
140
|
+
// ── 3. wait for keeper adoption ──
|
|
141
|
+
let activated = false;
|
|
142
|
+
for (;;) {
|
|
143
|
+
checkDeadline('adopted');
|
|
144
|
+
const pend = await ownPending();
|
|
145
|
+
if (!pend) {
|
|
146
|
+
activated = true;
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
if (pend.adoptions >= pend.needed) {
|
|
150
|
+
a.onPhase?.('adopted', { adoptions: pend.adoptions, needed: pend.needed });
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
await abortableDelay(AMENDMENT_POLL_MS, signal);
|
|
154
|
+
}
|
|
155
|
+
// ── 4. endorse (waives the remaining delay) ──
|
|
156
|
+
if (!activated && a.guardian) {
|
|
157
|
+
const tx = await a.guardian.endorseRuleUpdate(slotId);
|
|
158
|
+
a.onPhase?.('endorsed', tx);
|
|
159
|
+
}
|
|
160
|
+
// ── 5. activate once chain time AND votes allow it ──
|
|
161
|
+
let activateTx;
|
|
162
|
+
while (!activated) {
|
|
163
|
+
checkDeadline('activated');
|
|
164
|
+
// Re-read every round: an endorsement moves `notBefore`.
|
|
165
|
+
const pend = await ownPending();
|
|
166
|
+
if (!pend)
|
|
167
|
+
break;
|
|
168
|
+
const block = await chain.client.getBlock({ blockTag: 'latest' });
|
|
169
|
+
if (Number(block.timestamp) >= pend.notBefore && pend.adoptions >= pend.needed) {
|
|
170
|
+
try {
|
|
171
|
+
activateTx = await writer.activateRuleUpdate(slotId);
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
// Activation is permissionless: another party may have won the race since the read.
|
|
175
|
+
if (e instanceof RuleAmendmentError && e.code === 'no-pending' && (await ownPending()) === null)
|
|
176
|
+
break;
|
|
177
|
+
throw e;
|
|
178
|
+
}
|
|
179
|
+
a.onPhase?.('activated', activateTx);
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
await abortableDelay(AMENDMENT_POLL_MS, signal);
|
|
183
|
+
}
|
|
184
|
+
// ── 6. confirm the active commitment ──
|
|
185
|
+
const slot = await chain.readers.keyRegistry.getKeySlot(slotId);
|
|
186
|
+
if (!sameAddress(slot.ruleCommitment, commitment)) {
|
|
187
|
+
throw new RuleAmendmentError('not-activated', slotId, `${what}: slot ${slotId} enforces commitment ${slot.ruleCommitment} after activation, not ${commitment}`);
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
version: Number(slot.ruleVersion),
|
|
191
|
+
ruleCommitment: commitment,
|
|
192
|
+
...(proposeTx ? { proposeTx } : {}),
|
|
193
|
+
...(activateTx ? { activateTx } : {}),
|
|
194
|
+
};
|
|
195
|
+
}
|