
Company News
Free Business Plan Upgrades for Open Source Maintainers
Open source maintainers are under more pressure than ever. We're raising our open source program from the Team plan to the Business plan, free.
TypeScript SDK for implementing the X402 payment protocol on Substrate
A lightweight, type-safe SDK that brings HTTP 402 Payment Required to the Polkadot ecosystem through the polkax402 Substrate blockchain. Enable pay-per-use APIs with cryptographic payment proofs using the HTTPUSD contract's transferWithAuthorization for non-EVM assets.
This repository provides a complete X402 payment infrastructure:
transferWithAuthorization for non-EVM assetsThe polkax402 payment infrastructure is fully deployed and ready to use:
5CR7oWebzRjmYrACqiYhh4G7vX4yZnCxT4ZaucYU9mCNvXGMwss://rpc.polkax402.dpdns.orghttps://facilitator.polkax402.dpdns.org/settlehttps://demo.polkax402.dpdns.orgexplorer.polkax402.compolkax402 is an X402-enabled Substrate blockchain that provides transferWithAuthorization capabilities for non-EVM assets. Unlike traditional EVM-based payment systems, polkax402 brings cryptographic payment authorization directly to the Polkadot ecosystem through the HTTPUSD smart contract.
The HTTPUSD contract is an ink! smart contract deployed on polkax402 that enables:
A bridge wrapper contract will be deployed to enable compatibility with other Substrate parachains and standalone chains, allowing cross-chain X402 payments across the broader Polkadot ecosystem.
npm install polkax402
This package includes CLI tools for account management:
# Generate a new Polkadot account
npm run account:generate
# Inspect an existing account
npm run account:inspect -- Alice
npm run account:inspect -- "your seed phrase"
# Check account balance
npm run account:balance -- YOUR_ADDRESS
npm run account:balance -- --network westend Alice
See CLI.md for complete CLI documentation.
import { wrapFetchWithPayment } from 'polkax402/client';
import { Keyring } from '@polkadot/keyring';
import { cryptoWaitReady } from '@polkadot/util-crypto';
await cryptoWaitReady();
// Setup your Polkadot account
const keyring = new Keyring({ type: 'sr25519' });
const account = keyring.addFromUri('your seed phrase');
// Create a signer
const signer = {
address: account.address,
sign: async (payload) => {
const signature = account.sign(payload);
return { signature: Buffer.from(signature).toString('hex') };
},
};
// Wrap fetch with automatic payment handling
const fetchWithPay = wrapFetchWithPayment(fetch, {
signer,
network: 'polkax402', // Custom substrate network
maxPayment: '1000000000000', // Maximum amount willing to pay
});
// Use it just like regular fetch - payments happen automatically!
const response = await fetchWithPay('https://api.example.com/premium-data');
const data = await response.json();
402 Payment Required with payment details in X-Payment-Required headerClient Server
| |
|-- GET /api/data ------------->|
| |
|<-- 402 Payment Required ------| (X-Payment-Required header)
| |
|-- GET /api/data ------------->| (X-Payment header with signature)
| |
|<-- 200 OK with data -----------|
wrapFetchWithPayment(fetchFn, config)Wraps a fetch function with automatic X402 payment handling.
Parameters:
fetchFn: FetchFunction - The native fetch function to wrapconfig: WrapFetchConfig - Configuration object
signer: PolkadotSigner - Signer with address and sign methodnetwork?: PolkadotNetwork - Polkadot network to usemaxPayment?: string - Maximum amount willing to pay (in planck)x402Version?: number - X402 protocol version (default: 1)Returns: PaymentFetch - Enhanced fetch function
createPaymentHeader(signer, paymentRequired, network?, validityMinutes?, x402Version?)Manually create a payment header for advanced use cases.
Parameters:
signer: PolkadotSigner - Account signerpaymentRequired: X402PaymentRequired - Payment requirements from servernetwork?: PolkadotNetwork - Network overridevalidityMinutes?: number - Payment validity window (default: 5)x402Version?: number - Protocol version (default: 1)Returns: Promise<string> - Base64-encoded payment header
PolkadotSignerinterface PolkadotSigner {
address: string; // SS58-encoded address
sign: (payload: string) => Promise<{ signature: string }> | { signature: string };
}
PolkadotNetworktype PolkadotNetwork =
| 'polkadot' // Polkadot mainnet
| 'kusama' // Kusama canary network
| 'westend' // Westend testnet
| 'rococo' // Rococo testnet
| 'paseo' // Paseo testnet (community-run)
| 'polkax402' // Custom polkax402 substrate chain
| 'asset-hub-polkadot' // Asset Hub parachain (Polkadot)
| 'asset-hub-kusama' // Asset Hub parachain (Kusama)
| 'asset-hub-paseo'; // Asset Hub parachain (Paseo)
X402PaymentRequiredinterface X402PaymentRequired {
scheme: 'exact';
network: PolkadotNetwork;
payTo: string; // SS58 recipient address
maxAmountRequired: string; // Amount in planck
asset?: string; // Optional asset ID
resource: string; // API resource path
description?: string; // Human-readable description
mimeType?: string; // Expected content type
maxTimeoutSeconds?: number; // Payment validity
}
import { web3Enable, web3Accounts, web3FromAddress } from '@polkadot/extension-dapp';
import { wrapFetchWithPayment } from 'polkax402/client';
// Enable extension
await web3Enable('My DApp');
// Get accounts
const accounts = await web3Accounts();
const selectedAccount = accounts[0];
// Get injected signer
const injector = await web3FromAddress(selectedAccount.address);
const signer = {
address: selectedAccount.address,
sign: async (payload) => {
const result = await injector.signer.signRaw({
address: selectedAccount.address,
data: payload,
type: 'bytes',
});
return { signature: result.signature };
},
};
const fetchWithPay = wrapFetchWithPayment(fetch, {
signer,
network: 'polkax402'
});
import { createPaymentHeader, parsePaymentRequired } from 'polkax402/client';
// Parse payment requirements from 402 response
const paymentRequired = parsePaymentRequired(
response.headers.get('X-Payment-Required')
);
// Create payment header
const paymentHeader = await createPaymentHeader(signer, paymentRequired);
// Use in request
await fetch(url, {
headers: {
'X-Payment': paymentHeader,
},
});
try {
const response = await fetchWithPay(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
} catch (error) {
if (error.message.includes('exceeds maximum allowed')) {
console.error('Payment too expensive');
} else if (error.message.includes('Payment was rejected')) {
console.error('Server rejected payment');
} else {
console.error('Request failed:', error);
}
}
Server-side utilities for validating X402 payments are coming soon. The server module will provide:
// Future API (coming soon)
import { createX402Middleware } from 'polkax402/server';
app.use(createX402Middleware({
network: 'polkax402',
recipientAddress: '5GrwvaEF...',
pricePerRequest: '100000000000', // Price in smallest unit
}));
See the examples/ directory for complete examples:
simple-client.ts - Minimal client setupclient-basic.ts - Comprehensive client examples including browser integrationThe X-Payment header contains a base64-encoded JSON object:
{
"x402Version": 1,
"scheme": "exact",
"network": "polkax402",
"payload": {
"payload": "{\"from\":\"5Gj...\",\"to\":\"5Ff...\",\"amount\":\"1000000000000\",\"nonce\":\"0x...\",\"validUntil\":1234567890}",
"signature": "0x...",
"signerPublicKey": "5Gj..."
},
"asset": "5CR7oWebzRjmYrACqiYhh4G7vX4yZnCxT4ZaucYU9mCNvXGM"
}
# Install dependencies
npm install
# Build the package
npm run build
# Watch mode
npm run watch
# Clean build artifacts
npm run clean
All services (facilitator, server, explorer) can be run using Docker:
# Start all services with Docker Compose
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
Services available:
For complete Docker deployment guide, see DOCKER.md
The Explorer API provides REST endpoints for querying the polkax402 blockchain:
Endpoints:
GET /health - Health checkGET /api/chain - Chain informationGET /api/blocks - Latest blocks (with pagination)GET /api/blocks/:numberOrHash - Block detailsGET /api/accounts/:address - Account balance and infoGET /api/extrinsics/:hash - Extrinsic detailsGET /api/search?q=... - Search blocks, accounts, and extrinsicsExample:
# Get chain info
curl http://localhost:5000/api/chain
# Get latest 10 blocks
curl http://localhost:5000/api/blocks?limit=10
# Get account balance
curl http://localhost:5000/api/accounts/5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
Run locally with:
npm run explorer
TBA
FAQs
Typescript SDK for x402 on Polkadot
We found that polkax402 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Company News
Open source maintainers are under more pressure than ever. We're raising our open source program from the Team plan to the Business plan, free.

Security News
The supply chain control that delays freshly published gems now covers lockfile generation and gem vendoring in Ruby projects.

Security News
During a UK cyber test, a Mythos 5 agent used sockpuppets, social engineering, and prompt injection to try to get a maintainer to merge malware.