diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index a4ed07c..4e37d19 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -25,7 +25,7 @@ body: attributes: label: Version description: Output of `vapi --version` - placeholder: "0.17.4" + placeholder: "0.17.5" validations: { required: true } - type: dropdown id: surface diff --git a/CHANGELOG.md b/CHANGELOG.md index 608af36..15e44be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ sentence under it is the summary shown on the ## Unreleased +## 0.17.5 - 2026-12-03 + +`vapi task fund` can renew an expired, unused USDC authorization without counting the replacement twice against spend caps. + +### Fixed + +- `vapi task fund` can request a new USDC authorization after vAPI or confirmed chain state proves an earlier authorization expired unused, including when a pool was already created or the signer was interrupted. The replacement counts once against spend caps. + ## 0.17.4 - 2026-12-02 Pools with claims work in the CLI: `vapi task claim`, `show`, `cancel … pool` and `board` read them again. diff --git a/README.md b/README.md index 87cfbde..df56464 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ vAPI Network is not related to Vapi.ai, the voice AI company. ## Quickstart -This README describes client 0.17.4. `npm view vapi-network version` shows the latest published release. +This README describes client 0.17.5. `npm view vapi-network version` shows the latest published release. The client needs Node.js 22 or newer. ```bash diff --git a/docs/wallets.md b/docs/wallets.md index e6526fa..c13256e 100644 --- a/docs/wallets.md +++ b/docs/wallets.md @@ -254,7 +254,7 @@ vapi This screen comes from a vault restored from the BIP-39 test phrase into an empty home, so the account holds nothing and is not linked yet: ```text -vAPI 0.17.4 home /tmp/vapi-docs-home registry api.vapinetwork.ai +vAPI 0.17.5 home /tmp/vapi-docs-home registry api.vapinetwork.ai Owner not linked console: https://api.vapinetwork.ai/agents Vault unlocked on this device (macOS Keychain) backup: vapi backup diff --git a/package.json b/package.json index 11eb757..33ff9de 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vapi-network-workspace", - "version": "0.17.4", + "version": "0.17.5", "private": true, "description": "Open-source, non-custodial access to x402 APIs", "license": "Apache-2.0", diff --git a/packages/cli/package.json b/packages/cli/package.json index 036e51a..556bd15 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@vapi-network/cli", - "version": "0.17.4", + "version": "0.17.5", "description": "Command-line interface for the non-custodial vAPI Network wallet", "license": "Apache-2.0", "repository": { diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.ts index d75657d..406686b 100644 --- a/packages/cli/src/version.ts +++ b/packages/cli/src/version.ts @@ -1,3 +1,3 @@ // Kept in sync with packages/cli/package.json by version.test.ts. The CLI is // bundled into a single file, so it cannot read its own manifest at runtime. -export const CLI_VERSION = "0.17.4"; +export const CLI_VERSION = "0.17.5"; diff --git a/packages/core/README.md b/packages/core/README.md index 13d7856..1711084 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -263,7 +263,7 @@ basis points, or the registry label and computed percentage for legacy fees. | `validatePrivateKey` | function (value: string): Hex | 0.5.0 or earlier | | `validateRecoveryPhrase` | function (phrase: string): string | 0.5.0 or earlier | | `VAPI_BUILDER_CODE` | constant VAPI_BUILDER_CODE: "vapi" | 0.5.0 or earlier | -| `VAPI_CLIENT_VERSION` | constant VAPI_CLIENT_VERSION: "0.17.4" | 0.4.0 | +| `VAPI_CLIENT_VERSION` | constant VAPI_CLIENT_VERSION: "0.17.5" | 0.4.0 | | `WALLET_NAME_PATTERN` | constant WALLET_NAME_PATTERN: RegExp | 0.5.0 or earlier | | `walletEntrySchema` | constant walletEntrySchema: ZodObject<{ createdAt: ZodISODateTime; label: ZodOptional; spendCaps: ZodObject<{ perCallAtomic: ZodString; perDayAtomic: ZodString; }, $strip>; routerRefill: ZodOptional<...>; link: ZodOptional<...>; }, $strip> | 0.5.0 or earlier | | `walletNameSchema` | constant walletNameSchema: ZodString | 0.5.0 or earlier | diff --git a/packages/core/package.json b/packages/core/package.json index 3a6af8f..9f4fe13 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@vapi-network/core", - "version": "0.17.4", + "version": "0.17.5", "description": "Non-custodial x402 protocol, wallet policy, discovery, and receipts core", "license": "Apache-2.0", "repository": { diff --git a/packages/core/src/router-client.test.ts b/packages/core/src/router-client.test.ts index 53da0d1..ea15f4e 100644 --- a/packages/core/src/router-client.test.ts +++ b/packages/core/src/router-client.test.ts @@ -3290,7 +3290,7 @@ describe("Router purchase credit and receipt guards", () => { paymentId: "purchase_1234567890", phases: { requestMs: 100 }, policy: { capsApplied: true }, - client: { name: "vapi-network", version: "0.17.4" }, + client: { name: "vapi-network", version: "0.17.5" }, resourceUrl: `${API_BASE}/api/router/top-up/5`, settlement: { outcome: "unknown" }, outcome: "settlement_unknown", @@ -3337,7 +3337,7 @@ describe("Router purchase credit and receipt guards", () => { paymentId: "purchase_1234567890", phases: { requestMs: 100 }, policy: { capsApplied: true }, - client: { name: "vapi-network", version: "0.17.4" }, + client: { name: "vapi-network", version: "0.17.5" }, outcome: "paid", }); const raw = await readFile(receiptsPath, "utf8"); diff --git a/packages/core/src/spend-policy.ts b/packages/core/src/spend-policy.ts index c0ceece..ebdbb8c 100644 --- a/packages/core/src/spend-policy.ts +++ b/packages/core/src/spend-policy.ts @@ -468,6 +468,57 @@ export async function releaseSpend( }); } +type TaskFundingReservationLookup = { + ledgerPath: string; + wallet: WalletName; + taskKey: string; + reservationId: string; + now: Date; +}; + +function matchesTaskFundingReservation( + entry: z.infer, + input: TaskFundingReservationLookup, +) { + return ( + entry.id === input.reservationId && + entry.kind === "escrow-funding" && + (entry.taskKey === undefined || entry.taskKey === input.taskKey) + ); +} + +/** Whether this preparation has reserved funding spend on any stored day. */ +export async function hasTaskFundingReservation(input: TaskFundingReservationLookup) { + const rows = await readStoredSpendLedgerRows(input.ledgerPath, input.now, true); + return rows.some( + (row) => + row.wallet === input.wallet && + row.reservations?.some((entry) => matchesTaskFundingReservation(entry, input)), + ); +} + +/** Releases the exact reservation after its funding authorization is proven unusable. */ +export async function releaseTaskFundingReservation( + input: TaskFundingReservationLookup, +): Promise { + await withLedgerLock(input.ledgerPath, async () => { + const rows = await readStoredSpendLedgerRows(input.ledgerPath, input.now, true); + let released = false; + for (const row of rows) { + if (row.wallet !== input.wallet) continue; + const reservation = row.reservations?.find((entry) => + matchesTaskFundingReservation(entry, input), + ); + if (!reservation) continue; + const remaining = BigInt(row.spentAtomic) - BigInt(reservation.amountAtomic); + row.spentAtomic = (remaining > 0n ? remaining : 0n).toString(); + row.reservations = row.reservations!.filter((entry) => entry !== reservation); + released = true; + } + if (released) await writeLedgerAtomically(input.ledgerPath, rows); + }); +} + function parseAtomicCap(value: string, label: string): bigint { if (!/^\d+$/.test(value)) { throw new Error(`Invalid ${label} spend cap ${JSON.stringify(value)}.`); diff --git a/packages/core/src/status.test.ts b/packages/core/src/status.test.ts index c81bb10..54cbd57 100644 --- a/packages/core/src/status.test.ts +++ b/packages/core/src/status.test.ts @@ -95,7 +95,7 @@ function linkedAccount(): AgentLink { function deps(home: string, wallets: WalletStore, overrides: Partial = {}): StatusDeps { return { - version: "0.17.4", + version: "0.17.5", home, registry: "https://api.vapinetwork.ai", wallets, @@ -123,7 +123,7 @@ describe("buildStatus", () => { await expect( buildStatus(deps(home, wallets, { registry: "https://api.vapinetwork.ai/" })), ).resolves.toEqual({ - version: "0.17.4", + version: "0.17.5", home, registry: "https://api.vapinetwork.ai", vault: { @@ -170,7 +170,7 @@ describe("buildStatus", () => { ); expect(report).toEqual({ - version: "0.17.4", + version: "0.17.5", home, registry: "https://api.vapinetwork.ai", owner: { diff --git a/packages/core/src/support-report.test.ts b/packages/core/src/support-report.test.ts index 48c72d9..102e5a7 100644 --- a/packages/core/src/support-report.test.ts +++ b/packages/core/src/support-report.test.ts @@ -45,10 +45,10 @@ describe("support reports", () => { expect(result).toMatchObject({ path: join(reportsDirectory, "2026-09-10T08-09-10-123Z.json"), issueUrl: - "https://github.com/vAPI-Network/vapi-network/issues/new?template=bug.yml&title=payment%20failed%20oddly&version=0.17.4", + "https://github.com/vAPI-Network/vapi-network/issues/new?template=bug.yml&title=payment%20failed%20oddly&version=0.17.5", report: { message: "payment failed oddly", - clientVersion: "0.17.4", + clientVersion: "0.17.5", os: { platform: "test-os", release: "1.2.3", arch: "test-arch" }, node: "v22.0.0-test", receiptIds: ["receipt-1", "receipt-2", "receipt-3", "receipt-4", "receipt-5"], diff --git a/packages/core/src/support-report.ts b/packages/core/src/support-report.ts index c371402..06d1588 100644 --- a/packages/core/src/support-report.ts +++ b/packages/core/src/support-report.ts @@ -7,7 +7,7 @@ import { DEFAULT_REGISTRY_URL, getVapiPaths } from "./config.js"; import { createPublicFetch, type LookupFn } from "./net-guard.js"; import { readReceipts } from "./receipts.js"; -export const VAPI_CLIENT_VERSION = "0.17.4"; +export const VAPI_CLIENT_VERSION = "0.17.5"; export type SupportSystemInfo = { platform: string; diff --git a/packages/core/src/tasks/client.ts b/packages/core/src/tasks/client.ts index 5c90ca3..c79d5aa 100644 --- a/packages/core/src/tasks/client.ts +++ b/packages/core/src/tasks/client.ts @@ -93,6 +93,12 @@ export type TasksRequestOptions = { signal?: AbortSignal }; /** Retain the same key when retrying the same mutation. The client never retries automatically. */ export type TasksMutationOptions = TasksRequestOptions & { idempotencyKey: string }; +type TaskV2OperationBody = { + step: string; + transactionHash?: string; + proof?: "expired-authorization"; +}; + const tasksClientErrorBrand = Symbol.for("@vapi-network/core/TasksClientError"); export class TasksClientError extends Error { @@ -381,7 +387,7 @@ export function createTasksClient(options: TasksClientOptions): TasksClientV2 { operationV2( id: string, mode: "transaction" | "reconcile" | "recover" | "abandon", - body: { step: string; transactionHash?: string }, + body: TaskV2OperationBody, call: TasksMutationOptions, ) { input(taskV2StepSchema, body.step); @@ -912,7 +918,7 @@ export type TasksClient = { operationV2?( id: string, mode: "transaction" | "reconcile" | "recover" | "abandon", - body: { step: string; transactionHash?: string }, + body: TaskV2OperationBody, call: TasksMutationOptions, ): Promise< | z.infer diff --git a/packages/core/src/tasks/v2-execution.test.ts b/packages/core/src/tasks/v2-execution.test.ts index 90b468d..1d171f9 100644 --- a/packages/core/src/tasks/v2-execution.test.ts +++ b/packages/core/src/tasks/v2-execution.test.ts @@ -242,7 +242,15 @@ async function fixture(step: TaskV2OperationResponse["operation"]["step"] = "v2- keccak256(serializedTransaction), ), waitForTransactionReceipt: vi.fn(async () => ({ status: "success" })), - getBlock: vi.fn(async () => ({ timestamp: NOW_SECONDS })), + getBlockNumber: vi.fn(async () => 123n), + getBlock: vi.fn( + async (_block?: { + blockNumber?: bigint; + blockTag?: string; + }): Promise<{ timestamp: bigint; number?: bigint; hash?: Hex }> => ({ + timestamp: NOW_SECONDS, + }), + ), readContract: vi.fn(async (call: Read): Promise => { const pool = view.workOrder.terms.shape === "pool"; switch (call.functionName) { @@ -552,6 +560,21 @@ describe("recorded T11 operation boundaries", () => { await client.operationV2(V2_WRITE_OPERATION, "recover", { step: "v2-approve" }, call), ).toMatchObject({ scanComplete: false, operation: { state: "prepared", plan: null } }); }); + it("sends the expired authorization proof to the hosted abandon route", async () => { + const fetch = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => + Response.json({ orderId: V2_WRITE_ORDER, operation: null, outcome: "abandoned" }), + ); + const client = createTasksClient({ baseUrl: "https://tasks.example", fetch }); + const body = { step: "v2-fund", proof: "expired-authorization" } as const; + await expect( + client.operationV2(V2_WRITE_OPERATION, "abandon", body, { + idempotencyKey: V2_WRITE_OPERATION, + }), + ).resolves.toMatchObject({ outcome: "abandoned" }); + const request = new Request(...fetch.mock.calls[0]!); + expect(new URL(request.url).pathname).toBe(`/v1/work-operations/${V2_WRITE_OPERATION}/abandon`); + expect(await request.json()).toEqual(body); + }); it.each([ "chain_preflight_unavailable", "v2_binding_mismatch", @@ -2440,6 +2463,14 @@ function authorizedFunding( usdc?: `0x${string}`, ) { const intent = fundingIntent(chainId, usdc); + serveAuthorizedFunding(f, intent); + return intent; +} + +function serveAuthorizedFunding( + f: Awaited>, + intent: ReturnType, +) { f.client.prepareV2.mockResolvedValue(intent); f.client.confirmV2Signature.mockImplementation( async (_id: string, _op: string, signature: `0x${string}`) => { @@ -2457,7 +2488,6 @@ function authorizedFunding( return f.prepared; }, ); - return intent; } describe("a new clone funded by one authorization (hosted ERC-3009 funding)", () => { @@ -3112,11 +3142,480 @@ describe("a rerun of an operation that already signed something", () => { Object.assign(f.rpc, { getTransactionReceipt: vi.fn(async () => ({ status: "success" })) }); /** Two hours on: the chain clock and the local clock are past the authorization window. */ const twoHoursLater = (f: Fixture) => { - f.rpc.getBlock.mockResolvedValue({ timestamp: NOW_SECONDS + 7200n }); + f.rpc.getBlock.mockResolvedValue({ + timestamp: NOW_SECONDS + 7200n, + number: 123n, + hash: zeroHash, + }); return createTaskV2Executor({ ...f.options, now: () => new Date("2026-10-26T14:00:00Z") }); }; const journalKey = async (f: Fixture) => (await f.pending.preparation(V2_WRITE_ORDER, FUND_VERB))?.idempotencyKey; + const renewedIntent = ( + first: ReturnType, + timestamp = NOW_SECONDS + 7200n, + ) => ({ + ...first, + operationId: `${first.operationId}_renewed`, + typedData: { + ...first.typedData, + message: { + ...first.typedData.message, + validAfter: (timestamp - 1n).toString(), + validBefore: (timestamp + 300n).toString(), + nonce: `0x${"34".repeat(32)}`, + }, + }, + }); + + async function signedFunding(hosted: boolean, numericExpiry = false, signed = true) { + const f = onBase(await fixture("v2-fund"), READINESS_V2_ONLY); + f.input.policy = { maxPerTaskUsd: 100, approveAboveUsd: 100 }; + f.input.caps = { perCallAtomic: "1", perDayAtomic: "100000000" }; + const first = authorizedFunding(f, 8453, BASE_USDC); + if (numericExpiry) + Object.assign(first.typedData.message, { + validBefore: Number(first.typedData.message.validBefore), + }); + if (signed) f.client.confirmV2Signature.mockRejectedValueOnce(new Error("socket hang up")); + else f.typedSign.mockRejectedValueOnce(new Error("vault closed")); + await expect(f.execute(fund(f))).rejects.toMatchObject({ code: "chain_error" }); + if (hosted) { + // The hosted operation ID was already journaled before the funding step. + await f.pending.bindPreparationOperation(V2_WRITE_ORDER, FUND_VERB, V2_WRITE_OPERATION); + } + const journal = await f.pending.preparation(V2_WRITE_ORDER, FUND_VERB); + expect(journal).toMatchObject({ preparedV2: taskV2PreparedSchema.parse(first) }); + expect(journal?.signed).toBe(signed ? true : undefined); + expect(await f.pending.get(V2_WRITE_OPERATION, "v2-fund")).toBeUndefined(); + expect(await spent(f)).toBe("100000000"); + f.typedSign.mockClear(); + f.client.confirmV2Signature.mockClear(); + f.rpc.getBlock.mockClear(); + f.rpc.readContract.mockClear(); + return { f, first, journal: journal! }; + } + + const earlierPoolStep = (f: Fixture) => ({ + ...f.prepared, + operation: { ...f.prepared.operation, step: "v2-create-pool" as const, plan: null }, + }); + const abandonedFunding = { orderId: V2_WRITE_ORDER, operation: null, outcome: "abandoned" }; + const authorizationExpired = () => + new TasksClientError("http", "Funding authorization expired", 409, "authorization_expired"); + const replayFunding = ( + f: Fixture, + idempotencyKey: string, + current: () => TaskV2OperationResponse, + ) => { + const prepare = f.client.prepareV2.getMockImplementation()!; + f.client.prepareV2.mockImplementation((...args: unknown[]) => + (args[2] as { idempotencyKey: string }).idempotencyKey === idempotencyKey + ? Promise.resolve(current()) + : prepare(), + ); + }; + const hostedCalls = (f: Fixture) => + f.client.operationV2.mock.calls.map(([, mode, body]) => [mode, body]); + + it("renews after a saved, mined pool creation when the hosted funding step is prepared", async () => { + const { f, first, journal } = await signedFunding(true); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + replayFunding(f, journal.idempotencyKey, () => f.prepared); + // Earlier transaction bytes are journaled separately under the same hosted operation. + const raw = await account.signTransaction({ + to: BASE.bountyPoolFactoryV1, + chainId: 8453, + nonce: 0, + gas: 100000n, + gasPrice: 1n, + }); + await f.pending.put(V2_WRITE_OPERATION, "v2-create-pool", { + raw, + txHash: keccak256(raw), + signer: account.address, + chainId: 8453, + nonce: 0, + createdAt: "2026-10-26T12:00:00Z", + }); + f.sign.mockClear(); + nodeHoldsItAsMined(f); + f.rpc.getTransactionCount.mockResolvedValue(1); + f.client.operationV2.mockResolvedValueOnce(abandonedFunding); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(hostedCalls(f)[0]).toEqual([ + "abandon", + { step: "v2-fund", proof: "expired-authorization" }, + ]); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + expect(f.sign).toHaveBeenCalledTimes(1); + expect(await f.pending.get(V2_WRITE_OPERATION, "v2-create-pool")).toBeUndefined(); + expect(await spent(f)).toBe("100000000"); + }); + + it("recovers a saved, mined funding transaction without attempting abandonment", async () => { + const f = onBase(await fixture("v2-fund"), READINESS_V2_ONLY); + authorizedFunding(f, 8453, BASE_USDC); + await sentThenDropped(f, { action: "fund" }, "100000000"); + const saved = await f.pending.get(V2_WRITE_OPERATION, "v2-fund"); + expect(saved).toBeDefined(); + nodeHoldsItAsMined(f); + minedAndKnown(f); + f.typedSign.mockClear(); + f.sign.mockClear(); + f.client.confirmV2Signature.mockClear(); + f.rpc.sendRawTransaction.mockClear(); + f.client.operationV2.mockClear(); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(hostedCalls(f)).toEqual([["recover", { step: "v2-fund" }]]); + expect(f.client.prepareV2).toHaveBeenCalledTimes(1); + expect(await f.pending.get(V2_WRITE_OPERATION, "v2-fund")).toEqual(saved); + nothingLeftTheMachine(f); + expect(await spent(f)).toBe("100000000"); + }); + + it("abandons an unsent hosted pool creation at its current step", async () => { + const { f, first, journal } = await signedFunding(true); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + replayFunding(f, journal.idempotencyKey, () => earlierPoolStep(f)); + f.client.operationV2 + .mockRejectedValueOnce(authorizationExpired()) + .mockResolvedValueOnce(abandonedFunding); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(hostedCalls(f).slice(0, 2)).toEqual([ + ["recover", { step: "v2-create-pool" }], + ["abandon", { step: "v2-create-pool", proof: "expired-authorization" }], + ]); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + }); + + it("reconciles a submitted pool creation before abandoning the new current step", async () => { + const { f, first, journal } = await signedFunding(true); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + const transactionHash: Hex = `0x${"bc".repeat(32)}`; + const earlier = earlierPoolStep(f); + const submitted: TaskV2OperationResponse = { + ...earlier, + operation: { ...earlier.operation, state: "submitted", transactionHash }, + }; + let current = submitted; + replayFunding(f, journal.idempotencyKey, () => current); + f.client.operationV2 + .mockImplementationOnce(async () => { + // The journal saves the newly prepared fund step before validating its expired plan. + current = f.prepared; + throw authorizationExpired(); + }) + .mockResolvedValueOnce(abandonedFunding); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(hostedCalls(f).slice(0, 2)).toEqual([ + ["reconcile", { step: "v2-create-pool", transactionHash }], + ["abandon", { step: "v2-fund", proof: "expired-authorization" }], + ]); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + }); + + it("renews signed funding after hosted abandonment, with a new key and one reservation", async () => { + const { f, first, journal } = await signedFunding(true); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + replayFunding(f, journal.idempotencyKey, () => f.prepared); + f.client.operationV2.mockResolvedValueOnce(abandonedFunding); + + await expect( + executeTaskV2( + { + client: f.options.client, + chain: { ...missingTasksChain, executeV2: twoHoursLater(f) }, + pending: f.pending, + baseUrl: "https://api.example", + randomUUID: () => V2_WRITE_OPERATION, + signInHint: "test", + }, + fund(f), + ), + ).resolves.toMatchObject({ + ok: true, + operation: { state: "confirmed", step: "v2-fund" }, + }); + expect(f.client.operationV2).toHaveBeenNthCalledWith( + 1, + V2_WRITE_OPERATION, + "abandon", + { step: "v2-fund", proof: "expired-authorization" }, + expect.objectContaining({ idempotencyKey: expect.any(String) }), + ); + expect(f.client.prepareV2).toHaveBeenCalledTimes(3); + expect(f.client.prepareV2).toHaveBeenNthCalledWith( + 2, + V2_WRITE_ORDER, + { action: "fund" }, + { idempotencyKey: journal.idempotencyKey }, + ); + expect(f.client.prepareV2).toHaveBeenLastCalledWith( + V2_WRITE_ORDER, + { action: "fund" }, + expect.objectContaining({ + idempotencyKey: expect.not.stringMatching(journal!.idempotencyKey), + }), + ); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + expect( + f.rpc.readContract.mock.calls.some(([call]) => call.functionName === "authorizationState"), + ).toBe(false); + expect(await spent(f)).toBe("100000000"); + }); + + it.each(["submitted", "prepared"] as const)( + "finishes recovered funding from a %s step without signing or releasing its reservation", + async (operationState) => { + const { f, journal } = await signedFunding(true); + replayFunding(f, journal.idempotencyKey, () => f.prepared); + const transactionHash = `0x${"aa".repeat(32)}`; + // The order view can lag the operation journal. + f.client.getOrder.mockResolvedValueOnce({ + ...f.view, + workOrder: { ...f.view.workOrder, v2State: undefined }, + } as never); + f.client.operationV2 + .mockResolvedValueOnce({ + orderId: V2_WRITE_ORDER, + operation: { + ...f.prepared.operation, + state: operationState, + plan: null, + transactionHash: operationState === "submitted" ? transactionHash : null, + }, + outcome: "recovered", + }) + .mockResolvedValueOnce({ + orderId: V2_WRITE_ORDER, + operation: { ...f.prepared.operation, state: "confirmed", transactionHash }, + }); + walletHolds(f, 0n); + await expect( + twoHoursLater(f)({ + ...fund(f), + policy: { maxPerTaskUsd: 0, approveAboveUsd: 0 }, + }), + ).resolves.toMatchObject({ ok: true, operation: { state: "confirmed", step: "v2-fund" } }); + expect(f.client.operationV2.mock.calls.map(([, mode]) => mode)).toEqual([ + "abandon", + operationState === "submitted" ? "reconcile" : "recover", + ]); + expect(f.client.prepareV2).toHaveBeenCalledTimes(2); + nothingLeftTheMachine(f); + expect(await journalKey(f)).toBeUndefined(); + expect(await spent(f)).toBe("100000000"); + }, + ); + + it.each(["scanning", "authorization_still_live", "transaction_pending", "wrong order"] as const)( + "keeps signed funding when hosted abandonment returns %s", + async (outcome) => { + const { f, journal } = await signedFunding(true); + replayFunding(f, journal.idempotencyKey, () => f.prepared); + if (outcome === "scanning") { + f.client.operationV2.mockResolvedValue({ + orderId: V2_WRITE_ORDER, + operation: { ...f.prepared.operation, plan: null }, + outcome, + }); + } else if (outcome === "wrong order") { + f.client.operationV2.mockResolvedValueOnce({ + orderId: V2_WRITE_OPERATION, + operation: null, + outcome: "abandoned", + }); + } else { + f.client.operationV2.mockRejectedValueOnce( + new TasksClientError("http", outcome, 409, outcome), + ); + } + + await expect(twoHoursLater(f)(fund(f))).rejects.toMatchObject({ + message: expect.stringContaining("Nothing new was signed. Try again later."), + }); + expect(f.client.operationV2).toHaveBeenCalledTimes(outcome === "scanning" ? 256 : 1); + if (outcome === "scanning") expect(f.sleep).toHaveBeenCalledWith(1000); + expect(f.client.prepareV2).toHaveBeenCalledTimes(2); + expect(await f.pending.preparation(V2_WRITE_ORDER, FUND_VERB)).toEqual(journal); + nothingLeftTheMachine(f); + expect(await spent(f)).toBe("100000000"); + }, + ); + + it("waits for the hosted scan to finish before preparing fresh funding", async () => { + const { f, first, journal } = await signedFunding(true); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + replayFunding(f, journal.idempotencyKey, () => f.prepared); + f.client.operationV2 + .mockResolvedValueOnce({ + orderId: V2_WRITE_ORDER, + operation: { ...f.prepared.operation, plan: null }, + outcome: "scanning", + }) + .mockImplementationOnce(async () => { + expect(f.sleep).toHaveBeenCalledExactlyOnceWith(1000); + nothingLeftTheMachine(f); + expect(await journalKey(f)).toBe(journal.idempotencyKey); + return abandonedFunding; + }); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(hostedCalls(f).slice(0, 2)).toEqual([ + ["abandon", { step: "v2-fund", proof: "expired-authorization" }], + ["abandon", { step: "v2-fund", proof: "expired-authorization" }], + ]); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + }); + + const authorizationState = (f: Fixture, used: boolean | Error) => { + const read = f.rpc.readContract.getMockImplementation()!; + f.rpc.readContract.mockImplementation(async (call) => { + if (call.functionName !== "authorizationState") return read(call); + if (used instanceof Error) throw used; + return used; + }); + }; + + it("renews signed funding without a hosted operation after USDC proves it expired unused", async () => { + const { f, first } = await signedFunding(false); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + authorizationState(f, false); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(f.rpc.readContract).toHaveBeenCalledWith( + expect.objectContaining({ + address: BASE_USDC, + functionName: "authorizationState", + args: [first.typedData.message.from, first.typedData.message.nonce], + blockNumber: 122n, + }), + ); + expect(f.client.operationV2.mock.calls.some(([, mode]) => mode === "abandon")).toBe(false); + expect(f.client.prepareV2).toHaveBeenCalledTimes(2); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + expect(await spent(f)).toBe("100000000"); + }); + + it("releases an unused funding reservation from its original UTC day", async () => { + const { f, first } = await signedFunding(false, true); + const tomorrow = new Date("2026-10-27T12:00:00Z"); + const timestamp = BigInt(tomorrow.getTime() / 1000); + const next = renewedIntent(first, timestamp); + serveAuthorizedFunding(f, next); + authorizationState(f, false); + f.rpc.getBlock.mockResolvedValue({ timestamp, number: 122n, hash: zeroHash }); + + const rerun = createTaskV2Executor({ ...f.options, now: () => tomorrow }); + await expect(rerun(fund(f))).resolves.toMatchObject({ ok: true }); + expect(await spent(f)).toBe("0"); + expect((await readSpendLedger(f.input.ledgerPath, tomorrow, f.input.wallet)).spentAtomic).toBe( + "100000000", + ); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + }); + + it.each(["used", "still live", "at expiry", "reorg", "RPC error"] as const)( + "keeps signed funding without a hosted operation when USDC proof is %s", + async (outcome) => { + const { f, first, journal } = await signedFunding(false); + const rerun = twoHoursLater(f); + const expiry = BigInt(first.typedData.message.validBefore); + if (outcome === "still live" || outcome === "at expiry") + f.rpc.getBlock.mockResolvedValueOnce({ + timestamp: outcome === "at expiry" ? expiry : expiry - 1n, + number: 122n, + hash: zeroHash, + }); + if (outcome === "reorg") + f.rpc.getBlock + .mockResolvedValueOnce({ timestamp: expiry + 1n, number: 122n, hash: zeroHash }) + .mockResolvedValueOnce({ + timestamp: expiry + 1n, + number: 122n, + hash: `0x${"ab".repeat(32)}`, + }); + authorizationState(f, outcome === "RPC error" ? new Error("offline") : outcome === "used"); + + await expect(rerun(fund(f))).rejects.toMatchObject({ + message: expect.stringContaining("Nothing new was signed. Try again later."), + }); + expect(f.client.operationV2).not.toHaveBeenCalled(); + expect(f.client.prepareV2).toHaveBeenCalledTimes(1); + if (outcome === "reorg") + expect(f.rpc.getBlock.mock.calls).toEqual([ + [{ blockNumber: 122n }], + [{ blockNumber: 122n }], + ]); + expect(await f.pending.preparation(V2_WRITE_ORDER, FUND_VERB)).toEqual(journal); + nothingLeftTheMachine(f); + expect(await spent(f)).toBe("100000000"); + }, + ); + + it("proves expiry and renews after a crash between reserving spend and marking the signature", async () => { + const { f, first } = await signedFunding(false, false, false); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + authorizationState(f, false); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(f.rpc.readContract).toHaveBeenCalledWith( + expect.objectContaining({ functionName: "authorizationState", blockNumber: 122n }), + ); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + expect(await spent(f)).toBe("100000000"); + }); + + it("releases an expired legacy funding reservation without a task key", async () => { + const f = onBase(await fixture("v2-fund"), READINESS_V2_ONLY); + f.input.policy = { maxPerTaskUsd: 100, approveAboveUsd: 100 }; + f.input.caps = { perCallAtomic: "1", perDayAtomic: "100000000" }; + const first = fundingIntent(8453, BASE_USDC); + await f.pending.putPreparation(V2_WRITE_ORDER, FUND_VERB, { + idempotencyKey: V2_WRITE_OPERATION, + inputs: { action: "fund" }, + preparedV2: first, + }); + await reserveSpend(100000000n, f.input.caps, { + kind: "escrow-funding", + ledgerPath: f.input.ledgerPath, + wallet: f.input.wallet, + reservationId: V2_WRITE_OPERATION, + now: f.options.now!(), + maxPerTaskAtomic: 100000000n, + }); + const next = renewedIntent(first); + serveAuthorizedFunding(f, next); + authorizationState(f, false); + + await expect(twoHoursLater(f)(fund(f))).resolves.toMatchObject({ ok: true }); + expect(f.rpc.readContract).toHaveBeenCalledWith( + expect.objectContaining({ functionName: "authorizationState", blockNumber: 122n }), + ); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(next.typedData); + expect(await spent(f)).toBe("100000000"); + }); + + it("reuses a signed funding authorization within its window", async () => { + const { f, first } = await signedFunding(true); + await expect(f.execute(fund(f))).resolves.toMatchObject({ ok: true }); + expect(f.client.operationV2.mock.calls.some(([, mode]) => mode === "abandon")).toBe(false); + expect(f.client.prepareV2).toHaveBeenCalledTimes(1); + expect(f.typedSign).toHaveBeenCalledExactlyOnceWith(first.typedData); + expect(await spent(f)).toBe("100000000"); + }); it("does not sign a reserved funding authorization for the first time while Tasks is unavailable", async () => { const f = onBase(await fixture("v2-fund"), READINESS_V2_ONLY); @@ -3217,6 +3716,7 @@ describe("a rerun of an operation that already signed something", () => { expect(await journalKey(f)).toBe(key); expect(f.client.prepareV2).toHaveBeenCalledTimes(1); expect(f.typedSign).toHaveBeenCalledTimes(1); + expect(f.client.operationV2.mock.calls.some(([, mode]) => mode === "abandon")).toBe(false); // The node holds it as mined: the rerun reports it and finishes. nodeHoldsItAsMined(f); expect(await rerun(fund(f))).toMatchObject({ @@ -3278,30 +3778,8 @@ describe("a rerun of an operation that already signed something", () => { expect(await journalKey(f)).toBe(key); // Two hours later the wallet is topped up. vAPI hands out a new authorization. walletHolds(f, 1_000_000_000n); - const message = { - ...first.typedData.message, - validAfter: (NOW_SECONDS + 7199n).toString(), - validBefore: (NOW_SECONDS + 7500n).toString(), - nonce: `0x${"34".repeat(32)}`, - }; - const second = { ...first, typedData: { ...first.typedData, message } }; - f.client.prepareV2.mockResolvedValue(second); - f.client.confirmV2Signature.mockImplementation( - async (_id: string, _op: string, signature: `0x${string}`) => { - f.prepared.operation.plan.data = encodeFunctionData({ - abi: escrowV2Abi, - functionName: "fundWithAuthorization", - args: [ - account.address, - BigInt(message.validAfter), - BigInt(message.validBefore), - message.nonce as `0x${string}`, - signature, - ], - }); - return f.prepared; - }, - ); + const second = renewedIntent(first); + serveAuthorizedFunding(f, second); expect(await twoHoursLater(f)(fund(f))).toMatchObject({ ok: true }); expect(f.client.prepareV2).toHaveBeenCalledTimes(2); const keys = ( @@ -3313,20 +3791,6 @@ describe("a rerun of an operation that already signed something", () => { expect(f.typedSign).toHaveBeenCalledWith(second.typedData); expect(await spent(f)).toBe("100000000"); }); - it("keeps an authorization that was signed, also after its window", async () => { - const f = onBase(await fixture("v2-fund"), READINESS_V2_ONLY); - authorizedFunding(f, 8453, BASE_USDC); - // Signed and counted; the upload is never answered, so no transaction exists. - f.client.confirmV2Signature.mockRejectedValueOnce(new Error("socket hang up")); - await expect(f.execute(fund(f))).rejects.toMatchObject({ code: "chain_error" }); - const key = await journalKey(f); - // The ledger is lost as well: the journal alone remembers the signature. - await rm(f.input.ledgerPath); - await expect(twoHoursLater(f)(fund(f))).rejects.toMatchObject({ code: "v2_plan_mismatch" }); - expect(await journalKey(f)).toBe(key); - expect(f.client.prepareV2).toHaveBeenCalledTimes(1); - expect(f.typedSign).toHaveBeenCalledTimes(1); - }); it("holds the unsigned steps of a started create, approve and fund sequence", async () => { const f = onBase(await fixture("v2-approve-usdc"), READINESS_V2_ONLY); freshFunding( diff --git a/packages/core/src/tasks/v2-execution.ts b/packages/core/src/tasks/v2-execution.ts index 425735e..fe71436 100644 --- a/packages/core/src/tasks/v2-execution.ts +++ b/packages/core/src/tasks/v2-execution.ts @@ -7,6 +7,7 @@ import { import { assertWithinTaskV2Limit } from "./v2-limits.js"; import { acceptedV2WorkerBond, + isV2FundingAuthorizationExpiredUnused, isV2ResolverAction, v2Read, verifyV2Target, @@ -30,6 +31,8 @@ import { z } from "zod"; import type { SpendCaps } from "../config.js"; import { escrowFundingDayRemainingAtomic, + hasTaskFundingReservation, + releaseTaskFundingReservation, reserveSpend, SpendCapError, taskReservedAtomic, @@ -41,6 +44,7 @@ import { TasksClientError } from "./client.js"; import { TaskOperationError, type TaskOperationContext } from "./operation-support.js"; import { formatBaseUnitsUsd, taskMoney, taskPolicyAtomic, type TaskMoney } from "./money.js"; import { + taskV2AbandonSchema, taskV2ActionSchema, taskV2ConsentSchema, taskV2OperationResponseSchema, @@ -110,6 +114,107 @@ const balanceAbi = parseAbi(["function balanceOf(address account) view returns ( const PAID_NOW_ACTIONS: readonly string[] = ["fund", "raise-dispute", "counter-evidence"]; /** Steps that reserve their spend in the ledger right before their first signature. */ const RESERVING_ACTIONS: readonly string[] = [...PAID_NOW_ACTIONS, "approve-bond"]; +const FUNDING_STEPS: readonly string[] = [ + "v2-create-escrow", + "v2-create-pool", + "v2-approve-usdc", + "v2-fund", +]; + +const expiredFundingPending = (code = "operation_pending") => + new TaskOperationError( + code, + "Could not confirm the earlier funding authorization expired unused. Nothing new was signed. Try again later.", + ); + +/** Returns the recovered operation, or clears the way for fresh funding after proof of expiry. */ +async function recoverExpiredFundingAuthorization( + options: TasksChainOptions, + input: { + orderId: string; + intent: z.infer; + operationId: string | undefined; + idempotencyKey: string; + }, + sleep: (ms: number) => Promise, +): Promise { + const { orderId, intent, operationId, idempotencyKey } = input; + if (!isAddressEqual(intent.signer, options.account.address)) throw expiredFundingPending(); + try { + if (operationId === undefined) { + if (await isV2FundingAuthorizationExpiredUnused(options, intent)) return; + } else { + const { client, account } = options; + const validate = (value: unknown) => { + const result = taskV2OperationResponseSchema.parse(value); + const op = result.operation; + if ( + result.orderId !== orderId || + op.id !== operationId || + !isAddressEqual(op.expectedActor, account.address) || + !FUNDING_STEPS.includes(op.step) || + (op.state === "confirmed" && op.step !== "v2-fund") + ) + throw expiredFundingPending(); + return result; + }; + // Replaying the original prepare key returns the hosted operation's current metadata + // without revalidating its expired plan. + const readCurrent = async () => + validate(await client.prepareV2!(orderId, { action: "fund" }, { idempotencyKey })); + let result = await readCurrent(); + let scannedStep: string | undefined; + for (let poll = 0; poll < 256; poll++) { + const { step, state, transactionHash } = result.operation; + if (state === "confirmed") return result; + const mode = + state === "submitted" + ? "reconcile" + : state === "prepared" && step !== "v2-fund" && scannedStep !== step + ? "recover" + : "abandon"; + if (mode === "recover") scannedStep = step; + try { + const response = await client.operationV2!( + operationId, + mode, + mode === "abandon" + ? { step, proof: "expired-authorization" } + : { step, ...(transactionHash ? { transactionHash } : {}) }, + { idempotencyKey: randomUUID() }, + ); + if (mode === "abandon") { + const abandonment = taskV2AbandonSchema.parse(response); + if (abandonment.orderId !== orderId) throw expiredFundingPending(); + if (abandonment.outcome === "abandoned") return; + result = validate(abandonment); + if (abandonment.outcome === "recovered" && step === "v2-fund") return result; + if (abandonment.outcome === "scanning") await sleep(1000); + } else { + result = validate(response); + if (mode === "reconcile" && result.operation.state === "submitted") await sleep(1000); + } + } catch (error) { + if (!(error instanceof TasksClientError) || error.serverCode !== "authorization_expired") + throw error; + // A receipt can advance the journal before the server rejects the next plan. + result = await readCurrent(); + if ( + mode !== "recover" && + result.operation.step === step && + result.operation.state === state + ) + throw error; + } + } + } + } catch (error) { + throw expiredFundingPending( + error instanceof TasksClientError ? (error.serverCode ?? error.code) : undefined, + ); + } + throw expiredFundingPending(); +} /** The API chooses V2, never a local calldata builder. Old adapters keep the V1 path. */ export async function taskUsesV2(context: Pick, id: string) { @@ -207,7 +312,7 @@ export function createTaskV2Executor(options: TasksChainOptions) { action.action === "approve-bond" ? "v2-approve-usdc" : `v2-${action.action}`; const allowedSteps = action.action === "fund" - ? ["v2-create-escrow", "v2-create-pool", "v2-approve-usdc", "v2-fund"] + ? FUNDING_STEPS : action.action === "raise-dispute" || action.action === "counter-evidence" ? ["v2-approve-usdc", finalStep] : [finalStep]; @@ -225,24 +330,37 @@ export function createTaskV2Executor(options: TasksChainOptions) { ...(excludeReservationId === undefined ? {} : { excludeReservationId }), }); const savedOperation = journal.operationId; - const savedTransaction = - savedOperation !== undefined && - (await Promise.all(allowedSteps.map((step) => pending.get(savedOperation, step)))).some( - (entry) => entry !== undefined, - ); + const savedSteps = + savedOperation === undefined + ? [] + : await Promise.all( + allowedSteps.map(async (step) => ({ + step, + entry: await pending.get(savedOperation, step), + })), + ); + const savedTransaction = savedSteps.some(({ entry }) => entry !== undefined); + const fundingReservation = { + ledgerPath: input.ledgerPath, + wallet: input.wallet, + taskKey: input.id, + reservationId: journal.idempotencyKey, + now: now(), + }; // A typed signature is recorded in the journal the moment it is made. const signedBefore = journal.signed === true; - const started = + let started = savedTransaction || (RESERVING_ACTIONS.includes(action.action) && (signedBefore || - (await reservedForTask()) !== (await reservedForTask(journal.idempotencyKey)))); + (action.action === "fund" + ? await hasTaskFundingReservation(fundingReservation) + : (await reservedForTask()) !== (await reservedForTask(journal.idempotencyKey))))); // The transaction of the last step is saved and the node holds it as mined. Such a // rerun signs nothing and sends nothing: it reports the transaction and waits for the // API. Limits, approval and the funding time checks guard a new signature, so a mined // step is not asked about them again, and its amount stays on the day it was reserved. - const savedFinal = - savedOperation === undefined ? undefined : await pending.get(savedOperation, finalStep); + const savedFinal = savedSteps.find(({ step }) => step === finalStep)?.entry; const mined = savedFinal && isAddressEqual(savedFinal.signer, account.address) && @@ -255,26 +373,54 @@ export function createTaskV2Executor(options: TasksChainOptions) { )?.status === "success" ? savedFinal : undefined; - // A funding authorization nobody signed is only an offer with an end time. Once that - // time has passed it can never be signed, so this run asks for a new one under a new - // key. An intent that was signed, reserved or followed by a signed transaction stays. + // The local clock can tell us when to check a started intent. Only proof from vAPI or + // the chain makes it safe to replace one. A saved funding transaction keeps its recovery path. + let recoveredIntent: z.infer | undefined; if ( - current && - !started && action.action === "fund" && + !savedFinal && + current && "kind" in current && current.kind === "eip712" ) { + const intent = taskV2IntentSchema.parse(current); + const requiresProof = started || savedOperation !== undefined; const end = z - .object({ validBefore: uint }) - .safeParse(taskV2IntentSchema.parse(current).typedData.message); + .object({ + validBefore: requiresProof ? z.union([uint, z.number().int().nonnegative()]) : uint, + }) + .safeParse(intent.typedData.message); if (end.success && BigInt(end.data.validBefore) * 1000n <= BigInt(now().getTime())) { - await pending.completePreparation(input.id, verb); - journal = { idempotencyKey: randomUUID(), inputs: action }; - await pending.putPreparation(input.id, verb, journal); - current = undefined; + const recovered = requiresProof + ? await recoverExpiredFundingAuthorization( + options, + { + orderId: input.id, + intent, + operationId: savedOperation, + idempotencyKey: journal.idempotencyKey, + }, + sleep, + ) + : undefined; + if (recovered) { + recoveredIntent = intent; + current = recovered; + } else { + // Retire this operation's saved steps and reservation before losing their keys. + if (savedOperation !== undefined) + for (const { step, entry } of savedSteps) + if (entry) await pending.remove(savedOperation, step); + if (requiresProof) await releaseTaskFundingReservation(fundingReservation); + await pending.completePreparation(input.id, verb); + journal = { idempotencyKey: randomUUID(), inputs: action }; + await pending.putPreparation(input.id, verb, journal); + current = undefined; + started = false; + } } } + const alreadyExecuted = mined !== undefined || recoveredIntent !== undefined; // The readiness document is an availability statement and names the hosted chain; it // is never a trust anchor (see availability.ts). Read it before anything is prepared, // signed, sent or counted against a cap, and gate only new work on it. @@ -306,18 +452,18 @@ export function createTaskV2Executor(options: TasksChainOptions) { // accepted for the task, or the hosted chain ID; the local pin for it decides trust. const resumed = taskV2OperationResponseSchema.safeParse(current); let resumedChainId: number | undefined; - if (resumed.success && !resumed.data.operation.plan) { + if (!recoveredIntent && resumed.success && !resumed.data.operation.plan) { resumedChainId = (await pending.v2Target?.(input.id))?.chainId ?? readiness?.chainId; if (resumedChainId === undefined) fail("The hosted operation carries no plan and its chain cannot be read."); } const target = await verifyV2Target( options, - resumedChainId === undefined ? current : { chainId: resumedChainId }, + recoveredIntent ?? (resumedChainId === undefined ? current : { chainId: resumedChainId }), view, action, undefined, - mined !== undefined, + alreadyExecuted, ); if (mined && mined.chainId !== target.chainId) fail("The saved transaction is for another chain than the verified task."); @@ -545,11 +691,14 @@ export function createTaskV2Executor(options: TasksChainOptions) { excludeReservationId: reservationKey, }) : 0n; - if (!mined && pays + alreadyReserved > taskPolicyAtomic(input.policy.maxPerTaskUsd)) + if ( + !alreadyExecuted && + pays + alreadyReserved > taskPolicyAtomic(input.policy.maxPerTaskUsd) + ) return { ok: false as const, reason: "policy.perTask", money, ...progress }; - if (!mined && pays > remaining) + if (!alreadyExecuted && pays > remaining) return { ok: false as const, reason: "policy.perDay", money, ...progress }; - if (!mined && pays > taskPolicyAtomic(input.policy.approveAboveUsd)) { + if (!alreadyExecuted && pays > taskPolicyAtomic(input.policy.approveAboveUsd)) { if (input.approval && "ask" in input.approval) { if ( !(await input.approval.ask({ @@ -727,6 +876,7 @@ export function createTaskV2Executor(options: TasksChainOptions) { if (result.operation.state === "prepared") await sleep(1000); continue; } + if (recoveredIntent) throw expiredFundingPending(); // Only a plan the API has just re-validated is signed. const plan = recovered.parsed.operation.plan; if (!plan) return fail("The hosted operation is prepared but carries no plan to sign."); diff --git a/packages/core/src/tasks/v2-plan-guard.ts b/packages/core/src/tasks/v2-plan-guard.ts index 4cc0b98..89218de 100644 --- a/packages/core/src/tasks/v2-plan-guard.ts +++ b/packages/core/src/tasks/v2-plan-guard.ts @@ -14,6 +14,7 @@ import { zeroHash, } from "viem"; import { z } from "zod"; +import { EIP3009_AUTHORIZATION_STATE_ABI } from "../authorization-state.js"; import { canonicalJson } from "./canonical-json.js"; import { getTrustedTasksDurations } from "./trusted-deployments.js"; import { DEFAULT_ACCEPTANCE_WINDOW_SECONDS } from "./scope-terms.js"; @@ -84,6 +85,14 @@ const tokenAbi = parseAbi([ "function name() view returns (string)", "function version() view returns (string)", ]); +const fundingAuthorizationMessage = z.strictObject({ + from: address, + to: address, + value: uint, + validAfter: uint, + validBefore: uint, + nonce: hash, +}); const authorizationTypes = { ReceiveWithAuthorization: [ { name: "from", type: "address" }, @@ -763,6 +772,45 @@ export async function verifyV2Target( }; } +/** Check the nonce at a confirmed block whose timestamp proves expiry. */ +export async function isV2FundingAuthorizationExpiredUnused( + options: TasksChainOptions, + intent: z.infer, +) { + const { domain, message: raw, primaryType } = intent.typedData; + const message = fundingAuthorizationMessage.parse(raw); + const pin = getTrustedTasksV2Deployment(domain.chainId, { + overrides: options.trustedV2Deployments, + env: options.env, + notice: options.onV2UntrustedOverride, + }); + if ( + primaryType !== "ReceiveWithAuthorization" || + !same(message.from, options.account.address) || + !same(domain.verifyingContract, pin.usdc) || + domain.name !== pin.usdcName || + domain.version !== pin.usdcVersion + ) + return false; + const rpc = options.rpcFor(domain.chainId); + if ((await rpc.getChainId()) !== domain.chainId) return false; + const confirmations = options.confirmations ?? 2; + if (!Number.isSafeInteger(confirmations) || confirmations < 1) return false; + const safe = (await rpc.getBlockNumber({ cacheTime: 0 })) - BigInt(confirmations - 1); + if (safe < 0n) return false; + const block = await rpc.getBlock({ blockNumber: safe }); + if (!block.hash || block.timestamp <= message.validBefore) return false; + return ( + (await rpc.readContract({ + address: domain.verifyingContract, + abi: EIP3009_AUTHORIZATION_STATE_ABI, + functionName: "authorizationState", + args: [message.from, message.nonce], + blockNumber: safe, + })) === false && (await rpc.getBlock({ blockNumber: safe })).hash === block.hash + ); +} + export async function verifyV2TypedData( target: VerifiedV2Target, intent: z.infer, @@ -784,16 +832,7 @@ export async function verifyV2TypedData( target.milestones.map((m) => m.deadline), block.timestamp, ); - const message = z - .strictObject({ - from: address, - to: address, - value: uint, - validAfter: uint, - validBefore: uint, - nonce: hash, - }) - .parse(typed.message); + const message = fundingAuthorizationMessage.parse(typed.message); // The hosted authorization starts at 0 and expires within the hour; only its end is bounded. if ( typed.primaryType !== "ReceiveWithAuthorization" || diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 6b61270..79d7f4c 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@vapi-network/mcp", - "version": "0.17.4", + "version": "0.17.5", "description": "Local, non-custodial MCP server for discovering and paying x402 APIs", "license": "Apache-2.0", "repository": { diff --git a/packages/mcp/src/server.test.ts b/packages/mcp/src/server.test.ts index 0452aae..27794e2 100644 --- a/packages/mcp/src/server.test.ts +++ b/packages/mcp/src/server.test.ts @@ -554,7 +554,7 @@ describe("Agent Cash MCP marketplace tools", () => { outcome: "paid", listing: { providerHost: "93.184.216.34", source: "direct" }, policy: { capsApplied: false }, - client: { name: "vapi-network", version: "0.17.4" }, + client: { name: "vapi-network", version: "0.17.5" }, }, ], }); diff --git a/packages/mcp/src/x402.test.ts b/packages/mcp/src/x402.test.ts index 4fcbfef..f211947 100644 --- a/packages/mcp/src/x402.test.ts +++ b/packages/mcp/src/x402.test.ts @@ -360,7 +360,7 @@ describe("x402 v2 challenge parsing", () => { outcome: "declined_policy", quote: { amountAtomic: "2500" }, policy: { capsApplied: true }, - client: { name: "vapi-network", version: "0.17.4" }, + client: { name: "vapi-network", version: "0.17.5" }, error: { code: "spend_cap_exceeded" }, }); expect(receipt).not.toHaveProperty("payer"); diff --git a/packages/sources/package.json b/packages/sources/package.json index 9c6b3ae..aecb98b 100644 --- a/packages/sources/package.json +++ b/packages/sources/package.json @@ -1,6 +1,6 @@ { "name": "@vapi-network/sources", - "version": "0.17.4", + "version": "0.17.5", "description": "Discovery source plugins for vAPI Network", "license": "Apache-2.0", "repository": { diff --git a/packages/vapi-network/SKILL.md b/packages/vapi-network/SKILL.md index 01f31f0..1eae877 100644 --- a/packages/vapi-network/SKILL.md +++ b/packages/vapi-network/SKILL.md @@ -1,6 +1,6 @@ --- name: vapi -version: 0.17.4 +version: 0.17.5 description: >- Pay for one API call at a time, in USDC, from the agent's own wallet. Search vAPI Call before writing a scraper, before asking the user to sign up for an diff --git a/packages/vapi-network/package.json b/packages/vapi-network/package.json index c379f7c..c245d62 100644 --- a/packages/vapi-network/package.json +++ b/packages/vapi-network/package.json @@ -1,6 +1,6 @@ { "name": "vapi-network", - "version": "0.17.4", + "version": "0.17.5", "mcpName": "io.github.vAPI-Network/vapi-network", "description": "One local wallet for discovering and paying every x402 API", "license": "Apache-2.0", diff --git a/scripts/pack-check.mjs b/scripts/pack-check.mjs index e8b145f..d9b4d83 100644 --- a/scripts/pack-check.mjs +++ b/scripts/pack-check.mjs @@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url"; import { build } from "esbuild"; -const EXPECTED_VERSION = "0.17.4"; +const EXPECTED_VERSION = "0.17.5"; const EXPECTED_PACKAGES = new Set([ "@vapi-network/core", "@vapi-network/sources", diff --git a/server.json b/server.json index d11b7fe..18b1f75 100644 --- a/server.json +++ b/server.json @@ -3,7 +3,7 @@ "name": "io.github.vAPI-Network/vapi-network", "title": "vAPI Network", "description": "vAPI Network: local, non-custodial MCP server to discover and pay x402 APIs in USDC on Base.", - "version": "0.17.4", + "version": "0.17.5", "websiteUrl": "https://vapinetwork.ai", "icons": [ { @@ -28,7 +28,7 @@ "registryType": "npm", "registryBaseUrl": "https://registry.npmjs.org", "identifier": "vapi-network", - "version": "0.17.4", + "version": "0.17.5", "transport": { "type": "stdio" },