@block52/poker-vm-sdk

中文文档
1.24.0发布于 2026/11/05MITTypeScriptESM + CJS近 30 天下载 3038

TypeScript SDK for Block52 Poker VM

原始使用文档
文档目录29 节
  1. Features
  2. Installation
  3. Quick Start
  4. Create a Signing Client
  5. Create a Poker Game
  6. Work with Cards and Decks
  7. Query Game State
  8. Token Operations
  9. API Reference
  10. SigningCosmosClient
  11. CosmosClient
  12. Deck
  13. PokerSolver
  14. Wallet Utilities
  15. Configuration
  16. Network Endpoints
  17. Examples
  18. Development
  19. Building from Source
  20. Publishing to npm
  21. Project Structure
  22. TypeScript Support
  23. Canonical Types
  24. Browser Support
  25. Contributing
  26. License
  27. Support
  28. Related Projects
  29. Changelog

@block52/poker-vm-sdk

npm version SDK Tests 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

Changelog

See Releases for version history and changes.

版本与发布记录

@block52/poker-vm-sdk 共发布 69 个版本,首次发布于 2025/12/14;过去 12 个月发布了 69 个版本。

版本发布日期距今
1.24.0latest2026/11/053 天前
1.23.02026/11/026 天前
1.22.02026/10/318 天前
1.21.02026/10/309 天前
1.19.02026/10/309 天前
1.17.02026/10/2811 天前

关于 @block52/poker-vm-sdk 的常见问题

@block52/poker-vm-sdk 是什么?

TypeScript SDK for Block52 Poker VM

如何安装 @block52/poker-vm-sdk?

在项目目录运行 npm install @block52/poker-vm-sdk,或使用 pnpm add / yarn add / bun add。

@block52/poker-vm-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@block52/poker-vm-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@block52/poker-vm-sdk 可以商用吗?

@block52/poker-vm-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@block52/poker-vm-sdk 的下载量有多少?

根据 npm 官方下载统计,@block52/poker-vm-sdk 在 2026/10/09 – 2026/11/07 这 30 天内被下载 3,038 次,日均约 101 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@block52/poker-vm-sdk 还在维护吗?

最新版本 1.24.0 发布于 2026/11/05(3 天前);至今共发布 69 个版本,其中过去 12 个月发布了 69 个;首次发布于 2025/12/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。