Skip to Content
KryptWarden Developers
Guides

Pay with the SDK

Give your agent a fetch() that pays x402 APIs within its policy.

Install

npm install @kryptwarden/sdk

Node.js 20 or newer. The package is ESM only.

Create a client

import { createKryptWarden } from "@kryptwarden/sdk";

const kw = createKryptWarden({
  walletAddress: process.env.KW_WALLET_ADDRESS!, // your smart wallet, C…
  agentSecretKey: process.env.KW_AGENT_SECRET_KEY!, // from keygen, S…
  network: "stellar:testnet",
});

On Testnet that's all the configuration you need. The SDK uses the public Soroban RPC, Circle's Testnet USDC and the hosted relayer at pay.kryptwarden.xyz. See Configuration for every option.

Make paid requests

kw.fetch() takes the same arguments as fetch():

const res = await kw.fetch("https://demo-apis.kryptwarden.xyz/paid/search?q=soroban");
const data = await res.json();

If the server answers 402 Payment Required, the SDK:

  1. reads the price, recipient and asset from the challenge,
  2. reads the agent's live policy from the wallet,
  3. refuses straight away if the seller isn't allowed or the budget would be exceeded, and records the attempt on-chain,
  4. pays directly if the amount is within the auto-approve limit,
  5. otherwise opens a hold and waits for the owner, then pays,
  6. retries the request with the payment and returns the paid response.

Requests that don't return 402 pass through untouched.

Handle the outcomes

Policy refusals throw KryptWardenPaymentError. Everything else (DNS failures, a 500 from the seller) behaves like normal fetch.

import { KryptWardenPaymentError } from "@kryptwarden/sdk";

try {
  const res = await kw.fetch(url);
  return await res.json();
} catch (err) {
  if (!(err instanceof KryptWardenPaymentError)) throw err;

  switch (err.code) {
    case "REJECTED_BUDGET":
      return { skipped: true, reason: "daily budget reached; try tomorrow (UTC)" };
    case "REJECTED_SELLER":
      return { skipped: true, reason: `${err.seller} isn't an approved seller` };
    case "HOLD_DENIED":
    case "HOLD_EXPIRED":
      return { skipped: true, reason: `owner didn't approve ${err.amountUsdc} USDC` };
    default:
      throw err; // paused, revoked, expired, relayer trouble
  }
}

The full list is in Errors.

Waiting on holds

A payment above the auto-approve limit blocks until the owner decides, up to the hold timeout (10 minutes by default). Two options help:

const kw = createKryptWarden({
  walletAddress,
  agentSecretKey,
  // tell someone a decision is needed
  onHoldCreated: (h) => notify(`Approve ${h.amountUsdc} USDC to ${h.seller}? Hold #${h.holdId}`),
  // give up sooner than the on-chain timeout (fails closed with HOLD_EXPIRED)
  maxHoldWaitMs: 2 * 60_000,
});

If your agent shouldn't block, run the call in the background and carry on with other work.

Check the remaining budget

const s = await kw.getSummary();
const left = Number(s.remainingBudgetStroops) / 1e7;
console.log(`${left} USDC left today, ${s.activeHoldCount} holds open`);

Use it to plan: skip optional paid calls when the budget is low, instead of letting them fail.

Use it with an agent framework

kw.fetch is a plain function, so give it to anything that accepts a custom fetch. For example, as a tool for an LLM agent:

const tools = {
  paid_search: async ({ q }: { q: string }) => {
    const res = await kw.fetch(
      `https://demo-apis.kryptwarden.xyz/paid/search?q=${encodeURIComponent(q)}`,
    );
    return res.json();
  },
};

Return policy errors to the model as normal tool results (as in Handle the outcomes) so it can adapt instead of crashing.

On this page