@shade402/core
v0.0.1
Published
Core TypeScript library for X402 payment protocol
Downloads
6
Maintainers
Readme
@shade402/core
Core TypeScript library implementing the X402 payment protocol for autonomous AI agent payments on Solana.
Overview
The core package provides the foundational building blocks for the X402 payment protocol. It includes payment models, Solana blockchain integration, encryption utilities, and error handling. This package is used by all other Shade402 packages and can be used directly for custom implementations.
Features
- Payment request and authorization models with validation
- Solana blockchain payment processing
- SPL token transfer support
- Payment verification and expiration handling
- RSA encryption for resource field privacy
- Comprehensive error types and handling
- Full TypeScript support with Zod schema validation
- Network support for Solana mainnet and devnet
Installation
npm install @shade402/core
# or
pnpm add @shade402/core
# or
yarn add @shade402/coreDependencies
@solana/web3.js: Solana blockchain interactions@solana/spl-token: SPL token operationszod: Runtime schema validation
Usage
Payment Models
The core package provides two main model classes for representing payment data:
import { PaymentRequest, PaymentAuthorization } from '@shade402/core';
// Create payment request from server response
const requestData = {
max_amount_required: '0.01',
asset_type: 'spl-token',
asset_address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
payment_address: 'PaymentWalletAddress...',
network: 'solana-devnet',
expires_at: new Date(Date.now() + 300000),
nonce: 'unique-nonce',
payment_id: 'payment-id',
resource: 'encrypted-resource-data',
description: 'Payment for API access'
};
const paymentRequest = new PaymentRequest(requestData);
// Create authorization after payment
const authData = {
payment_id: paymentRequest.paymentId,
nonce: paymentRequest.nonce,
transaction_hash: 'transaction-signature',
public_key: 'wallet-public-key'
};
const authorization = new PaymentAuthorization(authData);Solana Payment Processor
The SolanaPaymentProcessor handles all blockchain operations for creating and verifying payments:
import { SolanaPaymentProcessor } from '@shade402/core';
import { Keypair } from '@solana/web3.js';
const wallet = Keypair.generate();
const processor = new SolanaPaymentProcessor(
'https://api.devnet.solana.com',
wallet,
{ defaultDecimals: 6 }
);
// Create payment transaction
const paymentRequest = new PaymentRequest(requestData);
const authorization = await processor.createPayment(
paymentRequest,
'0.01' // amount to pay
);
// Verify payment
const isValid = await processor.verifyPayment(
paymentRequest,
authorization
);Encryption Utilities
The package provides RSA encryption for protecting sensitive resource data:
import { generateKeyPair, encryptResource, decryptResource } from '@shade402/core';
// Generate key pair (server-side)
const { publicKey, privateKey } = await generateKeyPair();
// Encrypt resource data (server-side)
const encrypted = await encryptResource(
'sensitive-resource-data',
publicKey
);
// Decrypt resource data (client-side)
const decrypted = await decryptResource(
encrypted,
privateKey
);Error Handling
Comprehensive error types for different failure scenarios:
import {
X402Error,
PaymentRequiredError,
PaymentExpiredError,
InsufficientFundsError,
PaymentVerificationError,
TransactionBroadcastError,
InvalidPaymentRequestError,
ERROR_CODES
} from '@shade402/core';
try {
await processor.createPayment(paymentRequest, amount);
} catch (error) {
if (error instanceof PaymentExpiredError) {
console.error('Payment request expired');
} else if (error instanceof InsufficientFundsError) {
console.error('Insufficient wallet balance');
} else if (error instanceof PaymentVerificationError) {
console.error('Payment verification failed');
} else if (error instanceof TransactionBroadcastError) {
console.error('Transaction broadcast failed:', error.message);
}
}API Reference
PaymentRequest
Represents a payment request from a server.
Constructor:
new PaymentRequest(data: PaymentRequestData)
Properties:
maxAmountRequired: string- Maximum amount required for paymentassetType: string- Asset type (e.g., 'spl-token')assetAddress: string- Asset contract/mint addresspaymentAddress: string- Wallet address to receive paymentnetwork: string- Blockchain network identifierexpiresAt: Date- Payment request expiration timenonce: string- Unique nonce for this paymentpaymentId: string- Unique payment identifierresource: string- Encrypted resource identifierdescription?: string- Optional payment description
Methods:
isExpired(): boolean- Check if payment request has expiredtoJSON(): PaymentRequestData- Convert to JSON format
PaymentAuthorization
Represents a payment authorization after successful payment.
Constructor:
new PaymentAuthorization(data: PaymentAuthorizationData)
Properties:
paymentId: string- Payment identifiernonce: string- Payment noncetransactionHash: string- Blockchain transaction hashpublicKey: string- Payer's public key
Methods:
toJSON(): PaymentAuthorizationData- Convert to JSON format
SolanaPaymentProcessor
Handles Solana blockchain operations for payments.
Constructor:
new SolanaPaymentProcessor(rpcUrl: string, keypair?: Keypair, options?: SolanaPaymentProcessorOptions)
Methods:
async createPayment(request: PaymentRequest, amount: string, memo?: string): Promise<PaymentAuthorization>- Create and broadcast payment transactionasync verifyPayment(request: PaymentRequest, authorization: PaymentAuthorization): Promise<boolean>- Verify payment on blockchainasync getBalance(tokenMint?: string): Promise<number>- Get wallet token balance
Encryption Functions
async generateKeyPair(): Promise<{ publicKey: string, privateKey: string }>- Generate RSA key pairasync encryptResource(data: string, publicKey: string): Promise<string>- Encrypt resource dataasync decryptResource(encrypted: string, privateKey: string): Promise<string>- Decrypt resource data
Error Types
X402Error
Base error class for all X402-related errors.
PaymentRequiredError
Thrown when a payment is required but not provided.
PaymentExpiredError
Thrown when a payment request has expired.
InsufficientFundsError
Thrown when wallet lacks sufficient funds for payment.
PaymentVerificationError
Thrown when payment verification fails.
TransactionBroadcastError
Thrown when transaction broadcast to blockchain fails.
InvalidPaymentRequestError
Thrown when payment request data is invalid.
Configuration
SolanaPaymentProcessorOptions
interface SolanaPaymentProcessorOptions {
defaultDecimals?: number; // Default: 6 (common for USDC)
memo?: string; // Optional memo text for transactions
}Examples
Basic Payment Flow
import {
PaymentRequest,
PaymentAuthorization,
SolanaPaymentProcessor
} from '@shade402/core';
import { Keypair } from '@solana/web3.js';
const wallet = Keypair.generate();
const processor = new SolanaPaymentProcessor(
'https://api.devnet.solana.com',
wallet
);
// Parse payment request from server
const requestData = {
max_amount_required: '0.01',
asset_type: 'spl-token',
asset_address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
payment_address: 'PaymentWalletAddress...',
network: 'solana-devnet',
expires_at: new Date(Date.now() + 300000),
nonce: 'unique-nonce',
payment_id: 'payment-id',
resource: 'resource-data'
};
const paymentRequest = new PaymentRequest(requestData);
// Check expiration
if (paymentRequest.isExpired()) {
throw new Error('Payment request expired');
}
// Create payment
const authorization = await processor.createPayment(
paymentRequest,
paymentRequest.maxAmountRequired
);
// Verify payment
const isValid = await processor.verifyPayment(paymentRequest, authorization);
console.log('Payment verified:', isValid);Error Handling
import {
PaymentExpiredError,
InsufficientFundsError,
PaymentVerificationError,
TransactionBroadcastError
} from '@shade402/core';
try {
const authorization = await processor.createPayment(request, amount);
} catch (error) {
if (error instanceof PaymentExpiredError) {
console.error('Payment request has expired');
} else if (error instanceof InsufficientFundsError) {
console.error('Insufficient funds in wallet');
} else if (error instanceof PaymentVerificationError) {
console.error('Payment verification failed');
} else if (error instanceof TransactionBroadcastError) {
console.error('Transaction failed:', error.message);
} else {
console.error('Unexpected error:', error);
}
}TypeScript Support
The package is written in TypeScript and provides full type definitions. All types are exported and can be imported directly:
import type {
PaymentRequestData,
PaymentAuthorizationData,
SolanaPaymentProcessorOptions,
ErrorDetails
} from '@shade402/core';Network Support
The package supports Solana networks:
solana-mainnet: Solana mainnetsolana-devnet: Solana devnet
Security Considerations
- Always validate payment requests before processing
- Check expiration times before creating payments
- Verify payments on-chain before granting access
- Use HTTPS for all network communications
- Store private keys securely
- Never expose private keys in client-side code
- Use encryption for sensitive resource data
License
MIT
