Modexia AgentPay โ Python SDK for agent wallets & payments (USDC)
Project description
noteId: "8d854f304bd411f18bfe97159fe8ca5e" tags: []
๐ Modexia Python SDK
The ultimate Python client for AI Agents to seamlessly interact with Modexia's AgentPay API.
Welcome to the Modexia Python SDK (modexiaagentpay). Built from the ground up to give your AI agents and Python applications frictionless access to Modexia's wallet and payment infrastructure. Enable your AI to hold, manage, and transfer value with just a few lines of code!
๐ What's New in v0.7.0
Intent-to-Pay โ A new cryptographically signed payment system that gives agents rich compliance feedback, audit trails, and policy-aware spending.
| Feature | Description |
|---|---|
client.pay() |
High-level intent-based payment โ create, sign, submit, and poll in one call |
client.create_intent() |
Create an HMAC-SHA256 signed intent token |
client.submit_intent() |
Submit a signed token through the 11-step validation pipeline |
client.get_intent() |
Look up the status of a previously submitted intent |
client.list_intents() |
List recent intents for audit trail review |
IntentResult |
New dataclass with status, compliance metadata, daily spend, and suggestions |
memo parameter |
All payment methods now accept a memo for audit trail visibility |
๐ Getting Started: Your API Key
Before writing your first integration, you will need a Modexia developer account and an API key.
- Visit modexia.software
- Create or log into your developer account.
- Navigate to your dashboard and generate your API Key.
For deep dives, architecture, and advanced agentic payment flows, dive into our Full Documentation.
๐ System Architecture & Flow
The SDK supports two payment flows: the classic v1 transfer and the new v2 intent-based pipeline.
Intent-to-Pay Flow (v2 โ Recommended)
sequenceDiagram
participant Agent as ๐ค AI Agent
participant SDK as ๐ฆ Python SDK
participant API as ๐ Modexia API
participant Pipeline as ๐ Validation Pipeline
participant Chain as โ๏ธ Blockchain
Agent->>SDK: client.pay(recipient, amount, memo="...")
SDK->>SDK: Create intent JSON + HMAC-SHA256 sign
SDK->>API: POST /v2/intents/submit (signed token)
API->>API: Verify HMAC signature
API->>Pipeline: Run 11-step validation
Note over Pipeline: amount โ recipient โ expiry โ<br/>nonce โ wallet โ KYC โ<br/>SBT โ policy โ limits โ
alt All checks pass
Pipeline-->>API: approved
API->>Chain: Execute on-chain transfer
Chain-->>API: txId
API-->>SDK: IntentResult(status="executed", txId, daily_remaining, balance)
SDK-->>Agent: Rich result with compliance metadata ๐
else Validation fails
Pipeline-->>API: rejected (code + suggestion)
API-->>SDK: IntentResult(status="rejected", reason, suggestion)
SDK-->>Agent: Actionable rejection with fix suggestion
end
Classic Transfer Flow (v1 โ Still Supported)
sequenceDiagram
participant Agent as ๐ค AI Agent
participant SDK as ๐ฆ Python SDK
participant API as ๐ Modexia API
participant Chain as โ๏ธ Blockchain
Agent->>SDK: client.transfer(recipient, amount)
SDK->>API: POST /v1/agent/pay
Note over API: Internally creates synthetic intent<br/>and runs same validation pipeline
API->>Chain: Execute transfer
Chain-->>API: txId
API-->>SDK: {success: true, txId}
SDK-->>Agent: PaymentReceipt ๐
Note: The v1
transfer()method now internally routes through the same intent validation pipeline. You get the same compliance enforcement with zero code changes.
โจ Top-Level Features
- Intent-Based Payments: Cryptographically signed payment intents with HMAC-SHA256 verification, replay protection, and full compliance pipeline.
- Rich Compliance Feedback: Know exactly why a payment was rejected, with actionable suggestions and your daily spend/remaining budget.
- Audit Trail: Every payment records a
memoexplaining why the AI made the payment โ visible in the dashboard. - Built for AI Agents: Designed specifically for programmatic access to agent wallets and payments without complex cryptography.
- Async & "Swarm" Support: High-concurrency operations powered by blazing fast implementations in both synchronous and
asynciomodels. - Fully Typed: Returns robust Python dataclasses for exceptional developer experience and editor autocompletion.
- Reliable Networking: Built-in retry and exponential backoff mechanisms to gracefully handle transient network errors.
๐ฆ Installation
Install the production-ready package directly from PyPI:
pip install modexiaagentpay
For local development and contribution:
git clone https://github.com/Modaniel/SDKs.git
cd SDKs
pip install -e packages/SDKs/pythonSdk
๐ Quick Start Guide
Intent-Based Payment (v2 โ Recommended)
The pay() method is the new recommended way to make payments. It creates a signed intent, validates it through the compliance pipeline, and returns rich metadata.
from modexia import ModexiaClient
client = ModexiaClient(api_key="mx_test_your_api_key_here")
# Make a payment with full compliance feedback
result = client.pay(
recipient="0xabc123456789def0123456789abc0123456789def",
amount=5.0,
memo="Paying for GPT-4 API call to summarize document #42"
)
if result.status == "executed":
print(f"โ
Payment executed! TX ID: {result.txId}")
print(f"๐ฐ Balance after: {result.wallet_balance_after} USDC")
print(f"๐ Daily remaining: {result.daily_remaining} USDC")
elif result.status == "rejected":
print(f"โ Rejected: {result.reason}")
print(f"๐ก Suggestion: {result.suggestion}")
Classic Transfer (v1 โ Backwards Compatible)
from modexia import ModexiaClient
client = ModexiaClient(api_key="mx_test_your_api_key_here")
# Check balance
balance = client.retrieve_balance()
print(f"๐ฐ Balance: {balance} USDC")
# Simple transfer (still works, now with memo support)
receipt = client.transfer(
recipient="0xabc123456789def0123456789abc0123456789def",
amount=5.0,
wait=True,
memo="Paying vendor for compute resources"
)
if receipt.success:
print(f"โ
Transfer successful! TX ID: {receipt.txId}")
Async Usage (Swarm Mode)
For high-concurrency loops or AutoGPT-style agent networks:
import asyncio
from modexia import AsyncModexiaClient
async def main():
async with AsyncModexiaClient(api_key="mx_test_your_api_key_here") as client:
await client.validate_session()
# Intent-based payment (recommended)
result = await client.pay(
"0xabc...", 5.0,
memo="Async swarm payment for data processing"
)
print(f"Status: {result.status}, Daily remaining: {result.daily_remaining}")
# Or classic transfer
receipt = await client.transfer("0xabc...", 2.0, memo="Legacy flow")
print(f"TX: {receipt.txId}")
asyncio.run(main())
๐ API Reference
ModexiaClient & AsyncModexiaClient
The core classes for all network operations.
ModexiaClient(
api_key: str,
timeout: int = 15,
base_url: Optional[str] = None,
validate: bool = True
)
Intent-to-Pay Methods (v2)
| Method | Description | Returns |
|---|---|---|
pay(recipient, amount, memo=None, wait=True) |
Recommended. High-level intent-based payment โ creates, signs, submits, and polls. Returns rich compliance metadata. | IntentResult |
create_intent(recipient, amount, memo=None, action="transfer", ttl_seconds=300) |
Create a signed intent token locally (no network call). The token is base64url(payload).hex(hmac_sha256(payload, api_key)). |
str |
submit_intent(intent_token) |
Submit a signed intent token for validation and execution. | IntentResult |
get_intent(intent_id) |
Retrieve the status of a previously submitted intent by UUID. | IntentResult |
list_intents(limit=20) |
List recent payment intents for audit trail review. | List[IntentResult] |
Classic Methods (v1)
| Method | Description | Returns |
|---|---|---|
retrieve_balance() / get_balance() |
Fetches the current available balance of your agent's wallet. | str |
transfer(recipient, amount, idempotency_key=None, wait=True, memo=None) |
Send funds to a destination. Uses intent-hashing to prevent duplicate charges. | PaymentReceipt |
cross_chain_transfer(to_chain, to_token, recipient, amount) |
Cross-chain CCTP transfer via Squid Router. | PaymentReceipt |
get_history(limit=5) |
Fetch the recent transaction history for Agent memory. Now includes memo. |
TransactionHistoryResponse |
Vault / Micropayment Channel Methods
| Method | Description | Returns |
|---|---|---|
open_channel(provider, deposit, duration_hours=24) |
Open a payment channel with on-chain deposit. | dict |
consume_channel(channel_id, amount, idempotency_key=None) |
Execute an instant, gas-free micro-payment inside a channel. | ConsumeResponse |
settle_channel(channel_id) |
Settle a channel on-chain โ pays provider, refunds remainder. | dict |
get_channel(channel_id) |
Get the current status of a payment channel. | ChannelStatus |
list_channels(limit=50) |
List all payment channels for the authenticated agent. | List[ChannelStatus] |
Other
| Method | Description | Returns |
|---|---|---|
smart_fetch(method, url, **kwargs) |
Auto-negotiates 402 HTTP paywalls automatically. | Response |
๐ Data Models
IntentResult (New in v0.7.0)
The rich response returned from the intent-to-pay pipeline:
@dataclass
class IntentResult:
status: str # pending | approved | rejected | executed | failed
intent_id: Optional[str] # UUID for tracking
# Transaction details (populated on 'executed')
txId: Optional[str] # Circle transaction ID
txIds: Optional[List[str]] # Multiple IDs for multi-leg txs
txState: Optional[str] # PENDING โ COMPLETE
amount: Optional[str] # e.g. "5.00"
recipient: Optional[str] # 0x... address
# Compliance & policy metadata
wallet_balance_after: Optional[str] # Balance after payment
daily_spent: Optional[str] # How much spent today
daily_remaining: Optional[str] # Budget remaining today
# Rejection info
reason: Optional[str] # Why it was rejected
code: Optional[str] # Machine-readable code
suggestion: Optional[str] # Actionable fix suggestion
# Full validation pipeline results
validation: Dict[str, Any] # Per-step validation outcomes
Example validation field:
{
"amount": "valid",
"recipient": "valid",
"expiry": "valid",
"nonce": "valid",
"wallet": "valid",
"kyc": "valid",
"sbt": "valid",
"policy_registration": "valid",
"policy_per_request": "valid",
"policy_hourly": "valid",
"policy_daily": "valid"
}
PaymentReceipt
@dataclass
class PaymentReceipt:
success: bool
status: str # "PENDING" | "COMPLETE"
txId: Optional[str]
txHash: Optional[str]
errorReason: Optional[str]
TransactionHistoryItem
@dataclass
class TransactionHistoryItem:
txId: str
type: str
amount: str
state: str
createdAt: str
providerAddress: Optional[str]
txHash: Optional[str]
memo: Optional[str] # NEW in v0.7.0
๐ Exception Handling
The SDK provides robust error mapping to help your agent gracefully recover from failures. You can import these directly from the modexia package:
from modexia import ModexiaClient, ModexiaAuthError, ModexiaPaymentError, ModexiaNetworkError
graph TD;
Exception-->TimeoutError["TimeoutError: wait=True Polling exceeded 30s"];
Exception-->ModexiaError;
ModexiaError-->ModexiaAuthError["ModexiaAuthError: Key/Auth Issues"];
ModexiaError-->ModexiaPaymentError["ModexiaPaymentError: Insufficient Funds / API Responses with success=False"];
ModexiaError-->ModexiaNetworkError["ModexiaNetworkError: Connection Drops / Invalid JSON payloads"];
๐ Intent Token Format
The intent token is a compact, tamper-proof string:
base64url(canonical_json).hex(hmac_sha256(canonical_json, api_key))
Canonical JSON is the payload with keys sorted alphabetically and serialized with no whitespace:
{"action":"transfer","amount":"5.0","currency":"USDC","expiresAt":1715270400000,"idempotencyKey":"uuid","memo":"Paying for API call","nonce":1715270100000,"recipient":"0x..."}
The HMAC-SHA256 signature uses your API key as the secret. The backend verifies this signature using constant-time comparison to prevent timing attacks.
๐ Migration from v0.6.x
v0.7.0 is fully backwards compatible. No changes needed for existing code.
What's different internally: The transfer() method now routes through the same validation pipeline as pay(). Your existing code gets compliance enforcement for free.
To adopt v2 features:
- receipt = client.transfer("0x...", 5.0)
- if receipt.success:
- print(f"TX: {receipt.txId}")
+ result = client.pay("0x...", 5.0, memo="Paying for compute")
+ if result.status == "executed":
+ print(f"TX: {result.txId}, Remaining: {result.daily_remaining}")
๐ค Contributing to Open Source
We actively welcome community contributions to make this SDK even better.
- Fork & Branch: Open a Pull Request targeting the
developbranch. - Backward Compatibility: Please keep API contracts stable.
ModexiaClient,transfer(), andretrieve_balance()are canonical. - Testing: Make sure tests pass locally before submitting.
# Run tests from the repository root
pytest -q packages/SDKs/pythonSdk
๐ License & Support
modexiaagentpay is totally open-source and governed by the MIT License.
Need help scaling your agent swarm? Hit rate limits? Reach out to our engineering team or explore the docs at modexia.software.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file modexiaagentpay-0.7.0.tar.gz.
File metadata
- Download URL: modexiaagentpay-0.7.0.tar.gz
- Upload date:
- Size: 25.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
524d831abe97383690078597b63e9a49b189201cd6cf10abe08e9eec9011f635
|
|
| MD5 |
4ad707f3bd3066902f43b639049853e1
|
|
| BLAKE2b-256 |
afeff82dad673791c3f68fc5d0b5e50e236403433081fe1449a13ee04341a955
|
File details
Details for the file modexiaagentpay-0.7.0-py3-none-any.whl.
File metadata
- Download URL: modexiaagentpay-0.7.0-py3-none-any.whl
- Upload date:
- Size: 24.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
daeead5f3d6189a4d4ff2c46cfaa448b4f744b068e8d9161ccd7ccb45dd7c34b
|
|
| MD5 |
eaa0df24f411f915c36f37269947d762
|
|
| BLAKE2b-256 |
c9fb1f6c4e11721e00ddb4c9e781da5dbf6823574b7fdd931c4f18dab8d6ddd2
|