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
Ensure Node.js and npm are installed:
node --version npm --versionInstall the SDK via npm:
npm install hashbet-sdkFor 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 lintConfiguration
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-tokenArchitecture/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
- Fork the repository on GitHub.
- Clone your fork:
git clone https://github.com/yourusername/hashbet-sdk.git - Install dependencies:
npm install - 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 lintand 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
- Ensure tests pass:
npm test - Build successfully:
npm run build - Update documentation if needed.
- Submit PR with a clear description.
- Wait for review and address feedback.
Branching Strategy
main: Production-ready code.develop: Integration branch for features.- Feature branches:
feature/descriptionfor 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.tsTest 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 fileLicense & 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.
