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>
68 lines
2.7 KiB
TypeScript
68 lines
2.7 KiB
TypeScript
/**
|
|
* near_spend_guard_redeploy.ts — upgrade the WASM code on the ALREADY-
|
|
* deployed SpendGuard Testnet contract (`.secrets/near_spend_guard_credentials.json`)
|
|
* without touching its existing on-chain state.
|
|
*
|
|
* Unlike `near_spend_guard_deploy.ts` (which creates a brand-new account),
|
|
* this redeploys code to the SAME account id so the contract's existing
|
|
* `AgentRecord`/`ExposureBook`/dispute-count storage survives untouched —
|
|
* real NEAR behavior: a `DeployContract` action only replaces the account's
|
|
* code, never its storage. Deliberately does NOT call `new(...)` again:
|
|
* `#[init]` without `ignore_state` panics ("Already initialized") on an
|
|
* account whose state already exists, which is exactly the safety property
|
|
* we want here — this script only ever upgrades code, never re-inits.
|
|
*
|
|
* npm run near:spend-guard:redeploy
|
|
*/
|
|
import { existsSync, readFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { Account, JsonRpcProvider, type KeyPairString } from "near-api-js";
|
|
|
|
const SECRETS_DIR = join(process.cwd(), ".secrets");
|
|
const CREDENTIALS_PATH = join(SECRETS_DIR, "near_spend_guard_credentials.json");
|
|
const WASM_PATH = join(process.cwd(), "contracts-near/spend_guard/target/near/spend_guard.wasm");
|
|
|
|
async function main(): Promise<void> {
|
|
if (!existsSync(CREDENTIALS_PATH)) {
|
|
throw new Error(`${CREDENTIALS_PATH} not found — run \`npm run near:spend-guard:deploy\` first`);
|
|
}
|
|
if (!existsSync(WASM_PATH)) {
|
|
throw new Error(
|
|
`${WASM_PATH} not found — run \`cd contracts-near/spend_guard && cargo near build non-reproducible-wasm\` first`,
|
|
);
|
|
}
|
|
|
|
const credentials = JSON.parse(readFileSync(CREDENTIALS_PATH, "utf8")) as {
|
|
account_id: string;
|
|
private_key: KeyPairString;
|
|
rpc_url: string;
|
|
};
|
|
|
|
const provider = new JsonRpcProvider({ url: credentials.rpc_url });
|
|
const account = new Account(credentials.account_id, provider, credentials.private_key);
|
|
|
|
const wasm = readFileSync(WASM_PATH);
|
|
console.log(
|
|
`Redeploying ${wasm.length} bytes of upgraded contract wasm to the EXISTING account ` +
|
|
`${credentials.account_id} (state preserved)...`,
|
|
);
|
|
const deployResult = await account.deployContract(new Uint8Array(wasm));
|
|
console.log("redeploy tx:", JSON.stringify(deployResult, null, 2).slice(0, 1000));
|
|
|
|
const admin = await account.provider.callFunction<string>({
|
|
contractId: credentials.account_id,
|
|
method: "admin",
|
|
args: {},
|
|
});
|
|
console.log(`Post-redeploy sanity check — admin() still returns: ${admin}`);
|
|
if (admin !== credentials.account_id) {
|
|
throw new Error(`unexpected admin() after redeploy: ${admin}`);
|
|
}
|
|
console.log("Redeploy complete. Existing agent/exposure state preserved.");
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error(err);
|
|
process.exit(1);
|
|
});
|