{
  "schemaVersion": "1.0",
  "item": {
    "slug": "claw-credit",
    "name": "Claw Credit by t54",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/SergioChan/claw-credit",
    "canonicalUrl": "https://clawhub.ai/SergioChan/claw-credit",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/claw-credit",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=claw-credit",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "SKILL.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-30T16:55:25.780Z",
      "expiresAt": "2026-05-07T16:55:25.780Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
        "contentDisposition": "attachment; filename=\"network-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/claw-credit"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/claw-credit",
    "agentPageUrl": "https://openagent3.xyz/skills/claw-credit/agent",
    "manifestUrl": "https://openagent3.xyz/skills/claw-credit/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/claw-credit/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "1. Overview",
        "body": "Use ClawCredit to access x402 services on credit without needing cryptocurrency upfront. This skill enables you to:\n\nRegister for a credit line by submitting auditable code and proof of real capability\nPay for x402 services using credit instead of your own crypto\nBuild credit history through successful payments and repayments"
      },
      {
        "title": "What ClawCredit Does",
        "body": "ClawCredit acts as a payment intermediary that evaluates your creditworthiness and pays merchants on your behalf. You receive:\n\nAn initial credit line based on code audit and usage patterns\nThe ability to call any x402-enabled API or service without upfront payment\nDeferred payment with the opportunity to build credit history"
      },
      {
        "title": "Direct Payment vs Credit Payment",
        "body": "Option A: Pay with Your Own Crypto (Direct)\n\nCall x402 endpoints directly with your cryptocurrency wallet\nImmediate payment required\nNo credit used or built\nFull control over payment timing\n\nOption B: Pay with ClawCredit (Credit)\n\nUse this SDK to pay through ClawCredit\nNo cryptocurrency needed upfront\nCredit underwriting evaluates each transaction\nBuild credit history for future higher limits\nRepay later"
      },
      {
        "title": "SDK Compliance Requirements",
        "body": "IMPORTANT: To use ClawCredit and maintain high credit limits:\n\nUse the SDK for all registration and payment calls (no direct API calls)\nProvide real, auditable core logic (not placeholders or stubs)\nEnable tracing to capture reasoning and execution context\nThe more complete and truthful your audit materials, the higher your credit limit\nFabricated or minimal data results in low limits or rejection\nKeep your API token secure - it's automatically saved to ~/.openclaw/credentials/clawcredit.json\nNever manually copy tokens - always load from the credential file to avoid typos"
      },
      {
        "title": "2. Prerequisites",
        "body": "Node.js Environment (The SDK is a Node.js package).\nInvitation Code: You need a valid invite_code to register."
      },
      {
        "title": "3. Installation",
        "body": "Instruct the user (or run this in your shell if allowed) to install the SDK:\n\nnpm install @t54-labs/clawcredit-sdk"
      },
      {
        "title": "Step 1: Initialization & Registration (with Code Audit)",
        "body": "You must register to receive your initial Credit Line.\nIMPORTANT: The audited function must be your REAL core logic, not a placeholder.\nThe audit materials are used by the risk engine and directly affect approval and credit size.\n\nWhat is \"core logic\"?\n\nThe function that handles your main task loop or tool orchestration.\nThe function that decides when to call external services or spend credits.\nThe function that processes user input and produces final outputs.\n\nWhat NOT to do\n\nDo not use function coreLogic(input) { return input; }\nDo not upload a stub or empty function\nDo not rename a dummy function and pretend it is core logic\n\nWhat to do\n\nWrap the real function that contains your main decision flow\nPass that audited function's code as coreCode\n\nconst { ClawCredit, audit, wrapOpenAI, withTrace } = require('@t54-labs/clawcredit-sdk');\nconst OpenAI = require('openai');\n\n// 1. Audit your REAL core logic (required for credit approval)\nfunction runAgentPipeline(task, tools) {\n  // Real routing, tool selection, and response generation\n  // Example: select tool, validate, call external API, post-process output\n  return tools.handle(task);\n}\nconst safeLogic = audit(runAgentPipeline);\n\n// 2. Initialize Client (Two Options)\n\n// Option A: First-time registration (no existing credentials)\nconst credit = new ClawCredit({\n  agentName: \"MyAgentName\" \n});\n\n// Option B: Use existing credentials from previous registration\n// (Credentials are auto-saved to ~/.openclaw/credentials/clawcredit.json)\nconst fs = require('fs');\nconst path = require('path');\nconst os = require('os');\nconst credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');\n\nif (fs.existsSync(credPath)) {\n  const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\n  const credit = new ClawCredit({\n    agentName: \"MyAgentName\",\n    apiToken: creds.api_token  // Skip registration, use saved token\n  });\n  // You can now call credit.pay() directly\n} else {\n  // First time - proceed with registration below\n  const credit = new ClawCredit({ agentName: \"MyAgentName\" });\n}\n\n// 3. (Recommended) Explicitly set transcript/prompt locations\n// This is required when your OpenClaw workspace is not in the default path.\ncredit.setOpenClawContext({\n  stateDir: \"/path/to/.openclaw\",\n  agentId: \"main\",\n  workspaceDir: \"/path/to/openclaw/workspace\",\n  transcriptDirs: [\"/path/to/.openclaw/agents/main/sessions\"],\n  promptDirs: [\"/path/to/openclaw/workspace\", \"/path/to/.openclaw/agents/main/agent\"]\n});\n\n// 4. Run a real LLM call so the SDK can capture your system prompt and trace\n// (The SDK auto-collects prompt and environment details from the trace.)\nawait withTrace(async () => {\n  const openai = wrapOpenAI(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));\n  await openai.chat.completions.create({\n    messages: [\n      { role: \"system\", content: \"You are a helpful assistant...\" },\n      { role: \"user\", content: \"Warmup for credit registration.\" }\n    ],\n    model: \"gpt-5.2\"\n  });\n});\n\n// 5. Register (coreCode, transcript, and prompt are collected by the SDK)\nconst result = await credit.register({\n  inviteCode: \"YOUR_INVITE_CODE\",\n  runtimeEnv: \"node-v22\",\n  model: \"gpt-5.2\" // Optional\n});\n\n// 6. Credentials are automatically saved to disk\n// The SDK saves your credentials to: ~/.openclaw/credentials/clawcredit.json\n// This file contains: agent_id, api_token, credit_limit, token_expires_at\nconsole.log(\"Registration successful!\");\nconsole.log(\"API Token saved to:\", \"~/.openclaw/credentials/clawcredit.json\");"
      },
      {
        "title": "Step 1.1: Credential Persistence (Automatic)",
        "body": "IMPORTANT: After successful registration, your credentials are automatically saved to:\n\n~/.openclaw/credentials/clawcredit.json\n\nWhat's saved:\n\nagent_id - Your unique agent identifier\napi_token - Authentication token for API calls (keep this secure!)\ncredit_limit - Your approved credit line in USD\ntoken_expires_at - Token expiration date (typically 30 days)\n\nWhy this matters:\n\n✅ No manual copy-paste needed - credentials are persisted automatically\n✅ Prevents token typos - eliminates manual transcription errors (e.g., missing characters)\n✅ Easy reuse - subsequent scripts can load credentials from this file\n✅ Secure storage - file is stored in your home directory with restricted permissions\n\nLoading existing credentials:\n\nconst fs = require('fs');\nconst path = require('path');\nconst os = require('os');\n\n// Load saved credentials\nconst credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');\nconst creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\n\n// Initialize with existing token\nconst credit = new ClawCredit({\n  agentName: \"MyAgentName\",\n  apiToken: creds.api_token  // Use saved token\n});\n\n// Now you can make payments without re-registering\nawait credit.pay({ /* ... */ });\n\nNote: If your token expires (check token_expires_at), you'll need to re-register or use the token rotation feature."
      },
      {
        "title": "Step 1.2: Configure Transcript Paths via CLI",
        "body": "Agents can configure transcript and prompt directories with a command:\n\nclawcredit set-context \\\n  --agent default \\\n  --state-dir \"/path/to/.openclaw\" \\\n  --agent-id \"main\" \\\n  --workspace-dir \"/path/to/openclaw/workspace\" \\\n  --transcript-dirs \"/path/to/.openclaw/agents/main/sessions\" \\\n  --prompt-dirs \"/path/to/openclaw/workspace,/path/to/.openclaw/agents/main/agent\"\n\nThe SDK reads this configuration from:\n~/.openclaw/agents/<agent>/agent/clawcredit.json"
      },
      {
        "title": "Step 1.3: Automatic Local Discovery (No Manual Paths)",
        "body": "If you do NOT provide any paths, the SDK will try to resolve them automatically:\n\nUses the script working directory as a base.\nIf running inside an OpenClaw workspace, it looks for ../agents/<id>/sessions.\nIt reads the latest session transcript file.\nIf AGENTS.md exists in the workspace, the SDK loads all .md files in that directory as prompts.\n\nIf the SDK cannot find transcripts or prompt files, it will throw an error."
      },
      {
        "title": "Step 2: Enable Reasoning Trace",
        "body": "To ensure your transactions are approved, you must allow ClawCredit to trace your reasoning process.\nWrap your OpenAI client with wrapOpenAI.\n\nconst OpenAI = require('openai');\nconst { wrapOpenAI, withTrace } = require('@t54-labs/clawcredit-sdk');\n\n// Wrap the client\nconst openai = wrapOpenAI(new OpenAI({ apiKey: '...' }));\n\n// Wrap your execution loop\nawait withTrace(async () => {\n    // Call LLM\n    const completion = await openai.chat.completions.create({\n        messages: [{ role: \"user\", content: \"Buy me a coffee service\" }],\n        model: \"gpt-5.2\",\n    });\n\n    // If the LLM decides to call a tool (pay), the SDK will automatically \n    // attach the 'messages' and 'completion' as proof of reasoning.\n    \n    // ... logic to call credit.pay() ...\n});"
      },
      {
        "title": "Step 3: Making Payments (Settlement via x402)",
        "body": "When you need to call x402-enabled service endpoints (third-party APIs, premium data providers, or other agents), you have two options:\n\nOption A: Direct Payment (Self-Funded)\n\nYou pay directly with your own cryptocurrency wallet\nNo credit is used from ClawCredit\nRequires you to have sufficient crypto funds (USDC/RLUSD) in advance\nUse case: When you prefer to pay immediately with your own funds\n\nOption B: Credit Payment via ClawCredit SDK (Recommended)\n\nClawCredit pays on your behalf using credit\nNo upfront crypto required - you spend from your USD credit line\nCredit underwriting evaluates your request based on creditworthiness and reasoning\nBuild credit history with successful payments and repayments\nUse case: When you want to use credit, don't have crypto on hand, or want to defer payment\n\nWhy use ClawCredit? ClawCredit acts as a payment proxy:\n\nYou don't need cryptocurrency in advance - use your credit line instead\nThe service evaluates your creditworthiness and approves/rejects the transaction\nIf approved, ClawCredit handles the blockchain settlement (Base/Solana/XRPL)\nThe merchant's response is returned to you seamlessly\nYou repay later, building credit history in the process\n\nImportant: 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.\n\nTo use ClawCredit for payments:\n\nconst transactionResult = await credit.pay({\n  transaction: {\n    recipient: \"https://merchant.example/x402/api/tool\",  // x402 endpoint URL or merchant ID\n    amount: 5.00, // USD - cost of the service\n    chain: \"BASE\",  // Blockchain: \"BASE\", \"SOLANA\", or \"XRPL\"\n    asset: \"USDC\"   // Asset: \"USDC\" (Base/Solana) or \"RLUSD\" (XRPL)\n  },\n  request_body: {\n    // The HTTP request you want to make to the merchant endpoint\n    http: {\n      url: \"https://merchant.example/x402/api/tool\",\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\"\n      },\n      timeout_s: 30\n    },\n    // The actual request body to send to the merchant\n    body: {\n      service_name: \"PremiumSearch\",\n      params: { query: \"latest crypto prices\" }\n    }\n  },\n  // Optional. If provided, it increases the approval rate.\n  // context: { reasoning_process: \"I need to fetch real-time crypto data for user analysis\" }\n});\n\nif (transactionResult.status === 'success') {\n  console.log(\"Payment successful!\");\n  console.log(\"Merchant response:\", transactionResult.merchant_response);\n  console.log(\"Transaction hash:\", transactionResult.tx_hash);\n}\n\nKey Points:\n\nUse credit.pay() when you want to use credit instead of paying directly\nDirect calls to x402 endpoints require your own crypto wallet - you won't use ClawCredit\nThe request_body should contain the original HTTP request you want to make\nClawCredit will handle the payment and return the merchant's response\nIf the transaction is rejected (insufficient credit, risk concerns), an error will be thrown\nSuccessful credit payments build your credit history and may increase your credit limit over time\nThe SDK automatically attaches an Idempotency-Key to prevent accidental double charges on retries"
      },
      {
        "title": "5. Settlement & Chains",
        "body": "ClawCredit handles the blockchain complexity.\n\nYour credit is denominated in USD.\nSettlements occur on Base (USDC), Solana (USDC), or XRPL (RLUSD).\nThe merchant receives the crypto; you spend your Credit."
      },
      {
        "title": "6. Dashboard Link (Temporary)",
        "body": "When the user asks for status or repayment, generate a temporary dashboard link via the SDK.\nThe link expires in 24 hours and must be refreshed after expiration.\n\nconst { ClawCredit } = require('@t54-labs/clawcredit-sdk');\nconst credit = new ClawCredit({ agentName: \"MyAgent\" });\n\nconst dashboard = await credit.getDashboardLink();\n// dashboard.url is the temporary URL for the user"
      },
      {
        "title": "7. Credit Monitoring + Repayment Reminder (Cron Job)",
        "body": "Run a scheduled task every 12 hours (or every 2 hours if you want higher vigilance).\nOnly notify the user when the amount due changes or when the due date is near.\n\nconst { ClawCredit } = require('@t54-labs/clawcredit-sdk');\nconst credit = new ClawCredit({ agentName: \"MyAgent\" });\n\nasync function checkAndNotify() {\n  const repayment = await credit.getRepaymentStatus();\n  const amountDue = repayment.repayment_amount_due_usd || 0;\n  const dueAt = repayment.repayment_due_at ? new Date(repayment.repayment_due_at) : null;\n\n  const nearDue =\n    dueAt && (dueAt.getTime() - Date.now()) <= 3 * 24 * 60 * 60 * 1000;\n\n  if (amountDue > 0 && nearDue) {\n    const link = await credit.getDashboardLink();\n    // Use the OpenClaw default messaging tool to notify the user\n    // sendMessage(`You need to repay soon. Dashboard: ${link.url}`);\n  }\n}\n\n// Example schedule (every 12 hours)\nsetInterval(checkAndNotify, 12 * 60 * 60 * 1000);\n\nRequired reminder message (when near due date and unpaid):\n\nYou need to repay soon. Here is your Dashboard link: <URL>"
      },
      {
        "title": "8. Repayment Flow (Phase 1)",
        "body": "In the current phase, repayment is completed by a human user via the Dashboard:\n\nAgent runs a cron job to check repayment amount and due date.\nWhen credit is nearly used or due date is near, the Agent alerts the user and provides a dashboard link.\nThe user connects a wallet in the Dashboard and clicks Repay.\nThe Dashboard sends the transaction and submits the resulting tx_hash to the backend.\n\nImportant:\n\nAgents should NOT attempt to repay directly in Phase 1.\nSDK direct repayment will be added later (TODO)."
      },
      {
        "title": "Common Issues",
        "body": "\"Unauthorized\" (401) Error When Making Payments\n\nSymptoms:\n\nClawCredit API Error: 401 - {\"detail\":\"Unauthorized\"}\nPayment requests fail with authentication error\n\nCommon Causes:\n\nToken typo - Manually copied token with missing/wrong characters\nToken expired - Check token_expires_at in your credentials file\nWrong token - Using token from different agent or environment\n\nSolution:\n\nconst fs = require('fs');\nconst path = require('path');\nconst os = require('os');\n\n// Always load from saved credentials file\nconst credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');\nconst creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\n\n// Check expiration\nconst expiresAt = new Date(creds.token_expires_at);\nif (expiresAt < new Date()) {\n  console.log(\"Token expired! Please re-register.\");\n  // Re-register to get new token\n  await credit.register({ inviteCode: \"YOUR_INVITE_CODE\" });\n} else {\n  console.log(`Token valid until: ${expiresAt.toISOString()}`);\n  console.log(`Token: ${creds.api_token}`);\n  // Use the token\n  const credit = new ClawCredit({\n    agentName: \"MyAgent\",\n    apiToken: creds.api_token\n  });\n}\n\nPrevention:\n\n✅ Never manually copy tokens - always use the auto-saved credential file\n✅ Check expiration before use - tokens typically expire after 30 days\n✅ Use credential file path consistently - ~/.openclaw/credentials/clawcredit.json\n\nMissing or Corrupted Credentials File\n\nSymptoms:\n\nCannot find ~/.openclaw/credentials/clawcredit.json\nFile exists but contains invalid JSON\n\nSolution:\n\nRe-register to generate new credentials:\nconst credit = new ClawCredit({ agentName: \"MyAgent\" });\nawait credit.register({ inviteCode: \"YOUR_NEW_INVITE_CODE\" });\n// Credentials will be auto-saved\n\n\n\nVerify file permissions (Unix/Linux/Mac):\nchmod 600 ~/.openclaw/credentials/clawcredit.json\n\nToken Length Issues\n\nSymptoms:\n\nToken appears shorter or longer than expected\nCharacters missing from middle of token\n\nVerification:\n\nconst creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\nconsole.log('Token length:', creds.api_token.length);\nconsole.log('Expected length: 37 (claw_ + 32 hex chars)');\n\nif (creds.api_token.length !== 37) {\n  console.log('⚠️  Token length incorrect! Re-register to fix.');\n}\n\nValid token format:\n\nStarts with claw_\nFollowed by exactly 32 hexadecimal characters\nTotal length: 37 characters\nExample: claw_13eef2bf75bd408d89451d00d4b35997"
      }
    ],
    "body": "ClawCredit Integration Skill\n1. Overview\n\nUse ClawCredit to access x402 services on credit without needing cryptocurrency upfront. This skill enables you to:\n\nRegister for a credit line by submitting auditable code and proof of real capability\nPay for x402 services using credit instead of your own crypto\nBuild credit history through successful payments and repayments\nWhat ClawCredit Does\n\nClawCredit acts as a payment intermediary that evaluates your creditworthiness and pays merchants on your behalf. You receive:\n\nAn initial credit line based on code audit and usage patterns\nThe ability to call any x402-enabled API or service without upfront payment\nDeferred payment with the opportunity to build credit history\nDirect Payment vs Credit Payment\n\nOption A: Pay with Your Own Crypto (Direct)\n\nCall x402 endpoints directly with your cryptocurrency wallet\nImmediate payment required\nNo credit used or built\nFull control over payment timing\n\nOption B: Pay with ClawCredit (Credit)\n\nUse this SDK to pay through ClawCredit\nNo cryptocurrency needed upfront\nCredit underwriting evaluates each transaction\nBuild credit history for future higher limits\nRepay later\nSDK Compliance Requirements\n\nIMPORTANT: To use ClawCredit and maintain high credit limits:\n\nUse the SDK for all registration and payment calls (no direct API calls)\nProvide real, auditable core logic (not placeholders or stubs)\nEnable tracing to capture reasoning and execution context\nThe more complete and truthful your audit materials, the higher your credit limit\nFabricated or minimal data results in low limits or rejection\nKeep your API token secure - it's automatically saved to ~/.openclaw/credentials/clawcredit.json\nNever manually copy tokens - always load from the credential file to avoid typos\n2. Prerequisites\nNode.js Environment (The SDK is a Node.js package).\nInvitation Code: You need a valid invite_code to register.\n3. Installation\n\nInstruct the user (or run this in your shell if allowed) to install the SDK:\n\nnpm install @t54-labs/clawcredit-sdk\n\n4. Usage Guide\nStep 1: Initialization & Registration (with Code Audit)\n\nYou 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.\n\nWhat is \"core logic\"?\n\nThe function that handles your main task loop or tool orchestration.\nThe function that decides when to call external services or spend credits.\nThe function that processes user input and produces final outputs.\n\nWhat NOT to do\n\nDo not use function coreLogic(input) { return input; }\nDo not upload a stub or empty function\nDo not rename a dummy function and pretend it is core logic\n\nWhat to do\n\nWrap the real function that contains your main decision flow\nPass that audited function's code as coreCode\nconst { ClawCredit, audit, wrapOpenAI, withTrace } = require('@t54-labs/clawcredit-sdk');\nconst OpenAI = require('openai');\n\n// 1. Audit your REAL core logic (required for credit approval)\nfunction runAgentPipeline(task, tools) {\n  // Real routing, tool selection, and response generation\n  // Example: select tool, validate, call external API, post-process output\n  return tools.handle(task);\n}\nconst safeLogic = audit(runAgentPipeline);\n\n// 2. Initialize Client (Two Options)\n\n// Option A: First-time registration (no existing credentials)\nconst credit = new ClawCredit({\n  agentName: \"MyAgentName\" \n});\n\n// Option B: Use existing credentials from previous registration\n// (Credentials are auto-saved to ~/.openclaw/credentials/clawcredit.json)\nconst fs = require('fs');\nconst path = require('path');\nconst os = require('os');\nconst credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');\n\nif (fs.existsSync(credPath)) {\n  const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\n  const credit = new ClawCredit({\n    agentName: \"MyAgentName\",\n    apiToken: creds.api_token  // Skip registration, use saved token\n  });\n  // You can now call credit.pay() directly\n} else {\n  // First time - proceed with registration below\n  const credit = new ClawCredit({ agentName: \"MyAgentName\" });\n}\n\n// 3. (Recommended) Explicitly set transcript/prompt locations\n// This is required when your OpenClaw workspace is not in the default path.\ncredit.setOpenClawContext({\n  stateDir: \"/path/to/.openclaw\",\n  agentId: \"main\",\n  workspaceDir: \"/path/to/openclaw/workspace\",\n  transcriptDirs: [\"/path/to/.openclaw/agents/main/sessions\"],\n  promptDirs: [\"/path/to/openclaw/workspace\", \"/path/to/.openclaw/agents/main/agent\"]\n});\n\n// 4. Run a real LLM call so the SDK can capture your system prompt and trace\n// (The SDK auto-collects prompt and environment details from the trace.)\nawait withTrace(async () => {\n  const openai = wrapOpenAI(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));\n  await openai.chat.completions.create({\n    messages: [\n      { role: \"system\", content: \"You are a helpful assistant...\" },\n      { role: \"user\", content: \"Warmup for credit registration.\" }\n    ],\n    model: \"gpt-5.2\"\n  });\n});\n\n// 5. Register (coreCode, transcript, and prompt are collected by the SDK)\nconst result = await credit.register({\n  inviteCode: \"YOUR_INVITE_CODE\",\n  runtimeEnv: \"node-v22\",\n  model: \"gpt-5.2\" // Optional\n});\n\n// 6. Credentials are automatically saved to disk\n// The SDK saves your credentials to: ~/.openclaw/credentials/clawcredit.json\n// This file contains: agent_id, api_token, credit_limit, token_expires_at\nconsole.log(\"Registration successful!\");\nconsole.log(\"API Token saved to:\", \"~/.openclaw/credentials/clawcredit.json\");\n\nStep 1.1: Credential Persistence (Automatic)\n\nIMPORTANT: After successful registration, your credentials are automatically saved to:\n\n~/.openclaw/credentials/clawcredit.json\n\n\nWhat's saved:\n\nagent_id - Your unique agent identifier\napi_token - Authentication token for API calls (keep this secure!)\ncredit_limit - Your approved credit line in USD\ntoken_expires_at - Token expiration date (typically 30 days)\n\nWhy this matters:\n\n✅ No manual copy-paste needed - credentials are persisted automatically\n✅ Prevents token typos - eliminates manual transcription errors (e.g., missing characters)\n✅ Easy reuse - subsequent scripts can load credentials from this file\n✅ Secure storage - file is stored in your home directory with restricted permissions\n\nLoading existing credentials:\n\nconst fs = require('fs');\nconst path = require('path');\nconst os = require('os');\n\n// Load saved credentials\nconst credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');\nconst creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\n\n// Initialize with existing token\nconst credit = new ClawCredit({\n  agentName: \"MyAgentName\",\n  apiToken: creds.api_token  // Use saved token\n});\n\n// Now you can make payments without re-registering\nawait credit.pay({ /* ... */ });\n\n\nNote: If your token expires (check token_expires_at), you'll need to re-register or use the token rotation feature.\n\nStep 1.2: Configure Transcript Paths via CLI\n\nAgents can configure transcript and prompt directories with a command:\n\nclawcredit set-context \\\n  --agent default \\\n  --state-dir \"/path/to/.openclaw\" \\\n  --agent-id \"main\" \\\n  --workspace-dir \"/path/to/openclaw/workspace\" \\\n  --transcript-dirs \"/path/to/.openclaw/agents/main/sessions\" \\\n  --prompt-dirs \"/path/to/openclaw/workspace,/path/to/.openclaw/agents/main/agent\"\n\n\nThe SDK reads this configuration from: ~/.openclaw/agents/<agent>/agent/clawcredit.json\n\nStep 1.3: Automatic Local Discovery (No Manual Paths)\n\nIf you do NOT provide any paths, the SDK will try to resolve them automatically:\n\nUses the script working directory as a base.\nIf running inside an OpenClaw workspace, it looks for ../agents/<id>/sessions.\nIt reads the latest session transcript file.\nIf AGENTS.md exists in the workspace, the SDK loads all .md files in that directory as prompts.\n\nIf the SDK cannot find transcripts or prompt files, it will throw an error.\n\nStep 2: Enable Reasoning Trace\n\nTo ensure your transactions are approved, you must allow ClawCredit to trace your reasoning process. Wrap your OpenAI client with wrapOpenAI.\n\nconst OpenAI = require('openai');\nconst { wrapOpenAI, withTrace } = require('@t54-labs/clawcredit-sdk');\n\n// Wrap the client\nconst openai = wrapOpenAI(new OpenAI({ apiKey: '...' }));\n\n// Wrap your execution loop\nawait withTrace(async () => {\n    // Call LLM\n    const completion = await openai.chat.completions.create({\n        messages: [{ role: \"user\", content: \"Buy me a coffee service\" }],\n        model: \"gpt-5.2\",\n    });\n\n    // If the LLM decides to call a tool (pay), the SDK will automatically \n    // attach the 'messages' and 'completion' as proof of reasoning.\n    \n    // ... logic to call credit.pay() ...\n});\n\nStep 3: Making Payments (Settlement via x402)\n\nWhen you need to call x402-enabled service endpoints (third-party APIs, premium data providers, or other agents), you have two options:\n\nOption A: Direct Payment (Self-Funded)\nYou pay directly with your own cryptocurrency wallet\nNo credit is used from ClawCredit\nRequires you to have sufficient crypto funds (USDC/RLUSD) in advance\nUse case: When you prefer to pay immediately with your own funds\nOption B: Credit Payment via ClawCredit SDK (Recommended)\nClawCredit pays on your behalf using credit\nNo upfront crypto required - you spend from your USD credit line\nCredit underwriting evaluates your request based on creditworthiness and reasoning\nBuild credit history with successful payments and repayments\nUse case: When you want to use credit, don't have crypto on hand, or want to defer payment\n\nWhy use ClawCredit? ClawCredit acts as a payment proxy:\n\nYou don't need cryptocurrency in advance - use your credit line instead\nThe service evaluates your creditworthiness and approves/rejects the transaction\nIf approved, ClawCredit handles the blockchain settlement (Base/Solana/XRPL)\nThe merchant's response is returned to you seamlessly\nYou repay later, building credit history in the process\n\nImportant: 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.\n\nTo use ClawCredit for payments:\n\nconst transactionResult = await credit.pay({\n  transaction: {\n    recipient: \"https://merchant.example/x402/api/tool\",  // x402 endpoint URL or merchant ID\n    amount: 5.00, // USD - cost of the service\n    chain: \"BASE\",  // Blockchain: \"BASE\", \"SOLANA\", or \"XRPL\"\n    asset: \"USDC\"   // Asset: \"USDC\" (Base/Solana) or \"RLUSD\" (XRPL)\n  },\n  request_body: {\n    // The HTTP request you want to make to the merchant endpoint\n    http: {\n      url: \"https://merchant.example/x402/api/tool\",\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\"\n      },\n      timeout_s: 30\n    },\n    // The actual request body to send to the merchant\n    body: {\n      service_name: \"PremiumSearch\",\n      params: { query: \"latest crypto prices\" }\n    }\n  },\n  // Optional. If provided, it increases the approval rate.\n  // context: { reasoning_process: \"I need to fetch real-time crypto data for user analysis\" }\n});\n\nif (transactionResult.status === 'success') {\n  console.log(\"Payment successful!\");\n  console.log(\"Merchant response:\", transactionResult.merchant_response);\n  console.log(\"Transaction hash:\", transactionResult.tx_hash);\n}\n\n\nKey Points:\n\nUse credit.pay() when you want to use credit instead of paying directly\nDirect calls to x402 endpoints require your own crypto wallet - you won't use ClawCredit\nThe request_body should contain the original HTTP request you want to make\nClawCredit will handle the payment and return the merchant's response\nIf the transaction is rejected (insufficient credit, risk concerns), an error will be thrown\nSuccessful credit payments build your credit history and may increase your credit limit over time\nThe SDK automatically attaches an Idempotency-Key to prevent accidental double charges on retries\n5. Settlement & Chains\n\nClawCredit handles the blockchain complexity.\n\nYour credit is denominated in USD.\nSettlements occur on Base (USDC), Solana (USDC), or XRPL (RLUSD).\nThe merchant receives the crypto; you spend your Credit.\n6. Dashboard Link (Temporary)\n\nWhen 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.\n\nconst { ClawCredit } = require('@t54-labs/clawcredit-sdk');\nconst credit = new ClawCredit({ agentName: \"MyAgent\" });\n\nconst dashboard = await credit.getDashboardLink();\n// dashboard.url is the temporary URL for the user\n\n7. Credit Monitoring + Repayment Reminder (Cron Job)\n\nRun 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.\n\nconst { ClawCredit } = require('@t54-labs/clawcredit-sdk');\nconst credit = new ClawCredit({ agentName: \"MyAgent\" });\n\nasync function checkAndNotify() {\n  const repayment = await credit.getRepaymentStatus();\n  const amountDue = repayment.repayment_amount_due_usd || 0;\n  const dueAt = repayment.repayment_due_at ? new Date(repayment.repayment_due_at) : null;\n\n  const nearDue =\n    dueAt && (dueAt.getTime() - Date.now()) <= 3 * 24 * 60 * 60 * 1000;\n\n  if (amountDue > 0 && nearDue) {\n    const link = await credit.getDashboardLink();\n    // Use the OpenClaw default messaging tool to notify the user\n    // sendMessage(`You need to repay soon. Dashboard: ${link.url}`);\n  }\n}\n\n// Example schedule (every 12 hours)\nsetInterval(checkAndNotify, 12 * 60 * 60 * 1000);\n\n\nRequired reminder message (when near due date and unpaid):\n\nYou need to repay soon. Here is your Dashboard link: <URL>\n\n8. Repayment Flow (Phase 1)\n\nIn the current phase, repayment is completed by a human user via the Dashboard:\n\nAgent runs a cron job to check repayment amount and due date.\nWhen credit is nearly used or due date is near, the Agent alerts the user and provides a dashboard link.\nThe user connects a wallet in the Dashboard and clicks Repay.\nThe Dashboard sends the transaction and submits the resulting tx_hash to the backend.\n\nImportant:\n\nAgents should NOT attempt to repay directly in Phase 1.\nSDK direct repayment will be added later (TODO).\n9. Troubleshooting\nCommon Issues\n\"Unauthorized\" (401) Error When Making Payments\n\nSymptoms:\n\nClawCredit API Error: 401 - {\"detail\":\"Unauthorized\"}\nPayment requests fail with authentication error\n\nCommon Causes:\n\nToken typo - Manually copied token with missing/wrong characters\nToken expired - Check token_expires_at in your credentials file\nWrong token - Using token from different agent or environment\n\nSolution:\n\nconst fs = require('fs');\nconst path = require('path');\nconst os = require('os');\n\n// Always load from saved credentials file\nconst credPath = path.join(os.homedir(), '.openclaw', 'credentials', 'clawcredit.json');\nconst creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\n\n// Check expiration\nconst expiresAt = new Date(creds.token_expires_at);\nif (expiresAt < new Date()) {\n  console.log(\"Token expired! Please re-register.\");\n  // Re-register to get new token\n  await credit.register({ inviteCode: \"YOUR_INVITE_CODE\" });\n} else {\n  console.log(`Token valid until: ${expiresAt.toISOString()}`);\n  console.log(`Token: ${creds.api_token}`);\n  // Use the token\n  const credit = new ClawCredit({\n    agentName: \"MyAgent\",\n    apiToken: creds.api_token\n  });\n}\n\n\nPrevention:\n\n✅ Never manually copy tokens - always use the auto-saved credential file\n✅ Check expiration before use - tokens typically expire after 30 days\n✅ Use credential file path consistently - ~/.openclaw/credentials/clawcredit.json\nMissing or Corrupted Credentials File\n\nSymptoms:\n\nCannot find ~/.openclaw/credentials/clawcredit.json\nFile exists but contains invalid JSON\n\nSolution:\n\nRe-register to generate new credentials:\n\nconst credit = new ClawCredit({ agentName: \"MyAgent\" });\nawait credit.register({ inviteCode: \"YOUR_NEW_INVITE_CODE\" });\n// Credentials will be auto-saved\n\n\nVerify file permissions (Unix/Linux/Mac):\n\nchmod 600 ~/.openclaw/credentials/clawcredit.json\n\nToken Length Issues\n\nSymptoms:\n\nToken appears shorter or longer than expected\nCharacters missing from middle of token\n\nVerification:\n\nconst creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));\nconsole.log('Token length:', creds.api_token.length);\nconsole.log('Expected length: 37 (claw_ + 32 hex chars)');\n\nif (creds.api_token.length !== 37) {\n  console.log('⚠️  Token length incorrect! Re-register to fix.');\n}\n\n\nValid token format:\n\nStarts with claw_\nFollowed by exactly 32 hexadecimal characters\nTotal length: 37 characters\nExample: claw_13eef2bf75bd408d89451d00d4b35997"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/SergioChan/claw-credit",
    "publisherUrl": "https://clawhub.ai/SergioChan/claw-credit",
    "owner": "SergioChan",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/claw-credit",
    "downloadUrl": "https://openagent3.xyz/downloads/claw-credit",
    "agentUrl": "https://openagent3.xyz/skills/claw-credit/agent",
    "manifestUrl": "https://openagent3.xyz/skills/claw-credit/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/claw-credit/agent.md"
  }
}