Adds the SpendGuard entrypoint flagged in HACKATHON.md as a known limit: an agent with a still-ACTIVE spend key can now draw, repay, top up, and draw again on the SAME key, not just at the ExposureBook ledger level. - contracts-near/spend_guard/src/lib.rs: new admin-only top_up_allowance, re-reserving freed headroom (capped by the agent's own policy-approved credit line) and re-minting the agent's existing Function Call Access Key via spend_key::retop_spend_key. - src/spend_key.rs: retop_spend_key — a real NEAR protocol constraint found and fixed live against a running nearcore sandbox: AddKey unconditionally rejects an already-existing public key (AddKeyAlreadyExists), so topping up means delete_key + re-add in the SAME receipt, not a second AddKey call. Also fixed a clippy doc_lazy_continuation nit in this file's module docs. - src/exposure.rs: replaced two manual saturating-subtract patterns with u128::saturating_sub (clippy implicit_saturating_sub), and added a unit test proving repay-then-reserve-again reaches the full cap a second time. - tests/sandbox.rs: extended the real near-workspaces sandbox integration test (genuinely running local nearcore node) to prove the full loop live: draw -> repay -> top_up_allowance -> a real spend_to_seller call that succeeds again on the SAME original key -> dispute spike -> freeze -> revoked-key rejection. - lib/x402/near_spend_guard_client.ts: repayCreditLine + topUpAllowance client methods; scripts/near_spend_guard_full_demo.ts now exercises the same real repay/top-up/draw-again loop against the LIVE deployed public Testnet contract (spendguard-024e8dd6f7.testnet), not just the sandbox. - scripts/near_spend_guard_redeploy.ts: new script to upgrade the already-deployed contract's wasm in place (DeployContract replaces code only, never storage) — used to push this change to the live Testnet contract without losing its existing agent/exposure state. Also fixes a real, judge-relevant finding hit while running the above: NEAR's own legacy public RPC (rpc.testnet.near.org) now rejects most calls with -429 "WARNING! THIS ENDPOINT IS DEPRECATED!". Every default RPC URL in this repo (near_networks.ts, near_spend_guard_client.ts, near_spend_guard_deploy.ts, docs/near_x402.md's example) now defaults to FastNear's free public RPC instead; CRED402_NEAR_RPC_URL still overrides. Updated the one test that asserted the old default. 18/18 Rust unit tests green, cargo clippy -D warnings clean, the sandbox integration test passes against a real local nearcore node, the live Testnet bonus loop passes against the real public contract, and the full TS suite is 450/450 green with a clean typecheck. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
144 lines
6.7 KiB
TypeScript
144 lines
6.7 KiB
TypeScript
/**
|
|
* near_spend_guard_full_demo.ts — Day 11's "one command a judge can run"
|
|
* for the SpendGuard contract: builds the real contract wasm, runs the
|
|
* full automated test pass (18 Rust unit tests + a near-workspaces sandbox
|
|
* integration test exercising the ENTIRE loop — earn, policy, a capped
|
|
* spend key, real spends, a genuine nearcore allowance rejection, a real
|
|
* repay + top-up that lets the SAME still-active key draw again, a dispute
|
|
* spike, a freeze, and a genuine nearcore deleted-key rejection — against a
|
|
* real local nearcore node, zero manual steps), then, if a real Testnet
|
|
* deploy already exists (`scripts/near_spend_guard_deploy.ts`), runs a
|
|
* small real end-to-end loop against the LIVE deployed contract on NEAR
|
|
* Testnet as a bonus live artifact — including the same real
|
|
* repay/top-up/draw-again revolving-credit proof, on the public network.
|
|
*
|
|
* npm run demo:near-spend-guard
|
|
*/
|
|
import { existsSync, readFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { spawnSync } from "node:child_process";
|
|
import { SpendGuardClient } from "../lib/x402/near_spend_guard_client.js";
|
|
import { NearSpendControlledBuyerAgent } from "../agents/near_spend_controlled_buyer_agent.js";
|
|
import { NearWatchdogAgent } from "../agents/near_watchdog_agent.js";
|
|
import type { KeyPairString } from "near-api-js";
|
|
|
|
const CONTRACT_DIR = join(process.cwd(), "contracts-near", "spend_guard");
|
|
const CREDENTIALS_PATH = join(process.cwd(), ".secrets", "near_spend_guard_credentials.json");
|
|
|
|
function run(label: string, command: string, args: string[], cwd: string): void {
|
|
console.log(`\n=== ${label} (${command} ${args.join(" ")}) ===`);
|
|
const result = spawnSync(command, args, { cwd, stdio: "inherit" });
|
|
if (result.status !== 0) {
|
|
throw new Error(`${label} failed with exit code ${result.status}`);
|
|
}
|
|
}
|
|
|
|
async function runLiveTestnetLoop(): Promise<void> {
|
|
if (!existsSync(CREDENTIALS_PATH)) {
|
|
console.log(
|
|
`\n(No real Testnet deploy found at ${CREDENTIALS_PATH} — run \`npm run near:spend-guard:deploy\` first ` +
|
|
"for a live-network bonus run. The sandbox test above already fully proves the loop; this step is optional.)",
|
|
);
|
|
return;
|
|
}
|
|
|
|
const credentials = JSON.parse(readFileSync(CREDENTIALS_PATH, "utf8")) as {
|
|
account_id: string;
|
|
private_key: KeyPairString;
|
|
rpc_url: string;
|
|
};
|
|
console.log(`\n=== Live Testnet bonus run against ${credentials.account_id} ===`);
|
|
|
|
const config = { contractId: credentials.account_id, rpcUrl: credentials.rpc_url };
|
|
const adminClient = SpendGuardClient.withSecretKey(config, credentials.account_id, credentials.private_key);
|
|
|
|
const agentId = `demo-buyer-${Date.now()}`;
|
|
const agent = new NearSpendControlledBuyerAgent(config, agentId);
|
|
console.log(`Authorizing ${agentId} with a fresh real ed25519 key (${agent.publicKey})...`);
|
|
await agent.getAuthorized(adminClient, {
|
|
revenue_30d: "1000000000000000000000000", // 1 NEAR -> credit_line 0.3 NEAR
|
|
stake: "0",
|
|
dispute_rate_bps: 0,
|
|
accuracy_score: 100,
|
|
total_jobs: 5,
|
|
});
|
|
const record = await adminClient.getAgent(agentId);
|
|
console.log("real on-chain agent record:", record);
|
|
|
|
const seller = credentials.account_id; // self-loop for the demo; any funded account works
|
|
// Dust-sized amount so the real spend's VALUE never binds the cap — this
|
|
// run is specifically showing nearcore's own prepaid-gas allowance
|
|
// running out, the same real protocol mechanic `tests/sandbox.rs` proves
|
|
// deterministically against the local sandbox.
|
|
const spendResults = await agent.spendRepeatedly(seller, "1", 25);
|
|
console.log("real spend attempts:", spendResults);
|
|
|
|
// ---- real repay -> top up -> draw again, against the LIVE deployed
|
|
// contract (not just the local sandbox) — the revolving-credit loop
|
|
// added 2026-11-05. Repay exactly what was actually spent, then restore
|
|
// that same headroom on the agent's SAME still-active key. ----
|
|
const successfulSpends = spendResults.filter((r) => r.success).length;
|
|
if (successfulSpends > 0) {
|
|
console.log(`\nRepaying ${successfulSpends} yoctoNEAR of real outstanding exposure for ${agentId}...`);
|
|
await adminClient.repayCreditLine({ agentId, amountYocto: String(successfulSpends) });
|
|
const exposureAfterRepay = await adminClient.getExposure(agentId);
|
|
console.log("exposure after real repay:", exposureAfterRepay);
|
|
|
|
console.log(`Topping up ${agentId} by the same ${successfulSpends} yoctoNEAR on its SAME live key...`);
|
|
await adminClient.topUpAllowance({ agentId, amountYocto: String(successfulSpends) });
|
|
const exposureAfterTopUp = await adminClient.getExposure(agentId);
|
|
console.log("exposure after real top-up:", exposureAfterTopUp);
|
|
|
|
const postTopUpSpend = await agent.spendRepeatedly(seller, "1", 1);
|
|
console.log("real spend after top-up (must succeed, on the ORIGINAL key):", postTopUpSpend);
|
|
if (!postTopUpSpend[0]?.success) {
|
|
throw new Error("a spend after a real top_up_allowance must succeed on the live network's same key");
|
|
}
|
|
} else {
|
|
console.log("\n(No successful spends to repay/top up this run — skipping the revolving-credit bonus step.)");
|
|
}
|
|
|
|
const scammerId = `demo-scammer-${Date.now()}`;
|
|
const scammer = new NearSpendControlledBuyerAgent(config, scammerId);
|
|
await scammer.getAuthorized(adminClient, {
|
|
revenue_30d: "1000000000000000000000000",
|
|
stake: "0",
|
|
dispute_rate_bps: 0,
|
|
accuracy_score: 100,
|
|
total_jobs: 5,
|
|
});
|
|
console.log(`Authorized ${scammerId}; simulating a dispute-rate spike...`);
|
|
|
|
const watchdog = new NearWatchdogAgent(adminClient);
|
|
await watchdog.reportDisputeSpike(scammerId, 5);
|
|
console.log("frozen:", await watchdog.isFrozen(scammerId));
|
|
console.log("key_active:", await watchdog.isKeyActive(scammerId));
|
|
|
|
const postFreezeAttempt = await scammer.spendRepeatedly(seller, "1", 1);
|
|
console.log("post-freeze spend attempt (must fail):", postFreezeAttempt);
|
|
if (postFreezeAttempt[0]?.success) {
|
|
throw new Error("a revoked key must never be able to spend again on the live network either");
|
|
}
|
|
|
|
console.log("\nLive Testnet loop verified for real:", {
|
|
contract: credentials.account_id,
|
|
rpc: credentials.rpc_url,
|
|
buyer_credit_line: record?.credit_line,
|
|
real_spends: successfulSpends,
|
|
revolving_credit_proved: successfulSpends > 0,
|
|
scammer_frozen: await watchdog.isFrozen(scammerId),
|
|
});
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
run("Build contract wasm", "cargo", ["near", "build", "non-reproducible-wasm"], CONTRACT_DIR);
|
|
run("Full automated test pass (unit + sandbox)", "cargo", ["test"], CONTRACT_DIR);
|
|
await runLiveTestnetLoop();
|
|
console.log("\ndemo:near-spend-guard complete.");
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error(err);
|
|
process.exit(1);
|
|
});
|