Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(contracts): AgentTierHook, a Uniswap v4 hook where an ERC-8004 agent's reputation sets the LP fee it pays
ni3a4c452fcd6d4f
diff --git a/contracts/v4-hooks/README.md b/contracts/v4-hooks/README.mdindex 3f831a6de..0c086a9ca 100644--- a/contracts/v4-hooks/README.md+++ b/contracts/v4-hooks/README.md@@ -6,6 +6,7 @@ the home chain, and each product built on a hook here has or will have a Solana| Hook | Source | Flags | Status || --- | --- | --- | --- || `SkinHook` | [`src/SkinHook.sol`](./src/SkinHook.sol) | `0x20CC` | Not deployed |+| `AgentTierHook` | [`src/AgentTierHook.sol`](./src/AgentTierHook.sol) | `0x2080` | Not deployed |Background, prior art, and why these hooks: [`docs/uniswap-v4-hooks.md`](../../docs/uniswap-v4-hooks.md).@@ -65,6 +66,53 @@ hook.unequip(token); // token returnedhook.claim(payoutAddress); // creator, referrer or treasury withdraws ETH```+## AgentTierHook: an agent's reputation sets the fee it pays++A dynamic-fee pool where standing in the canonical+[ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) registries is worth money. An unknown+trader pays the base LP fee, a trader who controls a registered agent pays less, and an+agent whose reputation clears the pool's bar pays the least. LPs keep every fee. The hook+takes nothing and holds nothing.++- **Nothing to register with us.** The trader passes `abi.encode(uint256 agentId)` as+ `hookData`. The hook checks `ownerOf(agentId)` and `getAgentWallet(agentId)` on the+ identity registry against the account the router reports through `msgSender()`.+- **A named reviewer set.** The live reputation registry reverts with+ `"clientAddresses required"` when asked to summarise feedback from nobody in particular.+ Each pool therefore lists up to 16 reviewers whose feedback it trusts, plus optional+ tag filters, a minimum count and a minimum average score.+- **O(1) swaps.** Summarising reputation loops over reviewers and their feedback, so it+ runs in the permissionless `refreshTier(poolId, agentId)`, which caches the verdict+ until `ttl` passes. `beforeSwap` only reads the cache. An agent with no fresh entry+ still gets the registered-agent fee.+- **Every failure is the base fee.** Registry calls inside a swap are gas-capped and+ wrapped in try/catch. An untrusted router, a router with no `msgSender()`, malformed+ `hookData`, an agent the trader does not control, or a registry that reverts all+ produce an ordinary base-fee swap. The registries are upgradeable proxies, so this is+ the case that matters, and `test_brokenRegistry_costsTheDiscount_neverTheSwap` covers it.+- **Routers are trusted per pool.** A router that lies about `msgSender()` could hand+ anyone an agent's discount, so the pool admin opts routers in.++```solidity+PoolKey memory key = hook.createPool(+ currency0, currency1, 60, sqrtPriceX96,+ AgentTierHook.TierConfig({+ baseFee: 10_000, // 1.00% for anyone+ agentFee: 5_000, // 0.50% for a registered agent+ trustedFee: 1_000, // 0.10% once reputation clears the bar+ minCount: 5,+ minScore: 80e18, // average score, 18-decimal fixed point+ ttl: 1 days,+ tag1: "", tag2: ""+ }),+ reviewers, // whose feedback counts, 1 to 16 addresses+ routers // routers whose msgSender() this pool believes+);++hook.refreshTier(key.toId(), agentId); // anyone; caches the verdict+uint24 fee = hook.quoteFee(key.toId(), trader, agentId);+```+## Build and testFoundry is required (`curl -L https://foundry.paradigm.xyz | bash && foundryup`).@@ -75,14 +123,20 @@ forge buildforge test```-The suite runs against the real v4-core `PoolManager` and its reference swap router, not-stand-ins. `test/HookMiner.t.sol` proves the production deploy path: a mined CREATE2 salt+The `SkinHook` suite runs against the real v4-core `PoolManager` and its reference swap+router, not stand-ins. The `AgentTierHook` suite is a fork test against the live Base+`PoolManager` and the live ERC-8004 registries, and is skipped unless an RPC is set:++```bash+BASE_RPC_URL=https://base-rpc.publicnode.com forge test --match-contract AgentTierHookForkTest+```+ `test/HookMiner.t.sol` proves the production deploy path: a mined CREATE2 saltlands the hook at an address that passes the hook's own permission check.## DeployA v4 hook's permissions are the low 14 bits of its address, so it must be deployed with a-mined CREATE2 salt. `script/DeploySkinHook.s.sol` mines it and deploys through the+mined CREATE2 salt. `script/DeploySkinHook.s.sol` (and `script/DeployAgentTierHook.s.sol`) mines it and deploys through thecanonical CREATE2 deployer. Without `--broadcast` it is a dry run that prints the address.```bashdiff --git a/contracts/v4-hooks/script/DeployAgentTierHook.s.sol b/contracts/v4-hooks/script/DeployAgentTierHook.s.solnew file mode 100644index 000000000..09594d80c--- /dev/null+++ b/contracts/v4-hooks/script/DeployAgentTierHook.s.sol@@ -0,0 +1,38 @@+// SPDX-License-Identifier: MIT+pragma solidity 0.8.26;++import {Script, console2} from "forge-std/Script.sol";+import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";+import {AgentTierHook} from "../src/AgentTierHook.sol";+import {IERC8004Identity, IERC8004Reputation} from "../src/interfaces/IERC8004.sol";+import {HookMiner} from "./HookMiner.sol";++/// Deploys AgentTierHook at a mined, flag-matching address. The ERC-8004 registries sit at+/// the same address on every mainnet they are deployed to, so only POOL_MANAGER changes+/// from chain to chain.+///+/// POOL_MANAGER=0x498581ff718922c3f8e6a244956af099b2652b2b \+/// forge script script/DeployAgentTierHook.s.sol --rpc-url base --broadcast --verify+contract DeployAgentTierHook is Script {+ address constant CREATE2_DEPLOYER = 0x4e59b44847b379578588920cA78FbF26c0B4956C;+ IERC8004Identity constant IDENTITY = IERC8004Identity(0x8004A169FB4a3325136EB29fA0ceB6D2e539a432);+ IERC8004Reputation constant REPUTATION = IERC8004Reputation(0x8004BAa17C55a88189AE136b182e5fdA19dE9b63);+ // beforeInitialize | beforeSwap+ uint160 constant FLAGS = (1 << 13) | (1 << 7);++ function run() external returns (AgentTierHook hook) {+ IPoolManager poolManager = IPoolManager(vm.envAddress("POOL_MANAGER"));+ require(address(IDENTITY).code.length != 0, "no ERC-8004 identity registry on this chain");+ require(address(REPUTATION).code.length != 0, "no ERC-8004 reputation registry on this chain");++ bytes memory initCode =+ abi.encodePacked(type(AgentTierHook).creationCode, abi.encode(poolManager, IDENTITY, REPUTATION));+ (address expected, bytes32 salt) = HookMiner.find(CREATE2_DEPLOYER, FLAGS, initCode);+ console2.log("AgentTierHook will deploy at", expected);+ console2.logBytes32(salt);++ vm.broadcast();+ hook = new AgentTierHook{salt: salt}(poolManager, IDENTITY, REPUTATION);+ require(address(hook) == expected, "mined address mismatch");+ }+}diff --git a/contracts/v4-hooks/src/AgentTierHook.sol b/contracts/v4-hooks/src/AgentTierHook.solnew file mode 100644index 000000000..b5ec3b18c--- /dev/null+++ b/contracts/v4-hooks/src/AgentTierHook.sol@@ -0,0 +1,371 @@+// SPDX-License-Identifier: MIT+pragma solidity 0.8.26;++import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";+import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";+import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";+import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";+import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";+import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";+import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";+import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";+import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";++import {IERC8004Identity, IERC8004Reputation, IMsgSender} from "./interfaces/IERC8004.sol";++/// @title AgentTierHook+/// @notice Pools where an ERC-8004 agent's standing sets the LP fee it pays. An unknown+/// trader pays the base fee, a registered agent pays less, and an agent whose+/// reputation clears the pool's bar pays the least. LPs keep every fee; the hook+/// never takes or holds value.+/// @dev Reads the canonical ERC-8004 registries directly. There is nothing to register+/// with this hook: the trader names an `agentId` in `hookData` and the hook checks+/// that the trader controls it.+///+/// Three rules shape the design.+/// 1. Reputation needs a named reviewer set. The live registry refuses an empty one,+/// so each pool configures the reviewers whose feedback it trusts.+/// 2. Swaps stay O(1). Summarising reputation loops over reviewers and feedback, so+/// it happens in the permissionless `refreshTier`, which caches the result with an+/// expiry. `beforeSwap` only reads the cache.+/// 3. Every failure resolves to the base fee. The registries are upgradeable proxies+/// whose interface has already changed once, so each registry call is gas-capped+/// and wrapped in try/catch. A broken, hostile or upgraded registry can cost an+/// agent its discount. It can never block a swap or grant a discount.+contract AgentTierHook is IHooks {+ using PoolIdLibrary for PoolKey;++ uint24 public constant MAX_FEE = 100_000; // 10%+ uint256 public constant MAX_REVIEWERS = 16;+ uint32 public constant MIN_TTL = 1 hours;+ uint32 public constant MAX_TTL = 30 days;+ /// @dev Enough for an ERC-721 `ownerOf` behind a proxy, far too little to grief a swap.+ uint256 internal constant IDENTITY_CALL_GAS = 60_000;++ IPoolManager public immutable poolManager;+ IERC8004Identity public immutable identity;+ IERC8004Reputation public immutable reputation;++ struct TierConfig {+ uint24 baseFee; // anyone+ uint24 agentFee; // trader controls a registered agent+ uint24 trustedFee; // and that agent's cached reputation clears the bar+ uint64 minCount; // feedback entries required from the reviewer set+ int256 minScore; // required average, 18-decimal fixed point+ uint32 ttl; // how long a refreshed tier stays valid+ string tag1; // optional ERC-8004 feedback tag filters+ string tag2;+ }++ struct Pool {+ address admin;+ uint32 epoch; // bumped when the bar or reviewer set changes, which voids the cache+ TierConfig config;+ address[] reviewers;+ }++ struct CachedTier {+ bool trusted;+ uint64 expiry;+ }++ mapping(PoolId => Pool) internal _pools;+ /// @notice Routers whose `msgSender()` a pool believes. A router that lies about the+ /// trader could hand anyone a discount, so this is opt-in per pool.+ mapping(PoolId => mapping(address => bool)) public trustedRouter;+ mapping(PoolId => mapping(uint32 => mapping(uint256 => CachedTier))) internal _tiers;++ event PoolCreated(PoolId indexed poolId, address indexed admin, Currency currency0, Currency currency1);+ event ConfigChanged(PoolId indexed poolId, uint32 epoch);+ event RouterTrustChanged(PoolId indexed poolId, address indexed router, bool trusted);+ event AdminChanged(PoolId indexed poolId, address indexed previous, address indexed current);+ event TierRefreshed(+ PoolId indexed poolId, uint256 indexed agentId, bool trusted, uint64 count, int256 score, uint64 expiry+ );++ error NotPoolManager();+ error NotPoolAdmin();+ error OnlyThisHookCreatesPools();+ error HookNotImplemented();+ error UnknownPool();+ error InvalidFees();+ error InvalidTtl();+ error InvalidReviewers();+ error ZeroAddress();++ modifier onlyPoolManager() {+ if (msg.sender != address(poolManager)) revert NotPoolManager();+ _;+ }++ modifier onlyAdmin(PoolId poolId) {+ if (msg.sender != _pools[poolId].admin) revert NotPoolAdmin();+ _;+ }++ constructor(IPoolManager poolManager_, IERC8004Identity identity_, IERC8004Reputation reputation_) {+ if (address(identity_) == address(0) || address(reputation_) == address(0)) revert ZeroAddress();+ poolManager = poolManager_;+ identity = identity_;+ reputation = reputation_;+ Hooks.validateHookPermissions(+ IHooks(address(this)),+ Hooks.Permissions({+ beforeInitialize: true,+ afterInitialize: false,+ beforeAddLiquidity: false,+ afterAddLiquidity: false,+ beforeRemoveLiquidity: false,+ afterRemoveLiquidity: false,+ beforeSwap: true,+ afterSwap: false,+ beforeDonate: false,+ afterDonate: false,+ beforeSwapReturnDelta: false,+ afterSwapReturnDelta: false,+ afterAddLiquidityReturnDelta: false,+ afterRemoveLiquidityReturnDelta: false+ })+ );+ }++ // ------------------------------------------------------------------ pool setup++ /// @notice Create a dynamic-fee pool governed by this hook. The caller becomes its admin.+ /// @dev The hook initializes the pool itself. v4 skips callbacks for a hook's own calls,+ /// so `beforeInitialize` only ever runs for an outsider and always reverts: a pool+ /// cannot exist under this hook without a config.+ function createPool(+ Currency currency0,+ Currency currency1,+ int24 tickSpacing,+ uint160 sqrtPriceX96,+ TierConfig calldata config,+ address[] calldata reviewers,+ address[] calldata routers+ ) external returns (PoolKey memory key) {+ _validate(config, reviewers);+ key = PoolKey({+ currency0: currency0,+ currency1: currency1,+ fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,+ tickSpacing: tickSpacing,+ hooks: IHooks(address(this))+ });+ PoolId poolId = key.toId();++ Pool storage pool = _pools[poolId];+ pool.admin = msg.sender;+ pool.config = config;+ pool.reviewers = reviewers;+ for (uint256 i; i < routers.length; ++i) {+ trustedRouter[poolId][routers[i]] = true;+ emit RouterTrustChanged(poolId, routers[i], true);+ }++ poolManager.initialize(key, sqrtPriceX96);+ emit PoolCreated(poolId, msg.sender, currency0, currency1);+ }++ /// @notice Change the bar or the reviewer set. Every cached tier for the pool is voided.+ function setConfig(PoolId poolId, TierConfig calldata config, address[] calldata reviewers)+ external+ onlyAdmin(poolId)+ {+ _validate(config, reviewers);+ Pool storage pool = _pools[poolId];+ pool.config = config;+ pool.reviewers = reviewers;+ emit ConfigChanged(poolId, ++pool.epoch);+ }++ function setTrustedRouter(PoolId poolId, address router, bool trusted) external onlyAdmin(poolId) {+ trustedRouter[poolId][router] = trusted;+ emit RouterTrustChanged(poolId, router, trusted);+ }++ function setAdmin(PoolId poolId, address admin) external onlyAdmin(poolId) {+ if (admin == address(0)) revert ZeroAddress();+ emit AdminChanged(poolId, msg.sender, admin);+ _pools[poolId].admin = admin;+ }++ function _validate(TierConfig calldata config, address[] calldata reviewers) internal pure {+ if (config.baseFee > MAX_FEE || config.agentFee > config.baseFee || config.trustedFee > config.agentFee) {+ revert InvalidFees();+ }+ if (config.ttl < MIN_TTL || config.ttl > MAX_TTL) revert InvalidTtl();+ if (reviewers.length == 0 || reviewers.length > MAX_REVIEWERS) revert InvalidReviewers();+ for (uint256 i; i < reviewers.length; ++i) {+ if (reviewers[i] == address(0)) revert InvalidReviewers();+ }+ }++ // ------------------------------------------------------------------ reputation cache++ /// @notice Recompute and cache an agent's tier for a pool. Anyone may call it; the agent+ /// that wants the discount has the incentive to.+ function refreshTier(PoolId poolId, uint256 agentId) external returns (bool trusted) {+ Pool storage pool = _pools[poolId];+ if (pool.admin == address(0)) revert UnknownPool();+ TierConfig storage config = pool.config;++ uint64 count;+ int256 score;+ try reputation.getSummary(agentId, pool.reviewers, config.tag1, config.tag2) returns (+ uint64 count_, int128 value, uint8 decimals+ ) {+ count = count_;+ // The registry bounds decimals to 18; anything else is not a score this hook trusts.+ if (decimals <= 18) score = int256(value) * int256(10 ** uint256(18 - decimals));+ else count = 0;+ } catch {+ count = 0;+ }++ trusted = count != 0 && count >= config.minCount && score >= config.minScore;+ uint64 expiry = uint64(block.timestamp) + config.ttl;+ _tiers[poolId][pool.epoch][agentId] = CachedTier({trusted: trusted, expiry: expiry});+ emit TierRefreshed(poolId, agentId, trusted, count, score, expiry);+ }++ // ------------------------------------------------------------------ views++ function poolAdmin(PoolId poolId) external view returns (address) {+ return _pools[poolId].admin;+ }++ function poolConfig(PoolId poolId) external view returns (TierConfig memory config, uint32 epoch) {+ return (_pools[poolId].config, _pools[poolId].epoch);+ }++ function poolReviewers(PoolId poolId) external view returns (address[] memory) {+ return _pools[poolId].reviewers;+ }++ function cachedTier(PoolId poolId, uint256 agentId) external view returns (bool trusted, uint64 expiry) {+ CachedTier storage tier = _tiers[poolId][_pools[poolId].epoch][agentId];+ return (tier.trusted, tier.expiry);+ }++ /// @notice The LP fee `trader` would pay right now, swapping as `agentId` through a+ /// router this pool trusts.+ function quoteFee(PoolId poolId, address trader, uint256 agentId) external view returns (uint24) {+ return _feeFor(poolId, trader, agentId);+ }++ // ------------------------------------------------------------------ swap callback++ function beforeSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata, bytes calldata hookData)+ external+ view+ onlyPoolManager+ returns (bytes4, BeforeSwapDelta, uint24)+ {+ PoolId poolId = key.toId();+ uint24 fee = _pools[poolId].config.baseFee;++ // A discount needs three things: a 32-byte agentId, a router this pool trusts, and+ // that router naming a trader. Missing any of them is an ordinary base-fee swap.+ if (hookData.length == 32 && trustedRouter[poolId][sender]) {+ address trader = _traderOf(sender);+ if (trader != address(0)) fee = _feeFor(poolId, trader, uint256(bytes32(hookData[:32])));+ }+ return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, fee | LPFeeLibrary.OVERRIDE_FEE_FLAG);+ }++ function _traderOf(address router) internal view returns (address trader) {+ try IMsgSender(router).msgSender{gas: IDENTITY_CALL_GAS}() returns (address trader_) {+ trader = trader_;+ } catch {}+ }++ function _feeFor(PoolId poolId, address trader, uint256 agentId) internal view returns (uint24) {+ Pool storage pool = _pools[poolId];+ TierConfig storage config = pool.config;+ if (!_controls(trader, agentId)) return config.baseFee;++ CachedTier storage tier = _tiers[poolId][pool.epoch][agentId];+ if (tier.trusted && tier.expiry >= block.timestamp) return config.trustedFee;+ return config.agentFee;+ }++ /// @dev The trader controls the agent if it owns the identity NFT or is the agent's+ /// verified operating wallet. Either registry call failing counts as "no".+ function _controls(address trader, uint256 agentId) internal view returns (bool) {+ try identity.ownerOf{gas: IDENTITY_CALL_GAS}(agentId) returns (address owner) {+ if (owner == trader) return true;+ } catch {}+ try identity.getAgentWallet{gas: IDENTITY_CALL_GAS}(agentId) returns (address wallet) {+ return wallet == trader;+ } catch {+ return false;+ }+ }++ // ------------------------------------------------------------------ unused callbacks++ /// @dev Only reached when someone other than this hook initializes a pool that names it.+ function beforeInitialize(address, PoolKey calldata, uint160) external pure returns (bytes4) {+ revert OnlyThisHookCreatesPools();+ }++ function afterInitialize(address, PoolKey calldata, uint160, int24) external pure returns (bytes4) {+ revert HookNotImplemented();+ }++ function beforeAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)+ external+ pure+ returns (bytes4)+ {+ revert HookNotImplemented();+ }++ function afterAddLiquidity(+ address,+ PoolKey calldata,+ IPoolManager.ModifyLiquidityParams calldata,+ BalanceDelta,+ BalanceDelta,+ bytes calldata+ ) external pure returns (bytes4, BalanceDelta) {+ revert HookNotImplemented();+ }++ function beforeRemoveLiquidity(+ address,+ PoolKey calldata,+ IPoolManager.ModifyLiquidityParams calldata,+ bytes calldata+ ) external pure returns (bytes4) {+ revert HookNotImplemented();+ }++ function afterRemoveLiquidity(+ address,+ PoolKey calldata,+ IPoolManager.ModifyLiquidityParams calldata,+ BalanceDelta,+ BalanceDelta,+ bytes calldata+ ) external pure returns (bytes4, BalanceDelta) {+ revert HookNotImplemented();+ }++ function afterSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, BalanceDelta, bytes calldata)+ external+ pure+ returns (bytes4, int128)+ {+ revert HookNotImplemented();+ }++ function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {+ revert HookNotImplemented();+ }++ function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {+ revert HookNotImplemented();+ }+}diff --git a/contracts/v4-hooks/src/interfaces/IERC8004.sol b/contracts/v4-hooks/src/interfaces/IERC8004.solnew file mode 100644index 000000000..e6693b62e--- /dev/null+++ b/contracts/v4-hooks/src/interfaces/IERC8004.sol@@ -0,0 +1,26 @@+// SPDX-License-Identifier: MIT+pragma solidity 0.8.26;++/// @notice The slice of the canonical ERC-8004 IdentityRegistry this project reads.+/// Verified by eth_call against 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 on Base.+interface IERC8004Identity {+ function ownerOf(uint256 agentId) external view returns (address);+ function getAgentWallet(uint256 agentId) external view returns (address);+}++/// @notice The slice of the canonical ERC-8004 ReputationRegistry this project reads.+/// `getSummary` reverts with "clientAddresses required" when `clientAddresses` is+/// empty: the caller must say whose feedback it trusts. That is the standard's+/// sybil defence, not a quirk to route around.+interface IERC8004Reputation {+ function getSummary(uint256 agentId, address[] calldata clientAddresses, string calldata tag1, string calldata tag2)+ external+ view+ returns (uint64 count, int128 summaryValue, uint8 summaryValueDecimals);+}++/// @notice Routers expose the account that started the swap. The v4 Universal Router and+/// the v4-periphery routers implement this.+interface IMsgSender {+ function msgSender() external view returns (address);+}diff --git a/contracts/v4-hooks/test/AgentTierHook.fork.t.sol b/contracts/v4-hooks/test/AgentTierHook.fork.t.solnew file mode 100644index 000000000..1284d832b--- /dev/null+++ b/contracts/v4-hooks/test/AgentTierHook.fork.t.sol@@ -0,0 +1,280 @@+// SPDX-License-Identifier: MIT+pragma solidity 0.8.26;++import {Test} from "forge-std/Test.sol";+import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";+import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";+import {PoolModifyLiquidityTest} from "@uniswap/v4-core/src/test/PoolModifyLiquidityTest.sol";+import {PoolSwapTest} from "@uniswap/v4-core/src/test/PoolSwapTest.sol";+import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";+import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";+import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";+import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";+import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";+import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";+import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";++import {AgentTierHook} from "../src/AgentTierHook.sol";+import {IERC8004Identity, IERC8004Reputation} from "../src/interfaces/IERC8004.sol";+import {AttributedRouter} from "./AttributedRouter.sol";++contract PairToken is ERC20 {+ constructor(string memory symbol_) ERC20(symbol_, symbol_) {+ _mint(msg.sender, 1e30);+ }+}++interface IReputationClients {+ function getClients(uint256 agentId) external view returns (address[] memory);+}++/// Runs on a fork of Base against the LIVE Uniswap v4 PoolManager and the LIVE canonical+/// ERC-8004 registries. Nothing about the registries is simulated: the point of this hook+/// is reading them correctly, and a stand-in that accepted an empty reviewer list is+/// exactly how the one earlier ERC-8004 hook shipped a discount that can never fire.+///+/// BASE_RPC_URL=https://base-rpc.publicnode.com forge test --match-contract AgentTierHookForkTest+contract AgentTierHookForkTest is Test {+ using PoolIdLibrary for PoolKey;++ IPoolManager constant MANAGER = IPoolManager(0x498581fF718922c3f8e6A244956aF099B2652b2b);+ IERC8004Identity constant IDENTITY = IERC8004Identity(0x8004A169FB4a3325136EB29fA0ceB6D2e539a432);+ IERC8004Reputation constant REPUTATION = IERC8004Reputation(0x8004BAa17C55a88189AE136b182e5fdA19dE9b63);+ uint256 constant AGENT_ID = 1;++ // beforeInitialize | beforeSwap+ uint160 constant FLAGS = (1 << 13) | (1 << 7);+ uint24 constant BASE_FEE = 10_000; // 1%+ uint24 constant AGENT_FEE = 5_000; // 0.5%+ uint24 constant TRUSTED_FEE = 1_000; // 0.1%++ bool forked;+ AgentTierHook hook;+ AttributedRouter router;+ PoolSwapTest plainRouter;+ PoolModifyLiquidityTest liquidityRouter;+ PoolKey key;+ PoolId poolId;+ Currency currency0;+ Currency currency1;++ address agentOwner;+ address[] reviewers;+ uint64 liveCount;+ int256 liveScore;+ address stranger = makeAddr("stranger");++ function setUp() public {+ string memory rpc = vm.envOr("BASE_RPC_URL", string(""));+ if (bytes(rpc).length == 0) return;+ try vm.createSelectFork(rpc) {+ forked = true;+ } catch {+ return;+ }++ agentOwner = IDENTITY.ownerOf(AGENT_ID);+ address[] memory clients = IReputationClients(address(REPUTATION)).getClients(AGENT_ID);+ for (uint256 i; i < clients.length && i < 16; ++i) {+ reviewers.push(clients[i]);+ }+ (uint64 count, int128 value, uint8 decimals) = REPUTATION.getSummary(AGENT_ID, reviewers, "", "");+ liveCount = count;+ liveScore = int256(value) * int256(10 ** uint256(18 - decimals));++ address hookAddr = address(uint160(uint256(0x8004) << 144) | FLAGS);+ deployCodeTo("AgentTierHook.sol:AgentTierHook", abi.encode(MANAGER, IDENTITY, REPUTATION), hookAddr);+ hook = AgentTierHook(hookAddr);++ router = new AttributedRouter(MANAGER);+ plainRouter = new PoolSwapTest(MANAGER);+ liquidityRouter = new PoolModifyLiquidityTest(MANAGER);++ PairToken a = new PairToken("AAA");+ PairToken b = new PairToken("BBB");+ (currency0, currency1) = address(a) < address(b)+ ? (Currency.wrap(address(a)), Currency.wrap(address(b)))+ : (Currency.wrap(address(b)), Currency.wrap(address(a)));++ address[] memory routers = new address[](1);+ routers[0] = address(router);+ key = hook.createPool(currency0, currency1, 60, TickMath.getSqrtPriceAtTick(0), _config(liveScore), reviewers, routers);+ poolId = key.toId();++ a.approve(address(liquidityRouter), type(uint256).max);+ b.approve(address(liquidityRouter), type(uint256).max);+ liquidityRouter.modifyLiquidity(+ key,+ IPoolManager.ModifyLiquidityParams({tickLower: -6000, tickUpper: 6000, liquidityDelta: 1e24, salt: 0}),+ ""+ );++ address[3] memory traders = [agentOwner, stranger, address(this)];+ for (uint256 i; i < traders.length; ++i) {+ if (traders[i] != address(this)) {+ a.transfer(traders[i], 1e24);+ b.transfer(traders[i], 1e24);+ }+ vm.startPrank(traders[i]);+ a.approve(address(router), type(uint256).max);+ b.approve(address(router), type(uint256).max);+ a.approve(address(plainRouter), type(uint256).max);+ b.approve(address(plainRouter), type(uint256).max);+ vm.stopPrank();+ }+ }++ function _config(int256 minScore) internal view returns (AgentTierHook.TierConfig memory) {+ return AgentTierHook.TierConfig({+ baseFee: BASE_FEE,+ agentFee: AGENT_FEE,+ trustedFee: TRUSTED_FEE,+ minCount: liveCount,+ minScore: minScore,+ ttl: 1 days,+ tag1: "",+ tag2: ""+ });+ }++ /// Output of selling a fixed 1e18 of currency0. The pool is restored between calls, so+ /// a larger output means a smaller LP fee was charged.+ function _sell(address trader, bytes memory hookData) internal returns (uint256 out) {+ uint256 snapshot = vm.snapshotState();+ vm.prank(trader);+ BalanceDelta delta = router.swap(+ key,+ IPoolManager.SwapParams({+ zeroForOne: true,+ amountSpecified: -1e18,+ sqrtPriceLimitX96: TickMath.MIN_SQRT_PRICE + 1+ }),+ hookData+ );+ out = uint256(uint128(delta.amount1()));+ vm.revertToState(snapshot);+ }++ function test_liveRegistryStillRefusesAnEmptyReviewerList() public {+ vm.skip(!forked);+ vm.expectRevert(bytes("clientAddresses required"));+ REPUTATION.getSummary(AGENT_ID, new address[](0), "", "");+ assertGt(liveCount, 0, "agent #1 has feedback from the reviewer set");+ }++ function test_threeTiers_againstLiveRegistries() public {+ vm.skip(!forked);+ bytes memory asAgent = abi.encode(AGENT_ID);++ assertEq(hook.quoteFee(poolId, stranger, AGENT_ID), BASE_FEE, "naming an agent you do not control");+ assertEq(hook.quoteFee(poolId, agentOwner, AGENT_ID), AGENT_FEE, "registered, tier not refreshed yet");++ assertTrue(hook.refreshTier(poolId, AGENT_ID), "live reputation clears a bar set at its own value");+ assertEq(hook.quoteFee(poolId, agentOwner, AGENT_ID), TRUSTED_FEE);+ assertEq(hook.quoteFee(poolId, stranger, AGENT_ID), BASE_FEE, "someone else's standing is not yours");++ // The fee tiers are real: the same trade returns more as the fee drops.+ uint256 strangerOut = _sell(stranger, asAgent);+ uint256 noHookDataOut = _sell(agentOwner, "");+ uint256 trustedOut = _sell(agentOwner, asAgent);+ assertEq(strangerOut, noHookDataOut, "both pay the base fee");+ assertGt(trustedOut, strangerOut);+ // 1e18 in at price 1 with deep liquidity: outputs differ by the fee gap, 0.9%.+ assertApproxEqRel(trustedOut - strangerOut, 0.009e18, 0.01e18);+ }++ function test_tierExpires_andFallsBackToAgentFee() public {+ vm.skip(!forked);+ hook.refreshTier(poolId, AGENT_ID);+ vm.warp(block.timestamp + 1 days + 1);+ assertEq(hook.quoteFee(poolId, agentOwner, AGENT_ID), AGENT_FEE);+ }++ function test_barAboveLiveScore_isNotTrusted_andConfigChangeVoidsCache() public {+ vm.skip(!forked);+ hook.refreshTier(poolId, AGENT_ID);+ assertEq(hook.quoteFee(poolId, agentOwner, AGENT_ID), TRUSTED_FEE);++ hook.setConfig(poolId, _config(liveScore + 1), reviewers);+ assertEq(hook.quoteFee(poolId, agentOwner, AGENT_ID), AGENT_FEE, "old cache entry is void");+ assertFalse(hook.refreshTier(poolId, AGENT_ID));+ assertEq(hook.quoteFee(poolId, agentOwner, AGENT_ID), AGENT_FEE);+ }++ function test_untrustedRouterAlwaysPaysBaseFee() public {+ vm.skip(!forked);+ hook.refreshTier(poolId, AGENT_ID);+ hook.setTrustedRouter(poolId, address(router), false);++ uint256 untrusted = _sell(agentOwner, abi.encode(AGENT_ID));+ hook.setTrustedRouter(poolId, address(router), true);+ uint256 trusted = _sell(agentOwner, abi.encode(AGENT_ID));+ assertGt(trusted, untrusted);+ }++ function test_routerWithoutMsgSender_andMalformedHookData_swapAtBaseFee() public {+ vm.skip(!forked);+ hook.setTrustedRouter(poolId, address(plainRouter), true);+ plainRouter.swap(+ key,+ IPoolManager.SwapParams({+ zeroForOne: true,+ amountSpecified: -1e18,+ sqrtPriceLimitX96: TickMath.MIN_SQRT_PRICE + 1+ }),+ PoolSwapTest.TestSettings({takeClaims: false, settleUsingBurn: false}),+ abi.encode(AGENT_ID)+ );+ assertEq(_sell(agentOwner, hex"deadbeef"), _sell(stranger, ""));+ }++ function test_brokenRegistry_costsTheDiscount_neverTheSwap() public {+ vm.skip(!forked);+ hook.refreshTier(poolId, AGENT_ID);+ uint256 baseline = _sell(stranger, "");++ // Replace both registries with code that reverts on every call.+ vm.etch(address(IDENTITY), hex"60006000fd");+ vm.etch(address(REPUTATION), hex"60006000fd");+ assertEq(_sell(agentOwner, abi.encode(AGENT_ID)), baseline, "swap works, at the base fee");+ assertFalse(hook.refreshTier(poolId, AGENT_ID), "refresh records no trust instead of reverting");+ }++ function test_onlyTheHookCreatesPools_andOnlyAdminConfigures() public {+ vm.skip(!forked);+ PoolKey memory rogue = PoolKey({+ currency0: currency0,+ currency1: currency1,+ fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,+ tickSpacing: 10,+ hooks: IHooks(address(hook))+ });+ vm.expectRevert();+ MANAGER.initialize(rogue, TickMath.getSqrtPriceAtTick(0));++ vm.startPrank(stranger);+ vm.expectRevert(AgentTierHook.NotPoolAdmin.selector);+ hook.setTrustedRouter(poolId, stranger, true);+ vm.expectRevert(AgentTierHook.NotPoolAdmin.selector);+ hook.setConfig(poolId, _config(0), reviewers);+ vm.stopPrank();+ }++ function test_rejectsBadConfig() public {+ vm.skip(!forked);+ address[] memory none = new address[](0);+ AgentTierHook.TierConfig memory config = _config(0);++ vm.expectRevert(AgentTierHook.InvalidReviewers.selector);+ hook.setConfig(poolId, config, none);++ config.agentFee = BASE_FEE + 1;+ vm.expectRevert(AgentTierHook.InvalidFees.selector);+ hook.setConfig(poolId, config, reviewers);++ config = _config(0);+ config.ttl = 10 minutes;+ vm.expectRevert(AgentTierHook.InvalidTtl.selector);+ hook.setConfig(poolId, config, reviewers);+ }+}diff --git a/contracts/v4-hooks/test/AttributedRouter.sol b/contracts/v4-hooks/test/AttributedRouter.solnew file mode 100644index 000000000..cc0866ac0--- /dev/null+++ b/contracts/v4-hooks/test/AttributedRouter.sol@@ -0,0 +1,45 @@+// SPDX-License-Identifier: MIT+pragma solidity 0.8.26;++import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";+import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";+import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";+import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";+import {CurrencySettler} from "@uniswap/v4-core/test/utils/CurrencySettler.sol";+import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";++/// A small but complete swap router that tells hooks who started the swap, the way the+/// v4 Universal Router does through `msgSender()`. v4-core's reference PoolSwapTest does+/// not expose the trader, so it cannot exercise a hook that prices by identity.+contract AttributedRouter is IUnlockCallback {+ using CurrencySettler for Currency;++ IPoolManager public immutable manager;+ address public msgSender;++ constructor(IPoolManager manager_) {+ manager = manager_;+ }++ function swap(PoolKey memory key, IPoolManager.SwapParams memory params, bytes memory hookData)+ external+ returns (BalanceDelta delta)+ {+ msgSender = msg.sender;+ delta = abi.decode(manager.unlock(abi.encode(msg.sender, key, params, hookData)), (BalanceDelta));+ msgSender = address(0);+ }++ function unlockCallback(bytes calldata data) external returns (bytes memory) {+ require(msg.sender == address(manager), "only manager");+ (address payer, PoolKey memory key, IPoolManager.SwapParams memory params, bytes memory hookData) =+ abi.decode(data, (address, PoolKey, IPoolManager.SwapParams, bytes));++ BalanceDelta delta = manager.swap(key, params, hookData);+ if (delta.amount0() < 0) key.currency0.settle(manager, payer, uint128(-delta.amount0()), false);+ if (delta.amount1() < 0) key.currency1.settle(manager, payer, uint128(-delta.amount1()), false);+ if (delta.amount0() > 0) key.currency0.take(manager, payer, uint128(delta.amount0()), false);+ if (delta.amount1() > 0) key.currency1.take(manager, payer, uint128(delta.amount1()), false);+ return abi.encode(delta);+ }+}