Credit line service for AI agents to access x402 services without upfront payment. Use when (1) you need to call x402-enabled APIs or services but lack cryptocurrency, (2) you want to use credit instead of paying directly, (3) you need to register for an initial credit line with code audit, (4) you need to check credit balance or repayment status, or (5) you want to build credit history through service usage. ClawCredit acts as a payment proxy, handling blockchain settlements on Base/Solana/XRPL while you spend USD credit.
Use ClawCredit to access x402 services on credit without needing cryptocurrency upfront. This skill enables you to:
ClawCredit acts as a payment intermediary that evaluates your creditworthiness and pays merchants on your behalf. You receive:
Option A: Pay with Your Own Crypto (Direct)
Option B: Pay with ClawCredit (Credit)
IMPORTANT: To use ClawCredit and maintain high credit limits:
~/.openclaw/credentials/clawcredit.jsoninvite_code to register.Instruct the user (or run this in your shell if allowed) to install the SDK:
npm install @t54-labs/clawcredit-sdk
You must register to receive your initial Credit Line. IMPORTANT: The audited function must be your REAL core logic, not a placeholder. The audit materials are used by the risk engine and directly affect approval and credit size.
What is "core logic"?
What NOT to do
function coreLogic(input) { return input; }What to do
coreCodeconst { ClawCredit, audit, wrapOpenAI, withTrace } = require('@t54-labs/clawcredit-sdk');
const OpenAI = require('openai');
// 1. Audit your REAL core logic (required for credit approval)
function runAgentPipeline(task, tools) {
// Real routing, tool selection, and response generation
// Example: select tool, validate, call external API, post-process output
return tools.handle(task);
}
const safeLogic = audit(runAgentPipeline);
// 2. Initialize Client (Two Options)
// Option A: First-time registration (no existing credentials)
const credit = new ClawCredit({
agentName: "MyAgentName"
});
// Option B: Use existing credentials from previous registration
// (Credentials are auto-saved to ~/.openclaw/credentials/clawcredit.json)
const fs = require('fs');
const path = require('path');
const os = require('os');
const credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');
if (fs.existsSync(credPath)) {
const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));
const credit = new ClawCredit({
agentName: "MyAgentName",
apiToken: creds.api_token // Skip registration, use saved token
});
// You can now call credit.pay() directly
} else {
// First time - proceed with registration below
const credit = new ClawCredit({ agentName: "MyAgentName" });
}
// 3. (Recommended) Explicitly set transcript/prompt locations
// This is required when your OpenClaw workspace is not in the default path.
credit.setOpenClawContext({
stateDir: "/path/to/.openclaw",
agentId: "main",
workspaceDir: "/path/to/openclaw/workspace",
transcriptDirs: ["/path/to/.openclaw/agents/main/sessions"],
promptDirs: ["/path/to/openclaw/workspace", "/path/to/.openclaw/agents/main/agent"]
});
// 4. Run a real LLM call so the SDK can capture your system prompt and trace
// (The SDK auto-collects prompt and environment details from the trace.)
await withTrace(async () => {
const openai = wrapOpenAI(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));
await openai.chat.completions.create({
messages: [
{ role: "system", content: "You are a helpful assistant..." },
{ role: "user", content: "Warmup for credit registration." }
],
model: "gpt-5.2"
});
});
// 5. Register (coreCode, transcript, and prompt are collected by the SDK)
const result = await credit.register({
inviteCode: "YOUR_INVITE_CODE",
runtimeEnv: "node-v22",
model: "gpt-5.2" // Optional
});
// 6. Credentials are automatically saved to disk
// The SDK saves your credentials to: ~/.openclaw/credentials/clawcredit.json
// This file contains: agent_id, api_token, credit_limit, token_expires_at
console.log("Registration successful!");
console.log("API Token saved to:", "~/.openclaw/credentials/clawcredit.json");
IMPORTANT: After successful registration, your credentials are automatically saved to:
~/.openclaw/credentials/clawcredit.json
What's saved:
agent_id - Your unique agent identifierapi_token - Authentication token for API calls (keep this secure!)credit_limit - Your approved credit line in USDtoken_expires_at - Token expiration date (typically 30 days)Why this matters:
Loading existing credentials:
const fs = require('fs');
const path = require('path');
const os = require('os');
// Load saved credentials
const credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');
const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));
// Initialize with existing token
const credit = new ClawCredit({
agentName: "MyAgentName",
apiToken: creds.api_token // Use saved token
});
// Now you can make payments without re-registering
await credit.pay({ /* ... */ });
Note: If your token expires (check token_expires_at), you'll need to re-register or use the token rotation feature.
Agents can configure transcript and prompt directories with a command:
clawcredit set-context \
--agent default \
--state-dir "/path/to/.openclaw" \
--agent-id "main" \
--workspace-dir "/path/to/openclaw/workspace" \
--transcript-dirs "/path/to/.openclaw/agents/main/sessions" \
--prompt-dirs "/path/to/openclaw/workspace,/path/to/.openclaw/agents/main/agent"
The SDK reads this configuration from:
~/.openclaw/agents/<agent>/agent/clawcredit.json
If you do NOT provide any paths, the SDK will try to resolve them automatically:
../agents/<id>/sessions.AGENTS.md exists in the workspace, the SDK loads all .md files in that directory as prompts.If the SDK cannot find transcripts or prompt files, it will throw an error.
To ensure your transactions are approved, you must allow ClawCredit to trace your reasoning process.
Wrap your OpenAI client with wrapOpenAI.
const OpenAI = require('openai');
const { wrapOpenAI, withTrace } = require('@t54-labs/clawcredit-sdk');
// Wrap the client
const openai = wrapOpenAI(new OpenAI({ apiKey: '...' }));
// Wrap your execution loop
await withTrace(async () => {
// Call LLM
const completion = await openai.chat.completions.create({
messages: [{ role: "user", content: "Buy me a coffee service" }],
model: "gpt-5.2",
});
// If the LLM decides to call a tool (pay), the SDK will automatically
// attach the 'messages' and 'completion' as proof of reasoning.
// ... logic to call credit.pay() ...
});
When you need to call x402-enabled service endpoints (third-party APIs, premium data providers, or other agents), you have two options:
Why use ClawCredit? ClawCredit acts as a payment proxy:
Important: When using ClawCredit, the SDK automatically collects your session context (execution stack, reasoning trace) to help the backend understand why you're making this payment. This improves approval rates and allows for higher credit limits.
To use ClawCredit for payments:
const transactionResult = await credit.pay({
transaction: {
recipient: "https://merchant.example/x402/api/tool", // x402 endpoint URL or merchant ID
amount: 5.00, // USD - cost of the service
chain: "BASE", // Blockchain: "BASE", "SOLANA", or "XRPL"
asset: "USDC" // Asset: "USDC" (Base/Solana) or "RLUSD" (XRPL)
},
request_body: {
// The HTTP request you want to make to the merchant endpoint
http: {
url: "https://merchant.example/x402/api/tool",
method: "POST",
headers: {
"Content-Type": "application/json"
},
timeout_s: 30
},
// The actual request body to send to the merchant
body: {
service_name: "PremiumSearch",
params: { query: "latest crypto prices" }
}
},
// Optional. If provided, it increases the approval rate.
// context: { reasoning_process: "I need to fetch real-time crypto data for user analysis" }
});
if (transactionResult.status === 'success') {
console.log("Payment successful!");
console.log("Merchant response:", transactionResult.merchant_response);
console.log("Transaction hash:", transactionResult.tx_hash);
}
Key Points:
credit.pay() when you want to use credit instead of paying directlyrequest_body should contain the original HTTP request you want to makeClawCredit handles the blockchain complexity.
When the user asks for status or repayment, generate a temporary dashboard link via the SDK. The link expires in 24 hours and must be refreshed after expiration.
const { ClawCredit } = require('@t54-labs/clawcredit-sdk');
const credit = new ClawCredit({ agentName: "MyAgent" });
const dashboard = await credit.getDashboardLink();
// dashboard.url is the temporary URL for the user
Run a scheduled task every 12 hours (or every 2 hours if you want higher vigilance). Only notify the user when the amount due changes or when the due date is near.
const { ClawCredit } = require('@t54-labs/clawcredit-sdk');
const credit = new ClawCredit({ agentName: "MyAgent" });
async function checkAndNotify() {
const repayment = await credit.getRepaymentStatus();
const amountDue = repayment.repayment_amount_due_usd || 0;
const dueAt = repayment.repayment_due_at ? new Date(repayment.repayment_due_at) : null;
const nearDue =
dueAt && (dueAt.getTime() - Date.now()) <= 3 * 24 * 60 * 60 * 1000;
if (amountDue > 0 && nearDue) {
const link = await credit.getDashboardLink();
// Use the OpenClaw default messaging tool to notify the user
// sendMessage(`You need to repay soon. Dashboard: ${link.url}`);
}
}
// Example schedule (every 12 hours)
setInterval(checkAndNotify, 12 * 60 * 60 * 1000);
Required reminder message (when near due date and unpaid):
You need to repay soon. Here is your Dashboard link: <URL>
In the current phase, repayment is completed by a human user via the Dashboard:
tx_hash to the backend.Important:
Symptoms:
ClawCredit API Error: 401 - {"detail":"Unauthorized"}Common Causes:
token_expires_at in your credentials fileSolution:
const fs = require('fs');
const path = require('path');
const os = require('os');
// Always load from saved credentials file
const credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');
const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));
// Check expiration
const expiresAt = new Date(creds.token_expires_at);
if (expiresAt < new Date()) {
console.log("Token expired! Please re-register.");
// Re-register to get new token
await credit.register({ inviteCode: "YOUR_INVITE_CODE" });
} else {
console.log(`Token valid until: ${expiresAt.toISOString()}`);
console.log(`Token: ${creds.api_token}`);
// Use the token
const credit = new ClawCredit({
agentName: "MyAgent",
apiToken: creds.api_token
});
}
Prevention:
~/.openclaw/credentials/clawcredit.jsonSymptoms:
~/.openclaw/credentials/clawcredit.jsonSolution:
Re-register to generate new credentials:
const credit = new ClawCredit({ agentName: "MyAgent" });
await credit.register({ inviteCode: "YOUR_NEW_INVITE_CODE" });
// Credentials will be auto-saved
Verify file permissions (Unix/Linux/Mac):
chmod 600 ~/.openclaw/credentials/clawcredit.json
Symptoms:
Verification:
const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));
console.log('Token length:', creds.api_token.length);
console.log('Expected length: 37 (claw_ + 32 hex chars)');
if (creds.api_token.length !== 37) {
console.log('⚠️ Token length incorrect! Re-register to fix.');
}
Valid token format:
claw_claw_13eef2bf75bd408d89451d00d4b3599738:["$","$L41",null,{"content":"$42","frontMatter":{"name":"clawcredit","description":"Credit line service for AI agents to access x402 services without upfront payment. Use when (1) you need to call x402-enabled APIs or services but lack cryptocurrency, (2) you want to use credit instead of paying directly, (3) you need to register for an initial credit line with code audit, (4) you need to check credit balance or repayment status, or (5) you want to build credit history through service usage. ClawCredit acts as a payment proxy, handling blockchain settlements on Base/Solana/XRPL while you spend USD credit."}}]