cred402/scripts/near_spend_guard_deploy.ts
caelum0x f40b54c983 feat(near-spend-guard): close the revolving-credit demo gap with top_up_allowance
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>
2026-11-05 19:33:05 +03:00

117 lines
4.9 KiB
TypeScript

/**
* near_spend_guard_deploy.ts — deploy the SpendGuard contract
* (contracts-near/spend_guard) to a fresh NEAR Testnet account, fully
* programmatically.
*
* The hackathon plan's own pre-work rehearsal found that `cargo near
* create-dev-account` and `cargo near deploy ... sign-with-keychain send`
* are both fully interactive (they refuse piped stdin), so this script
* drives the real deploy via `near-api-js` directly instead of shelling out
* to that CLI:
* 1. Generate a fresh ed25519 keypair locally (no network call).
* 2. Create a brand-new named `*.testnet` account for free via the
* public, non-captcha faucet API (`POST
* https://helper.testnet.near.org/account`) — the same endpoint
* already proven to work for named subaccounts in this repo's NEAR
* x402 verification pass (see `plans/cred402.md`, tx
* `C1LNxQFEaR2AQj79U9WzToiB1eY86jwzmxoHKvr9W7jk`).
* 3. Deploy the built wasm (`cargo near build non-reproducible-wasm`
* output) to that account.
* 4. Call `new({ admin: <account_id> })` to initialize contract state.
*
* npm run near:spend-guard:deploy
*
* Credentials are written to `.secrets/near_spend_guard_credentials.json`
* (gitignored, mode 0600) — nothing here is a secret baked into source.
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { randomBytes } from "node:crypto";
import { Account, JsonRpcProvider, KeyPair } from "near-api-js";
// See `lib/x402/near_networks.ts::DEFAULT_NEAR_RPC_URL` for why this
// defaults to FastNear rather than NEAR's own now-rate-limited legacy
// public RPC (`rpc.testnet.near.org`, confirmed live 2026-11-05).
const RPC_URL = process.env.CRED402_NEAR_RPC_URL?.trim() || "https://rpc.testnet.fastnear.com";
const FAUCET_URL = "https://helper.testnet.near.org/account";
const SECRETS_DIR = join(process.cwd(), ".secrets");
const OUT_PATH = join(SECRETS_DIR, "near_spend_guard_credentials.json");
const WASM_PATH = join(process.cwd(), "contracts-near/spend_guard/target/near/spend_guard.wasm");
function randomAccountSuffix(): string {
return randomBytes(5).toString("hex");
}
async function createTestnetAccount(accountId: string, publicKey: string): Promise<void> {
const res = await fetch(FAUCET_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ newAccountId: accountId, newAccountPublicKey: publicKey }),
});
const body = await res.text();
if (!res.ok) {
throw new Error(`faucet account creation for ${accountId} failed (HTTP ${res.status}): ${body}`);
}
console.log(`faucet response for ${accountId}: ${body.slice(0, 200)}`);
}
async function main(): Promise<void> {
if (!existsSync(WASM_PATH)) {
throw new Error(
`${WASM_PATH} not found — run \`cd contracts-near/spend_guard && cargo near build non-reproducible-wasm\` first`,
);
}
if (existsSync(OUT_PATH) && !process.argv.includes("--force")) {
const existing = JSON.parse(readFileSync(OUT_PATH, "utf8")) as { account_id: string };
console.log(
`Credentials already exist at ${OUT_PATH} for ${existing.account_id} — pass --force to deploy a fresh contract account instead.`,
);
console.log(`CRED402_NEAR_SPEND_GUARD_CONTRACT=${existing.account_id}`);
return;
}
mkdirSync(SECRETS_DIR, { recursive: true });
const keyPair = KeyPair.fromRandom("ed25519");
const accountId = `spendguard-${randomAccountSuffix()}.testnet`;
const publicKey = keyPair.getPublicKey().toString();
console.log(`Creating real NEAR Testnet account ${accountId} via the public faucet (no owner credential used)...`);
await createTestnetAccount(accountId, publicKey);
const provider = new JsonRpcProvider({ url: RPC_URL });
const account = new Account(accountId, provider, keyPair.toString());
const wasm = readFileSync(WASM_PATH);
console.log(`Deploying ${wasm.length} bytes of real contract wasm to ${accountId} on ${RPC_URL}...`);
const deployResult = await account.deployContract(new Uint8Array(wasm));
console.log("deploy tx:", JSON.stringify(deployResult, null, 2).slice(0, 1000));
console.log(`Calling new({ admin: "${accountId}" }) to initialize contract state...`);
const initResult = await account.callFunction({
contractId: accountId,
methodName: "new",
args: { admin: accountId },
gas: 100_000_000_000_000n,
});
console.log("init result:", initResult);
const credentials = {
account_id: accountId,
public_key: publicKey,
private_key: keyPair.toString(),
network: "testnet",
rpc_url: RPC_URL,
};
writeFileSync(OUT_PATH, JSON.stringify(credentials, null, 2), { mode: 0o600 });
console.log("");
console.log(`Real deploy complete. Credentials written to ${OUT_PATH} (gitignored).`);
console.log(`CRED402_NEAR_SPEND_GUARD_CONTRACT=${accountId}`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});