@chainberry/berry-sdk
v1.0.0
Published
TypeScript SDK for ChainBerry External API
Maintainers
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 errorsConfigurationError: Configuration-related errorsAuthenticationError: Authentication-related errorsApiError: API request-related errorsValidationError: Validation-related errorsCryptoError: Cryptographic operation errorsNetworkError: Network/connection errorsRateLimitError: Rate limiting errors
Utility Classes
Logger: Configurable logging utilityValidator<T>: Generic validation frameworkwithRetry<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
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the test suite
- Submit a pull request
📄 License
MIT License - see LICENSE file for details.
