CoolFace
Apppublic

Topq/agenthire-protocol

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes
register_erc8004.py163 linesDownload Raw Back to scripts
1"""2ERC-8004 Identity Registration Script3Registers AgentHire agents on the ERC-8004 Identity Registry (Base Sepolia).4 5Identity Registry: 0x7177a6867296406881E20d6647232314736Dd09A6Function: register(string agentURI) returns (uint256 agentId)7"""8 9import os, json, sys10from pathlib import Path11from dotenv import load_dotenv12from web3 import Web313 14load_dotenv(Path(__file__).parent.parent / ".env")15 16# ── Config ────────────────────────────────────────────────────────17RPC_URL     = os.getenv("BASE_SEPOLIA_RPC", "https://sepolia.base.org")18PRIVATE_KEY = os.getenv("PRIVATE_KEY")19 20IDENTITY_REGISTRY   = "0x7177a6867296406881E20d6647232314736Dd09A"21REPUTATION_REGISTRY = "0xB5048e3ef1DA4E04deB6f7d0423D06F63869e322"22 23# ERC-8004 Identity Registry ABI (minimal)24IDENTITY_ABI = [25    {26        "inputs": [27            {"internalType": "string", "name": "agentURI", "type": "string"}28        ],29        "name": "register",30        "outputs": [31            {"internalType": "uint256", "name": "agentId", "type": "uint256"}32        ],33        "stateMutability": "nonpayable",34        "type": "function"35    },36    {37        "inputs": [38            {"internalType": "uint256", "name": "tokenId", "type": "uint256"}39        ],40        "name": "tokenURI",41        "outputs": [{"internalType": "string", "name": "", "type": "string"}],42        "stateMutability": "view",43        "type": "function"44    },45    {46        "anonymous": False,47        "inputs": [48            {"indexed": True, "name": "agentId", "type": "uint256"},49            {"indexed": True, "name": "owner",   "type": "address"},50            {"indexed": False,"name": "agentURI","type": "string"}51        ],52        "name": "AgentRegistered",53        "type": "event"54    }55]56 57AGENT_CARD_URI = "https://topq-agenthire-protocol.hf.space/agent.json"58 59 60def main():61    if not PRIVATE_KEY:62        print("ERROR: PRIVATE_KEY not set in .env")63        sys.exit(1)64 65    w3 = Web3(Web3.HTTPProvider(RPC_URL))66    if not w3.is_connected():67        print("ERROR: Cannot connect to Base Sepolia")68        sys.exit(1)69 70    account = w3.eth.account.from_key(PRIVATE_KEY)71    print(f"Registering from wallet: {account.address}")72    print(f"Balance: {w3.from_wei(w3.eth.get_balance(account.address), 'ether'):.6f} ETH")73 74    contract = w3.eth.contract(75        address=Web3.to_checksum_address(IDENTITY_REGISTRY),76        abi=IDENTITY_ABI77    )78 79    print(f"\nRegistering on ERC-8004 Identity Registry...")80    print(f"  URI: {AGENT_CARD_URI}")81 82    nonce = w3.eth.get_transaction_count(account.address)83 84    try:85        tx = contract.functions.register(AGENT_CARD_URI).build_transaction({86            "from":     account.address,87            "nonce":    nonce,88            "gas":      200_000,89            "gasPrice": w3.to_wei("0.01", "gwei"),90            "chainId":  8453291        })92 93        signed = account.sign_transaction(tx)94        tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)95        print(f"  TX sent: 0x{tx_hash.hex()}")96 97        receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)98        if receipt.status == 1:99            print(f"  ✅ Registration SUCCESS")100            print(f"  Block: {receipt.blockNumber}")101            print(f"  Gas used: {receipt.gasUsed}")102 103            # Try to extract agentId from logs104            try:105                decoded = contract.events.AgentRegistered().process_receipt(receipt)106                if decoded:107                    agent_id = decoded[0]["args"]["agentId"]108                    print(f"  Agent ID (NFT token): {agent_id}")109 110                    # Save registration data111                    reg_data = {112                        "txHash":   f"0x{tx_hash.hex()}",113                        "agentId":  str(agent_id),114                        "owner":    account.address,115                        "agentURI": AGENT_CARD_URI,116                        "registry": IDENTITY_REGISTRY,117                        "network":  "base-sepolia",118                        "block":    receipt.blockNumber119                    }120                    out_path = Path(__file__).parent.parent / "erc8004_registration.json"121                    with open(out_path, "w") as f:122                        json.dump(reg_data, f, indent=2)123                    print(f"\n  Saved to: {out_path}")124            except Exception as e:125                print(f"  (Could not decode event: {e})")126                # Save minimal data anyway127                reg_data = {128                    "txHash":   f"0x{tx_hash.hex()}",129                    "owner":    account.address,130                    "agentURI": AGENT_CARD_URI,131                    "registry": IDENTITY_REGISTRY,132                    "network":  "base-sepolia",133                    "block":    receipt.blockNumber134                }135                out_path = Path(__file__).parent.parent / "erc8004_registration.json"136                with open(out_path, "w") as f:137                    json.dump(reg_data, f, indent=2)138        else:139            print(f"  ❌ Transaction FAILED (status=0)")140            print(f"  TX: https://sepolia.basescan.org/tx/0x{tx_hash.hex()}")141 142    except Exception as e:143        print(f"  ❌ Error: {e}")144        # If already registered, that's fine — save a placeholder145        print("\n  Note: Agent may already be registered. Saving placeholder registration file.")146        reg_data = {147            "status":   "already_registered_or_error",148            "error":    str(e),149            "owner":    account.address,150            "agentURI": AGENT_CARD_URI,151            "registry": IDENTITY_REGISTRY,152            "network":  "base-sepolia"153        }154        out_path = Path(__file__).parent.parent / "erc8004_registration.json"155        with open(out_path, "w") as f:156            json.dump(reg_data, f, indent=2)157 158    print("\nDone.")159 160 161if __name__ == "__main__":162    main()163