Solidity API
ChessWager
https://github.com/Chess-Fish (opens in a new tab)
This contract is designed for managing chess wagers between users, saving game moves, and handling the payout of 1v1 matches. The Tournament Contract can call into this contract to create tournament matches among users.
GameWager
struct GameWager {
address player0;
address player1;
address wagerToken;
uint256 wager;
uint256 numberOfGames;
bool hasPlayerAccepted;
uint256 timeLimit;
uint256 timeLastMove;
uint256 timePlayer0;
uint256 timePlayer1;
bool isTournament;
bool isComplete;
bool hasBeenPaid;
}WagerStatus
struct WagerStatus {
bool isPlayer0White;
uint256 winsPlayer0;
uint256 winsPlayer1;
}Game
struct Game {
uint16[] moves;
}GaslessMoveData
struct GaslessMoveData {
address signer;
address player0;
address player1;
uint16 move;
uint256 moveNumber;
uint256 expiration;
bytes32 messageHash;
}gameWagers
mapping(address => struct ChessWager.GameWager) gameWagersaddress wager => GameWager
wagerPrizes
mapping(address => uint256) wagerPrizesaddress wager => WagerPrize
games
mapping(address => mapping(uint256 => struct ChessWager.Game)) gamesaddress wager => gameID => Game
gameIDs
mapping(address => uint256[]) gameIDsaddress wager => gameIDs
wagerStatus
mapping(address => struct ChessWager.WagerStatus) wagerStatusaddress wager => Player Wins
userGames
mapping(address => address[]) userGamesplayer can see game challenges
allWagers
address[] allWagersaddress[] wagers
ChessFishToken
address ChessFishTokenCFSH Token Address
DividendSplitter
address DividendSplitterDividend Splitter contract
ChessFishNFT
address ChessFishNFTChessFish Winner NFT contract
gaslessGame
contract GaslessGame gaslessGameGasless Game Helper Contract
constructor
constructor(address moveVerificationAddress, address _GaslessGame, address _DividendSplitter, address _ChessFishNFT) publiccreateGameWagerEvent
event createGameWagerEvent(address wager, address wagerToken, uint256 wagerAmount, uint256 timeLimit, uint256 numberOfGames)acceptWagerEvent
event acceptWagerEvent(address wagerAddress, address userAddress)playMoveEvent
event playMoveEvent(address wagerAddress, uint16 move)payoutWagerEvent
event payoutWagerEvent(address wagerAddress, address winner, address wagerToken, uint256 wagerAmount, uint256 protocolFee)cancelWagerEvent
event cancelWagerEvent(address wagerAddress, address userAddress)getAllWagersCount
function getAllWagersCount() external view returns (uint256)getAllWagerAddresses
function getAllWagerAddresses() external view returns (address[])getAllUserGames
function getAllUserGames(address player) external view returns (address[])getGameLength
function getGameLength(address wagerAddress) external view returns (uint256)getGameMoves
function getGameMoves(address wagerAddress, uint256 gameID) external view returns (struct ChessWager.Game)getLatestGameMoves
function getLatestGameMoves(address wagerAddress) external view returns (uint16[])getNumberOfGamesPlayed
function getNumberOfGamesPlayed(address wagerAddress) internal view returns (uint256)getGameWagers
function getGameWagers(address wagerAddress) external view returns (struct ChessWager.GameWager)getWagerPlayers
function getWagerPlayers(address wagerAddress) external view returns (address, address)getWagerStatus
function getWagerStatus(address wagerAddress) public view returns (address, address, uint256, uint256)Get Wager Status
Returns the current status of a specific wager.
Parameters
| Name | Type | Description |
|---|---|---|
| wagerAddress | address | The address of the wager for which the status is being requested. |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | address | player0 The address of the first player in the wager. |
| [1] | address | player1 The address of the second player in the wager. |
| [2] | uint256 | winsPlayer0 The number of wins recorded for player0. |
| [3] | uint256 | winsPlayer1 The number of wins recorded for player1. |
checkTimeRemaining
function checkTimeRemaining(address wagerAddress) public view returns (int256, int256)Checks how much time is remaining in game
using int to quickly check if game lost on time and to prevent underflow revert
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | int256 | timeRemainingPlayer0 |
| [1] | int256 | timeRemainingPlayer1 |
getPlayerMove
function getPlayerMove(address wagerAddress) public view returns (address)Gets the address of the player whose turn it is
Parameters
| Name | Type | Description |
|---|---|---|
| wagerAddress | address | address of the wager |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | address | playerAddress |
isPlayerWhite
function isPlayerWhite(address wagerAddress, address player) public view returns (bool)Returns boolean if player is white or not
Parameters
| Name | Type | Description |
|---|---|---|
| wagerAddress | address | address of the wager |
| player | address | address player |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | bool | isPlayerWhite |
getGameStatus
function getGameStatus(address wagerAddress) public view returns (uint8, uint256, uint32, uint32)Gets the game status for the last played game in a wager
Parameters
| Name | Type | Description |
|---|---|---|
| wagerAddress | address | address of the wager |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | uint8 | outcome, |
| [1] | uint256 | gameState |
| [2] | uint32 | player0State |
| [3] | uint32 | player1State |
getChainId
function getChainId() internal view returns (uint256)Returns chainId
used for ensuring unique hash independent of chain
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | uint256 | chainId |
getWagerAddress
function getWagerAddress(struct ChessWager.GameWager wager) internal view returns (address)Generates unique hash for a game wager
using keccak256 to generate a hash which is converted to an address
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | address | wagerAddress |
verifyGameUpdateState
function verifyGameUpdateState(bytes[] message, bytes[] signature) external returns (bool)Verifies game moves and updates the state of the wager
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | bool | isEndGame |
verifyGameUpdateStateDelegated
function verifyGameUpdateStateDelegated(bytes[2] delegations, bytes[] messages, bytes[] signatures) external returns (bool)Verifies game moves and updates the state of the wager
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | bool | isEndGame |
TournamentHandler
address TournamentHandleronlyTournament
modifier onlyTournament()addTournamentHandler
function addTournamentHandler(address _tournamentHandler) externalAdds Tournament contract
startWagersInTournament
function startWagersInTournament(address wagerAddress) externalStarts tournament wagers
createGameWagerTournamentSingle
function createGameWagerTournamentSingle(address player0, address player1, address wagerToken, uint256 wagerAmount, uint256 numberOfGames, uint256 timeLimit) external returns (address wagerAddress)Creates a wager between two players
only the tournament contract can call
Return Values
| Name | Type | Description |
|---|---|---|
| wagerAddress | address | created wager address |
createGameWager
function createGameWager(address player1, address wagerToken, uint256 wager, uint256 timeLimit, uint256 numberOfGames) external payable returns (address wagerAddress)Creates a 1v1 chess wager
acceptWager
function acceptWager(address wagerAddress) externalPlayer1 calls if they accept challenge
playMove
function playMove(address wagerAddress, uint16 move) external returns (bool)Plays move on the board
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | bool | bool true if endGame, adds extra game if stalemate |
payoutWager
function payoutWager(address wagerAddress) external returns (bool)Handles payout of wager
smallest wager amount is 18 wei before fees => 0
mintWinnerNFT
function mintWinnerNFT(address wagerAddress) externalmint tournament winner NFT
cancelWager
function cancelWager(address wagerAddress) externalCancel wager
cancel wager only if other player has not yet accepted && only if msg.sender is one of the players
updateWagerStateTime
function updateWagerStateTime(address wagerAddress) public returns (bool)Updates the state of the wager if player time is < 0
check when called with timeout w tournament set to public so that anyone can update time if player disappears
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | bool | wasUpdated returns true if status was updated |
updateWagerStateInsufficientMaterial
function updateWagerStateInsufficientMaterial(address wagerAddress) public returns (bool)Update wager state if insufficient material
set to public so that anyone can update
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | bool | wasUpdated returns true if status was updated |
depositToWager
function depositToWager(address wagerAddress, uint256 amount) externalDeposits prize to wager address
used to deposit prizes to wager
GaslessGame
https://github.com/Chess-Fish (opens in a new tab)
This smart contract is designed to handle gasless game moves. Key features include:
-
Off-Chain Move Signing: This contract enables game moves to be signed off-chain, significantly reducing the need for constant on-chain transactions. This approach substantially lowers transaction costs.
-
Delegated Signer Functionality: Players have the option to delegate a signer (generated on the front end) to execute moves on their behalf. This delegated signer functionality reduces the frequency of wallet signature requests, providing a smoother and more uninterrupted gameplay experience. It ensures that players can focus on strategy rather than managing transaction confirmations.
GaslessMove
struct GaslessMove {
address wagerAddress;
uint256 gameNumber;
uint256 moveNumber;
uint16 move;
uint256 expiration;
}GaslessMoveData
struct GaslessMoveData {
address signer;
address player0;
address player1;
struct GaslessGame.GaslessMove move;
bytes signature;
}Delegation
struct Delegation {
address delegatorAddress;
address delegatedAddress;
address wagerAddress;
}SignedDelegation
struct SignedDelegation {
struct GaslessGame.Delegation delegation;
bytes signature;
}moveVerification
contract MoveVerification moveVerificationMoveVerification contract
chessWager
contract ChessWager chessWagerdeployer
address deployeraddress deployer
MOVE_METHOD_HASH
bytes32 MOVE_METHOD_HASHEIP-712 typed move signature
DELEGATION_METHOD_HASH
bytes32 DELEGATION_METHOD_HASHEIP-712 typed delegation signature
onlyDeployer
modifier onlyDeployer()constructor
constructor(address moveVerificationAddress) publicsetChessWager
function setChessWager(address _chessWager) externalset ChessWager contract
encodeMoveMessage
function encodeMoveMessage(struct GaslessGame.GaslessMove move) external pure returns (bytes)Generates gasless move message
decodeMoveMessage
function decodeMoveMessage(bytes message) internal pure returns (struct GaslessGame.GaslessMove move)Decodes gasless move message
decodeWagerAddress
function decodeWagerAddress(bytes message) internal pure returns (address)Decodes gasless move message and returns wager address
verifyMoveSigner
function verifyMoveSigner(struct GaslessGame.GaslessMoveData moveData, bytes signature) internal viewtyped signature verification
verifyMoves
function verifyMoves(address playerToMove, struct GaslessGame.GaslessMoveData moveData, bytes[] messages, bytes[] signatures) internal view returns (uint16[] moves)Verifies signed messages and signatures in for loop
returns array of the gasless moves
verifyGameView
function verifyGameView(bytes[] messages, bytes[] signatures) public view returns (address wagerAddress, uint8 outcome, uint16[] moves)Verifies all signed messages and signatures
appends onchain moves to gasless moves reverts if invalid signature
createDelegation
function createDelegation(address delegatorAddress, address delegatedAddress, address wagerAddress) external pure returns (struct GaslessGame.Delegation)Create delegation data type helper function
encodeSignedDelegation
function encodeSignedDelegation(struct GaslessGame.Delegation delegation, bytes signature) external pure returns (bytes)Encode signed delegation helper function
decodeSignedDelegation
function decodeSignedDelegation(bytes signedDelegationBytes) public pure returns (struct GaslessGame.SignedDelegation signedDelegation)Decode Signed Delegation
checkIfAddressesArePlayers
function checkIfAddressesArePlayers(address delegator0, address delegator1, address wagerAddress) internal viewCheck if delegators match players in wagerAddress
checkDelegations
function checkDelegations(struct GaslessGame.SignedDelegation signedDelegation0, struct GaslessGame.SignedDelegation signedDelegation1) internal viewCheck delegations
verifyDelegation
function verifyDelegation(struct GaslessGame.SignedDelegation signedDelegation) internal viewtyped signature verification
verifyGameViewDelegated
function verifyGameViewDelegated(bytes[2] delegations, bytes[] messages, bytes[] signatures) external view returns (address wagerAddress, uint8 outcome, uint16[] moves)Verify game moves via delegated signature
MoveHelper
https://github.com/Chess-Fish (opens in a new tab)
This contract handles move conversion functionality to the MoveVerification contract as well as setting board coordinates.
pieces
mapping(uint8 => string) piecescoordinates
mapping(string => uint256) coordinatesalgebraic chess notation string => uint (0-63)
squareToCoordinate
mapping(uint256 => string) squareToCoordinatedeployer
address deployeraddress deployer
moveVerification
contract MoveVerification moveVerificationMoveVerification contract
protocolFee
uint256 protocolFee5% fee to token holders
OnlyDeployer
modifier OnlyDeployer()initCoordinates
function initCoordinates(string[64] coordinate, uint256[64] value) externalcalled from ts since hardcoding the mapping makes the contract too large
initPieces
function initPieces() internalInitialize pieces This function significantly increases the size of the compiled bytecode...
getLetter
function getLetter(uint8 piece) public view returns (string)Convert the number of a piece to the string character
Parameters
| Name | Type | Description |
|---|---|---|
| piece | uint8 | is the number of the piece |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | string | string is the letter of the piece |
convertFromMove
function convertFromMove(uint16 move) public pure returns (uint8, uint8)Converts a move from a 16-bit integer to a 2 8-bit integers.
Parameters
| Name | Type | Description |
|---|---|---|
| move | uint16 | is the move to convert |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | uint8 | fromPos and toPos |
| [1] | uint8 |
convertToMove
function convertToMove(uint8 fromPos, uint8 toPos) public pure returns (uint16)Converts two 8-bit integers to a 16-bit integer
Parameters
| Name | Type | Description |
|---|---|---|
| fromPos | uint8 | is the position to move a piece from. |
| toPos | uint8 | is the position to move a piece to. |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | uint16 | move |
moveToHex
function moveToHex(string move) external view returns (uint16 hexMove)Converts an algebraic chess notation string move to uint16 format
Parameters
| Name | Type | Description |
|---|---|---|
| move | string | is the move to convert i.e. e2e4 to hex move |
Return Values
| Name | Type | Description |
|---|---|---|
| hexMove | uint16 | is the resulting uint16 value |
hexToMove
function hexToMove(uint16 hexMove) public view returns (string move)Converts a uint16 hex value to move in algebraic chess notation
Parameters
| Name | Type | Description |
|---|---|---|
| hexMove | uint16 | is the move to convert to string |
Return Values
| Name | Type | Description |
|---|---|---|
| move | string | is the resulting string value |
getBoard
function getBoard(uint256 gameState) external view returns (string[64])returns string of letters representing the board only to be called by user or ui
Parameters
| Name | Type | Description |
|---|---|---|
| gameState | uint256 | is the uint256 game state of the board |
Return Values
| Name | Type | Description |
|---|---|---|
| [0] | string[64] | string[64] is the resulting array |
MoveVerification
https://github.com/Chess-Fish (opens in a new tab) This contract handles the logic for verifying the validity moves on the chessboard. Currently, pawns autoqueen by default.
Forked from: https://github.com/marioevz/chess.eth (opens in a new tab) (Updated from Solidity 0.7.6 to 0.8.17 & Added features and functionality)
empty_const
uint8 empty_constpawn_const
uint8 pawn_constbishop_const
uint8 bishop_constknight_const
uint8 knight_constrook_const
uint8 rook_constqueen_const
uint8 queen_constking_const
uint8 king_consttype_mask_const
uint8 type_mask_constcolor_const
uint8 color_constpiece_bit_size
uint8 piece_bit_sizepiece_pos_shift_bit
uint8 piece_pos_shift_biten_passant_const
uint32 en_passant_constking_pos_mask
uint32 king_pos_maskking_pos_zero_mask
uint32 king_pos_zero_maskking_pos_bit
uint16 king_pos_bitrook_king_side_move_mask
uint32 rook_king_side_move_maskFor castling masks, mask only the last bit of an uint8, to block any under/overflows.
rook_king_side_move_bit
uint16 rook_king_side_move_bitrook_queen_side_move_mask
uint32 rook_queen_side_move_maskrook_queen_side_move_bit
uint16 rook_queen_side_move_bitking_move_mask
uint32 king_move_maskpieces_left_bit
uint16 pieces_left_bitking_white_start_pos
uint8 king_white_start_posking_black_start_pos
uint8 king_black_start_pospos_move_mask
uint16 pos_move_maskrequest_draw_const
uint16 request_draw_constaccept_draw_const
uint16 accept_draw_constresign_const
uint16 resign_constinconclusive_outcome
uint8 inconclusive_outcomedraw_outcome
uint8 draw_outcomewhite_win_outcome
uint8 white_win_outcomeblack_win_outcome
uint8 black_win_outcomegame_state_start
uint256 game_state_startfull_long_word_mask
uint256 full_long_word_maskinvalid_move_constant
uint256 invalid_move_constantinitial_white_state
uint32 initial_white_stateInitial white state: 0f: 15 (non-king) pieces left 00: Queen-side rook at a1 position 07: King-side rook at h1 position 04: King at e1 position ff: En-passant at invalid position
initial_black_state
uint32 initial_black_stateInitial black state: 0f: 15 (non-king) pieces left 38: Queen-side rook at a8 position 3f: King-side rook at h8 position 3c: King at e8 position ff: En-passant at invalid position
checkGameFromStart
function checkGameFromStart(uint16[] moves) public pure returns (uint8, uint256, uint32, uint32)checkGame
function checkGame(uint256 startingGameState, uint32 startingPlayerState, uint32 startingOpponentState, bool startingTurnBlack, uint16[] moves) public pure returns (uint8 outcome, uint256 gameState, uint32 playerState, uint32 opponentState)Calculates the outcome of a game depending on the moves from a starting position. Reverts when an invalid move is found. @param startingGameState Game state from which start the movements @param startingPlayerState State of the first playing player @param startingOpponentState State of the other playing player @param startingTurnBlack Whether the starting player is the black pieces @param moves is the input array containing all the moves in the game @return outcome can be 0 for inconclusive, 1 for draw, 2 for white winning, 3 for black winning
verifyExecuteMove
function verifyExecuteMove(uint256 gameState, uint16 move, uint32 playerState, uint32 opponentState, bool currentTurnBlack) public pure returns (uint256 newGameState, uint32 newPlayerState, uint32 newOpponentState)Calculates the outcome of a single move given the current game state. Reverts for invalid movement. @param gameState current game state on which to perform the movement. @param move is the move to execute: 16-bit var, high word = from pos, low word = to pos move can also be: resign, request draw, accept draw. @param currentTurnBlack true if it's black turn @return newGameState the new game state after it's executed.
verifyExecutePawnMove
function verifyExecutePawnMove(uint256 gameState, uint8 fromPos, uint8 toPos, uint8 moveExtra, bool currentTurnBlack, uint32 playerState, uint32 opponentState) public pure returns (uint256 newGameState, uint32 newPlayerState)Calculates the outcome of a single move of a pawn given the current game state. Returns invalid_move_constant for invalid movement. @param gameState current game state on which to perform the movement. @param fromPos is position moving from. @param toPos is position moving to. @param currentTurnBlack true if it's black turn @return newGameState the new game state after it's executed.
verifyExecuteKnightMove
function verifyExecuteKnightMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack) public pure returns (uint256)Calculates the outcome of a single move of a knight given the current game state. Returns invalid_move_constant for invalid movement. @param gameState current game state on which to perform the movement. @param fromPos is position moving from. @param toPos is position moving to. @param currentTurnBlack true if it's black turn @return newGameState the new game state after it's executed.
verifyExecuteBishopMove
function verifyExecuteBishopMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack) public pure returns (uint256)Calculates the outcome of a single move of a bishop given the current game state. Returns invalid_move_constant for invalid movement. @param gameState current game state on which to perform the movement. @param fromPos is position moving from. @param toPos is position moving to. @param currentTurnBlack true if it's black turn @return newGameState the new game state after it's executed.
verifyExecuteRookMove
function verifyExecuteRookMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack) public pure returns (uint256)Calculates the outcome of a single move of a rook given the current game state. Returns invalid_move_constant for invalid movement. @param gameState current game state on which to perform the movement. @param fromPos is position moving from. @param toPos is position moving to. @param currentTurnBlack true if it's black turn @return newGameState the new game state after it's executed.
verifyExecuteQueenMove
function verifyExecuteQueenMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack) public pure returns (uint256)Calculates the outcome of a single move of the queen given the current game state. Returns invalid_move_constant for invalid movement. @param gameState current game state on which to perform the movement. @param fromPos is position moving from. @param toPos is position moving to. @param currentTurnBlack true if it's black turn @return newGameState the new game state after it's executed.
verifyExecuteKingMove
function verifyExecuteKingMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack, uint32 playerState) public pure returns (uint256 newGameState, uint32 newPlayerState)Calculates the outcome of a single move of the king given the current game state. Returns invalid_move_constant for invalid movement. @param gameState current game state on which to perform the movement. @param fromPos is position moving from. Behavior is undefined for values >= 0x40. @param toPos is position moving to. Behavior is undefined for values >= 0x40. @param currentTurnBlack true if it's black turn @return newGameState the new game state after it's executed.
checkQueenValidMoves
function checkQueenValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack) public pure returns (bool)Checks if a move is valid for the queen in the given game state. Returns true if the move is valid, false otherwise. @param gameState The current game state on which to perform the movement. @param fromPos The position from which the queen is moving. @param playerState The player's state containing information about the king position. @param currentTurnBlack True if it's black's turn, false otherwise. @return A boolean indicating whether the move is valid or not.
checkBishopValidMoves
function checkBishopValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack) public pure returns (bool)Checks if a move is valid for the bishop in the given game state. Returns true if the move is valid, false otherwise. @param gameState The current game state on which to perform the movement. @param fromPos The position from which the bishop is moving. Behavior is undefined for values >= 0x40. @param playerState The player's state containing information about the king position. @param currentTurnBlack True if it's black's turn, false otherwise. @return A boolean indicating whether the move is valid or not.
checkRookValidMoves
function checkRookValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack) public pure returns (bool)Checks if a move is valid for the rook in the given game state. Returns true if the move is valid, false otherwise. @param gameState The current game state on which to perform the movement. @param fromPos The position from which the rook is moving. Behavior is undefined for values >= 0x40. @param playerState The player's state containing information about the king position. @param currentTurnBlack True if it's black's turn, false otherwise. @return A boolean indicating whether the move is valid or not.
checkKnightValidMoves
function checkKnightValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack) public pure returns (bool)Checks if a move is valid for the knight in the given game state. Returns true if the move is valid, false otherwise. @param gameState The current game state on which to perform the movement. @param fromPos The position from which the knight is moving. Behavior is undefined for values >= 0x40. @param playerState The player's state containing information about the king position. @param currentTurnBlack True if it's black's turn, false otherwise. @return A boolean indicating whether the move is valid or not.
checkPawnValidMoves
function checkPawnValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, uint32 opponentState, bool currentTurnBlack) public pure returns (bool)Checks if a move is valid for the pawn in the given game state. Returns true if the move is valid, false otherwise. @param gameState The current game state on which to perform the movement. @param fromPos The position from which the knight is moving. Behavior is undefined for values >= 0x40. @param playerState The player's state containing information about the king position. @param currentTurnBlack True if it's black's turn, false otherwise. @return A boolean indicating whether the move is valid or not.
checkKingValidMoves
function checkKingValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack) public pure returns (bool)searchPiece
function searchPiece(uint256 gameState, uint32 playerState, uint32 opponentState, uint8 color, uint16 pBitOffset, uint16 bitSize) public pure returns (bool)Performs one iteration of recursive search for pieces. @param gameState Game state from which start the movements @param playerState State of the player @param opponentState State of the opponent @return returns true if any of the pieces in the current offest has legal moves
checkEndgame
function checkEndgame(uint256 gameState, uint32 playerState, uint32 opponentState) public pure returns (uint8)Checks the endgame state and determines whether the last user is checkmate'd or stalemate'd, or neither. @param gameState Game state from which start the movements @param playerState State of the player @return outcome can be 0 for inconclusive/only check, 1 stalemate, 2 checkmate
getInBetweenMask
function getInBetweenMask(uint8 fromPos, uint8 toPos) public pure returns (uint256)Gets the mask of the in-between squares. Basically it performs bit-shifts depending on the movement. Down: >> 8 Up: << 8 Right: << 1 Left: >> 1 UpRight: << 9 DownLeft: >> 9 DownRight: >> 7 UpLeft: << 7 Reverts for invalid movement. @param fromPos is position moving from. @param toPos is position moving to. @return mask of the in-between squares, can be bit-wise-and with the game state to check squares
getPositionMask
function getPositionMask(uint8 pos) public pure returns (uint256)Gets the mask (0xF) of a square @param pos square position. @return mask
getHorizontalMovement
function getHorizontalMovement(uint8 fromPos, uint8 toPos) public pure returns (uint8)Calculates the horizontal movement between two positions on a chessboard. @param fromPos The starting position from which the movement is measured. @param toPos The ending position to which the movement is measured. @return The horizontal movement between the two positions.
getVerticalMovement
function getVerticalMovement(uint8 fromPos, uint8 toPos) public pure returns (uint8)Calculates the vertical movement between two positions on a chessboard. @param fromPos The starting position from which the movement is measured. @param toPos The ending position to which the movement is measured. @return The vertical movement between the two positions.
checkForCheck
function checkForCheck(uint256 gameState, uint32 playerState) public pure returns (bool)Checks if the king in the given game state is under attack (check condition). @param gameState The current game state to analyze. @param playerState The player's state containing information about the king position. @return A boolean indicating whether the king is under attack (check) or not.
pieceUnderAttack
function pieceUnderAttack(uint256 gameState, uint8 pos) public pure returns (bool)Checks if a piece at the given position is under attack in the given game state. @param gameState The current game state to analyze. @param pos The position of the piece to check for attack. @return A boolean indicating whether the piece at the given position is under attack.
isStalemateViaInsufficientMaterial
function isStalemateViaInsufficientMaterial(uint256 gameState) public pure returns (bool)Checks if gameState has insufficient material @param gameState current game state @return isInsufficient returns true if insufficient material
commitMove
function commitMove(uint256 gameState, uint8 fromPos, uint8 toPos) public pure returns (uint256)Commits a move into the game state. Validity of the move is not checked. @param gameState current game state @param fromPos is the position to move a piece from. @param toPos is the position to move a piece to. @return newGameState
zeroPosition
function zeroPosition(uint256 gameState, uint8 pos) public pure returns (uint256)Zeroes out a piece position in the current game state. Behavior is undefined for position values greater than 0x3f @param gameState current game state @param pos is the position to zero out: 6-bit var, 3-bit word, high word = row, low word = column. @return newGameState
setPosition
function setPosition(uint256 gameState, uint8 pos, uint8 piece) public pure returns (uint256 newGameState)Sets a piece position in the current game state. Behavior is undefined for position values greater than 0x3f @param gameState current game state @param pos is the position to set the piece: 6-bit var, 3-bit word, high word = row, low word = column. @param piece to set, including color @return newGameState
pieceAtPosition
function pieceAtPosition(uint256 gameState, uint8 pos) public pure returns (uint8)Gets the piece at a given position in the current gameState. Behavior is undefined for position values greater than 0x3f @param gameState current game state @param pos is the position to get the piece: 6-bit var, 3-bit word, high word = row, low word = column. @return piece value including color
ChessFishTournament
https://github.com/Chess-Fish (opens in a new tab)
This contract handles the functionality of creating Round Robbin style tournaments as well as handling the payouts of ERC-20 tokens to tournament winners. This contract creates wagers in the ChessWager smart contract and then reads the result of the created wagers to calculate the number of wins for each user in the tournament.
Tournament
struct Tournament {
uint256 numberOfPlayers;
address[] authed_players;
address[] joined_players;
bool isByInvite;
uint256 numberOfGames;
address token;
uint256 tokenAmount;
uint256 prizePool;
bool isInProgress;
uint256 startTime;
uint256 timeLimit;
bool isComplete;
}PlayerWins
struct PlayerWins {
address player;
uint256 wins;
}protocolFee
uint256 protocolFee7% protocol fee
payoutProfile3
uint256[3] payoutProfile356% 37%
payoutProfile4_9
uint256[4] payoutProfile4_933% 29% 18% 13%
payoutProfile10_25
uint256[7] payoutProfile10_2536.5% 23% 13.5% 10% 5% 2.5% 2.5%
tournamentNonce
uint256 tournamentNonceincrements for each new tournament
tournaments
mapping(uint256 => struct ChessFishTournament.Tournament) tournamentsuint tournamentNonce => Tournament struct
tournamentWagerAddresses
mapping(uint256 => address[]) tournamentWagerAddressesuint tournament nonce => address[] wagerIDs
tournamentWins
mapping(uint256 => mapping(address => uint256)) tournamentWinsuint tournamentID => address player => wins
ChessWagerAddress
address ChessWagerAddressPaymentSplitter
address PaymentSplitterconstructor
constructor(address _chessWager, address _paymentSplitter) publicgetTournamentPlayers
function getTournamentPlayers(uint256 tournamentID) external view returns (address[])Returns players in tournament
getAuthorizedPlayers
function getAuthorizedPlayers(uint256 tournamentID) external view returns (address[])Returns authorized players in tournament
getTournamentWagerAddresses
function getTournamentWagerAddresses(uint256 tournamentID) external view returns (address[])Returns wager addresses in tournament
viewTournamentScore
function viewTournamentScore(uint256 tournamentID) external view returns (address[], uint256[])Calculates score
designed as view only returns addresses[] players returns uint[] scores
getPlayersSortedByWins
function getPlayersSortedByWins(uint256 tournamentID) public view returns (address[])Returns addresses winners sorted by highest wins
isPlayerInTournament
function isPlayerInTournament(uint256 tournamentID, address player) internal view returns (bool)Checks if address is in tournament
isPlayerAuthenticatedInTournament
function isPlayerAuthenticatedInTournament(uint256 tournamentID, address player) internal view returns (bool)createTournament
function createTournament(uint256 numberOfPlayers, uint256 numberOfGames, address token, uint256 tokenAmount, uint256 timeLimit) external returns (uint256)Creates a Tournament
creates a tournament, and increases the global tournament nonce
createTournamentWithSpecificPlayers
function createTournamentWithSpecificPlayers(address[] specificPlayers, uint256 numberOfGames, address token, uint256 tokenAmount, uint256 timeLimit, bool shouldJoin) external returns (uint256)Creates a Tournament with specific players
Creates a tournament, and increases the global tournament nonce
joinTournament
function joinTournament(uint256 tournamentID) externalJoin tournament
Parameters
| Name | Type | Description |
|---|---|---|
| tournamentID | uint256 | the tournamentID of the tournament that the user wants to join |
startTournament
function startTournament(uint256 tournamentID) externalStarts the tournament
minimum number of players = 3 if the number of players is greater than 3 and not equal to the maxNumber of players the tournament can start 1 day after creation
exitTournament
function exitTournament(uint256 tournamentID) externalExit tournament
user can exit if tournament is not in progress
payoutTournament
function payoutTournament(uint256 tournamentID) externalHandle payout of tournament
tallies, gets payout profile, sorts players by wins, handles payout one day must pass after end time for all games in GameWager contract
depositToTournament
function depositToTournament(uint256 tournamentID, uint256 amount) externalUsed to deposit prizes to tournament
IChessFishNFT
awardWinner
function awardWinner(address player, address wagerHash) external returns (uint256)IChessWager
createGameWagerTournamentSingle
function createGameWagerTournamentSingle(address player0, address player1, address wagerToken, uint256 wagerAmount, uint256 numberOfGames, uint256 timeLimit) external returns (address wagerAddress)startWagersInTournament
function startWagersInTournament(address wagerAddress) externalgetWagerStatus
function getWagerStatus(address wagerAddress) external view returns (address, address, uint256, uint256)Token
Test Token with large supply
_initial_supply
uint256 _initial_supplyvalue
uint256 valueconstructor
constructor() publicUSDC
Test Token with large supply
_initial_supply
uint256 _initial_supplyvalue
uint256 valueconstructor
constructor() publicdecimals
function decimals() public pure returns (uint8)_Returns the number of decimals used to get its user representation.
For example, if decimals equals 2, a balance of 505 tokens should
be displayed to a user as 5.05 (505 / 10 ** 2).
Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the default value returned by this function, unless it's overridden.
NOTE: This information is only used for display purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}._
ChessFish
_initial_supply
uint256 _initial_supplyname_
string name_symbol_
string symbol_constructor
constructor(address _owner) publicCrowdSale
deployer
address deployerChessFishToken
address ChessFishTokenUSDC
address USDCvalue
uint256 valueTokensPurchased
event TokensPurchased(address buyer, uint256 amountIn, uint256 amountOut)constructor
constructor(address _owner, address _chessFishToken, address _USDC, uint256 _value) publicdeposit
function deposit(uint256 amount) externalupdateUSDCAddress
function updateUSDCAddress(address _USDC) externalgetChessFishTokens
function getChessFishTokens(uint256 amountIn) externalendCrowdSale
function endCrowdSale() externalwithdraw
function withdraw() externalwithdrawERC20
function withdrawERC20(address token) externalPaymentSplitter
_This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware that the Ether will be split in this way, since it is handled transparently by the contract.
The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim an amount proportional to the percentage of total shares they were assigned. The distribution of shares is set at the time of contract deployment and can't be updated thereafter.
PaymentSplitter follows a pull payment model. This means that payments are not automatically forwarded to the
accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
function.
NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you to run tests before sending real value to this contract._
PayeeAdded
event PayeeAdded(address account, uint256 shares)PaymentReleased
event PaymentReleased(address to, uint256 amount)ERC20PaymentReleased
event ERC20PaymentReleased(contract IERC20 token, address to, uint256 amount)PaymentReceived
event PaymentReceived(address from, uint256 amount)CFSH_token
address CFSH_tokenconstructor
constructor(address _token) public_Creates an instance of PaymentSplitter where each account in payees is assigned the number of shares at
the matching position in the shares array.
All addresses in payees must be non-zero. Both arrays must have the same non-zero length, and there must be no
duplicates in payees._
receive
receive() external payable_The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the reliability of the events, and not the actual splitting of Ether.
To learn more about this see the Solidity documentation for https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback (opens in a new tab) functions]._
totalShares
function totalShares() public view returns (uint256)Getter for the total shares held by payees.
totalReleasedNative
function totalReleasedNative() public view returns (uint256)Getter for the total amount of Ether already released.
totalReleasedERC20
function totalReleasedERC20(contract IERC20 token) public view returns (uint256)Getter for the total amount of token already released. token should be the address of an IERC20
contract.
shares
function shares(address account) public view returns (uint256)Getter for the amount of shares held by an account.
releasedNative
function releasedNative(address account) public view returns (uint256)Getter for the amount of Ether already released to a payee.
releasedERC20
function releasedERC20(contract IERC20 token, address account) public view returns (uint256)Getter for the amount of token tokens already released to a payee. token should be the address of an
IERC20 contract.
releasableNative
function releasableNative(address account) public view returns (uint256)Getter for the amount of payee's releasable Ether.
releasableERC20
function releasableERC20(contract IERC20 token, address account) public view returns (uint256)Getter for the amount of payee's releasable token tokens. token should be the address of an
IERC20 contract.
releaseNative
function releaseNative(address payable account) publicTriggers a transfer to account of the amount of Ether they are owed, according to their percentage of the
total shares and their previous withdrawals.
releaseERC20
function releaseERC20(contract IERC20 token, address account) publicTriggers a transfer to account of the amount of token tokens they are owed, according to their
percentage of the total shares and their previous withdrawals. token must be the address of an IERC20
contract.
TreasuryVester
splitter
address splittercfsh
address cfshrecipient
address recipientvestingAmount
uint256 vestingAmountvestingBegin
uint256 vestingBeginvestingCliff
uint256 vestingCliffvestingEnd
uint256 vestingEndlastUpdate
uint256 lastUpdateconstructor
constructor(address cfsh_, address recipient_, uint256 vestingAmount_, uint256 vestingBegin_, uint256 vestingCliff_, uint256 vestingEnd_) publicsetRecipient
function setRecipient(address recipient_) publicclaim
function claim() publicreleaseDividendsERC20
function releaseDividendsERC20(address token) externalreleaseDividendsNative
function releaseDividendsNative() externalsetSplitterContract
function setSplitterContract(address _splitter) externalICFSH
balanceOf
function balanceOf(address account) external view returns (uint256)transfer
function transfer(address dst, uint256 rawAmount) external returns (bool)IPaymentSplitter
releasableERC20
function releasableERC20(address token, address account) external returns (uint256)releasableNative
function releasableNative(address account) external returns (uint256)releaseERC20
function releaseERC20(address token, address account) externalreleaseNative
function releaseNative(address account) externalChessFishNFT
wagerAddresses
mapping(uint256 => address) wagerAddressesChessWager
address ChessWagerdeployer
address deployeronlyChessFishWager
modifier onlyChessFishWager()onlyDeployer
modifier onlyDeployer()constructor
constructor() publicsetChessFishAddress
function setChessFishAddress(address _chessFish) externalawardWinner
function awardWinner(address player, address wagerAddress) external returns (uint256)