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

settlesettle

v0.1.6

Published

The official SDK for SettleSettle — Revenue Operating System for African developers

Downloads

89

Readme

SettleSettle SDK

The official, zero-dependency TypeScript SDK for SettleSettle — the Revenue Operating System for African developers.

SettleSettle equips software businesses with the tools needed to monetize applications across Africa using dynamic billing rails. Securely integrate virtual credit wallets, recurring subscriptions, rewarded ad monetization, and payment ledger auditing in just a few lines of code.


Table of Contents

  1. Installation
  2. Quick Start
  3. Core Concepts & Billing Modes
  4. SDK Modules Reference
  5. Error Handling
  6. Graceful Shutdown
  7. TypeScript Support

Installation

Install the package via your preferred package manager. SettleSettle is zero-dependency, maintaining a ultra-light footprint in both serverless and long-running backend environments.

# Using npm
npm install settlesettle

# Using pnpm
pnpm add settlesettle

# Using yarn
yarn add settlesettle

Quick Start

Initialize the client with your secret API key. The SDK automatically falls back to the SETTLESETTLE_API_KEY environment variable if no options are passed explicitly.

import { SettleSettle } from 'settlesettle'

// Configured via argument or SETTLESETTLE_API_KEY environment variable
const settle = new SettleSettle({
  apiKey: 'ss_live_your_secret_key'
})

// Query user credits wallet balance
const { balance } = await settle.wallet.getBalance('user_123')
console.log(`User has ${balance} credits remaining.`)

Sandbox & Production Isolation

SettleSettle operates safe sandbox testing capabilities separated by API Key prefixes. The SDK automatically detects the environment and active key prefix to prevent production configuration errors:

  • Sandbox Test Mode: Configured with a key starting with ss_test_. Real billing gateways are bypassed, allowing free simulation of payment checkouts.
  • Production Live Mode: Configured with a key starting with ss_live_. Connects to verified rails.

Sandbox & Live Getters

You can audit the active API Key configuration directly on the main SDK client:

if (settle.isSandbox) {
  console.log("Staging sandbox active - no real charges will occur.")
}

if (settle.isLive) {
  console.log("Production environments active.")
}

Environment Mismatch Warning alerts

To guarantee integration safety, the SDK runs startup validation: If you supply a sandbox test key (ss_test_...) in a production environment (process.env.NODE_ENV === 'production'), the SDK will automatically emit a clear warning to the console:

⚠️ [SettleSettle SDK Warning]: Utilizing sandbox test key (ss_test_...) in production environment. Sandbox transactions will not charge real money.

Core Concepts & Billing Modes

SettleSettle supports three major billing configurations, which can be toggled and combined within your developer dashboard configuration:

1. Credits Billing

An atomic, high-velocity virtual wallet system. Perfect for usage-based apps (e.g., deducting 5 credits per AI prompt or 15 credits per image rendering).

  • Benefit: End-users top up credit packages in local currencies, and developers charge programmatically for granular usage.
  • Fallbacks: When credits hit zero, seamlessly offer rewarded ad videos as an instant credit replenishment fallback.

2. Subscriptions Billing

Enforce recurring time-bound payments (Monthly, Annual, etc.) with automatic background renewals, grace periods, and trial days.

  • Supported Rails: Wallet-based debit cycles (virtual balances charged automatically on interval) or Paystack-backed recurrent card billing.
  • Checks: Block premium features with a simple access gate in your code.

3. One-Time Payments

Traditional digital checkout for specific items, physical goods, lifetime access passes, or one-off credit bundle packages.

  • Supported Rails: Paystack (Card, Bank Transfer, USSD, NQR) and Solana Devnet (manual USDC operations).

SDK Modules Reference

The SettleSettle client coordinates distinct submodules to handle specific monetization features:


Payments

Easily initialize visual checkout interfaces and verify Paystack or Solana transactions.

// 1. Initialize a checkout session
const { checkoutUrl, reference } = await settle.payments.initialize({
  endUserId: 'user_123',
  amountKobo: 500000,   // ₦5,000 in kobo (always in smallest currency unit)
  email: '[email protected]',
  callbackUrl: 'https://myapp.com/checkout/callback' // Optional success return URL
})

// Redirect your user to checkoutUrl to complete the payment
console.log(`Checkout URL: ${checkoutUrl}`)

// 2. Verify payment status later (e.g., inside callback page or cron checks)
const result = await settle.payments.verify(reference)
if (result.status === 'success') {
  console.log('Payment successfully processed!')
}

// 3. Support for Web3 Solana USDC audit tracking (Devnet)
const solanaResult = await settle.payments.verifySolana(
  'sol_ref_9901',
  '4t6fHnQ9...' // On-chain transaction signature
)

Wallet

Manage user virtual credit balances directly from the SDK with atomic transaction logs.

// Credit a user's wallet (e.g., promotional sign-up bonus)
await settle.wallet.credit('user_123', {
  amount: 100,
  description: 'Welcome bonus',
})

// Deduct credits for usage
import { InsufficientCreditsError } from 'settlesettle'

try {
  await settle.wallet.debit('user_123', {
    amount: 10,
    description: 'AI Query execution',
  })
} catch (err) {
  if (err instanceof InsufficientCreditsError) {
    // Gracefully handle balance exhaustion
    console.log(`Insufficient credits. Current balance: ${err.currentBalance}`)
  }
}

// View paginated transaction history
const history = await settle.wallet.getHistory('user_123', { page: 1, limit: 10 })
console.log(history.transactions) // List of past credits/debits

Subscriptions

Check user recurring subscription plans, verify access states, activate webhooks, or schedule cancellations.

// 1. Check if user has active subscription access to your premium tier
const { hasAccess, reason, subscription } = await settle.subscriptions.checkAccess('user_123')

if (!hasAccess) {
  console.log(`Access Denied: ${reason}`)
  // Trigger pricing paywall modal
} else {
  console.log(`Access Granted! Active Plan: ${subscription?.planId}`)
}

// 2. Get full user subscription details
const subDetails = await settle.subscriptions.getSubscription('user_123')
if (subDetails) {
  console.log(`Subscription status: ${subDetails.status}`)
}

// 3. Activate a subscription manually (e.g., upon successful checkout webhook confirmation)
const newSub = await settle.subscriptions.activate('user_123', 'plan_pro_monthly', {
  userEmail: '[email protected]',
  billingMode: 'wallet_balance' // Supports 'wallet_balance' or 'paystack_recurrent'
})

// 4. Cancel subscription (defaults to cancel-at-period-end so user retains access until period expires)
const cancelled = await settle.subscriptions.cancel('user_123', 'plan_pro_monthly')
console.log(`Subscription will officially expire on: ${cancelled.currentPeriodEnd}`)

Events (Usage Metering)

Track user usage activities with a high-performance background buffering queue. Event reporting is non-blocking and synchronous in your hot code path.

// Non-blocking and synchronous — events are batched and flushed in background thread
settle.events.track({
  userId: 'user_123',
  eventType: 'AI_QUERY',
  metadata: { model: 'gpt-4', tokens: 1500 }
})

// Query usage summary metrics for a user
const summary = await settle.events.getSummary('user_123')
console.log(`Total events tracked today: ${summary.totalCount}`)

Authentication

Retrieve, rotate, and manage JWT session credentials for programmatically calling administrative developer APIs.

const auth = await settle.auth.login({
  email: '[email protected]',
  password: 'securepassword',
})

// Set the access token to authenticate the SDK for developer configuration routes
settle.setAccessToken(auth.accessToken)

Users (Directory Sync)

Keep customer accounts in sync. Idempotently mirror user profiles from your application database into SettleSettle's unified directory.

// Safe to call on every user login or profile update
await settle.users.sync({
  externalUserId: 'user_abc123',
  email: '[email protected]',
  name: 'Tunde Adeyemi',
})

Billing (Widget Support & Ad Rewards)

Bootstrap checkout widgets, load pricing modes, and issue free virtual credits to users for completing ad video views.

// 1. Bootstrap all UI config, plans, wallet balances, and active billing modes in a single call
const config = await settle.billing.bootstrap('user_123')
console.log('Theme Color:', config.uiConfig.themeColor)
console.log('Allowed Modes:', config.allowedBillingModes) // e.g. ['credits', 'subscription']

// 2. Reward ad credits upon completed video stream (calculated server-side)
const result = await settle.billing.rewardAd('user_123')
console.log(`Awarded ${result.creditsAwarded} credits. New balance: ${result.newBalance}`)

// 3. Report custom ad network impressions
await settle.billing.reportAdImpression('imp_abc123', 45) // 45 seconds duration

// 4. Developer Management (Requires JWT Auth)
const packages = await settle.billing.listPackages('app_123')
const newAction = await settle.billing.createAction('app_123', {
  eventType: 'PREMIUM_FEATURE',
  creditCost: 50
})

Ads (Developer Earnings)

Track and withdraw the ad-reward revenue generated by your application's ad completions.

// Fetch ad-rewards earnings summary and ledger balances
const earnings = await settle.ads.getEarningsSummary()
console.log('Available for withdrawal:', earnings.balance.availableKobo)

// Withdraw earnings to your registered developer bank account
await settle.ads.withdrawEarnings(500000) // Withdraw ₦5,000 in kobo

Advertiser (Campaign Management)

Configure advertising campaigns, creative media assets, and programmatic budgets.

// Create a new campaign const campaign = await settle.advertiser.createCampaign({ name: 'Summer Promo 2026', budgetKobo: 1000000, // ₦10,000 rewardCredits: 10 })

// Attach creative copywriting and link assets to campaign await settle.advertiser.addCreative(campaign.id, { headline: 'Premium Coding Assistant!', body: 'Work 10x faster with AI.', ctaLabel: 'Try Now', ctaUrl: 'https://brand.com/assistant', brandName: 'BrandX' })


---

## Error Handling

The SettleSettle SDK uses strictly typed, self-documenting error classes. Catching specific exception types is essential for constructing seamless failover systems:

```typescript
import {
  SettleSettleError,
  InsufficientCreditsError,
  AuthenticationError,
} from 'settlesettle'

try {
  await settle.wallet.debit('user_123', { amount: 15 })
} catch (err) {
  if (err instanceof InsufficientCreditsError) {
    console.log(`Balance: ${err.currentBalance}. Requested: ${err.requestedAmount}.`)
    // Trigger rewarded ad view fallback or credit top-up paywall
  } else if (err instanceof AuthenticationError) {
    console.error('Invalid API Key credentials')
  } else if (err instanceof SettleSettleError) {
    console.error('General SettleSettle Exception:', err.message)
  }
}

SDK Error Mapping

| Error Class | HTTP Code | Root Cause | |---|---|---| | AuthenticationError | 401 | Invalid, expired, or deactivated API secret key | | ValidationError | 400 | Malformed request body, missing fields, or invalid formats | | InsufficientCreditsError | 402 | Debit amount exceeds user's current wallet balance | | RateLimitError | 429 | Request volume exceeded limits. SDK automatically backs off and retries | | TimeoutError | - | Network connection timed out (Default limit: 10000ms) | | ApiError | 500 / Other | General server execution errors or database lock faults |


Graceful Shutdown

The usage metering events module utilizes memory buffering to optimize network overhead. When deploying in server environments, ensure the queue is cleanly flushed during server shutdown or container termination:

// On server shutdown or process exit
await settle.destroy()

Documentation

For full documentation and API reference, please visit settlesettle.uno.