@agenticprimitives/contracts 1.0.0-alpha.46 → 1.0.0-alpha.47

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 (82) hide show
  1. package/AUDIT.md +60 -26
  2. package/deployments-base-sepolia.json +2 -0
  3. package/deployments-faithchain.json +2 -0
  4. package/deployments-hopechain.json +2 -0
  5. package/dist/abi/AgentAccount.json +175 -0
  6. package/dist/abi/AgentAccountFactory.json +47 -0
  7. package/dist/abi/AgentNameAttributeResolver.json +24 -0
  8. package/dist/abi/AgentNameRegistry.json +369 -0
  9. package/dist/abi/AgentNameUniversalResolver.json +34 -0
  10. package/dist/abi/AgentProfileResolver.json +48 -0
  11. package/dist/abi/AgentRegistryBase.json +158 -0
  12. package/dist/abi/AgentRelationship.json +212 -0
  13. package/dist/abi/AgreementRegistry.json +10 -0
  14. package/dist/abi/AttestationRegistry.json +49 -0
  15. package/dist/abi/AttributeStorage.json +24 -0
  16. package/dist/abi/CustodyPolicy.json +184 -0
  17. package/dist/abi/DelegationManager.json +96 -0
  18. package/dist/abi/DigestBindingEnforcer.json +103 -1
  19. package/dist/abi/EstateProjectionRegistry.json +137 -24
  20. package/dist/abi/GeoFeatureRegistry.json +42 -0
  21. package/dist/abi/IAgentAccountFactoryView.json +13 -0
  22. package/dist/abi/IAgentAccountGovernanceTimelockView.json +15 -0
  23. package/dist/abi/ICustodyPolicyFactoryView.json +13 -0
  24. package/dist/abi/ICustodyPolicyPasskeyView.json +50 -0
  25. package/dist/abi/IRedemptionContext.json +15 -0
  26. package/dist/abi/ITreasurySpendPolicyAccountView.json +44 -0
  27. package/dist/abi/IUpgradeVoucherView.json +26 -0
  28. package/dist/abi/OntologyTermRegistry.json +57 -0
  29. package/dist/abi/PaymentEnforcer.json +10 -0
  30. package/dist/abi/PermissionlessSubregistry.json +165 -0
  31. package/dist/abi/PricedSubregistry.json +57 -0
  32. package/dist/abi/RelationshipTypeRegistry.json +57 -0
  33. package/dist/abi/ShapeRegistry.json +57 -0
  34. package/dist/abi/SkillDefinitionRegistry.json +42 -0
  35. package/dist/abi/TreasurySpendPolicy.json +106 -1
  36. package/dist/abi/UpgradeVoucher.json +176 -0
  37. package/dist/abi/index.d.ts +6 -0
  38. package/dist/abi/index.js +6 -0
  39. package/dist/deployments/base-sepolia.d.ts +2 -0
  40. package/dist/deployments/base-sepolia.js +4 -0
  41. package/dist/deployments/faithchain.d.ts +2 -0
  42. package/dist/deployments/faithchain.js +4 -0
  43. package/dist/deployments/hopechain.d.ts +2 -0
  44. package/dist/deployments/hopechain.js +4 -0
  45. package/package.json +1 -1
  46. package/src/AgentAccount.sol +531 -92
  47. package/src/AgentAccountFactory.sol +28 -2
  48. package/src/IAgentAccount.sol +14 -0
  49. package/src/SmartAgentPaymaster.sol +30 -3
  50. package/src/UpgradeVoucher.sol +74 -0
  51. package/src/agency/DelegationManager.sol +177 -52
  52. package/src/agency/ICaveatEnforcer.sol +10 -0
  53. package/src/agency/IDelegationManager.sol +6 -5
  54. package/src/agreement/AgreementRegistry.sol +61 -17
  55. package/src/attestation/AttestationRegistry.sol +115 -22
  56. package/src/custody/CustodyPolicy.sol +393 -47
  57. package/src/custody/TreasurySpendPolicy.sol +192 -29
  58. package/src/enforcers/AllowedMethodsEnforcer.sol +6 -1
  59. package/src/enforcers/AllowedTargetsEnforcer.sol +6 -1
  60. package/src/enforcers/DigestBindingEnforcer.sol +91 -19
  61. package/src/enforcers/PaymentEnforcer.sol +32 -1
  62. package/src/enforcers/QuorumEnforcer.sol +1 -1
  63. package/src/enforcers/ValueEnforcer.sol +6 -1
  64. package/src/geo/GeoFeatureRegistry.sol +25 -1
  65. package/src/governance/AgenticGovernance.sol +16 -0
  66. package/src/identity/AgentProfileResolver.sol +11 -0
  67. package/src/naming/AgentNameAttributeResolver.sol +17 -2
  68. package/src/naming/AgentNamePredicates.sol +1 -1
  69. package/src/naming/AgentNameRegistry.sol +205 -10
  70. package/src/naming/AgentNameUniversalResolver.sol +26 -0
  71. package/src/naming/PermissionlessSubregistry.sol +69 -23
  72. package/src/naming/PricedSubregistry.sol +28 -0
  73. package/src/ontology/AttributeStorage.sol +93 -80
  74. package/src/ontology/OntologyTermRegistry.sol +28 -0
  75. package/src/ontology/ShapeRegistry.sol +28 -0
  76. package/src/payments/PaymentEscrow.sol +23 -15
  77. package/src/payments/PaymentReceiptRegistry.sol +11 -3
  78. package/src/registry/AgentRegistryBase.sol +39 -0
  79. package/src/registry/EstateProjectionRegistry.sol +94 -40
  80. package/src/relationships/AgentRelationship.sol +112 -7
  81. package/src/relationships/RelationshipTypeRegistry.sol +28 -0
  82. package/src/skills/SkillDefinitionRegistry.sol +25 -1
@@ -11,22 +11,78 @@ pragma solidity ^0.8.28;
11
11
  * redemption alike, because the account runs its hooks on both — that adds the value each call moves
12
12
  * to the current window and refuses the one that would pass the ceiling.
13
13
  *
14
- * WHAT IT COUNTS. Native value (`value` on the call) when `asset == address(0)`; otherwise ERC-20
15
- * `transfer(to, amount)` and `transferFrom(from, to, amount)` calldata aimed at `asset`. Anything else
16
- * moves no value of this asset and is not counted. A batch is one call: its inner calls are summed.
14
+ * WHAT IT COUNTS (generation 4 — spec 445 §1.5, audit CUST-2). The hook sees calldata BEFORE the call,
15
+ * so it counts what a call can COMMIT the treasury to, not what later settles:
16
+ * native budget (`asset == address(0)`):
17
+ * - the `value` of every call, and of the batch frame;
18
+ * - `withdrawTo(address,uint256)` on the account's EntryPoint (its deposit there is its own
19
+ * native balance; the call carries `value == 0`).
20
+ * ERC-20 budget, calls whose target is `asset`:
21
+ * - `transfer(to, amount)`, `transferFrom(from, to, amount)` → `amount`;
22
+ * - `approve(spender, amount)`, `increaseAllowance(spender, added)` → the amount GRANTED. An
23
+ * allowance is a promise to pay: the spender's later `transferFrom` goes straight to the token
24
+ * and no hook ever sees it, so the only place it can be counted is where it is made. An
25
+ * unlimited approval exceeds any finite ceiling and is refused;
26
+ * - `approve(spender, 0)`, `decreaseAllowance(…)` → 0. Tightening is never spend. It is also
27
+ * never CREDITED BACK: the hook cannot see how much of the old allowance was already drawn,
28
+ * so a credit would let approve → pull → approve(0) repeat without limit;
29
+ * - ANY OTHER SELECTOR on the tracked token, or calldata too short for the selector it names →
30
+ * REFUSED (`UnrecognizedTokenCall`). Fail closed: `permit` routed through the account,
31
+ * `transferAndCall`, a token-specific mover — the hook cannot price what it does not
32
+ * understand, so a budgeted treasury does not make the call.
33
+ * A batch is one call: its inner calls are summed. A payload the hook cannot decode is refused, never
34
+ * counted as zero.
35
+ *
36
+ * WHAT THE CEILING DOES NOT BOUND — stated so nobody relies on more than the code does:
37
+ * - any asset other than the ONE budgeted here (one budget per account per module instance; an
38
+ * ERC-20 budget does not count native value, and the reverse);
39
+ * - allowances that already existed when the hook was installed;
40
+ * - anything the token accepts on a SIGNATURE instead of a call from the account: EIP-2612 `permit`,
41
+ * EIP-3009 `transferWithAuthorization`, Permit2. Those are submitted by a third party and
42
+ * validated through the account's ERC-1271 — no `execute`, no hook;
43
+ * - gas: the ERC-4337 prefund the EntryPoint takes in `validateUserOp`;
44
+ * - the timing of an allowance: one granted in window 1 can be drawn in window 2, so with
45
+ * allowances the bound is CUMULATIVE (outflow through window n ≤ n × ceiling), not per window;
46
+ * - non-standard tokens whose `transfer` / `approve` do not mean what ERC-20 says (rebasing,
47
+ * fee-on-transfer, hooks), and any call the account makes through an upgrade.
17
48
  *
18
49
  * WINDOWS are fixed-length epochs from `windowStart` — never sliding — so the check is O(1) and the
19
50
  * refusal is reproducible off chain from the receipt and the block time.
20
51
  *
21
- * WHO SETS IT. The budget is the install data: `installModule(4, this, abi.encode(asset, ceiling,
22
- * windowSeconds))`, which on a custody-governed treasury is a governance selector under its quorum;
23
- * changing it is an uninstall + reinstall under the same gate. There is no setter a single key could
24
- * reach. Per-delegation ceilings are untouched: the tighter of the two refuses.
52
+ * WHO SETS IT, AND WHICH TREASURIES IT ACTUALLY PROTECTS (spec 445 §1.5, audit CUST-3 / ACCT-3).
53
+ * The budget is the install data: `installModule(4, this, abi.encode(asset, ceiling, windowSeconds))`.
54
+ * `lowerCeiling` / `setCeiling` change the ceiling in place — the window and what was spent in it are
55
+ * kept (an uninstall + reinstall would reset `spent`, handing out a second ceiling in one window).
56
+ * - CUSTODY-GOVERNED treasury (mode > 0): install, uninstall and `setCeiling` are `CustodyPolicy`
57
+ * actions at T5 (critical quorum + the 24 h floor); `lowerCeiling` at T4. No single custodian,
58
+ * delegate or module can reach any of them: on a governed account an installed module is never
59
+ * an `execute` target (`AgentAccount._rejectModuleTarget`), and a non-canonical executor module
60
+ * runs its calls through this hook and cannot dispatch account governance. HERE the ceiling
61
+ * bounds every custodian key, every delegate and every other module — everything short of the
62
+ * T5 quorum.
63
+ * - SELF-GOVERNED treasury (mode 0): the account's one credential IS its custody tier. It can
64
+ * `uninstallModule` this hook, or call `setCeiling`, in one user operation with no delay — and so
65
+ * can any EXECUTOR module that credential installed (on a mode-0 account an executor may make
66
+ * every self-call the credential can; it is that credential's equal, which is why it is retired
67
+ * with it). The ceiling there bounds DELEGATES — never the custodian key, never its executor
68
+ * modules. A mode-0 treasury's ceiling is exactly as strong as its single key. (Spec 420: assets
69
+ * live only in treasuries — a treasury that must be bounded against its own keys must be
70
+ * custody-governed.)
71
+ * On every mode a delegation stack is refused this module as a target, and `onInstall` /
72
+ * `onUninstall` verify the account's own installed flag, so `execute(this, onUninstall())` cannot
73
+ * drop the budget while the account still lists the hook.
74
+ * Per-delegation ceilings are untouched: the tighter of the two refuses.
25
75
  *
26
76
  * WHAT IT IS NOT: a policy of who may spend (that is the mandate), a rate limit on calls, or anything
27
77
  * a planner consults — the harness may READ `budget()` to say "this would exceed the treasury's
28
78
  * shared budget" before a signature (honesty); the hook is the authority.
29
79
  */
80
+ /// @dev The account's ERC-7579 module view + its EntryPoint (the native-deposit exit).
81
+ interface ITreasurySpendPolicyAccountView {
82
+ function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext) external view returns (bool);
83
+ function entryPoint() external view returns (address);
84
+ }
85
+
30
86
  contract TreasurySpendPolicy {
31
87
  struct Budget {
32
88
  address asset; // address(0) = native value
@@ -49,9 +105,28 @@ contract TreasurySpendPolicy {
49
105
  error NotInstalledOn(address account);
50
106
  error AlreadyInstalledOn(address account);
51
107
  error BadBudget();
108
+ /// @dev ACCT-3: `onInstall` by an account that does not list this hook as installed (a direct
109
+ /// `execute(hook, onInstall)`), or `onUninstall` by one that still does.
110
+ error NotInstalledAsHookOn(address account);
111
+ error StillInstalledOn(address account);
112
+ /// @dev CUST-2: calldata to the budgeted token that the hook cannot price. Fail closed.
113
+ error UnrecognizedTokenCall(bytes4 selector);
114
+ /// @dev CUST-2: the hook payload did not decode as either encoding the account produces. Fail closed.
115
+ error UndecodableCall();
116
+ /// @dev `lowerCeiling` with a value that is not strictly lower.
117
+ error NotLower(uint256 current, uint256 requested);
118
+
119
+ event CeilingChanged(address indexed account, uint256 oldCeiling, uint256 newCeiling);
120
+
121
+ uint256 private constant MODULE_TYPE_HOOK = 4;
52
122
 
53
123
  bytes4 private constant TRANSFER = bytes4(keccak256("transfer(address,uint256)"));
54
124
  bytes4 private constant TRANSFER_FROM = bytes4(keccak256("transferFrom(address,address,uint256)"));
125
+ bytes4 private constant APPROVE = bytes4(keccak256("approve(address,uint256)"));
126
+ bytes4 private constant INCREASE_ALLOWANCE = bytes4(keccak256("increaseAllowance(address,uint256)"));
127
+ bytes4 private constant DECREASE_ALLOWANCE = bytes4(keccak256("decreaseAllowance(address,uint256)"));
128
+ /// @dev `IStakeManager.withdrawTo(address payable, uint256)` — the account's EntryPoint deposit leaving.
129
+ bytes4 private constant WITHDRAW_TO = bytes4(keccak256("withdrawTo(address,uint256)"));
55
130
 
56
131
  // ─── ERC-7579 module surface ───────────────────────────────────────
57
132
 
@@ -59,9 +134,14 @@ contract TreasurySpendPolicy {
59
134
  function moduleId() external pure returns (string memory) { return "agenticprimitives-treasury-spend-policy-1"; }
60
135
 
61
136
  /// @notice Called by the account from `installModule` (governance-gated there): the budget is the install data.
137
+ /// @dev ACCT-3: the caller must be an account that is INSTALLING this hook — `installModule` sets its
138
+ /// installed flag before calling here. A caller that cannot answer the view reverts (fail closed).
62
139
  function onInstall(bytes calldata initData) external {
63
140
  Budget storage b = _budgets[msg.sender];
64
141
  if (b.installed) revert AlreadyInstalledOn(msg.sender);
142
+ if (!ITreasurySpendPolicyAccountView(msg.sender).isModuleInstalled(MODULE_TYPE_HOOK, address(this), "")) {
143
+ revert NotInstalledAsHookOn(msg.sender);
144
+ }
65
145
  (address asset, uint256 ceiling, uint64 windowSeconds) = abi.decode(initData, (address, uint256, uint64));
66
146
  if (windowSeconds == 0) revert BadBudget();
67
147
  b.asset = asset;
@@ -74,26 +154,60 @@ contract TreasurySpendPolicy {
74
154
  emit BudgetInstalled(msg.sender, asset, ceiling, windowSeconds, b.windowStart);
75
155
  }
76
156
 
157
+ /// @dev ACCT-3 (the R917-C-1 pattern `CustodyPolicy.onUninstall` uses): the account must have ALREADY
158
+ /// dropped this hook. `AgentAccount.uninstallModule` clears its flag before calling here; any other
159
+ /// caller that is the account — a custodian's `execute(hook, onUninstall())`, a delegation, another
160
+ /// module — still lists the hook and is refused, so the budget cannot be deleted while the account
161
+ /// keeps calling `preCheck` on a hook that no longer counts.
77
162
  function onUninstall(bytes calldata) external {
78
163
  if (!_budgets[msg.sender].installed) revert NotInstalledOn(msg.sender);
164
+ if (ITreasurySpendPolicyAccountView(msg.sender).isModuleInstalled(MODULE_TYPE_HOOK, address(this), "")) {
165
+ revert StillInstalledOn(msg.sender);
166
+ }
79
167
  delete _budgets[msg.sender];
80
168
  emit BudgetUninstalled(msg.sender);
81
169
  }
82
170
 
171
+ // ─── Changing the ceiling in place (spec 445 §1.5, CUST-3) ─────────
172
+
173
+ /// @notice Tighten the ceiling. `msg.sender` is the account. Reverts unless `newCeiling` is strictly
174
+ /// lower — which is why a custody quorum may reach it at T4 (`CustodyAction.LowerSpendCeiling`).
175
+ /// The window and the amount already spent in it are kept; if `spent` is already above the new
176
+ /// ceiling, nothing more is spendable until the window rolls.
177
+ function lowerCeiling(uint256 newCeiling) external {
178
+ Budget storage b = _budgets[msg.sender];
179
+ if (!b.installed) revert NotInstalledOn(msg.sender);
180
+ if (newCeiling >= b.ceiling) revert NotLower(b.ceiling, newCeiling);
181
+ emit CeilingChanged(msg.sender, b.ceiling, newCeiling);
182
+ b.ceiling = newCeiling;
183
+ }
184
+
185
+ /// @notice Set the ceiling to any value — this is the call that can RAISE it. `msg.sender` is the account;
186
+ /// on a custody-governed treasury the only route is `CustodyAction.SetSpendCeiling` (T5). On a
187
+ /// self-governed treasury the one credential reaches it directly (see the contract notice).
188
+ function setCeiling(uint256 newCeiling) external {
189
+ Budget storage b = _budgets[msg.sender];
190
+ if (!b.installed) revert NotInstalledOn(msg.sender);
191
+ emit CeilingChanged(msg.sender, b.ceiling, newCeiling);
192
+ b.ceiling = newCeiling;
193
+ }
194
+
83
195
  // ─── The hook ──────────────────────────────────────────────────────
84
196
 
85
197
  /// @notice `preCheck` from the account: `msgData` is `abi.encode(target, value, data)` for `execute` and
86
198
  /// `abi.encode(Call[])` for `executeBatch`. Sums the value this call moves in the budget's asset and
87
199
  /// refuses when the window's total would pass the ceiling.
88
- function preCheck(address, uint256, bytes calldata msgData) external returns (bytes memory) {
200
+ function preCheck(address, uint256 value, bytes calldata msgData) external returns (bytes memory) {
89
201
  Budget storage b = _budgets[msg.sender];
90
202
  if (!b.installed) return hex"";
91
- uint256 amount = _valueMoved(b.asset, msgData);
203
+ uint256 amount = _valueMoved(b.asset, value, msgData);
92
204
  if (amount == 0) return hex"";
93
205
  uint64 idx = uint64((block.timestamp - b.windowStart) / b.windowSeconds);
94
206
  if (idx != b.windowIndex) { b.windowIndex = idx; b.spent = 0; }
207
+ // Compared without adding first: `amount` may be type(uint256).max (an unlimited approval), and
208
+ // `spent` may sit above a ceiling that was lowered mid-window.
209
+ if (b.spent > b.ceiling || amount > b.ceiling - b.spent) revert BudgetExceeded(b.ceiling, b.spent, amount);
95
210
  uint256 next = b.spent + amount;
96
- if (next > b.ceiling) revert BudgetExceeded(b.ceiling, b.spent, amount);
97
211
  b.spent = next;
98
212
  emit Spent(msg.sender, idx, amount, next);
99
213
  return hex"";
@@ -120,21 +234,49 @@ contract TreasurySpendPolicy {
120
234
  // ─── Internals ─────────────────────────────────────────────────────
121
235
 
122
236
  /// @dev Both encodings the account uses, told apart by the first word: `abi.encode(Call[])` opens with the
123
- /// array's offset (exactly 0x20), `abi.encode(target, value, data)` with the target address — and no
124
- /// contract lives at address 0x20. The decode runs through an external self-call so a malformed payload
125
- /// is caught rather than reverting the account's call (abi.decode cannot be tried in place).
126
- function _valueMoved(address asset, bytes calldata msgData) internal view returns (uint256 total) {
127
- if (msgData.length < 32) return 0;
128
- uint256 first = uint256(bytes32(msgData[0:32]));
129
- if (first == 0x20) {
237
+ /// array's offset (exactly 0x20), `abi.encode(target, value, data)` with the target address.
238
+ ///
239
+ /// FAIL CLOSED (CUST-2). Before generation 4 a payload that did not decode was counted as ZERO —
240
+ /// a fail-open on the one input the ceiling depends on. It is now refused (`UndecodableCall`). The
241
+ /// decode runs through an external self-call only so the failure can be turned into that error.
242
+ ///
243
+ /// The 0x20 ambiguity: a SINGLE call whose target is the address 0x20 also opens with 0x20, and its
244
+ /// remaining words can be shaped to decode as a harmless batch. For a native budget that would have
245
+ /// let the call's real value go uncounted, so in the batch branch the frame's own `value` (what the
246
+ /// account says it is sending: the real value for `execute`, 0 for `executeBatch`) is added. For an
247
+ /// ERC-20 budget the real call goes to 0x20, which is not the token: nothing to count.
248
+ function _valueMoved(address asset, uint256 frameValue, bytes calldata msgData) internal view returns (uint256 total) {
249
+ if (msgData.length < 32) revert UndecodableCall();
250
+ address ep = asset == address(0) ? _entryPointOf(msg.sender) : address(0);
251
+ if (uint256(bytes32(msgData[0:32])) == 0x20) {
130
252
  try this.decodeBatch(msgData) returns (Call[] memory calls) {
131
- for (uint256 i = 0; i < calls.length; i++) total += _amountOf(asset, calls[i].target, calls[i].value, calls[i].data);
253
+ if (asset == address(0)) total = frameValue;
254
+ for (uint256 i = 0; i < calls.length; i++) {
255
+ total = _satAdd(total, _amountOf(asset, ep, calls[i].target, calls[i].value, calls[i].data));
256
+ }
132
257
  return total;
133
- } catch { return 0; }
258
+ } catch { revert UndecodableCall(); }
134
259
  }
135
260
  try this.decodeSingle(msgData) returns (address target, uint256 value, bytes memory data) {
136
- return _amountOf(asset, target, value, data);
137
- } catch { return 0; }
261
+ return _amountOf(asset, ep, target, value, data);
262
+ } catch { revert UndecodableCall(); }
263
+ }
264
+
265
+ function _satAdd(uint256 a, uint256 b) private pure returns (uint256) {
266
+ unchecked {
267
+ uint256 c = a + b;
268
+ return c < a ? type(uint256).max : c;
269
+ }
270
+ }
271
+
272
+ /// @dev The account's EntryPoint, for the native-deposit exit. An account that cannot answer has none
273
+ /// this hook can name; its native budget then counts call value only.
274
+ function _entryPointOf(address account) private view returns (address) {
275
+ (bool ok, bytes memory ret) = account.staticcall(
276
+ abi.encodeWithSelector(ITreasurySpendPolicyAccountView.entryPoint.selector)
277
+ );
278
+ if (!ok || ret.length < 32) return address(0);
279
+ return abi.decode(ret, (address));
138
280
  }
139
281
 
140
282
  struct Call { address target; uint256 value; bytes data; }
@@ -146,21 +288,42 @@ contract TreasurySpendPolicy {
146
288
  return abi.decode(msgData, (Call[]));
147
289
  }
148
290
 
149
- function _amountOf(address asset, address target, uint256 value, bytes memory data) internal pure returns (uint256) {
150
- if (asset == address(0)) return value;
151
- if (target != asset || data.length < 4) return 0;
291
+ /// @dev What ONE call commits the treasury to, in the budgeted asset. See the contract notice for the
292
+ /// rule and for what it does not cover.
293
+ function _amountOf(address asset, address ep, address target, uint256 value, bytes memory data)
294
+ internal
295
+ pure
296
+ returns (uint256)
297
+ {
152
298
  bytes4 sel;
153
- assembly { sel := mload(add(data, 32)) }
154
- if (sel == TRANSFER && data.length >= 68) {
299
+ if (data.length >= 4) {
300
+ assembly { sel := mload(add(data, 32)) }
301
+ }
302
+ if (asset == address(0)) {
303
+ // Native: the value sent, plus a withdrawal of the account's EntryPoint deposit.
304
+ if (ep != address(0) && target == ep && sel == WITHDRAW_TO) {
305
+ if (data.length < 68) revert UnrecognizedTokenCall(sel);
306
+ uint256 withdrawn;
307
+ assembly { withdrawn := mload(add(data, 68)) }
308
+ return _satAdd(value, withdrawn);
309
+ }
310
+ return value;
311
+ }
312
+ if (target != asset) return 0;
313
+ // The budgeted token. Every selector is either priced or refused.
314
+ if (sel == TRANSFER || sel == APPROVE || sel == INCREASE_ALLOWANCE) {
315
+ if (data.length < 68) revert UnrecognizedTokenCall(sel);
155
316
  uint256 amount;
156
317
  assembly { amount := mload(add(data, 68)) }
157
- return amount;
318
+ return amount; // approve(…, 0) → 0: a revocation is not spend (and is never credited back)
158
319
  }
159
- if (sel == TRANSFER_FROM && data.length >= 100) {
320
+ if (sel == TRANSFER_FROM) {
321
+ if (data.length < 100) revert UnrecognizedTokenCall(sel);
160
322
  uint256 amount;
161
323
  assembly { amount := mload(add(data, 100)) }
162
324
  return amount;
163
325
  }
164
- return 0;
326
+ if (sel == DECREASE_ALLOWANCE && data.length >= 68) return 0;
327
+ revert UnrecognizedTokenCall(sel);
165
328
  }
166
329
  }
@@ -13,7 +13,12 @@ import "../agency/ICaveatEnforcer.sol";
13
13
  * (hooks are `pure`, contract has zero storage). The DM-side pause
14
14
  * check in `DelegationManager.redeemDelegation` gates all
15
15
  * reachable enforcer dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
16
- * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
16
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`. *
17
+ * Spec 445 / audit DLG-2 — SCOPE. This enforcer judges the ONE `(target, value, callData)` the
18
+ * DelegationManager was asked to execute, nothing nested inside it. That is the whole call a
19
+ * delegation can cause only because the manager refuses a redemption whose target is the
20
+ * executing account itself (`SelfTargetedRedemption`) — the route by which a self-`executeBatch`
21
+ * once ran inner calls no enforcer saw. Do not reuse this enforcer under a manager without that rule.
17
22
  */
18
23
  contract AllowedMethodsEnforcer is ICaveatEnforcer {
19
24
  error MethodNotAllowed();
@@ -13,7 +13,12 @@ import "../agency/ICaveatEnforcer.sol";
13
13
  * (hooks are `pure`, contract has zero storage). The DM-side pause
14
14
  * check in `DelegationManager.redeemDelegation` gates all
15
15
  * reachable enforcer dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
16
- * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
16
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`. *
17
+ * Spec 445 / audit DLG-2 — SCOPE. This enforcer judges the ONE `(target, value, callData)` the
18
+ * DelegationManager was asked to execute, nothing nested inside it. That is the whole call a
19
+ * delegation can cause only because the manager refuses a redemption whose target is the
20
+ * executing account itself (`SelfTargetedRedemption`) — the route by which a self-`executeBatch`
21
+ * once ran inner calls no enforcer saw. Do not reuse this enforcer under a manager without that rule.
17
22
  */
18
23
  contract AllowedTargetsEnforcer is ICaveatEnforcer {
19
24
  error TargetNotAllowed();
@@ -9,7 +9,7 @@ import "../agency/ICaveatEnforcer.sol";
9
9
  * projection, an accepted offer — so that the delegation is a MANDATE (spec 336 §8.3, spec 350
10
10
  * §2): authority *for a reason*, not authority for any purpose until revoked.
11
11
  *
12
- * @dev terms = abi.encode(bytes32 kind, bytes32 digest)
12
+ * @dev terms = abi.encode(bytes32 kind, bytes32 digest[, uint256 maxUses]) — signed by the delegator
13
13
  * args = abi.encode(bytes32 presented, bytes32 stepNonce) — supplied by the redeemer at redemption
14
14
  *
15
15
  * `kind` names WHICH artifact the digest is of, so an off-chain reader can tell an intent binding
@@ -35,28 +35,70 @@ import "../agency/ICaveatEnforcer.sol";
35
35
  * now committed, on chain, to that intent, and a step whose real intent differs is caught by the
36
36
  * verifier that computed the digest from the step rather than from the caveat.
37
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.
38
+ * SINGLE USE IS WHAT THE DELEGATOR SIGNED (spec 445 / audit DLG-3; supersedes R917-C-4's rule).
39
+ * Generation 2–3 consumed a redemption under `(delegator, delegationHash, kind, stepNonce)` with
40
+ * `stepNonce` read from `args`. `args` are outside the signed delegation hash by design, so the
41
+ * party the caveat constrains chose the key: one mandate was redeemed five times with five fresh
42
+ * nonces. The bound now lives in the SIGNED `terms`:
43
+ *
44
+ * terms = abi.encode(bytes32 kind, bytes32 digest) — 64 bytes: ONE redemption
45
+ * terms = abi.encode(bytes32 kind, bytes32 digest, uint256 maxUses) — 96 bytes: at most
46
+ * `maxUses` (>= 1)
47
+ * args = abi.encode(bytes32 presented, bytes32 stepNonce) — unchanged
48
+ *
49
+ * A counter keyed `(delegator, delegationHash, kind)` — nothing the redeemer supplies — is
50
+ * incremented in `beforeHook` and may not pass the signed bound (`UsesExhausted`). A mandate that
51
+ * legitimately covers N on-chain steps says N in its terms; the (N+1)-th redemption reverts
52
+ * whatever nonce it brings. The 64-byte form is the strict reading of "single use": a mandate
53
+ * built by a mirror that has not learned the count redeems once and then fails closed.
54
+ *
55
+ * `stepNonce` keeps its job as the step's on-chain IDENTITY (the harness derives it from the
56
+ * intent digest and the step's operation id, the same derivation as `PaymentEnforcer`'s nonce):
57
+ * a replay of one step reverts `StepNonceReused` even while uses remain, and `isUsed` answers
58
+ * "did this step redeem?" for resume-with-recheck. It is recorded per REDEEMER, so where a
59
+ * delegation is open, or a grant has been re-delegated to several parties, one party cannot
60
+ * mark another's step as done by redeeming under the same nonce. The COUNT is deliberately not
61
+ * per redeemer — the delegator signed a total, and a per-redeemer count on an open delegation
62
+ * would be no bound at all. Consequence, stated: on an OPEN delegation any redeemer can spend
63
+ * the signed uses (each spend still has to pass every other caveat and execute the call). A
64
+ * mandate that must not be raced names its delegate; then the manager admits nobody else.
65
+ *
66
+ * A use is spent only by a redemption that completes: the write happens in `beforeHook`, inside
67
+ * `DelegationManager.redeemDelegation`'s single transaction with no try/catch around hooks or
68
+ * execution, so a later caveat, the executed call, or an after-hook reverting rolls the use and
69
+ * the nonce back with everything else.
70
+ *
71
+ * The hooks mutate state and are `onlyDelegationManager` (EXT-PMT-1's rule for stateful
72
+ * enforcers): a stranger cannot spend a use or a nonce outside a valid redemption.
45
73
  */
46
74
  contract DigestBindingEnforcer is ICaveatEnforcer {
47
75
  error BadTermsLength();
48
76
  error BadArgsLength();
77
+ error ZeroMaxUses();
49
78
  error DigestMismatch(bytes32 kind, bytes32 bound, bytes32 presented);
50
79
  error StepNonceReused(bytes32 kind, bytes32 stepNonce);
80
+ /// @notice The signed bound is spent: `maxUses` redemptions of this binding have already happened.
81
+ error UsesExhausted(bytes32 kind, uint256 maxUses);
51
82
  error NotDelegationManager(address caller);
52
83
 
53
- /// @notice The ONLY authorized caller of `beforeHook` — it consumes a nonce (R917-C-4).
84
+ /// @notice The ONLY authorized caller of `beforeHook` — it consumes a use.
54
85
  address public immutable delegationManager;
55
86
 
56
- /// delegator => delegationHash => keccak256(kind, stepNonce) => consumed
87
+ /// delegator => delegationHash => kind => redemptions so far (bounded by the SIGNED terms)
88
+ mapping(address => mapping(bytes32 => mapping(bytes32 => uint256))) private _uses;
89
+ /// delegator => delegationHash => keccak256(kind, redeemer, stepNonce) => consumed
57
90
  mapping(address => mapping(bytes32 => mapping(bytes32 => bool))) private _used;
58
91
 
59
- event DigestBindingRedeemed(address indexed delegator, bytes32 indexed delegationHash, bytes32 indexed kind, bytes32 presented, bytes32 stepNonce);
92
+ event DigestBindingRedeemed(
93
+ address indexed delegator,
94
+ bytes32 indexed delegationHash,
95
+ bytes32 indexed kind,
96
+ bytes32 presented,
97
+ bytes32 stepNonce,
98
+ address redeemer,
99
+ uint256 use,
100
+ uint256 maxUses
101
+ );
60
102
 
61
103
  constructor(address delegationManager_) {
62
104
  require(delegationManager_ != address(0), "DigestBindingEnforcer: zero DelegationManager");
@@ -68,9 +110,32 @@ contract DigestBindingEnforcer is ICaveatEnforcer {
68
110
  _;
69
111
  }
70
112
 
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))];
113
+ /// @notice Whether `redeemer` already redeemed `stepNonce` under this binding (a step's
114
+ /// "did it happen" check — recorded per redeemer, see the contract note).
115
+ function isUsed(address delegator, bytes32 delegationHash, bytes32 kind, address redeemer, bytes32 stepNonce)
116
+ external
117
+ view
118
+ returns (bool)
119
+ {
120
+ return _used[delegator][delegationHash][keccak256(abi.encode(kind, redeemer, stepNonce))];
121
+ }
122
+
123
+ /// @notice How many redemptions this binding has spent (compare with the `maxUses` in its terms).
124
+ function usesOf(address delegator, bytes32 delegationHash, bytes32 kind) external view returns (uint256) {
125
+ return _uses[delegator][delegationHash][kind];
126
+ }
127
+
128
+ /// @notice Decode a binding's signed terms. 64 bytes ⇒ `maxUses == 1`.
129
+ function decodeTerms(bytes calldata terms) public pure returns (bytes32 kind, bytes32 digest, uint256 maxUses) {
130
+ if (terms.length == 64) {
131
+ (kind, digest) = abi.decode(terms, (bytes32, bytes32));
132
+ maxUses = 1;
133
+ } else if (terms.length == 96) {
134
+ (kind, digest, maxUses) = abi.decode(terms, (bytes32, bytes32, uint256));
135
+ if (maxUses == 0) revert ZeroMaxUses();
136
+ } else {
137
+ revert BadTermsLength();
138
+ }
74
139
  }
75
140
 
76
141
  function beforeHook(
@@ -78,20 +143,27 @@ contract DigestBindingEnforcer is ICaveatEnforcer {
78
143
  bytes calldata args,
79
144
  bytes32 delegationHash,
80
145
  address delegator,
81
- address,
146
+ address redeemer,
82
147
  address,
83
148
  uint256,
84
149
  bytes calldata
85
150
  ) external override onlyDelegationManager {
86
- if (terms.length != 64) revert BadTermsLength();
151
+ (bytes32 kind, bytes32 bound, uint256 maxUses) = decodeTerms(terms);
87
152
  if (args.length != 64) revert BadArgsLength();
88
- (bytes32 kind, bytes32 bound) = abi.decode(terms, (bytes32, bytes32));
89
153
  (bytes32 presented, bytes32 stepNonce) = abi.decode(args, (bytes32, bytes32));
90
154
  if (presented != bound) revert DigestMismatch(kind, bound, presented);
91
- bytes32 slot = keccak256(abi.encode(kind, stepNonce));
155
+
156
+ // The step's identity, per redeemer: a replay of one step is refused even while uses remain.
157
+ bytes32 slot = keccak256(abi.encode(kind, redeemer, stepNonce));
92
158
  if (_used[delegator][delegationHash][slot]) revert StepNonceReused(kind, stepNonce);
93
159
  _used[delegator][delegationHash][slot] = true;
94
- emit DigestBindingRedeemed(delegator, delegationHash, kind, presented, stepNonce);
160
+
161
+ // The bound the delegator signed: keyed by nothing the redeemer supplies.
162
+ uint256 use = _uses[delegator][delegationHash][kind] + 1;
163
+ if (use > maxUses) revert UsesExhausted(kind, maxUses);
164
+ _uses[delegator][delegationHash][kind] = use;
165
+
166
+ emit DigestBindingRedeemed(delegator, delegationHash, kind, presented, stepNonce, redeemer, use, maxUses);
95
167
  }
96
168
 
97
169
  function afterHook(
@@ -4,6 +4,12 @@ pragma solidity ^0.8.28;
4
4
  import "../agency/ICaveatEnforcer.sol";
5
5
  import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
6
6
 
7
+ /// @dev The one thing this enforcer asks of its DelegationManager beyond calling the hooks: whose
8
+ /// account executes the redemption in flight (audit DLG-8c). Attribution only.
9
+ interface IRedemptionContext {
10
+ function redemptionRootDelegator() external view returns (address);
11
+ }
12
+
7
13
  interface IPaymentReceiptRegistry {
8
14
  function record(
9
15
  bytes32 mandateId,
@@ -39,6 +45,21 @@ interface IPaymentReceiptRegistry {
39
45
  * `DelegationManager.redeemDelegation`. The state SSTOREs are atomic with the underlying
40
46
  * transfer — if Phase-2 execution reverts, the budget/nonce writes revert with it.
41
47
  *
48
+ * Spec 445 / audit DLG-8:
49
+ * (a) `mandateId` and `resourceHash` come from `args`, which the delegator did NOT sign. They
50
+ * are the REDEEMER'S ASSERTION of what the charge was for, carried into the receipt so a
51
+ * reader can match it against off-chain records — never proof of it. What a receipt
52
+ * proves is the signed part: `amount` of `asset` moved from `payer` to `treasury` under
53
+ * `delegationHash`, once, for `nonce`;
54
+ * (b) a zero-amount charge is refused (`ZeroAmount`) — it satisfied every check including the
55
+ * M1 balance observation and wrote a receipt for nothing;
56
+ * (c) the receipt's `payer` is the ROOT delegator — the account the DelegationManager
57
+ * executes through and whose balance moves — read from the manager's redemption
58
+ * context. The hook's `delegator` is the delegator of the LINK that carries this caveat;
59
+ * on a derived (re-delegated) mandate that is an intermediary which paid nothing. Budget,
60
+ * window and nonce stay keyed by that link (`[delegator][delegationHash]`): they bound
61
+ * the grant the link's delegator made, whoever's funds move.
62
+ *
42
63
  * `transfer`-only by construction (spec §163): `target == asset` rejects multicall/router
43
64
  * targets; the 68-byte length + selector check rejects `transferFrom`/`approve`/extra-arg
44
65
  * smuggling; `value == 0` rejects ETH; the DelegationManager's single (target,value,data)
@@ -99,6 +120,10 @@ contract PaymentEnforcer is ICaveatEnforcer {
99
120
  error AggregateExceeded(uint256 spent, uint256 maxAggregate, uint256 amount);
100
121
  error FrequencyExceeded(uint32 callsInWindow, uint32 maxRedemptionsPerWindow);
101
122
  error NonceReused(bytes32 nonce);
123
+ /// @notice DLG-8b: a charge of zero moves nothing and may not write a receipt.
124
+ error ZeroAmount();
125
+ /// @notice DLG-8c: the manager reported no redemption in flight, so there is no payer to name.
126
+ error NoRedemptionInFlight();
102
127
  error NotDelegationManager(address caller);
103
128
  /// @notice M1 (seam audit): the transfer did not move `amount` to the treasury (a token that returns
104
129
  /// false without reverting, a fee-on-transfer skim, or a missing beforeHook snapshot) — so no
@@ -155,6 +180,7 @@ contract PaymentEnforcer is ICaveatEnforcer {
155
180
  if (bytes4(callData[0:4]) != TRANSFER_SELECTOR) revert NotTransferCall();
156
181
  (address to, uint256 amount) = abi.decode(callData[4:], (address, uint256));
157
182
  if (to != treasury) revert WrongRecipient(treasury, to);
183
+ if (amount == 0) revert ZeroAmount();
158
184
  if (amount > maxPerCharge) revert ChargeExceedsMax(amount, maxPerCharge);
159
185
 
160
186
  // ── replay: single-use nonce per delegation (on-chain idempotency, PAY-RAIL-4) ──
@@ -219,7 +245,12 @@ contract PaymentEnforcer is ICaveatEnforcer {
219
245
  if (IERC20(asset).balanceOf(treasury) < (snap - 1) + amount) revert SettlementNotObserved();
220
246
 
221
247
  if (address(receiptRegistry) != address(0)) {
222
- receiptRegistry.record(mandateId, delegator, treasury, asset, amount, resourceHash, delegationHash, nonce);
248
+ // DLG-8c: the payer is the account that executed the transfer (the root delegator), not the
249
+ // delegator of whichever link carries this caveat. One source, no fallback: a manager that
250
+ // reports no redemption in flight cannot have executed one.
251
+ address payer = IRedemptionContext(delegationManager).redemptionRootDelegator();
252
+ if (payer == address(0)) revert NoRedemptionInFlight();
253
+ receiptRegistry.record(mandateId, payer, treasury, asset, amount, resourceHash, delegationHash, nonce);
223
254
  }
224
255
  }
225
256
 
@@ -173,7 +173,7 @@ contract QuorumEnforcer is ICaveatEnforcer {
173
173
  revert InsufficientQuorum(signatures.length / 65, threshold);
174
174
  }
175
175
 
176
- address prev;
176
+ address prev = address(0); // explicit: strictly-ascending signer order starts above zero
177
177
  for (uint256 i; i < threshold; i++) {
178
178
  address signer = SignatureSlotRecovery.recoverFromSlot(
179
179
  expectedPayloadHash,
@@ -13,7 +13,12 @@ import "../agency/ICaveatEnforcer.sol";
13
13
  * (hooks are `pure`, contract has zero storage). The DM-side pause
14
14
  * check in `DelegationManager.redeemDelegation` gates all
15
15
  * reachable enforcer dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
16
- * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
16
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`. *
17
+ * Spec 445 / audit DLG-2 — SCOPE. This enforcer judges the ONE `(target, value, callData)` the
18
+ * DelegationManager was asked to execute, nothing nested inside it. That is the whole call a
19
+ * delegation can cause only because the manager refuses a redemption whose target is the
20
+ * executing account itself (`SelfTargetedRedemption`) — the route by which a self-`executeBatch`
21
+ * once ran inner calls no enforcer saw. Do not reuse this enforcer under a manager without that rule.
17
22
  */
18
23
  contract ValueEnforcer is ICaveatEnforcer {
19
24
  error ValueExceedsLimit();