diff --git a/typescript/.changeset/tolca-seller-check.md b/typescript/.changeset/tolca-seller-check.md new file mode 100644 index 000000000..ec499f027 --- /dev/null +++ b/typescript/.changeset/tolca-seller-check.md @@ -0,0 +1,5 @@ +--- +"@coinbase/agentkit": patch +--- + +Added a Tolca action provider to check an x402 seller (OFAC crypto addresses, official USDC, Bazaar price and payTo) and to screen a counterparty against sanctions lists before paying diff --git a/typescript/agentkit/README.md b/typescript/agentkit/README.md index 37b14207f..a7f30d209 100644 --- a/typescript/agentkit/README.md +++ b/typescript/agentkit/README.md @@ -609,6 +609,19 @@ const agent = createAgent({
+Tolca + + + + + + + + + +
check_x402_sellerChecks an x402 seller before paying it (OFAC crypto addresses, official USDC, mainnet, Bazaar price and payTo) and returns allow, review or block with a signed receipt.
screen_sanctionsScreens a company or person name against US, UK, EU and Canadian sanctions lists and returns allow, review or block with the matching entries.
+
+
Twitter diff --git a/typescript/agentkit/src/action-providers/index.ts b/typescript/agentkit/src/action-providers/index.ts index 9f7164086..13558975b 100644 --- a/typescript/agentkit/src/action-providers/index.ts +++ b/typescript/agentkit/src/action-providers/index.ts @@ -26,6 +26,7 @@ export * from "./opensea"; export * from "./spl"; export * from "./superfluid"; export * from "./sushi"; +export * from "./tolca"; export * from "./truemarkets"; export * from "./twitter"; export * from "./wallet"; diff --git a/typescript/agentkit/src/action-providers/tolca/README.md b/typescript/agentkit/src/action-providers/tolca/README.md new file mode 100644 index 000000000..377b031bb --- /dev/null +++ b/typescript/agentkit/src/action-providers/tolca/README.md @@ -0,0 +1,59 @@ +# Tolca Action Provider + +This directory contains the **TolcaActionProvider**, which lets an agent check who it is about to pay before an x402 payment. + +## Directory Structure + +``` +tolca/ +├── tolcaActionProvider.ts # Provider with the two actions +├── tolcaActionProvider.test.ts # Tests +├── schemas.ts # Action schemas and configuration type +├── index.ts # Main exports +└── README.md # This file +``` + +## Actions + +### `check_x402_seller` + +Checks an x402 seller before the agent pays it ($0.01 USDC per check). Give the seller's `url` (Tolca reads its 402 payment request without paying it) or the `paymentRequired` object the agent already received, and optionally the `sellerName`. + +Tolca checks: + +- the `payTo` wallet against OFAC SDN crypto addresses +- that the asset is the official USDC contract on its network, and that the network is a mainnet +- that price and `payTo` match the seller's Coinbase x402 Bazaar listing +- optionally, the seller's company name against US, UK, EU and Canadian sanctions lists + +The answer's `action` is `allow`, `review` (ask a human before paying) or `block`, with the reasons and an Ed25519-signed receipt. + +### `screen_sanctions` + +Screens a company or person name against US (Consolidated Screening List, including OFAC SDN), UK, EU and Canadian sanctions lists ($0.005 USDC per check). Returns `allow`, `review` or `block`, the matching entries, the date of each list and a signed receipt. + +## Payment + +Each call is paid per use over x402 from the agent's own wallet, in USDC on Base mainnet or Solana mainnet. No API key or account is needed. + +Before paying, the provider reads Tolca's 402 payment request and refuses to pay unless every option goes to Tolca's own wallet, in official USDC, at or below `maxPriceUsdc` (default 0.02 USDC). + +## Configuration + +```typescript +import { tolcaActionProvider } from "@coinbase/agentkit"; + +const provider = tolcaActionProvider({ + maxPriceUsdc: 0.02, // optional, highest price paid for one call +}); +``` + +## Network Support + +- Base mainnet (`base-mainnet`) +- Solana mainnet (`solana-mainnet`) + +## Notes + +- Signed receipts can be verified at https://tolca.tonbot.ca/receipts/verify with the public key at https://tolca.tonbot.ca/.well-known/tolca-receipt-key.json. +- API reference: https://tolca.tonbot.ca/openapi.json diff --git a/typescript/agentkit/src/action-providers/tolca/index.ts b/typescript/agentkit/src/action-providers/tolca/index.ts new file mode 100644 index 000000000..d4630485c --- /dev/null +++ b/typescript/agentkit/src/action-providers/tolca/index.ts @@ -0,0 +1,2 @@ +export { TolcaActionProvider, tolcaActionProvider } from "./tolcaActionProvider"; +export * from "./schemas"; diff --git a/typescript/agentkit/src/action-providers/tolca/schemas.ts b/typescript/agentkit/src/action-providers/tolca/schemas.ts new file mode 100644 index 000000000..288a00ab2 --- /dev/null +++ b/typescript/agentkit/src/action-providers/tolca/schemas.ts @@ -0,0 +1,60 @@ +import { z } from "zod"; + +/** + * Configuration for the TolcaActionProvider. + */ +export interface TolcaConfig { + /** + * Base URL of the Tolca API. Defaults to https://tolca.tonbot.ca. + */ + baseUrl?: string; + + /** + * Highest price, in USDC, the provider will pay for one Tolca call. + * Defaults to 0.02 (payment-check costs 0.01, sanctions screening 0.005). + */ + maxPriceUsdc?: number; +} + +/** + * Input schema for checking an x402 seller before paying it. + */ +export const CheckX402SellerSchema = z + .object({ + url: z + .string() + .url() + .nullable() + .describe( + "URL of the x402 endpoint the agent is about to pay. Tolca requests it without paying and reads its 402 payment request. Provide this or paymentRequired.", + ), + paymentRequired: z + .record(z.string(), z.unknown()) + .nullable() + .describe( + "The decoded 402 payment request (PAYMENT-REQUIRED header or 402 body) the agent received from the seller. Provide this or url.", + ), + sellerName: z + .string() + .max(160) + .nullable() + .describe( + "Optional legal name of the company behind the seller, to also screen it against US, UK, EU and Canadian sanctions lists.", + ), + }) + .strip() + .describe("Check an x402 seller with Tolca payment-check before paying it"); + +/** + * Input schema for screening a company or person name against sanctions lists. + */ +export const ScreenSanctionsSchema = z + .object({ + name: z + .string() + .min(2) + .max(160) + .describe("Name of the company or person to screen, e.g. 'Acme Trading Ltd.'"), + }) + .strip() + .describe("Screen a company or person name against sanctions lists with Tolca"); diff --git a/typescript/agentkit/src/action-providers/tolca/tolcaActionProvider.test.ts b/typescript/agentkit/src/action-providers/tolca/tolcaActionProvider.test.ts new file mode 100644 index 000000000..f4fa465e8 --- /dev/null +++ b/typescript/agentkit/src/action-providers/tolca/tolcaActionProvider.test.ts @@ -0,0 +1,249 @@ +import { TolcaActionProvider, tolcaActionProvider } from "./tolcaActionProvider"; +import { EvmWalletProvider } from "../../wallet-providers"; +import { x402Client, wrapFetchWithPayment } from "@x402/fetch"; +import { registerExactEvmScheme } from "@x402/evm/exact/client"; +import { registerExactSvmScheme } from "@x402/svm/exact/client"; + +jest.mock("@x402/fetch"); +jest.mock("@x402/evm/exact/client"); +jest.mock("@x402/svm/exact/client"); + +const mockFetch = jest.fn(); +const mockPaidFetch = jest.fn(); +const mockX402Client = { registerScheme: jest.fn() }; + +jest + .mocked(x402Client) + .mockImplementation(() => mockX402Client as unknown as InstanceType); +jest.mocked(wrapFetchWithPayment).mockReturnValue(mockPaidFetch); +jest + .mocked(registerExactEvmScheme) + .mockImplementation(() => mockX402Client as unknown as InstanceType); +jest + .mocked(registerExactSvmScheme) + .mockImplementation(() => mockX402Client as unknown as InstanceType); + +global.fetch = mockFetch; + +const TOLCA_BASE_PAY_TO = "0x35F0B86a7E33F561faf7cfa5654CAd9162C4A17d"; +const BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; + +const makeWallet = (networkId = "base-mainnet") => { + const wallet = Object.create(EvmWalletProvider.prototype); + wallet.toSigner = jest.fn().mockReturnValue({ address: "0x1234" }); + wallet.readContract = jest.fn(); + wallet.getNetwork = jest.fn().mockReturnValue({ protocolFamily: "evm", networkId }); + return wallet as EvmWalletProvider; +}; + +const jsonResponse = (status: number, data: unknown, headers: Record = {}) => + ({ + status, + headers: { get: (name: string) => headers[name.toLowerCase()] ?? null }, + text: jest.fn().mockResolvedValue(JSON.stringify(data)), + json: jest.fn().mockResolvedValue(data), + }) as unknown as Response; + +const paymentRequired = (accepts: Array>) => + jsonResponse( + 402, + {}, + { + "payment-required": Buffer.from(JSON.stringify({ x402Version: 2, accepts })).toString( + "base64", + ), + }, + ); + +const tolcaAccepts = (amount = "10000") => [ + { + scheme: "exact", + network: "eip155:8453", + amount, + asset: BASE_USDC, + payTo: TOLCA_BASE_PAY_TO, + }, +]; + +describe("TolcaActionProvider", () => { + let provider: TolcaActionProvider; + + beforeEach(() => { + jest.clearAllMocks(); + jest.mocked(wrapFetchWithPayment).mockReturnValue(mockPaidFetch); + provider = tolcaActionProvider(); + }); + + describe("supportsNetwork", () => { + it("supports Base mainnet and Solana mainnet", () => { + expect(provider.supportsNetwork({ protocolFamily: "evm", networkId: "base-mainnet" })).toBe( + true, + ); + expect(provider.supportsNetwork({ protocolFamily: "svm", networkId: "solana-mainnet" })).toBe( + true, + ); + }); + + it("does not support testnets or other chains", () => { + expect(provider.supportsNetwork({ protocolFamily: "evm", networkId: "base-sepolia" })).toBe( + false, + ); + expect( + provider.supportsNetwork({ protocolFamily: "evm", networkId: "ethereum-mainnet" }), + ).toBe(false); + }); + }); + + describe("check_x402_seller", () => { + it("asks for a url or a payment request", async () => { + const result = JSON.parse( + await provider.checkX402Seller(makeWallet(), { + url: null, + paymentRequired: null, + sellerName: null, + }), + ); + expect(result.success).toBe(false); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it("checks the 402 terms, pays Tolca and returns the verdict", async () => { + mockFetch.mockResolvedValueOnce(paymentRequired(tolcaAccepts())); + mockPaidFetch.mockResolvedValueOnce( + jsonResponse(200, { action: "allow", risk_score: 5, reasons: [] }), + ); + + const result = JSON.parse( + await provider.checkX402Seller(makeWallet(), { + url: "https://seller.example/api", + paymentRequired: null, + sellerName: "Acme Data Inc.", + }), + ); + + expect(result.success).toBe(true); + expect(result.verdict).toBe("allow"); + expect(mockFetch).toHaveBeenCalledWith( + "https://tolca.tonbot.ca/v1/payment-check", + expect.objectContaining({ method: "POST" }), + ); + const sentBody = JSON.parse(mockFetch.mock.calls[0][1].body); + expect(sentBody).toEqual({ + url: "https://seller.example/api", + seller_name: "Acme Data Inc.", + }); + expect(wrapFetchWithPayment).toHaveBeenCalledWith(fetch, mockX402Client); + expect(mockPaidFetch).toHaveBeenCalledTimes(1); + }); + + it("sends the payment request when one is given", async () => { + mockFetch.mockResolvedValueOnce(paymentRequired(tolcaAccepts())); + mockPaidFetch.mockResolvedValueOnce(jsonResponse(200, { action: "block" })); + const seller402 = { x402Version: 2, accepts: [{ payTo: "0xabc" }] }; + + const result = JSON.parse( + await provider.checkX402Seller(makeWallet(), { + url: null, + paymentRequired: seller402, + sellerName: null, + }), + ); + + expect(result.verdict).toBe("block"); + expect(JSON.parse(mockFetch.mock.calls[0][1].body)).toEqual({ payment_required: seller402 }); + }); + + it("refuses to pay a wallet that is not Tolca's", async () => { + mockFetch.mockResolvedValueOnce( + paymentRequired([ + { ...tolcaAccepts()[0], payTo: "0x0000000000000000000000000000000000000bad" }, + ]), + ); + + const result = JSON.parse( + await provider.checkX402Seller(makeWallet(), { + url: "https://seller.example/api", + paymentRequired: null, + sellerName: null, + }), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("nothing was paid"); + expect(mockPaidFetch).not.toHaveBeenCalled(); + }); + + it("refuses to pay above the price cap", async () => { + mockFetch.mockResolvedValueOnce(paymentRequired(tolcaAccepts("50000"))); + + const result = JSON.parse( + await provider.checkX402Seller(makeWallet(), { + url: "https://seller.example/api", + paymentRequired: null, + sellerName: null, + }), + ); + + expect(result.success).toBe(false); + expect(mockPaidFetch).not.toHaveBeenCalled(); + }); + + it("refuses an asset that is not the official USDC", async () => { + mockFetch.mockResolvedValueOnce( + paymentRequired([ + { ...tolcaAccepts()[0], asset: "0x1111111111111111111111111111111111111111" }, + ]), + ); + + const result = JSON.parse( + await provider.checkX402Seller(makeWallet(), { + url: "https://seller.example/api", + paymentRequired: null, + sellerName: null, + }), + ); + + expect(result.success).toBe(false); + expect(mockPaidFetch).not.toHaveBeenCalled(); + }); + + it("returns Tolca's error without paying when it does not answer 402", async () => { + mockFetch.mockResolvedValueOnce(jsonResponse(400, { error: "url or payment_required" })); + + const result = JSON.parse( + await provider.checkX402Seller(makeWallet(), { + url: "https://seller.example/api", + paymentRequired: null, + sellerName: null, + }), + ); + + expect(result.success).toBe(false); + expect(result.status).toBe(400); + expect(mockPaidFetch).not.toHaveBeenCalled(); + }); + }); + + describe("screen_sanctions", () => { + it("screens a name and returns the verdict", async () => { + mockFetch.mockResolvedValueOnce(paymentRequired(tolcaAccepts("5000"))); + mockPaidFetch.mockResolvedValueOnce( + jsonResponse(200, { action: "block", risk_score: 95, matches: [{ list: "SDN" }] }), + ); + + const result = JSON.parse( + await provider.screenSanctions(makeWallet(), { name: "Example Sanctioned Co." }), + ); + + expect(result.success).toBe(true); + expect(result.verdict).toBe("block"); + expect(mockFetch).toHaveBeenCalledWith( + "https://tolca.tonbot.ca/v1/sanctions-check", + expect.objectContaining({ method: "POST" }), + ); + expect(JSON.parse(mockFetch.mock.calls[0][1].body)).toEqual({ + name: "Example Sanctioned Co.", + }); + }); + }); +}); diff --git a/typescript/agentkit/src/action-providers/tolca/tolcaActionProvider.ts b/typescript/agentkit/src/action-providers/tolca/tolcaActionProvider.ts new file mode 100644 index 000000000..170b46138 --- /dev/null +++ b/typescript/agentkit/src/action-providers/tolca/tolcaActionProvider.ts @@ -0,0 +1,314 @@ +import { z } from "zod"; +import { x402Client, wrapFetchWithPayment } from "@x402/fetch"; +import { registerExactEvmScheme } from "@x402/evm/exact/client"; +import { registerExactSvmScheme } from "@x402/svm/exact/client"; +import { ActionProvider } from "../actionProvider"; +import { CreateAction } from "../actionDecorator"; +import { Network } from "../../network"; +import { EvmWalletProvider, SvmWalletProvider, WalletProvider } from "../../wallet-providers"; +import { CheckX402SellerSchema, ScreenSanctionsSchema, TolcaConfig } from "./schemas"; + +const DEFAULT_BASE_URL = "https://tolca.tonbot.ca"; +const DEFAULT_MAX_PRICE_USDC = 0.02; +const SUPPORTED_NETWORK_IDS = ["base-mainnet", "solana-mainnet"]; + +/** + * Wallets that receive payment for Tolca calls. The provider refuses to pay anyone else. + */ +const TOLCA_PAY_TO = new Set([ + "0x35f0b86a7e33f561faf7cfa5654cad9162c4a17d", + "9e4z6QAGPT9Nj7nDsxQT7Vthbx8d8NnYCLWrejL2SZsJ", +]); + +/** Official USDC contracts on the networks Tolca accepts. */ +const USDC_ASSETS = new Set([ + "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", + "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", +]); + +type PaymentOption = { + payTo?: string; + asset?: string; + amount?: string; + maxAmountRequired?: string; +}; + +/** + * Normalize an address for comparison: EVM addresses are case-insensitive, Solana ones are not. + * + * @param address - The address to normalize. + * @returns The normalized address. + */ +function normalize(address: string): string { + return address.startsWith("0x") ? address.toLowerCase() : address; +} + +/** + * Extract a readable message from an unknown error. + * + * @param error - The error to describe. + * @returns A readable message. + */ +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * TolcaActionProvider lets an agent check who it is about to pay. + * + * - check_x402_seller: before paying an x402 seller, screen its payTo wallet against OFAC + * crypto addresses, confirm the asset is the official USDC on its network, and compare price + * and payTo with the seller's Coinbase x402 Bazaar listing. Returns allow / review / block. + * - screen_sanctions: screen a company or person name against US, UK, EU and Canadian lists. + * + * Each call is paid per use over x402 (USDC on Base or Solana) from the agent's wallet. + * The provider only pays Tolca's own wallets, in official USDC, up to maxPriceUsdc per call. + */ +export class TolcaActionProvider extends ActionProvider { + private readonly baseUrl: string; + private readonly maxPriceUsdc: number; + + /** + * Creates a new TolcaActionProvider. + * + * @param config - Optional base URL and per-call price cap. + */ + constructor(config: TolcaConfig = {}) { + super("tolca", []); + this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ""); + this.maxPriceUsdc = config.maxPriceUsdc ?? DEFAULT_MAX_PRICE_USDC; + } + + /** + * Checks an x402 seller before the agent pays it. + * + * @param walletProvider - The wallet that pays for the check. + * @param args - The seller URL or its 402 payment request, and an optional seller name. + * @returns A JSON string with Tolca's verdict, or an error. + */ + @CreateAction({ + name: "check_x402_seller", + description: ` +Checks an x402 seller BEFORE the agent pays it, using Tolca payment-check ($0.01 USDC, paid automatically from the wallet). + +Use it before paying a seller the agent has not paid before, or when the price or wallet looks unusual. +Provide either: +- url: the seller endpoint (Tolca reads its 402 payment request without paying it), or +- paymentRequired: the decoded 402 payment request the agent already received. +Optionally add sellerName to also screen the company behind the seller against sanctions lists. + +Tolca checks the payTo wallet against OFAC SDN crypto addresses, that the asset is the official USDC on its network, that the network is a mainnet, and that price and payTo match the seller's Coinbase x402 Bazaar listing. + +The answer has an "action": +- allow: safe to pay +- review: do not pay automatically; ask a human +- block: do not pay +It also lists the reasons and includes a signed receipt the agent can keep as evidence.`, + schema: CheckX402SellerSchema, + }) + async checkX402Seller( + walletProvider: WalletProvider, + args: z.infer, + ): Promise { + if (!args.url && !args.paymentRequired) { + return JSON.stringify({ + success: false, + error: "Provide url (the seller endpoint) or paymentRequired (its 402 payment request).", + }); + } + + const body: Record = args.paymentRequired + ? { payment_required: args.paymentRequired } + : { url: args.url }; + if (args.sellerName) { + body.seller_name = args.sellerName; + } + + try { + const { status, data } = await this.paidPost(walletProvider, "/v1/payment-check", body); + if (status !== 200) { + return JSON.stringify({ success: false, status, data }); + } + const result = data as Record; + return JSON.stringify({ success: true, verdict: result.action, ...result }); + } catch (error) { + return JSON.stringify({ success: false, error: errorMessage(error) }); + } + } + + /** + * Screens a company or person name against sanctions lists. + * + * @param walletProvider - The wallet that pays for the check. + * @param args - The name to screen. + * @returns A JSON string with Tolca's verdict, or an error. + */ + @CreateAction({ + name: "screen_sanctions", + description: ` +Screens a company or person name against US (Consolidated Screening List, incl. OFAC SDN), UK, EU and Canadian sanctions lists, using Tolca ($0.005 USDC, paid automatically from the wallet). + +Use it before paying, hiring or signing with a counterparty the agent does not know. +The answer has an "action" (allow / review / block), the matching list entries if any, the date of each list, and a signed receipt. +A "review" means a possible match that a human should look at.`, + schema: ScreenSanctionsSchema, + }) + async screenSanctions( + walletProvider: WalletProvider, + args: z.infer, + ): Promise { + try { + const { status, data } = await this.paidPost(walletProvider, "/v1/sanctions-check", { + name: args.name, + }); + if (status !== 200) { + return JSON.stringify({ success: false, status, data }); + } + const result = data as Record; + return JSON.stringify({ success: true, verdict: result.action, ...result }); + } catch (error) { + return JSON.stringify({ success: false, error: errorMessage(error) }); + } + } + + /** + * Tolca accepts payment on Base mainnet and Solana mainnet. + * + * @param network - The network to check. + * @returns True if the wallet can pay Tolca on this network. + */ + supportsNetwork = (network: Network) => SUPPORTED_NETWORK_IDS.includes(network.networkId ?? ""); + + /** + * POSTs to Tolca, checks the 402 payment request, then pays it from the wallet. + * + * @param walletProvider - The wallet that pays. + * @param path - The Tolca API path. + * @param body - The JSON body. + * @returns The HTTP status and parsed response. + */ + private async paidPost( + walletProvider: WalletProvider, + path: string, + body: Record, + ): Promise<{ status: number; data: unknown }> { + if ( + !(walletProvider instanceof EvmWalletProvider || walletProvider instanceof SvmWalletProvider) + ) { + throw new Error("Only EVM and Solana wallet providers can pay for Tolca calls."); + } + + const url = `${this.baseUrl}${path}`; + const init: RequestInit = { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }; + + // 1. Ask without paying: Tolca answers 402 with its price and wallet. + const unpaid = await fetch(url, init); + if (unpaid.status !== 402) { + return { status: unpaid.status, data: await this.parse(unpaid) }; + } + + // 2. Pay only Tolca's own wallets, in official USDC, up to the price cap. + const options = await this.paymentOptions(unpaid); + const cap = Math.round(this.maxPriceUsdc * 1_000_000); + const unsafe = options.filter(option => { + const payTo = normalize(String(option.payTo ?? "")); + const asset = normalize(String(option.asset ?? "")); + const amount = Number(option.amount ?? option.maxAmountRequired ?? NaN); + return ( + !TOLCA_PAY_TO.has(payTo) || + !USDC_ASSETS.has(asset) || + !Number.isFinite(amount) || + amount > cap + ); + }); + if (options.length === 0 || unsafe.length > 0) { + throw new Error( + "Unexpected price, asset or wallet in Tolca's payment request: nothing was paid.", + ); + } + + // 3. Pay and get the answer. + const client = await this.createX402Client(walletProvider); + const paidFetch = wrapFetchWithPayment(fetch, client); + const paid = await paidFetch(url, init); + return { status: paid.status, data: await this.parse(paid) }; + } + + /** + * Reads the payment options from a 402 response (PAYMENT-REQUIRED header, or the body for x402 v1). + * + * @param response - The 402 response. + * @returns The payment options. + */ + private async paymentOptions(response: Response): Promise { + const header = response.headers.get("payment-required"); + let decoded: unknown; + if (header) { + decoded = JSON.parse(Buffer.from(header, "base64").toString("utf8")); + } else { + decoded = await response.json(); + } + const accepts = (decoded as { accepts?: unknown })?.accepts; + return Array.isArray(accepts) ? (accepts as PaymentOption[]) : []; + } + + /** + * Parses a response as JSON when possible, otherwise as text. + * + * @param response - The response to parse. + * @returns The parsed body. + */ + private async parse(response: Response): Promise { + const text = await response.text(); + try { + return JSON.parse(text); + } catch { + return text; + } + } + + /** + * Creates an x402 client that signs with the agent's wallet. + * + * @param walletProvider - The EVM or Solana wallet provider. + * @returns The configured x402 client. + */ + private async createX402Client(walletProvider: WalletProvider): Promise { + const client = new x402Client(); + if (walletProvider instanceof EvmWalletProvider) { + const account = walletProvider.toSigner(); + const signer = { + ...account, + readContract: (args: { + address: `0x${string}`; + abi: readonly unknown[]; + functionName: string; + args?: readonly unknown[]; + }) => + walletProvider.readContract({ + address: args.address, + abi: args.abi as never, + functionName: args.functionName as never, + args: args.args as never, + }), + }; + registerExactEvmScheme(client, { signer }); + } else if (walletProvider instanceof SvmWalletProvider) { + const signer = await walletProvider.toSigner(); + registerExactSvmScheme(client, { signer }); + } + return client; + } +} + +/** + * Factory function to create a new TolcaActionProvider. + * + * @param config - Optional base URL and per-call price cap. + * @returns A new TolcaActionProvider. + */ +export const tolcaActionProvider = (config?: TolcaConfig) => new TolcaActionProvider(config);