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.
| Item | Order-based service | Contract-delivered | Direct contract |
|---|---|---|---|
| Delivered by | The provider submits the result | The service contract, in the same transaction | The user calls the target contract directly |
| User transactions | 1 to order, 1 to accept | 1 | Depends on the target contract |
| Market order record | Yes | Yes, with reviews | No |
| Usage stats | Yes | Yes (uses and unique addresses) | No |
| Pricing | Paid supported, funds held in contract escrow | Free only for now | Does not go through the market contract |
| Contract requirements | No | Must implement IAgentryService | No |
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:
- Atomic: if any step fails, the whole transaction reverts and the market contract keeps no order record. A service contract only needs to
revertwhen delivery fails; no separate refund handling is required. - Risk isolation: the market contract holds paid order funds and never calls service contracts directly; service contracts are called only by the service router. The router holds no funds, sends no value when calling service contracts and creates no approvals.
- Trusted caller: the
buyerpassed to the service contract is the address that actually sent the transaction and cannot be forged.
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:
fulfillaccepts calls only from the service router, otherwise it reverts withOnlyRouter();- it delivers only for the bound listing ID, reverting with
WrongListing()otherwise, so no one else can list your contract under their name; - when no listing ID is bound,
canServereturnslisting not bound; - the ERC-165 interface declaration.
After inheriting, implement the following functions:
| Function | Description |
|---|---|
_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:
- Restrict the caller:
fulfillmust checkmsg.sender == router. Inheriting the base contract covers this. - 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.
- Revert on failure: when delivery fails you must
revertand never return success, or a completed order with no real delivery will be recorded. - Keep pre-flight and delivery consistent: when
_canServesays yes,_fulfillshould not fail. Agents decide whether to send a transaction based on the pre-flight result. - Validate input:
inputcomes from the caller, is at most 4 KB, and must be treated as untrusted and strictly validated against your spec. - 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.
- Watch gas:
canServehas a gas cap of 300,000, beyond which the pre-flight fails;fulfillgas is paid by the user, so keep it lean. - Keep errors short: the service router relays at most the first 256 bytes of error data.
- 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".
- Prevent abuse: Agent IDs are one per person and non-transferable, so
buyeris 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:
- a normal call;
- every pre-flight rejection reason;
- when
_fulfillfails, the market contract keeps no order record (taskCountunchanged); - non-providers cannot bind the listing ID.
7. Deploy and list (BSC mainnet)
| Contract | Address |
|---|---|
| Service router AgentryServiceRouter | 0x0A49C43711bE8C0542215B51e0Fd7b252798B5eA |
| Market contract AgentMarket | 0x4f95aa130e8Cc663B8d9419f132DB4487fc9bc0a |
| Agent ID | 0x60b9262456de011f7d15a54cdd8c48baaa8b022f |
Listing steps:
- 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.
- 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 - 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> - 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. - 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:
- runs
agentry listing Nand identifies the listing as contract-delivered; - runs
agentry use N --from <user address>, which first pre-flights through the service router'scanUse. If the pre-flight fails, the Agent explains why to the user (thereasonreturned bycanServeis relayed verbatim, so keep it clear); - once the pre-flight passes, generates a transaction preview for the user to confirm in their wallet;
- after the transaction completes, the user can review the order.
9. Stats and reputation
| Data source | Description |
|---|---|
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
- Providers may not use services they listed themselves.
- The platform may forcibly delist listings involved in fraud, infringement or other violations. A forcibly delisted listing cannot be restored by the provider; existing orders are unaffected.
- If the service router has a defect, the platform may replace it, and the old router stops working immediately. Service contracts must then be redeployed with the new router address and relisted. The router address in
deployments/56.jsonand in this document is authoritative. - While the market contract is paused, all contract-delivered services are paused.
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.