Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 { approvalAfterUnbind, 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 agent row is "not checked", never "no wallet, so no approval".
const onchain_approval = agentErr
? { checked: false as const, reason: `Could not read this agent's wallet, so the on-chain approval was not read. It may still be live.` }
: await approvalAfterUnbind(
rpcSpendChain(process.env.BASE_SEPOLIA_RPC_URL || 'https://sepolia.base.org'),
owner.human_wallet,
(agentRow as { wallet_address?: string | null } | null)?.wallet_address ?? null,
);
return res.json({ ...revoked, onchain_approval });
Comment thread
DealAppSeo marked this conversation as resolved.
Resolved
});

/** "My team of experts" — every agent this caller owns. */
Expand Down
59 changes: 59 additions & 0 deletions src/services/agent-spend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,62 @@ 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) {
return { checked: false, reason: `Could not read the approval from the chain: ${(e as Error)?.message ?? String(e)}. 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}).`,
};
}
63 changes: 63 additions & 0 deletions tests/unbind-approval.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* 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 } 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('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();
}
});
Loading