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
16 changes: 15 additions & 1 deletion src/routes/v1/byok.ts
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,21 @@ router.delete('/human/bind/:agentId', async (req: Request, res: Response) => {
if (!owner || owner.owner_id !== p.owner.id) {
return res.status(403).json({ error: 'not_owner', message: 'You do not currently own this agent.' });
}
return res.json(await revokeBinding(String(req.params.agentId)));
const agentId = String(req.params.agentId);
const revoked = await revokeBinding(agentId);
if (!revoked.ok) return res.json(revoked);
// R4: an unbind does not touch an on-chain USDC approval (wallet mode). Say what is still live.
Comment thread
DealAppSeo marked this conversation as resolved.
Resolved
const { approvalForAgentRow, rpcSpendChain } = require('../../services/agent-spend') as typeof import('../../services/agent-spend');
const { data: agentRow, error: agentErr } = await db.from('repid_agents').select('wallet_address').eq('id', agentId).maybeSingle();
// An unreadable OR MISSING agent row is "not checked", never "no wallet, so no approval" (Grok r2 on #1559).
// rpcSpendChain only builds a provider; nothing is read unless the row has a wallet.
const onchain_approval = await approvalForAgentRow(
rpcSpendChain(process.env.BASE_SEPOLIA_RPC_URL || 'https://sepolia.base.org'),
owner.human_wallet,
agentRow as { wallet_address?: string | null } | null,
Boolean(agentErr),
);
return res.json({ ...revoked, onchain_approval });
});

/** "My team of experts" — every agent this caller owns. */
Expand Down
83 changes: 83 additions & 0 deletions src/services/agent-spend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,86 @@ export async function executeSpend(chain: SpendChain, checked: Extract<CheckOutc
cap_after_usdc: after === null ? null : formatUsdc(after),
};
}

/**
* WHAT AN UNBIND LEAVES ON CHAIN (R4, 2026-11-16).
*
* Unbinding writes `revoked_at` on the binding and nothing else. In AGENT_SPEND_SOURCE=wallet the
* owner gave the agent's wallet a USDC approval, and an ERC-20 approval changes only when the
* OWNER's wallet calls approve (or the spender uses it up). So the approval outlives the unbind.
* This server refuses every spend by an unbound agent (routes/agent-spend.ts, not_bound), but the
* agent wallet's key is still custodied here, so "nothing can spend it" would be a claim about this
* code, not about the chain. The unbind answer therefore states the live allowance, read from the
* chain, and how to end it. Stake mode has no approval, so it reads 0.
*
* A failed read is NOT_CHECKED, never "0". [V 2026-11-16, block 59404267: every owner -> agent
* wallet pair on record, the one revoked binding included, reads 0; the E2E runs used stake mode.]
*/
export type UnbindApproval =
| { checked: true; live: false; allowance_usdc: string; note?: string }
| { checked: true; live: true; allowance_usdc: string; agent_wallet: string; statement: string; how_to_end: string }
| { checked: false; reason: string };

const UNBIND_READ_TIMEOUT_MS = 10_000;

export async function approvalAfterUnbind(
read: Pick<SpendChain, 'chainId' | 'allowance'>,
owner: string | null | undefined,
agentWallet: string | null | undefined,
): Promise<UnbindApproval> {
if (!agentWallet) return { checked: true, live: false, allowance_usdc: '0.0', note: 'This agent has no wallet, so no approval to it can exist.' };
if (!owner || !ethers.isAddress(owner) || !ethers.isAddress(agentWallet)) {
return { checked: false, reason: 'The owner or agent wallet on record is not an address, so the on-chain approval was not read.' };
}
let allowance: bigint;
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error(`no answer in ${UNBIND_READ_TIMEOUT_MS} ms`)), UNBIND_READ_TIMEOUT_MS);
});
const [chainId, a] = await Promise.race([Promise.all([read.chainId(), read.allowance(owner, agentWallet)]), timeout]);
if (chainId !== SPEND_CHAIN_ID) return { checked: false, reason: `The RPC answered for chain ${chainId}, not Base Sepolia, so the approval was not read.` };
allowance = a;
} catch (e: unknown) {
// Never echo the RPC error (Strix on #1559): ethers puts the request URL in its message, and a
// provider URL can carry an API key (https://<provider>/v2/<key>). The text goes to the server log.
const msg = (e as Error)?.message ?? String(e);
console.error('[agent-spend] unbind approval read failed:', msg);
const why = /no answer in \d+ ms/.test(msg) ? 'the RPC did not answer in time' : 'the RPC read failed';
return { checked: false, reason: `Could not read the approval from the chain: ${why}. It may still be live.` };
Comment thread
DealAppSeo marked this conversation as resolved.
Resolved
} finally {
clearTimeout(timer);
}
if (allowance === 0n) return { checked: true, live: false, allowance_usdc: '0.0' };
const wallet = ethers.getAddress(agentWallet);
return {
checked: true,
live: true,
allowance_usdc: formatUsdc(allowance),
agent_wallet: wallet,
statement:
`Unbinding does not change your on-chain USDC approval. Your wallet still allows this agent's wallet (${wallet}) ` +
`to move up to ${formatUsdc(allowance)} USDC. This server refuses every spend by an unbound agent, but the approval ` +
`itself stays live on Base Sepolia until your wallet sets it to 0.`,
how_to_end: `From your wallet, call USDC.approve(${wallet}, 0) on Base Sepolia (USDC ${USDC_BASE_SEPOLIA}).`,
};
}

/**
* The unbind answer for the agent row as the route read it. Only a row READ with no wallet means no
* approval can exist. A read error, or NO row at all, is NOT_CHECKED (Grok r2 on #1559: a missing row
* used to reach approvalAfterUnbind as a null wallet and answer "no wallet, 0" without reading
* anything). The binding's FK cascades from repid_agents, so a missing row means the agent was deleted
* between the owner read and this one; its wallet's approval may still be live.
*/
export async function approvalForAgentRow(
read: Pick<SpendChain, 'chainId' | 'allowance'>,
owner: string | null | undefined,
row: { wallet_address?: string | null } | null | undefined,
readFailed: boolean,
): Promise<UnbindApproval> {
if (readFailed || !row) {
return { checked: false, reason: "Could not read this agent's wallet, so the on-chain approval was not read. It may still be live." };
}
return approvalAfterUnbind(read, owner, row.wallet_address ?? null);
}
101 changes: 101 additions & 0 deletions tests/unbind-approval.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**
* R4 (2026-11-16): an unbind does not touch an on-chain USDC approval, so the unbind answer states it.
*
* WHY THIS IS NOT A TEST OF THE CHAIN. revokeBinding writes `revoked_at` and nothing else; an ERC-20
* approval changes only when the owner's wallet calls approve (or the spender uses it). So in wallet
* mode (AGENT_SPEND_SOURCE=wallet) the approval outlives the unbind by construction. What this file
* pins is that the unbind answer SAYS so, from a live read, and that a failed read is NOT_CHECKED,
* never "0". The chain here is a fake; nothing is read from a chain.
*/
import { approvalAfterUnbind, approvalForAgentRow } from '../src/services/agent-spend';

const OWNER = '0x' + 'aa'.repeat(20);
const AGENT = '0x' + 'bb'.repeat(20);
const chain = (allowance: bigint | Error, chainId = 84532n) => ({
chainId: async () => chainId,
allowance: async () => {
if (allowance instanceof Error) throw allowance;
return allowance;
},
});

test('wallet mode: an approval that outlives the unbind is stated, with the amount and how to end it', async () => {
const out = await approvalAfterUnbind(chain(2_500_000n), OWNER, AGENT);
expect(out).toMatchObject({ checked: true, live: true, allowance_usdc: '2.5' });
if (out.checked && out.live) {
expect(out.statement).toMatch(/does not change your on-chain USDC approval/);
expect(out.statement).toMatch(/2\.5 USDC/);
expect(out.how_to_end).toMatch(/approve\(0x[bB]{40}, 0\)/);
}
});

test('stake mode (no approval): reads 0 and says nothing is live', async () => {
await expect(approvalAfterUnbind(chain(0n), OWNER, AGENT)).resolves.toEqual({ checked: true, live: false, allowance_usdc: '0.0' });
});

test('a failed read is NOT_CHECKED and says it may still be live, never "0"', async () => {
const out = await approvalAfterUnbind(chain(new Error('rpc down')), OWNER, AGENT);
expect(out.checked).toBe(false);
if (!out.checked) expect(out.reason).toMatch(/may still be live/);
});

test('a failed read never echoes the RPC error, which carries the provider URL and any key in it (Strix on #1559)', async () => {
const err = new Error('server response 401 (request={ }, response={ }, error=null, info={ "requestUrl": "https://rpc.example.invalid/v2/NOT-A-REAL-KEY-123" })');
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
try {
const out = await approvalAfterUnbind(chain(err), OWNER, AGENT);
expect(out.checked).toBe(false);
const text = JSON.stringify(out);
expect(text).not.toMatch(/NOT-A-REAL-KEY-123|rpc\.example|https?:\/\//);
} finally {
spy.mockRestore();
}
});

test('the wrong chain is NOT_CHECKED', async () => {
const out = await approvalAfterUnbind(chain(5n, 1n), OWNER, AGENT);
expect(out).toMatchObject({ checked: false });
});

test('no owner wallet on record is NOT_CHECKED; an agent with no wallet can have no approval', async () => {
await expect(approvalAfterUnbind(chain(5n), null, AGENT)).resolves.toMatchObject({ checked: false });
await expect(approvalAfterUnbind(chain(5n), 'not-an-address', AGENT)).resolves.toMatchObject({ checked: false });
await expect(approvalAfterUnbind(chain(5n), OWNER, null)).resolves.toMatchObject({ checked: true, live: false });
});

test('a read that never answers times out to NOT_CHECKED', async () => {
jest.useFakeTimers();
try {
const hanging = { chainId: async () => 84532n, allowance: () => new Promise<bigint>(() => {}) };
const p = approvalAfterUnbind(hanging, OWNER, AGENT);
await jest.advanceTimersByTimeAsync(10_001);
await expect(p).resolves.toMatchObject({ checked: false });
} finally {
jest.useRealTimers();
}
});

describe('approvalForAgentRow: the agent row as the unbind route read it (Grok r2 on #1559)', () => {
const untouched = {
chainId: async (): Promise<bigint> => { throw new Error('the chain must not be read'); },
allowance: async (): Promise<bigint> => { throw new Error('the chain must not be read'); },
};

test('NO row is NOT_CHECKED, never "no wallet, 0", and reads no chain', async () => {
const out = await approvalForAgentRow(untouched, OWNER, null, false);
expect(out).toMatchObject({ checked: false });
if (!out.checked) expect(out.reason).toMatch(/may still be live/);
});

test('a read error is NOT_CHECKED and reads no chain', async () => {
await expect(approvalForAgentRow(untouched, OWNER, { wallet_address: AGENT }, true)).resolves.toMatchObject({ checked: false });
});

test('a row READ with no wallet is the one case that says no approval can exist', async () => {
await expect(approvalForAgentRow(untouched, OWNER, { wallet_address: null }, false)).resolves.toMatchObject({ checked: true, live: false });
});

test('a row with a wallet reads the chain', async () => {
await expect(approvalForAgentRow(chain(2_500_000n), OWNER, { wallet_address: AGENT }, false)).resolves.toMatchObject({ checked: true, live: true, allowance_usdc: '2.5' });
});
});
Loading