@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,958 @@
|
|
|
1
|
+
import { requireRule } from './ruleInput.js';
|
|
2
|
+
import { networkNameForChain, resolveNetworkProfile, assertEurcFaucetAllowed } from './networks.js';
|
|
3
|
+
import { SlotCommitmentExpiredError } from './commitmentRecovery.js';
|
|
4
|
+
import { requestSlotSeed } from './slotSeed.js';
|
|
5
|
+
// Client-side ON-CHAIN WRITE path: the client is a sovereign actor with its own
|
|
6
|
+
// EVM account that signs its own transactions - no relayer/provisioner.
|
|
7
|
+
//
|
|
8
|
+
// Slot creation is permissionless (KeyRegistry.createKeySlot* has no owner gate;
|
|
9
|
+
// the creator is just msg.sender) and fee-less (only gas), so a fresh
|
|
10
|
+
// funded account can create and own a slot. This client signs:
|
|
11
|
+
// - createKeySlot(Filtered) - create + own a slot (committee drawn on-chain,
|
|
12
|
+
// nodes auto-DKG),
|
|
13
|
+
// - TSRA approve + Settlement.fund - prepay the slot's metered usage,
|
|
14
|
+
// and exposes plain ETH/TSRA transfers (so a funded key can also back a faucet).
|
|
15
|
+
//
|
|
16
|
+
// Lives in the `@t3foundry/tasra-sdk/chain` subpath (viem). Browser + Node (uses
|
|
17
|
+
// globalThis.crypto for slot/salt randomness; no Node-only APIs).
|
|
18
|
+
import { createPublicClient, createWalletClient, defineChain, http, concat, encodeFunctionData, keccak256, parseEventLogs, toHex, } from 'viem';
|
|
19
|
+
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
|
|
20
|
+
import { createTasraChainClient } from './client.js';
|
|
21
|
+
import { createRegisteredRelaySubmitter } from './registeredRelay.js';
|
|
22
|
+
import { describeRevert } from './revertReason.js';
|
|
23
|
+
import { canonicalize, isOid4vpRule } from '../auth/oid4vp.js';
|
|
24
|
+
import { isOauthEnvelope, loadRego } from '../auth/rego.js';
|
|
25
|
+
import { TasraError } from '../errors.js';
|
|
26
|
+
import { keyRegistryAbi } from './abis/keyRegistry.js';
|
|
27
|
+
import { RuleAmendmentError, immutableError, pendingError, readAmendmentOnChain, sameAddress, } from './ruleAmendmentCore.js';
|
|
28
|
+
import { nodeRegistryAbi } from './abis/nodeRegistry.js';
|
|
29
|
+
/**
|
|
30
|
+
* Return whether active operators include both tagged keepers and other roles, making an unfiltered draw include non-keepers.
|
|
31
|
+
* @param active Total active operator count.
|
|
32
|
+
* @param tagged Active operator count carrying the keeper tag.
|
|
33
|
+
*/
|
|
34
|
+
export function untaggedDrawSeatsNonKeepers(active, tagged) {
|
|
35
|
+
return tagged > 0n && tagged < active;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Return whether a FILTERED draw cannot be seated: fewer tagged-ACTIVE candidates than the
|
|
39
|
+
* committee size the slot asks for. This is the shortfall `KeyRegistry` reverts
|
|
40
|
+
* `InsufficientFilteredPool(have, need)` on, judged on the tag filter alone.
|
|
41
|
+
* @param candidates Active operators carrying EVERY required tag (KeyRegistry takes the smallest
|
|
42
|
+
* tagged count when a slot requires several).
|
|
43
|
+
* @param n Committee size the slot asks for.
|
|
44
|
+
*/
|
|
45
|
+
export function filteredDrawCannotSeat(candidates, n) {
|
|
46
|
+
// A malformed threshold is not a pool shortfall. n = 0, a fraction or a non-number is the
|
|
47
|
+
// contract's `InvalidThreshold` to report; claiming a pool problem would send the caller to
|
|
48
|
+
// look at the operator set for a mistake that is in the arguments.
|
|
49
|
+
if (!Number.isSafeInteger(n) || n <= 0)
|
|
50
|
+
return false;
|
|
51
|
+
return candidates < BigInt(n);
|
|
52
|
+
}
|
|
53
|
+
import { settlementAbi } from './abis/settlement.js';
|
|
54
|
+
import { tasraTokenAbi } from './abis/tasraToken.js';
|
|
55
|
+
import { thresholdRandomBeaconAbi } from './abis/thresholdRandomBeacon.js';
|
|
56
|
+
import { bondingCurveAbi } from './abis/bondingCurve.js';
|
|
57
|
+
import { mockEurcAbi } from './abis/mockEurc.js';
|
|
58
|
+
import { treasuryAbi } from './abis/treasury.js';
|
|
59
|
+
import { tasraVestingVaultAbi } from './abis/tasraVestingVault.js';
|
|
60
|
+
import { DEFAULT_CHAIN_ID, requireAddress, requireVaultAddress, } from './deployments.js';
|
|
61
|
+
/** `KeyRegistry.Mode` enum order. */
|
|
62
|
+
const SLOT_MODES = ['frost', 'bls', 'tecdsa', 'bls-bn254', 'tecdsa-p256'];
|
|
63
|
+
function modeIndex(mode) {
|
|
64
|
+
const i = SLOT_MODES.indexOf(mode);
|
|
65
|
+
if (i < 0)
|
|
66
|
+
throw new TasraError(`createSlot: unknown mode ${JSON.stringify(mode)} (expected ${SLOT_MODES.join(' | ')})`);
|
|
67
|
+
return i;
|
|
68
|
+
}
|
|
69
|
+
/** `KeyRegistry.AuthType` enum order - APPEND-only on-chain, so never reorder. */
|
|
70
|
+
const SLOT_AUTH_TYPES = ['unspecified', 'oid4vp', 'oauth'];
|
|
71
|
+
function authTypeIndex(auth) {
|
|
72
|
+
if (auth === undefined)
|
|
73
|
+
return 0;
|
|
74
|
+
const i = SLOT_AUTH_TYPES.indexOf(auth);
|
|
75
|
+
if (i < 0) {
|
|
76
|
+
throw new TasraError(`createSlot: unknown authType ${JSON.stringify(auth)} (expected ${SLOT_AUTH_TYPES.join(' | ')})`);
|
|
77
|
+
}
|
|
78
|
+
return i;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Map a `KeyRegistry.AuthType` ordinal read from chain back to its label.
|
|
82
|
+
* @param ordinal The `auth` field of `KeyRegistry.getKeySlot`.
|
|
83
|
+
*/
|
|
84
|
+
export function slotAuthTypeOf(ordinal) {
|
|
85
|
+
const auth = SLOT_AUTH_TYPES[ordinal];
|
|
86
|
+
if (auth === undefined) {
|
|
87
|
+
throw new TasraError(`unknown KeyRegistry.AuthType ordinal ${ordinal} (this SDK knows ${SLOT_AUTH_TYPES.join(' | ')}); upgrade @t3foundry/tasra-sdk`);
|
|
88
|
+
}
|
|
89
|
+
return auth;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Resolve the rule a creation commits to, and refuse - before any chain call - an envelope the
|
|
93
|
+
* network would strand: one on a slot not declared `authType: 'oauth'`, or one no keeper would
|
|
94
|
+
* store. An OID4VP rule on an `oauth` slot stays allowed (the restriction is one-directional).
|
|
95
|
+
*/
|
|
96
|
+
async function creationRule(args, what) {
|
|
97
|
+
let rule;
|
|
98
|
+
const policy = args.oauthPolicy;
|
|
99
|
+
if (policy !== undefined) {
|
|
100
|
+
if (args.rule !== undefined)
|
|
101
|
+
throw new TasraError(`${what}: pass either \`rule\` or \`oauthPolicy\`, not both`);
|
|
102
|
+
if (args.authType !== 'oauth')
|
|
103
|
+
throw new TasraError(`${what}: an \`oauthPolicy\` slot requires authType: 'oauth'`);
|
|
104
|
+
rule = (await loadRego()).pack(policy);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
rule = requireRule(args);
|
|
108
|
+
}
|
|
109
|
+
if (!isOauthEnvelope(rule))
|
|
110
|
+
return rule;
|
|
111
|
+
if (args.authType !== 'oauth') {
|
|
112
|
+
throw new TasraError(`${what}: a kk_oauth policy envelope requires authType: 'oauth' — keepers refuse an envelope on any other slot`);
|
|
113
|
+
}
|
|
114
|
+
const lint = (await loadRego()).lint(rule);
|
|
115
|
+
if (!lint.admissible)
|
|
116
|
+
throw new TasraError(`${what}: keepers would not store this envelope: ${lint.admissionError ?? 'not admissible'}`);
|
|
117
|
+
return rule;
|
|
118
|
+
}
|
|
119
|
+
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
|
|
120
|
+
/** Refuse a value that is not 0x-prefixed 32-byte hex, before any chain call. */
|
|
121
|
+
function requireBytes32(value, field, what) {
|
|
122
|
+
if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(value)) {
|
|
123
|
+
throw new TasraError(`${what}: ${field} must be 0x-prefixed 32-byte hex`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Resolve the rule string an amendment commits to: an `oauthPolicy` is packed into the canonical
|
|
128
|
+
* `kk_oauth` envelope, a `rule` is taken as given. No chain call; the auth-type check needs the
|
|
129
|
+
* slot and runs in {@link amendmentPreflight}.
|
|
130
|
+
* @param a Amendment arguments carrying exactly one of `rule` and `oauthPolicy`.
|
|
131
|
+
* @param what Caller name used in error messages.
|
|
132
|
+
*/
|
|
133
|
+
export async function resolveAmendmentRule(a, what) {
|
|
134
|
+
const policy = a.oauthPolicy;
|
|
135
|
+
const hasRule = a.rule !== undefined;
|
|
136
|
+
if (policy !== undefined) {
|
|
137
|
+
if (hasRule)
|
|
138
|
+
throw new TasraError(`${what}: pass either \`rule\` or \`oauthPolicy\`, not both`);
|
|
139
|
+
try {
|
|
140
|
+
return (await loadRego()).pack(policy);
|
|
141
|
+
}
|
|
142
|
+
catch (e) {
|
|
143
|
+
throw new RuleAmendmentError('not-admissible', a.slotId, `${what}: the oauthPolicy cannot be packed into a kk_oauth envelope: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (!hasRule && !('dcqlRule' in a))
|
|
147
|
+
throw new TasraError(`${what}: pass either \`rule\` or \`oauthPolicy\``);
|
|
148
|
+
return requireRule(a);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Refuse, before signing, an amendment rule the slot's keepers would never store: a `kk_oauth`
|
|
152
|
+
* envelope on a slot not created with `authType: 'oauth'` (`wrong-auth-type`), or an envelope
|
|
153
|
+
* that fails the network's gate (`not-admissible`). An OID4VP rule on an `oauth` slot stays allowed.
|
|
154
|
+
* @param rule Resolved amendment rule.
|
|
155
|
+
* @param state The slot's amendment state read from chain.
|
|
156
|
+
* @param slotId Slot being amended.
|
|
157
|
+
* @param what Caller name used in error messages.
|
|
158
|
+
*/
|
|
159
|
+
export async function amendmentPreflight(rule, state, slotId, what) {
|
|
160
|
+
if (!isOauthEnvelope(rule))
|
|
161
|
+
return;
|
|
162
|
+
if (state.authOrdinal !== SLOT_AUTH_TYPES.indexOf('oauth')) {
|
|
163
|
+
const label = SLOT_AUTH_TYPES[state.authOrdinal] ?? `ordinal ${state.authOrdinal}`;
|
|
164
|
+
throw new RuleAmendmentError('wrong-auth-type', slotId, `${what}: a kk_oauth policy envelope requires authType: 'oauth' — keepers refuse an envelope on any other slot, ` +
|
|
165
|
+
`and slot ${slotId} was created with authType '${label}'`);
|
|
166
|
+
}
|
|
167
|
+
let lint;
|
|
168
|
+
try {
|
|
169
|
+
lint = (await loadRego()).lint(rule);
|
|
170
|
+
}
|
|
171
|
+
catch (e) {
|
|
172
|
+
throw new RuleAmendmentError('not-admissible', slotId, `${what}: keepers would not store this envelope: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
173
|
+
}
|
|
174
|
+
if (!lint.admissible) {
|
|
175
|
+
throw new RuleAmendmentError('not-admissible', slotId, `${what}: keepers would not store this envelope: ${lint.admissionError ?? 'not admissible'}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* salted DCQL rule commitment: `keccak256(DOMAIN || salt || rule)`.
|
|
180
|
+
*
|
|
181
|
+
* Must byte-for-byte match the reference rule-commitment function - the keeper
|
|
182
|
+
* re-derives this to verify-fill the rule and the verifier re-derives it to
|
|
183
|
+
* authenticate a fetched one, so a mismatch here means every keeper refuses the
|
|
184
|
+
* rule and the slot stays fail-closed. Cross-checked vector: salt 0x11*32 over
|
|
185
|
+
* "EmployeeOf:dept=Engineering" =
|
|
186
|
+
* 0x176e8b17e8e6b587e649754fe682f7ad6eb12f97461a295d2cfa9c92c287dfde.
|
|
187
|
+
*
|
|
188
|
+
* not the `salt` passed to createKeySlot - that is the committee-selection
|
|
189
|
+
* salt and never touches the rule.
|
|
190
|
+
*/
|
|
191
|
+
/**
|
|
192
|
+
* Wait for a receipt and reject reverted transactions. Receipt availability alone does not prove execution succeeded.
|
|
193
|
+
*/
|
|
194
|
+
async function confirmed(pub, hash, what) {
|
|
195
|
+
const receipt = await pub.waitForTransactionReceipt({ hash });
|
|
196
|
+
if (receipt.status !== 'success') {
|
|
197
|
+
throw new Error(`${what} REVERTED on chain (tx ${hash}) — the call did not take effect`);
|
|
198
|
+
}
|
|
199
|
+
return receipt;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Compute the salted rule commitment. OID4VP queries and `kk_oauth` policy envelopes use canonical JSON; other rule formats retain their exact bytes.
|
|
203
|
+
* @param ruleSalt Private 32-byte salt saved with the slot creation intent.
|
|
204
|
+
* @param rule Clear authorization rule; OID4VP queries and policy envelopes are canonicalized before hashing.
|
|
205
|
+
*/
|
|
206
|
+
export function ruleCommitment(ruleSalt, rule) {
|
|
207
|
+
// Envelope test first, like the network's grammar dispatch; both JSON grammars commit their
|
|
208
|
+
// RFC 8785 form, anything else its exact bytes.
|
|
209
|
+
const body = isOauthEnvelope(rule) || isOid4vpRule(rule) ? canonicalize(rule) : rule;
|
|
210
|
+
return keccak256(concat([toHex('keykeeper/rule-commitment/v1'), ruleSalt, toHex(body)]));
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Return whether the disclosed rule and salt reproduce the on-chain commitment. Invalid inputs and mismatches return false.
|
|
214
|
+
* @param rule Clear rule received for the slot.
|
|
215
|
+
* @param ruleSalt Private salt associated with that rule commitment.
|
|
216
|
+
* @param onChainRuleCommitment Commitment read from the on-chain slot.
|
|
217
|
+
*/
|
|
218
|
+
export function verifyRuleCommitment(rule, ruleSalt, onChainRuleCommitment) {
|
|
219
|
+
try {
|
|
220
|
+
return ruleCommitment(ruleSalt, rule) === onChainRuleCommitment;
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/** Fresh 0x-prefixed 32-byte private key for a new sovereign client account. */
|
|
227
|
+
export function generateClientKey() {
|
|
228
|
+
return generatePrivateKey();
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Check whether the RPC host permits the legacy loopback chain-ID fallback.
|
|
232
|
+
*/
|
|
233
|
+
function isLoopbackRpc(rpcUrl) {
|
|
234
|
+
try {
|
|
235
|
+
const host = new URL(rpcUrl).hostname;
|
|
236
|
+
return (host === 'localhost' ||
|
|
237
|
+
host.endsWith('.localhost') ||
|
|
238
|
+
host === '127.0.0.1' ||
|
|
239
|
+
host === '0.0.0.0' ||
|
|
240
|
+
host === '[::1]' ||
|
|
241
|
+
host === '::1');
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
function random32() {
|
|
248
|
+
const b = new Uint8Array(32);
|
|
249
|
+
(globalThis.crypto).getRandomValues(b);
|
|
250
|
+
return `0x${Array.from(b, x => x.toString(16).padStart(2, '0')).join('')}`;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Create an account-bound client for slot lifecycle, settlement and token transactions. Use deployed addresses and the chain ID from a tasra-releases network manifest.
|
|
254
|
+
* @param cfg RPC, manifest contract addresses, chain ID and an explicit signing account.
|
|
255
|
+
*/
|
|
256
|
+
export function createTasraWriteClient(cfg) {
|
|
257
|
+
const chainId = cfg.chainId ?? cfg.wallet?.chain?.id;
|
|
258
|
+
if (chainId === undefined && !isLoopbackRpc(cfg.rpcUrl)) {
|
|
259
|
+
throw new TasraError(`createTasraWriteClient: chainId is required for ${cfg.rpcUrl}. ` +
|
|
260
|
+
'Use the chain ID from the tasra-releases manifest or a chain-bound wallet.');
|
|
261
|
+
}
|
|
262
|
+
const chain = defineChain({
|
|
263
|
+
id: chainId ?? DEFAULT_CHAIN_ID,
|
|
264
|
+
name: 'keykeeper',
|
|
265
|
+
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
|
|
266
|
+
rpcUrls: { default: { http: [cfg.rpcUrl] } },
|
|
267
|
+
});
|
|
268
|
+
// Reads and receipt-waiting always go through OUR PublicClient, never the
|
|
269
|
+
// supplied wallet's transport - an injected provider is rate-limited, may be on
|
|
270
|
+
// a different node, and can be unavailable while the user's tab is backgrounded.
|
|
271
|
+
const pub = createPublicClient({ chain, transport: http(cfg.rpcUrl) });
|
|
272
|
+
const addr = cfg.addresses;
|
|
273
|
+
const relay = cfg.relay;
|
|
274
|
+
let lastRelay;
|
|
275
|
+
let registeredRelay;
|
|
276
|
+
async function relayForward(to, data, label) {
|
|
277
|
+
if (!relay)
|
|
278
|
+
throw new Error('relayForward: no relay configured');
|
|
279
|
+
registeredRelay ??= createRegisteredRelaySubmitter(createTasraChainClient({ rpcUrl: cfg.rpcUrl, addresses: cfg.addresses, chainId: chain.id }), relay, wallet);
|
|
280
|
+
lastRelay = await registeredRelay.submit(to, data, label);
|
|
281
|
+
return lastRelay;
|
|
282
|
+
}
|
|
283
|
+
/** One door for every sender-bound write: the relayer when configured, else the local key. */
|
|
284
|
+
async function sendCall(address, abi, functionName, args, label) {
|
|
285
|
+
const call = { abi, functionName, args };
|
|
286
|
+
if (relay)
|
|
287
|
+
return (await relayForward(address, encodeFunctionData(call), label)).txHash;
|
|
288
|
+
return wallet.writeContract({ address, ...call });
|
|
289
|
+
}
|
|
290
|
+
const supplied = cfg.wallet;
|
|
291
|
+
let wallet;
|
|
292
|
+
let account;
|
|
293
|
+
if (supplied) {
|
|
294
|
+
if (!supplied.account) {
|
|
295
|
+
throw new Error('createTasraWriteClient: the supplied `wallet` has no account bound — ' +
|
|
296
|
+
'pass a client from wagmi getWalletClient() or createWalletClient({account, chain, transport})');
|
|
297
|
+
}
|
|
298
|
+
wallet = supplied;
|
|
299
|
+
account = supplied.account;
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
if (!cfg.privateKey) {
|
|
303
|
+
throw new Error('createTasraWriteClient: pass either `privateKey` or `wallet`');
|
|
304
|
+
}
|
|
305
|
+
account = privateKeyToAccount(cfg.privateKey);
|
|
306
|
+
wallet = createWalletClient({ account, chain, transport: http(cfg.rpcUrl) });
|
|
307
|
+
}
|
|
308
|
+
// A dev/test RPC (besu/anvil) under load can transiently return a STALE nonce for
|
|
309
|
+
// getTransactionCount - e.g. 0 for an account already at 64 - and viem then builds
|
|
310
|
+
// a tx with that nonce, which the node rejects with "nonce too low". This is safe
|
|
311
|
+
// to retry: the tx was rejected BEFORE entering the mempool (no double-submit
|
|
312
|
+
// risk), and since no nonceManager is attached, each retry re-derives the nonce
|
|
313
|
+
// fresh, so a re-run a moment later clears the glitch. Bounded + backoff; only
|
|
314
|
+
// nonce-too-low retries - every other error throws immediately.
|
|
315
|
+
//
|
|
316
|
+
// local-KEY PATH only. Two reasons a supplied wallet must not get this:
|
|
317
|
+
// 1. A browser wallet manages its own nonce, so a retry would re-enter the
|
|
318
|
+
// signing flow and surface as a SECOND signature prompt for one action -
|
|
319
|
+
// which reads to the user as a double-spend attempt.
|
|
320
|
+
// 2. It monkey-patches the client, and that client belongs to the caller.
|
|
321
|
+
if (!supplied) {
|
|
322
|
+
const NONCE_TOO_LOW = /nonce too low|nonce provided for the transaction is lower/i;
|
|
323
|
+
const withNonceRetry = async (op) => {
|
|
324
|
+
let lastErr;
|
|
325
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
326
|
+
try {
|
|
327
|
+
return await op();
|
|
328
|
+
}
|
|
329
|
+
catch (e) {
|
|
330
|
+
lastErr = e;
|
|
331
|
+
if (!NONCE_TOO_LOW.test(String(e?.message ?? e)))
|
|
332
|
+
throw e;
|
|
333
|
+
await new Promise(r => setTimeout(r, 250 * (attempt + 1)));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
throw lastErr;
|
|
337
|
+
};
|
|
338
|
+
const _writeContract = wallet.writeContract.bind(wallet);
|
|
339
|
+
wallet.writeContract = ((args) => withNonceRetry(() => _writeContract(args)));
|
|
340
|
+
const _sendTransaction = wallet.sendTransaction.bind(wallet);
|
|
341
|
+
wallet.sendTransaction = ((args) => withNonceRetry(() => _sendTransaction(args)));
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The contract's own policy preconditions, checked BEFORE signing.
|
|
345
|
+
*
|
|
346
|
+
* Shared by every path that writes a policy so they reject identically. Failing
|
|
347
|
+
* here costs nothing; discovering it as a revert costs the creation on the
|
|
348
|
+
* atomic paths, and on the legacy path costs the slot its amendability forever.
|
|
349
|
+
*/
|
|
350
|
+
async function validateRulePolicy(policy) {
|
|
351
|
+
const guardian = policy.guardian ?? ZERO_ADDRESS;
|
|
352
|
+
if (guardian.toLowerCase() === policy.admin.toLowerCase()) {
|
|
353
|
+
throw new Error('rule policy: guardian must differ from admin');
|
|
354
|
+
}
|
|
355
|
+
if (guardian === ZERO_ADDRESS) {
|
|
356
|
+
// READ the floor from the contract; never hardcode it. `MIN_RULE_TIMELOCK` is a
|
|
357
|
+
// public constant, so duplicating it here would be a second source of truth that
|
|
358
|
+
// drifts silently the day the contract changes - and it would drift in the
|
|
359
|
+
// dangerous direction, accepting a policy the chain then rejects.
|
|
360
|
+
const min = (await pub.readContract({
|
|
361
|
+
address: requireAddress(addr, 'KeyRegistry'),
|
|
362
|
+
abi: keyRegistryAbi,
|
|
363
|
+
functionName: 'MIN_RULE_TIMELOCK',
|
|
364
|
+
}));
|
|
365
|
+
if (BigInt(policy.timelockSecs) < BigInt(min)) {
|
|
366
|
+
throw new Error(`rule policy: a slot with no guardian needs a timelock of at least ${String(min)}s ` +
|
|
367
|
+
`(MIN_RULE_TIMELOCK), got ${policy.timelockSecs}s`);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return guardian;
|
|
371
|
+
}
|
|
372
|
+
/** The `RulePolicy` tuple the contract expects; all-zero means "immutable". */
|
|
373
|
+
async function policyTuple(policy) {
|
|
374
|
+
if (!policy)
|
|
375
|
+
return { admin: ZERO_ADDRESS, guardian: ZERO_ADDRESS, timelock: 0 };
|
|
376
|
+
const guardian = await validateRulePolicy(policy);
|
|
377
|
+
return { admin: policy.admin, guardian, timelock: policy.timelockSecs };
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* A one-shot creation reverts `CommitRevealRequired()` when the registry has `requireCommitReveal`
|
|
381
|
+
* set, which every production genesis does. The remedy is a different call rather than a different
|
|
382
|
+
* argument, so name it here: the raw revert says nothing about `createSlotCommitReveal`.
|
|
383
|
+
*/
|
|
384
|
+
function rethrowCommitRevealRequired(e) {
|
|
385
|
+
const named = describeRevert(e) ?? '';
|
|
386
|
+
if (`${named} ${String(e?.message ?? '')}`.includes('CommitRevealRequired')) {
|
|
387
|
+
throw new Error('createSlot: this deployment requires commit-reveal creation (KeyRegistry.requireCommitReveal is set) — ' +
|
|
388
|
+
'use createSlotCommitReveal(), which commits the parameters and reveals once the beacon has advanced', { cause: e });
|
|
389
|
+
}
|
|
390
|
+
throw e;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Resolve keeper-selection tags, rejecting BOTH ways a draw can be unseatable: an unfiltered
|
|
394
|
+
* draw on a deployment whose active set holds non-keeper roles, and a FILTERED draw asking for
|
|
395
|
+
* more of a tag than the active set carries.
|
|
396
|
+
*/
|
|
397
|
+
async function resolveDrawTags(tags, n) {
|
|
398
|
+
const chosen = tags ?? ['keykeeper'];
|
|
399
|
+
// The candidate count KeyRegistry judges a shortfall on: the candidate-array length for these
|
|
400
|
+
// tags. ONE read, no per-operator loop - the same cost at 15 operators or 10,000 - and it does
|
|
401
|
+
// not depend on the draw seed, so this never has to guess which committee the real draw picks.
|
|
402
|
+
// ⚠ Returns null rather than trusting the decode: the caller compares it against n with a
|
|
403
|
+
// BigInt comparison, and `undefined < 5n` is a TypeError, not false — so a probe that comes
|
|
404
|
+
// back in any other shape would crash a create instead of quietly declining to judge it.
|
|
405
|
+
const candidatesFor = async (tagHashes) => {
|
|
406
|
+
const keyRegistry = requireAddress(addr, 'KeyRegistry');
|
|
407
|
+
const nodeRegistry = addr.NodeRegistry ??
|
|
408
|
+
await pub.readContract({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'nodeRegistry' });
|
|
409
|
+
// Read back through `unknown`: the abi TYPES this as a 3-tuple, and that type is exactly what
|
|
410
|
+
// must not be trusted here — the value arrives from an RPC (or, in the unit fixtures, a mock).
|
|
411
|
+
const probe = await pub.readContract({
|
|
412
|
+
address: nodeRegistry,
|
|
413
|
+
abi: nodeRegistryAbi,
|
|
414
|
+
functionName: 'drawActive',
|
|
415
|
+
// minStake 0: this counts TAG MEMBERSHIP, not who could be drawn today. Folding stake
|
|
416
|
+
// in would turn a funding problem into a message about tags.
|
|
417
|
+
args: [tagHashes, 0n, 1, `0x${'00'.repeat(32)}`],
|
|
418
|
+
});
|
|
419
|
+
const candidates = Array.isArray(probe) ? probe[1] : undefined;
|
|
420
|
+
return typeof candidates === 'bigint' ? candidates : null;
|
|
421
|
+
};
|
|
422
|
+
if (chosen.length > 0) {
|
|
423
|
+
const hashes = chosen.map(t => keccak256(toHex(t)));
|
|
424
|
+
// ⚠⚠ THE TAGGED PATH USED TO RETURN HERE WITHOUT LOOKING AT THE POOL AT ALL, and it is the
|
|
425
|
+
// DEFAULT path, so the commonest create had no pre-send check while the rare untagged one
|
|
426
|
+
// did. Measured 2026-09-29: a caller sized n from the keepers answering HTTP, one of the
|
|
427
|
+
// five was unbonding, and `revealKeySlot` reverted `InsufficientFilteredPool(4, 5)`.
|
|
428
|
+
// ⚠ BEST EFFORT, DELIBERATELY: a guard that exists to improve a message must never become a
|
|
429
|
+
// new way to fail. If the pool cannot be read - no NodeRegistry in the book and a
|
|
430
|
+
// KeyRegistry that will not answer, an RPC hiccup - we send anyway and let the chain stay
|
|
431
|
+
// the authority. The untagged branch below keeps propagating, because there the read IS
|
|
432
|
+
// the safety judgement rather than a diagnostic.
|
|
433
|
+
const candidates = await candidatesFor(hashes).catch(() => null);
|
|
434
|
+
if (candidates !== null && filteredDrawCannotSeat(candidates, n)) {
|
|
435
|
+
const named = chosen.map(t => `"${t}"`).join(' + ');
|
|
436
|
+
throw new Error(`createSlot: this deployment has ${candidates} ACTIVE operator(s) carrying ${named}, ` +
|
|
437
|
+
`but the slot asks for n=${n}, so the filtered draw cannot be seated and the chain ` +
|
|
438
|
+
`would revert InsufficientFilteredPool(${candidates}, ${n}).\n` +
|
|
439
|
+
'Refused before sending because the mistake is not recoverable: with commit-reveal the ' +
|
|
440
|
+
'commit is already paid for and the shortfall surfaces only at the REVEAL, a beacon ' +
|
|
441
|
+
'epoch later.\n' +
|
|
442
|
+
'⚠ A keeper answering HTTP is not necessarily ACTIVE here: unbonding, retired and ' +
|
|
443
|
+
'slashed-to-deactivate operators keep serving while the registry excludes them from ' +
|
|
444
|
+
'every draw. Size n from this count, not from how many endpoints respond.');
|
|
445
|
+
}
|
|
446
|
+
return hashes;
|
|
447
|
+
}
|
|
448
|
+
const keyRegistry = requireAddress(addr, 'KeyRegistry');
|
|
449
|
+
const nodeRegistry = addr.NodeRegistry ??
|
|
450
|
+
(await pub.readContract({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'nodeRegistry' }));
|
|
451
|
+
const active = (await pub.readContract({
|
|
452
|
+
address: nodeRegistry, abi: nodeRegistryAbi, functionName: 'activeCount',
|
|
453
|
+
}));
|
|
454
|
+
const tagged = await candidatesFor([keccak256(toHex('keykeeper'))]);
|
|
455
|
+
// Unreadable here is NOT best-effort: on this branch the count IS the safety judgement, so
|
|
456
|
+
// declining to judge means declining to send. (Before the shared helper existed this path
|
|
457
|
+
// reached `undefined > 0n` and died as a TypeError naming nothing.)
|
|
458
|
+
if (tagged === null)
|
|
459
|
+
throw new Error('createSlot: cannot read the keeper-tagged operator count, so an untagged draw cannot be cleared as safe');
|
|
460
|
+
if (untaggedDrawSeatsNonKeepers(active, tagged)) {
|
|
461
|
+
throw new Error(`createSlot: this deployment has ${active} active operators but only ${tagged} carry the ` +
|
|
462
|
+
'`keykeeper` tag, so a draw with no tags can seat an accountant or a verifier — neither ' +
|
|
463
|
+
'of which serves a key slot. Drop `tags: []` (the default is ["keykeeper"]).\n' +
|
|
464
|
+
'Refused before sending because the mistake is not recoverable: the slot would be ' +
|
|
465
|
+
'created and paid for, and its DKG would never run.');
|
|
466
|
+
}
|
|
467
|
+
return [];
|
|
468
|
+
}
|
|
469
|
+
/** Self-sign createKeySlotFiltered. Returns the slot id once the tx is mined. */
|
|
470
|
+
async function createSlot(args) {
|
|
471
|
+
const rule = await creationRule(args, 'createSlot');
|
|
472
|
+
const slotId = args.slotId ?? random32();
|
|
473
|
+
const salt = args.salt ?? random32();
|
|
474
|
+
const ruleSalt = args.ruleSalt ?? random32();
|
|
475
|
+
// Named `…Hash` only because `ruleCommitment` is the function that derives it;
|
|
476
|
+
// this is the SALTED value the contract stores as `KeySlot.ruleCommitment`.
|
|
477
|
+
const ruleCommitmentHash = ruleCommitment(ruleSalt, rule);
|
|
478
|
+
const tags = await resolveDrawTags(args.tags, args.n);
|
|
479
|
+
const mode = modeIndex(args.mode);
|
|
480
|
+
const auth = authTypeIndex(args.authType);
|
|
481
|
+
// The `…WithPolicy` entry point is used only when there is a policy: a slot with
|
|
482
|
+
// no amendment authority is created through the original function, so the common
|
|
483
|
+
// path keeps its long-standing, widely-verified call shape.
|
|
484
|
+
if (args.exportable && args.rulePolicy) {
|
|
485
|
+
throw new Error('createSlot: `exportable` and `rulePolicy` cannot be combined — there is no single ' +
|
|
486
|
+
'entry point for both. Create an exportable slot without an amendment policy.');
|
|
487
|
+
}
|
|
488
|
+
const keyRegistry = requireAddress(addr, 'KeyRegistry');
|
|
489
|
+
const policy = args.rulePolicy ? await policyTuple(args.rulePolicy) : undefined;
|
|
490
|
+
const txHash = await (args.exportable
|
|
491
|
+
? sendCall(keyRegistry, keyRegistryAbi, 'createKeySlotFilteredExportable', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags], 'createKeySlotFilteredExportable')
|
|
492
|
+
: policy
|
|
493
|
+
? sendCall(keyRegistry, keyRegistryAbi, 'createKeySlotFilteredWithPolicy', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, policy], 'createKeySlotFilteredWithPolicy')
|
|
494
|
+
: sendCall(keyRegistry, keyRegistryAbi, 'createKeySlotFiltered', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags], 'createKeySlotFiltered')).catch(rethrowCommitRevealRequired);
|
|
495
|
+
await confirmed(pub, txHash, 'createKeySlotFiltered');
|
|
496
|
+
// ruleSalt is returned because it exists NOWHERE else: without it the rule
|
|
497
|
+
// can never be provisioned to a keeper.
|
|
498
|
+
return { slotId, txHash, ruleSalt, rule, relay: lastRelay?.txHash === txHash ? lastRelay : undefined };
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Grinding-resistant slot creation - the production default:
|
|
502
|
+
* commit the params, request an accountant seed, then reveal+create. Falls back
|
|
503
|
+
* to the beacon-epoch wait when a usable seed is unavailable. Needs a beacon
|
|
504
|
+
* (ThresholdRandomBeacon address in the book, or resolved from KeyRegistry.randomBeacon).
|
|
505
|
+
* `onEpoch` reports fallback wait progress; `seeded` identifies the completed path.
|
|
506
|
+
*/
|
|
507
|
+
async function createSlotCommitReveal(args) {
|
|
508
|
+
const maxWaitMs = args.maxWaitMs ?? 180_000;
|
|
509
|
+
args.signal?.throwIfAborted();
|
|
510
|
+
if (!Number.isSafeInteger(maxWaitMs) || maxWaitMs < 1 || maxWaitMs > 2_147_483_647)
|
|
511
|
+
throw new Error('Invalid commit-reveal wait');
|
|
512
|
+
if (args.exportable)
|
|
513
|
+
throw new Error('Commit-reveal does not support raw-export slots');
|
|
514
|
+
const rule = await creationRule(args, 'createSlotCommitReveal');
|
|
515
|
+
const slotId = args.slotId ?? random32();
|
|
516
|
+
const salt = args.salt ?? random32();
|
|
517
|
+
const ruleSalt = args.ruleSalt ?? random32();
|
|
518
|
+
const ruleCommitmentHash = ruleCommitment(ruleSalt, rule);
|
|
519
|
+
const tags = await resolveDrawTags(args.tags, args.n);
|
|
520
|
+
const mode = modeIndex(args.mode);
|
|
521
|
+
// `auth` is not an input to `computeCommitment` - the commitment deliberately
|
|
522
|
+
// does not cover it, so it is passed at the REVEAL only.
|
|
523
|
+
const auth = authTypeIndex(args.authType);
|
|
524
|
+
// Application descriptors already pin KeyRegistry. Its configured beacon is
|
|
525
|
+
// authoritative when the caller has no separate beacon address in its book.
|
|
526
|
+
const beacon = addr.ThresholdRandomBeacon ?? await pub.readContract({
|
|
527
|
+
address: requireAddress(addr, 'KeyRegistry'), abi: keyRegistryAbi, functionName: 'randomBeacon',
|
|
528
|
+
});
|
|
529
|
+
if (!beacon || beacon === '0x0000000000000000000000000000000000000000')
|
|
530
|
+
throw new Error('KeyRegistry has no random beacon');
|
|
531
|
+
// Validated UP FRONT, before the commit is signed. A policy the chain would
|
|
532
|
+
// reject must not be discovered at the reveal, minutes and one beacon epoch
|
|
533
|
+
// later, when the commit has already been paid for.
|
|
534
|
+
const policy = args.rulePolicy ? await policyTuple(args.rulePolicy) : null;
|
|
535
|
+
const commitment = (await pub.readContract({
|
|
536
|
+
address: requireAddress(addr, 'KeyRegistry'),
|
|
537
|
+
abi: keyRegistryAbi,
|
|
538
|
+
functionName: 'computeCommitment',
|
|
539
|
+
args: [slotId, ruleCommitmentHash, args.k, args.n, mode, salt, tags, account.address],
|
|
540
|
+
}));
|
|
541
|
+
const keyReg = requireAddress(addr, 'KeyRegistry');
|
|
542
|
+
const beaconEpoch = () => pub.readContract({ address: beacon, abi: thresholdRandomBeaconAbi, functionName: 'epoch' });
|
|
543
|
+
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
|
|
544
|
+
const transact = async (step, name, values, seeded) => {
|
|
545
|
+
args.signal?.throwIfAborted();
|
|
546
|
+
await args.recovery?.onTransaction({ step, phase: 'submitting', seeded });
|
|
547
|
+
args.signal?.throwIfAborted();
|
|
548
|
+
const hash = await sendCall(keyReg, keyRegistryAbi, name, values, name);
|
|
549
|
+
await args.recovery?.onTransaction({ step, phase: 'submitted', hash, seeded });
|
|
550
|
+
return hash;
|
|
551
|
+
};
|
|
552
|
+
const commitTx = args.recovery?.commitTx ?? await transact('commit', 'commitKeySlot', [commitment]);
|
|
553
|
+
await confirmed(pub, commitTx, 'commitKeySlot');
|
|
554
|
+
await args.recovery?.onTransaction({ step: 'commit', phase: 'confirmed', hash: commitTx });
|
|
555
|
+
// Read the ACTUAL target epoch the contract pinned (computing it client-side
|
|
556
|
+
// races the ~20s beacon). slotCommits to (targetEpoch, expiryEpoch, creator, used).
|
|
557
|
+
const commit = (await pub.readContract({ address: keyReg, abi: keyRegistryAbi, functionName: 'slotCommits', args: [commitment] }));
|
|
558
|
+
const targetEpoch = Number(commit[0]);
|
|
559
|
+
if (args.recovery) {
|
|
560
|
+
if (commit[2].toLowerCase() !== account.address.toLowerCase() || commit[0] === 0n)
|
|
561
|
+
throw new TasraError('Saved creation does not match this creator and commitment');
|
|
562
|
+
if (args.recovery.revealTx) {
|
|
563
|
+
await confirmed(pub, args.recovery.revealTx, 'revealKeySlot');
|
|
564
|
+
const completed = await pub.readContract({ address: keyReg, abi: keyRegistryAbi, functionName: 'slotCommits', args: [commitment] });
|
|
565
|
+
if (!completed[3])
|
|
566
|
+
throw new TasraError('Saved reveal did not consume this commitment');
|
|
567
|
+
await args.recovery.onTransaction({ step: 'reveal', phase: 'confirmed', hash: args.recovery.revealTx, seeded: args.recovery.seeded });
|
|
568
|
+
return { slotId, commitTx, revealTx: args.recovery.revealTx, targetEpoch, ruleSalt, rule, seeded: args.recovery.seeded ?? false };
|
|
569
|
+
}
|
|
570
|
+
if (commit[3])
|
|
571
|
+
throw new TasraError('Commitment already consumed; reconcile the reveal hash before continuing');
|
|
572
|
+
}
|
|
573
|
+
// accountant-seeded creation FAST PATH: ask the accountant set to threshold-sign this commitment, and reveal
|
|
574
|
+
// immediately instead of waiting for `targetEpoch`.
|
|
575
|
+
//
|
|
576
|
+
// Strictly an optimisation, and written so it can only ever cost time. Every way it can go
|
|
577
|
+
// wrong - no accountant reachable, a KeyRegistry too old to have `commitSeedDigest`, a set
|
|
578
|
+
// whose group key is not the beacon's - lands in the epoch wait below, which is what this
|
|
579
|
+
// path did before it existed. The commitment is unchanged either way, so nothing is lost by
|
|
580
|
+
// trying.
|
|
581
|
+
// The seeded reveal draws a DIFFERENT committee than the epoch path would, because the seed
|
|
582
|
+
// is different. That is the mechanism, not a side effect: both seeds post-date the
|
|
583
|
+
// commitment, so both are ungrindable, and the creator does not get to pick which it gets.
|
|
584
|
+
let seed = null;
|
|
585
|
+
if (args.slotSeed !== false) {
|
|
586
|
+
try {
|
|
587
|
+
seed = await requestSlotSeed(createTasraChainClient({ rpcUrl: cfg.rpcUrl, addresses: cfg.addresses, chainId: chain.id }), keyReg, commitment, { urls: args.accountantUrls, timeoutMs: args.slotSeedTimeoutMs });
|
|
588
|
+
}
|
|
589
|
+
catch {
|
|
590
|
+
seed = null;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
args.onSeed?.(seed);
|
|
594
|
+
if (seed) {
|
|
595
|
+
try {
|
|
596
|
+
const seededTx = policy
|
|
597
|
+
? await transact('reveal', 'revealKeySlotWithSeedAndPolicy', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, seed.signature, policy], true)
|
|
598
|
+
: await transact('reveal', 'revealKeySlotWithSeed', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, seed.signature], true);
|
|
599
|
+
await confirmed(pub, seededTx, 'revealKeySlotWithSeed');
|
|
600
|
+
await args.recovery?.onTransaction({ step: 'reveal', phase: 'confirmed', hash: seededTx, seeded: true });
|
|
601
|
+
return { slotId, commitTx, revealTx: seededTx, targetEpoch, ruleSalt, rule, seeded: true };
|
|
602
|
+
}
|
|
603
|
+
catch (e) {
|
|
604
|
+
// Under a relay this must rethrow. The relay submitter owns the retries of the one
|
|
605
|
+
// request it signed, and falling through would start a second signed request against the
|
|
606
|
+
// same forwarder nonce - the defect that wedges every later write by this signer.
|
|
607
|
+
// Without a relay, a reverted seeded reveal has spent gas and left the commitment
|
|
608
|
+
// untouched, so the epoch wait below still completes the creation.
|
|
609
|
+
if (relay || args.recovery)
|
|
610
|
+
throw e;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
// Wait for the beacon to reach the target, then reveal - retrying across the
|
|
614
|
+
// epoch boundary (EpochNotReached / BeaconSeedUnavailable can transiently fire
|
|
615
|
+
// until the seed for the target epoch has landed).
|
|
616
|
+
const deadline = Date.now() + maxWaitMs;
|
|
617
|
+
let revealTx;
|
|
618
|
+
let prevEpoch = -1;
|
|
619
|
+
while (!revealTx) {
|
|
620
|
+
args.signal?.throwIfAborted();
|
|
621
|
+
const cur = Number(await beaconEpoch());
|
|
622
|
+
args.onEpoch?.(cur, targetEpoch);
|
|
623
|
+
if (!commit[3] && BigInt(cur) > commit[1])
|
|
624
|
+
throw new SlotCommitmentExpiredError(chain.id, keyReg, slotId, commitment, account.address, salt);
|
|
625
|
+
if (cur < targetEpoch) {
|
|
626
|
+
if (Date.now() > deadline)
|
|
627
|
+
throw new Error(`beacon did not reach target epoch ${targetEpoch} (at ${cur})`);
|
|
628
|
+
// The beacon is anchored to CHAIN time (tick = block.timestamp / interval).
|
|
629
|
+
// On a mint-on-demand chain (the local dev chain), block.timestamp only
|
|
630
|
+
// advances when a transaction mints a block - so an idle chain freezes the
|
|
631
|
+
// beacon and this wait would always hit its deadline. When the epoch has
|
|
632
|
+
// not moved since the last poll AND the head is stale, nudge chain time
|
|
633
|
+
// with a zero-value self-transfer. On live chains (Fuji, mainnet) blocks
|
|
634
|
+
// flow continuously, the head is never stale, and no nudge is ever sent.
|
|
635
|
+
if (!relay && cur === prevEpoch) {
|
|
636
|
+
try {
|
|
637
|
+
const head = await pub.getBlock();
|
|
638
|
+
const nowSecs = BigInt(Math.floor(Date.now() / 1000));
|
|
639
|
+
if (nowSecs - head.timestamp > 5n && wallet.account) {
|
|
640
|
+
const nudge = await wallet.sendTransaction({ to: wallet.account.address, value: 0n });
|
|
641
|
+
await confirmed(pub, nudge, 'chain-time nudge');
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
catch {
|
|
645
|
+
// Best-effort: a failed nudge leaves us exactly where a passive wait would be.
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
prevEpoch = cur;
|
|
649
|
+
await sleep(3000);
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
try {
|
|
653
|
+
// With a policy, the reveal PINS IT in the same transaction. That is the
|
|
654
|
+
// whole point: as a follow-up call it is unwinnable from a wallet that
|
|
655
|
+
// prompts, because the DKG starts the instant this transaction lands.
|
|
656
|
+
revealTx = policy
|
|
657
|
+
? await transact('reveal', 'revealKeySlotWithPolicy', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, policy], false)
|
|
658
|
+
: await transact('reveal', 'revealKeySlot', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags], false);
|
|
659
|
+
await confirmed(pub, revealTx, 'revealKeySlot');
|
|
660
|
+
await args.recovery?.onTransaction({ step: 'reveal', phase: 'confirmed', hash: revealTx, seeded: false });
|
|
661
|
+
}
|
|
662
|
+
catch (e) {
|
|
663
|
+
revealTx = undefined;
|
|
664
|
+
// The relay submitter owns bounded retries of one signed request. Never start a
|
|
665
|
+
// replacement attempt or a direct write from this epoch-wait loop.
|
|
666
|
+
if (relay || args.recovery)
|
|
667
|
+
throw e;
|
|
668
|
+
if (Date.now() > deadline)
|
|
669
|
+
throw e;
|
|
670
|
+
await sleep(3000);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return { slotId, commitTx, revealTx, targetEpoch, ruleSalt, rule, seeded: false };
|
|
674
|
+
}
|
|
675
|
+
/** Prepay a slot's metered usage: approve TSRA then Settlement.fund(slot, amount). */
|
|
676
|
+
async function fundSlot(slotId, amount) {
|
|
677
|
+
const token = requireAddress(addr, 'TasraToken');
|
|
678
|
+
const settlement = requireAddress(addr, 'Settlement');
|
|
679
|
+
const approveTx = await wallet.writeContract({ address: token, abi: tasraTokenAbi, functionName: 'approve', args: [settlement, amount] });
|
|
680
|
+
await confirmed(pub, approveTx, 'approve');
|
|
681
|
+
const fundTx = await sendCall(settlement, settlementAbi, 'fund', [slotId, amount], 'fund');
|
|
682
|
+
await confirmed(pub, fundTx, 'fund');
|
|
683
|
+
return { approveTx, fundTx, relay: relay ? lastRelay : undefined };
|
|
684
|
+
}
|
|
685
|
+
/** Send native ETH (gas) - e.g. a funded key backing a faucet. */
|
|
686
|
+
async function sendEth(to, wei) {
|
|
687
|
+
const h = await wallet.sendTransaction({ to, value: wei });
|
|
688
|
+
await confirmed(pub, h, 'sendEth');
|
|
689
|
+
return h;
|
|
690
|
+
}
|
|
691
|
+
/** Transfer TSRA - e.g. a faucet handing tokens to a fresh client. */
|
|
692
|
+
async function transferTsra(to, amount) {
|
|
693
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'TasraToken'), abi: tasraTokenAbi, functionName: 'transfer', args: [to, amount] });
|
|
694
|
+
await confirmed(pub, h, 'transfer');
|
|
695
|
+
return h;
|
|
696
|
+
}
|
|
697
|
+
/** EURC the curve prices in (the real Circle token, or the demo mock on a dev/test chain). */
|
|
698
|
+
async function eurcBalance(a) {
|
|
699
|
+
return (await pub.readContract({ address: requireAddress(addr, 'MockEurc'), abi: mockEurcAbi, functionName: 'balanceOf', args: [a] }));
|
|
700
|
+
}
|
|
701
|
+
/** Approve EURC to the bonding curve - an ERC-20 approve, always from the local key. */
|
|
702
|
+
async function approveEurcForCurve(amount) {
|
|
703
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'MockEurc'), abi: mockEurcAbi, functionName: 'approve', args: [requireAddress(addr, 'BondingCurve'), amount] });
|
|
704
|
+
await confirmed(pub, h, 'approve');
|
|
705
|
+
return h;
|
|
706
|
+
}
|
|
707
|
+
/** DEV/TEST only: mint the demo MockEurc (permissionless faucet). Fails against real EURC. */
|
|
708
|
+
async function mintMockEurc(to, amount) {
|
|
709
|
+
const actualChainId = await pub.getChainId();
|
|
710
|
+
const token = requireAddress(addr, 'MockEurc');
|
|
711
|
+
const profile = resolveNetworkProfile(networkNameForChain(actualChainId), { chainId: actualChainId, eurcAddress: token });
|
|
712
|
+
assertEurcFaucetAllowed(profile, actualChainId, token);
|
|
713
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'MockEurc'), abi: mockEurcAbi, functionName: 'mint', args: [to, amount] });
|
|
714
|
+
await confirmed(pub, h, 'mint');
|
|
715
|
+
return h;
|
|
716
|
+
}
|
|
717
|
+
// slot lifecycle (KeyRegistry; gated to the slot's creator/owner)
|
|
718
|
+
/** Rotate a slot's key - re-DKG under a new epoch. */
|
|
719
|
+
async function rotateKey(slotId, reason = '') {
|
|
720
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'KeyRegistry'), abi: keyRegistryAbi, functionName: 'rotateKey', args: [slotId, reason] });
|
|
721
|
+
await confirmed(pub, h, 'rotateKey');
|
|
722
|
+
return h;
|
|
723
|
+
}
|
|
724
|
+
/** Reshare a slot to a new operator set / threshold. */
|
|
725
|
+
async function reshareKey(slotId, newOperators, k, n, reason = '') {
|
|
726
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'KeyRegistry'), abi: keyRegistryAbi, functionName: 'reshareKey', args: [slotId, newOperators, k, n, reason] });
|
|
727
|
+
await confirmed(pub, h, 'reshareKey');
|
|
728
|
+
return h;
|
|
729
|
+
}
|
|
730
|
+
/** Cancel a slot. */
|
|
731
|
+
async function cancelSlot(slotId) {
|
|
732
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'KeyRegistry'), abi: keyRegistryAbi, functionName: 'cancelSlot', args: [slotId] });
|
|
733
|
+
await confirmed(pub, h, 'cancelSlot');
|
|
734
|
+
return h;
|
|
735
|
+
}
|
|
736
|
+
/** Renew a slot's lease. `renew` is creator-only, so this must be signed by the slot's creator -
|
|
737
|
+
* routed through `sendCall` so it relays (ERC-2771 forward) when a relay is configured, exactly
|
|
738
|
+
* like `createSlot`. A direct `writeContract` here would sign with the local key, which is not
|
|
739
|
+
* the creator when the slot was created under a forwarded (`_msgSender()`) identity. */
|
|
740
|
+
async function renewSlot(slotId) {
|
|
741
|
+
const h = await sendCall(requireAddress(addr, 'KeyRegistry'), keyRegistryAbi, 'renew', [slotId], 'renew');
|
|
742
|
+
await confirmed(pub, h, 'renew');
|
|
743
|
+
return h;
|
|
744
|
+
}
|
|
745
|
+
/** Set the slot's per-request verifier-committee policy: committee
|
|
746
|
+
* draw size + signing quorum. */
|
|
747
|
+
async function setVerifierPolicy(slotId, committee, quorum, onTransaction) {
|
|
748
|
+
await onTransaction?.({ phase: 'submitting' });
|
|
749
|
+
const h = await sendCall(requireAddress(addr, 'KeyRegistry'), keyRegistryAbi, 'setVerifierPolicy', [slotId, committee, quorum], 'setVerifierPolicy');
|
|
750
|
+
await onTransaction?.({ phase: 'submitted', hash: h });
|
|
751
|
+
await confirmed(pub, h, 'setVerifierPolicy');
|
|
752
|
+
await onTransaction?.({ phase: 'confirmed', hash: h });
|
|
753
|
+
return h;
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Pin amendment authority while the slot is fresh. Prefer passing rulePolicy at creation so key generation cannot win the race. The guardian must differ from the administrator, and omitting a guardian requires the contract minimum timelock.
|
|
757
|
+
*/
|
|
758
|
+
async function setRulePolicy(slotId, policy) {
|
|
759
|
+
const keyReg = requireAddress(addr, 'KeyRegistry');
|
|
760
|
+
const guardian = await validateRulePolicy(policy);
|
|
761
|
+
const h = await wallet.writeContract({
|
|
762
|
+
address: keyReg,
|
|
763
|
+
abi: keyRegistryAbi,
|
|
764
|
+
functionName: 'setRulePolicy',
|
|
765
|
+
args: [slotId, policy.admin, guardian, policy.timelockSecs],
|
|
766
|
+
});
|
|
767
|
+
await confirmed(pub, h, 'setRulePolicy');
|
|
768
|
+
return h;
|
|
769
|
+
}
|
|
770
|
+
// rule amendment (KeyRegistry.proposeRuleUpdate / endorse / veto / activate)
|
|
771
|
+
// Every refusal below is raised BEFORE `sendCall`: a proposal no keeper will store never
|
|
772
|
+
// activates, and on a slot without a guardian nobody can clear it.
|
|
773
|
+
/** Propose a new rule as the slot's rule admin; checks every contract precondition first. */
|
|
774
|
+
async function proposeRuleUpdate(a) {
|
|
775
|
+
const what = 'proposeRuleUpdate';
|
|
776
|
+
requireBytes32(a.slotId, 'slotId', what);
|
|
777
|
+
requireBytes32(a.ruleSalt, 'ruleSalt', what);
|
|
778
|
+
const rule = await resolveAmendmentRule(a, what);
|
|
779
|
+
const keyRegistry = requireAddress(addr, 'KeyRegistry');
|
|
780
|
+
const state = await readAmendmentOnChain(pub.readContract, keyRegistry, a.slotId);
|
|
781
|
+
if (sameAddress(state.admin, ZERO_ADDRESS))
|
|
782
|
+
throw immutableError(a.slotId);
|
|
783
|
+
if (!sameAddress(account.address, state.admin)) {
|
|
784
|
+
throw new RuleAmendmentError('not-admin', a.slotId, `${what}: slot ${a.slotId} has rule admin ${state.admin}, but this client signs as ${account.address} ` +
|
|
785
|
+
'(a relayed call is still signed by this account). Use a write client for the rule admin key');
|
|
786
|
+
}
|
|
787
|
+
if (state.pending)
|
|
788
|
+
throw pendingError(a.slotId, state);
|
|
789
|
+
await amendmentPreflight(rule, state, a.slotId, what);
|
|
790
|
+
const commitment = ruleCommitment(a.ruleSalt, rule);
|
|
791
|
+
if (commitment.toLowerCase() === state.ruleCommitment.toLowerCase()) {
|
|
792
|
+
throw new RuleAmendmentError('same-rule', a.slotId, `${what}: slot ${a.slotId} already enforces this rule (same salted commitment ${commitment}); nothing to amend`);
|
|
793
|
+
}
|
|
794
|
+
const txHash = await sendCall(keyRegistry, keyRegistryAbi, 'proposeRuleUpdate', [a.slotId, commitment], what);
|
|
795
|
+
const receipt = await confirmed(pub, txHash, what);
|
|
796
|
+
const proposed = parseEventLogs({ abi: keyRegistryAbi, eventName: 'RuleUpdateProposed', logs: receipt.logs })
|
|
797
|
+
.find(l => sameAddress(l.address, keyRegistry) && l.args.slotId.toLowerCase() === a.slotId.toLowerCase());
|
|
798
|
+
if (!proposed) {
|
|
799
|
+
throw new TasraError(`${what}: tx ${txHash} confirmed but carries no RuleUpdateProposed event for slot ${a.slotId}`);
|
|
800
|
+
}
|
|
801
|
+
return {
|
|
802
|
+
slotId: a.slotId,
|
|
803
|
+
txHash,
|
|
804
|
+
version: Number(proposed.args.version),
|
|
805
|
+
notBefore: Number(proposed.args.notBefore),
|
|
806
|
+
ruleCommitment: commitment,
|
|
807
|
+
ruleSalt: a.ruleSalt,
|
|
808
|
+
rule,
|
|
809
|
+
relay: lastRelay?.txHash === txHash ? lastRelay : undefined,
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
/** Endorse or veto the pending amendment as the slot's guardian. */
|
|
813
|
+
async function guardianCall(slotId, functionName) {
|
|
814
|
+
requireBytes32(slotId, 'slotId', functionName);
|
|
815
|
+
const keyRegistry = requireAddress(addr, 'KeyRegistry');
|
|
816
|
+
const state = await readAmendmentOnChain(pub.readContract, keyRegistry, slotId);
|
|
817
|
+
if (sameAddress(state.guardian, ZERO_ADDRESS)) {
|
|
818
|
+
throw new RuleAmendmentError('not-guardian', slotId, `${functionName}: slot ${slotId} has no rule guardian, so nobody can call it`, { hasGuardian: false });
|
|
819
|
+
}
|
|
820
|
+
if (!sameAddress(account.address, state.guardian)) {
|
|
821
|
+
throw new RuleAmendmentError('not-guardian', slotId, `${functionName}: slot ${slotId} has rule guardian ${state.guardian}, but this client signs as ${account.address}. ` +
|
|
822
|
+
'Use a write client for the guardian key', { hasGuardian: true });
|
|
823
|
+
}
|
|
824
|
+
if (!state.pending) {
|
|
825
|
+
throw new RuleAmendmentError('no-pending', slotId, `${functionName}: slot ${slotId} has no pending rule amendment`);
|
|
826
|
+
}
|
|
827
|
+
const h = await sendCall(keyRegistry, keyRegistryAbi, functionName, [slotId], functionName);
|
|
828
|
+
await confirmed(pub, h, functionName);
|
|
829
|
+
return h;
|
|
830
|
+
}
|
|
831
|
+
const endorseRuleUpdate = (slotId) => guardianCall(slotId, 'endorseRuleUpdate');
|
|
832
|
+
const vetoRuleUpdate = (slotId) => guardianCall(slotId, 'vetoRuleUpdate');
|
|
833
|
+
/** Activate the pending amendment once chain time and keeper adoption allow it. */
|
|
834
|
+
async function activateRuleUpdate(slotId) {
|
|
835
|
+
const what = 'activateRuleUpdate';
|
|
836
|
+
requireBytes32(slotId, 'slotId', what);
|
|
837
|
+
const keyRegistry = requireAddress(addr, 'KeyRegistry');
|
|
838
|
+
const state = await readAmendmentOnChain(pub.readContract, keyRegistry, slotId, { withVotes: true });
|
|
839
|
+
const pending = state.pending;
|
|
840
|
+
if (!pending)
|
|
841
|
+
throw new RuleAmendmentError('no-pending', slotId, `${what}: slot ${slotId} has no pending rule amendment`);
|
|
842
|
+
// The contract compares `block.timestamp`, so the check must too: the local clock can be far
|
|
843
|
+
// ahead of an idle chain.
|
|
844
|
+
const block = await pub.getBlock({ blockTag: 'latest' });
|
|
845
|
+
const chainTime = Number(block.timestamp);
|
|
846
|
+
if (chainTime < pending.notBefore) {
|
|
847
|
+
throw new RuleAmendmentError('timelock', slotId, `${what}: amendment version ${pending.version} of slot ${slotId} may activate from chain time ${pending.notBefore}; ` +
|
|
848
|
+
`the latest block is at ${chainTime} (${pending.notBefore - chainTime}s to go)`, { notBefore: pending.notBefore, chainTime, pendingVersion: pending.version });
|
|
849
|
+
}
|
|
850
|
+
const have = pending.adoptions ?? 0;
|
|
851
|
+
const need = pending.needed ?? 0;
|
|
852
|
+
if (have < need) {
|
|
853
|
+
throw new RuleAmendmentError('below-threshold', slotId, `${what}: amendment version ${pending.version} of slot ${slotId} has ${have} of ${need} keeper adoptions; ` +
|
|
854
|
+
'keepers adopt it once they hold the rule - deliver it with provisionRule({expect: \'pending\'})', { have, need, pendingVersion: pending.version });
|
|
855
|
+
}
|
|
856
|
+
const h = await sendCall(keyRegistry, keyRegistryAbi, what, [slotId], what);
|
|
857
|
+
await confirmed(pub, h, what);
|
|
858
|
+
return h;
|
|
859
|
+
}
|
|
860
|
+
// TASRA tokenomics (BondingCurve / TasraToken)
|
|
861
|
+
/** Buy TSRA from the bonding curve. Approve `eurcAmount` of EURC to the
|
|
862
|
+
* BondingCurve first; read balances for the fill. */
|
|
863
|
+
async function buyTsra(eurcAmount, minTsraOut) {
|
|
864
|
+
const h = await sendCall(requireAddress(addr, 'BondingCurve'), bondingCurveAbi, 'buy', [eurcAmount, minTsraOut], 'buy');
|
|
865
|
+
await confirmed(pub, h, 'buy');
|
|
866
|
+
return h;
|
|
867
|
+
}
|
|
868
|
+
/** Redeem TSRA back to the bonding curve (approves TSRA to the curve first).
|
|
869
|
+
* `minEurcOut` is the slippage floor the pre-audit hardening added to `redeem` (the
|
|
870
|
+
* VWAP can move between the read and the inclusion); `0n` accepts any fill. */
|
|
871
|
+
async function redeemTsra(tsraAmount, minEurcOut = 0n) {
|
|
872
|
+
const curve = requireAddress(addr, 'BondingCurve');
|
|
873
|
+
const approveTx = await wallet.writeContract({ address: requireAddress(addr, 'TasraToken'), abi: tasraTokenAbi, functionName: 'approve', args: [curve, tsraAmount] });
|
|
874
|
+
await confirmed(pub, approveTx, 'approve');
|
|
875
|
+
const redeemTx = await wallet.writeContract({ address: curve, abi: bondingCurveAbi, functionName: 'redeem', args: [tsraAmount, minEurcOut] });
|
|
876
|
+
await confirmed(pub, redeemTx, 'redeem');
|
|
877
|
+
return { approveTx, redeemTx };
|
|
878
|
+
}
|
|
879
|
+
/** Burn TSRA from the caller's balance (deflationary). */
|
|
880
|
+
async function burnTsra(amount) {
|
|
881
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'TasraToken'), abi: tasraTokenAbi, functionName: 'burn', args: [amount] });
|
|
882
|
+
await confirmed(pub, h, 'burn');
|
|
883
|
+
return h;
|
|
884
|
+
}
|
|
885
|
+
const spotPrice = () => pub.readContract({ address: requireAddress(addr, 'BondingCurve'), abi: bondingCurveAbi, functionName: 'spotPrice' });
|
|
886
|
+
const priceAt = (sold) => pub.readContract({ address: requireAddress(addr, 'BondingCurve'), abi: bondingCurveAbi, functionName: 'priceAt', args: [sold] });
|
|
887
|
+
// treasury / vault (owner / refunder gated)
|
|
888
|
+
async function treasuryWithdraw(to, amount) {
|
|
889
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'Treasury'), abi: treasuryAbi, functionName: 'withdraw', args: [to, amount] });
|
|
890
|
+
await confirmed(pub, h, 'withdraw');
|
|
891
|
+
return h;
|
|
892
|
+
}
|
|
893
|
+
async function treasuryRefund(to, amount) {
|
|
894
|
+
const h = await wallet.writeContract({ address: requireAddress(addr, 'Treasury'), abi: treasuryAbi, functionName: 'refund', args: [to, amount] });
|
|
895
|
+
await confirmed(pub, h, 'refund');
|
|
896
|
+
return h;
|
|
897
|
+
}
|
|
898
|
+
/** Release vested TSRA from one tranche's vault to its beneficiary. */
|
|
899
|
+
async function vaultRelease(tranche) {
|
|
900
|
+
const h = await wallet.writeContract({ address: requireVaultAddress(addr, tranche), abi: tasraVestingVaultAbi, functionName: 'release', args: [] });
|
|
901
|
+
await confirmed(pub, h, 'release');
|
|
902
|
+
return h;
|
|
903
|
+
}
|
|
904
|
+
const tsraBalance = (of) => pub.readContract({ address: requireAddress(addr, 'TasraToken'), abi: tasraTokenAbi, functionName: 'balanceOf', args: [of ?? account.address] });
|
|
905
|
+
const ethBalance = (of) => pub.getBalance({ address: of ?? account.address });
|
|
906
|
+
const settlementBalance = (slotId) => pub.readContract({ address: requireAddress(addr, 'Settlement'), abi: settlementAbi, functionName: 'balanceOf', args: [slotId] });
|
|
907
|
+
return {
|
|
908
|
+
account,
|
|
909
|
+
address: account.address,
|
|
910
|
+
createSlot,
|
|
911
|
+
createSlotCommitReveal,
|
|
912
|
+
fundSlot,
|
|
913
|
+
sendEth,
|
|
914
|
+
transferTsra,
|
|
915
|
+
// slot lifecycle
|
|
916
|
+
rotateKey,
|
|
917
|
+
reshareKey,
|
|
918
|
+
cancelSlot,
|
|
919
|
+
renewSlot,
|
|
920
|
+
setVerifierPolicy,
|
|
921
|
+
setRulePolicy,
|
|
922
|
+
// rule amendment
|
|
923
|
+
proposeRuleUpdate,
|
|
924
|
+
endorseRuleUpdate,
|
|
925
|
+
vetoRuleUpdate,
|
|
926
|
+
activateRuleUpdate,
|
|
927
|
+
// tokenomics
|
|
928
|
+
buyTsra,
|
|
929
|
+
approveEurcForCurve,
|
|
930
|
+
mintMockEurc,
|
|
931
|
+
eurcBalance,
|
|
932
|
+
/** True when sender-bound calls are relayed. */
|
|
933
|
+
relayEnabled: !!relay,
|
|
934
|
+
/** Receipt of the most recent relayed call (id, tx, gas the relayer paid). */
|
|
935
|
+
lastRelay: () => lastRelay,
|
|
936
|
+
pendingRelayAttempt: () => registeredRelay?.pendingAttempt(),
|
|
937
|
+
reconcileRelay: async () => {
|
|
938
|
+
const result = await registeredRelay?.reconcile();
|
|
939
|
+
if (result?.receipt)
|
|
940
|
+
lastRelay = result.receipt;
|
|
941
|
+
return result;
|
|
942
|
+
},
|
|
943
|
+
redeemTsra,
|
|
944
|
+
burnTsra,
|
|
945
|
+
spotPrice,
|
|
946
|
+
priceAt,
|
|
947
|
+
// treasury / vault
|
|
948
|
+
treasuryWithdraw,
|
|
949
|
+
treasuryRefund,
|
|
950
|
+
vaultRelease,
|
|
951
|
+
// reads
|
|
952
|
+
tsraBalance,
|
|
953
|
+
ethBalance,
|
|
954
|
+
settlementBalance,
|
|
955
|
+
wallet,
|
|
956
|
+
pub,
|
|
957
|
+
};
|
|
958
|
+
}
|