Blog ·

Store a file for a cent from TypeScript. No account.

A TypeScript program with a USDC wallet stores, finds, reads and deletes a file over a REST API, paying per request with x402. The whole run cost $0.035.

What this is

At the end of this guide you have one TypeScript file, under 300 lines, that stores a file on Artefaktum, finds it by search, downloads it, checks the bytes and deletes it. There is no account and no API key: a wallet pays for each request. Our run of the whole walk-through cost $0.035, and the upload was one cent of that. The same guide exists in Python.

The payments run over x402, an open protocol built on the HTTP status 402 Payment Required: the server answers a request with a price, and the client repeats the request with a signed payment. The money is USDC, a token that tracks the US dollar, on Base, a low-fee network built on Ethereum. You write none of the protocol yourself. The official @x402/fetch package wraps fetch, and you call plain REST URLs, so what you learn here carries over to other APIs that speak x402.

These are the prices:

Operation Price Buys
Read: list, get, download $0.005 One request
Search $0.01 One request
Upload up to 10 MiB $0.01 30 days of storage
Upload up to 100 MiB $0.05 30 days of storage
Upload up to 1 GiB $0.50 30 days of storage
New version The upload band of its size At least 30 days from that upload
Extend The band of everything the artifact holds 30 more days
Complete an upload, delete Free A wallet signature, no payment

A band is a size tier: an upload costs the price of the smallest tier its size fits in.

The guide is written for a developer who is at home in TypeScript, has never used x402 and may never have held any crypto.

What you need

Node 24, or Node 22 from 22.18, or Node 23 from 23.6. These run a .ts file directly, so there is no build step. We recommend Node 24. Node 23.6 prints an experimental warning about type stripping, which you can ignore; our run was on Node 23.6 and printed it.

The official x402 client, in a new folder:

npm init -y
npm pkg set type=module
npm install --save-exact @x402/fetch@2.29.0 @x402/evm@2.29.0 @x402/extensions@2.29.0 viem@2.57.13

The four packages are @x402/fetch (it wraps fetch), @x402/evm (signing for Base), @x402/extensions (the sign-in that the free calls use) and viem (it turns the private key into an account). Keep the type=module line: without it the file fails on its first import with “Cannot use import statement outside a module”.

A wallet private key that holds a few cents of USDC on Base. Create a new wallet in any wallet app that supports Base and export its private key. Send it a dollar of USDC from an exchange or from another wallet, and choose Base as the network when you send. The wallet needs no ETH for fees: a payment here is an authorization that you sign, and the wallet sends no transaction itself. A facilitator, a service that checks the signed payment and submits it to the network, does that part. Artefaktum uses Coinbase’s.

Use a throwaway wallet that holds only what you are ready to spend. The key sits in an environment variable, and whoever has the key can spend everything in the wallet. Never use the key of a wallet that holds real savings, and do not put the key in a file you commit.

export WALLET_KEY=0x...   # the private key, 64 hex characters

The guide builds one file, pay.ts, block by block. Paste the blocks in the order they appear and run the file once, at the end. The output under each step is from our own run against production on Base mainnet on 15 November 2026, with the transaction hashes, the ids and the wallet address shortened.

The file starts with the imports and two constants:

import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, extname, join } from "node:path";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { createSIWxClientExtension } from "@x402/extensions/sign-in-with-x";
import { wrapFetchWithPayment, x402Client } from "@x402/fetch";
import { privateKeyToAccount } from "viem/accounts";

const BASE = process.env.ARTEFAKTUM_BASE ?? "https://api.artefaktum.dev";
const NETWORK = "eip155:8453"; // Base mainnet

See the price

A request without a payment costs nothing and tells you the price. Three small helpers come first. x402 headers are JSON, base64-encoded, and an amount is a whole number of millionths of a USDC.

/** x402 headers are JSON, base64-encoded. */
function decode(header: string) {
  return JSON.parse(Buffer.from(header, "base64").toString());
}

/** USDC has six decimals: an amount of 5000 is 0.005 USDC. */
function usdc(amount: string | number) {
  return String(Number(amount) / 1_000_000);
}

/** What a payment cost, in words. Unknown when the client did not tell us the amount. */
function priceText(amount: string | null) {
  return amount ? `${usdc(amount)} USDC` : "unknown";
}

Now ask for your list of projects with plain fetch, no wallet involved:

/** Ask without paying. The answer is 402, and its PAYMENT-REQUIRED header has the price. */
async function seePrice() {
  const response = await fetch(`${BASE}/v1/projects`);
  console.log(`GET /v1/projects → ${response.status}`);
  const header = response.headers.get("PAYMENT-REQUIRED");
  if (response.status !== 402 || !header) {
    throw new Error(`${BASE} did not answer 402 with a PAYMENT-REQUIRED header`);
  }
  const offer = decode(header).accepts[0];
  console.log(JSON.stringify(offer, null, 2));
  console.log(`price: ${usdc(offer.amount)} USDC on ${offer.network}`);
}
(node:24847) ExperimentalWarning: Type Stripping is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
== See the price ==
GET /v1/projects → 402
{
  "scheme": "exact",
  "network": "eip155:8453",
  "amount": "5000",
  "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  "payTo": "0xeccc9f03eb79c6a5b0fbd919f95656557e6a6173",
  "maxTimeoutSeconds": 60,
  "extra": {
    "name": "USD Coin",
    "version": "2"
  }
}
price: 0.005 USDC on eip155:8453

The first two lines are the warning that Node 23.6 prints before the program’s own output. The status is 402, and the PAYMENT-REQUIRED header carries an offer. Four of its fields matter here:

  • amount is the price in the smallest unit of the token. USDC has six decimals, so "5000" is $0.005.
  • network is where the payment happens. eip155:8453 is Base mainnet.
  • asset is the contract address of the token, here USDC on Base.
  • payTo is the address that receives the money, here Artefaktum’s.

Pay

To pay, the program needs your key. wallet() reads it from WALLET_KEY and stops with a usage line when it is not 64 hex characters. The program never prints the key.

/** The account of the private key in WALLET_KEY: 64 hex characters, 0x in front or not. */
function wallet() {
  const key = (process.env.WALLET_KEY ?? "").replace(/^0x/, "");
  if (/^[0-9a-fA-F]{64}$/.test(key)) {
    try {
      return privateKeyToAccount(`0x${key}`);
    } catch {
      // 64 hex characters, but not a key. The library's message would show them.
    }
  }
  console.error("usage: WALLET_KEY=0x<private key, 64 hex characters> node pay.ts [file]");
  process.exit(2);
}

makeClient() builds the fetch that pays. It registers two abilities: paying a price in USDC on Base, and signing in, which the free calls need later. Then it wraps fetch. From here on the client answers a 402 that names a price for you: it signs a payment for that price and repeats the request. Only a payment that the server refuses still comes back to your code as a 402.

The client pays whatever price the server quotes, which here is at most the price table above, so keep only small change in the wallet (that is the second reason for a throwaway wallet), especially before you point the same code at another API.

/** A fetch that answers a 402 by itself: it pays, or signs in, and repeats the call. */
function makeClient() {
  const account = wallet();
  console.log(`wallet: ${account.address}`);

  const client = new x402Client()
    // Paid routes: sign a USDC payment for the price the server names.
    .register(NETWORK, new ExactEvmScheme(account))
    // Free routes (complete, delete): sign a message that proves who we are. No money moves.
    .registerExtension(createSIWxClientExtension({ signers: [account] }));
  // Called each time the client signs a payment: keep the amount for the cost table.
  client.onAfterPaymentCreation(async (context) => {
    lastPrice = context.selectedRequirements.amount;
  });

  return wrapFetchWithPayment(fetch, client);
}

The program keeps four names at module level, and a type for the rows of the last one: the fetch that pays, the wallet’s project, the amount of the last payment and the list of what each call cost.

type Cost = { call: string; amount: string | null; transaction: string };

let pay: typeof fetch; // the fetch that pays; main() sets it
let projectId: string; // the wallet's project; main() sets it
let lastPrice: string | null = null; // the amount of the payment the client signed last
const costs: Cost[] = []; // one row per call, for the table at the end

Every API call goes through one function. It prints the status. A call that was paid for comes back with a PAYMENT-RESPONSE header, the receipt, and then the line also shows the amount and the hash of the transaction that moved the money.

/** Make one API call, print its result and its price, and return the JSON answer. */
async function call(method: string, path: string, body?: unknown): Promise<any> {
  lastPrice = null;
  const response = await pay(BASE + path, {
    method,
    headers: body === undefined ? undefined : { "content-type": "application/json" },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  let line = `${method} ${path} → ${response.status}`;
  const text = await response.text();
  if (!response.ok) {
    console.log(line);
    throw new Error(`${method} ${path} answered ${response.status}: ${text}`);
  }

  // A call that was paid for comes back with a PAYMENT-RESPONSE header: the receipt.
  const receipt = response.headers.get("PAYMENT-RESPONSE");
  if (receipt) {
    const transaction = decode(receipt).transaction;
    line += `  paid ${priceText(lastPrice)} tx ${transaction}`;
    costs.push({ call: `${method} ${path}`, amount: lastPrice, transaction });
  } else {
    costs.push({ call: `${method} ${path}`, amount: null, transaction: "" });
  }
  console.log(line);
  return text ? JSON.parse(text) : null;
}

The first paid call, made from main() further down, is the same request as before:

== Pay ==
wallet: 0xC89C…c7cf
GET /v1/projects → 200  paid 0.005 USDC tx 0x4271…b5be

This time the answer is 200 with the list of projects. There was no sign-up: a wallet’s first payment creates its account and a default project, and the program keeps that project’s id. The wallet is the account. Settling a payment on Base takes a moment, so a paid call is slower than a free one.

Store a file

The program stores the file you name on the command line, or a small text file that it writes itself. It reads the bytes before the first paid call, so a path that cannot be read costs nothing.

/** The file's bytes. Read before anything is paid, so a bad path costs nothing. */
async function readBytes(path: string) {
  try {
    return await readFile(path);
  } catch (error) {
    console.error(`cannot read ${path}: ${error instanceof Error ? error.message : error}`);
    process.exit(2);
  }
}
/** A small text file to store when the program is run without one. */
async function sampleFile() {
  const path = join(tmpdir(), "hello-x402.txt");
  await writeFile(path, `Stored over x402 at ${new Date().toISOString()}\n`);
  return path;
}

Storing takes three steps. Of the three, only the first costs money; checking afterwards that the file is ready costs a read per look.

Reserve. POST /v1/artifacts/uploads says what is coming: a name, a content type and a size. The price follows the size, and up to 10 MiB it is $0.01. The answer has the ids of the new artifact and its version, and a signed upload URL. Node has no table of content types of its own, so the program carries a short one.

const CONTENT_TYPES: Record<string, string> = {
  ".txt": "text/plain",
  ".md": "text/markdown",
  ".json": "application/json",
  ".csv": "text/csv",
  ".pdf": "application/pdf",
};

/** Reserve room for the file (paid). The answer has the new artifact's ids and an upload URL. */
async function reserveUpload(filename: string, data: Buffer) {
  return await call("POST", "/v1/artifacts/uploads", {
    project_id: projectId,
    filename,
    content_type: CONTENT_TYPES[extname(filename).toLowerCase()] ?? "application/octet-stream",
    size_bytes: data.length,
    title: filename,
    tags: ["x402-guide"],
  });
}

Send the bytes. They go straight to storage with a plain HTTP PUT to the signed URL. No wallet is involved and nothing is paid.

Complete. This call tells the server that the bytes are in place. It is free, but the server still has to know that the caller is the wallet that paid for the reservation. With no account and no API key, the proof is a signature. The route answers 402 with a challenge from sign-in-with-x, the x402 extension for proving which wallet you are, in place of a price. The client signs that one-time message with the wallet key and repeats the call. No money moves, so the line in the output has no paid part. The program sends the file’s sha256 with this call, to have something to compare the download with.

After that the server checks the stored bytes in the background, and the program asks for the artifact until its status is ready. Each look is a paid read at $0.005. The looks are 4 seconds apart and there are at most 10. In our run the file was ready on the first look.

/** Send the bytes to storage (free), complete the upload (free), wait until it is ready. */
async function storeFile(data: Buffer, reserved: any) {
  const artifactId: string = reserved.artifact.id;
  const versionId: string = reserved.artifact.version_id;

  // The bytes go straight to storage, to a signed URL. No wallet is involved.
  const upload = reserved.upload;
  const put = await fetch(upload.url, { method: "PUT", body: data, headers: upload.headers });
  console.log(`PUT the bytes to storage → ${put.status}`);
  if (!put.ok) throw new Error(`storage refused the bytes: ${put.status} ${await put.text()}`);

  // Completing is free: the server asks only for proof that we are the wallet that paid.
  // We send the file's sha256 with it, to compare with what we download later.
  await call("POST", `/v1/artifacts/${artifactId}/versions/${versionId}/complete`, {
    sha256: createHash("sha256").update(data).digest("hex"),
  });

  // The server checks the stored bytes in the background. Each look is a paid read.
  for (let look = 1; look <= 10; look += 1) {
    await new Promise((resolve) => setTimeout(resolve, 4000));
    const artifact = await call("GET", `/v1/artifacts/${artifactId}`);
    if (artifact.status === "ready") return;
    console.log(`status is ${artifact.status} (look ${look} of 10, each look is paid)`);
  }
  throw new Error("the artifact is not ready after 10 looks");
}
== Store a file ==
POST /v1/artifacts/uploads → 201  paid 0.01 USDC tx 0x1527…b4fb
PUT the bytes to storage → 200
POST /v1/artifacts/01a1e045-…/versions/01a1e045-…/complete → 200
GET /v1/artifacts/01a1e045-… → 200  paid 0.005 USDC tx 0xe8ce…12bb

The file is stored. The reservation cost one cent, and the look that found it ready cost half a cent.

Find it and read it back

A search costs $0.01. The program searches the wallet’s project for the file’s name, picks its own artifact out of the results and takes the sha256 that the server holds for it. The download call costs $0.005 and returns a signed URL, not the bytes. Fetching that URL is a plain GET, free, with no wallet involved. The program hashes what it gets and compares.

/** Search for the artifact (paid), download it (paid) and check the bytes. */
async function findAndRead(artifactId: string, query: string) {
  const found = await call("POST", "/v1/artifacts/search", {
    project_id: projectId,
    query,
    mode: "text",
    limit: 5,
  });
  const hit = found.items.find((item: any) => item.artifact.id === artifactId);
  if (!hit) throw new Error(`search for "${query}" did not find ${artifactId}`);
  const expected = hit.artifact.latest_version.sha256;

  // The download call returns a signed URL, not the bytes. Fetching that URL is free.
  const download = await call("GET", `/v1/artifacts/${artifactId}/download`);
  const stored = await fetch(download.url);
  console.log(`GET the bytes from storage → ${stored.status}`);
  if (!stored.ok) {
    throw new Error(`storage refused the download: ${stored.status} ${await stored.text()}`);
  }
  const data = Buffer.from(await stored.arrayBuffer());
  const actual = createHash("sha256").update(data).digest("hex");
  if (actual !== expected) throw new Error(`sha256 differs: stored ${expected}, downloaded ${actual}`);
  console.log(`downloaded ${data.length} bytes, sha256 matches`);
}
== Find it and read it back ==
POST /v1/artifacts/search → 200  paid 0.01 USDC tx 0x0b85…78bb
GET /v1/artifacts/01a1e045-…/download → 200  paid 0.005 USDC tx 0x4c29…ef7a
GET the bytes from storage → 200
downloaded 45 bytes, sha256 matches

The 45 bytes are the small text file the program wrote for itself.

Delete it

Deleting is free for the same reason completing is: the server needs to know that you own the artifact, and a signature from the wallet proves it.

/** Delete the artifact. Free: like complete, it needs a signature, not a payment. */
async function deleteArtifact(artifactId: string) {
  await call("DELETE", `/v1/artifacts/${artifactId}`);
}
== Delete it ==
DELETE /v1/artifacts/01a1e045-… → 202

main() ties the steps together. The delete sits in a finally: from the reservation on there is something to delete, whatever goes wrong after it. If the delete itself fails, the program says so and exits with status 1.

async function main() {
  // Check the key and read the file first: a mistake here should cost nothing.
  wallet();
  const path = process.argv[2] ?? (await sampleFile());
  const data = await readBytes(path);
  let deleted = true;

  console.log("== See the price ==");
  await seePrice();

  console.log("\n== Pay ==");
  pay = makeClient();
  try {
    // A wallet's first payment creates its account and a default project.
    const projects = await call("GET", "/v1/projects");
    projectId = projects.items[0].id;

    console.log("\n== Store a file ==");
    const reserved = await reserveUpload(basename(path), data);
    const artifactId: string = reserved.artifact.id;
    try {
      await storeFile(data, reserved);
      console.log("\n== Find it and read it back ==");
      await findAndRead(artifactId, basename(path));
    } finally {
      // From the reservation on there is something to delete, whatever went wrong.
      console.log("\n== Delete it ==");
      try {
        await deleteArtifact(artifactId);
      } catch (error) {
        deleted = false;
        console.error(`could not delete ${artifactId}: ${error instanceof Error ? error.message : error}`);
        console.error("it expires on its own after 30 days");
      }
    }
  } finally {
    console.log("\n== What it cost ==");
    printCosts();
  }
  if (!deleted) process.exit(1);
}

If you do not delete, nothing bad happens. An upload buys 30 days of storage. The artifact expires at the end of them and is removed, unless you extend it first: POST /v1/artifacts/{id}/extend buys 30 more days at the band of everything the artifact holds, which for a small file is the same cent again.

What it cost

The last function prints the calls the run made, the price of each and the transaction that paid for it. The table lists the calls that succeeded; a call that fails is not in it.

/** The calls this run made, what each one cost, and the transaction that paid for it. */
function printCosts() {
  const width = Math.max(4, ...costs.map((row) => row.call.length));
  console.log(`${"call".padEnd(width)} | price      | tx`);
  for (const row of costs) {
    const price = row.transaction ? priceText(row.amount) : "free";
    console.log(`${row.call.padEnd(width)} | ${price.padEnd(10)} | ${row.transaction}`);
  }
  const paid = costs.filter((row) => row.transaction).map((row) => row.amount);
  const total = paid.reduce((sum, amount) => sum + Number(amount ?? 0), 0);
  console.log(`total: ${usdc(total)} USDC in ${paid.length} payments`);
  if (paid.includes(null)) {
    console.log("the total leaves out the payments whose amount is unknown");
  }
}

Six more lines start the program, and the file is complete:

try {
  await main();
} catch (error) {
  console.error(`failed: ${error instanceof Error ? error.message : error}`);
  process.exit(1);
}
node pay.ts              # stores a small text file it writes itself
node pay.ts report.pdf   # or a file of yours

This is the table our run ended with:

== What it cost ==
call                                                       | price      | tx
GET /v1/projects                                           | 0.005 USDC | 0x4271…b5be
POST /v1/artifacts/uploads                                 | 0.01 USDC  | 0x1527…b4fb
POST /v1/artifacts/01a1e045-…/versions/01a1e045-…/complete | free       |
GET /v1/artifacts/01a1e045-…                               | 0.005 USDC | 0xe8ce…12bb
POST /v1/artifacts/search                                  | 0.01 USDC  | 0x0b85…78bb
GET /v1/artifacts/01a1e045-…/download                      | 0.005 USDC | 0x4c29…ef7a
DELETE /v1/artifacts/01a1e045-…                            | free       |
total: 0.035 USDC in 5 payments

Five payments, 0.035 USDC in total: one cent for the upload, one cent for the search and three reads at half a cent each: the list of projects, the look that found the file ready and the download. Completing and deleting cost nothing. Had the file needed more looks before it was ready, each one would have added $0.005.

Rules worth knowing

  • An API key and a wallet never stack. A request with an Authorization header takes the API-key path and is never asked to pay; a payment header on it is ignored. Only a request without that header gets the 402.
  • A call the server rejects is not charged. The server settles your payment only after the request has done its work. When the request ends in an error before that, a 404 or a validation error for example, the payment is voided and nothing is charged. In the rare case that a call ends in an error after the payment was submitted, a 502 for example, the transfer may still have gone through. The transaction is then visible on a block explorer, and a payment taken for a request that was not served is refunded in USDC to the address that paid it: email support@artefaktum.dev with the transaction hash. The refund policy has the wording.
  • A payment fits one price. A signed payment whose amount differs from the price the server quotes is refused with 402 and the error invalid_payment_requirements. One that was used before is refused with payment_already_used. The client signs a new payment for every call, so you meet these only when you build payments by hand.
  • An empty wallet gets the 402 again. The error field of the decoded PAYMENT-REQUIRED header then carries the facilitator’s reason, and that reason can be vague. When we probed Coinbase’s facilitator with a wallet that held nothing, it answered invalid_payload, not a word about the balance. If a paid call is refused, look at the wallet’s USDC balance on Base first.
  • 503 payments_busy means try again. The server settles only a few payments at once. Beyond that it answers 503 with the code payments_busy and Retry-After: 1. Nothing was charged.
  • Your payments are public. Any Base block explorer, basescan.org for one, shows them on the page of your wallet address. Look under its token transfers, not in its list of transactions: the facilitator submits the transaction, not your wallet. Each payment is a USDC transfer from your wallet to the payTo address of the offer.

Where next

  • Pay per request: the prices, the protocol and what 30 days of storage means.
  • The REST reference: the routes and their fields.
  • https://api.artefaktum.dev/.well-known/x402: the machine-readable manifest of the paid routes and their prices.
  • The complete program is the sum of the blocks above, in the order they appear.
  • The same guide in Python.

This page as Markdown: /blog/pay-per-request-from-typescript.md