LangGraph Integration
The @shade402/langgraph package provides payment nodes for LangGraph workflows, enabling agents to make X402 payments as part of their execution graph.
Installation
pnpm add @shade402/langgraph @shade402/client @shade402/core @langchain/langgraphQuick Start
import { StateGraph } from '@langchain/langgraph';
import { fetchWithPaymentNode } from '@shade402/langgraph';
import { Keypair } from '@solana/web3.js';
import { PaymentState } from '@shade402/langgraph';
const workflow = new StateGraph<PaymentState>({
channels: {
api_url: { reducer: (x, y) => y ?? x },
api_response: { reducer: (x, y) => y ?? x },
wallet_keypair: { reducer: (x, y) => y ?? x },
},
});
workflow.addNode('fetch_api', fetchWithPaymentNode);
workflow.setEntryPoint('fetch_api');
const app = workflow.compile();
const result = await app.invoke({
api_url: 'https://api.example.com/premium-data',
wallet_keypair: Keypair.generate(),
});Payment Nodes
fetchWithPaymentNode
fetchWithPaymentNodeCombined node that fetches API and handles payment automatically:
This node:
Makes HTTP request to
state.api_urlIf 402 received, automatically creates payment
Retries request with payment
Returns API response in
state.api_response
paymentNode
paymentNodeSeparate payment node for more control:
This node:
Expects
state.payment_requiredto be trueMakes payment for
state.api_urlUpdates
state.api_responseandstate.payment_completed
Payment State
The PaymentState interface defines the state structure:
Workflow Patterns
Simple Payment Flow
Conditional Payment Flow
Multiple API Calls
Conditional Functions
checkPaymentRequired
checkPaymentRequiredRoutes based on whether payment is required:
Returns:
'payment_required': Ifstate.payment_requiredis true'success': Ifstate.api_responseexists'error': Otherwise
checkPaymentCompleted
checkPaymentCompletedRoutes based on payment completion:
Returns:
'completed': Ifstate.payment_completedis true'failed': Otherwise
Custom Conditional Functions
Complete Example
Best Practices
Define clear state structure
Handle errors appropriately
Set maximum payment amounts
Use conditional edges for flow control
Process API responses in separate nodes
Monitor payment usage
Log payment transactions
Test with devnet before production
Use secure wallet storage
Consider rate limiting
Next Steps
Learn about LangChain Integration
Check out Examples for more workflows
Review Security best practices
Last updated
