Æternity State Channels: A Peer-to-peer Browser Game

Reading Time: 13 minutes

  •  
  •  
  •  
  • 17
  •  
  •  
    17
    Shares

Original text by David Weil and Hernan Di Pietro

Introduction

Æternity is a promising blockchain platform with great potential for many application scopes. One such great feature is the native support for state channels.

In this article we will explore how we built a peer-to-peer browser game to explore this Æternity capability; along examine related features of the platform such as:

  • ForgAE and companion tools
  • The Sophia functional contract development language

Besides the technical aspects, Æternity has a vibrant, warm and helpful community.

To begin any development for the Æternity blockchain platform, you will need:

  • ForgAE: The framework for creating, deploying and testing AE smart contracts; it also provides the capability of running a local development node and compiler.
  • Aepp SDK: The set of interfaces to access the underlying node APIs. Several SDKs for Javascript, Python, Go and Elixir exist; however, we’ll refer to the Javascript one in this document. This SDK includes a webpack bundle to access the interfaces from the browser = environment.

ForgAE
https://github.com/aeternity/aepp-forgae-js

Aepp SDK (Javascript)
https://github.com/aeternity/aepp-sdk-js

Forum
https://forum.aeternity.com/

ADVICE
To have a better understanding of this guide, you should already grasp a general knowledge of blockchain technology and its associated terms and concepts.

Æternity State Channels

Top blockchain platforms such as Ethereum are known for having scalability problems. Several “Layer 2” solutions are being actively developed with uneven degrees of success, such as Perun, Celer, Raiden, etc. or off-chain generalized schemes such as Plasma. Those projects try to maximize transaction throughput by building off-chain layers on top -and leveraging- the base Ethereum chain qualities and features.

In short, users perform and accumulate state-changing transactions off-chain, reaching mutual agreement by signing the state transitions, and finally settling a final state on the blockchain which comprises all the state transitions done in the channel.

Æternity aims to provide a native implementation of state channels tightly integrated with the base blockchain features. For example, it’s possible to alter or verify state in channels by executing code; that is, Smart Contracts running off-chain, a feature that has been very hard to implement on top of Ethereum.

Complicated usability and no straightforward end-user experience have been some of the issues faced by blockchain projects and developer communities to achieve critical mass. Æternity objective is to also provide a solid platform for building user friendly mobile and web centric Dapps.

What we built

In this document, we will describe a game built upon the following specifications:

  • Typical Reversi rules implementation
  • Peer-to-peer communication through State Channels
  • A Smart Contract that keeps game state (board), performs validation and piece placement
  • Running in browser and featuring 3-D graphics
  • Using local Æternity development node and accounts

Before getting into the details, let’s run the game to see the bigger picture.

How to run the game

Software prerequisites

This guide was tested in Linux (Debian) and MacOS systems. Windows should require similar steps.

  1. Install ForgAE toolchain: npm install -g forgae
  2. Install Docker and Docker Composer. This is needed to run local nodes effortlessly. e.g: If you are running Debian, this will suffice: sudo apt-get install docker.io docker-compose
  3. Try to startup Æternity local nodes within a Docker container. Go to the root of the game project directory, where the docker-compose.yml file is located, and execute the following at your command prompt:forgae node This command will download the proper images for a container running three nodes and a local Sophia compiler right in your system. If your setup goes well, you will see an output indicating the proper funding of the default wallets/accounts included with the ForgAE local nodes:

We are ready to go!

WARNING Online and docker-image provided compiler versions may differ. At the time of this writing, online compiler was version 3.1.0, while docker image served V2.1.0 at port 3080. This must be considered carefully as some breaking changes -for example in supported address formats- were introduced in the transition from 2.X to 3.X compiler versions.

For current compiler versions and change logs, check (https://compiler.aepps.com/)

Æternity recommends to use a local compiler instead of relying upon online-compiler for production environment.

Game Files

The files needed to run the game are located under the aepp folder. They include:

  • aepp-sdk.browser* the Æternity application SDK bundle targeted at browser environments.
  • index.html the main HTML file for the game.
  • reversi-contract.js a Javascript file containing the contract source for compilation within the game (this must mirror contracts/Reversi.aes file in the root directory).
  • reversi-game.js the game code itself.

WARNING If you are going to launch the game from the filesystem directly (without a web server), you are probably going to need a browser extension to support CORS. For example, Firefox users can install CORS Everywhere (https://addons.mozilla.org/es/firefox/addon/cors-everywhere).

Open the index.html file in your browser. You should see the initial screen as follows:

State Channels have two sides; the initiator is the party who opens the channel and deploys the contract code in it. The other peer is called responder.
You may want to open two browser instances side by side to play.

Choose WHITE in one of your browser windows. It will connect to the node, and wait for the other party to join. Choose BLACK in the other window to join the channel.

If your node is responding and the peer-to-peer communication is working,

the WHITE player (the initiator) will compile and deploy the contract in the Smart Channel. This will take a moment. After this, the board will be setup, and game will ask the WHITE player to play. The BLACK player browser instance will wait for the rival to place a disc.

White Plays

From this point, the game will go forward, with both peers exchanging and signing state transitions which represent changes in the game board, until neither player has moves to make. In this moment, the game ends.

With this in perspective, let’s see the details.

State Channel Details

Channel Setup

Game Client and State Channel

In the state Channel both players are equal but there is a practical difference: one must initiate the state channel connection while the other must do its part accepting it, they are called initiator and responder respectively.

Opening the State Channel

Opening a State Channel is quite easy and it can be done in a few steps:

(1) You must open your connection to the Æternity node first. We do this in the setup_node() function:

You’ll notice it requires more information in comparison to what a simple node connection, that is because Universal class groups together multiple functionalities, including both of a node connection and the functionality of an account.

Note that for our example, the parameters indicate URLs of local test node and compilers, and addresses created -and funded- in the ForgAE docker image startup.

(2) In order to successfully create a State Channel, the initiator must first put a certain amount of AE to allow its creation:

(3) With the connection open, you can create the State Channel to your peer. To do this, you must have its public address (see the open_channel function in the game code):

Here signer_func is a function the channel client will use to sign and accept channel updates received from the other endpoint. Here follows a basic definition:

(4) A tag is used to discriminate different messages or state transition types.

Additionally, in the open_channel function we setup an event handler for the State-Channel to be informed about its status:

Deploying and Calling a Contract Inside the State Channel

The contract is, in our case, deployed by the channel initiator, which is incidentally the WHITE player. After that this player will get a deployment address and it will be shared with the other player through a regular State-channel message.

If we have already loaded the contract’s source code into reversi_aes variable we use this function to:

  • Compile contract’s code
  • Encode the initial call to contract’s constructor function init
  • Deploy the contract in the channel we created (for this, we use again the sign-function)
  • Send the obtained address through channel to the opposite endpoint

On the other end, we’ll need the deployed contract address in order to access it, no matter if it is already in the state channel. For that we setup another channel event handler:

Calling Contract Functions

We can perform two different kinds of calls to contract functions: stateless and stateful.

Stateless Function Calls

The simplest case we have is a contract function get_turn which receives no-arguments and returns an integer representing whose player the current turn is:

As we did before with the constructor, we need to encode the call (function name and arguments), using the contract’s source code.
After that, we tell the channel to perform a static contract call. The result will be returned and must be decoded with the right type.

Stateful Function Calls

A stateful call is pretty similar, except that it will result in a transaction which will be sent in the channel.

The only difference to the static-call being the call-function used which will return information containing the round in the channel where the call is made. That must be used later to retrieve the call result, by calling the function channel.getContractCall().

This contract function place_disc(addr: address,row: int, col: int ): int receives one address and two integer arguments that we must pass as a string. The int return value is returned as an integer with values specified in the contract source code.

Game State and Events

At the moment, Æternity SDK has no contract-event implementations. There are some alternatives for this:

  1. Although there are not exactly the same than contract generated events, channels do support custom messages between peers that you can use to let the other end know when change was produced in your side because of your action.
  2. Anytime the contract state is altered as a consecuence of a user interaction, a new state is generated and to be persisted it must first be received by the other user (the one who didn’t generated the change/transaction/call); who must sign it to be accepted and persisted in the channel. This is the approach we chose to keep the contract state synchronized in our application. We achieve this by using a custom signer function which will use custom tags to trigger contract changed events we will use later:

Closing Channel

A final call is required on the channel in order to close it, and make its final state get stored in the blockchain. That is done with this code:

Smart Contract development

Sophia: An Overview

Ethereum is known for introducing the concept of the “world computer”: code deployed on the blockchain, running on a virtual machine across all nodes in form of “smart contracts”, using the concept of “gas” as a medium to pay for computation. Æternity inherits those familiar concepts.
Solidity is the standard imperative language to write smart contracts for the Ethereum platform and the EVM. Æternity offers an alternative approach: program smart contracts using a functional language.

Based on ReasonML, support a typical range of functional features. The rationale for using a functional language is to make automated formal verification proofs easier. This is a critical point in Smart Contract development after many security issues that caused heavy fund losses in the past.

Sophia is a functional language in the ML family. We’ve chosen the functional programming paradigm because it makes it easier to write correct programs — something which is particularly important with smart contracts. The qualities of functional languages which make them (potentially) more reliable than programs written using the imperative paradigm include restricted mutable state, fewer side-effect, easier to read code components, better handling of concurrency, and ease of debugging and testing.

For details, see:

Contract and Game Flow

The Reversi game structure and rules that we implemented are: two players, 8×8 board. Rows and columns are numbered 0 to 7. Each board cell can have the following values: 0 for empty cell, 1 for a cell with a WHITE disc, and 2 for a cell with a BLACK disc.

The initial board is as follows:

The Reversi contract provides the following functions:

  • get_board to get the current board state
  • place_disc to place a players’ disc in the board
  • get_turn to get the current turn (black or white)
  • is_finished to get if the game is finished

(1) The typical sequence of calls in a game are:Contract is deployed in the state channel, initialized with the addresses of white and black players respectively. Initialization also sets up the initial board state and the initial turn to 1 (WHITE moves first).

(2) The game checks for the current turn calling get_turn contract function. Depending on the turn asks the player to wait or play.

(3) The place_disc function is called when the player wants to place a disc in a cell. This is the most complex function in the smart contract.

(3.1) It will check for necessary preconditions such as if the provided coordinate is an empty cell, and scan the cell to check if it will result in a valid move -that is, a move that overthrows the player rival’ pieces on the board.

(3.2) Remember that in Reversi, for each direction from your cell as center, you will overthrow any adjacent rival discs lying on a line, finishing with another piece of your own. For example:

(3.3) If the WHITE player calls the place_disc function with (row 7, col 3) as coordinate, the eight directions from that center will be scanned. Going in the up direction (same column, rows decreasing), we found two BLACK pieces in-line, finished with a WHITE (own) piece in row 3, col 3. This will cause the contract code to alter the board overthrowing pieces BLACK at R4, C3 and R5,C3 and replacing them with WHITE ones. The same will occur in the up-right diagonal direction, where R5, C4 will change to WHITE. The updated board state will be:

(3.4) Scanning is done in recursive form in the internal function scan_discs_to_reverse, that returns a list of cells that the current player will change playing. If this list is zero length, the place_disc function will return an integer code 4 meaning that’s not an available move; otherwise, the reverse_cells and flip_cell functions are called to flip the required discs.

(3.5) Finally, place_disc will switch the turn and return a successful error code (zero).

At this point, the game Javascript client code will update the view and pass the turn to the other player.

(4) At this point, the game Javascript client code will update the view and pass the turn to the other player.

Keep in mind that before each player is allowed to make a move, we check if they do have any movement available from the current board state. If no moves are available to the current player, his turn is passed-on to the rival. If also the rival is out-of-moves, the game is considered finished, in either a draw or a win to the player with the highest count of discs in the board.
Just as a sidenote, we really implemented this in the Sophia smart contract in our first versions of the game, but it was so expensive in terms of gas that it was impossible to do it.

We learned that contract calls in channels are limited to 1 millon of gas units. This puts a definitely quite important limit to the complexity of a single call. At the time of this writing, there is no option to modify gas provision in state channels.

Contract Debugging Tricks

Debugging smart contracts has been always quite complicated due to the immaturity of tools, and the implied transactional model. Even when working on a testnet does not require to waste real funds, development and test cycle is naturally slow.

Common practices in other environments such as placing breakpoints and inspecting state is either unavailable or very limited in the blockchain platform. Ethereum has been the leader so far with the Ganache RPC contract debugger.

For the development of the Reversi smart contract, we devised a simple but effective manner of reporting internal state in form of a “log” of debugging strings.

The contract maintains the following member in the game state:

which is initialized as an empty list:

The aim of this state variable is to keep a debug log which will be returned in abort() calls. A new string can be appended to the log with the function:

For example, a typical call could be:

We modified the require function to abort returning the stored logs:

The conversion from the debug_log of list(string) to a single string is done by the simple list_to_string helper function:

When abort is called triggering an exception, you can decode the error at the calling point with the AE Javascript SDK and checkout the logging information.

Note that storing information is expensive. You will be limited to gas restrictions even in testnet, so use this sparingly.

Function Call Gas Measurement

A contract function call gas cost can be known upfront, if a static call is executed; remind no state updates will occur.

A static call will return an object, if successful, with a field gasUsed. The following is a sample result data from get_turn static call:

Just for comparison, get_board will consume about 1600 units of gas, while place_disc from ~22000 units upwards, depending on the required board scan recursion depth to know the outcome of the players’ move.

Unit Testing

The ForgAE toolset includes unit testing capabilities.

You can check the following links for further information:

– https://dev.aepps.com/tutorials/get-started-with-unit-testing.html

– https://dev.aepps.com/tutorials/how-to-write-unit-test-1.html

In case of our game, the test folder provides a contract testing Javascript file which simulates a game between two players, checking that the game setup, contract deployment and subsequent board state transitions are correct.

To run the tests, ensure you have the Æternity SDK installed. This is the standalone version, not the Webpack bundled for the browser. Ensure by running

on the root directory.

Once you get aepp-sdk@3.4.0 installed, you can run the test suite by executing:

This will deploy the Reversi contract against the docker image nodes and start 18 tests including contract deployment, and several exchanges (game moves) between the two parties. Note that this is a contract functionality test, it does not use the State channel infrastructure.

You should see an output similar to:

For each piece call, the correct turn and board state are checked according to the game rules.

The test suite included does not reach the end-of-game board state but you can play by adding subsequent tests if you want, or by adding different kind of them.


  •  
  •  
  •  
  • 17
  •  
  •  
    17
    Shares