@block52/poker-vm-sdk
v1.1.9
Published
TypeScript SDK for Block52 Poker VM
Downloads
742
Maintainers
Readme
@block52/poker-vm-sdk
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-sdkor with yarn:
yarn add @block52/poker-vm-sdkQuick 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: tieQuery 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 gamejoinGame(gameId, seat, buyInAmount)- Join an existing game at a specific seatleaveGame(gameId)- Leave a game and cash outperformAction(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 tablesendTokens(fromAddress, toAddress, amount, denom?, memo?)- Send tokens to another addresssendB52USDC(fromAddress, toAddress, amount, memo?)- Send b52USDC tokens
Bridge Methods
processDeposit(depositIndex)- Process a bridge deposit from Ethereum by indexinitiateWithdrawal(baseAddress, amount)- Initiate withdrawal to Base chaingetWithdrawalRequest(nonce)- Query a specific withdrawal request by noncelistWithdrawalRequests(cosmosAddress?)- List withdrawal requests
Wallet Methods
getWalletAddress()- Get the current wallet addresssetWallet(wallet)- Set a new wallet for signinggetWallet()- Get the current wallet instancedisconnect()- Close the client connection
CosmosClient
Query-only client for reading blockchain state via REST API.
Blockchain Query Methods
getAccount(address)- Get account informationgetAllBalances(address)- Get all token balances for an addressgetBalance(address, denom?)- Get specific token balance (default: b52USDC)getHeight()- Get current block heightgetTx(txHash)- Get transaction by hashgetBlock(height)- Get a specific block by heightgetLatestBlock()- Get the most recent blockgetBlocks(startHeight, count?)- Get multiple blocks starting from a heightgetLatestBlocks(count?)- Get the most recent N blocks
Game Query Methods
getGame(gameId)- Get game options/configuration by IDgetGameState(gameId)- Get current game state by IDlistGames()- Get all active gamesfindGames(min?, max?)- Find games by player capacity (minPlayers/maxPlayers)getPlayerGames(playerAddress)- Get all games for a specific playergetLegalActions(gameId, playerAddress?)- Get legal actions for a player in a game
Token & Utility Methods
getB52USDCBalance(address)- Get b52USDC balance for an addressb52usdcToUsdc(amount)- Convert b52USDC (micro units) to USDC display formatusdcToB52usdc(amount)- Convert USDC to b52USDC (micro units)calculateEquity(hands, board?, dead?, simulations?)- Calculate hand equity via Monte CarlocalculateEquityFull(hands, board?, dead?, simulations?)- Calculate equity with full metadatalistWithdrawalRequests(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 deckgetNext()- Draw next carddeal(amount)- Deal multiple cardstoString()- Serialize deck to stringshuffle(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 cardscompareHands(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 mnemonicgetAddressFromMnemonic(mnemonic, prefix?)- Derive address from mnemonicisValidMnemonic(mnemonic)- Validate mnemonic phraseBLOCK52_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:
- create-game-example.ts - Complete example of creating a poker game
- wallet-example.ts - Wallet creation and management
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.tsDevelopment
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 lintPublishing to npm
The SDK is automatically published to npm via GitHub Actions when a release is created.
Automated Publishing Process
Update the version in
package.json:cd sdk # Edit package.json to update version (e.g., "1.1.9")Commit and push the version change:
git add package.json git commit -m "chore: update SDK version to 1.1.9" git pushCreate 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.jsonmust match the tag version (e.g.,1.1.9for tagsdk-v1.1.9) - The
NPM_TOKENsecret must be configured in GitHub repository settings - The workflow uses
--ignore-scriptsto skip theprepublishOnlyscript 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 wireTexasHoldemStateDTO- Game state (containsplayers,communityCards, etc.)GameOptionsDTO- Game configuration (NOformatorowner- 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
- 📚 Documentation: CLAUDE.md - Detailed SDK documentation
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 🌐 Website: Block52
Related Projects
Changelog
See Releases for version history and changes.
