Building on a Subnet solution by Ava Labs

codelink

CodeLink

Posted on September 12, 2023

Building on a Subnet solution by Ava Labs

šŸ˜” Background & Problem Statement

In the ever-evolving world of blockchain technology, Avalanche has emerged as a prominent L1 player, driving innovation and pushing the boundaries of what's possible with the introduction of Subnets: Avalancheā€™s answer to the blockchain trilemma. This design, based on horizontal scaling, paves the way for avant-garde applications of blockchain.

With Avalanche Subnets, developers can craft bespoke blockchains tailored to their distinct requirements. Whether a gaming application or a decentralized finance system (DeFi), Avalanche Subnets promise enhancements in performance, cost efficiency, user experience, and security.

Last fall, our team at Codelink embarked on an ambitious endeavor: creating a multiplayer game demo using Avalanche's groundbreaking Subnet technology. Venturing into the uncharted waters of pioneering tech is seldom a smooth sail.

After months of painstaking development and troubleshooting, it became evident that many of our hurdles stemmed from a significant gap in infrastructure tooling. Our perseverance paid off, and we eventually managed to successfully release the game demo. In our quest for solutions, we joined hands with Kurtosis. Their expertise became instrumental as we refined and de-complicated the Avalanche Subnet setup, affirming our belief that there had to be a more streamlined approach to this technology.

By integrating Kurtosis' solution into the Avalanche Subnet framework, we slashed the intricacy of the subnet initiation ā€” for instance, trimming down a 440-line instruction to just 300. We believe Kurtosis can be used as a valuable tool to lower the barriers of adoption for Avalanche subnets & blockchain gaming and hope to share our learnings from the experience in this short blog post.

šŸ”ØSolution

In this blog post, we share how our team at CodeLink uses Kurtosis, an open-source developer tool, to spin up an Avalanche subnet locally, run a virtual machine binary (e.g., subnet-evm), and deploy a sample game onto it. Using Kurtosis is quicker and simpler than using a Hardhat environment or the Fuji testnet. But donā€™t take our word for it; read on and see for yourself.

Table of contents:

  • How to use Kurtosis to spin up a local Avalanche subnet
  • How to set up & play the multiplayer game
  • Conclusion & Takeaways

āž° Shortcut

For those who wish to dive straight into the code, the source code behind the demo game can be found here. Simply follow the README instructions for getting it all set up. We offer a few ways to deploy the game, including on a local Hardhat environment or the Fuji testnet. Still, we encourage folks to use Kurtosis because of the incredibly short time it takes to get started. The package (i.e., the environment definition) written by Kurtosis is found here, which gives anyone a reproducible and portable way to spin up an Avalanche subnet of any size or configuration, either locally or in the cloud.

šŸš¢ How to use Kurtosis to deploy a local Avalanche subnet

Kurtosis authored the Avalanche package, which is a portable and parameterized environment definition meant to give developers a reliable and highly customizable way to spin up an Avalanche subnet for their development, prototyping, and testing needs. This package is meant to help get builders started faster by abstracting away the complexities of setting up the subnet so that developers can focus on building their virtual machine logic and their decentralized applications on top of the subnet.

Kurtosis is used by Codelink for quick and trivial local deployment of the game for testing and development. There are only 3 steps to deploy everything!

  1. Install the prerequisite tools: Make sure you have Docker installed & started on your machine, then install Kurtosis. For MacOS, run the below (other installation methods can be found here).
# Install Kurtosis
brew install kurtosis-tech/tap/kurtosis-cli
Enter fullscreen mode Exit fullscreen mode

You can check that youā€™ve installed Kurtosis properly by running the following, which will return both the CLI and the Kurtosis Engine versions.

kurtosis version
Enter fullscreen mode Exit fullscreen mode

2. Download the game & deployment logic

git clone git@github.com:CodeLinkIO/MoveAndWhap.git && cd MoveAndWhap
Enter fullscreen mode Exit fullscreen mode

3. Spin up the subnet

kurtosis run . '{"ephemeral_ports": true,"node_count": 1}' --enclave mnw
Enter fullscreen mode Exit fullscreen mode

Boom! That is it! You now have a local Avalanche subnet running with subnet-evm! The above command is instructing Kurtosis to use the environment definition to spin up a single Avalanche node with the container prots mapped automatically to ephemeral ports on your machine. Weā€™ve also specified that we want our ā€œenclaveā€ or environment to be named ā€œmnwā€.

You should see the following get returned:

Starlark code successfully run. No output was returned.
INFO[2023-08-17T15:01:43+01:00] ============================================
INFO[2023-08-17T15:01:43+01:00] ||          Created enclave: mnw          ||
INFO[2023-08-17T15:01:43+01:00] ============================================
Name:            mnw
UUID:            583e4e0c0daa
Status:          RUNNING
Creation Time:   Thu, 17 Aug 2023 14:59:09 BST

========================================= Files Artifacts =========================================
UUID           Name
20aae956fac7   billowing-leaf
d0e7b55f8f61   cool-flower
00eba7025c76   crisp-rose
3e4d09dee2cd   crisp-wave
337b870bc927   dry-fossil
59bd6b490b65   weathered-pumpkin

========================================== User Services ==========================================
UUID           Name      Ports                                  Status
ecb9f4fced3c   builder   <none>                                 RUNNING
b9ec063e96b2   node-0    rpc: 9650/tcp -> 127.0.0.1:57308       RUNNING
                         staking: 9651/tcp -> 127.0.0.1:57309
Enter fullscreen mode Exit fullscreen mode

As you can see above in the example output, Kurtosis has spun up a single Avalanche (non-staking) node with the subnet-evm binary and exposes an RPC port for you to connect to. In this case, it is 127.0.0.1:57308.

Wait, so was that it?

Yes! The command above in Step 3 is actually telling Kurtosis to run this main.star file, which is an environment definition that takes care of spinning up an Avalanche validator node from scratch and runs the VM binary (weā€™re using subnet-evm by default, but any VM can be used). Itā€™s written in Starlark, a dialect of Python, and is meant to gracefully handle dynamic dependency passing and careful sequencing of steps that are often required for blockchain set up and configurations.

Next, letā€™s check out how to play the game and showcase how the blockchain can revolutionize the gaming industry.

šŸŽÆ How to set up & play the multiplayer game on an Avalanche subnet

The game demo built by Codelink is a multiplayer game where all user actions get recorded on-chain. This game was originally developed to accomplish two things: (1) to help developers understand how to program a Web3 game on an EVM chain and (2) to get our hands dirty with cutting-edge tech and to see what was possible.

A more thorough description of the game mechanics is here, but essentially, itā€™s like a naval search-and-destroy game where players can move around the ocean and attack other players for points. Any number of players can join and, as explained earlier, every move gets recorded on-chain.

1. Obtain the full RPC URL from the locally deployed Avalanche subnet. In your terminal, you should be able to scroll up to see the Starlark output. This output object will return a few fields, with the chain-rpc-url being one of them.

Starlark code successfully run. Output was:
{
    "allocations": "8db97c7cece249c2b98bdc0226cc4c2a57bf52fc=0xd3c21bcecceda1000000",
    "chain genesis id": "13123",
    "chain id": "2E4dXs9pQYT4rZNtdUXn7AQ1RLLx8RmppD4pHBeVSp1Gz45FyR",
    "chain-rpc-url": "http://172.16.2.6:9650/ext/bc/2E4dXs9pQYT4rZNtdUXn7AQ1RLLx8RmppD4pHBeVSp1Gz45FyR/rpc",
    "rpc-urls": [
        "http://172.16.2.6:9650",
        "http://172.16.2.7:9650",
        "http://172.16.2.8:9650",
        "http://172.16.2.4:9650",
        "http://172.16.2.5:9650"
    ],
    "subnet id": "2aPkmYuVqCBMGnyDBUsKExmD6SZa7JSH8sw8ekcsQ41nTj2qrp",
    "validator ids": [
        "29LFE6XeaPWKXRTJLLZZArQHoHtajEoejG8uGMiER6ryemkTyq",
        "UsnnLv3Mhyj1HhcknTF52ayqjgR65zBx1sLMcJgzZRjpuuLvR",
        "2mA5R4DPvUJu55Gvz1AHSyvEwarCQnqmUoVLYoupt5pKz6MqC2",
        "2rduTdenpScvJC8e393KohQGwm3yZnaJ8a5v1ezS6n9Fmhz7xB",
        "jB1nnGBdZrMbuS2D4NSjrXTwphLJASyRNq3Rp2JyVJF6VRswg"
    ],
    "vm id": "tGBrM7iZGgNZvqPiwD9oD716rVRR9PiB6BFuG3ot3SP54ie8K"
Enter fullscreen mode Exit fullscreen mode

2. Connect your wallet to the local Avalanche subnet using Metamask: To interact with the game, we need a wallet to be connected, just like any other decentralized application on the blockchain. In this tutorial, weā€™re going to use Metamask as an example.

To connect your wallet, simply follow the instructions here from Metamask, under the ā€œAdding a network manuallyā€ section with the following data:

Once everything is entered, make sure you click ā€œsaveā€ and switch to the ā€œmaw networkā€ using the Metamask UI!

3. Get some test tokens to play the game with. Using Metamask, follow these instructions, under the ā€œImporting using a private keyā€ section with the following data:

  • Private key string: 56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027

Youā€™ve now imported the address 0x8db97c7cece249c2b98bdc0226cc4c2a57bf52fc with 1,000,000 MAW tokens for use in the game!

4. Deploy the game contracts & start playing! To do this, run these 3 commands separately from the home directory of MoveAndWhap:

#Python
$ npm run deploy:local_subnet # This deploys the game's smart contracts to the subnet
$ npm run server # This starts the game server
$ npm run ai # This adds a few bots in the game to play with
$ yarn start # This starts the frontend
Enter fullscreen mode Exit fullscreen mode

That is it! You have now configured all you need to start playing a multiplayer game on a local Avalanche subnet! As mentioned earlier, all moves are recorded on-chain so each time that is done, a transaction must be signed via a wallet interaction via Metamask. With ERC4337 though, session keys should enable a more seamless experience for a user down the road.

Diagram - Move-and-Whap

šŸƒ Conclusion & takeaways

Subnets are Avalancheā€™s answer to the scalability portion of the blockchain trilemma, allowing for near-infinite horizontal scaling by giving institutions the ability to create their own instances of blockchains with rules and configurations specific to their needs. This means performance, cost, data sovereignty/isolation, and UX can all be calibrated for the game or DeFi application being built!

In this blog post, we shared our experiences from designing & building a sample game on an Avalanche subnet and how Kurtosis was able to play a key role in reducing the complexities and overhead of setting up an Avalanche subnet for local development & deployment of our game.

Our goal with this project was to shed light on how developers can take advantage of Avalanche subnets to pave the way for more builders in the future & to help on-board the next billion users onto web3. If you or your organization are considering building on a subnet, we at codelink.io would love to help you get started!

About Codelink

CodeLink is an exceptional powerhouse in the blockchain industry, known for their groundbreaking contributions to projects like CryptoKitties and NBA Topshot - both of which have garnered immense popularity. Their expertise in cutting-edge technologies such as blockchain development & other technologies sets them apart as innovative trailblazers, continuously pushing the boundaries of what's possible in Web3. With their unwavering commitment to overcoming challenges and their relentless pursuit of innovation, CodeLink is revolutionizing the blockchain landscape with their extraordinary creations.

To learn how CodeLink can partner with your team to deliver high-quality releases and get you to market sooner, contact us via ideas@codelink.io

About Kurtosis

Kurtosis is an open-source build system for web3 test environments that gracefully handles dynamic dependency passing and sequential set up logic - both of which are often required for bootstrapping complex L1 infrastructure. Environment definitions written using Kurtosis are completely reproducible, portable, and work at any scale (as only limited by the underlying hardware) to empower engineers to test functionalities or scales that they couldnā€™t before. Spend less time building custom testing harnesses and frameworks - try Kurtosis today by getting in touch with us at hello@kurtosistech.com.

About Avalanche subnets

Subnets are Avalancheā€™s answer to the scaling portion of the blockchain trilemma. They are a unique scaling solution that enables institutions of any size to use distributed ledger technology for their applications, whether it be for gaming or for a DeFi use case. Subnets are powerful because they allow anyone to establish their own sovereign blockchain and control the levers. This includes being able to fine-tune application-specific requirements (compute, speed, etc.), data provenance and privacy, and validator sovereignty.

You can read more about Subnets here in Avalancheā€™s docs.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
codelink
CodeLink

Posted on September 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related