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

hashbet-sdk

v0.2.2

Published

A TypeScript SDK for interacting with the HashBet smart contract and REST API.

Downloads

1,856

Readme

HashBet SDK

Project Overview

The HashBet SDK is a comprehensive TypeScript library designed to facilitate seamless interaction with the HashBet decentralized betting platform. It addresses the complexity of blockchain-based betting by providing a simple, type-safe interface for placing bets on-chain, querying bet data via REST APIs, and performing utility operations. Built for developers integrating betting functionality into dApps, web applications, or backend services, it ensures secure, efficient, and user-friendly access to HashBet's smart contract and backend systems.

Key value propositions include:

  • Decentralized Betting: Direct on-chain bet placement and settlement using Ethereum-compatible wallets.
  • Rich Data Access: Retrieve user stats, leaderboards, and bet histories through a robust REST API.
  • Developer Experience: Full TypeScript support with auto-completion, type checking, and comprehensive documentation.
  • Extensibility: Modular design allowing easy integration into existing projects.

Features

  • On-Chain Betting: Place and settle bets directly on the HashBet smart contract.
  • API Integration: Query bet histories, user statistics, leaderboards, and more via REST endpoints.
  • Utility Functions: Format token amounts, predict outcomes, validate addresses, and calculate payouts.
  • Authentication: Secure wallet-based sign-in for API access.
  • TypeScript Types: Strongly typed interfaces for all data structures and API responses.
  • Error Handling: Comprehensive error management for network failures and invalid inputs.
  • Event Listening: Real-time bet event subscriptions for dynamic applications.

Prerequisites & Installation

System Requirements

  • Node.js: Version 18.0.0 or higher (LTS recommended).
  • npm: Version 8.0.0 or higher (comes with Node.js).
  • Git: For cloning the repository (optional for users).
  • Ethereum Wallet: MetaMask or another EVM-compatible wallet for on-chain interactions.

Installation

  1. Ensure Node.js and npm are installed:

    node --version
    npm --version
  2. Install the SDK via npm:

    npm install hashbet-sdk
  3. For development (if contributing):

    git clone https://github.com/yourusername/hashbet-sdk.git
    cd hashbet-sdk
    npm install

Usage Guide

Basic Setup

Initialize the SDK with your preferred network and API settings:

import { HashBetSDK } from 'hashbet-sdk';

const sdk = new HashBetSDK({
  network: 'mainnet', // 'mainnet' or 'testnet'
  apiBaseUrl: 'https://hashbet.onrender.com', // Optional: custom API endpoint
  authToken: 'your-jwt-token', // Optional: for authenticated requests
});

Placing a Bet (On-Chain)

// Connect wallet (browser environment)
const sdkWithWallet = await HashBetSDK.connectWallet({
  network: 'mainnet',
});

// Place a bet (choice: true for Big, false for Small)
const result = await sdkWithWallet.contract.placeBet(true, 1000000000000000000n); // 1 CELO in wei
console.log('Bet placed:', result.txHash);

Querying Data (API)

// Get leaderboard
const leaderboard = await sdk.api.getLeaderboard({ period: 'week', limit: 10 });
console.log('Top players:', leaderboard.entries);

// Get user stats (requires authentication)
await sdk.api.login({ address: '0x...', signature: '...', message: '...' });
const stats = await sdk.api.getUserStats();
console.log('User stats:', stats);

Using Utility Functions

import { formatTokenAmount, getOutcome, calculatePayout } from 'hashbet-sdk';

// Format amounts
console.log(formatTokenAmount(1000000000000000000n, 18, 'CELO')); // "1.0 CELO"

// Predict outcome from block hash
const outcome = getOutcome('0x123abc...'); // "Big" or "Small"

// Calculate potential payout
const payout = calculatePayout(1000000000000000000n, 500); // With 5% house edge
console.log('Payout:', formatTokenAmount(payout, 18));

CLI Examples

For development:

# Run tests
npm test

# Build the project
npm run build

# Lint code
npm run lint

Configuration

The SDK supports customization through the HashBetSDKConfig interface:

| Option | Type | Default | Description | |-----------------|-----------|-----------------------------|-------------| | network | Network | 'mainnet' | Blockchain network: 'mainnet' or 'testnet'. | | contractAddress | string | Auto-detected from network | Custom smart contract address. | | apiBaseUrl | string | 'https://hashbet.onrender.com' | REST API base URL. | | authToken | string | undefined | JWT token for authenticated API requests. | | apiTimeout | number | 10000 | API request timeout in milliseconds. |

Example with full configuration:

const sdk = new HashBetSDK({
  network: 'testnet',
  contractAddress: '0x...',
  apiBaseUrl: 'https://custom-api.com',
  authToken: process.env.HASHBET_TOKEN,
  apiTimeout: 15000,
});

Environment variables can be used for sensitive data:

export HASHBET_API_URL=https://hashbet.onrender.com
export HASHBET_AUTH_TOKEN=your-token

Architecture/Tech Stack

Technologies Used

  • Language: TypeScript (strict mode for type safety).
  • Blockchain Interaction: Ethers.js v6 for Ethereum-compatible networks (e.g., Celo).
  • API Client: Native Fetch API with retry logic and error handling.
  • Testing: Jest with ts-jest for unit and integration tests.
  • Linting: ESLint with TypeScript rules.
  • Build Tool: Rollup for bundling CJS/ESM outputs and TypeScript declarations.
  • Package Manager: npm for dependency management and publishing.

High-Level Architecture

  • ContractClient: Handles on-chain operations (bet placement, settlement, token approvals) via smart contract interactions.
  • APIClient: Manages REST API calls for off-chain data (stats, leaderboards, authentication).
  • Utils: Pure functions for formatting, calculations, and validations.
  • Types: Centralized type definitions for contracts, APIs, and configurations.
  • Index: Barrel export for clean imports.

The SDK follows a modular, client-server pattern, separating on-chain logic from API interactions for scalability and maintainability.

Contributing Guidelines

We welcome contributions! Follow these steps to contribute effectively:

Development Setup

  1. Fork the repository on GitHub.
  2. Clone your fork: git clone https://github.com/yourusername/hashbet-sdk.git
  3. Install dependencies: npm install
  4. Create a feature branch: git checkout -b feature/your-feature-name

Coding Standards

  • Use TypeScript with strict mode enabled.
  • Follow ESLint rules: Run npm run lint and fix issues.
  • Write tests for new features: Aim for >80% coverage.
  • Use conventional commits: feat:, fix:, docs:, etc.
  • Keep PRs focused: One feature or bug fix per PR.

Pull Request Process

  1. Ensure tests pass: npm test
  2. Build successfully: npm run build
  3. Update documentation if needed.
  4. Submit PR with a clear description.
  5. Wait for review and address feedback.

Branching Strategy

  • main: Production-ready code.
  • develop: Integration branch for features.
  • Feature branches: feature/description for new work.
  • Bug fixes: fix/issue-description.

Testing

The SDK includes a comprehensive test suite using Jest.

Running Tests

# Run all tests
npm test

# Run with coverage
npm test -- --coverage

# Run specific test file
npm test -- tests/apiClient.test.ts

Test Structure

  • Unit Tests: Test individual functions in utils.ts, API methods, and contract interactions.
  • Integration Tests: Mock blockchain and API responses for end-to-end flows.
  • Coverage: Target 100% for critical paths (bet placement, API calls).

Ensure all tests pass before submitting PRs.

Project Structure

hashbet-sdk/
├── src/
│   ├── api/APIClient.ts          # REST API interactions
│   ├── contract/
│   │   ├── ContractClient.ts     # On-chain logic
│   │   ├── constants.ts          # Network configs and ABI
│   │   └── hashbet.abi.json      # Smart contract ABI
│   ├── types/
│   │   ├── index.ts              # TypeScript interfaces
│   │   └── global.d.ts           # Global type extensions
│   ├── utils.ts                  # Utility functions
│   ├── index.ts                  # Main exports
│   └── HashBetSDK.ts             # Core SDK class
├── tests/
│   ├── apiClient.test.ts         # API tests
│   └── utils.test.ts             # Utility tests
├── package.json                  # Project metadata and scripts
├── tsconfig.json                 # TypeScript configuration
├── jest.config.js                # Testing configuration
├── rollup.config.js              # Build configuration
├── .gitignore                    # Excluded files
├── .eslintrc.js                  # Linting rules
└── README.md                     # This file

License & Credits

License

This project is licensed under the MIT License. See the LICENSE file for details.

Credits

  • Ethers.js: For Ethereum blockchain interactions.
  • TypeScript: For type-safe development.
  • Jest: For testing framework.
  • ESLint: For code quality.

Built with ❤️ for the decentralized betting community.