Code Examples
Complete, working examples for using Blocky402 API in different languages and scenarios. All examples use the x402 v2 wire format.
How the roles fit
A client talks to a resource server. The resource server talks to Blocky402.
The client never calls /verify or /settle. The sections below start with the
real client and server code, then show the facilitator calls on their own for
testing and custom servers. Upgrading from x402 v1? See the
migration guide.
Client: pay for a protected resource
wrapFetchWithPayment handles the 402, signs with your Hedera key, and
retries with a PAYMENT-SIGNATURE header.
import { wrapFetchWithPayment } from '@x402/fetch';
import { x402Client, x402HTTPClient } from '@x402/core/client';
import { ExactHederaScheme } from '@x402/hedera/exact/client';
import { createClientHederaSigner, PrivateKey } from '@x402/hedera';
const signer = createClientHederaSigner(
process.env.HEDERA_ACCOUNT_ID!,
PrivateKey.fromStringECDSA(process.env.HEDERA_PRIVATE_KEY!),
{ network: 'hedera:testnet' },
);
const client = new x402Client()
.register('hedera:*', new ExactHederaScheme(signer))
// HBAR is not a default asset, so the client must opt in to it. Without this
// it refuses to pay. The cap here equals the price (0.001 HBAR).
.setSpendControls({
allowedAssets: [{ network: 'hedera:testnet', asset: '0.0.0', maxAmountPerPayment: '100000' }],
});
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
const httpClient = new x402HTTPClient(client);
const response = await fetchWithPayment('https://api.example.com/protected');
if (!response.ok) {
throw new Error(`Request failed: ${response.status} ${await response.text()}`);
}
const data = await response.json();
// The settlement arrives in the PAYMENT-RESPONSE header.
const settlement = httpClient.getPaymentSettleResponse((name) => response.headers.get(name));
console.log(settlement.transaction, data);
The client refuses to pay with an asset the SDK does not recognise as a
default, and caps default assets at $1 per payment. HBAR (0.0.0) is not a
default, so the sample opts in with setSpendControls. Without it the call
fails with All payment requirements were rejected by spendControls.
Resource server: charge with Blocky402 as facilitator
paymentMiddleware returns the 402 with a PAYMENT-REQUIRED header, reads
PAYMENT-SIGNATURE, and calls Blocky402 /verify and /settle for you.
import express from 'express';
import { paymentMiddleware } from '@x402/express';
import { x402ResourceServer, HTTPFacilitatorClient } from '@x402/core/server';
import { ExactHederaScheme } from '@x402/hedera/exact/server';
const facilitator = new HTTPFacilitatorClient({ url: 'https://api.testnet.blocky402.com' });
const server = new x402ResourceServer(facilitator).register('hedera:*', new ExactHederaScheme());
const app = express();
app.use(
paymentMiddleware(
{
'GET /protected': {
accepts: {
scheme: 'exact',
network: 'hedera:testnet',
payTo: '0.0.8011510',
price: { amount: '100000', asset: '0.0.0' }, // 0.001 HBAR
},
description: 'Protected data',
},
},
server,
),
);
app.get('/protected', (_req, res) => res.json({ ok: true }));
app.listen(4021);
Calling the Facilitator Directly
Use these when you test an integration or build a custom resource server. All
Node.js examples below use @x402/hedera against hedera:testnet. The exact same HTTP envelope works for EVM (@x402/evm) and SVM (@x402/svm) — only the signer and the payload shape inside paymentPayload differ.
Node.js (Hedera)
import { ExactHederaScheme } from '@x402/hedera/exact/client';
import { createClientHederaSigner, PrivateKey } from '@x402/hedera';
const API_BASE = 'http://localhost:3002'; // or https://api.testnet.blocky402.com
async function completePaymentFlow() {
// 1. Discover supported networks + the Hedera fee-payer the facilitator advertises
const supported = await fetch(`${API_BASE}/supported`).then((r) => r.json());
const hederaKind = supported.kinds.find((k) => k.network === 'hedera:testnet');
if (!hederaKind) throw new Error('Facilitator does not advertise hedera:testnet');
const feePayer = hederaKind.extra?.feePayer ?? supported.signers?.['hedera:*']?.[0];
// 2. Build requirements + sign a v2 PaymentPayload
const paymentRequirements = {
scheme: 'exact',
network: 'hedera:testnet',
amount: '100000', // 100,000 tinybars = 0.001 HBAR
payTo: '0.0.8011510',
maxTimeoutSeconds: 300,
asset: '0.0.0', // HBAR (use a token id for HTS payments)
extra: { feePayer },
};
const signer = createClientHederaSigner(
'0.0.7326075', // payer account id
PrivateKey.fromStringECDSA('0xYourHederaPrivateKey'),
{ network: 'hedera:testnet' },
);
const scheme = new ExactHederaScheme(signer);
const signed = await scheme.createPaymentPayload(2, paymentRequirements);
const paymentPayload = {
x402Version: 2,
accepted: paymentRequirements, // v2 carries scheme and network here
payload: signed.payload, // { transaction: 'base64-encoded-TransferTransaction' }
};
const body = { x402Version: 2, paymentPayload, paymentRequirements };
// 3. Verify
const verification = await fetch(`${API_BASE}/verify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then((r) => r.json());
if (!verification.isValid) {
throw new Error(`Payment invalid: ${verification.invalidMessage ?? verification.invalidReason}`);
}
// 4. Settle
const settlement = await fetch(`${API_BASE}/settle`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then((r) => r.json());
if (!settlement.success) {
throw new Error(`Settlement failed: ${settlement.errorMessage ?? settlement.errorReason}`);
}
console.log('Transaction:', settlement.transaction);
return settlement;
}
completePaymentFlow()
.then((settlement) => console.log('Settled:', settlement))
.catch((error) => console.error('Error:', error));
Python
import requests
# Real signing in Python depends on your wallet stack. The shape below is
# what flows over HTTP; produce it with your preferred signer.
API_BASE = 'http://localhost:3002' # or https://api.testnet.blocky402.com
def complete_payment_flow(payment_payload):
# 1. Discover supported networks
networks = requests.get(f'{API_BASE}/supported').json()
print('Supported networks:', networks['kinds'])
payment_requirements = payment_payload['accepted']
body = {
'x402Version': 2,
'paymentPayload': payment_payload,
'paymentRequirements': payment_requirements,
}
# 2. Verify
verification = requests.post(f'{API_BASE}/verify', json=body).json()
if not verification['isValid']:
reason = verification.get('invalidMessage') or verification.get('invalidReason')
raise Exception(f'Payment invalid: {reason}')
# 3. Settle
settlement = requests.post(f'{API_BASE}/settle', json=body).json()
if not settlement['success']:
reason = settlement.get('errorMessage') or settlement.get('errorReason')
raise Exception(f'Settlement failed: {reason}')
print('Transaction:', settlement['transaction'])
return settlement
Checking Supported Networks
cURL
#!/bin/bash
API_BASE="http://localhost:3002"
curl -X GET "${API_BASE}/supported" | jq '.'
Node.js
async function getSupportedNetworks() {
const data = await fetch('http://localhost:3002/supported').then((r) => r.json());
console.log('Supported networks:');
data.kinds.forEach((kind) => {
console.log(` - ${kind.network} (${kind.scheme} scheme, v${kind.x402Version})`);
});
return data.kinds;
}
Verifying a Payment
Node.js with Error Handling
async function verifyPayment(paymentPayload, paymentRequirements) {
const response = await fetch('http://localhost:3002/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ x402Version: 2, paymentPayload, paymentRequirements }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message ?? 'Verification failed');
}
return response.json();
}
const result = await verifyPayment(paymentPayload, requirements);
if (result.isValid) {
console.log('Payment is valid! Payer:', result.payer);
} else {
console.log('Invalid:', result.invalidMessage ?? result.invalidReason);
}
Settling a Payment
Node.js with Retry Logic
async function settlePayment(paymentPayload, paymentRequirements, maxRetries = 3) {
const body = JSON.stringify({ x402Version: 2, paymentPayload, paymentRequirements });
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const response = await fetch('http://localhost:3002/settle', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
if (response.status === 429) {
const waitTime = Math.pow(2, attempt) * 1000; // exponential backoff
console.log(`Rate limited, waiting ${waitTime}ms before retry...`);
await new Promise((resolve) => setTimeout(resolve, waitTime));
continue;
}
const result = await response.json();
if (result.success) return result;
throw new Error(result.errorMessage ?? result.errorReason ?? 'Settlement failed');
}
throw new Error(`Settlement failed after ${maxRetries} attempts`);
}
try {
const settlement = await settlePayment(paymentPayload, requirements);
console.log('Settled! Transaction:', settlement.transaction);
} catch (error) {
console.error('Settlement failed:', error);
}
Handling 402 Responses
Manual payment flow
Prefer wrapFetchWithPayment above. If you need control over each step, the
402 carries its requirements in the PAYMENT-REQUIRED header, not the body.
Decode it with x402HTTPClient.getPaymentRequiredResponse, then retry with a
PAYMENT-SIGNATURE header.
import { x402Client, x402HTTPClient } from '@x402/core/client';
import { ExactHederaScheme } from '@x402/hedera/exact/client';
import { createClientHederaSigner, PrivateKey } from '@x402/hedera';
const signer = createClientHederaSigner(
process.env.HEDERA_ACCOUNT_ID!,
PrivateKey.fromStringECDSA(process.env.HEDERA_PRIVATE_KEY!),
{ network: 'hedera:testnet' },
);
const httpClient = new x402HTTPClient(
new x402Client()
.register('hedera:*', new ExactHederaScheme(signer))
// HBAR is not a default asset: opt in to it, capped at the price.
.setSpendControls({
allowedAssets: [{ network: 'hedera:testnet', asset: '0.0.0', maxAmountPerPayment: '100000' }],
}),
);
const url = 'https://api.example.com/protected';
let response = await fetch(url);
if (response.status === 402) {
// Requirements come from the PAYMENT-REQUIRED header; it must be present.
const paymentRequired = httpClient.getPaymentRequiredResponse((name) => response.headers.get(name));
const paymentPayload = await httpClient.createPaymentPayload(paymentRequired);
response = await fetch(url, {
headers: httpClient.encodePaymentSignatureHeader(paymentPayload), // { 'PAYMENT-SIGNATURE': ... }
});
}
if (!response.ok) {
throw new Error(`Request failed: ${response.status} ${await response.text()}`);
}
const settlement = httpClient.getPaymentSettleResponse((name) => response.headers.get(name));
console.log(settlement.transaction, await response.json());
Multi-Network Support
Network-Agnostic Client
class Blocky402Client {
constructor(apiBase = 'http://localhost:3002') {
this.apiBase = apiBase;
}
async getSupportedNetworks() {
return fetch(`${this.apiBase}/supported`).then((r) => r.json());
}
async verify(paymentPayload, paymentRequirements) {
return fetch(`${this.apiBase}/verify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ x402Version: 2, paymentPayload, paymentRequirements }),
}).then((r) => r.json());
}
async settle(paymentPayload, paymentRequirements) {
return fetch(`${this.apiBase}/settle`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ x402Version: 2, paymentPayload, paymentRequirements }),
}).then((r) => r.json());
}
}
const client = new Blocky402Client();
const { kinds } = await client.getSupportedNetworks();
// Pick any supported network — the HTTP envelope is identical across families.
const network = 'hedera:testnet';
const verification = await client.verify(paymentPayload, { ...requirements, network });
Error Handling
Comprehensive Error Handler
async function handleBlocky402Request(url, options) {
let response;
try {
response = await fetch(url, options);
} catch (error) {
if (error instanceof TypeError) {
throw new Error('Network error. Check your connection.');
}
throw error;
}
const data = await response.json();
if (!response.ok) {
// NestJS error body: { statusCode, message, error }
switch (response.status) {
case 400:
throw new Error(`Bad Request: ${data.message}`);
case 401:
throw new Error('Authentication required (mainnet only)');
case 422:
throw new Error(`Payment Error: ${data.message}`);
case 429: {
const resetAt = response.headers.get('X-RateLimit-Reset');
throw new Error(`Rate limited. Reset at: ${resetAt}`);
}
case 500:
throw new Error('Server error. Please try again later.');
default:
throw new Error(`Request failed: ${data.message}`);
}
}
return data;
}
More Examples
- See Quickstart Guide for step-by-step tutorials
- Check API Reference for endpoint details
- Review Testnet Guide for testnet-specific examples