How somebody determined to place a whole chess sport on-chain

Right this moment, we’ll be reviewing the sensible contract behind the first-ever on-chain chess engine. It’s known as 5/9 (fiveoutofnine). The creator simply decided: screw it, I’m gonna put a whole chess sport on-chain. And it’s not simply the AI for taking part in the sport, he additionally put the artwork (NFTs) completely on-chain.
There are a lot of examples of placing numerous issues on-chain, equivalent to SVG information and 3D information of NFTs. Even the SVG and 3D renderers as effectively. I’m at all times fascinated by these. It jogs my memory of the 90s when computing assets had been scarce and folks got here up with numerous tips/optimizations to assist the sport on sluggish {hardware}. The identical is going on with blockchains the place each single efficiency and gasoline bit is squeezed out for max efficiency.
Let’s dive into the optimizations that 5/9 needed to make to be able to run chess on Ethereum. Right here is the define of this text:
- Sport dynamics — what’s it about?
- The sensible contract supply code
- On-chain information illustration
- Producing NFTs
- Sport engine
- The sport consists of you (participant) taking part in towards the AI that’s programmed into the sensible contract. The AI at all times performs black.
- You can also make a transfer, and the engine will reply with its personal transfer. Making a transfer requires gasoline, however you get an NFT in return.

- All of the video games and strikes are recorded on the blockchain. There are 59 video games max and 59 strikes per sport max.
- There is only one sport being performed at a time. Anybody could make the subsequent transfer and the sport will proceed.
- Every thing’s on-chain: the engine, the NFT information, and the picture (within the type of HTML)
- There’s an fascinating adaption to NFT/web3 world: Every transfer (and the corresponding counter transfer by the AI) can be minted as an NFT:


There are 4 sensible contracts:
Chess.sol
— for information illustration. How the chessboard, chess items, and strikes are represented on-chain.Engine.sol
— the AI that may make strikes, seize items, and many othersfiveoutofnine.sol
— ERC-721 implementation permitting to mint strikesfiveoutofnineART.sol
— helper utilized by the above contract for producing the metadata and pictures for NFTs
The supply code could be discovered on the 5/9 website or on Etherscan.
The creator additionally translated the primary 2 sensible contracts (information illustration and the engine) to Python for simpler readability and understanding. You may’t run them on the blockchain, however logically they’re equal to the precise Solidity contracts. Verify them out on Github.
Now let’s break down the contracts one after the other.
Chess.sol
defines the information constructions for the chessboard, items, and strikes. A bit is represented utilizing 4 bits:
Board illustration is a bit more difficult. The complete board suits right into a 256-bit integer (8×8 board=64 cells at 4 bit for each bit → 64*4=256). You entry the cells within the board utilizing bit shifts and bit masks:(board >> (27 << 2)) & 0xF
is similar as board[27]
if board was only a flat array.
Why is the precise board6x6
quite than8x8
? As a result of we have to maintain the outermost rows and columns empty for environment friendly computation of whether or not a transfer is inside the board bounds (isValid
operate)
Additionally, the bit on the underside proper nook of the board represents whose flip it’s to maneuver:
The strikes are represented compactly in 12 bits.
The strikes usually are not saved one-by-one as a result of there is no such thing as a environment friendly information construction for storing 12 bits in Solidity. As an alternative, 21 strikes are packed right into a single 256-bit integer (21*12=252<256). The sport assumes that there are 105 strikes max per sport:

The append
operate provides a transfer to MovesArray
:

The remainder of the Chess.sol
contract are simply helper features that permit you to do issues like/manipulate board, apply strikes, and many others. Listed below are all these features (I skipped implementation of a few of them for brevity):
The Chess.sol
contract is used as a library for uint256
and movesArray
in order that the helper features (rotate
, applyMove
, and many others) are hooked up to uint256
and movesArray
:
This lets you do issues like:
Let’s transfer on to the subsequent contracts:
fiveoutofnine.sol
— implementation of the ERC-721 customary.fiveoutofnineART.sol
— a set of helper features for producing the NFT artwork — known as byfiveoutofnine.sol
.
Right here is the annotated fiveoutofnine.sol
:

The contract above retains observe of the sport index, transfer index, all of the strikes which have been made, exterior and inner token ids, and many others. It calls the Engine.sol
contract (the sport AI) to seek for one of the best counter transfer.
Every transfer (which really consists of white’s and black’s strikes) has a token id and could be minted as an NFT. The artwork for the NFT is generated within the _tokenURI
operate which itself calls the getMetadata
operate of fiveoutofnineART.sol
.

getMetadata
manually constructs the HTML for the NFT picture. As you’d anticipate, there are many if statements and strings concatenations to generate the HTML and its inline CSS. This gist has a shortened model of this code.
getMetadata
additionally manually creates the JSON for the attributes of the NFT. The attributes are:
- identify: string within the format “Sport #X, Transfer #Y”
- description: proven within the picture under

- bit border, colour technology, dimension, hole, and peak: defined under

Listed below are some footage with numerous attributes from the OpenSea page:

Now, onto the final contract: Engine.sol
. This contract has the searchMove
operate that’s utilized by fiveoutofnine.sol
to make a counter transfer.
I gained’t get into the small print of this contract as a result of it has a lot of chess-specific algorithms. However the high-level technique is obvious from the above code snippet: generated all potential strikes, consider every transfer in line with some heuristic, and choose one of the best transfer.
This can be a fairly cool undertaking demonstrating what’s potential on blockchains. The writer put a fantastic effort into gasoline optimization by bit-packing every little thing as effectively as potential. That is so hardcore and jogs my memory of C. Sure, it makes the code arduous to learn, however you save a lot gasoline with one of these code. (It prices round 0.06ETH to mint a transfer=$175 as of now. Fairly good for such a posh contract).
The writer additionally made the sport 100% trustless: that means nobody, not even the writer can change the logic of the sport. There isn’t a improve mechanism or something like that. Sure, it resulted in bugs which might be can’t be mounted now, however it’s 100% trustless.
The undertaking additionally has very cool-looking artwork/NFT for every transfer, permitting you to personal a chunk of chess historical past.
And probably the most fascinating half is that every one of this was performed by a school scholar. This was their means of studying Solidity. The undertaking already impressed others (MateInEight) to construct on prime of 5/9.