BLOGPOST
Cosmos Blog Header
3327 Logo

Made with love️ for blockchain community by humans from MVP Workshop

Contact us at

[email protected]

All Rights reserved 2022 c 3327

Ticking All the Boxes: How Madara Modifications Enable On-Chain Game Logic

Introduction

One of the main lessons from the previous two years is that the blockchain gaming space is expanding rapidly, with many new projects and features being built. However, it still remains in its infancy stage, as no title has managed to grab the mainstream market. I’m not talking about metaverse and virtual reality on the blockchain, though it is a massive part of the gaming space. I’m talking about a core gameplay experience that entirely runs on-chain. Most games require a certain amount of trade-offs, where the game incorporates transactions for interaction between users and with the game itself, but the logic is mainly run off-chain on Web2 architecture. This is because games require a lot of computing power, which can quickly become expensive if it ran entirely on-chain.

But what if we could move certain parts of the game logic on-chain, such as the movement of non-playable characters or weather changes? This would be a step in the right direction, and that is exactly what we aimed to achieve with ticking functionality, a transaction invoked by the protocol at the start of each new block and guaranteed to be processed with top priority. And this is how the Ticking Madara project came to be.

Ticking Madara is a modified version of the Madara sequencer for Starknet which implements ticking functionality. This project was inspired by Ticking Optimism, a similar project which achieved the same end result for the Optimism rollup chain, and it was utilized in the implementation of Conway’s Game of Life called Ticking Conway, a community-driven on-chain interactive game. The benefit of ticking functionality is integrating it into an app chain and invoking the app logic entirely on-chain. This logic can be expanded as needed, and as long as the dedicated sender address has enough funds to cover the fees for invoking the tick function, it will be processed as the first transaction in every block.

Understanding the Project

But first, we need to answer some basic questions: what are Starknet and Madara? And how do they fit together? Let’s first dispel any misconceptions about these projects.

Starknet is a Zero-knowledge rollup solution Layer 2 network on Ethereum. It uses ZK rollups and STARK proofs for highly secure and efficient scaling of the Ethereum network with a throughput of one million transactions per second. Other Starknet benefits include:

  • utilization of Web2 security mechanisms (such as fingerprints and facial recognition),
  • account abstraction, meaning user accounts and smart contracts are a unified type, and thus a lot of cool features can be introduced into applications, like not being required to sign every transaction with the user's private keys, enabling multi-signatures and social recovery.

The programming language of the network is Cairo, which is continuously evolving. A major upgrade from version 0 to version 1 consequently meant a shift from a Python environment to a Rust environment. Cairo is a general-purpose language, meaning it’s not strictly tied to smart contract development.

Starknet is composed of several different components, which all play a distinct role in running the entire network. These components are:

  • Sequencers - receive, batch, and execute transactions,
  • Provers - validate work of sequencers, generate proofs of correctness for sequencer processes,
  • Nodes - network auditors, state maintenance.

In the picture below, you can see the high-level overview of the Starknet architecture.

In order to implement ticking functionality, we needed to modify the order of transactions and make sure tick transactions were included in every block, which means our focus turned to the sequencer, specifically Madara.

Madara is a decentralized Starknet sequencer on Substrate. In other words, they serve as the entry point for transactions into the Starknet system. The sequencer is crucial in enabling efficient and scalable transaction processing on the Starknet network. Under the hood, Madara uses Cairo VM and Blockifier to execute, order and validate the transactions. As Madara is a Substrate project, we were able to customize the Starknet pallet to our own needs.

By adding ticking functionality on Madara, we enabled the execution of various game elements (e.g., movement of non-playable characters, weather changes, etc.) completely on-chain with no external computation.

Getting Involved in the Community

One of the best elements of working on this project is joining a vibrant community of developers for the Madara and Starknet ecosystem. Participating in these groups helped us immensely by pointing out various intricacies of the sequencer code, which contributed to our ability to solve problems promptly and efficiently.

We got in touch with the ecosystem lead as well. The meeting with Louis Guthmann showed us great possibilities and opportunities for building in the Starknet ecosystem. Developers are empowered and encouraged to bring forth project ideas for the ecosystem, and in turn, the developers would receive support from the leadership to realize these ideas into fully-fledged applications.

Starknet and Madara are very well-documented projects, especially given the pace of development and evolution of the whole ecosystem. There are plenty of developers working hard to make sure that project documentation is well-organized and up-to-date.

Making the Modification

After gaining a deeper understanding of the inner workings of Starknet and Madara, it was time to plan how we would execute the modification to achieve this functionality. This section will focus primarily on code and concrete implementation, so if you’re not interested in this topic, feel free to skip this section.

First, we will inspect the code before any modifications are made. The entire runtime logic is defined in the Starknet pallet. The on_finalize runtime hook is called at the end of each block, creating a new Starknet block. The Substrate block is automatically saved, and we wrap the Starknet block to Substrate. With the mapping from the Substrate block hash to the Starknet block hash. The BlockifierStateAdapter is used when executing transactions to directly manage Substrate storage (read & write into it).

Our main changes to the Starknet pallet are:

  • Adding the “invoke_tick” function, which calls the tick function on the smart contract,
  • Modified existing “invoke” function by moving and separating out the logic for executing transactions into a separate function. This was done in order to be able to invoke this piece of functionality in each new block,
  • Added the “set_tick_tx” function for creating and signing the transaction, making it ready for execution,
  • Added the aforementioned “execute_tx” which takes one transaction as a parameter and invokes it on the Starknet blockchain,
  • Added constant variables for reuse throughout implementation.

We have implemented ticking functionality as an optional feature, meaning you can still run Madara Sequencer without it. The app takes in a command line option –tick to enable it.

In the screenshot below, you can see a high-level overview of runtime logic with ticking functionality.

All of our code is available on our GitHub repository, and Ticking Madara is also available as a Docker image on Docker Hub.

Testing

In order to test the ticking functionality, we needed to ensure that the ticking transaction was invoked in each new block. But what exactly does this ticking transaction do?

As this is mainly a Proof-of-concept with plenty of room for improvement, we have kept the ticking contract simple. When the tick function is invoked, it increments an unsigned integer counter by one and emits an event that tick has occurred. That counter variable is stored in the smart contract storage. On average, a new block was created in six seconds, meaning the tick function should also be invoked every six seconds.

Smart contracts were written in both version 0 and version 1 of the Cairo language. In order to alleviate some of the difficulties of writing, compiling, and deploying contracts, we used Protostar, a toolchain for Starknet smart contract development. It is similar to what Hardhat does for Ethereum developers.

We used the “artillery” framework to simulate various types of on-chain activity, such as transfers of both fungible and non-fungible tokens, and the invocation of the ticking contract indirectly through a proxy contract and the ticking transaction.

Upon test completion, we successfully verified that the ticking transaction was successfully invoked in each block, and it also received top priority by being the first transaction processed in every block. The logs below show that in the current block (36), the tick is successfully invoked and processed first.

2023-07-26 22:24:00 [36] & Successfully execute tick tx
2023-07-26 22:24:00 [36] * Successfully invoke tick and initialize block
2023-07-26 22:24:00 [36] # Welcome to store block
2023-07-26 22:24:00 - Prepared block for proposing at 36 (17 ms) [hash: 0x8d482bb3f4f7f4a10fb41c606402ebaa30f279c1455376e2c44923c870d38;
parent_hash: Oxb581...26a9; extrinsics (2)

2023-07-26 22:24:00 Pre-sealed block for proposal at 36. Hash now 0xc94ef50951620958a08a93155051aec0711d5251102b8913f292ab093b8b45,
previously 0x8d4e82bb3f4f7f4a10fb41c60e6402ebaa30f279c1455376e2c44923c870d38.

2023-07-26 22:24:00 * Imported #36 (0x94e...8b45)
2023-07-26 22:24:00 [36] < Running offchain worker at block 36.
2023-07-26 22:24:00 [36] # No last known Ethereum block number found. Skipping execution of L1 messages.
2023-07-26 22:24:01 27 Idle (0 peers), best: #36 (0xc94 ...8b45), finalized #34 (0x6ca3...6b4),

Next Steps

Going forward, the plan is to incorporate the Kakarot zkEVM, another Starknet side project, for running the game logic written in Solidity alongside Ticking Madara. Moreover, the ticking functionality could introduce an element of randomness to the game, making it a unique experience that continuously evolves and keeps the players interested and engaged for an extended period of time.

As things stand currently, we are using the Madara test account to sign and invoke the tick transaction at each block. If that account runs out of gas, the ticking transaction will not occur. One way to mitigate this is to add several accounts (think of them as gas tanks), which can invoke the transaction if the previous one runs out of ETH. Tick would be invoked on a daily basis 14,400 times (since Madara stores a block every six seconds), which needs to be multiplied by the gas cost of the tick transaction. With this calculation, projects can plan accordingly and for the long term. We are exploring integration possibilities with Braavos and/or Argent X wallets. Currently, these wallets haven’t been integrated with Madara, and Ticking Madara uses a Madara test account to cover the fees as a result. However, further development in this area would allow users (and projects) to use their wallets for tick transaction fee payments.

Conclusion

This is not the end of the road by any means, and it’s only the beginning. We believe the blockchain gaming space will move in the direction of more on-chain computation, less relying on Web2 architecture, and becoming more app chain driven, where games will have their separate blockchains connected to a general-purpose blockchain network. We look forward to the future and the possibility of games incorporating ticking functionality into their products.

It has been a true pleasure working on this solution on Madara Sequencer. We explored the Starknet ecosystem and Substrate framework in depth, and wrote smart contracts in multiple versions of Cairo, but most importantly, we came in contact with many talented and passionate developers and participants of various projects in Starknet. We will monitor the future development of Madara closely.

For more information on Starknet, Madara, or any other Starknet-related project, please visit the official Starknet website, their GitHub repository, and join their online communities to build, discuss and engage with other participants.

If you’d like to work on a project which feels alive, has the technology which pushes the boundaries of Web3, and has a vibrant and open community, then Starknet is a place for you.

Acknowledgments

Special thanks to Louis Guthmann for a warm welcome to the Starknet ecosystem, Abdel Hamid Bakhta, and other members of the Madara Telegram group for pleasant interactions and answering all questions we had during development.

SHARE

COMMENTS (0)

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

You may also find this interesting:

How Lens helps us build user-centric Web3 products?

In our previous blog post, we covered one of the biggest challenges Web3 faces: building user (de)centric products. The main points were: One of the ways to solve this challenge is to start with the validation and exploration of the problems users have rather than a tech solution that can be developed. We want to […]

By Milos Novitovic
December 15, 2022
Deep Dive DeFi: Derivatives

Derivatives DeFi has been an emerging market for the past three years in the Web3 world. Protocols have tried to bridge the gap and bring traditional financial instruments to the Web3world, offering users decentralization, full custody, and favorable conditions to make their own choices with minimum intermediation.  So far, we (Web3 users) have been successful […]

By Andrija Raicevic
December 8, 2022
ML meets Blockchain: The Clash of Buzzwords

Blockchain technology and ZK proofs may be the last missing puzzle pieces for creating trustless and secure decentralized machine learning networks. This complex symphony of technologies opens the door for accessing knowledge from private databases, such as hospitals or government databases, without leaking information while still providing verifiable models and predictions.  Intro Machine learning has […]

By Aleksandar Veljkovic
December 1, 2022
Layer Hack: zkSync’s Account Abstraction

About Layer Hack Encode Club hosted a great hackathon focused on Layer 2 scaling solutions - Layer Hack. The hackathon lasted for nearly a month (Oct. 17 - Nov. 13), and was sponsored by AltLayer, Boba Network, Metis, and zkSync - each sponsor had their track with its own topic.  Out of those four tracks, […]

By Milos Bojinovic
November 24, 2022
Let’s geek out together!
Would you love to work with us on Web3-related experiments and studies?
Drop us a message