Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletions packages/core/src/tasks/v2-execution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
escrowV2Abi,
bountyEscrowV2Abi,
bountyPoolV1Abi,
bountyPoolFactoryV1Abi,
reviewerRegistryV2Abi,
} from "./v2-abi.js";
import { acceptedV2TermsHash } from "./v2-plan-guard.js";
Expand Down Expand Up @@ -2459,6 +2460,171 @@ function authorizedFunding(
return intent;
}

describe("a new clone funded by one authorization (hosted ERC-3009 funding)", () => {
// vAPI prepares the first funding of a new order as one ReceiveWithAuthorization to the
// clone's predicted address; the clone is created only after the signature is confirmed.
function newClone(f: Awaited<ReturnType<typeof fixture>>) {
let registered = false;
const original = f.rpc.readContract.getMockImplementation()!;
f.rpc.readContract.mockImplementation(async (call) => {
if (call.functionName === "isEscrow") return registered;
if (!registered && call.address?.toLowerCase() === state.escrow.toLowerCase())
throw new Error("Cannot read the escrow before creation");
return original(call);
});
f.rpc.waitForTransactionReceipt.mockImplementation(async () => {
registered = true;
return { status: "success" };
});
return { registered: () => registered };
}
it("predicts the clone from accepted terms, signs once, then creates and funds it", async () => {
const f = await fixture("v2-fund");
const intent = authorizedFunding(f);
const clone = newClone(f);
f.client.confirmV2Signature.mockImplementation(
async (_id: string, _op: string, signature: `0x${string}`) => {
f.prepared.operation.plan.to = FACTORY.toLowerCase() as Hex;
f.prepared.operation.plan.data = encodeFunctionData({
abi: escrowFactoryV2Abi,
functionName: "createAndFundWithAuthorization",
args: [
...creationArgs(),
account.address,
BigInt(intent.typedData.message.validAfter),
BigInt(intent.typedData.message.validBefore),
intent.typedData.message.nonce as `0x${string}`,
signature,
],
});
return f.prepared;
},
);
expect(await f.execute({ ...f.input, write: { action: "fund" } })).toMatchObject({
ok: true,
operation: { step: "v2-fund", state: "confirmed" },
});
expect(f.typedSign).toHaveBeenCalledTimes(1);
expect(f.sign).toHaveBeenCalledTimes(1);
expect(f.sign.mock.calls[0]![0]).toMatchObject({ to: FACTORY.toLowerCase() });
expect(clone.registered()).toBe(true);
});
it("funds a new open vAPI ID pool: one authorization, then create and fund", async () => {
const f = await fixture("v2-fund");
Object.assign(f.view.workOrder, {
terms: {
shape: "pool",
pool: {
rewardPerClaimBaseUnits: "20000000",
budgetBaseUnits: "100000000",
gate: "open",
verifier: "poster",
openCheck: "vapi-id",
},
},
market: { ...f.view.workOrder.market, deadlineAt: DEADLINE },
v2State: undefined,
});
const intent = authorizedFunding(f);
let registered = false;
const original = f.rpc.readContract.getMockImplementation()!;
f.rpc.readContract.mockImplementation(async (call) => {
if (call.functionName === "isPool") return registered;
if (!registered && call.address?.toLowerCase() === state.escrow.toLowerCase())
throw new Error("Cannot read the pool before creation");
if (call.functionName === "rewardPerClaim") return 20000000n;
if (call.functionName === "deadline") return BigInt(Date.parse(DEADLINE) / 1000);
if (call.functionName === "gate") return 1;
if (call.functionName === "verifier") return account.address;
if (call.functionName === "budget") return 100000000n;
return original(call);
});
f.rpc.waitForTransactionReceipt.mockImplementation(async () => {
registered = true;
return { status: "success" };
});
const create = encodeFunctionData({
abi: bountyPoolFactoryV1Abi,
functionName: "createPool",
args: [
account.address,
20000000n,
100000000n,
BigInt(Date.parse(DEADLINE) / 1000),
acceptedV2TermsHash(f.view as unknown as import("./types.js").GetOrderResponse, PIN, 0n),
1,
account.address,
keccak256(toHex(V2_WRITE_ORDER)),
],
});
let current = f.prepared;
const step = (name: "v2-create-pool" | "v2-fund", to: string, data: Hex) =>
(current = {
...current,
operation: {
...current.operation,
step: name,
plan: { ...current.operation.plan, step: name, to: to.toLowerCase() as Hex, data },
},
});
f.client.confirmV2Signature.mockImplementation(
async (_id: string, _op: string, signature: `0x${string}`) => {
step("v2-create-pool", POOL_FACTORY, create);
// vAPI returns the create step now and the authorized funding as the following step.
fundData = encodeFunctionData({
abi: bountyPoolV1Abi,
functionName: "fundWithAuthorization",
args: [
account.address,
BigInt(intent.typedData.message.validAfter),
BigInt(intent.typedData.message.validBefore),
intent.typedData.message.nonce as `0x${string}`,
signature,
],
});
return current;
},
);
let fundData: Hex = "0x";
f.client.operationV2.mockImplementation(async (_id, mode, body) => {
if (mode === "recover") return { ...current, recovered: false, scanComplete: true };
if (mode === "reconcile" && current.operation.step === "v2-create-pool")
return step("v2-fund", state.escrow, fundData);
return {
...current,
operation: {
...current.operation,
state: mode === "transaction" ? "submitted" : "confirmed",
transactionHash: (body as { transactionHash?: string }).transactionHash,
},
};
});
expect(await f.execute({ ...f.input, write: { action: "fund" } })).toMatchObject({
ok: true,
operation: { step: "v2-fund", state: "confirmed" },
});
expect(f.typedSign).toHaveBeenCalledTimes(1);
const [creation, funding] = f.sign.mock.calls.map(([tx]) => tx);
expect(f.sign).toHaveBeenCalledTimes(2);
expect(creation).toMatchObject({ to: POOL_FACTORY.toLowerCase() });
expect(funding).toMatchObject({ to: state.escrow });
});
it("refuses to sign when the pinned factory predicts another clone for the accepted terms", async () => {
const f = await fixture("v2-fund");
authorizedFunding(f);
newClone(f);
const original = f.rpc.readContract.getMockImplementation()!;
f.rpc.readContract.mockImplementation(async (call) =>
call.functionName === "predictEscrow" ? WORKER : original(call),
);
await expect(f.execute({ ...f.input, write: { action: "fund" } })).rejects.toThrow(
/prediction/u,
);
expect(f.typedSign).not.toHaveBeenCalled();
expect(f.sign).not.toHaveBeenCalled();
});
});

describe("Base mainnet: today's production readiness (configured: false)", () => {
it("parses the exact production body as unavailable on chain 8453", async () => {
const f = onBase(await fixture("v2-fund"), READINESS_UNAVAILABLE);
Expand Down
33 changes: 27 additions & 6 deletions packages/core/src/tasks/v2-plan-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ export type VerifiedV2Target = {
/** Verified escrow terms: the registered clone's terms(), or accepted creation terms. */
terms?: V2EscrowTerms;
milestones: Array<{ amount: bigint; deadline: bigint; status: number }>;
/**
* The contract whose MIN_WORK_TIME bounds funding deadlines: the factory implementation while
* the clone is not created yet (its code does not exist), otherwise the clone itself.
*/
deadlineSource?: Address;
/** Exact factory prediction inputs (predictEscrow / predictBountyEscrow / predictPool). */
creationArgs?: readonly unknown[];
};
Expand Down Expand Up @@ -563,9 +568,16 @@ export async function verifyV2Target(
verifyAcceptedCreation(options, view, pin, creationArgs, pool, chainId, fresh);
candidate = await predict(creationArgs);
}
// A first funding names a clone that does not exist yet: the approval of a fresh clone, or
// vAPI's ERC-3009 intent (one ReceiveWithAuthorization to the predicted clone, created only
// after the signature is confirmed). Derive the creation arguments from the accepted terms
// and the pinned factory's live fee, and trust only the factory's own prediction for them.
// An authorization can be redeemed only by its `to` contract, and that address exists only
// as the clone of exactly these arguments, so the signature is bound to the accepted order.
const signatureIntent = !plan && intent.success;
if (
action.action === "fund" &&
plan?.step === "v2-approve-usdc" &&
(plan?.step === "v2-approve-usdc" || signatureIntent) &&
(!candidate || !(await isRegistered(candidate)))
) {
fresh = await creationPolicy(rpc, pin, pool);
Expand All @@ -583,20 +595,27 @@ export async function verifyV2Target(
"The V2 target cannot be independently verified from this response. A registered target or verifiable funding creation terms are required.",
);
if (!(await isRegistered(candidate))) {
// The hosted signature intent has no frozen creation arguments: never sign
// a redeemable authorization to its unverified predicted address.
if (action.action !== "fund" || !plan || !creationArgs || !fresh)
// Only a first funding may name an unregistered clone, and only with creation arguments
// this client derived or checked itself (above): never sign toward an unverified address.
if (action.action !== "fund" || (!plan && !signatureIntent) || !creationArgs || !fresh)
return v2GuardFailure("The V2 target is not registered by the locally pinned factory.");
const expectedCreation = acceptedCreationArgs(options, view, pin, chainId, fresh);
if (canon(creationArgs) !== canon(expectedCreation))
return v2GuardFailure("Fresh funding inputs differ from locally accepted creation terms.");
verifyActor(action, options.account.address, address.parse(order.clientAddress));
const terms = pool ? undefined : escrowTermsSchema.parse(creationArgs[0]);
verifyBinding(candidate, terms?.termsHash ?? hash.parse(creationArgs[4]));
let deadlineSource: Address | undefined;
let freshMilestones: VerifiedV2Target["milestones"] = [];
if (!pool && !bounty) {
const implementation = address.parse(
await v2Read(rpc, factory, escrowFactoryV2Abi, "implementation"),
);
deadlineSource = implementation;
freshMilestones = z
.array(milestoneSchema)
.parse(creationArgs[1])
.map((m) => ({ amount: m.amount, deadline: m.deadline, status: 0 }));
if (
!same(await v2Read(rpc, implementation, escrowV2Abi, "FACTORY"), factory) ||
!same(await v2Read(rpc, implementation, escrowV2Abi, "USDC"), pin.usdc)
Expand Down Expand Up @@ -627,7 +646,9 @@ export async function verifyV2Target(
feeBp: fresh.feeBp,
termsHash: terms?.termsHash ?? hash.parse(creationArgs[4]),
...(terms ? { terms } : {}),
milestones: [],
// The accepted milestones, so the signing-block deadline check covers the new clone too.
milestones: freshMilestones,
...(deadlineSource ? { deadlineSource } : {}),
creationArgs,
};
}
Expand Down Expand Up @@ -759,7 +780,7 @@ export async function verifyV2TypedData(
if (!target.pool && !target.bounty)
await verifyFundingDeadlines(
target.rpc,
target.escrow,
target.deadlineSource ?? target.escrow,
target.milestones.map((m) => m.deadline),
block.timestamp,
);
Expand Down
Loading