CodeHash-Validated Agent Registry with Active Discovery

codehash-validated-agent-registry-with-active-discovery · discovery-registry · 1264 B runtime · registry-info

scores

source

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract AgentCodeRegistry {
    mapping(address => bytes32) private agentCodeHash;
    mapping(address => uint256) private agentIndex;
    mapping(bytes32 => address[]) private agentsByHash;

    event Registered(address indexed agent, bytes32 indexed codeHash);
    event Unregistered(address indexed agent, bytes32 indexed codeHash);

    function register(bytes32 codeHash) external {
        require(agentCodeHash[msg.sender] == bytes32(0), "dup");
        require(msg.sender.code.length > 0 && msg.sender.codehash == codeHash, "bad");
        address[] storage list = agentsByHash[codeHash];
        agentIndex[msg.sender] = list.length;
        list.push(msg.sender);
        agentCodeHash[msg.sender] = codeHash;
        emit Registered(msg.sender, codeHash);
    }

    function unregister(bytes32 codeHash) external {
        require(agentCodeHash[msg.sender] == codeHash, "not");
        address[] storage list = agentsByHash[codeHash];
        uint256 idx = agentIndex[msg.sender];
        uint256 lastIndex = list.length - 1;
        address moved = list[lastIndex];
        list[idx] = moved;
        agentIndex[moved] = idx;
        list.pop();
        delete agentCodeHash[msg.sender];
        emit Unregistered(msg.sender, codeHash);
    }

    function discover(bytes32 codeHash) external view returns (address[] memory result) {
        address[] storage list = agentsByHash[codeHash];
        uint256 n = list.length;
        result = new address[](n);
        uint256 count;
        unchecked {
            for (uint256 i; i < n; ++i) {
                address a = list[i];
                if (a.codehash == codeHash) result[count++] = a;
            }
        }
        assembly { mstore(result, count) }
    }
}

published

published on mainnet · 0x50b5C88C3c71c0b12Bc7CFdD510481f1749e8aEF · tx 0xe28729cf3b6a9825… · tempo (4217) · mainnet

published on testnet · 0x35397c8B9b0593dFaACd15f8a8Ed871d6318774e · tx 0xbec87717ea446221… · tempo (42431) · testnet