npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@shade402/core

v0.0.1

Published

Core TypeScript library for X402 payment protocol

Downloads

6

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

Dependencies

  • @solana/web3.js: Solana blockchain interactions
  • @solana/spl-token: SPL token operations
  • zod: 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 payment
  • assetType: string - Asset type (e.g., 'spl-token')
  • assetAddress: string - Asset contract/mint address
  • paymentAddress: string - Wallet address to receive payment
  • network: string - Blockchain network identifier
  • expiresAt: Date - Payment request expiration time
  • nonce: string - Unique nonce for this payment
  • paymentId: string - Unique payment identifier
  • resource: string - Encrypted resource identifier
  • description?: string - Optional payment description

Methods:

  • isExpired(): boolean - Check if payment request has expired
  • toJSON(): PaymentRequestData - Convert to JSON format

PaymentAuthorization

Represents a payment authorization after successful payment.

Constructor:

  • new PaymentAuthorization(data: PaymentAuthorizationData)

Properties:

  • paymentId: string - Payment identifier
  • nonce: string - Payment nonce
  • transactionHash: string - Blockchain transaction hash
  • publicKey: 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 transaction
  • async verifyPayment(request: PaymentRequest, authorization: PaymentAuthorization): Promise<boolean> - Verify payment on blockchain
  • async getBalance(tokenMint?: string): Promise<number> - Get wallet token balance

Encryption Functions

  • async generateKeyPair(): Promise<{ publicKey: string, privateKey: string }> - Generate RSA key pair
  • async encryptResource(data: string, publicKey: string): Promise<string> - Encrypt resource data
  • async 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 mainnet
  • solana-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