@agenticprimitives/contracts 1.0.0-alpha.4 → 1.0.0-alpha.41

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.
Files changed (108) hide show
  1. package/AUDIT.md +330 -47
  2. package/README.md +56 -10
  3. package/deployments-base-sepolia.json +50 -0
  4. package/deployments-faithchain.json +75 -0
  5. package/deployments-hopechain.json +57 -0
  6. package/deployments-paymaster-anvil.json +1 -0
  7. package/deployments-registries-base-sepolia.json +1 -0
  8. package/deployments-registries-hopechain.json +1 -0
  9. package/dist/abi/AgentAccount.json +1827 -0
  10. package/dist/abi/AgentAccountFactory.json +545 -0
  11. package/dist/abi/AgentNameRegistry.json +51 -0
  12. package/dist/abi/AgentRegistryBase.json +652 -0
  13. package/dist/abi/AgenticGovernance.json +32 -0
  14. package/dist/abi/AgreementRegistry.json +427 -0
  15. package/dist/abi/ApprovedHashRegistry.json +47 -2
  16. package/dist/abi/AttestationRegistry.json +436 -0
  17. package/dist/abi/CallDataHashEnforcer.json +119 -0
  18. package/dist/abi/CustodyPolicy.json +1179 -0
  19. package/dist/abi/DelegationManager.json +656 -0
  20. package/dist/abi/DigestBindingEnforcer.json +251 -0
  21. package/dist/abi/EstateProjectionRegistry.json +293 -0
  22. package/dist/abi/GeoFeatureRegistry.json +625 -0
  23. package/dist/abi/IAgentAccount.json +262 -0
  24. package/dist/abi/IAgentAccountFactoryAccessor.json +15 -0
  25. package/dist/abi/IAgentAccountFactoryView.json +54 -0
  26. package/dist/abi/IAgentAccountPauseView.json +15 -0
  27. package/dist/abi/IAgenticPrimitivesAgentAccount.json +15 -0
  28. package/dist/abi/IApprovedHashRegistryView.json +26 -0
  29. package/dist/abi/IApprovedHashRegistryWrite.json +35 -0
  30. package/dist/abi/ICustodyPolicyAccountModuleView.json +31 -0
  31. package/dist/abi/ICustodyPolicyFactoryView.json +15 -0
  32. package/dist/abi/ICustodyPolicyPauseView.json +15 -0
  33. package/dist/abi/IDelegationManager.json +171 -0
  34. package/dist/abi/IERC7579HookLike.json +44 -0
  35. package/dist/abi/IERC7579ModuleLike.json +28 -0
  36. package/dist/abi/IPaymentReceiptRegistry.json +50 -0
  37. package/dist/abi/IRegistryMembershipPolicy.json +70 -0
  38. package/dist/abi/MockUSDC.json +621 -0
  39. package/dist/abi/PayloadClassesEnforcer.json +117 -0
  40. package/dist/abi/PaymentEnforcer.json +441 -0
  41. package/dist/abi/PaymentEscrow.json +324 -0
  42. package/dist/abi/PaymentReceiptRegistry.json +182 -0
  43. package/dist/abi/PermissionlessSubregistry.json +5 -0
  44. package/dist/abi/PricedSubregistry.json +869 -0
  45. package/dist/abi/QuorumEnforcer.json +311 -0
  46. package/dist/abi/ReceiptAnchorRegistry.json +153 -0
  47. package/dist/abi/SignatureSlotRecovery.json +88 -0
  48. package/dist/abi/SkillDefinitionRegistry.json +491 -0
  49. package/dist/abi/SmartAgentPaymaster.json +873 -0
  50. package/dist/abi/TreasurySpendPolicy.json +369 -0
  51. package/dist/abi/UniversalSignatureValidator.json +65 -0
  52. package/dist/abi/index.d.ts +38 -0
  53. package/dist/abi/index.js +38 -0
  54. package/dist/deployments/base-sepolia.d.ts +46 -0
  55. package/dist/deployments/base-sepolia.js +54 -0
  56. package/dist/deployments/faithchain.d.ts +55 -0
  57. package/dist/deployments/faithchain.js +79 -0
  58. package/dist/deployments/hopechain.d.ts +53 -0
  59. package/dist/deployments/hopechain.js +61 -0
  60. package/dist/deployments/index.d.ts +13 -0
  61. package/dist/deployments/index.js +28 -0
  62. package/dist/deployments/paymaster-anvil.d.ts +11 -0
  63. package/dist/deployments/paymaster-anvil.js +9 -0
  64. package/dist/deployments/registries-base-sepolia.d.ts +10 -0
  65. package/dist/deployments/registries-base-sepolia.js +8 -0
  66. package/dist/deployments/registries-hopechain.d.ts +10 -0
  67. package/dist/deployments/registries-hopechain.js +8 -0
  68. package/package.json +55 -8
  69. package/src/AgentAccount.sol +569 -38
  70. package/src/AgentAccountFactory.sol +157 -16
  71. package/src/ApprovedHashRegistry.sol +41 -6
  72. package/src/IAgentAccount.sol +23 -0
  73. package/src/SmartAgentPaymaster.sol +156 -12
  74. package/src/UniversalSignatureValidator.sol +3 -0
  75. package/src/agency/DelegationManager.sol +179 -0
  76. package/src/agency/IDelegationManager.sol +38 -0
  77. package/src/agreement/AgreementRegistry.sol +331 -0
  78. package/src/attestation/AttestationRegistry.sol +384 -0
  79. package/src/custody/CustodyPolicy.sol +263 -15
  80. package/src/custody/TreasurySpendPolicy.sol +166 -0
  81. package/src/enforcers/AllowedMethodsEnforcer.sol +6 -0
  82. package/src/enforcers/AllowedTargetsEnforcer.sol +6 -0
  83. package/src/enforcers/CallDataHashEnforcer.sol +61 -0
  84. package/src/enforcers/DigestBindingEnforcer.sol +107 -0
  85. package/src/enforcers/PayloadClassesEnforcer.sol +30 -0
  86. package/src/enforcers/PaymentEnforcer.sol +257 -0
  87. package/src/enforcers/QuorumEnforcer.sol +24 -1
  88. package/src/enforcers/TimestampEnforcer.sol +7 -0
  89. package/src/enforcers/ValueEnforcer.sol +6 -0
  90. package/src/geo/GeoFeatureRegistry.sol +197 -0
  91. package/src/governance/AgenticGovernance.sol +26 -4
  92. package/src/identity/AgentProfilePredicates.sol +23 -0
  93. package/src/libraries/SignatureSlotRecovery.sol +24 -7
  94. package/src/libraries/WebAuthnLib.sol +13 -0
  95. package/src/mocks/MockUSDC.sol +152 -0
  96. package/src/naming/AgentNamePredicates.sol +89 -0
  97. package/src/naming/AgentNameRegistry.sol +65 -18
  98. package/src/naming/AgentNameUniversalResolver.sol +1 -1
  99. package/src/naming/PermissionlessSubregistry.sol +19 -2
  100. package/src/naming/PricedSubregistry.sol +209 -0
  101. package/src/payments/PaymentEscrow.sol +164 -0
  102. package/src/payments/PaymentReceiptRegistry.sol +67 -0
  103. package/src/provenance/ReceiptAnchorRegistry.sol +55 -0
  104. package/src/registry/AgentRegistryBase.sol +313 -0
  105. package/src/registry/EstateProjectionRegistry.sol +109 -0
  106. package/src/registry/IRegistryMembershipPolicy.sol +30 -0
  107. package/src/relationships/AgentRelationship.sol +8 -0
  108. package/src/skills/SkillDefinitionRegistry.sol +187 -0
@@ -0,0 +1,61 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import "../agency/ICaveatEnforcer.sol";
5
+
6
+ /**
7
+ * @title CallDataHashEnforcer
8
+ * @notice Pins a delegation to EXACTLY one calldata payload — the exact-call
9
+ * binding ADR-0027 / spec 249 (RW1-4b) needs for sensitive ops.
10
+ * @dev terms = abi.encode(bytes32 expectedHash), where
11
+ * `expectedHash == keccak256(callData)` for the single call this
12
+ * delegation authorizes. `beforeHook` recomputes `keccak256(callData)`
13
+ * and reverts on mismatch.
14
+ *
15
+ * Ported from smart-agent's `CallDataHashEnforcer` (the "P4 — sensitive
16
+ * ops require exact-call sub-delegation" doctrine). Combined with
17
+ * `AllowedTargetsEnforcer` (target) + a tight `TimestampEnforcer`
18
+ * window + `ValueEnforcer`, a consent sub-delegation can pin the precise
19
+ * call — not merely its selector — so a registry that checks
20
+ * `DelegationManager.verifyAuthorizationForCall(...)` binds consent to the
21
+ * exact assertion being stored (RW1-1).
22
+ *
23
+ * R6.7 — Stateless validator: hooks are `pure`, the contract has zero
24
+ * storage, so no `whenNotPaused` is needed; the DM-side pause check in
25
+ * `DelegationManager.redeemDelegation` gates all reachable enforcer
26
+ * dispatch, and the read-only `verifyAuthorizationForCall` evaluates it
27
+ * via `staticcall`.
28
+ */
29
+ contract CallDataHashEnforcer is ICaveatEnforcer {
30
+ error BadTermsLength();
31
+ error CallDataMismatch(bytes32 expected, bytes32 actual);
32
+
33
+ function beforeHook(
34
+ bytes calldata terms,
35
+ bytes calldata,
36
+ bytes32,
37
+ address,
38
+ address,
39
+ address,
40
+ uint256,
41
+ bytes calldata callData
42
+ ) external pure override {
43
+ if (terms.length != 32) revert BadTermsLength();
44
+ bytes32 expected = abi.decode(terms, (bytes32));
45
+ bytes32 actual = keccak256(callData);
46
+ if (expected != actual) revert CallDataMismatch(expected, actual);
47
+ }
48
+
49
+ function afterHook(
50
+ bytes calldata,
51
+ bytes calldata,
52
+ bytes32,
53
+ address,
54
+ address,
55
+ address,
56
+ uint256,
57
+ bytes calldata
58
+ ) external pure override {
59
+ // No post-execution check needed.
60
+ }
61
+ }
@@ -0,0 +1,107 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import "../agency/ICaveatEnforcer.sol";
5
+
6
+ /**
7
+ * @title DigestBindingEnforcer
8
+ * @notice Binds a delegation to a 32-byte digest of an OFF-CHAIN artifact — an intent, a disclosure
9
+ * projection, an accepted offer — so that the delegation is a MANDATE (spec 336 §8.3, spec 350
10
+ * §2): authority *for a reason*, not authority for any purpose until revoked.
11
+ *
12
+ * @dev terms = abi.encode(bytes32 kind, bytes32 digest)
13
+ * args = abi.encode(bytes32 presented, bytes32 stepNonce) — supplied by the redeemer at redemption
14
+ *
15
+ * `kind` names WHICH artifact the digest is of, so an off-chain reader can tell an intent binding
16
+ * from a projection binding without guessing:
17
+ * keccak256("ap:intent") — the canonical intent (RFC 8785 JCS bytes)
18
+ * keccak256("ap:projection") — what was disclosed to the grantee (spec 336 §4)
19
+ * keccak256("ap:offer") — the accepted offer (spec 336 §5)
20
+ * keccak256("ap:plan") — the admitted plan (spec 408 §2.3)
21
+ * One enforcer serves all four: the mechanics are identical and the kind belongs in the terms,
22
+ * where it is signed, rather than in which contract address was chosen.
23
+ *
24
+ * WHAT THIS ENFORCES, HONESTLY. The chain cannot know what an intent *means*; it can only hold
25
+ * the redeemer to a commitment. `beforeHook` requires the redeemer to PRESENT the digest it is
26
+ * acting under, and reverts if that is not the bound one. Two things follow:
27
+ * 1. the binding is part of the SIGNED delegation — immutable, inspectable, and what the
28
+ * off-chain per-step verifier (`delegation.verifyMandateForStep`) compares a step's
29
+ * intent digest against. That verifier is where "does this step belong to this intent" is
30
+ * actually decided; this contract makes the answer un-forgeable rather than deciding it;
31
+ * 2. the presented digest lands in the transaction, so the receipt's `intentDigest` and the
32
+ * chain's record of what the redeemer claimed to be doing are the same bytes — evidence a
33
+ * third party can check without trusting either side.
34
+ * A redeemer that copies `terms` into `args` satisfies the digest check; that is the point — it has
35
+ * now committed, on chain, to that intent, and a step whose real intent differs is caught by the
36
+ * verifier that computed the digest from the step rather than from the caveat.
37
+ *
38
+ * R917-C-4 (spec 408 §1.4) — SINGLE-USE PER STEP. A digest-bound redemption is consumed under
39
+ * `(delegator, delegationHash, kind, stepNonce)`: the harness derives `stepNonce` from the intent
40
+ * digest and the step's reference (the same derivation as `PaymentEnforcer`'s nonce), so ONE step
41
+ * redeems once and a replay of it reverts `StepNonceReused`. Which steps exist is bound off chain by
42
+ * the plan digest the mandate carries; the chain holds each of them to one redemption. The hooks
43
+ * therefore mutate state and are `onlyDelegationManager` (EXT-PMT-1's rule for stateful enforcers):
44
+ * a stranger cannot burn a step's nonce ahead of the legitimate redemption.
45
+ */
46
+ contract DigestBindingEnforcer is ICaveatEnforcer {
47
+ error BadTermsLength();
48
+ error BadArgsLength();
49
+ error DigestMismatch(bytes32 kind, bytes32 bound, bytes32 presented);
50
+ error StepNonceReused(bytes32 kind, bytes32 stepNonce);
51
+ error NotDelegationManager(address caller);
52
+
53
+ /// @notice The ONLY authorized caller of `beforeHook` — it consumes a nonce (R917-C-4).
54
+ address public immutable delegationManager;
55
+
56
+ /// delegator => delegationHash => keccak256(kind, stepNonce) => consumed
57
+ mapping(address => mapping(bytes32 => mapping(bytes32 => bool))) private _used;
58
+
59
+ event DigestBindingRedeemed(address indexed delegator, bytes32 indexed delegationHash, bytes32 indexed kind, bytes32 presented, bytes32 stepNonce);
60
+
61
+ constructor(address delegationManager_) {
62
+ require(delegationManager_ != address(0), "DigestBindingEnforcer: zero DelegationManager");
63
+ delegationManager = delegationManager_;
64
+ }
65
+
66
+ modifier onlyDelegationManager() {
67
+ if (msg.sender != delegationManager) revert NotDelegationManager(msg.sender);
68
+ _;
69
+ }
70
+
71
+ /// @notice Whether `stepNonce` was already consumed for this binding (a reader's replay check).
72
+ function isUsed(address delegator, bytes32 delegationHash, bytes32 kind, bytes32 stepNonce) external view returns (bool) {
73
+ return _used[delegator][delegationHash][keccak256(abi.encode(kind, stepNonce))];
74
+ }
75
+
76
+ function beforeHook(
77
+ bytes calldata terms,
78
+ bytes calldata args,
79
+ bytes32 delegationHash,
80
+ address delegator,
81
+ address,
82
+ address,
83
+ uint256,
84
+ bytes calldata
85
+ ) external override onlyDelegationManager {
86
+ if (terms.length != 64) revert BadTermsLength();
87
+ if (args.length != 64) revert BadArgsLength();
88
+ (bytes32 kind, bytes32 bound) = abi.decode(terms, (bytes32, bytes32));
89
+ (bytes32 presented, bytes32 stepNonce) = abi.decode(args, (bytes32, bytes32));
90
+ if (presented != bound) revert DigestMismatch(kind, bound, presented);
91
+ bytes32 slot = keccak256(abi.encode(kind, stepNonce));
92
+ if (_used[delegator][delegationHash][slot]) revert StepNonceReused(kind, stepNonce);
93
+ _used[delegator][delegationHash][slot] = true;
94
+ emit DigestBindingRedeemed(delegator, delegationHash, kind, presented, stepNonce);
95
+ }
96
+
97
+ function afterHook(
98
+ bytes calldata,
99
+ bytes calldata,
100
+ bytes32,
101
+ address,
102
+ address,
103
+ address,
104
+ uint256,
105
+ bytes calldata
106
+ ) external pure override {}
107
+ }
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import "../agency/ICaveatEnforcer.sol";
5
+
6
+ /**
7
+ * @title PayloadClassesEnforcer — the INFORMATION-FLOW caveat (spec 410 §7)
8
+ * @notice Where a read precedes a write in one plan — read a member's record, then send a message — the
9
+ * mandate names, as ontology classes, what the write MAY CARRY: `apvault:ContactEmail`, never
10
+ * `apvault:GivingHistory`. terms = abi.encode(string[] classIris).
11
+ *
12
+ * THE CHAIN CANNOT READ A PAYLOAD, and this enforcer does not pretend to: its hooks are pure no-ops.
13
+ * What it does is pin the terms INTO THE SIGNED DELEGATION — the caveat is part of the EIP-712 hash
14
+ * the person approved — so the off-chain per-step verifier (`delegation.evaluateCaveats`, strict)
15
+ * judges the write's declared payload classes (the tool contract's `carries`, per argument) against
16
+ * exactly what was signed, and nobody can widen the list without a new signature. An enforcer that
17
+ * judged nothing and pinned nothing would be a comment; this one pins.
18
+ *
19
+ * What it is NOT: authority over the read (the read has its own mandate and scope), a content
20
+ * filter, or a substitute for the vault's per-record scope — those are enforced where the data is.
21
+ */
22
+ contract PayloadClassesEnforcer is ICaveatEnforcer {
23
+ function beforeHook(bytes calldata, bytes calldata, bytes32, address, address, address, uint256, bytes calldata) external pure override {}
24
+ function afterHook(bytes calldata, bytes calldata, bytes32, address, address, address, uint256, bytes calldata) external pure override {}
25
+
26
+ /// @notice The classes a wire's terms name — for a reader with the wire and no SDK.
27
+ function classesOf(bytes calldata terms) external pure returns (string[] memory) {
28
+ return abi.decode(terms, (string[]));
29
+ }
30
+ }
@@ -0,0 +1,257 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import "../agency/ICaveatEnforcer.sol";
5
+ import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
6
+
7
+ interface IPaymentReceiptRegistry {
8
+ function record(
9
+ bytes32 mandateId,
10
+ address payer,
11
+ address payee,
12
+ address asset,
13
+ uint256 amount,
14
+ bytes32 resourceHash,
15
+ bytes32 delegationHash,
16
+ bytes32 nonce
17
+ ) external;
18
+ }
19
+
20
+ /**
21
+ * @title PaymentEnforcer
22
+ * @notice x402 pay-per-use caveat enforcer (spec 272, PAY-CON-1). Constrains a redeemed PAYMENT
23
+ * delegation to EXACTLY a capped `IERC20.transfer(treasury, amount)`, with a per-delegation
24
+ * aggregate spend cap, a windowed frequency cap, and a single-use nonce (on-chain replay
25
+ * guard). Fuses smart-agent's AllocationLimit (spend) + RateLimit (window) into one
26
+ * `beforeHook` so spend, frequency, and binding are checked ATOMICALLY — a charge that passes
27
+ * the rate limit but busts the budget reverts the whole redemption as a unit (spec §2 divergence).
28
+ *
29
+ * @dev terms = abi.encode(
30
+ * address treasury, address asset, uint256 maxAmountPerCharge,
31
+ * uint256 maxAggregate, uint32 maxRedemptionsPerWindow, uint32 windowSeconds) // 192 bytes
32
+ * args = abi.encode(bytes32 mandateId, bytes32 nonce, bytes32 resourceHash)
33
+ *
34
+ * State is keyed [delegator][delegationHash] so sibling delegations never cross-interfere
35
+ * (a redeemer can't bypass the cap by re-anchoring under a different delegation).
36
+ *
37
+ * Fail-closed (spec §9): wrong/zero asset or treasury, non-`transfer` calldata, wrong
38
+ * recipient/amount, ANY cap breach, or a reused nonce reverts and blocks the whole
39
+ * `DelegationManager.redeemDelegation`. The state SSTOREs are atomic with the underlying
40
+ * transfer — if Phase-2 execution reverts, the budget/nonce writes revert with it.
41
+ *
42
+ * `transfer`-only by construction (spec §163): `target == asset` rejects multicall/router
43
+ * targets; the 68-byte length + selector check rejects `transferFrom`/`approve`/extra-arg
44
+ * smuggling; `value == 0` rejects ETH; the DelegationManager's single (target,value,data)
45
+ * redemption shape rejects batch/delegatecall.
46
+ */
47
+ contract PaymentEnforcer is ICaveatEnforcer {
48
+ bytes4 private constant TRANSFER_SELECTOR = IERC20.transfer.selector; // 0xa9059cbb
49
+
50
+ struct Budget {
51
+ uint256 spent; // cumulative against maxAggregate
52
+ uint64 windowStart; // start of the current frequency window
53
+ uint32 callsInWindow; // redemptions so far in the current window
54
+ }
55
+
56
+ /// delegator => delegationHash => budget/window state
57
+ mapping(address => mapping(bytes32 => Budget)) private _budgets;
58
+ /// delegator => delegationHash => nonce => consumed (on-chain replay guard)
59
+ mapping(address => mapping(bytes32 => mapping(bytes32 => bool))) private _nonceUsed;
60
+
61
+ /// @notice M1 (seam audit): keccak256(delegator, delegationHash, nonce) => (treasury balanceBefore + 1).
62
+ /// Snapshotted in `beforeHook`; consumed in `afterHook` to verify the transfer ACTUALLY moved
63
+ /// `amount` to the treasury before the settlement receipt is written. `+1` sentinel so a set
64
+ /// entry is distinguishable from an unset slot even when the treasury balance is 0. Set and
65
+ /// deleted within a single non-reentrant `redeemDelegation`, so it never persists across txs.
66
+ mapping(bytes32 => uint256) private _settleSnap;
67
+
68
+ /// @notice The ONLY authorized caller of the hooks (EXT-PMT-1 / C-NEW-1). Unlike the stateless
69
+ /// enforcers (timestamp/value/targets/methods), this enforcer MUTATES state (budget, nonce)
70
+ /// and writes a settlement receipt — so it is NOT safe to call externally. A direct caller
71
+ /// that is not the DelegationManager could otherwise forge a `PaymentSettled` receipt and
72
+ /// grief the victim's budget/nonce with no actual transfer. Bound immutably at deploy; the
73
+ /// hooks revert `NotDelegationManager` for any other `msg.sender`.
74
+ address public immutable delegationManager;
75
+
76
+ /// @notice Trustless receipt sink (PAY-CON-4). Immutable; `address(0)` disables registry receipts
77
+ /// (the `PaymentCharged` event below is always the primary on-chain receipt).
78
+ IPaymentReceiptRegistry public immutable receiptRegistry;
79
+
80
+ event PaymentCharged(
81
+ address indexed delegator,
82
+ bytes32 indexed delegationHash,
83
+ bytes32 indexed mandateId,
84
+ address treasury,
85
+ address asset,
86
+ uint256 amount,
87
+ bytes32 nonce,
88
+ bytes32 resourceHash,
89
+ uint256 totalSpent,
90
+ uint32 callsInWindow
91
+ );
92
+
93
+ error InvalidTerms();
94
+ error ValueNotZero();
95
+ error AssetMismatch(address expectedAsset, address target);
96
+ error NotTransferCall();
97
+ error WrongRecipient(address treasury, address to);
98
+ error ChargeExceedsMax(uint256 amount, uint256 maxAmountPerCharge);
99
+ error AggregateExceeded(uint256 spent, uint256 maxAggregate, uint256 amount);
100
+ error FrequencyExceeded(uint32 callsInWindow, uint32 maxRedemptionsPerWindow);
101
+ error NonceReused(bytes32 nonce);
102
+ error NotDelegationManager(address caller);
103
+ /// @notice M1 (seam audit): the transfer did not move `amount` to the treasury (a token that returns
104
+ /// false without reverting, a fee-on-transfer skim, or a missing beforeHook snapshot) — so no
105
+ /// settlement receipt is written and the whole redemption reverts.
106
+ error SettlementNotObserved();
107
+
108
+ /// @dev The hooks are state-mutating + receipt-emitting, so ONLY the DelegationManager may invoke
109
+ /// them (EXT-PMT-1). `_runBeforeHooks`/`_runAfterHooks` call the enforcer directly, so during a
110
+ /// real `redeemDelegation` msg.sender IS the DelegationManager. The `verifyAuthorization` view
111
+ /// path staticcalls the hook from the same DelegationManager and still reverts on the SSTORE
112
+ /// under staticcall (yields `false`), exactly as before — the modifier does not change that.
113
+ modifier onlyDelegationManager() {
114
+ if (msg.sender != delegationManager) revert NotDelegationManager(msg.sender);
115
+ _;
116
+ }
117
+
118
+ constructor(address delegationManager_, address receiptRegistry_) {
119
+ require(delegationManager_ != address(0), "PaymentEnforcer: zero DelegationManager");
120
+ delegationManager = delegationManager_;
121
+ receiptRegistry = IPaymentReceiptRegistry(receiptRegistry_);
122
+ }
123
+
124
+ function beforeHook(
125
+ bytes calldata terms,
126
+ bytes calldata args,
127
+ bytes32 delegationHash,
128
+ address delegator,
129
+ address, /*redeemer*/
130
+ address target,
131
+ uint256 value,
132
+ bytes calldata callData
133
+ ) external override onlyDelegationManager {
134
+ // ── terms (immutable, set at delegation creation) ──
135
+ if (terms.length != 192) revert InvalidTerms();
136
+ (
137
+ address treasury,
138
+ address asset,
139
+ uint256 maxPerCharge,
140
+ uint256 maxAggregate,
141
+ uint32 maxPerWindow,
142
+ uint32 windowSeconds
143
+ ) = abi.decode(terms, (address, address, uint256, uint256, uint32, uint32));
144
+ if (
145
+ treasury == address(0) || asset == address(0) || maxPerCharge == 0 || maxAggregate < maxPerCharge
146
+ || maxPerWindow == 0 || windowSeconds == 0
147
+ ) {
148
+ revert InvalidTerms();
149
+ }
150
+
151
+ // ── calldata MUST be exactly IERC20.transfer(treasury, amount): single call, no ETH ──
152
+ if (value != 0) revert ValueNotZero();
153
+ if (target != asset) revert AssetMismatch(asset, target);
154
+ if (callData.length != 68) revert NotTransferCall(); // 4 + 32 + 32; rejects transferFrom/approve/extra args
155
+ if (bytes4(callData[0:4]) != TRANSFER_SELECTOR) revert NotTransferCall();
156
+ (address to, uint256 amount) = abi.decode(callData[4:], (address, uint256));
157
+ if (to != treasury) revert WrongRecipient(treasury, to);
158
+ if (amount > maxPerCharge) revert ChargeExceedsMax(amount, maxPerCharge);
159
+
160
+ // ── replay: single-use nonce per delegation (on-chain idempotency, PAY-RAIL-4) ──
161
+ (bytes32 mandateId, bytes32 nonce, bytes32 resourceHash) = abi.decode(args, (bytes32, bytes32, bytes32));
162
+ if (_nonceUsed[delegator][delegationHash][nonce]) revert NonceReused(nonce);
163
+ _nonceUsed[delegator][delegationHash][nonce] = true;
164
+
165
+ Budget storage b = _budgets[delegator][delegationHash];
166
+
167
+ // ── aggregate spend cap (port AllocationLimitEnforcer) ──
168
+ uint256 nextSpent = b.spent + amount;
169
+ if (nextSpent > maxAggregate) revert AggregateExceeded(b.spent, maxAggregate, amount);
170
+
171
+ // ── windowed frequency cap; roll on expiry (port RateLimitEnforcer) ──
172
+ uint64 nowTs = uint64(block.timestamp);
173
+ if (b.windowStart == 0 || nowTs >= b.windowStart + windowSeconds) {
174
+ b.windowStart = nowTs;
175
+ b.callsInWindow = 0;
176
+ }
177
+ uint32 nextCalls = b.callsInWindow + 1;
178
+ if (nextCalls > maxPerWindow) revert FrequencyExceeded(b.callsInWindow, maxPerWindow);
179
+
180
+ b.spent = nextSpent;
181
+ b.callsInWindow = nextCalls;
182
+
183
+ emit PaymentCharged(
184
+ delegator, delegationHash, mandateId, treasury, asset, amount, nonce, resourceHash, nextSpent, nextCalls
185
+ );
186
+
187
+ // M1 (seam audit): snapshot the treasury balance BEFORE the transfer. The trustless settlement
188
+ // receipt (PAY-CON-4) is written in `afterHook` ONLY once the transfer is observed to have moved
189
+ // `amount` to the treasury — a token that returns false without reverting (or a fee-on-transfer
190
+ // skim) then records NO receipt and reverts the whole redemption, so "a settled charge always has
191
+ // a receipt and an unsettled one never does" holds against the value that ACTUALLY moved.
192
+ _settleSnap[_settleKey(delegator, delegationHash, nonce)] = IERC20(asset).balanceOf(treasury) + 1;
193
+ }
194
+
195
+ function afterHook(
196
+ bytes calldata terms,
197
+ bytes calldata args,
198
+ bytes32 delegationHash,
199
+ address delegator,
200
+ address, /*redeemer*/
201
+ address, /*target*/
202
+ uint256, /*value*/
203
+ bytes calldata callData
204
+ ) external override onlyDelegationManager {
205
+ // Only this enforcer's own 192-byte-terms caveat carries a snapshot (beforeHook validated the
206
+ // shape); ignore anything else defensively so a malformed sibling caveat can't revert settlement.
207
+ if (terms.length != 192) return;
208
+ (address treasury, address asset,,,,) = abi.decode(terms, (address, address, uint256, uint256, uint32, uint32));
209
+ (bytes32 mandateId, bytes32 nonce, bytes32 resourceHash) = abi.decode(args, (bytes32, bytes32, bytes32));
210
+ (, uint256 amount) = abi.decode(callData[4:], (address, uint256));
211
+
212
+ bytes32 key = _settleKey(delegator, delegationHash, nonce);
213
+ uint256 snap = _settleSnap[key];
214
+ if (snap == 0) revert SettlementNotObserved(); // no beforeHook snapshot (defensive)
215
+ delete _settleSnap[key];
216
+
217
+ // The treasury must have received AT LEAST `amount` since the snapshot. A silent transfer failure
218
+ // (balance unchanged) or a fee-on-transfer short-delivery fails this and reverts the redemption.
219
+ if (IERC20(asset).balanceOf(treasury) < (snap - 1) + amount) revert SettlementNotObserved();
220
+
221
+ if (address(receiptRegistry) != address(0)) {
222
+ receiptRegistry.record(mandateId, delegator, treasury, asset, amount, resourceHash, delegationHash, nonce);
223
+ }
224
+ }
225
+
226
+ /// @dev Unique per redemption — the nonce is single-use per [delegator][delegationHash].
227
+ function _settleKey(address delegator, bytes32 delegationHash, bytes32 nonce) private pure returns (bytes32) {
228
+ return keccak256(abi.encode(delegator, delegationHash, nonce));
229
+ }
230
+
231
+ // ── views (off-chain budget display + idempotency checks) ──
232
+
233
+ function getBudget(address delegator, bytes32 delegationHash)
234
+ external
235
+ view
236
+ returns (uint256 spent, uint64 windowStart, uint32 callsInWindow)
237
+ {
238
+ Budget storage b = _budgets[delegator][delegationHash];
239
+ return (b.spent, b.windowStart, b.callsInWindow);
240
+ }
241
+
242
+ function isNonceUsed(address delegator, bytes32 delegationHash, bytes32 nonce) external view returns (bool) {
243
+ return _nonceUsed[delegator][delegationHash][nonce];
244
+ }
245
+
246
+ /// @notice Encode the immutable caveat terms (mirrors `delegation.buildPaymentMandateCaveats`).
247
+ function encodeTerms(
248
+ address treasury,
249
+ address asset,
250
+ uint256 maxAmountPerCharge,
251
+ uint256 maxAggregate,
252
+ uint32 maxRedemptionsPerWindow,
253
+ uint32 windowSeconds
254
+ ) external pure returns (bytes memory) {
255
+ return abi.encode(treasury, asset, maxAmountPerCharge, maxAggregate, maxRedemptionsPerWindow, windowSeconds);
256
+ }
257
+ }
@@ -68,12 +68,23 @@ import "../libraries/SignatureSlotRecovery.sol";
68
68
  * Only the first `threshold` slots are checked. Excess entries
69
69
  * beyond the threshold are ignored — callers SHOULD NOT pad blobs
70
70
  * unnecessarily as calldata cost scales linearly.
71
+ *
72
+ * R6.7 — Stateless validator; no `whenNotPaused` modifier needed.
73
+ * `beforeHook` is `external view` (reads `block.chainid`), `afterHook`
74
+ * is `external pure` (empty body); contract has zero storage
75
+ * variables. The DM-side pause check in
76
+ * `DelegationManager.redeemDelegation` gates all reachable enforcer
77
+ * dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
78
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
71
79
  */
72
80
  contract QuorumEnforcer is ICaveatEnforcer {
73
81
  error InsufficientQuorum(uint256 supplied, uint8 threshold);
74
82
  error UnauthorizedSigner(address signer);
75
83
  error DuplicateOrUnsortedSigner(address signer);
76
84
  error PayloadHashMismatch(bytes32 expected, bytes32 supplied);
85
+ /// @notice EN-11: a degenerate quorum caveat (threshold 0, or a threshold the
86
+ /// signer set can never satisfy) must fail closed, not pass with zero sigs.
87
+ error InvalidThreshold(uint8 threshold, uint256 signerSetSize);
77
88
 
78
89
  /// @notice Typehash for the quorum-action binding (contract audit C-4).
79
90
  /// @dev Bound to (chainId, enforcer, delegationHash, delegator, redeemer,
@@ -127,6 +138,15 @@ contract QuorumEnforcer is ICaveatEnforcer {
127
138
  abi.decode(terms, (address[], uint8, address));
128
139
  (bytes32 suppliedPayloadHash, bytes memory signatures) = abi.decode(args, (bytes32, bytes));
129
140
 
141
+ // EN-11: fail closed on a degenerate quorum. threshold == 0 would skip the
142
+ // verification loop entirely AND make `signatures.length < 0` unreachable, so
143
+ // the caveat would pass with ZERO signatures. A threshold larger than the
144
+ // signer set is unsatisfiable; reject it up front rather than running out of
145
+ // slots mid-loop.
146
+ if (threshold == 0 || threshold > signerSet.length) {
147
+ revert InvalidThreshold(threshold, signerSet.length);
148
+ }
149
+
130
150
  // Contract audit C-4: bind the signed payload to the actual
131
151
  // execution context. Previously the redeemer chose payloadHash
132
152
  // freely, so a quorum signed off-chain to "approve a transfer
@@ -159,7 +179,10 @@ contract QuorumEnforcer is ICaveatEnforcer {
159
179
  expectedPayloadHash,
160
180
  signatures,
161
181
  i,
162
- approvedHashRegistry
182
+ approvedHashRegistry,
183
+ // Spec 302 W2 — quorum passkey signers are custodians OF THE
184
+ // DELEGATOR account; their v=2 PIA is scoped to it.
185
+ delegator
163
186
  );
164
187
 
165
188
  // Sorted-ascending check (also rejects duplicates).
@@ -8,6 +8,13 @@ import "../agency/ICaveatEnforcer.sol";
8
8
  * @notice Enforces a time window — delegation is only valid between two timestamps.
9
9
  * @dev terms = abi.encode(uint256 validAfter, uint256 validUntil)
10
10
  * Follows ERC-7710 / MetaMask DeleGator beforeHook/afterHook pattern.
11
+ *
12
+ * R6.7 — Stateless validator; no `whenNotPaused` modifier needed.
13
+ * `beforeHook` is `external view` (reads `block.timestamp`); contract
14
+ * has zero storage. The DM-side pause check in
15
+ * `DelegationManager.redeemDelegation` gates all reachable enforcer
16
+ * dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
17
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
11
18
  */
12
19
  contract TimestampEnforcer is ICaveatEnforcer {
13
20
  error TimestampNotYetValid();
@@ -8,6 +8,12 @@ import "../agency/ICaveatEnforcer.sol";
8
8
  * @notice Enforces a maximum ETH value per call.
9
9
  * @dev terms = abi.encode(uint256 maxValue)
10
10
  * Follows ERC-7710 / MetaMask DeleGator beforeHook/afterHook pattern.
11
+ *
12
+ * R6.7 — Stateless validator; no `whenNotPaused` modifier needed
13
+ * (hooks are `pure`, contract has zero storage). The DM-side pause
14
+ * check in `DelegationManager.redeemDelegation` gates all
15
+ * reachable enforcer dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
16
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
11
17
  */
12
18
  contract ValueEnforcer is ICaveatEnforcer {
13
19
  error ValueExceedsLimit();