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

@block52/poker-vm-sdk

v1.1.9

Published

TypeScript SDK for Block52 Poker VM

Downloads

742

Readme

@block52/poker-vm-sdk

npm version License: MIT

TypeScript SDK for Block52 Poker VM - A blockchain-based poker platform built on Cosmos.

Features

  • 🎮 Complete Poker Game Logic - Card dealing, hand evaluation, and game state management
  • 🔐 Cosmos Blockchain Integration - Transaction signing, querying, and wallet management
  • 🎲 Deck Management - Shuffle, deal, and track card states with blockchain-verified randomness
  • 🤝 Type-Safe - Full TypeScript support with generated types from protobuf definitions
  • 🔄 Real-time Updates - WebSocket support for live game state synchronization
  • 💰 Token Operations - Built-in USDC token handling and conversions

Installation

npm install @block52/poker-vm-sdk

or with yarn:

yarn add @block52/poker-vm-sdk

Quick Start

Create a Signing Client

import { createSigningClientFromMnemonic, getDefaultCosmosConfig } from '@block52/poker-vm-sdk';

// Connect to the blockchain
const config = getDefaultCosmosConfig("mainnet"); // or "testnet", "localhost"
const mnemonic = "your twelve word mnemonic phrase here...";

const client = await createSigningClientFromMnemonic(config, mnemonic);
const walletAddress = await client.getWalletAddress();
console.log("Wallet Address:", walletAddress);

Create a Poker Game

// Define game parameters
const gameParams = {
    gameFormat: "cash",                      // or "tournament"
    gameVariant: "texas-holdem",
    minPlayers: 2,
    maxPlayers: 6,
    minBuyIn: client.usdcToB52usdc(10),      // 10 USDC minimum
    maxBuyIn: client.usdcToB52usdc(100),     // 100 USDC maximum
    smallBlind: client.usdcToB52usdc(0.5),   // 0.5 USDC small blind
    bigBlind: client.usdcToB52usdc(1),       // 1 USDC big blind
    timeout: 60                               // 60 seconds per action
};

// Create the game on-chain
const txHash = await client.createGame(
    gameParams.gameFormat,
    gameParams.gameVariant,
    gameParams.minPlayers,
    gameParams.maxPlayers,
    gameParams.minBuyIn,
    gameParams.maxBuyIn,
    gameParams.smallBlind,
    gameParams.bigBlind,
    gameParams.timeout
);

console.log("Game created! Transaction:", txHash);

Work with Cards and Decks

import { Deck, PokerSolver } from '@block52/poker-vm-sdk';

// Create and shuffle a deck
const deck = new Deck();
deck.shuffle([1, 2, 3, 4, 5]); // Seed for deterministic shuffle

// Deal cards
const playerHand = deck.deal(2);  // Deal 2 cards to player
const communityCards = deck.deal(5); // Deal 5 community cards

// Evaluate hand strength
const allCards = [...playerHand, ...communityCards];
const evaluation = PokerSolver.evaluateSevenCardHand(allCards);
console.log("Hand type:", evaluation.type);
console.log("Hand rank:", evaluation.rank);

// Compare two hands
const player1Evaluation = PokerSolver.evaluateSevenCardHand(player1Cards);
const player2Evaluation = PokerSolver.evaluateSevenCardHand(player2Cards);
const result = PokerSolver.compareHands(player1Evaluation, player2Evaluation);
// result > 0: player1 wins, < 0: player2 wins, 0: tie

Query Game State

import { CosmosClient, getDefaultCosmosConfig } from '@block52/poker-vm-sdk';

// Create a query-only client (no signing required)
const config = getDefaultCosmosConfig("mainnet");
const queryClient = new CosmosClient(config);

// Query a game by ID
const game = await queryClient.getGame(gameId);
console.log("Game options:", game);

// Get game state
const gameState = await queryClient.getGameState(gameId);
console.log("Game state:", gameState);

// List all games
const allGames = await queryClient.listGames();
console.log("Active games:", allGames.length);

// Get games for a specific player
const playerGames = await queryClient.getPlayerGames(playerAddress);
console.log("Player games:", playerGames.length);

Token Operations

// Convert between USDC and b52usdc (blockchain representation)
const usdcAmount = 100; // 100 USDC
const b52usdcAmount = client.usdcToB52usdc(usdcAmount);

// Convert back
const usdcValue = client.b52usdcToUsdc(b52usdcAmount);

// Check balance
const balance = await client.getB52USDCBalance(walletAddress);
console.log("Balance:", client.b52usdcToUsdc(balance), "USDC");

API Reference

SigningCosmosClient

Extends CosmosClient with transaction signing capabilities. Includes all query methods from CosmosClient plus:

Transaction Methods

  • createGame(gameFormat, gameVariant, minPlayers, maxPlayers, minBuyIn, maxBuyIn, smallBlind, bigBlind, timeout, rakeConfig?, sngConfig?) - Create a new poker game
  • joinGame(gameId, seat, buyInAmount) - Join an existing game at a specific seat
  • leaveGame(gameId) - Leave a game and cash out
  • performAction(gameId, action, amount?, data?) - Perform a poker action (fold, call, raise, check, all-in, deal)
  • topUp(gameId, amount) - Add chips to your stack at a table
  • sendTokens(fromAddress, toAddress, amount, denom?, memo?) - Send tokens to another address
  • sendB52USDC(fromAddress, toAddress, amount, memo?) - Send b52USDC tokens

Bridge Methods

  • processDeposit(depositIndex) - Process a bridge deposit from Ethereum by index
  • initiateWithdrawal(baseAddress, amount) - Initiate withdrawal to Base chain
  • getWithdrawalRequest(nonce) - Query a specific withdrawal request by nonce
  • listWithdrawalRequests(cosmosAddress?) - List withdrawal requests

Wallet Methods

  • getWalletAddress() - Get the current wallet address
  • setWallet(wallet) - Set a new wallet for signing
  • getWallet() - Get the current wallet instance
  • disconnect() - Close the client connection

CosmosClient

Query-only client for reading blockchain state via REST API.

Blockchain Query Methods

  • getAccount(address) - Get account information
  • getAllBalances(address) - Get all token balances for an address
  • getBalance(address, denom?) - Get specific token balance (default: b52USDC)
  • getHeight() - Get current block height
  • getTx(txHash) - Get transaction by hash
  • getBlock(height) - Get a specific block by height
  • getLatestBlock() - Get the most recent block
  • getBlocks(startHeight, count?) - Get multiple blocks starting from a height
  • getLatestBlocks(count?) - Get the most recent N blocks

Game Query Methods

  • getGame(gameId) - Get game options/configuration by ID
  • getGameState(gameId) - Get current game state by ID
  • listGames() - Get all active games
  • findGames(min?, max?) - Find games by player capacity (minPlayers/maxPlayers)
  • getPlayerGames(playerAddress) - Get all games for a specific player
  • getLegalActions(gameId, playerAddress?) - Get legal actions for a player in a game

Token & Utility Methods

  • getB52USDCBalance(address) - Get b52USDC balance for an address
  • b52usdcToUsdc(amount) - Convert b52USDC (micro units) to USDC display format
  • usdcToB52usdc(amount) - Convert USDC to b52USDC (micro units)
  • calculateEquity(hands, board?, dead?, simulations?) - Calculate hand equity via Monte Carlo
  • calculateEquityFull(hands, board?, dead?, simulations?) - Calculate equity with full metadata
  • listWithdrawalRequests(cosmosAddress?) - List withdrawal requests (all or for specific address)

Deck

Card deck management with blockchain integration.

Methods

  • constructor(deck?: string) - Create deck from mnemonic string or new ordered deck
  • getNext() - Draw next card
  • deal(amount) - Deal multiple cards
  • toString() - Serialize deck to string
  • shuffle(seed) - Shuffle deck (testing only, production uses blockchain randomness)

Constants

  • Deck.DECK_SIZE - Number of cards in a standard deck (52)
  • Deck.RANK_MAP - Map of rank values to strings (A, T, J, Q, K)
  • Deck.SUIT_MAP - Map of suit values to strings (C, D, H, S)

PokerSolver

Hand evaluation and poker logic.

Static Methods

  • evaluatePartialHand(cards) - Evaluate poker hand strength (partial or complete hand)
  • evaluateSevenCardHand(cards) - Evaluate best 5-card hand from 7 cards
  • compareHands(hand1, hand2) - Compare two hands to determine winner

Wallet Utilities

Utilities for wallet management.

  • generateWallet(prefix?, wordCount?) - Generate a new wallet with random mnemonic (12 or 24 words)
  • createWalletFromMnemonic(mnemonic, prefix?) - Create wallet from existing mnemonic
  • getAddressFromMnemonic(mnemonic, prefix?) - Derive address from mnemonic
  • isValidMnemonic(mnemonic) - Validate mnemonic phrase
  • BLOCK52_HD_PATH - Standard Cosmos HD derivation path for Block52

Configuration

Network Endpoints

import { getDefaultCosmosConfig } from '@block52/poker-vm-sdk';

// Mainnet
const mainnetConfig = getDefaultCosmosConfig("mainnet");

// Testnet
const testnetConfig = getDefaultCosmosConfig("testnet");

// Local development
const localConfig = getDefaultCosmosConfig("localhost");

// Custom configuration
const customConfig = {
    rpcEndpoint: "https://your-node.example.com:26657",
    restEndpoint: "https://your-node.example.com:1317",
    chainId: "pokerchain-1",
    prefix: "poker"
};

Examples

Check out the examples directory for complete working examples:

To run the examples:

git clone https://github.com/block52/poker-vm.git
cd poker-vm/sdk
yarn install
yarn build
npx ts-node examples/create-game-example.ts

Development

Building from Source

# Clone the repository
git clone https://github.com/block52/poker-vm.git
cd poker-vm/sdk

# Install dependencies
yarn install

# Build the SDK
yarn build

# Run tests
yarn test

# Lint code
yarn lint

Publishing to npm

The SDK is automatically published to npm via GitHub Actions when a release is created.

Automated Publishing Process

  1. Update the version in package.json:

    cd sdk
    # Edit package.json to update version (e.g., "1.1.9")
  2. Commit and push the version change:

    git add package.json
    git commit -m "chore: update SDK version to 1.1.9"
    git push
  3. Create a GitHub release with a tag matching sdk-v*:

    gh release create sdk-v1.1.9 --title "SDK v1.1.9" --notes "Release notes here"

The GitHub Action workflow will automatically:

  • Install dependencies
  • Run tests
  • Build the SDK
  • Verify the package.json version matches the release tag
  • Publish to npm with public access

Important Notes:

  • The release tag must start with sdk-v (e.g., sdk-v1.1.9)
  • The version in package.json must match the tag version (e.g., 1.1.9 for tag sdk-v1.1.9)
  • The NPM_TOKEN secret must be configured in GitHub repository settings
  • The workflow uses --ignore-scripts to skip the prepublishOnly script since it already builds the SDK

Project Structure

sdk/
├── src/
│   ├── index.ts                    # Main entry point
│   ├── client.ts                   # Base client implementation
│   ├── cosmosClient.ts             # Query client
│   ├── signingClient.ts            # Signing client
│   ├── deck.ts                     # Deck class
│   ├── pokerSolver.ts              # Hand evaluation
│   ├── walletUtils.ts              # Wallet utilities
│   ├── types/                      # TypeScript type definitions
│   ├── utils/                      # Utility functions
│   └── pokerchain.poker.v1/        # Generated protobuf types
├── examples/                       # Usage examples
├── tests/                          # Test files
└── dist/                           # Built output (after yarn build)

TypeScript Support

This SDK is written in TypeScript and includes full type definitions. No additional @types packages are needed.

import type { GameStateResponseDTO, PlayerDTO, ActionDTO } from '@block52/poker-vm-sdk';

Canonical Types

The SDK defines the single source of truth for all game types:

  • GameStateResponseDTO - Root type for game data over the wire
  • TexasHoldemStateDTO - Game state (contains players, communityCards, etc.)
  • GameOptionsDTO - Game configuration (NO format or owner - use root fields)
  • PlayerDTO - Player information

See CLAUDE.md for complete type rules.

Browser Support

The SDK works in both Node.js and browser environments. For browser usage, you may need to configure polyfills for Node.js built-ins:

// Example webpack config
module.exports = {
  resolve: {
    fallback: {
      "stream": require.resolve("stream-browserify"),
      "crypto": require.resolve("crypto-browserify"),
      "buffer": require.resolve("buffer/")
    }
  }
};

Contributing

Contributions are welcome! Please see the main repository for contribution guidelines.

License

MIT License - see LICENSE file for details.

Support

Related Projects

Changelog

See Releases for version history and changes.