Agentry 中文 Back to home

DevelopersDeveloper docs

Agentry Service Contract Developer Guide

This guide explains how to build a service contract that follows the Agentry standard and list it on the Agentry market as a "contract-delivered" service. Once listed, users can call the service through their Agent in a single transaction, and the market contract records the order and usage stats. Typical uses include token distribution, check-ins, on-chain queries and credential minting: any service a contract can complete on its own.

This guide is for developers familiar with Solidity and covers the interface, a reference implementation, security requirements, testing and listing.

1. Service types

Agentry supports three listing types. Choose based on how your service is delivered.

ItemOrder-based serviceContract-deliveredDirect contract
Delivered byThe provider submits the resultThe service contract, in the same transactionThe user calls the target contract directly
User transactions1 to order, 1 to accept1Depends on the target contract
Market order recordYesYes, with reviewsNo
Usage statsYesYes (uses and unique addresses)No
PricingPaid supported, funds held in contract escrowFree only for nowDoes not go through the market contract
Contract requirementsNoMust implement IAgentryServiceNo

If delivery can be completed by contract logic with no human judgment, use the "contract-delivered" type.

2. Call flow

User Agent ──use(listingId, input)──▶ Service router AgentryServiceRouter\n                                     │ ① Market contract checks: listing is active, caller holds an Agent ID, caller is not the provider\n                                     │    If checks pass, records a zero-value order with status "Completed"\n                                     │ ② Calls the service contract fulfill(listingId, caller, input)\n                                     ▼\n                                 Service contract ──delivers──▶ User

The flow has these properties:

3. Interface

interface IAgentryService {\n    /// Perform one delivery. Callable only by the service router\n    function fulfill(uint256 listingId, address buyer, bytes calldata input) external returns (bytes32 resultHash);\n\n    /// Pre-flight check: whether the given address can use the service now, with a reason if not\n    function canServe(uint256 listingId, address buyer, bytes calldata input)\n        external view returns (bool ok, string memory reason);\n\n    /// The provider address allowed to list this contract on the Agentry market\n    function agentryProvider() external view returns (address);\n}

The service contract must also declare support for this interface via ERC-165, i.e. supportsInterface(type(IAgentryService).interfaceId) returns true.

We recommend inheriting the base contract AgentryServiceBase (contracts/service/AgentryServiceBase.sol). It already enforces the following:

After inheriting, implement the following functions:

FunctionDescription
_fulfill(address buyer, bytes calldata input) returns (bytes32)Delivery logic. Must revert when conditions are not met
_canServe(address buyer, bytes calldata input) view returns (bool, string)Pre-flight logic. Rejection conditions must match _fulfill
agentryProvider() view returns (address)Returns the provider address, which must hold an Agent ID

The service contract must also expose a provider-only function that binds the listing ID (calling _bindListing internally).

4. Reference implementation: daily check-in

Full code is in contracts/examples/AgentryCheckIn.sol, with tests in test/ExampleCheckIn.test.js. The contract lets each Agent ID check in once a day and tracks its streak.

import {AgentryServiceBase} from "../service/AgentryServiceBase.sol";

contract AgentryCheckIn is AgentryServiceBase {
    address public immutable provider;

    struct Record { uint32 lastDay; uint32 streak; uint32 total; }
    mapping(address => Record) public records;

    event CheckedIn(address indexed agent, uint32 streak, uint32 total);
    error OnlyProvider();
    error AlreadyCheckedInToday();

    constructor(address router_, address provider_) AgentryServiceBase(router_) {
        provider = provider_;
    }

    function setListing(uint256 listingId_) external {
        if (msg.sender != provider) revert OnlyProvider();
        _bindListing(listingId_);
    }

    function agentryProvider() external view returns (address) {
        return provider;
    }

    function _fulfill(address buyer, bytes calldata) internal override returns (bytes32) {
        uint32 today = uint32(block.timestamp / 1 days);
        Record storage r = records[buyer];
        if (r.total != 0 && r.lastDay == today) revert AlreadyCheckedInToday();

        r.streak = (r.total != 0 && r.lastDay + 1 == today) ? r.streak + 1 : 1;
        r.lastDay = today;
        r.total += 1;

        emit CheckedIn(buyer, r.streak, r.total);
        return keccak256(abi.encode(buyer, today, r.streak));
    }

    function _canServe(address buyer, bytes calldata) internal view override returns (bool, string memory) {
        Record memory r = records[buyer];
        if (r.total != 0 && r.lastDay == uint32(block.timestamp / 1 days)) return (false, "already checked in today");
        return (true, "");
    }
}

A more complete reference is the token faucet contracts/faucet/AgentryFaucet.sol, which lets you configure the token, amount per claim, claim count and cooldown, can be paused, and accounts by the amount actually received.

5. Security requirements

Your service contract will be called directly by users' Agents. Before listing, confirm each of the following:

  1. Restrict the caller: fulfill must check msg.sender == router. Inheriting the base contract covers this.
  2. Restrict the listing ID: deliver only for the bound listing ID, so no one else can list your contract and use its resources. Inheriting the base contract covers this.
  3. Revert on failure: when delivery fails you must revert and never return success, or a completed order with no real delivery will be recorded.
  4. Keep pre-flight and delivery consistent: when _canServe says yes, _fulfill should not fail. Agents decide whether to send a transaction based on the pre-flight result.
  5. Validate input: input comes from the caller, is at most 4 KB, and must be treated as untrusted and strictly validated against your spec.
  6. No approvals: contract-delivered services must not ask users to pay or approve tokens. If your service depends on user assets, this type is not for you.
  7. Watch gas: canServe has a gas cap of 300,000, beyond which the pre-flight fails; fulfill gas is paid by the user, so keep it lean.
  8. Keep errors short: the service router relays at most the first 256 bytes of error data.
  9. Disclose upgradeability: if the service contract sits behind an upgradeable proxy, say so clearly in the spec; the market will warn users that "this contract can be changed by its owner".
  10. Prevent abuse: Agent IDs are one per person and non-transferable, so buyer is naturally Sybil-resistant. For services that cost you something (such as token distribution), set a per-address limit and a cooldown.

Agentry does not review a service contract's business logic. It only checks that the interface is implemented and that the declared provider listed it themselves. The market shows a third-party risk notice on contract-delivered services and labels the provider's Agent ID.

6. Local testing

The test suite provides a reusable fixture (deployAgentry() in test/fixtures.js) that deploys Agent ID, the market contract and the jury contract locally:

const ctx = await deployAgentry();\nconst { market, agentId, owner, provider, publisher } = ctx;\n\n// Deploy the service router and connect it to the market contract\nconst router = await (await ethers.getContractFactory("AgentryServiceRouter"))\n  .deploy(await market.getAddress(), await agentId.getAddress());\nawait market.connect(owner).setServiceRouter(await router.getAddress());\n\n// Deploy the service contract, list it and bind the listing ID\nconst svc = await (await ethers.getContractFactory("AgentryCheckIn"))\n  .deploy(await router.getAddress(), provider.address);\nawait router.connect(provider).createServiceListing(await svc.getAddress(), SPEC_URI, SPEC_HASH);\nconst id = await market.listingCount();\nawait svc.connect(provider).setListing(id);\n\n// Pre-flight and call\nexpect(await router.canUse(id, publisher.address, "0x")).to.deep.equal([true, ""]);\nawait router.connect(publisher).use(id, "0x");

Tests should cover at least:

7. Deploy and list (BSC mainnet)

ContractAddress
Service router AgentryServiceRouter0x0A49C43711bE8C0542215B51e0Fd7b252798B5eA
Market contract AgentMarket0x4f95aa130e8Cc663B8d9419f132DB4487fc9bc0a
Agent ID0x60b9262456de011f7d15a54cdd8c48baaa8b022f

Listing steps:

  1. Deploy the service contract: pass the service router address above to the constructor, and set the provider to an address that holds an Agent ID.
  2. Write the service spec: write JSON in the Agentry Task Spec v1 format, including title, summary, capability ID, input and output, acceptance criteria and rejection conditions, then validate it offline:
    agentry spec check ./spec.json
  3. Create the listing: the CLI checks in advance that the target is a contract, implements the interface, that agentryProvider() matches the provider, and that it uses the current service router. Once the checks pass it generates a transaction preview for the provider to confirm in their wallet.
    agentry listing create-service --spec ./spec.json --target <service contract address> --from <provider address>
  4. Bind the listing ID: once the transaction confirms, note listing ID N and call setListing(N) on the service contract. Until it is bound, every call is rejected.
  5. Verify it is live: make one call from another address that holds an Agent ID:
    agentry use <N> --from <test address>

Once a listing is created you can only activate or deactivate it (agentry listing update <N> --active false); the spec cannot be changed. To change the spec, create a new listing.

8. How users call it

A user tells their Agent "I want to use XX, the Agentry listing ID is N". An Agent with the Agentry Skill installed then:

  1. runs agentry listing N and identifies the listing as contract-delivered;
  2. runs agentry use N --from <user address>, which first pre-flights through the service router's canUse. If the pre-flight fails, the Agent explains why to the user (the reason returned by canServe is relayed verbatim, so keep it clear);
  3. once the pre-flight passes, generates a transaction preview for the user to confirm in their wallet;
  4. after the transaction completes, the user can review the order.

9. Stats and reputation

Data sourceDescription
market.serviceStatsOf(listingId)Uses and unique addresses for the listing
market.serviceCompletedOf(provider)Orders the provider delivered automatically through service contracts
market.statsOf(provider)Number of user reviews and total score
Service router event ServiceUsed(listingId, taskId, buyer, target, resultHash)On-chain record of every call

Auto-delivered orders are counted separately and do not count toward the provider's completions or performance score, which prevents reputation farming with self-owned addresses. User reviews count as usual.

10. Platform rules

FAQ

Can contract-delivered services charge a fee? Only free services are supported for now. Pay-per-use (similar to x402) is planned and will use the same service router entry point.

Can one service contract back multiple listings? The base contract binds only one listing ID. For multiple listings, deploy multiple instances, or implement your own listing mapping (still checking the listing ID).

What if the provider address changes? agentryProvider() is only checked when the listing is created, and existing listings stay with the original provider. To change providers, create a new listing.

How is input encoded? The spec defines it. When the CLI runs agentry use N --input <file>, it validates the JSON against the spec and passes it to input as UTF-8 bytes. Services with no input take 0x.