Smart Contracts
Smart Contract API

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) gameWagers

address wager => GameWager

wagerPrizes

mapping(address => uint256) wagerPrizes

address wager => WagerPrize

games

mapping(address => mapping(uint256 => struct ChessWager.Game)) games

address wager => gameID => Game

gameIDs

mapping(address => uint256[]) gameIDs

address wager => gameIDs

wagerStatus

mapping(address => struct ChessWager.WagerStatus) wagerStatus

address wager => Player Wins

userGames

mapping(address => address[]) userGames

player can see game challenges

allWagers

address[] allWagers

address[] wagers

ChessFishToken

address ChessFishToken

CFSH Token Address

DividendSplitter

address DividendSplitter

Dividend Splitter contract

ChessFishNFT

address ChessFishNFT

ChessFish Winner NFT contract

gaslessGame

contract GaslessGame gaslessGame

Gasless Game Helper Contract

constructor

constructor(address moveVerificationAddress, address _GaslessGame, address _DividendSplitter, address _ChessFishNFT) public

createGameWagerEvent

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

NameTypeDescription
wagerAddressaddressThe address of the wager for which the status is being requested.

Return Values

NameTypeDescription
[0]addressplayer0 The address of the first player in the wager.
[1]addressplayer1 The address of the second player in the wager.
[2]uint256winsPlayer0 The number of wins recorded for player0.
[3]uint256winsPlayer1 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

NameTypeDescription
[0]int256timeRemainingPlayer0
[1]int256timeRemainingPlayer1

getPlayerMove

function getPlayerMove(address wagerAddress) public view returns (address)

Gets the address of the player whose turn it is

Parameters

NameTypeDescription
wagerAddressaddressaddress of the wager

Return Values

NameTypeDescription
[0]addressplayerAddress

isPlayerWhite

function isPlayerWhite(address wagerAddress, address player) public view returns (bool)

Returns boolean if player is white or not

Parameters

NameTypeDescription
wagerAddressaddressaddress of the wager
playeraddressaddress player

Return Values

NameTypeDescription
[0]boolisPlayerWhite

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

NameTypeDescription
wagerAddressaddressaddress of the wager

Return Values

NameTypeDescription
[0]uint8outcome,
[1]uint256gameState
[2]uint32player0State
[3]uint32player1State

getChainId

function getChainId() internal view returns (uint256)

Returns chainId

used for ensuring unique hash independent of chain

Return Values

NameTypeDescription
[0]uint256chainId

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

NameTypeDescription
[0]addresswagerAddress

verifyGameUpdateState

function verifyGameUpdateState(bytes[] message, bytes[] signature) external returns (bool)

Verifies game moves and updates the state of the wager

Return Values

NameTypeDescription
[0]boolisEndGame

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

NameTypeDescription
[0]boolisEndGame

TournamentHandler

address TournamentHandler

onlyTournament

modifier onlyTournament()

addTournamentHandler

function addTournamentHandler(address _tournamentHandler) external

Adds Tournament contract

startWagersInTournament

function startWagersInTournament(address wagerAddress) external

Starts 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

NameTypeDescription
wagerAddressaddresscreated 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) external

Player1 calls if they accept challenge

playMove

function playMove(address wagerAddress, uint16 move) external returns (bool)

Plays move on the board

Return Values

NameTypeDescription
[0]boolbool 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) external

mint tournament winner NFT

cancelWager

function cancelWager(address wagerAddress) external

Cancel 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

NameTypeDescription
[0]boolwasUpdated 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

NameTypeDescription
[0]boolwasUpdated returns true if status was updated

depositToWager

function depositToWager(address wagerAddress, uint256 amount) external

Deposits 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:

  1. 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.

  2. 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 moveVerification

MoveVerification contract

chessWager

contract ChessWager chessWager

deployer

address deployer

address deployer

MOVE_METHOD_HASH

bytes32 MOVE_METHOD_HASH

EIP-712 typed move signature

DELEGATION_METHOD_HASH

bytes32 DELEGATION_METHOD_HASH

EIP-712 typed delegation signature

onlyDeployer

modifier onlyDeployer()

constructor

constructor(address moveVerificationAddress) public

setChessWager

function setChessWager(address _chessWager) external

set 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 view

typed 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 view

Check if delegators match players in wagerAddress

checkDelegations

function checkDelegations(struct GaslessGame.SignedDelegation signedDelegation0, struct GaslessGame.SignedDelegation signedDelegation1) internal view

Check delegations

verifyDelegation

function verifyDelegation(struct GaslessGame.SignedDelegation signedDelegation) internal view

typed 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) pieces

coordinates

mapping(string => uint256) coordinates

algebraic chess notation string => uint (0-63)

squareToCoordinate

mapping(uint256 => string) squareToCoordinate

deployer

address deployer

address deployer

moveVerification

contract MoveVerification moveVerification

MoveVerification contract

protocolFee

uint256 protocolFee

5% fee to token holders

OnlyDeployer

modifier OnlyDeployer()

initCoordinates

function initCoordinates(string[64] coordinate, uint256[64] value) external

called from ts since hardcoding the mapping makes the contract too large

initPieces

function initPieces() internal

Initialize 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

NameTypeDescription
pieceuint8is the number of the piece

Return Values

NameTypeDescription
[0]stringstring 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

NameTypeDescription
moveuint16is the move to convert

Return Values

NameTypeDescription
[0]uint8fromPos 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

NameTypeDescription
fromPosuint8is the position to move a piece from.
toPosuint8is the position to move a piece to.

Return Values

NameTypeDescription
[0]uint16move

moveToHex

function moveToHex(string move) external view returns (uint16 hexMove)

Converts an algebraic chess notation string move to uint16 format

Parameters

NameTypeDescription
movestringis the move to convert i.e. e2e4 to hex move

Return Values

NameTypeDescription
hexMoveuint16is 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

NameTypeDescription
hexMoveuint16is the move to convert to string

Return Values

NameTypeDescription
movestringis 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

NameTypeDescription
gameStateuint256is the uint256 game state of the board

Return Values

NameTypeDescription
[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_const

pawn_const

uint8 pawn_const

bishop_const

uint8 bishop_const

knight_const

uint8 knight_const

rook_const

uint8 rook_const

queen_const

uint8 queen_const

king_const

uint8 king_const

type_mask_const

uint8 type_mask_const

color_const

uint8 color_const

piece_bit_size

uint8 piece_bit_size

piece_pos_shift_bit

uint8 piece_pos_shift_bit

en_passant_const

uint32 en_passant_const

king_pos_mask

uint32 king_pos_mask

king_pos_zero_mask

uint32 king_pos_zero_mask

king_pos_bit

uint16 king_pos_bit

rook_king_side_move_mask

uint32 rook_king_side_move_mask

For 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_bit

rook_queen_side_move_mask

uint32 rook_queen_side_move_mask

rook_queen_side_move_bit

uint16 rook_queen_side_move_bit

king_move_mask

uint32 king_move_mask

pieces_left_bit

uint16 pieces_left_bit

king_white_start_pos

uint8 king_white_start_pos

king_black_start_pos

uint8 king_black_start_pos

pos_move_mask

uint16 pos_move_mask

request_draw_const

uint16 request_draw_const

accept_draw_const

uint16 accept_draw_const

resign_const

uint16 resign_const

inconclusive_outcome

uint8 inconclusive_outcome

draw_outcome

uint8 draw_outcome

white_win_outcome

uint8 white_win_outcome

black_win_outcome

uint8 black_win_outcome

game_state_start

uint256 game_state_start

full_long_word_mask

uint256 full_long_word_mask

invalid_move_constant

uint256 invalid_move_constant

initial_white_state

uint32 initial_white_state

Initial 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_state

Initial 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 protocolFee

7% protocol fee

payoutProfile3

uint256[3] payoutProfile3

56% 37%

payoutProfile4_9

uint256[4] payoutProfile4_9

33% 29% 18% 13%

payoutProfile10_25

uint256[7] payoutProfile10_25

36.5% 23% 13.5% 10% 5% 2.5% 2.5%

tournamentNonce

uint256 tournamentNonce

increments for each new tournament

tournaments

mapping(uint256 => struct ChessFishTournament.Tournament) tournaments

uint tournamentNonce => Tournament struct

tournamentWagerAddresses

mapping(uint256 => address[]) tournamentWagerAddresses

uint tournament nonce => address[] wagerIDs

tournamentWins

mapping(uint256 => mapping(address => uint256)) tournamentWins

uint tournamentID => address player => wins

ChessWagerAddress

address ChessWagerAddress

PaymentSplitter

address PaymentSplitter

constructor

constructor(address _chessWager, address _paymentSplitter) public

getTournamentPlayers

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) external

Join tournament

Parameters

NameTypeDescription
tournamentIDuint256the tournamentID of the tournament that the user wants to join

startTournament

function startTournament(uint256 tournamentID) external

Starts 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) external

Exit tournament

user can exit if tournament is not in progress

payoutTournament

function payoutTournament(uint256 tournamentID) external

Handle 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) external

Used 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) external

getWagerStatus

function getWagerStatus(address wagerAddress) external view returns (address, address, uint256, uint256)

Token

Test Token with large supply

_initial_supply

uint256 _initial_supply

value

uint256 value

constructor

constructor() public

USDC

Test Token with large supply

_initial_supply

uint256 _initial_supply

value

uint256 value

constructor

constructor() public

decimals

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_supply

name_

string name_

symbol_

string symbol_

constructor

constructor(address _owner) public

CrowdSale

deployer

address deployer

ChessFishToken

address ChessFishToken

USDC

address USDC

value

uint256 value

TokensPurchased

event TokensPurchased(address buyer, uint256 amountIn, uint256 amountOut)

constructor

constructor(address _owner, address _chessFishToken, address _USDC, uint256 _value) public

deposit

function deposit(uint256 amount) external

updateUSDCAddress

function updateUSDCAddress(address _USDC) external

getChessFishTokens

function getChessFishTokens(uint256 amountIn) external

endCrowdSale

function endCrowdSale() external

withdraw

function withdraw() external

withdrawERC20

function withdrawERC20(address token) external

PaymentSplitter

_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_token

constructor

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) public

Triggers 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) public

Triggers 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 splitter

cfsh

address cfsh

recipient

address recipient

vestingAmount

uint256 vestingAmount

vestingBegin

uint256 vestingBegin

vestingCliff

uint256 vestingCliff

vestingEnd

uint256 vestingEnd

lastUpdate

uint256 lastUpdate

constructor

constructor(address cfsh_, address recipient_, uint256 vestingAmount_, uint256 vestingBegin_, uint256 vestingCliff_, uint256 vestingEnd_) public

setRecipient

function setRecipient(address recipient_) public

claim

function claim() public

releaseDividendsERC20

function releaseDividendsERC20(address token) external

releaseDividendsNative

function releaseDividendsNative() external

setSplitterContract

function setSplitterContract(address _splitter) external

ICFSH

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) external

releaseNative

function releaseNative(address account) external

ChessFishNFT

wagerAddresses

mapping(uint256 => address) wagerAddresses

ChessWager

address ChessWager

deployer

address deployer

onlyChessFishWager

modifier onlyChessFishWager()

onlyDeployer

modifier onlyDeployer()

constructor

constructor() public

setChessFishAddress

function setChessFishAddress(address _chessFish) external

awardWinner

function awardWinner(address player, address wagerAddress) external returns (uint256)