From 3b87adf8ff232da81fa69bc30895dddca90134cc Mon Sep 17 00:00:00 2001 From: kemppelinvestments-del Date: Wed, 11 Nov 2026 23:45:23 -0500 Subject: [PATCH 1/2] feat: add AgentCoin action provider Adds agentcoinActionProvider (find_service, route_task, place_order, get_order, claim_listing, verify, refund) for escrowed agent-to-agent orders with delivery verdicts on Base Sepolia. Includes static zod schemas, unit tests, README and a changeset. --- .../.changeset/brave-agentcoin-escrow.md | 5 + typescript/agentkit/README.md | 33 + .../src/action-providers/agentcoin/README.md | 56 ++ .../agentcoin/agentcoinActionProvider.test.ts | 401 +++++++++++ .../agentcoin/agentcoinActionProvider.ts | 620 ++++++++++++++++++ .../action-providers/agentcoin/constants.ts | 168 +++++ .../src/action-providers/agentcoin/index.ts | 2 + .../src/action-providers/agentcoin/schemas.ts | 125 ++++ .../agentkit/src/action-providers/index.ts | 1 + 9 files changed, 1411 insertions(+) create mode 100644 typescript/.changeset/brave-agentcoin-escrow.md create mode 100644 typescript/agentkit/src/action-providers/agentcoin/README.md create mode 100644 typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.test.ts create mode 100644 typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.ts create mode 100644 typescript/agentkit/src/action-providers/agentcoin/constants.ts create mode 100644 typescript/agentkit/src/action-providers/agentcoin/index.ts create mode 100644 typescript/agentkit/src/action-providers/agentcoin/schemas.ts diff --git a/typescript/.changeset/brave-agentcoin-escrow.md b/typescript/.changeset/brave-agentcoin-escrow.md new file mode 100644 index 0000000000..6217546fe8 --- /dev/null +++ b/typescript/.changeset/brave-agentcoin-escrow.md @@ -0,0 +1,5 @@ +--- +"@coinbase/agentkit": patch +--- + +Added AgentCoin action provider for escrowed agent-to-agent orders with delivery verdicts on Base Sepolia diff --git a/typescript/agentkit/README.md b/typescript/agentkit/README.md index 37b14207fb..a2ccf7e7ce 100644 --- a/typescript/agentkit/README.md +++ b/typescript/agentkit/README.md @@ -178,6 +178,39 @@ const agent = createAgent({
+AgentCoin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
find_serviceSearches the AgentCoin index of paid agent services (A2A, MCP, x402, ERC-8004) or fetches one listing (Base Sepolia testnet).
route_taskRanks candidate sellers for a task and budget, with quote, request template and delivery score.
place_orderPlaces an escrowed order and funds it from the wallet; funds are released only on a staked evaluator's delivery verdict.
get_orderReturns an order's status, escrow job state, verdict and signed delivery record.
claim_listingSeller side: indexes a metadata URL and claims a listing with an EIP-712 signature or well-known file.
verifyChecks AgentCoin EIP-191 signatures on delivery scores and delivery records locally.
refundSends the escrow refund-path call that applies to a job (cancel, claimRefund, timeoutRelease or finalize).
+
+
Base Account diff --git a/typescript/agentkit/src/action-providers/agentcoin/README.md b/typescript/agentkit/src/action-providers/agentcoin/README.md new file mode 100644 index 0000000000..922f7fdb7c --- /dev/null +++ b/typescript/agentkit/src/action-providers/agentcoin/README.md @@ -0,0 +1,56 @@ +# AgentCoin Action Provider + +This directory contains the **AgentCoinActionProvider** implementation, which lets an agent find paid agent services, pay them through an escrow that releases funds only on a staked evaluator's delivery verdict, and claim refunds. + +> **Testnet only.** The provider supports **Base Sepolia** (`eip155:84532`) and test USDC (`0x036CbD53842c5426634e7929541eC2318f3dCF7e`). The hosted router at https://agentcoinhq.com is an early testnet deployment; payments have no real value. Source for the AgentCoin client libraries: https://github.com/stos-technologies/agentcoin + +## Directory Structure + +``` +agentcoin/ +├── agentcoinActionProvider.ts # Main provider +├── agentcoinActionProvider.test.ts # Unit tests +├── constants.ts # Router URL, contract addresses and ABIs +├── schemas.ts # Action schemas +├── index.ts # Main exports +└── README.md # This file +``` + +## Actions + +- `find_service`: Search the AgentCoin index of paid agent services (A2A, MCP, x402, ERC-8004), or fetch one listing by id +- `route_task`: Rank candidate sellers for a task and budget (quote, request template, delivery score). No payment +- `place_order`: Place an escrowed order and fund it from the wallet + + - Checks the router's unsigned transactions against local constants (USDC, JobEscrow, chain, amount, buyer) before signing + - Sends `USDC.approve` and `JobEscrow.createAndFundFor`, records the job with the router and calls the seller + - The amount is capped by `maxPayment` (default 50000 base units = 0.05 test USDC) + +- `get_order`: Read an order's status, escrow job state, deliverable hash, verdict and signed delivery record +- `claim_listing`: Seller side. Index a metadata URL and/or claim a listing with an EIP-712 signature or a `/.well-known/agentcoin-claim` file +- `verify`: Check AgentCoin EIP-191 signatures locally (delivery scores and delivery records, RFC 8785 canonical JSON) +- `refund`: Send the JobEscrow refund-path call that applies to the job (`cancel`, `claimRefund`, `timeoutRelease` or `finalize`), after a simulation + +## Configuration + +```typescript +import { agentcoinActionProvider } from "@coinbase/agentkit"; + +const provider = agentcoinActionProvider({ + baseUrl: "https://agentcoinhq.com", // optional, or set AGENTCOIN_URL + maxPayment: 50000n, // optional, USDC base units per order + allowedServiceIds: ["svc_962928f654d2a8a1"], // optional allowlist for place_order +}); +``` + +No API key is needed. Signing and transactions use the agent's `EvmWalletProvider`. + +## Network Support + +Base Sepolia only (`base-sepolia`). + +## Notes + +- Escrow flow: funds sit in JobEscrow until a staked evaluator rules. A "delivered" verdict pays the seller; "not delivered", or no verdict before the deadline, refunds the buyer. A challenged verdict that is overturned slashes the evaluator's stake. +- Delivery scores exclude orders placed by the AgentCoin operator itself. +- For direct (non-escrow) x402 payments, use the `x402` action provider. diff --git a/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.test.ts b/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.test.ts new file mode 100644 index 0000000000..b6f7d5b7af --- /dev/null +++ b/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.test.ts @@ -0,0 +1,401 @@ +import { + encodeAbiParameters, + encodeEventTopics, + encodeFunctionData, + keccak256, + toBytes, +} from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { EvmWalletProvider } from "../../wallet-providers"; +import { + agentcoinActionProvider, + AgentCoinActionProvider, + canonicalJson, + verifyAgentCoinSignature, +} from "./agentcoinActionProvider"; +import { + FindServiceSchema, + PlaceOrderSchema, + RefundSchema, + RouteTaskSchema, + VerifySchema, +} from "./schemas"; +import { AGENTCOIN_ESCROW, AGENTCOIN_USDC, ERC20_APPROVE_ABI, ESCROW_ABI } from "./constants"; + +const BUYER = "0x78e2C0164A80F3e337AE17e3bA4b8EA2C0Fa488e"; +const PROVIDER = "0x6A32bC3Bb5eA1dc814f14E29e6f026535129A84f"; +const EVALUATOR = "0x1111111111111111111111111111111111111111"; +const SPEC_HASH = `0x${"ab".repeat(32)}` as `0x${string}`; +const TX1 = `0x${"01".repeat(32)}` as `0x${string}`; +const TX2 = `0x${"02".repeat(32)}` as `0x${string}`; + +const jsonResponse = (body: unknown, status = 200) => + ({ + ok: status >= 200 && status < 300, + status, + json: async () => body, + text: async () => JSON.stringify(body), + }) as unknown as Response; + +const escrowOrder = (overrides: Record = {}) => ({ + orderId: "ord_0123456789abcdef", + serviceId: "svc_962928f654d2a8a1", + mode: "escrow", + escrow: { + chainId: 84532, + contract: AGENTCOIN_ESCROW, + token: AGENTCOIN_USDC, + amount: "10000", + provider: PROVIDER, + evaluator: EVALUATOR, + }, + transactions: [ + { + label: "approve", + chainId: 84532, + to: AGENTCOIN_USDC, + value: "0", + data: encodeFunctionData({ + abi: ERC20_APPROVE_ABI, + functionName: "approve", + args: [AGENTCOIN_ESCROW, 10000n], + }), + }, + { + label: "createAndFundFor", + chainId: 84532, + to: AGENTCOIN_ESCROW, + value: "0", + data: encodeFunctionData({ + abi: ESCROW_ABI, + functionName: "createAndFundFor", + args: [BUYER, PROVIDER, EVALUATOR, 10000n, 1900000000n, SPEC_HASH], + }), + }, + ], + sellerCall: { method: "POST", url: "https://seller.example/v1/notarize" }, + ...overrides, +}); + +const jobCreatedLog = () => ({ + address: AGENTCOIN_ESCROW, + topics: encodeEventTopics({ + abi: ESCROW_ABI, + eventName: "JobCreated", + args: { jobId: 42n, client: BUYER, provider: PROVIDER }, + }), + data: encodeAbiParameters( + [ + { type: "address" }, + { type: "uint256" }, + { type: "uint64" }, + { type: "bytes32" }, + { type: "uint32" }, + ], + [EVALUATOR, 10000n, 1900000000n, SPEC_HASH, 1], + ), +}); + +describe("AgentCoin schemas", () => { + it("accepts a valid search", () => { + expect(FindServiceSchema.safeParse({ q: "notary", maxPrice: "10000" }).success).toBe(true); + }); + + it("rejects a non-numeric price", () => { + expect(FindServiceSchema.safeParse({ maxPrice: "0.01" }).success).toBe(false); + }); + + it("requires a task for route_task", () => { + expect(RouteTaskSchema.safeParse({}).success).toBe(false); + }); + + it("requires a serviceId for place_order", () => { + expect(PlaceOrderSchema.safeParse({ body: {} }).success).toBe(false); + }); + + it("rejects a non-decimal jobId", () => { + expect(RefundSchema.safeParse({ jobId: "0x10" }).success).toBe(false); + }); + + it("rejects unknown fields", () => { + expect(VerifySchema.safeParse({ serviceId: "svc_1", extra: true }).success).toBe(false); + }); +}); + +describe("canonicalJson", () => { + it("sorts keys and drops undefined members (RFC 8785)", () => { + expect( + canonicalJson({ b: 1, a: [true, null, "x"], c: undefined, d: { z: 1e-7, y: 0.00001 } }), + ).toBe('{"a":[true,null,"x"],"b":1,"d":{"y":0.00001,"z":1e-7}}'); + }); +}); + +describe("verifyAgentCoinSignature", () => { + const account = privateKeyToAccount(`0x${"11".repeat(32)}`); + + const sign = async (doc: Record) => { + const digest = keccak256(toBytes(canonicalJson(doc))); + const value = await account.signMessage({ message: { raw: digest } }); + return { + ...doc, + signature: { scheme: "eip191", signer: account.address, signedDigest: digest, value }, + }; + }; + + it("accepts a valid signature", async () => { + const result = await verifyAgentCoinSignature(await sign({ v: "x", n: 1 })); + expect(result.valid).toBe(true); + expect(result.signer).toBe(account.address); + expect(result.signerIsOperator).toBe(false); + }); + + it("rejects a modified document", async () => { + const doc = await sign({ v: "x", n: 1 }); + const result = await verifyAgentCoinSignature({ ...doc, n: 2 }); + expect(result.valid).toBe(false); + }); + + it("reports a missing signature", async () => { + expect((await verifyAgentCoinSignature({ v: "x" })).valid).toBe(false); + }); +}); + +describe("AgentCoinActionProvider", () => { + let provider: AgentCoinActionProvider; + let wallet: jest.Mocked; + let fetchMock: jest.SpyInstance; + + beforeEach(() => { + provider = agentcoinActionProvider({ baseUrl: "https://router.example/" }); + wallet = { + getAddress: jest.fn().mockReturnValue(BUYER), + getNetwork: jest + .fn() + .mockReturnValue({ protocolFamily: "evm", networkId: "base-sepolia", chainId: "84532" }), + sendTransaction: jest.fn(), + waitForTransactionReceipt: jest.fn(), + readContract: jest.fn(), + signTypedData: jest.fn(), + getPublicClient: jest.fn(), + } as unknown as jest.Mocked; + fetchMock = jest.spyOn(global, "fetch"); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + describe("supportsNetwork", () => { + it("supports Base Sepolia", () => { + expect(provider.supportsNetwork({ protocolFamily: "evm", networkId: "base-sepolia" })).toBe( + true, + ); + }); + + it("does not support Base mainnet", () => { + expect(provider.supportsNetwork({ protocolFamily: "evm", networkId: "base-mainnet" })).toBe( + false, + ); + }); + + it("does not support non-EVM networks", () => { + expect(provider.supportsNetwork({ protocolFamily: "svm", networkId: "solana-devnet" })).toBe( + false, + ); + }); + }); + + describe("findService", () => { + it("builds the search query", async () => { + fetchMock.mockResolvedValue(jsonResponse({ results: [] })); + await provider.findService({ q: "notary", maxPrice: "10000" }); + expect(fetchMock.mock.calls[0][0]).toBe( + "https://router.example/v1/services?q=notary&maxPrice=10000", + ); + }); + + it("fetches one listing by id", async () => { + fetchMock.mockResolvedValue(jsonResponse({ id: "svc_1" })); + const out = JSON.parse(await provider.findService({ id: "svc_1" })); + expect(fetchMock.mock.calls[0][0]).toBe("https://router.example/v1/services/svc_1"); + expect(out.id).toBe("svc_1"); + }); + + it("returns HTTP errors as JSON", async () => { + fetchMock.mockResolvedValue(jsonResponse({ error: "not found" }, 404)); + const out = JSON.parse(await provider.findService({ id: "svc_x" })); + expect(out.success).toBe(false); + expect(out.error).toContain("404"); + }); + }); + + describe("routeTask", () => { + it("defaults the network constraint to Base Sepolia", async () => { + fetchMock.mockResolvedValue(jsonResponse({ candidates: [] })); + await provider.routeTask({ task: "timestamp notary", budget: "10000" }); + const body = JSON.parse(fetchMock.mock.calls[0][1].body); + expect(body).toEqual({ + task: "timestamp notary", + budget: "10000", + constraints: { network: "eip155:84532" }, + }); + }); + }); + + describe("placeOrder", () => { + it("checks, funds and records an escrow order", async () => { + fetchMock + .mockResolvedValueOnce(jsonResponse(escrowOrder())) + .mockResolvedValueOnce(jsonResponse({ status: "funded", verdict: null })) + .mockResolvedValueOnce(jsonResponse({ receipt: { v: "agentcoin-notary/v1" } })); + wallet.sendTransaction.mockResolvedValueOnce(TX1).mockResolvedValueOnce(TX2); + wallet.waitForTransactionReceipt + .mockResolvedValueOnce({ status: "success", logs: [] }) + .mockResolvedValueOnce({ status: "success", logs: [jobCreatedLog()] }); + + const out = JSON.parse( + await provider.placeOrder(wallet, { + serviceId: "svc_962928f654d2a8a1", + body: { sha256: SPEC_HASH }, + }), + ); + + expect(out.jobId).toBe("42"); + expect(out.status).toBe("funded"); + expect(out.transactions).toEqual([ + { label: "approve", hash: TX1 }, + { label: "createAndFundFor", hash: TX2 }, + ]); + expect(wallet.sendTransaction).toHaveBeenCalledTimes(2); + const orderBody = JSON.parse(fetchMock.mock.calls[0][1].body); + expect(orderBody).toEqual({ + serviceId: "svc_962928f654d2a8a1", + mode: "escrow", + buyer: BUYER, + }); + expect(fetchMock.mock.calls[1][0]).toBe( + "https://router.example/v1/orders/ord_0123456789abcdef/receipt", + ); + expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ jobId: "42", paymentTx: TX2 }); + const header = fetchMock.mock.calls[2][1].headers["PAYMENT-SIGNATURE"]; + expect(JSON.parse(Buffer.from(header, "base64").toString())).toEqual({ + x402Version: 2, + accepted: { scheme: "agentcoin-escrow", network: "eip155:84532" }, + payload: { jobId: "42", txHash: TX2 }, + }); + }); + + it("refuses an amount above maxPayment", async () => { + const order = escrowOrder(); + fetchMock.mockResolvedValueOnce( + jsonResponse({ ...order, escrow: { ...order.escrow, amount: "60000" } }), + ); + const out = JSON.parse( + await provider.placeOrder(wallet, { serviceId: "svc_962928f654d2a8a1" }), + ); + expect(out.success).toBe(false); + expect(out.error).toContain("maxPayment"); + expect(wallet.sendTransaction).not.toHaveBeenCalled(); + }); + + it("refuses an unexpected escrow contract", async () => { + const order = escrowOrder(); + fetchMock.mockResolvedValueOnce( + jsonResponse({ ...order, escrow: { ...order.escrow, contract: EVALUATOR } }), + ); + const out = JSON.parse( + await provider.placeOrder(wallet, { serviceId: "svc_962928f654d2a8a1" }), + ); + expect(out.success).toBe(false); + expect(wallet.sendTransaction).not.toHaveBeenCalled(); + }); + + it("refuses a funding transaction for another client", async () => { + wallet.getAddress.mockReturnValue(PROVIDER); + fetchMock.mockResolvedValueOnce(jsonResponse(escrowOrder())); + const out = JSON.parse( + await provider.placeOrder(wallet, { serviceId: "svc_962928f654d2a8a1" }), + ); + expect(out.success).toBe(false); + expect(out.error).toContain("client"); + expect(wallet.sendTransaction).not.toHaveBeenCalled(); + }); + + it("respects allowedServiceIds", async () => { + const limited = agentcoinActionProvider({ allowedServiceIds: ["svc_a"] }); + const out = JSON.parse(await limited.placeOrder(wallet, { serviceId: "svc_b" })); + expect(out.success).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); + }); + + describe("getOrder", () => { + it("reads the order", async () => { + fetchMock.mockResolvedValue(jsonResponse({ orderId: "ord_1", verdict: "complete" })); + const out = JSON.parse(await provider.getOrder({ orderId: "ord_1" })); + expect(fetchMock.mock.calls[0][0]).toBe("https://router.example/v1/orders/ord_1"); + expect(out.verdict).toBe("complete"); + }); + }); + + describe("claimListing", () => { + it("returns the claim challenge without signing", async () => { + fetchMock.mockResolvedValue(jsonResponse({ typedData: {} })); + await provider.claimListing(wallet, { serviceId: "svc_1" }); + expect(fetchMock.mock.calls[0][0]).toBe("https://router.example/v1/services/svc_1/claim"); + expect(wallet.signTypedData).not.toHaveBeenCalled(); + }); + + it("signs and submits an EIP-712 claim", async () => { + fetchMock + .mockResolvedValueOnce(jsonResponse({ id: "svc_1", metadataHash: SPEC_HASH })) + .mockResolvedValueOnce(jsonResponse({ claimed: true })); + wallet.signTypedData.mockResolvedValue("0xsig"); + const out = JSON.parse( + await provider.claimListing(wallet, { serviceId: "svc_1", sign: true }), + ); + expect(out.claimed).toBe(true); + expect(wallet.signTypedData.mock.calls[0][0].primaryType).toBe("Claim"); + expect(JSON.parse(fetchMock.mock.calls[1][1].body).signature).toBe("0xsig"); + }); + }); + + describe("refund", () => { + const job = (state: number, extra: Record = {}) => ({ + client: BUYER, + state, + accepted: true, + deadline: 1n, + ...extra, + }); + + it("sends claimRefund for a funded job past its deadline", async () => { + wallet.readContract.mockResolvedValue(job(2)); + const simulateContract = jest.fn().mockResolvedValue({}); + wallet.getPublicClient.mockReturnValue({ simulateContract } as never); + wallet.sendTransaction.mockResolvedValue(TX1); + wallet.waitForTransactionReceipt.mockResolvedValue({ status: "success" }); + const out = JSON.parse(await provider.refund(wallet, { jobId: "42" })); + expect(out).toMatchObject({ action: "claimRefund", sent: true, tx: TX1 }); + expect(simulateContract.mock.calls[0][0].functionName).toBe("claimRefund"); + }); + + it("returns the reason when no refund applies", async () => { + wallet.readContract.mockResolvedValue(job(8)); + const out = JSON.parse(await provider.refund(wallet, { jobId: "42" })); + expect(out.sent).toBe(false); + expect(wallet.sendTransaction).not.toHaveBeenCalled(); + }); + + it("does not send when the simulation reverts", async () => { + wallet.readContract.mockResolvedValue(job(3)); + wallet.getPublicClient.mockReturnValue({ + simulateContract: jest.fn().mockRejectedValue(new Error("EvalWindowOpen")), + } as never); + const out = JSON.parse(await provider.refund(wallet, { jobId: "42" })); + expect(out.sent).toBe(false); + expect(out.reason).toContain("simulation reverted"); + expect(wallet.sendTransaction).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.ts b/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.ts new file mode 100644 index 0000000000..2da67e8185 --- /dev/null +++ b/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.ts @@ -0,0 +1,620 @@ +import { z } from "zod"; +import { + decodeFunctionData, + encodeFunctionData, + getAddress, + keccak256, + parseEventLogs, + toBytes, + verifyMessage, + Hex, +} from "viem"; +import { ActionProvider } from "../actionProvider"; +import { CreateAction } from "../actionDecorator"; +import { Network } from "../../network"; +import { EvmWalletProvider } from "../../wallet-providers"; +import { + FindServiceSchema, + RouteTaskSchema, + PlaceOrderSchema, + GetOrderSchema, + ClaimListingSchema, + VerifySchema, + RefundSchema, +} from "./schemas"; +import { + AGENTCOIN_CAIP2, + AGENTCOIN_CHAIN_ID, + AGENTCOIN_DEFAULT_MAX_PAYMENT, + AGENTCOIN_DEFAULT_URL, + AGENTCOIN_ESCROW, + AGENTCOIN_OPERATOR_SIGNER, + AGENTCOIN_SUPPORTED_NETWORKS, + AGENTCOIN_USDC, + ERC20_APPROVE_ABI, + ESCROW_ABI, + ESCROW_STATES, +} from "./constants"; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Json = Record; + +/** + * Configuration for the AgentCoin action provider. + */ +export interface AgentCoinConfig { + /** Router base URL. Defaults to AGENTCOIN_URL or https://agentcoinhq.com. */ + baseUrl?: string; + /** Per-order payment ceiling in USDC base units. Defaults to 50000 (0.05 test USDC). */ + maxPayment?: bigint | string | number; + /** If set, orders are only placed for these listing ids. */ + allowedServiceIds?: string[]; + /** Timeout for each router request in milliseconds. Defaults to 90000. */ + requestTimeoutMs?: number; +} + +/** + * RFC 8785 (JCS) canonical JSON for plain JSON values. + * + * @param value - The JSON value to canonicalize. + * @returns The canonical JSON string. + */ +export function canonicalJson(value: unknown): string { + if (value === null || typeof value !== "object") { + if (typeof value === "number" && !Number.isFinite(value)) { + throw new Error("non-finite number cannot be canonicalized"); + } + return JSON.stringify(value); + } + if (Array.isArray(value)) { + return `[${value.map(v => (v === undefined ? "null" : canonicalJson(v))).join(",")}]`; + } + const entries = Object.keys(value as Json) + .filter(k => (value as Json)[k] !== undefined) + .sort() + .map(k => `${JSON.stringify(k)}:${canonicalJson((value as Json)[k])}`); + return `{${entries.join(",")}}`; +} + +/** + * Checks an AgentCoin EIP-191 document signature: personal_sign over keccak256(RFC 8785(document without "signature")). + * + * @param doc - The signed document. + * @returns Whether the signature is valid, the recovered signer and whether it is the AgentCoin operator. + */ +export async function verifyAgentCoinSignature(doc: Json | null | undefined): Promise { + const sig = doc?.signature; + if (!sig || sig.scheme !== "eip191") return { valid: false, reason: "no eip191 signature" }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { signature: _signature, ...unsigned } = doc as Json; + const digest = keccak256(toBytes(canonicalJson(unsigned))); + if (sig.signedDigest && String(sig.signedDigest).toLowerCase() !== digest.toLowerCase()) { + return { valid: false, digest, reason: "digest mismatch (document modified)" }; + } + const valid = await verifyMessage({ + address: getAddress(sig.signer), + message: { raw: digest }, + signature: sig.value as Hex, + }); + const signer = getAddress(sig.signer); + return { + valid, + signer, + signerIsOperator: signer === getAddress(AGENTCOIN_OPERATOR_SIGNER), + digest, + }; +} + +/** + * AgentCoinActionProvider lets an agent find paid agent services, pay them through an escrow that + * releases funds only on a staked evaluator's delivery verdict, and claim refunds. Base Sepolia testnet only. + */ +export class AgentCoinActionProvider extends ActionProvider { + private readonly baseUrl: string; + private readonly maxPayment: bigint; + private readonly allowedServiceIds: Set | null; + private readonly requestTimeoutMs: number; + + /** + * Constructs a new AgentCoinActionProvider. + * + * @param config - Optional configuration. + */ + constructor(config: AgentCoinConfig = {}) { + super("agentcoin", []); + this.baseUrl = (config.baseUrl ?? process.env.AGENTCOIN_URL ?? AGENTCOIN_DEFAULT_URL).replace( + /\/+$/, + "", + ); + this.maxPayment = BigInt(config.maxPayment ?? AGENTCOIN_DEFAULT_MAX_PAYMENT); + this.allowedServiceIds = config.allowedServiceIds ? new Set(config.allowedServiceIds) : null; + this.requestTimeoutMs = config.requestTimeoutMs ?? 90_000; + } + + /** + * Searches the AgentCoin service index. + * + * @param args - The search arguments. + * @returns The search results as stringified JSON. + */ + @CreateAction({ + name: "find_service", + description: `Searches the AgentCoin index of paid agent services (A2A, MCP, x402, ERC-8004). +With id: returns one listing with skills, prices, request formats and delivery score. +Inputs: id, q (text), protocol, maxPrice (USDC base units), minScore (0-1), claimed, cursor, limit. +Read-only. Base Sepolia testnet.`, + schema: FindServiceSchema, + }) + async findService(args: z.infer): Promise { + return this.run(async () => { + if (args.id) return this.api("GET", `/v1/services/${encodeURIComponent(args.id)}`); + const qs = new URLSearchParams(); + for (const [k, v] of Object.entries(args)) { + if (v !== undefined && v !== null && k !== "id") qs.set(k, String(v)); + } + const query = qs.toString(); + return this.api("GET", `/v1/services${query ? `?${query}` : ""}`); + }); + } + + /** + * Ranks candidate sellers for a task. + * + * @param args - The task and constraints. + * @returns Ranked candidates as stringified JSON. + */ + @CreateAction({ + name: "route_task", + description: `Returns ranked candidate sellers for a task and budget, with quote, request template, +delivery score and supported order modes. No payment. Read-only. Base Sepolia testnet.`, + schema: RouteTaskSchema, + }) + async routeTask(args: z.infer): Promise { + return this.run(async () => { + const { task, budget, ...constraints } = args; + return this.api("POST", "/v1/route", { + task, + ...(budget ? { budget } : {}), + constraints: { network: AGENTCOIN_CAIP2, ...constraints }, + }); + }); + } + + /** + * Places an escrowed order and funds it from the wallet. + * + * @param walletProvider - The wallet provider that pays for the order. + * @param args - The order arguments. + * @returns The order, funding transactions and seller response as stringified JSON. + */ + @CreateAction({ + name: "place_order", + description: `Places an escrowed order for an AgentCoin listing and funds it from the wallet. +Test USDC is held in the JobEscrow contract until a staked evaluator rules on delivery: paid to the +seller if delivered, refunded to the buyer if not (or if no verdict arrives in time). +Sends 2 transactions (USDC approve, createAndFundFor), records the job with the router and calls the seller. +The amount is capped by the provider's maxPayment (default 0.05 test USDC). +Inputs: serviceId, optional skillId, optional body (JSON sent to the seller). Base Sepolia testnet.`, + schema: PlaceOrderSchema, + }) + async placeOrder( + walletProvider: EvmWalletProvider, + args: z.infer, + ): Promise { + return this.run(async () => { + this.assertServiceAllowed(args.serviceId); + const me = getAddress(walletProvider.getAddress()); + const order = await this.api("POST", "/v1/orders", { + serviceId: args.serviceId, + ...(args.skillId ? { skillId: args.skillId } : {}), + mode: "escrow", + buyer: me, + }); + const txs = this.checkEscrowOrder(order, me); + + const sent: { label: string; hash: Hex }[] = []; + let jobId: string | null = null; + for (const tx of txs) { + const hash = await walletProvider.sendTransaction({ + to: getAddress(tx.to), + data: tx.data as Hex, + value: 0n, + }); + const receipt = await walletProvider.waitForTransactionReceipt(hash); + if (receipt?.status !== "success") + throw new Error(`${tx.label ?? "transaction"} reverted: ${hash}`); + sent.push({ label: tx.label ?? "", hash }); + const created = parseEventLogs({ + abi: ESCROW_ABI, + logs: receipt.logs ?? [], + eventName: "JobCreated", + }).find(l => getAddress(l.address) === getAddress(AGENTCOIN_ESCROW)); + if (created) jobId = created.args.jobId.toString(); + } + if (!jobId) throw new Error("no JobCreated event in the funding transaction"); + const fundTx = sent[sent.length - 1].hash; + const recorded = await this.api( + "POST", + `/v1/orders/${encodeURIComponent(order.orderId)}/receipt`, + { + jobId, + paymentTx: fundTx, + }, + ); + + let seller: Json | null = null; + const call = order.sellerCall; + if (call?.url) { + const header = Buffer.from( + JSON.stringify({ + x402Version: 2, + accepted: { scheme: "agentcoin-escrow", network: AGENTCOIN_CAIP2 }, + payload: { jobId, txHash: fundTx }, + }), + ).toString("base64"); + const response = await fetch(call.url, { + method: call.method ?? "POST", + headers: { "content-type": "application/json", "PAYMENT-SIGNATURE": header }, + ...(args.body !== undefined ? { body: JSON.stringify(args.body) } : {}), + signal: AbortSignal.timeout(this.requestTimeoutMs), + }); + const text = await response.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // non-JSON seller response + } + seller = { status: response.status, body }; + } + + return { + orderId: order.orderId, + serviceId: order.serviceId, + mode: "escrow", + amount: String(order.escrow.amount), + jobId, + transactions: sent, + status: recorded?.status ?? null, + verdict: recorded?.verdict ?? null, + seller, + next: "Call get_order to read the verdict; call refund if the job was not delivered.", + testnet: true, + }; + }); + } + + /** + * Returns an order's status. + * + * @param args - The order id. + * @returns The order as stringified JSON. + */ + @CreateAction({ + name: "get_order", + description: `Returns an AgentCoin order's status, payment transaction, escrow job state, deliverable hash, +verdict and operator-signed delivery record. Escrow orders are refreshed from chain, which can take up to a minute. +Read-only.`, + schema: GetOrderSchema, + }) + async getOrder(args: z.infer): Promise { + return this.run(() => this.api("GET", `/v1/orders/${encodeURIComponent(args.orderId)}`)); + } + + /** + * Seller side: indexes and/or claims a listing. + * + * @param walletProvider - The wallet provider used to sign the claim. + * @param args - The claim arguments. + * @returns The claim result as stringified JSON. + */ + @CreateAction({ + name: "claim_listing", + description: `Seller side. url: indexes a public metadata document (A2A agent card, x402 resource, MCP server card, +ERC-8004 registration). serviceId: returns the claim challenge; sign=true signs the EIP-712 claim with the wallet +(which must be the listing's payTo or ERC-8004 owner); method=well-known checks /.well-known/agentcoin-claim.`, + schema: ClaimListingSchema, + }) + async claimListing( + walletProvider: EvmWalletProvider, + args: z.infer, + ): Promise { + return this.run(async () => { + const claimant = getAddress(walletProvider.getAddress()); + let serviceId = args.serviceId; + let submitted: Json | null = null; + if (!serviceId && args.url) { + submitted = await this.api("POST", "/v1/services", { url: args.url }); + serviceId = submitted?.listing?.id; + } + if (!serviceId) throw new Error("serviceId or url required"); + const id = encodeURIComponent(serviceId); + let claim: Json; + if (args.method === "well-known") { + claim = await this.api("POST", `/v1/services/${id}/claim/verify`, { + method: "well-known", + claimant, + }); + } else if (!args.sign) { + claim = await this.api("POST", `/v1/services/${id}/claim`, { claimant }); + } else { + const listing = await this.api("GET", `/v1/services/${id}`); + const metadataHash = listing.metadataHash; + if (!/^0x[0-9a-fA-F]{64}$/.test(String(metadataHash ?? ""))) { + throw new Error("listing has no metadataHash"); + } + const expiresAt = BigInt(Math.floor(Date.now() / 1000) + 3600); + const signature = await walletProvider.signTypedData({ + domain: { name: "AgentCoin Index", version: "1", chainId: AGENTCOIN_CHAIN_ID }, + types: { + Claim: [ + { name: "serviceId", type: "string" }, + { name: "claimant", type: "address" }, + { name: "metadataHash", type: "bytes32" }, + { name: "expiresAt", type: "uint256" }, + ], + }, + primaryType: "Claim", + message: { serviceId, claimant, metadataHash, expiresAt }, + }); + claim = await this.api("POST", `/v1/services/${id}/claim/verify`, { + claimant, + expiresAt: expiresAt.toString(), + signature, + }); + } + return submitted ? { submitted, claim } : claim; + }); + } + + /** + * Verifies AgentCoin signatures locally. + * + * @param args - The listing and/or order to verify. + * @returns The verification results as stringified JSON. + */ + @CreateAction({ + name: "verify", + description: `Checks AgentCoin signatures locally. serviceId: the EIP-191 signed delivery score and its evidence root. +orderId: the operator-signed delivery record of an order. Returns signer, validity and whether the signer is the +AgentCoin operator. Read-only.`, + schema: VerifySchema, + }) + async verify(args: z.infer): Promise { + return this.run(async () => { + if (!args.serviceId && !args.orderId) throw new Error("serviceId or orderId required"); + const out: Json = {}; + if (args.serviceId) { + const rep = await this.api("GET", `/v1/reputation/${encodeURIComponent(args.serviceId)}`); + const signature = rep.score + ? await verifyAgentCoinSignature(rep.score) + : { valid: false, reason: "no score" }; + const evidenceRootMatches = + Array.isArray(rep.evidence) && rep.score?.evidenceRoot + ? keccak256(toBytes(canonicalJson(rep.evidence))) === rep.score.evidenceRoot + : false; + out.service = { + serviceId: args.serviceId, + score: rep.score ?? null, + signature, + evidenceRootMatches, + }; + } + if (args.orderId) { + const o = await this.api("GET", `/v1/orders/${encodeURIComponent(args.orderId)}`); + out.order = { + orderId: o.orderId, + status: o.status, + verdict: o.verdict, + deliverableHash: o.deliverableHash, + deliveryRecord: o.deliveryRecord + ? await verifyAgentCoinSignature(o.deliveryRecord) + : { valid: false, reason: "no delivery record" }, + }; + } + return out; + }); + } + + /** + * Sends the escrow refund-path call that applies to a job. + * + * @param walletProvider - The wallet provider that sends the call. + * @param args - The order or job id. + * @returns The refund result as stringified JSON. + */ + @CreateAction({ + name: "refund", + description: `Escrow orders: reads the JobEscrow job state and sends the refund-path call that applies +(cancel before the seller accepts, claimRefund after the deadline, timeoutRelease after a missed verdict, +finalize after the challenge window). Simulates first and returns the reason when no call applies. +Inputs: orderId or jobId. Base Sepolia testnet.`, + schema: RefundSchema, + }) + async refund( + walletProvider: EvmWalletProvider, + args: z.infer, + ): Promise { + return this.run(async () => { + let jobId = args.jobId; + if (!jobId && args.orderId) { + jobId = (await this.api("GET", `/v1/orders/${encodeURIComponent(args.orderId)}`)).jobId; + } + if (!jobId) throw new Error("jobId, or orderId of an escrow order, required"); + const job = (await walletProvider.readContract({ + address: AGENTCOIN_ESCROW, + abi: ESCROW_ABI, + functionName: "getJob", + args: [BigInt(jobId)], + })) as Json; + const state = ESCROW_STATES[Number(job.state)]; + const now = BigInt(Math.floor(Date.now() / 1000)); + let fn: "cancel" | "claimRefund" | "timeoutRelease" | "finalize" | null = null; + if (state === "Funded" && !job.accepted) fn = "cancel"; + else if (state === "Funded" && now >= BigInt(job.deadline)) fn = "claimRefund"; + else if (state === "Submitted") fn = "timeoutRelease"; + else if (state === "Rejected" || state === "Partial" || state === "Completed") + fn = "finalize"; + if (!fn) return { jobId, state, sent: false, reason: `no refund action for state ${state}` }; + const me = getAddress(walletProvider.getAddress()); + if (fn === "cancel" && getAddress(job.client) !== me) { + return { jobId, state, sent: false, reason: "cancel is callable by the job client only" }; + } + try { + await walletProvider.getPublicClient().simulateContract({ + account: me, + address: AGENTCOIN_ESCROW, + abi: ESCROW_ABI, + functionName: fn, + args: [BigInt(jobId)], + }); + } catch (e) { + const err = e as { shortMessage?: string; message?: string }; + return { + jobId, + state, + action: fn, + sent: false, + reason: `simulation reverted: ${err.shortMessage ?? err.message}`, + }; + } + const hash = await walletProvider.sendTransaction({ + to: AGENTCOIN_ESCROW, + data: encodeFunctionData({ abi: ESCROW_ABI, functionName: fn, args: [BigInt(jobId)] }), + value: 0n, + }); + const receipt = await walletProvider.waitForTransactionReceipt(hash); + return { jobId, state, action: fn, sent: true, tx: hash, status: receipt?.status ?? null }; + }); + } + + /** + * Checks if the action provider supports the given network. + * + * @param network - The network to check. + * @returns True for Base Sepolia only. + */ + supportsNetwork = (network: Network) => + network.protocolFamily === "evm" && + (AGENTCOIN_SUPPORTED_NETWORKS as readonly string[]).includes(network.networkId ?? ""); + + /** + * Checks the router's unsigned escrow transactions against local constants before signing them. + * + * @param order - The order returned by the router. + * @param me - The buyer address. + * @returns The two transactions to send. + */ + private checkEscrowOrder(order: Json, me: Hex): Json[] { + const e = order?.escrow ?? {}; + const usdc = getAddress(AGENTCOIN_USDC); + const escrow = getAddress(AGENTCOIN_ESCROW); + if (Number(e.chainId) !== AGENTCOIN_CHAIN_ID) + throw new Error(`escrow chainId ${e.chainId} is not 84532`); + if (!e.contract || getAddress(e.contract) !== escrow) + throw new Error(`unexpected escrow contract ${e.contract}`); + if (!e.token || getAddress(e.token) !== usdc) + throw new Error(`unexpected payment token ${e.token}`); + const amount = BigInt(e.amount ?? 0); + if (amount <= 0n) throw new Error("order has no escrow amount"); + if (amount > this.maxPayment) + throw new Error(`amount ${amount} exceeds maxPayment ${this.maxPayment}`); + const txs: Json[] = order.transactions ?? []; + if (txs.length !== 2) throw new Error("expected 2 escrow transactions"); + const [approveTx, fundTx] = txs; + if (getAddress(approveTx.to) !== usdc || BigInt(approveTx.value ?? 0) !== 0n) { + throw new Error("approve transaction target or value mismatch"); + } + const ap = decodeFunctionData({ abi: ERC20_APPROVE_ABI, data: approveTx.data }); + if ( + ap.functionName !== "approve" || + getAddress(ap.args[0]) !== escrow || + ap.args[1] !== amount + ) { + throw new Error("approve must be approve(escrow, amount)"); + } + if (getAddress(fundTx.to) !== escrow || BigInt(fundTx.value ?? 0) !== 0n) { + throw new Error("funding transaction target or value mismatch"); + } + const cf = decodeFunctionData({ abi: ESCROW_ABI, data: fundTx.data }); + if (cf.functionName !== "createAndFundFor") + throw new Error("funding transaction must be createAndFundFor"); + const [client, provider, evaluator, fundAmount] = cf.args as readonly [ + Hex, + Hex, + Hex, + bigint, + bigint, + Hex, + ]; + if (getAddress(client) !== me) throw new Error("createAndFundFor client is not this wallet"); + if ( + getAddress(provider) !== getAddress(e.provider) || + getAddress(evaluator) !== getAddress(e.evaluator) || + fundAmount !== amount + ) { + throw new Error("createAndFundFor arguments do not match the order's escrow terms"); + } + return txs; + } + + /** + * Throws unless the listing is allowed by the provider configuration. + * + * @param serviceId - The listing id. + */ + private assertServiceAllowed(serviceId: string): void { + if (this.allowedServiceIds && !this.allowedServiceIds.has(serviceId)) { + throw new Error(`serviceId ${serviceId} is not in allowedServiceIds`); + } + } + + /** + * Calls the AgentCoin router. + * + * @param method - HTTP method. + * @param path - Request path. + * @param body - Optional JSON body. + * @returns The parsed JSON response. + */ + private async api(method: string, path: string, body?: unknown): Promise { + const response = await fetch(this.baseUrl + path, { + method, + headers: { "content-type": "application/json", accept: "application/json" }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + signal: AbortSignal.timeout(this.requestTimeoutMs), + }); + const json = await response.json().catch(() => null); + if (!response.ok) { + throw new Error(`${method} ${path} returned ${response.status}: ${json?.error ?? "error"}`); + } + return json ?? {}; + } + + /** + * Runs an action body and serializes the result, returning errors as JSON. + * + * @param fn - The action body. + * @returns The result as stringified JSON. + */ + private async run(fn: () => Promise): Promise { + try { + const result = await fn(); + return JSON.stringify(result, (_k, v) => (typeof v === "bigint" ? v.toString() : v)); + } catch (error) { + return JSON.stringify({ + success: false, + error: error instanceof Error ? error.message : String(error), + }); + } + } +} + +/** + * Factory function to create an AgentCoinActionProvider. + * + * @param config - Optional configuration. + * @returns A new AgentCoinActionProvider. + */ +export const agentcoinActionProvider = (config: AgentCoinConfig = {}) => + new AgentCoinActionProvider(config); diff --git a/typescript/agentkit/src/action-providers/agentcoin/constants.ts b/typescript/agentkit/src/action-providers/agentcoin/constants.ts new file mode 100644 index 0000000000..c906fb633b --- /dev/null +++ b/typescript/agentkit/src/action-providers/agentcoin/constants.ts @@ -0,0 +1,168 @@ +/** + * Default AgentCoin router URL (Base Sepolia testnet deployment). + */ +export const AGENTCOIN_DEFAULT_URL = "https://agentcoinhq.com"; + +/** + * Networks supported by the AgentCoin action provider. Testnet only. + */ +export const AGENTCOIN_SUPPORTED_NETWORKS = ["base-sepolia"] as const; + +/** + * Base Sepolia chain id. + */ +export const AGENTCOIN_CHAIN_ID = 84532; + +/** + * CAIP-2 identifier for Base Sepolia. + */ +export const AGENTCOIN_CAIP2 = "eip155:84532"; + +/** + * Circle test USDC on Base Sepolia. + */ +export const AGENTCOIN_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; + +/** + * AgentCoin JobEscrow contract on Base Sepolia. + */ +export const AGENTCOIN_ESCROW = "0x4EaF6d09F8C22980Bb16E719779ACe73A7b1CB3D"; + +/** + * Address of the AgentCoin operator key that signs scores and delivery records (EIP-191). + */ +export const AGENTCOIN_OPERATOR_SIGNER = "0xf1b27b5Bd659D9Bfb4835777E64B8F8e5C3eCf68"; + +/** + * Default per-order payment ceiling in USDC base units (0.05 test USDC). + */ +export const AGENTCOIN_DEFAULT_MAX_PAYMENT = 50_000n; + +/** + * JobEscrow job states, indexed by the on-chain enum value. + */ +export const ESCROW_STATES = [ + "None", + "Open", + "Funded", + "Submitted", + "Completed", + "Rejected", + "Partial", + "Disputed", + "Settled", + "Expired", + "Cancelled", +] as const; + +/** + * Minimal ERC-20 approve ABI. + */ +export const ERC20_APPROVE_ABI = [ + { + type: "function", + name: "approve", + stateMutability: "nonpayable", + inputs: [ + { name: "spender", type: "address" }, + { name: "amount", type: "uint256" }, + ], + outputs: [{ name: "", type: "bool" }], + }, +] as const; + +/** + * Subset of the JobEscrow ABI used by this provider. + */ +export const ESCROW_ABI = [ + { + type: "function", + name: "createAndFundFor", + stateMutability: "nonpayable", + inputs: [ + { name: "client", type: "address" }, + { name: "provider", type: "address" }, + { name: "evaluator", type: "address" }, + { name: "amount", type: "uint256" }, + { name: "deadline", type: "uint64" }, + { name: "specHash", type: "bytes32" }, + ], + outputs: [{ name: "jobId", type: "uint256" }], + }, + { + type: "function", + name: "claimRefund", + stateMutability: "nonpayable", + inputs: [{ name: "jobId", type: "uint256" }], + outputs: [], + }, + { + type: "function", + name: "cancel", + stateMutability: "nonpayable", + inputs: [{ name: "jobId", type: "uint256" }], + outputs: [], + }, + { + type: "function", + name: "timeoutRelease", + stateMutability: "nonpayable", + inputs: [{ name: "jobId", type: "uint256" }], + outputs: [], + }, + { + type: "function", + name: "finalize", + stateMutability: "nonpayable", + inputs: [{ name: "jobId", type: "uint256" }], + outputs: [], + }, + { + type: "function", + name: "getJob", + stateMutability: "view", + inputs: [{ name: "jobId", type: "uint256" }], + outputs: [ + { + name: "", + type: "tuple", + components: [ + { name: "client", type: "address" }, + { name: "provider", type: "address" }, + { name: "evaluator", type: "address" }, + { name: "configVersion", type: "uint32" }, + { name: "state", type: "uint8" }, + { name: "outcome", type: "uint8" }, + { name: "accepted", type: "bool" }, + { name: "instant", type: "bool" }, + { name: "payoutBps", type: "uint16" }, + { name: "deadline", type: "uint64" }, + { name: "submittedAt", type: "uint64" }, + { name: "verdictAt", type: "uint64" }, + { name: "disputedAt", type: "uint64" }, + { name: "amount", type: "uint256" }, + { name: "providerBond", type: "uint256" }, + { name: "slashBase", type: "uint256" }, + { name: "specHash", type: "bytes32" }, + { name: "deliverableHash", type: "bytes32" }, + { name: "reasonHash", type: "bytes32" }, + ], + }, + ], + }, + { + type: "event", + name: "JobCreated", + anonymous: false, + inputs: [ + { name: "jobId", type: "uint256", indexed: true }, + { name: "client", type: "address", indexed: true }, + { name: "provider", type: "address", indexed: true }, + { name: "evaluator", type: "address", indexed: false }, + { name: "amount", type: "uint256", indexed: false }, + { name: "deadline", type: "uint64", indexed: false }, + { name: "specHash", type: "bytes32", indexed: false }, + { name: "configVersion", type: "uint32", indexed: false }, + ], + }, +] as const; diff --git a/typescript/agentkit/src/action-providers/agentcoin/index.ts b/typescript/agentkit/src/action-providers/agentcoin/index.ts new file mode 100644 index 0000000000..a7a38ddbe2 --- /dev/null +++ b/typescript/agentkit/src/action-providers/agentcoin/index.ts @@ -0,0 +1,2 @@ +export * from "./agentcoinActionProvider"; +export * from "./schemas"; diff --git a/typescript/agentkit/src/action-providers/agentcoin/schemas.ts b/typescript/agentkit/src/action-providers/agentcoin/schemas.ts new file mode 100644 index 0000000000..c362e37cc0 --- /dev/null +++ b/typescript/agentkit/src/action-providers/agentcoin/schemas.ts @@ -0,0 +1,125 @@ +import { z } from "zod"; + +const usdcAmount = z + .string() + .regex(/^[0-9]{1,18}$/, "USDC base units (6 decimals) as a decimal string") + .describe("Amount in USDC base units (6 decimals) as a decimal string, e.g. 10000 = 0.01 USDC"); + +const protocol = z + .enum(["x402", "a2a", "mcp", "openapi", "erc8004"]) + .describe("Protocol the service speaks"); + +const serviceId = z.string().max(40).describe("AgentCoin listing id, e.g. svc_962928f654d2a8a1"); + +const orderId = z.string().max(40).describe("AgentCoin order id, e.g. ord_f06171f16b1402f1"); + +/** + * Input schema for find_service. + */ +export const FindServiceSchema = z + .object({ + id: serviceId.optional().describe("Listing id; when set, returns that one listing"), + q: z.string().max(300).optional().describe("Free-text search query"), + protocol: protocol.optional(), + maxPrice: usdcAmount.optional().describe("Maximum price in USDC base units"), + minScore: z.number().min(0).max(1).optional().describe("Minimum delivered-after-pay rate"), + claimed: z.boolean().optional().describe("Only listings claimed by their operator"), + cursor: z.string().max(200).optional().describe("Pagination cursor from a previous call"), + limit: z.number().int().min(1).max(50).optional().describe("Page size (1-50)"), + }) + .strict() + .describe("Search the AgentCoin service index, or fetch one listing by id"); + +/** + * Input schema for route_task. + */ +export const RouteTaskSchema = z + .object({ + task: z.string().min(2).max(2000).describe("Plain-language description of the task"), + budget: usdcAmount.optional().describe("Budget in USDC base units"), + protocol: protocol.optional(), + claimed: z.boolean().optional().describe("Only listings claimed by their operator"), + minScore: z.number().min(0).max(1).optional().describe("Minimum delivered-after-pay rate"), + limit: z.number().int().min(1).max(20).optional().describe("Maximum number of candidates"), + }) + .strict() + .describe("Rank candidate sellers for a task and budget"); + +/** + * Input schema for place_order. + */ +export const PlaceOrderSchema = z + .object({ + serviceId, + skillId: z + .string() + .max(300) + .optional() + .describe("Skill id from the listing, if it has several"), + body: z + .record(z.string(), z.unknown()) + .optional() + .describe("JSON request body sent to the seller (see the listing's request template)"), + }) + .strict() + .describe("Place an escrowed order for a listing and fund it from the wallet"); + +/** + * Input schema for get_order. + */ +export const GetOrderSchema = z + .object({ + orderId, + }) + .strict() + .describe("Get an order's status, escrow job state and verdict"); + +/** + * Input schema for claim_listing. + */ +export const ClaimListingSchema = z + .object({ + serviceId: serviceId.optional().describe("Listing id to claim"), + url: z + .string() + .url() + .max(2000) + .optional() + .describe("Public metadata URL to index (A2A card, x402 resource, MCP server card)"), + sign: z + .boolean() + .optional() + .describe("Sign the EIP-712 claim with the wallet (must be the listing's payTo or owner)"), + method: z + .enum(["eip712", "well-known"]) + .optional() + .describe("Claim method; well-known checks /.well-known/agentcoin-claim on the seller host"), + }) + .strict() + .describe("Seller side: index a listing and/or claim it"); + +/** + * Input schema for verify. + */ +export const VerifySchema = z + .object({ + serviceId: serviceId.optional().describe("Check the signed delivery score of a listing"), + orderId: orderId.optional().describe("Check the signed delivery record of an order"), + }) + .strict() + .describe("Verify AgentCoin signatures locally"); + +/** + * Input schema for refund. + */ +export const RefundSchema = z + .object({ + orderId: orderId.optional().describe("Escrow order id"), + jobId: z + .string() + .regex(/^[0-9]{1,30}$/) + .optional() + .describe("JobEscrow job id (decimal string)"), + }) + .strict() + .describe("Send the escrow refund-path call that applies to the job, if any"); diff --git a/typescript/agentkit/src/action-providers/index.ts b/typescript/agentkit/src/action-providers/index.ts index 9f71640866..7e5debbc1b 100644 --- a/typescript/agentkit/src/action-providers/index.ts +++ b/typescript/agentkit/src/action-providers/index.ts @@ -4,6 +4,7 @@ export * from "./actionProvider"; export * from "./customActionProvider"; export * from "./across"; +export * from "./agentcoin"; export * from "./alchemy"; export * from "./baseAccount"; export * from "./basename"; From d1ab61a7b35377c79398eab5caf692acd5de791a Mon Sep 17 00:00:00 2001 From: kemppelinvestments-del Date: Wed, 18 Nov 2026 22:19:55 -0500 Subject: [PATCH 2/2] refactor: rename AgentCoin to AgentKoin Renames the action provider, its directory, files, identifiers, README and changeset from AgentCoin to AgentKoin. The hosted service domain and wire-level identifiers keep their current names. --- ...in-escrow.md => brave-agentkoin-escrow.md} | 2 +- typescript/agentkit/README.md | 6 +- .../src/action-providers/agentcoin/index.ts | 2 - .../{agentcoin => agentkoin}/README.md | 26 ++--- .../agentkoinActionProvider.test.ts} | 40 ++++---- .../agentkoinActionProvider.ts} | 94 +++++++++---------- .../{agentcoin => agentkoin}/constants.ts | 24 ++--- .../src/action-providers/agentkoin/index.ts | 2 + .../{agentcoin => agentkoin}/schemas.ts | 8 +- .../agentkit/src/action-providers/index.ts | 2 +- 10 files changed, 104 insertions(+), 102 deletions(-) rename typescript/.changeset/{brave-agentcoin-escrow.md => brave-agentkoin-escrow.md} (55%) delete mode 100644 typescript/agentkit/src/action-providers/agentcoin/index.ts rename typescript/agentkit/src/action-providers/{agentcoin => agentkoin}/README.md (74%) rename typescript/agentkit/src/action-providers/{agentcoin/agentcoinActionProvider.test.ts => agentkoin/agentkoinActionProvider.test.ts} (94%) rename typescript/agentkit/src/action-providers/{agentcoin/agentcoinActionProvider.ts => agentkoin/agentkoinActionProvider.ts} (90%) rename typescript/agentkit/src/action-providers/{agentcoin => agentkoin}/constants.ts (84%) create mode 100644 typescript/agentkit/src/action-providers/agentkoin/index.ts rename typescript/agentkit/src/action-providers/{agentcoin => agentkoin}/schemas.ts (94%) diff --git a/typescript/.changeset/brave-agentcoin-escrow.md b/typescript/.changeset/brave-agentkoin-escrow.md similarity index 55% rename from typescript/.changeset/brave-agentcoin-escrow.md rename to typescript/.changeset/brave-agentkoin-escrow.md index 6217546fe8..24a079196f 100644 --- a/typescript/.changeset/brave-agentcoin-escrow.md +++ b/typescript/.changeset/brave-agentkoin-escrow.md @@ -2,4 +2,4 @@ "@coinbase/agentkit": patch --- -Added AgentCoin action provider for escrowed agent-to-agent orders with delivery verdicts on Base Sepolia +Added AgentKoin action provider for escrowed agent-to-agent orders with delivery verdicts on Base Sepolia diff --git a/typescript/agentkit/README.md b/typescript/agentkit/README.md index a2ccf7e7ce..aa05535042 100644 --- a/typescript/agentkit/README.md +++ b/typescript/agentkit/README.md @@ -178,11 +178,11 @@ const agent = createAgent({
-AgentCoin +AgentKoin - + @@ -202,7 +202,7 @@ const agent = createAgent({ - + diff --git a/typescript/agentkit/src/action-providers/agentcoin/index.ts b/typescript/agentkit/src/action-providers/agentcoin/index.ts deleted file mode 100644 index a7a38ddbe2..0000000000 --- a/typescript/agentkit/src/action-providers/agentcoin/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./agentcoinActionProvider"; -export * from "./schemas"; diff --git a/typescript/agentkit/src/action-providers/agentcoin/README.md b/typescript/agentkit/src/action-providers/agentkoin/README.md similarity index 74% rename from typescript/agentkit/src/action-providers/agentcoin/README.md rename to typescript/agentkit/src/action-providers/agentkoin/README.md index 922f7fdb7c..c999526285 100644 --- a/typescript/agentkit/src/action-providers/agentcoin/README.md +++ b/typescript/agentkit/src/action-providers/agentkoin/README.md @@ -1,15 +1,17 @@ -# AgentCoin Action Provider +# AgentKoin Action Provider -This directory contains the **AgentCoinActionProvider** implementation, which lets an agent find paid agent services, pay them through an escrow that releases funds only on a staked evaluator's delivery verdict, and claim refunds. +> AgentKoin was formerly named AgentCoin. The hosted service domain and some wire-level identifiers (`agentcoinhq.com`, `/.well-known/agentcoin-claim`) keep the old name for now. -> **Testnet only.** The provider supports **Base Sepolia** (`eip155:84532`) and test USDC (`0x036CbD53842c5426634e7929541eC2318f3dCF7e`). The hosted router at https://agentcoinhq.com is an early testnet deployment; payments have no real value. Source for the AgentCoin client libraries: https://github.com/stos-technologies/agentcoin +This directory contains the **AgentKoinActionProvider** implementation, which lets an agent find paid agent services, pay them through an escrow that releases funds only on a staked evaluator's delivery verdict, and claim refunds. + +> **Testnet only.** The provider supports **Base Sepolia** (`eip155:84532`) and test USDC (`0x036CbD53842c5426634e7929541eC2318f3dCF7e`). The hosted router at https://agentcoinhq.com is an early testnet deployment; payments have no real value. Source for the AgentKoin client libraries: https://github.com/stos-technologies/agentcoin ## Directory Structure ``` -agentcoin/ -├── agentcoinActionProvider.ts # Main provider -├── agentcoinActionProvider.test.ts # Unit tests +agentkoin/ +├── agentkoinActionProvider.ts # Main provider +├── agentkoinActionProvider.test.ts # Unit tests ├── constants.ts # Router URL, contract addresses and ABIs ├── schemas.ts # Action schemas ├── index.ts # Main exports @@ -18,7 +20,7 @@ agentcoin/ ## Actions -- `find_service`: Search the AgentCoin index of paid agent services (A2A, MCP, x402, ERC-8004), or fetch one listing by id +- `find_service`: Search the AgentKoin index of paid agent services (A2A, MCP, x402, ERC-8004), or fetch one listing by id - `route_task`: Rank candidate sellers for a task and budget (quote, request template, delivery score). No payment - `place_order`: Place an escrowed order and fund it from the wallet @@ -28,16 +30,16 @@ agentcoin/ - `get_order`: Read an order's status, escrow job state, deliverable hash, verdict and signed delivery record - `claim_listing`: Seller side. Index a metadata URL and/or claim a listing with an EIP-712 signature or a `/.well-known/agentcoin-claim` file -- `verify`: Check AgentCoin EIP-191 signatures locally (delivery scores and delivery records, RFC 8785 canonical JSON) +- `verify`: Check AgentKoin EIP-191 signatures locally (delivery scores and delivery records, RFC 8785 canonical JSON) - `refund`: Send the JobEscrow refund-path call that applies to the job (`cancel`, `claimRefund`, `timeoutRelease` or `finalize`), after a simulation ## Configuration ```typescript -import { agentcoinActionProvider } from "@coinbase/agentkit"; +import { agentkoinActionProvider } from "@coinbase/agentkit"; -const provider = agentcoinActionProvider({ - baseUrl: "https://agentcoinhq.com", // optional, or set AGENTCOIN_URL +const provider = agentkoinActionProvider({ + baseUrl: "https://agentcoinhq.com", // optional, or set AGENTKOIN_URL maxPayment: 50000n, // optional, USDC base units per order allowedServiceIds: ["svc_962928f654d2a8a1"], // optional allowlist for place_order }); @@ -52,5 +54,5 @@ Base Sepolia only (`base-sepolia`). ## Notes - Escrow flow: funds sit in JobEscrow until a staked evaluator rules. A "delivered" verdict pays the seller; "not delivered", or no verdict before the deadline, refunds the buyer. A challenged verdict that is overturned slashes the evaluator's stake. -- Delivery scores exclude orders placed by the AgentCoin operator itself. +- Delivery scores exclude orders placed by the AgentKoin operator itself. - For direct (non-escrow) x402 payments, use the `x402` action provider. diff --git a/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.test.ts b/typescript/agentkit/src/action-providers/agentkoin/agentkoinActionProvider.test.ts similarity index 94% rename from typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.test.ts rename to typescript/agentkit/src/action-providers/agentkoin/agentkoinActionProvider.test.ts index b6f7d5b7af..4080086cc6 100644 --- a/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.test.ts +++ b/typescript/agentkit/src/action-providers/agentkoin/agentkoinActionProvider.test.ts @@ -8,11 +8,11 @@ import { import { privateKeyToAccount } from "viem/accounts"; import { EvmWalletProvider } from "../../wallet-providers"; import { - agentcoinActionProvider, - AgentCoinActionProvider, + agentkoinActionProvider, + AgentKoinActionProvider, canonicalJson, - verifyAgentCoinSignature, -} from "./agentcoinActionProvider"; + verifyAgentKoinSignature, +} from "./agentkoinActionProvider"; import { FindServiceSchema, PlaceOrderSchema, @@ -20,7 +20,7 @@ import { RouteTaskSchema, VerifySchema, } from "./schemas"; -import { AGENTCOIN_ESCROW, AGENTCOIN_USDC, ERC20_APPROVE_ABI, ESCROW_ABI } from "./constants"; +import { AGENTKOIN_ESCROW, AGENTKOIN_USDC, ERC20_APPROVE_ABI, ESCROW_ABI } from "./constants"; const BUYER = "0x78e2C0164A80F3e337AE17e3bA4b8EA2C0Fa488e"; const PROVIDER = "0x6A32bC3Bb5eA1dc814f14E29e6f026535129A84f"; @@ -43,8 +43,8 @@ const escrowOrder = (overrides: Record = {}) => ({ mode: "escrow", escrow: { chainId: 84532, - contract: AGENTCOIN_ESCROW, - token: AGENTCOIN_USDC, + contract: AGENTKOIN_ESCROW, + token: AGENTKOIN_USDC, amount: "10000", provider: PROVIDER, evaluator: EVALUATOR, @@ -53,18 +53,18 @@ const escrowOrder = (overrides: Record = {}) => ({ { label: "approve", chainId: 84532, - to: AGENTCOIN_USDC, + to: AGENTKOIN_USDC, value: "0", data: encodeFunctionData({ abi: ERC20_APPROVE_ABI, functionName: "approve", - args: [AGENTCOIN_ESCROW, 10000n], + args: [AGENTKOIN_ESCROW, 10000n], }), }, { label: "createAndFundFor", chainId: 84532, - to: AGENTCOIN_ESCROW, + to: AGENTKOIN_ESCROW, value: "0", data: encodeFunctionData({ abi: ESCROW_ABI, @@ -78,7 +78,7 @@ const escrowOrder = (overrides: Record = {}) => ({ }); const jobCreatedLog = () => ({ - address: AGENTCOIN_ESCROW, + address: AGENTKOIN_ESCROW, topics: encodeEventTopics({ abi: ESCROW_ABI, eventName: "JobCreated", @@ -96,7 +96,7 @@ const jobCreatedLog = () => ({ ), }); -describe("AgentCoin schemas", () => { +describe("AgentKoin schemas", () => { it("accepts a valid search", () => { expect(FindServiceSchema.safeParse({ q: "notary", maxPrice: "10000" }).success).toBe(true); }); @@ -130,7 +130,7 @@ describe("canonicalJson", () => { }); }); -describe("verifyAgentCoinSignature", () => { +describe("verifyAgentKoinSignature", () => { const account = privateKeyToAccount(`0x${"11".repeat(32)}`); const sign = async (doc: Record) => { @@ -143,7 +143,7 @@ describe("verifyAgentCoinSignature", () => { }; it("accepts a valid signature", async () => { - const result = await verifyAgentCoinSignature(await sign({ v: "x", n: 1 })); + const result = await verifyAgentKoinSignature(await sign({ v: "x", n: 1 })); expect(result.valid).toBe(true); expect(result.signer).toBe(account.address); expect(result.signerIsOperator).toBe(false); @@ -151,22 +151,22 @@ describe("verifyAgentCoinSignature", () => { it("rejects a modified document", async () => { const doc = await sign({ v: "x", n: 1 }); - const result = await verifyAgentCoinSignature({ ...doc, n: 2 }); + const result = await verifyAgentKoinSignature({ ...doc, n: 2 }); expect(result.valid).toBe(false); }); it("reports a missing signature", async () => { - expect((await verifyAgentCoinSignature({ v: "x" })).valid).toBe(false); + expect((await verifyAgentKoinSignature({ v: "x" })).valid).toBe(false); }); }); -describe("AgentCoinActionProvider", () => { - let provider: AgentCoinActionProvider; +describe("AgentKoinActionProvider", () => { + let provider: AgentKoinActionProvider; let wallet: jest.Mocked; let fetchMock: jest.SpyInstance; beforeEach(() => { - provider = agentcoinActionProvider({ baseUrl: "https://router.example/" }); + provider = agentkoinActionProvider({ baseUrl: "https://router.example/" }); wallet = { getAddress: jest.fn().mockReturnValue(BUYER), getNetwork: jest @@ -322,7 +322,7 @@ describe("AgentCoinActionProvider", () => { }); it("respects allowedServiceIds", async () => { - const limited = agentcoinActionProvider({ allowedServiceIds: ["svc_a"] }); + const limited = agentkoinActionProvider({ allowedServiceIds: ["svc_a"] }); const out = JSON.parse(await limited.placeOrder(wallet, { serviceId: "svc_b" })); expect(out.success).toBe(false); expect(fetchMock).not.toHaveBeenCalled(); diff --git a/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.ts b/typescript/agentkit/src/action-providers/agentkoin/agentkoinActionProvider.ts similarity index 90% rename from typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.ts rename to typescript/agentkit/src/action-providers/agentkoin/agentkoinActionProvider.ts index 2da67e8185..623ea6bee5 100644 --- a/typescript/agentkit/src/action-providers/agentcoin/agentcoinActionProvider.ts +++ b/typescript/agentkit/src/action-providers/agentkoin/agentkoinActionProvider.ts @@ -23,14 +23,14 @@ import { RefundSchema, } from "./schemas"; import { - AGENTCOIN_CAIP2, - AGENTCOIN_CHAIN_ID, - AGENTCOIN_DEFAULT_MAX_PAYMENT, - AGENTCOIN_DEFAULT_URL, - AGENTCOIN_ESCROW, - AGENTCOIN_OPERATOR_SIGNER, - AGENTCOIN_SUPPORTED_NETWORKS, - AGENTCOIN_USDC, + AGENTKOIN_CAIP2, + AGENTKOIN_CHAIN_ID, + AGENTKOIN_DEFAULT_MAX_PAYMENT, + AGENTKOIN_DEFAULT_URL, + AGENTKOIN_ESCROW, + AGENTKOIN_OPERATOR_SIGNER, + AGENTKOIN_SUPPORTED_NETWORKS, + AGENTKOIN_USDC, ERC20_APPROVE_ABI, ESCROW_ABI, ESCROW_STATES, @@ -40,10 +40,10 @@ import { type Json = Record; /** - * Configuration for the AgentCoin action provider. + * Configuration for the AgentKoin action provider. */ -export interface AgentCoinConfig { - /** Router base URL. Defaults to AGENTCOIN_URL or https://agentcoinhq.com. */ +export interface AgentKoinConfig { + /** Router base URL. Defaults to AGENTKOIN_URL or https://agentcoinhq.com. */ baseUrl?: string; /** Per-order payment ceiling in USDC base units. Defaults to 50000 (0.05 test USDC). */ maxPayment?: bigint | string | number; @@ -77,12 +77,12 @@ export function canonicalJson(value: unknown): string { } /** - * Checks an AgentCoin EIP-191 document signature: personal_sign over keccak256(RFC 8785(document without "signature")). + * Checks an AgentKoin EIP-191 document signature: personal_sign over keccak256(RFC 8785(document without "signature")). * * @param doc - The signed document. - * @returns Whether the signature is valid, the recovered signer and whether it is the AgentCoin operator. + * @returns Whether the signature is valid, the recovered signer and whether it is the AgentKoin operator. */ -export async function verifyAgentCoinSignature(doc: Json | null | undefined): Promise { +export async function verifyAgentKoinSignature(doc: Json | null | undefined): Promise { const sig = doc?.signature; if (!sig || sig.scheme !== "eip191") return { valid: false, reason: "no eip191 signature" }; // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -100,46 +100,46 @@ export async function verifyAgentCoinSignature(doc: Json | null | undefined): Pr return { valid, signer, - signerIsOperator: signer === getAddress(AGENTCOIN_OPERATOR_SIGNER), + signerIsOperator: signer === getAddress(AGENTKOIN_OPERATOR_SIGNER), digest, }; } /** - * AgentCoinActionProvider lets an agent find paid agent services, pay them through an escrow that + * AgentKoinActionProvider lets an agent find paid agent services, pay them through an escrow that * releases funds only on a staked evaluator's delivery verdict, and claim refunds. Base Sepolia testnet only. */ -export class AgentCoinActionProvider extends ActionProvider { +export class AgentKoinActionProvider extends ActionProvider { private readonly baseUrl: string; private readonly maxPayment: bigint; private readonly allowedServiceIds: Set | null; private readonly requestTimeoutMs: number; /** - * Constructs a new AgentCoinActionProvider. + * Constructs a new AgentKoinActionProvider. * * @param config - Optional configuration. */ - constructor(config: AgentCoinConfig = {}) { - super("agentcoin", []); - this.baseUrl = (config.baseUrl ?? process.env.AGENTCOIN_URL ?? AGENTCOIN_DEFAULT_URL).replace( + constructor(config: AgentKoinConfig = {}) { + super("agentkoin", []); + this.baseUrl = (config.baseUrl ?? process.env.AGENTKOIN_URL ?? AGENTKOIN_DEFAULT_URL).replace( /\/+$/, "", ); - this.maxPayment = BigInt(config.maxPayment ?? AGENTCOIN_DEFAULT_MAX_PAYMENT); + this.maxPayment = BigInt(config.maxPayment ?? AGENTKOIN_DEFAULT_MAX_PAYMENT); this.allowedServiceIds = config.allowedServiceIds ? new Set(config.allowedServiceIds) : null; this.requestTimeoutMs = config.requestTimeoutMs ?? 90_000; } /** - * Searches the AgentCoin service index. + * Searches the AgentKoin service index. * * @param args - The search arguments. * @returns The search results as stringified JSON. */ @CreateAction({ name: "find_service", - description: `Searches the AgentCoin index of paid agent services (A2A, MCP, x402, ERC-8004). + description: `Searches the AgentKoin index of paid agent services (A2A, MCP, x402, ERC-8004). With id: returns one listing with skills, prices, request formats and delivery score. Inputs: id, q (text), protocol, maxPrice (USDC base units), minScore (0-1), claimed, cursor, limit. Read-only. Base Sepolia testnet.`, @@ -175,7 +175,7 @@ delivery score and supported order modes. No payment. Read-only. Base Sepolia te return this.api("POST", "/v1/route", { task, ...(budget ? { budget } : {}), - constraints: { network: AGENTCOIN_CAIP2, ...constraints }, + constraints: { network: AGENTKOIN_CAIP2, ...constraints }, }); }); } @@ -189,7 +189,7 @@ delivery score and supported order modes. No payment. Read-only. Base Sepolia te */ @CreateAction({ name: "place_order", - description: `Places an escrowed order for an AgentCoin listing and funds it from the wallet. + description: `Places an escrowed order for an AgentKoin listing and funds it from the wallet. Test USDC is held in the JobEscrow contract until a staked evaluator rules on delivery: paid to the seller if delivered, refunded to the buyer if not (or if no verdict arrives in time). Sends 2 transactions (USDC approve, createAndFundFor), records the job with the router and calls the seller. @@ -228,7 +228,7 @@ Inputs: serviceId, optional skillId, optional body (JSON sent to the seller). Ba abi: ESCROW_ABI, logs: receipt.logs ?? [], eventName: "JobCreated", - }).find(l => getAddress(l.address) === getAddress(AGENTCOIN_ESCROW)); + }).find(l => getAddress(l.address) === getAddress(AGENTKOIN_ESCROW)); if (created) jobId = created.args.jobId.toString(); } if (!jobId) throw new Error("no JobCreated event in the funding transaction"); @@ -248,7 +248,7 @@ Inputs: serviceId, optional skillId, optional body (JSON sent to the seller). Ba const header = Buffer.from( JSON.stringify({ x402Version: 2, - accepted: { scheme: "agentcoin-escrow", network: AGENTCOIN_CAIP2 }, + accepted: { scheme: "agentcoin-escrow", network: AGENTKOIN_CAIP2 }, payload: { jobId, txHash: fundTx }, }), ).toString("base64"); @@ -292,7 +292,7 @@ Inputs: serviceId, optional skillId, optional body (JSON sent to the seller). Ba */ @CreateAction({ name: "get_order", - description: `Returns an AgentCoin order's status, payment transaction, escrow job state, deliverable hash, + description: `Returns an AgentKoin order's status, payment transaction, escrow job state, deliverable hash, verdict and operator-signed delivery record. Escrow orders are refreshed from chain, which can take up to a minute. Read-only.`, schema: GetOrderSchema, @@ -345,7 +345,7 @@ ERC-8004 registration). serviceId: returns the claim challenge; sign=true signs } const expiresAt = BigInt(Math.floor(Date.now() / 1000) + 3600); const signature = await walletProvider.signTypedData({ - domain: { name: "AgentCoin Index", version: "1", chainId: AGENTCOIN_CHAIN_ID }, + domain: { name: "AgentKoin Index", version: "1", chainId: AGENTKOIN_CHAIN_ID }, types: { Claim: [ { name: "serviceId", type: "string" }, @@ -368,16 +368,16 @@ ERC-8004 registration). serviceId: returns the claim challenge; sign=true signs } /** - * Verifies AgentCoin signatures locally. + * Verifies AgentKoin signatures locally. * * @param args - The listing and/or order to verify. * @returns The verification results as stringified JSON. */ @CreateAction({ name: "verify", - description: `Checks AgentCoin signatures locally. serviceId: the EIP-191 signed delivery score and its evidence root. + description: `Checks AgentKoin signatures locally. serviceId: the EIP-191 signed delivery score and its evidence root. orderId: the operator-signed delivery record of an order. Returns signer, validity and whether the signer is the -AgentCoin operator. Read-only.`, +AgentKoin operator. Read-only.`, schema: VerifySchema, }) async verify(args: z.infer): Promise { @@ -387,7 +387,7 @@ AgentCoin operator. Read-only.`, if (args.serviceId) { const rep = await this.api("GET", `/v1/reputation/${encodeURIComponent(args.serviceId)}`); const signature = rep.score - ? await verifyAgentCoinSignature(rep.score) + ? await verifyAgentKoinSignature(rep.score) : { valid: false, reason: "no score" }; const evidenceRootMatches = Array.isArray(rep.evidence) && rep.score?.evidenceRoot @@ -408,7 +408,7 @@ AgentCoin operator. Read-only.`, verdict: o.verdict, deliverableHash: o.deliverableHash, deliveryRecord: o.deliveryRecord - ? await verifyAgentCoinSignature(o.deliveryRecord) + ? await verifyAgentKoinSignature(o.deliveryRecord) : { valid: false, reason: "no delivery record" }, }; } @@ -442,7 +442,7 @@ Inputs: orderId or jobId. Base Sepolia testnet.`, } if (!jobId) throw new Error("jobId, or orderId of an escrow order, required"); const job = (await walletProvider.readContract({ - address: AGENTCOIN_ESCROW, + address: AGENTKOIN_ESCROW, abi: ESCROW_ABI, functionName: "getJob", args: [BigInt(jobId)], @@ -463,7 +463,7 @@ Inputs: orderId or jobId. Base Sepolia testnet.`, try { await walletProvider.getPublicClient().simulateContract({ account: me, - address: AGENTCOIN_ESCROW, + address: AGENTKOIN_ESCROW, abi: ESCROW_ABI, functionName: fn, args: [BigInt(jobId)], @@ -479,7 +479,7 @@ Inputs: orderId or jobId. Base Sepolia testnet.`, }; } const hash = await walletProvider.sendTransaction({ - to: AGENTCOIN_ESCROW, + to: AGENTKOIN_ESCROW, data: encodeFunctionData({ abi: ESCROW_ABI, functionName: fn, args: [BigInt(jobId)] }), value: 0n, }); @@ -496,7 +496,7 @@ Inputs: orderId or jobId. Base Sepolia testnet.`, */ supportsNetwork = (network: Network) => network.protocolFamily === "evm" && - (AGENTCOIN_SUPPORTED_NETWORKS as readonly string[]).includes(network.networkId ?? ""); + (AGENTKOIN_SUPPORTED_NETWORKS as readonly string[]).includes(network.networkId ?? ""); /** * Checks the router's unsigned escrow transactions against local constants before signing them. @@ -507,9 +507,9 @@ Inputs: orderId or jobId. Base Sepolia testnet.`, */ private checkEscrowOrder(order: Json, me: Hex): Json[] { const e = order?.escrow ?? {}; - const usdc = getAddress(AGENTCOIN_USDC); - const escrow = getAddress(AGENTCOIN_ESCROW); - if (Number(e.chainId) !== AGENTCOIN_CHAIN_ID) + const usdc = getAddress(AGENTKOIN_USDC); + const escrow = getAddress(AGENTKOIN_ESCROW); + if (Number(e.chainId) !== AGENTKOIN_CHAIN_ID) throw new Error(`escrow chainId ${e.chainId} is not 84532`); if (!e.contract || getAddress(e.contract) !== escrow) throw new Error(`unexpected escrow contract ${e.contract}`); @@ -570,7 +570,7 @@ Inputs: orderId or jobId. Base Sepolia testnet.`, } /** - * Calls the AgentCoin router. + * Calls the AgentKoin router. * * @param method - HTTP method. * @param path - Request path. @@ -611,10 +611,10 @@ Inputs: orderId or jobId. Base Sepolia testnet.`, } /** - * Factory function to create an AgentCoinActionProvider. + * Factory function to create an AgentKoinActionProvider. * * @param config - Optional configuration. - * @returns A new AgentCoinActionProvider. + * @returns A new AgentKoinActionProvider. */ -export const agentcoinActionProvider = (config: AgentCoinConfig = {}) => - new AgentCoinActionProvider(config); +export const agentkoinActionProvider = (config: AgentKoinConfig = {}) => + new AgentKoinActionProvider(config); diff --git a/typescript/agentkit/src/action-providers/agentcoin/constants.ts b/typescript/agentkit/src/action-providers/agentkoin/constants.ts similarity index 84% rename from typescript/agentkit/src/action-providers/agentcoin/constants.ts rename to typescript/agentkit/src/action-providers/agentkoin/constants.ts index c906fb633b..86244ac45c 100644 --- a/typescript/agentkit/src/action-providers/agentcoin/constants.ts +++ b/typescript/agentkit/src/action-providers/agentkoin/constants.ts @@ -1,42 +1,42 @@ /** - * Default AgentCoin router URL (Base Sepolia testnet deployment). + * Default AgentKoin router URL (Base Sepolia testnet deployment). */ -export const AGENTCOIN_DEFAULT_URL = "https://agentcoinhq.com"; +export const AGENTKOIN_DEFAULT_URL = "https://agentcoinhq.com"; /** - * Networks supported by the AgentCoin action provider. Testnet only. + * Networks supported by the AgentKoin action provider. Testnet only. */ -export const AGENTCOIN_SUPPORTED_NETWORKS = ["base-sepolia"] as const; +export const AGENTKOIN_SUPPORTED_NETWORKS = ["base-sepolia"] as const; /** * Base Sepolia chain id. */ -export const AGENTCOIN_CHAIN_ID = 84532; +export const AGENTKOIN_CHAIN_ID = 84532; /** * CAIP-2 identifier for Base Sepolia. */ -export const AGENTCOIN_CAIP2 = "eip155:84532"; +export const AGENTKOIN_CAIP2 = "eip155:84532"; /** * Circle test USDC on Base Sepolia. */ -export const AGENTCOIN_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; +export const AGENTKOIN_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; /** - * AgentCoin JobEscrow contract on Base Sepolia. + * AgentKoin JobEscrow contract on Base Sepolia. */ -export const AGENTCOIN_ESCROW = "0x4EaF6d09F8C22980Bb16E719779ACe73A7b1CB3D"; +export const AGENTKOIN_ESCROW = "0x4EaF6d09F8C22980Bb16E719779ACe73A7b1CB3D"; /** - * Address of the AgentCoin operator key that signs scores and delivery records (EIP-191). + * Address of the AgentKoin operator key that signs scores and delivery records (EIP-191). */ -export const AGENTCOIN_OPERATOR_SIGNER = "0xf1b27b5Bd659D9Bfb4835777E64B8F8e5C3eCf68"; +export const AGENTKOIN_OPERATOR_SIGNER = "0xf1b27b5Bd659D9Bfb4835777E64B8F8e5C3eCf68"; /** * Default per-order payment ceiling in USDC base units (0.05 test USDC). */ -export const AGENTCOIN_DEFAULT_MAX_PAYMENT = 50_000n; +export const AGENTKOIN_DEFAULT_MAX_PAYMENT = 50_000n; /** * JobEscrow job states, indexed by the on-chain enum value. diff --git a/typescript/agentkit/src/action-providers/agentkoin/index.ts b/typescript/agentkit/src/action-providers/agentkoin/index.ts new file mode 100644 index 0000000000..be01d3b2b8 --- /dev/null +++ b/typescript/agentkit/src/action-providers/agentkoin/index.ts @@ -0,0 +1,2 @@ +export * from "./agentkoinActionProvider"; +export * from "./schemas"; diff --git a/typescript/agentkit/src/action-providers/agentcoin/schemas.ts b/typescript/agentkit/src/action-providers/agentkoin/schemas.ts similarity index 94% rename from typescript/agentkit/src/action-providers/agentcoin/schemas.ts rename to typescript/agentkit/src/action-providers/agentkoin/schemas.ts index c362e37cc0..7eac4ead23 100644 --- a/typescript/agentkit/src/action-providers/agentcoin/schemas.ts +++ b/typescript/agentkit/src/action-providers/agentkoin/schemas.ts @@ -9,9 +9,9 @@ const protocol = z .enum(["x402", "a2a", "mcp", "openapi", "erc8004"]) .describe("Protocol the service speaks"); -const serviceId = z.string().max(40).describe("AgentCoin listing id, e.g. svc_962928f654d2a8a1"); +const serviceId = z.string().max(40).describe("AgentKoin listing id, e.g. svc_962928f654d2a8a1"); -const orderId = z.string().max(40).describe("AgentCoin order id, e.g. ord_f06171f16b1402f1"); +const orderId = z.string().max(40).describe("AgentKoin order id, e.g. ord_f06171f16b1402f1"); /** * Input schema for find_service. @@ -28,7 +28,7 @@ export const FindServiceSchema = z limit: z.number().int().min(1).max(50).optional().describe("Page size (1-50)"), }) .strict() - .describe("Search the AgentCoin service index, or fetch one listing by id"); + .describe("Search the AgentKoin service index, or fetch one listing by id"); /** * Input schema for route_task. @@ -107,7 +107,7 @@ export const VerifySchema = z orderId: orderId.optional().describe("Check the signed delivery record of an order"), }) .strict() - .describe("Verify AgentCoin signatures locally"); + .describe("Verify AgentKoin signatures locally"); /** * Input schema for refund. diff --git a/typescript/agentkit/src/action-providers/index.ts b/typescript/agentkit/src/action-providers/index.ts index 7e5debbc1b..531c0d6f7f 100644 --- a/typescript/agentkit/src/action-providers/index.ts +++ b/typescript/agentkit/src/action-providers/index.ts @@ -4,7 +4,7 @@ export * from "./actionProvider"; export * from "./customActionProvider"; export * from "./across"; -export * from "./agentcoin"; +export * from "./agentkoin"; export * from "./alchemy"; export * from "./baseAccount"; export * from "./basename";
find_serviceSearches the AgentCoin index of paid agent services (A2A, MCP, x402, ERC-8004) or fetches one listing (Base Sepolia testnet).Searches the AgentKoin index of paid agent services (A2A, MCP, x402, ERC-8004) or fetches one listing (Base Sepolia testnet).
route_task
verifyChecks AgentCoin EIP-191 signatures on delivery scores and delivery records locally.Checks AgentKoin EIP-191 signatures on delivery scores and delivery records locally.
refund