Skip to main content

Program reference

The magic_chess Anchor program (Anchor 1.1.2) lives in magic-chess-program/programs/magic_chess.

Program ID (devnet)FbXiX6xcMRPVuTc7AZkQMSbpKa1uBzQY16NFf5jhJC7h
IDLsdk/src/idl/magic_chess.json
MagicBlock delegation programDELeGGvXpWV2fqJUhqcF5ZSYMS4JTLjteaAMARRSaeSh
MagicBlock session keys (gum)KeyspM2ssCJbqUhQ4k7sveSiY4WjnYsrXkC8oDbwde5
src/
├── lib.rs # instruction dispatch (#[ephemeral] #[program])
├── constants.rs # seeds, limits, fee splits
├── errors/ # ChessError (codes 6000–6058)
├── events/ # Anchor events read by the indexer
├── instructions/ # one file per instruction
├── state/ # ChessMatch, PredictionPool, PredictionBet, enums
└── utils/
├── chess_logic.rs # move generation, validation, game-end detection
└── payout_logic.rs # escrow payouts

Accounts​

AccountSeedsHolds
ChessMatch["chess_match", match_id]Players, board, turn, clock, castling/en passant, position history, wager terms, session keys, delegation flags
Match escrow (SPL token account)["match_escrow", match_id]Both wagers. Owned by its own PDA, closed at settlement or abort
PredictionPool["prediction_pool", match_id]Totals bet on White/Black/Draw, fee, settlement flag
Prediction vault (SPL token account)["prediction_pool_vault", prediction_pool]Prediction stakes
PredictionBet["prediction_bet", prediction_pool, bettor]One bettor's stake and outcome

match_id is a UTF-8 string of at most 32 bytes chosen by the creator. ZUG Arena uses mc- plus random characters.

ChessMatch fields​

FieldMeaning
players[2]players[0] is White (creator), players[1] is Black (Pubkey::default() until joined)
current_turnWhite or Black. Authorization derives from this, not from current_player_idx (kept for layout compatibility)
last_move_timestamp, move_timeout_durationPer-move clock in seconds, 30 s to 7 days (enforced at initialize_match)
game_status, game_end_reasonSee the enums below
board[8][8]Option<Piece>. Row 0 is rank 1, column 0 is the a-file
castling_rights, en_passant_target, halfmove_clock, fullmove_numberStandard FEN state
position_historyUp to 200 position hashes for threefold repetition
betting_token_mint, bet_amount_player_one/two, total_potWager terms. 0 is a free match
platform_fee_basis_points, platform_fee_walletFee terms set by the creator (max 10 000 bps)
payout_processedtrue after settlement or abort. Gates close_match
prediction_enabledAllows a PredictionPool for this match
is_delegated, delegation_uidRollup delegation state
white/black_session_signer, ..._expires_atRegistered fast-play session keys
active_task_idUnused, always -1. Kept so the account layout doesn't change

Enums​

  • GameStatus: WaitingForOpponent, Active, WhiteWins, BlackWins, Draw, Aborted
  • GameEndReason: Checkmate, Stalemate, Resignation, Timeout, FiftyMoveRule, ThreefoldRepetition, Aborted, InsufficientMaterial
  • PieceType: Pawn, Knight, Bishop, Rook, Queen, King

Instructions​

Match​

InstructionArgsWhoEffect
initialize_matchmatch_id, bet_amount, move_timeout_duration, platform_fee_basis_points, platform_fee_wallet, prediction_enabledCreator (White)Creates the match and escrow, deposits White's wager. The clock must be 30 s to 7 days, the fee at most 10% and the fee wallet the program's PLATFORM_FEE_WALLET
join_matchbet_amount (must equal the creator's)Anyone but the creatorDeposits Black's wager, sets status Active, starts the clock
abort_match—Creator, while WaitingForOpponentRefunds the wager, closes escrow, status Aborted
make_movefrom_row, from_col, to_row, to_col, promotionSide to move: wallet, its registered session key, or a gum SessionTokenV2Validates and applies the move, detects mate/draws, emits MoveMadeEvent. A move after the side's time ran out ends the game instead
resign_game—Either player (wallet)Opponent wins by Resignation
claim_timeout_win—The player not on moveWins by Timeout once now - last_move_timestamp > move_timeout_duration
process_match_settlement—AnyonePays out the escrow (see below), closes it, sets payout_processed. The escrow rent goes to payer, which must be a player or the platform fee wallet
close_match—A player or the platform fee wallet, after payout_processedCloses the ChessMatch account and returns its rent to the signer

MagicBlock​

InstructionWhoEffect
delegate_matchA player (any payer may fund it)Delegates ChessMatch to the rollup
commit_stateA player, on the rollupCommits rollup state to L1 and keeps the delegation
undelegate_matchA player, on the rollupCommits and returns the account to L1
process_undelegationDelegation programCallback generated by #[ephemeral], not called directly
set_session_keyA playerRegisters session_signer for that player's side until expires_at (max 7 days)
revoke_session_keyA playerClears that player's session key

Prediction pool (on-chain)​

InstructionWhoEffect
initialize_prediction_poolAnyone, when prediction_enabledCreates the pool and vault
place_prediction_betNon-players, while the match is WaitingForOpponent or ActiveStakes on White (0), Black (1) or Draw (2)
cancel_prediction_betBettor, if the match is waiting or abortedRefunds the stake
settle_prediction_poolAnyone, after the match endsFixes the pool result
claim_prediction_winningsBettorPays the winning share

See Prediction market for the payout split.

Settlement math​

fee = total_pot * platform_fee_basis_points / 10_000

WhiteWins / BlackWins: winner gets total_pot - fee
Draw: White gets (total_pot - fee) / 2 (rounded down),
Black gets the rest

Settlement checks that the player token accounts belong to the players, all accounts use the match mint, the fee account is owned by platform_fee_wallet, and no two accounts are the same.

Events​

EventEmitted byKey fields
MatchCreatedEventinitialize_matchcreator, mint, bet, timeout, fee bps
PlayerJoinedEventjoin_matchboth players, mint, bet per player
MoveMadeEventmake_moveplayer, colour, coordinates, promotion, SAN-style move, FEN, check/mate/stalemate flags
GameEndedEventgame-ending move, resign, timeoutstatus, winner, reason
PayoutEventsettlement (win)winner, amount, fee
DrawPayoutEventsettlement (draw)both players, amount each, fee
MatchAbortedEventabort_matchcreator
MatchClosedEventclose_matchmatch id

The backend indexer decodes these events from confirmed transactions on L1 and on the rollup. See Backend.

Errors​

CodeNameMessage
6000InvalidOwnerThe provided token account is not owned by the player.
6001InvalidMintThe provided token account's mint does not match the betting token mint.
6002InvalidBetAmountThe bet amount is invalid.
6003MatchAlreadyFullThe match is already full.
6004InvalidMatchIdLengthMatch ID length is invalid or exceeds maximum allowed.
6005InvalidPublicKeyStringInvalid public key string format during parsing.
6006InvalidPlatformFeePlatform fee basis points exceed maximum (10000).
6007UnsupportedBettingTokenUnsupported betting token mint. Only SEND or wSOL allowed.
6008InvalidMoveOutOfBoundsInvalid move: Coordinates out of bounds.
6009InvalidMoveEmptySourceInvalid move: Source square is empty.
6010InvalidMoveNotYourPieceInvalid move: Not your piece to move.
6011InvalidMoveCannotCaptureOwnPieceInvalid move: Cannot capture your own piece.
6012InvalidMoveIllegalPieceMovementInvalid move: Illegal movement for this piece type.
6013InvalidMoveLeavesKingInCheckInvalid move: Move leaves king in check.
6014InvalidPromotionPieceInvalid promotion: Specified piece type is not allowed for promotion.
6015InvalidPromotionNotOnLastRankInvalid promotion: Pawn is not on the last rank for promotion.
6016InvalidPromotionNotAPawnInvalid promotion: Only pawns can be promoted.
6017KingNotFoundInternal error: King not found on the board.
6018InvalidMatchIdInvalid Match ID provided.
6019AlreadyJoinedYou are already joined this match.
6020InvalidEscrowAccountInvalid escrow account authority.
6021MathErrorArithmetic operation overflow/underflow.
6022GameNotActiveThe game is not currently active.
6023NotAPlayerThe signer is not a registered player in this match.
6024NotYourTurnIt is not the signer's turn to move.
6025PlayerTimedOutPlayer has timed out.
6026MatchAlreadyFullOrActiveMatch is already full or active, cannot join.
6027InvalidMintForJoinThe mint of your token account does not match the established betting token for this match.
6028CannotJoinOwnMatchPlayer cannot join their own match as the second player.
6029BetAmountMismatchJoining bet amount does not match the creator's bet amount.
6030OpponentNotJoinedYetOpponent has not joined the match yet, cannot determine winner by resignation.
6031NotOpponentsTurnToClaimTimeoutIt is not the opponent's turn, so you cannot claim a timeout win yet.
6032TimeoutNotConfiguredMove timeout is not configured for this match.
6033OpponentNotTimedOutOpponent has not actually timed out yet.
6034GameNotConcludedThe game has not yet concluded.
6035PayoutAlreadyProcessedPayout for this match has already been processed.
6036PlayerTokenAccountMismatchPlayer token account mismatch for payout.
6037PlatformTokenAccountErrorPlatform fee token account mismatch or invalid mint for payout.
6038InvalidPlatformFeeWalletPlatform fee wallet does not match the expected recipient.
6039DuplicateAccountsDuplicate mutable accounts detected — state corruption risk.
6040InvalidGameStateForPayoutGame state is invalid for processing a payout (e.g., winner does not exist).
6041UnauthorizedSignerSigner is not authorized — must be the player whose turn it is or a valid session key.
6042InvalidSessionSession key is expired or invalid for this action.
6043MatchNotWaitingForOpponentMatch is not in WaitingForOpponent state, cannot abort.
6044NotMatchCreatorOnly the match creator can perform this action.
6045MatchNotSettledMatch settlement has not been processed yet, cannot close.
6046PredictionNotEnabledPrediction market is not enabled for this match.
6047PredictionPoolAlreadyExistsA prediction pool already exists for this match.
6048PredictionPoolNotFoundPrediction pool not found for this match.
6049PlayersCannotBetPlayers in the match cannot place prediction bets.
6050BettingClosedBetting is closed — the match is no longer Active.
6051InvalidOutcomeInvalid outcome — must be 0 (White), 1 (Black), or 2 (Draw).
6052SettlementAlreadyProcessedPrediction settlement has already been processed for this pool.
6053AlreadyClaimedWinnings have already been claimed for this bet.
6054NothingToClaimNothing to claim — no balance available for this bet.
6055MatchNotAbortedThe match has not been aborted, cannot cancel this way.
6056CannotCancelActiveMatchCannot cancel bet on an Active match.
6057InvalidTimeoutDurationMove timeout duration must be non-negative.