Guides

Build a TypeScript agent

Pay x402 endpoints from any Node.js agent, with error handling and low-balance alerts.

Install

terminal
npm install @unslept/sdk viem

viem is a peer dependency used for signing and chain access. The SDK runs on Node.js 20 or newer.

Configure

The robinhood-chain preset reads its chain settings from the environment. The Developers page in the app shows these values for your account.

.env
UNSLEPT_AGENT_ACCOUNT=0x...            # your agent account
UNSLEPT_SIGNER_KEY=0x...               # the agent's signing key, from your secret store
UNSLEPT_CHAIN_ID=4663
UNSLEPT_RPC_URL=https://rpc.mainnet.chain.robinhood.com
UNSLEPT_USDG=0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168
UNSLEPT_ROUTER=0x1FeAB3B8f88FB0667B686fDCB0206194e88c984b
UNSLEPT_BUFFERS=0xcD853fb30eCe3134Cf21e2f47B9e23eaf965F40D

Pay a request

agent.ts
import { Unslept, UnsleptError } from "@unslept/sdk";
import { privateKeyToAccount } from "viem/accounts";

const unslept = new Unslept({
  agentAccount: process.env.UNSLEPT_AGENT_ACCOUNT,
  signer: privateKeyToAccount(process.env.UNSLEPT_SIGNER_KEY as `0x${string}`),
  network: "robinhood-chain",
  // Optional: report policy refusals so the owner's webhooks receive them.
  reportUrl: "https://www.unslept.xyz",
});

try {
  const res = await unslept.fetch("https://api.example.com/data", undefined, {
    maxAmount: 500_000n, // never pay more than 0.50 USDG for this call
  });
  console.log(await res.json());
  console.log(unslept.localPayments().at(-1)); // amount, fee, payee, transaction hash
} catch (e) {
  if (e instanceof UnsleptError) console.error(e.code, e.message);
  else throw e;
}

unslept.fetch takes the same arguments as the standard fetch, plus options. If the server does not answer 402, nothing is paid and you get the response as usual.

Watch the balance

agent.ts
const stop = unslept.onLowBalance(
  (b) => console.warn("Low balance", b.net),
  { threshold: 5_000_000n, intervalMs: 60_000 }, // below 5 USDG, checked every minute
);

For alerts that reach you even when the agent is offline, register a webhook instead. See Webhooks.

Amounts

All amounts are atomic USDG units as bigint. USDG has 6 decimals, so 1_000_000n is 1 USDG and 10_000n is 0.01 USDG.