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/langgraph

Quick 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

Combined node that fetches API and handles payment automatically:

This node:

  1. Makes HTTP request to state.api_url

  2. If 402 received, automatically creates payment

  3. Retries request with payment

  4. Returns API response in state.api_response

paymentNode

Separate payment node for more control:

This node:

  1. Expects state.payment_required to be true

  2. Makes payment for state.api_url

  3. Updates state.api_response and state.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

Routes based on whether payment is required:

Returns:

  • 'payment_required': If state.payment_required is true

  • 'success': If state.api_response exists

  • 'error': Otherwise

checkPaymentCompleted

Routes based on payment completion:

Returns:

  • 'completed': If state.payment_completed is true

  • 'failed': Otherwise

Custom Conditional Functions

Complete Example

Best Practices

  1. Define clear state structure

  2. Handle errors appropriately

  3. Set maximum payment amounts

  4. Use conditional edges for flow control

  5. Process API responses in separate nodes

  6. Monitor payment usage

  7. Log payment transactions

  8. Test with devnet before production

  9. Use secure wallet storage

  10. Consider rate limiting

Next Steps

Last updated