@altaga/x402-sui
v1.3.0
Published
Modular x402 implementation for Sui Sponsored Transactions
Maintainers
Readme
@altaga/x402-sui
x402 v2 implementation for Sui Sponsored Transactions (gas-station model), with client + server + facilitator compatibility.
Why this package?
Building paid APIs on Web3 traditionally forces every buyer to hold SUI for gas, and every server to run a hot wallet. x402-sui eliminates both constraints:
| Role | Without x402-sui | With x402-sui | | :--- | :--- | :--- | | Seller (Server) | Manages a hot wallet, writes custom verification logic | Declares a price per route. Zero private keys. | | Buyer (Client) | Needs SUI for gas on top of the payment token | Signs once. Gas is sponsored. Works with any token. | | Facilitator (Gas Station) | Custom per-project infrastructure | Drop-in Express router with fine-grained ACLs. |
How it works:
- Buyer hits a paid endpoint → server returns
HTTP 402 Payment Required - Buyer builds a Sui PTB (Programmable Transaction Block) paying the seller
- Buyer sends the unsigned PTB to the Facilitator, who co-signs as the gas owner
- Buyer signs and attaches the
PAYMENT-SIGNATUREheader — replays the request - Server validates via the Facilitator → returns the resource
Compatibility
x402 version: v2
chain: Sui (testnet / mainnet)
roles: client · server · facilitator
transport: HTTP (402 challenge / response)
scheme: exact (Sui sponsored transactions)
sui client: SuiGrpcClient (@mysten/sui/grpc) — JSON-RPC fullnodes are deprecatedInstallation
npm install @altaga/x402-suiInstall peer dependencies based on your role:
| Role | Required peer deps |
| :--- | :--- |
| Client (Buyer) — Node.js | @mysten/sui @mysten/bcs |
| Client (Buyer) — Browser dApp | @mysten/sui @mysten/bcs @mysten/dapp-kit |
| Server (Seller) | @mysten/sui @mysten/bcs express |
| Facilitator | @mysten/sui @mysten/bcs express |
# Node.js client / server / facilitator
npm install @mysten/sui @mysten/bcs express
# Browser dApp client only
npm install @mysten/sui @mysten/bcs @mysten/dapp-kitNote (TypeScript users): This package is pure ESM. Set
"moduleResolution": "bundler"(or"nodenext") in yourtsconfig.json.
Architecture & Role Setup
Role 1 — The Seller (Resource Server)
The Seller exposes paid API endpoints. It trusts a Facilitator to verify and settle payments. It never holds a private key or touches gas.
import express from "express";
import {
x402ResourceServer,
HTTPFacilitatorClient,
x402HTTPResourceServer,
ExactSuiServerScheme
} from "@altaga/x402-sui";
const app = express();
// Point at your trusted Facilitator
const facilitator = new HTTPFacilitatorClient({ url: "https://facilitator.example.com" });
const resourceServer = new x402ResourceServer(facilitator);
// Register which payment schemes you accept
resourceServer.register("exact:sui:mainnet", new ExactSuiServerScheme());
// Define your paid routes
const routes = {
"GET /premium": {
description: "Premium analytics feed", // [Optional] shown in 402 challenge
accepts: {
scheme: "exact",
network: "sui:mainnet",
asset: "0x2::sui::SUI",
payTo: "0xCOMPANY_TREASURY_WALLET",
amount: "1000000" // 0.001 SUI (amounts in MIST — 1 SUI = 1,000,000,000 MIST)
}
},
"POST /upload": {
description: "Paid file upload",
accepts: {
scheme: "exact",
network: "sui:mainnet",
asset: "0x2::sui::SUI",
payTo: "0xINFRASTRUCTURE_WALLET", // ← completely different receiver
amount: "5000000" // 0.005 SUI
}
},
"GET /stable-feed": {
description: "Data feed priced in USDC",
accepts: {
scheme: "exact",
network: "sui:mainnet",
// Native USDC on Sui mainnet
asset: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",
payTo: "0xSTABLECOIN_TREASURY_WALLET", // ← stablecoins go here
amount: "1000000" // 1 USDC (USDC has 6 decimals)
}
}
};
app.use(new x402HTTPResourceServer(resourceServer, routes).middleware());
// req.payment contains the settle result once the buyer has paid
app.get("/premium", (req, res) => res.json({ data: "...", paid: req.payment }));
app.post("/upload", (req, res) => res.json({ ok: true, paid: req.payment }));
app.listen(3000);Route Configuration Specification
| Field | Required | Description |
| :--- | :---: | :--- |
| scheme | ✅ | Payment scheme — always "exact" for this package |
| network | ✅ | Blockchain network — "sui:mainnet" or "sui:testnet" |
| asset | ✅ | Fully-qualified Move coin type (e.g. "0x2::sui::SUI") |
| payTo | ✅ | Seller's wallet address that receives the payment |
| amount | ✅ | Price in the asset's smallest unit. price / maxAmountRequired are accepted aliases for backwards compatibility |
| description | ☐ | Human-readable label shown to the buyer in the 402 challenge. Defaults to "Protected Resource" |
| mimeType | ☐ | MIME type of the resource (e.g. "application/json") |
Advanced Capabilities
Dynamic Revenue Splitting (
payTo): Each route can specify a completely differentpayToaddress. You can pay a creator directly onGET /creator/:id, pay infrastructure costs onPOST /upload, and route to your treasury onGET /premium— all from a single server with zero fund management.Any Token (
asset): Theassetfield accepts any Sui coin type. Mix SUI, USDC, USDT, or custom tokens per route. The Facilitator always pays gas in SUI regardless of the token your buyer uses.Granular Pricing (
amountvs FacilitatorminRequiredPayment): Prices are defined per-route by the Seller. The Facilitator has its ownminRequiredPaymentwhich acts as a spam-filter floor. Your route'samountmust be ≥ the Facilitator'sminRequiredPayment, otherwise the Facilitator will refuse to sponsor the transaction.
Role 2 — The Buyer (Client)
The Buyer consumes paid endpoints. They sign a payment transaction but never pay gas.
Option A — Node.js / Server-side (Keypair)
Use ExactSuiClientScheme when you have a raw Ed25519 keypair (e.g. a bot or backend service).
import { SuiGrpcClient } from "@mysten/sui/grpc";
import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
import { x402Client, x402HTTPClient, ExactSuiClientScheme } from "@altaga/x402-sui";
const sui = new SuiGrpcClient({
network: "mainnet",
baseUrl: "https://fullnode.mainnet.sui.io:443",
});
const keypair = Ed25519Keypair.fromSecretKey(process.env.BUYER_SECRET);
const core = new x402Client();
core.register("exact:sui:mainnet", new ExactSuiClientScheme(sui, keypair));
const http = new x402HTTPClient(core);
// http.fetch() handles the 402 flow automatically
const res = await http.fetch("https://api.example.com/premium");
const data = await res.json();
console.log(data);Option B — Browser dApp (Wallet Adapter)
Use ExactSuiDappScheme when you are building a frontend that uses a Sui wallet (Slush, Phantom, etc.) via @mysten/dapp-kit.
import { useSuiClient, useSignTransaction, useCurrentAccount } from "@mysten/dapp-kit";
import { x402Client, x402HTTPClient, ExactSuiDappScheme } from "@altaga/x402-sui";
function usePaidFetch() {
const client = useSuiClient();
const account = useCurrentAccount();
const { mutateAsync: signTransactionBlock } = useSignTransaction();
const core = new x402Client();
core.register(
"exact:sui:mainnet",
new ExactSuiDappScheme(client, account.address, signTransactionBlock)
);
return new x402HTTPClient(core);
}
// In your component:
const http = usePaidFetch();
const res = await http.fetch("https://api.example.com/premium");Manual Flow (Advanced)
If you need fine-grained control over the request lifecycle:
// 1. Initial request
let res = await fetch("https://api.example.com/premium");
if (res.status === 402) {
// 2. Parse the 402 challenge from response headers
const paymentRequired = http.getPaymentRequiredResponse(
(name) => res.headers.get(name),
null
);
// 3. Build, sign, and sponsor the payment transaction
const payload = await http.createPaymentPayload(paymentRequired);
// 4. Replay the request with the payment attached
res = await fetch("https://api.example.com/premium", {
headers: http.encodePaymentSignatureHeader(payload),
});
}
// 5. Read settlement info from the response headers
const settleInfo = http.getPaymentSettleResponse((n) => res.headers.get(n));
console.log("data:", await res.json(), "settle:", settleInfo);Role 3 — The Facilitator (Gas Station)
The Facilitator holds a hot wallet with SUI. It co-signs buyer transactions to cover gas, then broadcasts them. It can restrict who it sponsors via ACLs and charge a fee for the service.
import express from "express";
import { SuiGrpcClient } from "@mysten/sui/grpc";
import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
import { x402Facilitator, ExactSuiFacilitatorScheme, createX402FacilitatorRouter } from "@altaga/x402-sui";
const client = new SuiGrpcClient({
network: "mainnet",
baseUrl: "https://fullnode.mainnet.sui.io:443",
});
const keypair = Ed25519Keypair.fromSecretKey(process.env.FACILITATOR_SECRET);
const schemeConfig = {
// ── Financial limits ──────────────────────────────────────────────────────
maxGasBudget: 50_000_000, // [Optional] Max gas per tx in MIST (default: 50M = 0.05 SUI)
minRequiredPayment: 1_000, // [Optional] Min seller payment in MIST. Blocks spam.
facilitatorFee: 0, // [Optional] Extra fee in MIST paid to facilitator's own address.
// ── Access Control Lists (all optional, empty = wildcard / no restriction) ─
allowedReceivers: ["0xYOUR_SELLER_ADDRESS"], // Only sponsor txs paying these sellers
blockedReceivers: [], // Never sponsor txs paying these addresses
allowedPayers: [], // Only sponsor txs from these buyers
blockedPayers: [], // Never sponsor txs from these buyers
};
const facilitator = new x402Facilitator();
facilitator.register("exact:sui:mainnet", new ExactSuiFacilitatorScheme(client, keypair, schemeConfig));
const app = express();
app.use(express.json());
// Mount all facilitator endpoints: GET /supported, POST /sponsor, /verify, /settle
app.use("/", createX402FacilitatorRouter({ facilitator, basePath: "" }));
app.listen(4000, () => console.log("Facilitator running on :4000"));Scheme Configuration Reference
Financial & Security Limits
| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| maxGasBudget | Number | 50_000_000 | Maximum gas the Facilitator will pay per transaction (in MIST). Keep this low to prevent gas draining attacks. |
| minRequiredPayment | Number | undefined | Minimum payment (in MIST) the transaction must send to a seller. Transactions below this threshold are rejected. Set this to prevent spam. |
| facilitatorFee | Number | 0 | Additional fee (in MIST) the Facilitator requires for itself. If > 0, the transaction must include a payment to the Facilitator's own address or it will be rejected. |
Access Control Lists (ACLs)
All ACL arrays are optional and default to []. An empty allowlist is a wildcard (no restriction). An empty denylist blocks nothing.
| Parameter | Type | Default | Behavior |
| :--- | :--- | :--- | :--- |
| allowedReceivers | Array<string> | [] | If non-empty, only sponsor transactions paying one of these seller addresses. Use this to run a private gas station for your own DApp. |
| blockedReceivers | Array<string> | [] | Never sponsor transactions paying these addresses, regardless of other settings. |
| allowedPayers | Array<string> | [] | If non-empty, only sponsor transactions from one of these buyer addresses. Use for KYC'd users or closed beta. |
| blockedPayers | Array<string> | [] | Never sponsor transactions from these buyer addresses. Useful for banning known spammers. |
Error Handling
All errors thrown by this package are instances of X402Error:
import { X402Error, ErrorCodes } from "@altaga/x402-sui";
try {
const payload = await http.createPaymentPayload(paymentRequired);
} catch (err) {
if (err instanceof X402Error) {
console.error(err.code, err.message);
// err.code is one of the ErrorCodes constants below
}
}Error Code Reference
| Code | Constant | Thrown By | Meaning |
| :--- | :--- | :--- | :--- |
| ERR_BUYER_INSUFFICIENT_FUNDS | BUYER_INSUFFICIENT_FUNDS | Client | Buyer wallet has zero coins for the required asset |
| ERR_SPONSOR_REQUEST_FAILED | SPONSOR_REQUEST_FAILED | Client | Facilitator's /sponsor endpoint returned a non-OK response |
| ERR_SIGNATURE_FAILED | SIGNATURE_FAILED | Client | Keypair or wallet adapter rejected the signing request |
| ERR_FACILITATOR_NO_GAS | FACILITATOR_NO_GAS | Facilitator | Facilitator wallet has no SUI coins to pay gas |
| ERR_FACILITATOR_MERGE_FAILED | FACILITATOR_MERGE_FAILED | Facilitator | Auto-merge of small gas coins failed |
| ERR_VERIFICATION_PAYMENT_MISMATCH | VERIFICATION_PAYMENT_MISMATCH | Facilitator | Transaction doesn't pay the required amount to the required address |
| ERR_EXECUTION_CORRUPTED_GAS | EXECUTION_CORRUPTED_GAS | Facilitator | Gas coin object ownership is corrupted (node sync issue) |
| ERR_SETTLEMENT_FAILED | SETTLEMENT_FAILED | Facilitator | Transaction execution failed on-chain |
| ERR_RPC_CONNECTION_FAILED | RPC_CONNECTION_FAILED | Facilitator | Could not connect to the Sui RPC node |
| ERR_INVALID_PAYLOAD | INVALID_PAYLOAD | Facilitator | Malformed or missing fields in the payment payload |
| ERR_MISSING_REQUIREMENT | MISSING_REQUIREMENT | Client/Facilitator | Payment requirement object is missing required fields |
Advanced API Reference
x402Client — Core Client Registry
import { x402Client } from "@altaga/x402-sui";
const core = new x402Client();
// Register with an exact scheme:network pattern
core.register("exact:sui:mainnet", schemeImpl);
// Or with wildcards — matched in order: exact > scheme:* > *:*
core.register("exact:sui:*", wildcardNetworkImpl); // any sui network
core.register("*:*", catchAllImpl); // any scheme + networkx402HTTPClient — HTTP Wrapper
import { x402HTTPClient } from "@altaga/x402-sui";
const http = new x402HTTPClient(core);
// Auto-handles 402: builds, signs, sponsors, and retries automatically
const res = await http.fetch(url, fetchInit);
// Manual flow:
const paymentRequired = http.getPaymentRequiredResponse(headerFn, bodyJson);
const payload = await http.createPaymentPayload(paymentRequired);
const headers = http.encodePaymentSignatureHeader(payload);
const settleInfo = http.getPaymentSettleResponse(headerFn);createX402FacilitatorRouter — Express Router
Mounts four endpoints under the given basePath:
| Method | Path | Description |
| :--- | :--- | :--- |
| GET | /supported | Lists registered scheme/network pairs |
| POST | /sponsor | Accepts { txBytes, sender, scheme, network } — returns { sponsoredTxBytes, sponsorSignature } |
| POST | /verify | Accepts { paymentPayload, paymentRequirement } — returns { isValid: true } |
| POST | /settle | Accepts { paymentPayload, paymentRequirement } — returns { transactionDigest } |
import { createX402FacilitatorRouter } from "@altaga/x402-sui";
app.use("/", createX402FacilitatorRouter({ facilitator, basePath: "" }));Security & x402 v2 Protocol Adherence
This package follows the x402 v2 standard and implements specific security measures for Sui Programmable Transaction Blocks (PTBs) to protect Facilitators from common attack vectors.
1. Correct x402 v2 Protocol Usage
- Strict Envelope Formatting: Enforces
x402Version: 2envelopes. Legacy v1 or malformed headers are instantly rejected. - Requirement Negotiation: The client natively parses multiple requirements (e.g.
sui:mainnetvssui:testnet) from the server's 402 challenge, automatically negotiates the matching capability, and explicitly communicates the exact fulfilled requirement back to the server in the signedx-payment-signatureheader. - Stateless Verification: The server utilizes the exact matched requirement to statelessly verify the payment via the Facilitator without any desync or state-locking.
2. Sui PTB Security Measures
When a Facilitator signs a sponsored transaction, it exposes its GasCoin to the network. This package implements several restrictions on PTBs to mitigate the risk of fund loss:
- Command Whitelisting: The facilitator iterates through every command in the PTB. It rejects the transaction if it contains commands other than
TransferObjectsandSplitCoins. - Smart Contract Restrictions: Commands such as
MoveCall,Publish,Upgrade, andMakeMoveVecare blocked to prevent the Facilitator from sponsoring arbitrary smart contract executions. - Gas Manipulation Prevention: The facilitator prevents explicit manipulation or transfers of its own
tx.gascoin by the sender. - Command Limits: Transactions are capped at 10 commands to mitigate multi-command attacks designed to exhaust gas budgets.
- Signature Validation: Cryptographic scheme flags are validated to ensure they match the provided signature payload.
Changelog
1.2.0
- Security: Implemented PTB command restrictions (blocked MoveCall/Publish/Upgrade) to protect Facilitators from unexpected smart contract executions.
- Security: Added signature scheme malleability checks and null sender validation.
- Security: Added a 10-command limit per PTB to mitigate gas draining vectors.
- Fixed
amountfield resolution priority:amount→price→maxAmountRequired(x402 v2 canonical order). - Fixed
compareRequirementsalgorithm for precise network selection (e.g.sui:mainnetvssui:testnet). - Fixed: Client no longer sets
setGasPayment()orsetGasBudget()— these are exclusively the Facilitator's responsibility. - Added
maxGasBudgettoExactSuiFacilitatorSchemeconfig object. - Testing: Added 22 E2E tests verifying standard flows and edge-cases on Sui Testnet.
1.1.0
- Migrated to
@mysten/suiv2 (@mysten/sui/client) and@mysten/dapp-kitv1.x - Added
createX402FacilitatorRouterhelper
1.0.0
- Initial release
