@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
@@ -1,11 +1,13 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  pragma solidity ^0.8.28;
3
3
 
4
+ import "../governance/GovernanceManaged.sol";
5
+
4
6
  /**
5
7
  * @title AgentNameRegistry
6
8
  * @notice Hierarchical multi-root name registry for Smart Agents.
7
9
  *
8
- * Names are keyed by `node` (the ENS-style namehash:
10
+ * Names are keyed by `node` (the recursive namehash:
9
11
  * `keccak256(parentNode || labelhash)`). Each node has an owner (a Smart
10
12
  * Agent address), a resolver, an optional subregistry delegate that may
11
13
  * issue children, a parent pointer, the labelhash, and an optional
@@ -36,7 +38,11 @@ pragma solidity ^0.8.28;
36
38
  * discipline (a primary name only counts when the forward record
37
39
  * agrees).
38
40
  */
39
- contract AgentNameRegistry {
41
+ /// @dev R6.8 — inherits `GovernanceManaged` to gain the
42
+ /// `whenNotPaused` modifier on its mutating surface. The registry
43
+ /// still owns its own per-node auth (`_requireParentAuth` /
44
+ /// `msg.sender == owner`); governance only owns the pause flag.
45
+ contract AgentNameRegistry is GovernanceManaged {
40
46
  // ─── H7-C.4 / CON-NAMING-001 — root-initializer gate ───────────────
41
47
  //
42
48
  // `initializeRoot` was permissionless: any mempool observer could
@@ -71,6 +77,12 @@ contract AgentNameRegistry {
71
77
  error NameExpired();
72
78
  error RootAlreadyInitialized();
73
79
  error EmptyLabel();
80
+ /// @notice AN-1-ONCHAIN (audit 2026-06-10) — the label is not in canonical form. The off-chain
81
+ /// SDK `normalizeLabel` (NFC + lowercase + `[a-z0-9-]`, 1..63, no leading/trailing `-`) was
82
+ /// bypassable by any DIRECT contract caller, allowing homoglyph / mixed-case / zero-width /
83
+ /// embedded-dot squatting of names. The charset is now enforced ON CHAIN; because a valid
84
+ /// label is already lowercase ASCII, raw-byte hashing equals hashing the normalized label.
85
+ error InvalidLabel();
74
86
  error ZeroOwner();
75
87
  /// @notice H7-C.4 / CON-NAMING-001 — `initializeRoot` may only be called
76
88
  /// by the immutable `initializer` set at construction. Closes the
@@ -129,10 +141,13 @@ contract AgentNameRegistry {
129
141
 
130
142
  // ─── Constructor (H7-C.4) ───────────────────────────────────────
131
143
 
132
- /// @notice Set the immutable root-initializer. The deploy script
133
- /// deploys the registry + calls `initializeRoot` in the same
134
- /// transaction so the TLD can't be frontrun.
135
- constructor(address initializer_) {
144
+ /// @notice Set the immutable root-initializer + governance pointer.
145
+ /// The deploy script deploys the registry + calls
146
+ /// `initializeRoot` in the same transaction so the TLD
147
+ /// can't be frontrun. R6.8 added `governance_` so the
148
+ /// registry can read the system pause flag through
149
+ /// `GovernanceManaged._pausedSafe()`.
150
+ constructor(address initializer_, address governance_) GovernanceManaged(governance_) {
136
151
  if (initializer_ == address(0)) revert ZeroOwner();
137
152
  initializer = initializer_;
138
153
  }
@@ -151,6 +166,25 @@ contract AgentNameRegistry {
151
166
  return keccak256(abi.encodePacked(bytes32(0), keccak256(bytes("agent"))));
152
167
  }
153
168
 
169
+ /// @notice AN-1-ONCHAIN — enforce the canonical single-label charset on chain. Mirrors the SDK
170
+ /// `normalizeLabel`: a single label of 1..63 bytes drawn from `[a-z0-9-]`, with no leading
171
+ /// or trailing `-`. Reverts `EmptyLabel` / `InvalidLabel`. Reusable from `register` +
172
+ /// `initializeRoot` so NO write path can anchor a non-canonical (squattable) label.
173
+ function _validateLabel(bytes memory b) internal pure {
174
+ uint256 len = b.length;
175
+ if (len == 0) revert EmptyLabel();
176
+ if (len > 63) revert InvalidLabel();
177
+ // no leading / trailing hyphen (0x2d)
178
+ if (b[0] == 0x2d || b[len - 1] == 0x2d) revert InvalidLabel();
179
+ for (uint256 i = 0; i < len; i++) {
180
+ uint8 c = uint8(b[i]);
181
+ bool ok = (c >= 0x61 && c <= 0x7a) // a-z
182
+ || (c >= 0x30 && c <= 0x39) // 0-9
183
+ || c == 0x2d; // -
184
+ if (!ok) revert InvalidLabel();
185
+ }
186
+ }
187
+
154
188
  // ─── Root Initialization (multi-root) ───────────────────────────
155
189
 
156
190
  /**
@@ -170,7 +204,7 @@ contract AgentNameRegistry {
170
204
  // TLD. The deploy script bundles deploy+init in one transaction so no
171
205
  // frontrun window exists.
172
206
  if (msg.sender != initializer) revert NotInitializer(msg.sender, initializer);
173
- if (bytes(label).length == 0) revert EmptyLabel();
207
+ _validateLabel(bytes(label)); // AN-1-ONCHAIN: canonical charset on chain
174
208
  if (rootOwner == address(0)) revert ZeroOwner();
175
209
  rootNode = namehashRoot(label);
176
210
  if (_records[rootNode].registeredAt != 0) revert RootAlreadyInitialized();
@@ -219,15 +253,18 @@ contract AgentNameRegistry {
219
253
  address newOwner,
220
254
  address resolverContract,
221
255
  uint64 expiry
222
- ) external returns (bytes32 childNode) {
223
- if (bytes(label).length == 0) revert EmptyLabel();
256
+ ) external whenNotPaused returns (bytes32 childNode) {
257
+ _validateLabel(bytes(label)); // AN-1-ONCHAIN: canonical charset on chain
224
258
  if (newOwner == address(0)) revert ZeroOwner();
225
259
  _requireParentAuth(parentNode);
226
260
  _requireNotExpired(parentNode);
227
261
 
228
262
  bytes32 lh = keccak256(bytes(label));
229
263
  childNode = keccak256(abi.encodePacked(parentNode, lh));
230
- if (_records[childNode].registeredAt != 0) revert NodeAlreadyExists();
264
+ // M2 (seam audit): an EXPIRED name is reclaimable (parent-authorized re-register). Only a LIVE
265
+ // record blocks re-registration — previously expiry was inert and a name could never be reclaimed.
266
+ bool reclaiming = _records[childNode].registeredAt != 0;
267
+ if (reclaiming && !isExpired(childNode)) revert NodeAlreadyExists();
231
268
 
232
269
  _records[childNode] = NameRecord({
233
270
  owner: newOwner,
@@ -240,7 +277,8 @@ contract AgentNameRegistry {
240
277
  });
241
278
 
242
279
  _children[parentNode][lh] = childNode;
243
- _childLabels[parentNode].push(lh);
280
+ // Only index a brand-new child; a reclaim reuses the existing _childLabels entry (no duplicate).
281
+ if (!reclaiming) _childLabels[parentNode].push(lh);
244
282
  _label[childNode] = label;
245
283
 
246
284
  emit NameRegistered(childNode, parentNode, label, newOwner, resolverContract, expiry);
@@ -252,7 +290,7 @@ contract AgentNameRegistry {
252
290
  * Authorized to the node's owner ONLY — labels can't be
253
291
  * changed once set, preventing display spoofing.
254
292
  */
255
- function backfillLabel(bytes32 node, string calldata label_) external {
293
+ function backfillLabel(bytes32 node, string calldata label_) external whenNotPaused {
256
294
  _requireNodeAuth(node);
257
295
  if (bytes(label_).length == 0) revert EmptyLabel();
258
296
  if (keccak256(bytes(label_)) != _records[node].labelhash) revert NotAuthorized();
@@ -262,26 +300,26 @@ contract AgentNameRegistry {
262
300
 
263
301
  // ─── Setters ────────────────────────────────────────────────────
264
302
 
265
- function setOwner(bytes32 node, address newOwner) external {
303
+ function setOwner(bytes32 node, address newOwner) external whenNotPaused {
266
304
  _requireNodeAuth(node);
267
305
  if (newOwner == address(0)) revert ZeroOwner();
268
306
  _records[node].owner = newOwner;
269
307
  emit OwnerChanged(node, newOwner);
270
308
  }
271
309
 
272
- function setResolver(bytes32 node, address resolverContract) external {
310
+ function setResolver(bytes32 node, address resolverContract) external whenNotPaused {
273
311
  _requireNodeAuth(node);
274
312
  _records[node].resolver = resolverContract;
275
313
  emit ResolverChanged(node, resolverContract);
276
314
  }
277
315
 
278
- function setSubregistry(bytes32 node, address subregistryContract) external {
316
+ function setSubregistry(bytes32 node, address subregistryContract) external whenNotPaused {
279
317
  _requireNodeAuth(node);
280
318
  _records[node].subregistry = subregistryContract;
281
319
  emit SubregistryChanged(node, subregistryContract);
282
320
  }
283
321
 
284
- function renew(bytes32 node, uint64 newExpiry) external {
322
+ function renew(bytes32 node, uint64 newExpiry) external whenNotPaused {
285
323
  _requireNodeAuth(node);
286
324
  _records[node].expiry = newExpiry;
287
325
  emit NameRenewed(node, newExpiry);
@@ -293,7 +331,10 @@ contract AgentNameRegistry {
293
331
  * NOT verify the forward record points back here. The
294
332
  * universal resolver enforces the round-trip on reads.
295
333
  */
296
- function setPrimaryName(bytes32 node) external {
334
+ function setPrimaryName(bytes32 node) external whenNotPaused {
335
+ // R6.3: `registeredAt == 0` is a sentinel "record-never-created" check.
336
+ // Storage default IS exactly 0; not a numeric precision concern.
337
+ // slither-disable-next-line incorrect-equality
297
338
  if (node != bytes32(0) && _records[node].registeredAt == 0) revert NodeNotFound();
298
339
  _primaryName[msg.sender] = node;
299
340
  if (node == bytes32(0)) emit PrimaryNameCleared(msg.sender);
@@ -315,7 +356,13 @@ contract AgentNameRegistry {
315
356
  function parent(bytes32 node) external view returns (bytes32) { return _records[node].parent; }
316
357
  function labelhash(bytes32 node) external view returns (bytes32) { return _records[node].labelhash; }
317
358
  function expiry(bytes32 node) external view returns (uint64) { return _records[node].expiry; }
318
- function recordExists(bytes32 node) external view returns (bool) { return _records[node].registeredAt != 0; }
359
+ /// @dev M2 (seam audit): an EXPIRED record does NOT exist for read purposes — so the resolver
360
+ /// (resolveName/resolveString, which gate on recordExists) and any other reader stop resolving
361
+ /// an expired name. Expiry now provides real revocation, not a decorative field. Registry
362
+ /// mutators gate on the raw `registeredAt`/`isExpired`, not this, so re-registration is unaffected.
363
+ function recordExists(bytes32 node) external view returns (bool) {
364
+ return _records[node].registeredAt != 0 && !isExpired(node);
365
+ }
319
366
  function registeredAt(bytes32 node) external view returns (uint64) { return _records[node].registeredAt; }
320
367
 
321
368
  function childNode(bytes32 parentNode, bytes32 lh) external view returns (bytes32) {
@@ -122,7 +122,7 @@ contract AgentNameUniversalResolver {
122
122
  /**
123
123
  * @notice Reverse-resolve a Smart Agent address to its primary name
124
124
  * STRING in a single external call. Per spec/222 this is
125
- * the ENS-aligned reverse path — no log walks, no name
125
+ * the on-chain reverse path — no log walks, no name
126
126
  * reconstruction in the SDK, no event indexer required.
127
127
  *
128
128
  * Walks `parent(node)` up the registry, reading `label(node)`
@@ -2,6 +2,7 @@
2
2
  pragma solidity ^0.8.28;
3
3
 
4
4
  import "./AgentNameRegistry.sol";
5
+ import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
5
6
 
6
7
  /**
7
8
  * @title PermissionlessSubregistry
@@ -36,7 +37,15 @@ import "./AgentNameRegistry.sol";
36
37
  * through whatever authority `newOwner` represents (EOA wallet,
37
38
  * PSA CustodyPolicy quorum, etc.).
38
39
  */
39
- contract PermissionlessSubregistry {
40
+ /// @dev R6.2 — `ReentrancyGuard` closes the Slither finding
41
+ /// `reentrancy-no-eth` on `register()`: the prior-claim check
42
+ /// (`claimedBy[msg.sender] != 0`) was followed by an external
43
+ /// call to `REGISTRY.register(...)` BEFORE the corresponding
44
+ /// state write. A malicious resolver invoked by the registry
45
+ /// could re-enter `register()` and pass the check a second time.
46
+ /// The guard prevents any nested call into `register()`, closing
47
+ /// the window. Recon doc § 4.1 / `docs/audits/r6-contracts-recon-2026-05-31.md`.
48
+ contract PermissionlessSubregistry is ReentrancyGuard {
40
49
  AgentNameRegistry public immutable REGISTRY;
41
50
  bytes32 public immutable PARENT_NODE;
42
51
  address public immutable DEFAULT_RESOLVER;
@@ -77,12 +86,20 @@ contract PermissionlessSubregistry {
77
86
  * fee — fee gating belongs in a different subregistry
78
87
  * shape if needed.
79
88
  */
80
- function register(string calldata label, address newOwner) external returns (bytes32 childNode) {
89
+ function register(string calldata label, address newOwner) external nonReentrant returns (bytes32 childNode) {
81
90
  if (bytes(label).length == 0) revert EmptyLabel();
82
91
  if (bytes(label).length < MIN_LABEL_LENGTH) revert LabelTooShort();
83
92
  if (newOwner == address(0)) revert ZeroNewOwner();
84
93
  bytes32 prior = claimedBy[msg.sender];
85
94
  if (prior != bytes32(0)) revert AlreadyClaimed(prior);
95
+ // R9 / docs/audits/r9-static-analysis-triage.md § Slither M-1:
96
+ // Slither flags this as cross-function reentrancy because state is
97
+ // written AFTER the external call. The function is `nonReentrant`
98
+ // (line 89) + REGISTRY is an immutable contract we control
99
+ // (`AgentNameRegistry`) that does not call back into this contract.
100
+ // The cross-function reader (`hasClaimed`) is view-only. No invariant
101
+ // is violated by the pre-write-window. Triaged false positive.
102
+ // slither-disable-next-line reentrancy-no-eth
86
103
  childNode = REGISTRY.register(PARENT_NODE, label, newOwner, DEFAULT_RESOLVER, 0);
87
104
  claimedBy[msg.sender] = childNode;
88
105
  unchecked {
@@ -0,0 +1,209 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import "./AgentNameRegistry.sol";
5
+ import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
6
+ import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
7
+ import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
8
+ import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
9
+ import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
10
+
11
+ /**
12
+ * @title PricedSubregistry
13
+ * @notice A subregistry for one typed root where a claim COSTS a coin and needs a ticket (spec 431; the contract
14
+ * spec is 432). The successor of `PermissionlessSubregistry` for a root whose names are purchased.
15
+ *
16
+ * One signed operation, one receipt:
17
+ * - The PAYER calls `claim(ticket, gateSig)`. The payer is a treasury Smart Agent (assets live only in treasuries);
18
+ * it approved this contract for the price beforehand, in the same user operation.
19
+ * - The TICKET is signed (EIP-712) by an estate's naming GATE — the key a Home holds. A gate signs only after its
20
+ * own rules passed (the domain rule: a protected label needs a verified email at that domain). The contract
21
+ * checks the signature against the gates the governor named; it stores nothing about why the gate agreed
22
+ * beyond `domain` (a label, never an email).
23
+ * - The PRICE is a pure function of the label's length and this root's base, computed here and checked against
24
+ * the ticket, so the Home, the naming service and the chain agree on the number.
25
+ * - The fee moves from the payer to the fee treasury; the name is registered to `ticket.owner`; the owner is
26
+ * recorded as having claimed under this root (one name per owner per root, never released); the price and the
27
+ * time are stored so a reader never needs a log.
28
+ *
29
+ * What this is NOT (spec 431 D6): no expiry, no renewal, no resale, no refund. A paid name is an address card and
30
+ * grants nobody authority.
31
+ *
32
+ * Authority model: the registry sees `msg.sender == address(this)` AND `r.subregistry == this`; the child is owned
33
+ * by `ticket.owner`, never by this contract. Governance (gates, fee treasury, the price table) is the governor's —
34
+ * meant to be the root owner / the town's governor, and transferable.
35
+ */
36
+ contract PricedSubregistry is ReentrancyGuard, EIP712 {
37
+ using SafeERC20 for IERC20;
38
+
39
+ AgentNameRegistry public immutable REGISTRY;
40
+ bytes32 public immutable PARENT_NODE;
41
+ address public immutable DEFAULT_RESOLVER;
42
+ IERC20 public immutable COIN;
43
+
44
+ uint256 public constant MIN_LABEL_LENGTH = 3;
45
+
46
+ /// @dev keccak256("ClaimTicket(bytes32 parentNode,string label,address owner,address payer,uint256 price,bytes32 domain,uint256 expiry,bytes32 nonce)")
47
+ bytes32 public constant CLAIM_TICKET_TYPEHASH =
48
+ keccak256("ClaimTicket(bytes32 parentNode,string label,address owner,address payer,uint256 price,bytes32 domain,uint256 expiry,bytes32 nonce)");
49
+
50
+ struct ClaimTicket {
51
+ bytes32 parentNode;
52
+ string label;
53
+ address owner;
54
+ address payer;
55
+ uint256 price;
56
+ /// @dev keccak256 of the domain the gate vouched for (`ibm.com`), or zero for an unprotected label.
57
+ bytes32 domain;
58
+ uint256 expiry;
59
+ bytes32 nonce;
60
+ }
61
+
62
+ address public governor;
63
+ address public feeTreasury;
64
+ /// @notice Estate naming gates whose tickets this root accepts.
65
+ mapping(address => bool) public gates;
66
+
67
+ /// @notice The price table: `base` in coin units for a label of 8+ characters; multipliers ×10 for lengths
68
+ /// 3, 4, 5, 6, 7 (an 8+ label is ×1); `cap` in coin units. Spec 431 §2.
69
+ uint256 public base;
70
+ uint16[5] public multipliersX10;
71
+ uint256 public cap;
72
+
73
+ /// @notice owner → the child node already claimed under this root (one per owner).
74
+ mapping(address => bytes32) public claimedBy;
75
+ /// @notice node → what was paid, and when. Readable without a log scan.
76
+ mapping(bytes32 => uint256) public paid;
77
+ mapping(bytes32 => uint64) public paidAt;
78
+ mapping(bytes32 => bool) public usedNonce;
79
+ uint256 public claimCount;
80
+
81
+ event NamePurchased(address indexed owner, address indexed payer, bytes32 indexed childNode, string label, uint256 price, bytes32 domain);
82
+ event GateSet(address indexed gate, bool allowed);
83
+ event FeeTreasurySet(address indexed feeTreasury);
84
+ event PriceTableSet(uint256 base, uint16[5] multipliersX10, uint256 cap);
85
+ event GovernorTransferred(address indexed oldGovernor, address indexed newGovernor);
86
+
87
+ error NotGovernor();
88
+ error ZeroAddress();
89
+ error WrongRoot();
90
+ error NotPayer();
91
+ error TicketExpired();
92
+ error NonceUsed();
93
+ error WrongPrice(uint256 expected);
94
+ error NotAGate(address signer);
95
+ error AlreadyClaimed(bytes32 existingNode);
96
+ error LabelTooShort();
97
+ error EmptyLabel();
98
+
99
+ modifier onlyGovernor() {
100
+ if (msg.sender != governor) revert NotGovernor();
101
+ _;
102
+ }
103
+
104
+ constructor(
105
+ AgentNameRegistry registry,
106
+ bytes32 parentNode,
107
+ address defaultResolver,
108
+ IERC20 coin,
109
+ address governor_,
110
+ address feeTreasury_,
111
+ uint256 base_,
112
+ uint16[5] memory multipliersX10_,
113
+ uint256 cap_
114
+ ) EIP712("PricedSubregistry", "1") {
115
+ if (governor_ == address(0) || feeTreasury_ == address(0) || address(coin) == address(0)) revert ZeroAddress();
116
+ REGISTRY = registry;
117
+ PARENT_NODE = parentNode;
118
+ DEFAULT_RESOLVER = defaultResolver;
119
+ COIN = coin;
120
+ governor = governor_;
121
+ feeTreasury = feeTreasury_;
122
+ base = base_;
123
+ multipliersX10 = multipliersX10_;
124
+ cap = cap_;
125
+ }
126
+
127
+ // ── the price ───────────────────────────────────────────────────────────────────────────────────────────
128
+
129
+ /// @notice What `label` costs under this root: `min(cap, base × multiplier(length))`. Pure in the label.
130
+ function priceOf(string calldata label) public view returns (uint256) {
131
+ uint256 len = bytes(label).length;
132
+ if (len < MIN_LABEL_LENGTH) revert LabelTooShort();
133
+ uint256 x10 = len >= 8 ? 10 : multipliersX10[len - 3];
134
+ uint256 p = (base * x10) / 10;
135
+ return p > cap ? cap : p;
136
+ }
137
+
138
+ // ── the claim ───────────────────────────────────────────────────────────────────────────────────────────
139
+
140
+ /// @notice The EIP-712 digest a gate signs for `t`.
141
+ function ticketDigest(ClaimTicket calldata t) public view returns (bytes32) {
142
+ return _hashTypedDataV4(keccak256(abi.encode(
143
+ CLAIM_TICKET_TYPEHASH, t.parentNode, keccak256(bytes(t.label)), t.owner, t.payer, t.price, t.domain, t.expiry, t.nonce
144
+ )));
145
+ }
146
+
147
+ /**
148
+ * @notice Buy `<label>.<root>` for `t.owner`, paid by `msg.sender` (= `t.payer`) with a ticket a gate signed.
149
+ * Reverts when the ticket is for another root, expired, re-used, carries the wrong price, is signed by
150
+ * nobody the governor named, when the owner already holds a name here, or when the registry refuses
151
+ * (the label is taken).
152
+ */
153
+ function claim(ClaimTicket calldata t, bytes calldata gateSig) external nonReentrant returns (bytes32 childNode) {
154
+ if (bytes(t.label).length == 0) revert EmptyLabel();
155
+ if (t.parentNode != PARENT_NODE) revert WrongRoot();
156
+ if (t.payer != msg.sender) revert NotPayer();
157
+ if (t.owner == address(0)) revert ZeroAddress();
158
+ if (block.timestamp > t.expiry) revert TicketExpired();
159
+ if (usedNonce[t.nonce]) revert NonceUsed();
160
+ uint256 price = priceOf(t.label);
161
+ if (t.price != price) revert WrongPrice(price);
162
+ bytes32 prior = claimedBy[t.owner];
163
+ if (prior != bytes32(0)) revert AlreadyClaimed(prior);
164
+ address signer = ECDSA.recover(ticketDigest(t), gateSig);
165
+ if (!gates[signer]) revert NotAGate(signer);
166
+
167
+ usedNonce[t.nonce] = true;
168
+ if (price > 0) COIN.safeTransferFrom(msg.sender, feeTreasury, price);
169
+ // The registry is an immutable contract we control and does not call back here; the guard holds anyway.
170
+ // slither-disable-next-line reentrancy-no-eth
171
+ childNode = REGISTRY.register(PARENT_NODE, t.label, t.owner, DEFAULT_RESOLVER, 0);
172
+ claimedBy[t.owner] = childNode;
173
+ paid[childNode] = price;
174
+ paidAt[childNode] = uint64(block.timestamp);
175
+ unchecked { claimCount += 1; }
176
+ emit NamePurchased(t.owner, msg.sender, childNode, t.label, price, t.domain);
177
+ }
178
+
179
+ function hasClaimed(address owner) external view returns (bool) {
180
+ return claimedBy[owner] != bytes32(0);
181
+ }
182
+
183
+ // ── governance ──────────────────────────────────────────────────────────────────────────────────────────
184
+
185
+ function setGate(address gate, bool allowed) external onlyGovernor {
186
+ if (gate == address(0)) revert ZeroAddress();
187
+ gates[gate] = allowed;
188
+ emit GateSet(gate, allowed);
189
+ }
190
+
191
+ function setFeeTreasury(address feeTreasury_) external onlyGovernor {
192
+ if (feeTreasury_ == address(0)) revert ZeroAddress();
193
+ feeTreasury = feeTreasury_;
194
+ emit FeeTreasurySet(feeTreasury_);
195
+ }
196
+
197
+ function setPriceTable(uint256 base_, uint16[5] calldata multipliersX10_, uint256 cap_) external onlyGovernor {
198
+ base = base_;
199
+ multipliersX10 = multipliersX10_;
200
+ cap = cap_;
201
+ emit PriceTableSet(base_, multipliersX10_, cap_);
202
+ }
203
+
204
+ function transferGovernor(address newGovernor) external onlyGovernor {
205
+ if (newGovernor == address(0)) revert ZeroAddress();
206
+ emit GovernorTransferred(governor, newGovernor);
207
+ governor = newGovernor;
208
+ }
209
+ }
@@ -0,0 +1,164 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
5
+ import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
6
+ import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
7
+
8
+ /**
9
+ * @title PaymentEscrow
10
+ * @notice Hold-and-capture for an exchange order (spec 243 §5.5 escrow rail, FG-PAY-7).
11
+ * A payer funds a hold keyed by `orderHash`; funds then move on exactly ONE terminal path:
12
+ * - release → captured to the payee (on fulfillment evidence)
13
+ * - refund → returned to the payer (payee-consented, before capture)
14
+ * - reclaim → returned to the payer (payer-initiated, after expiry)
15
+ * Symmetric-escrow doctrine (273 EXC-D4): any escrowable leg can be held. Ports the
16
+ * smart-agent `CommitmentRegistry` status-machine pattern; no third-party escrow dependency.
17
+ *
18
+ * @dev HASH-ONLY events (orderHash only — no amounts/addresses leak; privacy posture §6). Apps read
19
+ * hold state via the `getHold` view (`readContract`), never inline `eth_getLogs` (ADR-0012).
20
+ * Fail-closed: a hold moves Held → {Captured|Refunded|Reclaimed} once and never again
21
+ * (checks-effects-interactions + ReentrancyGuard). Uses OZ SafeERC20 for fee/no-return tokens.
22
+ */
23
+ contract PaymentEscrow is ReentrancyGuard {
24
+ using SafeERC20 for IERC20;
25
+
26
+ enum Status {
27
+ None,
28
+ Held,
29
+ Captured,
30
+ Refunded,
31
+ Reclaimed
32
+ }
33
+
34
+ struct Hold {
35
+ address payer; // funded the hold
36
+ address asset; // ERC-20
37
+ uint256 amount;
38
+ address payee; // captures on release
39
+ address refundTo; // receives refund / reclaim
40
+ address releaser; // OPTIONAL extra party authorized to release (0 = payee-only)
41
+ uint64 expiry; // payer may reclaim at/after this time
42
+ Status status;
43
+ }
44
+
45
+ // EXT-PMT-3: holds are keyed by (payer, orderHash), NOT orderHash alone — so a stranger cannot
46
+ // squat a predictable orderHash to block the real payer's deposit (HoldExists griefing). Each payer
47
+ // has an independent namespace for any given orderHash.
48
+ mapping(bytes32 holdKey => Hold) private _holds;
49
+
50
+ event EscrowDeposited(bytes32 indexed orderHash);
51
+ event EscrowReleased(bytes32 indexed orderHash);
52
+ event EscrowRefunded(bytes32 indexed orderHash);
53
+ event EscrowReclaimed(bytes32 indexed orderHash);
54
+
55
+ error HoldExists();
56
+ error NoHold();
57
+ error NotHeld();
58
+ error ZeroAmount();
59
+ error ZeroAddress();
60
+ error BadExpiry();
61
+ error NotAuthorized();
62
+ error NotYetExpired();
63
+ error Expired();
64
+
65
+ /// @dev The (payer, orderHash) namespace key. Terminal calls by the payee/releaser pass `payer`;
66
+ /// the payer's own `reclaim`/`deposit` derive it from `msg.sender`.
67
+ function _key(address payer, bytes32 orderHash) private pure returns (bytes32) {
68
+ return keccak256(abi.encode(payer, orderHash));
69
+ }
70
+
71
+ /**
72
+ * @notice Fund a hold for `orderHash`. Pulls `amount` of `asset` from the caller (the payer).
73
+ * @param refundTo Where refund/reclaim returns funds; 0 defaults to the payer.
74
+ * @param releaser Extra address allowed to `release` besides `payee`; 0 = payee-only.
75
+ */
76
+ function deposit(
77
+ bytes32 orderHash,
78
+ address asset,
79
+ uint256 amount,
80
+ address payee,
81
+ address refundTo,
82
+ address releaser,
83
+ uint64 expiry
84
+ ) external nonReentrant {
85
+ bytes32 key = _key(msg.sender, orderHash);
86
+ if (_holds[key].status != Status.None) revert HoldExists();
87
+ if (amount == 0) revert ZeroAmount();
88
+ if (asset == address(0) || payee == address(0)) revert ZeroAddress();
89
+ if (expiry <= block.timestamp) revert BadExpiry();
90
+
91
+ // EXT-PMT-3: credit the REALIZED amount received (balance delta), not the requested `amount`. A
92
+ // fee-on-transfer / rebasing asset delivers less than `amount`, which would otherwise over-credit
93
+ // the hold and let it draw from other holds' funds in the shared pool (cross-hold drain). The
94
+ // external transfer happens before the storage write, but nonReentrant + the status check above
95
+ // keep it safe (a reentrant deposit is blocked; a duplicate (payer,orderHash) reverts HoldExists).
96
+ uint256 beforeBal = IERC20(asset).balanceOf(address(this));
97
+ // Triaged false positive: `deposit` is `nonReentrant`, so the balanceOf delta cannot be
98
+ // manipulated by re-entering between the two reads — the guard blocks any callback. The
99
+ // before/after balance read is the EXT-PMT-3 realized-amount fix for fee-on-transfer assets.
100
+ // slither-disable-next-line reentrancy-balance
101
+ IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
102
+ uint256 received = IERC20(asset).balanceOf(address(this)) - beforeBal;
103
+ if (received == 0) revert ZeroAmount();
104
+
105
+ _holds[key] = Hold({
106
+ payer: msg.sender,
107
+ asset: asset,
108
+ amount: received,
109
+ payee: payee,
110
+ refundTo: refundTo == address(0) ? msg.sender : refundTo,
111
+ releaser: releaser,
112
+ expiry: expiry,
113
+ status: Status.Held
114
+ });
115
+ emit EscrowDeposited(orderHash);
116
+ }
117
+
118
+ /// @notice Capture a held order to the payee. Authorized: the payee, or the configured releaser.
119
+ /// `payer` namespaces the hold (EXT-PMT-3). Cannot release at/after expiry — that window is
120
+ /// the payer's `reclaim` (removes the prior release/reclaim race; spec 243 §reclaim intent).
121
+ function release(address payer, bytes32 orderHash) external nonReentrant {
122
+ Hold storage h = _held(_key(payer, orderHash));
123
+ if (msg.sender != h.payee && (h.releaser == address(0) || msg.sender != h.releaser)) revert NotAuthorized();
124
+ if (block.timestamp >= h.expiry) revert Expired();
125
+ h.status = Status.Captured;
126
+ emit EscrowReleased(orderHash);
127
+ IERC20(h.asset).safeTransfer(h.payee, h.amount);
128
+ }
129
+
130
+ /// @notice Payee-consented refund of a held order to the payer (before capture). `payer` namespaces.
131
+ function refund(address payer, bytes32 orderHash) external nonReentrant {
132
+ Hold storage h = _held(_key(payer, orderHash));
133
+ if (msg.sender != h.payee) revert NotAuthorized();
134
+ h.status = Status.Refunded;
135
+ emit EscrowRefunded(orderHash);
136
+ IERC20(h.asset).safeTransfer(h.refundTo, h.amount);
137
+ }
138
+
139
+ /// @notice Payer reclaims a held order after expiry (never released). Payer-initiated → the hold is
140
+ /// derived from `msg.sender`, so only the payer can reach their own hold.
141
+ function reclaim(bytes32 orderHash) external nonReentrant {
142
+ Hold storage h = _held(_key(msg.sender, orderHash));
143
+ if (block.timestamp < h.expiry) revert NotYetExpired();
144
+ h.status = Status.Reclaimed;
145
+ emit EscrowReclaimed(orderHash);
146
+ IERC20(h.asset).safeTransfer(h.refundTo, h.amount);
147
+ }
148
+
149
+ /// @notice Full hold record for (payer, orderHash) — app reads via this view, not log scans (ADR-0012).
150
+ function getHold(address payer, bytes32 orderHash) external view returns (Hold memory) {
151
+ return _holds[_key(payer, orderHash)];
152
+ }
153
+
154
+ function statusOf(address payer, bytes32 orderHash) external view returns (Status) {
155
+ return _holds[_key(payer, orderHash)].status;
156
+ }
157
+
158
+ /// @dev Load a hold that MUST be in `Held` (fail-closed): missing → NoHold; terminal → NotHeld.
159
+ function _held(bytes32 key) private view returns (Hold storage h) {
160
+ h = _holds[key];
161
+ if (h.status == Status.None) revert NoHold();
162
+ if (h.status != Status.Held) revert NotHeld();
163
+ }
164
+ }