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

@chainberry/berry-sdk

v1.0.0

Published

TypeScript SDK for ChainBerry External API

Readme

BerrySdk - ChainBerry External API SDK

A comprehensive TypeScript SDK for interacting with the ChainBerry External API, featuring robust error handling, automatic retries, logging, and validation.

🚀 Features

  • Type-safe API client with full TypeScript support
  • Automatic authentication with OAuth2 client credentials flow
  • Robust error handling with custom error classes
  • Automatic retries with exponential backoff
  • Comprehensive logging with configurable levels
  • Input validation with built-in validators
  • Environment-based configuration with fallbacks
  • Crypto utilities for signature generation and verification

📦 Installation

npm install @chainberry/berry-sdk

🏗️ Project Structure

libs/berrySdk/src/lib/
├── api/                    # API client and setup
│   ├── api.external.ts     # Generated API client
│   ├── api-setup.ts        # API initialization and configuration
│   └── index.ts            # API exports
├── crypto/                 # Cryptographic utilities
│   ├── utils.ts            # Signature generation and verification
│   └── index.ts            # Crypto exports
├── deposits/               # Deposit-related functionality
│   ├── create-deposit.ts   # Deposit creation with signature
│   ├── get-deposit.ts      # Deposit retrieval with JWT auth
│   ├── examples/           # Usage examples
│   └── index.ts            # Deposit exports
├── checkout/               # Checkout-related functionality
│   ├── create-checkout.ts  # Checkout creation with signature
│   ├── get-checkout.ts     # Checkout retrieval with JWT auth
│   ├── update-checkout.ts  # Checkout update with JWT auth
│   ├── examples/           # Usage examples
│   └── index.ts            # Checkout exports
├── errors/                 # Custom error classes
│   ├── berry-sdk-errors.ts # Error definitions
│   └── index.ts            # Error exports
├── utils/                  # Utility functions
│   ├── logger.ts           # Logging utilities
│   ├── retry.ts            # Retry logic with backoff
│   ├── validation.ts       # Input validation
│   └── index.ts            # Utils exports
└── index.ts                # Main library exports

🚀 Quick Start

Basic Setup

import { init, Environment } from "@chainberry/berry-sdk";

// Initialize the API client
const api = await init({
  environment: Environment.STAGING,
  clientId: "your-client-id",
  clientSecret: "your-client-secret",
  privateKey: "your-private-key",
});

Using Environment Variables

import { init, Environment } from "@chainberry/berry-sdk";

// Set environment variables
process.env.CB_API_ENVIRONMENT = "staging";
process.env.CB_API_CLIENT_ID = "your-client-id";
process.env.CB_API_CLIENT_SECRET = "your-client-secret";
process.env.CB_API_PRIVATE_KEY = "your-private-key";

// Initialize with environment variables
const api = await init();

💳 Creating Deposits

The SDK provides a createDeposit function that automatically generates signatures for deposit requests:

import { createDeposit, Environment, init } from "@chainberry/berry-sdk";

// Initialize the API
await init({ environment: Environment.STAGING });

// Define deposit parameters
const depositParams = {
  amount: "0.1",
  currency: "USD",
  paymentGatewayName: "ETH",
  paymentCurrency: "ETH",
  callbackUrl: "https://your-callback-url.com/webhook",
  tradingAccountLogin: "user123",
};

// Create and submit deposit request
const depositResponse = await createDeposit(depositParams);
console.log("Deposit created:", depositResponse.paymentId);

📊 Getting Deposit Information

The SDK provides a getDeposit function with automatic retry logic:

import { getDeposit, Environment, init } from "@chainberry/berry-sdk";

// Initialize the API
await init({ environment: Environment.STAGING });

// Get deposit information with automatic retries
const depositInfo = await getDeposit({
  paymentId: "your-payment-id",
  maxRetries: 3,
});

console.log("Deposit status:", depositInfo.status);
console.log("Amount:", depositInfo.transactionAmount);

🔧 Advanced Configuration

Custom Logger

import { logger, LogLevel } from "@chainberry/berry-sdk";

// Configure logging
logger.setLevel(LogLevel.DEBUG);
logger.setPrefix("[MyApp]");
logger.setConsoleEnabled(true);

// Use in your code
logger.info("API call successful");
logger.error("API call failed", { error: "details" });

Custom Retry Configuration

import { withRetry } from "@chainberry/berry-sdk";

const result = await withRetry(() => api.deposits.depositControllerGetDeposit(paymentId), {
  maxAttempts: 5,
  baseDelay: 2000,
  maxDelay: 30000,
  backoffMultiplier: 1.5,
  retryCondition: (error) => error.statusCode >= 500,
  onRetry: (attempt, error, delay) => {
    console.log(`Retry ${attempt} after ${delay}ms`);
  },
});

Input Validation

import { Validators } from "@chainberry/berry-sdk";

// Validate deposit parameters
const depositParams = {
  amount: "0.1",
  currency: "USD",
  callbackUrl: "https://example.com/callback",
  tradingAccountLogin: "user123",
};

// Validate each field
Validators.amount.validateAndThrow(depositParams.amount, "Amount");
Validators.currency.validateAndThrow(depositParams.currency, "Currency");
Validators.callbackUrl.validateAndThrow(depositParams.callbackUrl, "Callback URL");
Validators.tradingAccountLogin.validateAndThrow(depositParams.tradingAccountLogin, "Trading Account Login");

🛠️ Error Handling

The SDK provides custom error classes for better error handling:

import {
  BerrySdkError,
  ConfigurationError,
  AuthenticationError,
  ApiError,
  ValidationError,
} from "@chainberry/berry-sdk";

try {
  const deposit = await createDeposit(params);
} catch (error) {
  if (error instanceof ConfigurationError) {
    console.error("Configuration issue:", error.message);
  } else if (error instanceof AuthenticationError) {
    console.error("Authentication failed:", error.message);
  } else if (error instanceof ValidationError) {
    console.error("Validation failed:", error.details);
  } else if (error instanceof ApiError) {
    console.error("API error:", error.statusCode, error.message);
  } else {
    console.error("Unknown error:", error);
  }
}

🧪 Testing

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run linting
npm run lint

# Fix linting issues
npm run lint:fix

📚 API Reference

Core Functions

init(config?: ExternalApiConfig): Promise<ApiInstance>

Initialize the API client with configuration.

Parameters:

  • config (optional): Configuration object with environment, credentials, etc.

Returns:

  • Promise<ApiInstance>: Configured API instance

createDeposit(params: CreateDepositParams): Promise<DepositDto>

Create a deposit with automatic signature generation.

Parameters:

  • params: Deposit parameters including amount, currency, callback URL, etc.

Returns:

  • Promise<DepositDto>: Created deposit information

getDeposit(params: GetDepositParams): Promise<GetDepositDto>

Get deposit information with automatic authentication and retry logic.

Parameters:

  • params: Parameters including payment ID and retry configuration

Returns:

  • Promise<GetDepositDto>: Deposit information

Error Classes

  • BerrySdkError: Base error class for all SDK errors
  • ConfigurationError: Configuration-related errors
  • AuthenticationError: Authentication-related errors
  • ApiError: API request-related errors
  • ValidationError: Validation-related errors
  • CryptoError: Cryptographic operation errors
  • NetworkError: Network/connection errors
  • RateLimitError: Rate limiting errors

Utility Classes

  • Logger: Configurable logging utility
  • Validator<T>: Generic validation framework
  • withRetry<T>: Retry utility with exponential backoff

🔒 Security

  • Private keys are never logged or exposed
  • All API calls use HTTPS
  • Automatic token refresh on authentication failures
  • Input validation to prevent injection attacks

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite
  6. Submit a pull request

📄 License

MIT License - see LICENSE file for details.