Skip to main content

Python SDK for MoltsPay - Agent-to-Agent Payments. LangChain compatible.

Project description

MoltsPay Python SDK

PyPI version Python versions License: MIT

Python SDK for MoltsPay - Agent-to-Agent Payments.

MoltsPay enables AI agents to pay each other for services using the x402 protocol - HTTP-native payments with USDC stablecoins. No gas fees, no complex wallet management.

What is MoltsPay?

MoltsPay is blockchain payment infrastructure designed for AI agents. It solves a fundamental problem: how do autonomous AI agents pay for services?

  • ๐Ÿค– Agent-to-Agent Commerce - AI agents can autonomously discover, pay for, and use services
  • ๐Ÿ’จ Gasless Payments - Uses EIP-2612 permits, no ETH needed
  • ๐Ÿ”— x402 Protocol - HTTP 402 Payment Required - payments as native HTTP flow
  • ๐Ÿ”’ Spending Limits - Set per-transaction and daily limits for safety
  • ๐ŸŒ Multi-Chain - Base and Polygon supported
  • ๐Ÿฆœ LangChain Ready - Drop-in tools for LangChain agents

Installation

pip install moltspay

For LangChain integration:

pip install moltspay[langchain]

Quick Start

from moltspay import MoltsPay

# Initialize (auto-creates wallet if not exists)
client = MoltsPay()
print(f"Wallet address: {client.address}")

# Discover services from a provider
services = client.discover("https://juai8.com/zen7")
for svc in services:
    print(f"{svc.id}: {svc.price} {svc.currency}")

# Pay for a service
result = client.pay(
    "https://juai8.com/zen7",
    "text-to-video",
    prompt="a cat dancing on the beach"
)
print(result.result)

Testnet Quickstart

New to MoltsPay? Start on testnet - no real money needed!

from moltspay import MoltsPay

# Initialize on Base Sepolia testnet
client = MoltsPay(chain="base_sepolia")
print(f"Wallet: {client.address}")

# Get free testnet USDC (1 USDC, once per 24h)
result = client.faucet()
if result.success:
    print(f"Got {result.amount} USDC! TX: {result.tx_hash}")

# Make a test payment
result = client.pay(
    "https://moltspay.com/a/yaqing",
    "text-to-video",
    prompt="a robot dancing in the rain"
)
print(result)

Get Testnet USDC:

  • MoltsPay faucet: client.faucet() (1 USDC, once per 24h)
  • Circle faucet: https://faucet.circle.com/ (select Base Sepolia, get 10 USDC)

Run the demo:

python demos/testnet_faucet_demo.py

Features

Auto Wallet Management

Wallet is automatically created on first run and stored at ~/.moltspay/wallet.json. Compatible with Node.js CLI.

from moltspay import MoltsPay

client = MoltsPay()
print(f"Address: {client.address}")

Funding Your Wallet

Before making payments, you need USDC in your wallet.

Option 1: Testnet (Free - For Testing)

Use the faucet to get free testnet USDC:

from moltspay import MoltsPay

# Initialize on testnet
client = MoltsPay(chain="base_sepolia")
print(f"Wallet: {client.address}")

# Get 1 free USDC (once per 24 hours)
result = client.faucet()
if result.success:
    print(f"Received {result.amount} USDC!")
    print(f"TX: {result.tx_hash}")
else:
    print(f"Error: {result.error}")

Alternative: Use Circle's faucet to get 10 USDC on Base Sepolia.

Option 2: Mainnet (Real Money)

Method A: Coinbase Onramp (Easiest)

Buy USDC with debit card or Apple Pay:

from moltspay import MoltsPay

client = MoltsPay()  # Default: Base mainnet

# Generate funding link (opens Coinbase Onramp)
result = client.fund(10)  # $10 minimum
print(f"Open this URL to pay: {result.url}")

# Or print QR code to terminal
client.fund_qr(10)

Method B: Direct Transfer

Send USDC from any wallet (Coinbase, MetaMask, etc.):

from moltspay import MoltsPay

client = MoltsPay()
print(f"Send USDC to: {client.address}")
print(f"Chain: Base (chainId: 8453)")

โš ๏ธ Important: Send USDC on the Base chain, not Ethereum mainnet!

Spending Limits

Control your agent's spending with built-in limits:

from moltspay import MoltsPay

client = MoltsPay()

# Check current limits
limits = client.limits()
print(f"Max per tx: {limits.max_per_tx}")
print(f"Max per day: {limits.max_per_day}")
print(f"Spent today: {limits.spent_today}")

# Update limits
client.set_limits(max_per_tx=20, max_per_day=200)

Multi-Chain Support

MoltsPay supports multiple chains. Default is Base, but you can use Polygon:

from moltspay import MoltsPay

# Default: Base
client = MoltsPay()

# Use Polygon
client = MoltsPay(chain='polygon')

# Pay on Polygon
result = client.pay(
    "https://juai8.com/zen7",
    "text-to-video",
    prompt="a cat dancing"
)

Supported Chains:

Chain Network ID Token Type
Base eip155:8453 USDC Mainnet
Polygon eip155:137 USDC Mainnet
Base Sepolia eip155:84532 USDC Testnet

All chains are gasless - the CDP facilitator handles all on-chain settlement.

For testnet, use client.faucet() to get free test USDC.

Async Support

Full async/await support for high-performance applications:

import asyncio
from moltspay import AsyncMoltsPay

async def main():
    async with AsyncMoltsPay() as client:
        result = await client.pay(
            "https://juai8.com/zen7",
            "text-to-video",
            prompt="a cat dancing"
        )
        print(result.result)

asyncio.run(main())

Error Handling

Comprehensive exception types for robust error handling:

from moltspay import MoltsPay, InsufficientFunds, LimitExceeded, PaymentError

client = MoltsPay()

try:
    result = client.pay(...)
except InsufficientFunds as e:
    print(f"Need {e.required} USDC, have {e.balance}")
except LimitExceeded as e:
    print(f"Exceeds {e.limit_type} limit: {e.amount} > {e.limit}")
except PaymentError as e:
    print(f"Payment failed: {e}")

API Reference

Complete Method List

Method Description Returns
client.pay(provider_url, service_id, **params) Pay for and execute a service PaymentResult
client.discover(provider_url) List services from a provider List[Service]
client.balance() Get wallet USDC balance Balance
client.limits() Get current spending limits Limits
client.set_limits(max_per_tx, max_per_day) Set spending limits None
client.faucet() Get free testnet USDC (1/day) FaucetResult
client.fund(amount) Open funding page FundingResult
client.address Property: wallet address str

The .pay() Method

This is the only method for making payments:

result = client.pay(
    provider_url: str,         # e.g., "https://juai8.com/zen7"
    service_id: str,           # e.g., "text-to-video"  
    token: str = "USDC",       # "USDC" or "USDT"
    **params                   # Service-specific parameters
)

# Examples:
result = client.pay("https://juai8.com/zen7", "text-to-video", prompt="a cat")
result = client.pay("https://juai8.com/zen7", "image-to-video", image_url="https://...")

PaymentResult Object

result.success      # bool - True if payment succeeded
result.amount       # float - Amount paid (e.g., 0.99)
result.currency     # str - "USDC" or "USDT"
result.tx_hash      # str - Blockchain transaction hash
result.result       # Any - Service result (e.g., video URL)
result.error        # str | None - Error message if failed

โš ๏ธ Methods That DO NOT Exist

The following methods are sometimes incorrectly suggested by AI assistants, but they do not exist:

# โŒ WRONG - These DO NOT exist:
client.x402(...)           # NO! 
client.transfer(...)       # NO!
client.send(...)           # NO!
client.execute(...)        # NO!
client.call_service(...)   # NO!
client.request(...)        # NO!
client.make_payment(...)   # NO!

# โœ… CORRECT - Use this:
client.pay(provider_url, service_id, **params)

LangChain Integration

Use MoltsPay as tools in your LangChain agents - let your AI autonomously pay for services!

from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from moltspay.integrations.langchain import MoltsPayTool

llm = ChatOpenAI(model="gpt-4")
tools = [MoltsPayTool()]

agent = initialize_agent(
    tools, 
    llm, 
    agent=AgentType.OPENAI_FUNCTIONS,
    verbose=True
)

# Agent can now pay for AI services!
result = agent.run("Generate a video of a cat dancing on the beach")

Available Tools

Two tools available for different use cases:

from moltspay.integrations.langchain import get_moltspay_tools

tools = get_moltspay_tools()  # Returns both tools
Tool Description
MoltsPayTool Pay for and execute services
MoltsPayDiscoverTool Discover available services and prices

CLI Compatibility

Wallet format is fully compatible with the Node.js CLI:

# Create wallet with Node CLI
npx moltspay init --chain base

# Use same wallet in Python
python -c "from moltspay import MoltsPay; print(MoltsPay().address)"

How x402 Works

Your Agent                     Service Provider              Blockchain
    โ”‚                               โ”‚                           โ”‚
    โ”‚ Request service               โ”‚                           โ”‚
    โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>   โ”‚                           โ”‚
    โ”‚                               โ”‚                           โ”‚
    โ”‚ 402 + price + wallet          โ”‚                           โ”‚
    โ”‚ <โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€   โ”‚                           โ”‚
    โ”‚                               โ”‚                           โ”‚
    โ”‚ [Sign payment - NO GAS]       โ”‚                           โ”‚
    โ”‚                               โ”‚                           โ”‚
    โ”‚ Request + signed payment      โ”‚                           โ”‚
    โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>   โ”‚ Verify & settle           โ”‚
    โ”‚                               โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚
    โ”‚                               โ”‚                           โ”‚
    โ”‚ 200 OK + result               โ”‚                           โ”‚
    โ”‚ <โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€   โ”‚                           โ”‚

Your agent never pays gas - the CDP facilitator handles all on-chain settlement.

Use Cases

  • AI Assistants - Let your assistant pay for premium APIs
  • Autonomous Agents - Agents that can spend within limits
  • Multi-Agent Systems - Agents paying other agents for services
  • AI Pipelines - Pay-per-use for expensive compute steps

Running a Server (Accepting Payments)

Want to accept payments for your AI services? See the Server Guide.

Quick start:

# Install
pip install moltspay

# Create skill structure
mkdir my_skill && cd my_skill
# Add moltspay.services.json and __init__.py (see docs)

# Start server
moltspay-server ./my_skill --port 8402

Related Projects

Links

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

moltspay-0.6.1.tar.gz (42.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

moltspay-0.6.1-py3-none-any.whl (33.9 kB view details)

Uploaded Python 3

File details

Details for the file moltspay-0.6.1.tar.gz.

File metadata

  • Download URL: moltspay-0.6.1.tar.gz
  • Upload date:
  • Size: 42.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for moltspay-0.6.1.tar.gz
Algorithm Hash digest
SHA256 334b182d5d7010ec31b193d21e6228a6744987dda5313e21a8841705e346d780
MD5 471a1c17a4fb2484a6ad7d405a7a904f
BLAKE2b-256 0bd980d35c68e693e532d5c019177040ae1e61d17b9f17a86795c98a6d074c5b

See more details on using hashes here.

File details

Details for the file moltspay-0.6.1-py3-none-any.whl.

File metadata

  • Download URL: moltspay-0.6.1-py3-none-any.whl
  • Upload date:
  • Size: 33.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for moltspay-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 3e5c64922952504251845a913c6911ebb131e96505de8c0486c2a534547420fd
MD5 38c2d9612dee1894d8c97612554ef1a8
BLAKE2b-256 769b22cb23af87c383927f23cc2587737e26ff3b38a728de8e5a14964f85fc1a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page