Gas Optimization In Solidity: Strategies For Cost-Effective Smart Contracts
Gas is the “fuel” that powers smart contract execution. This article offers practical strategies for Solidity gas optimization.
🇺🇦 Hacken stands with Ukraine!Learn more
GameFi is one of the newest revelations to come out in the blockchain industry, garnering millions of dollars to develop games that enable the novel play-to-earn model. Some of these blockchain games promise to construct an enjoyable gaming experience, whereby a user will be rewarded for participating in the in-game economy/community. Traditionally, the value of a game lies in the experience, people pay money to spend their time doing something that brings them enjoyment. GameFi lets players monetize their time by allowing them to transfer in-game assets into the real world through cryptocurrencies and non-fungible tokens (NFTs).
Just as the DeFi economy holds dozens of billions of dollars in value, the capitalization of the GameFi sector might soon reach this figure. Axie Infinity – the top blockchain game by volume – saw their native token AXS go from a $200 million market cap to almost $10 billion market cap in less than six months. The industry has also received millions in funding to begin the development of new and improved blockchain games. Major investors like Gala Games together with C2 Ventures launched their venture fund for GameFi for $100 million, as well as Solana Ventures, Forte, and Griffin Gaming Partners also starting a $150 million fund. In 2021 alone, the blockchain games and infrastructure industry received over $4 billion in venture capital (VC) funding.
Not all blockchain games are created equally. Due to the increasing complexity of crypto technology, the development of a GameFi project becomes more difficult as well. Many seasoned experts in the security field are caught off guard, allowing skilled hackers to steal millions from unwitting projects. According to a report from Chainalysis – a leading blockchain analytics firm – total crypto transaction volume grew to $15.8 trillion in 2021, up 567% from 2020’s totals. The illicit transaction volume increased by 79% as well. The theft from DeFi protocols was estimated at about $2.2 billion in 2021 alone – and malicious actors have also started targeting GameFi projects.
As soon as blockchains like Ethereum, Solana, and Avalanche started supporting more complex smart contracts that allowed for the creation of games – which it did in multitudes with more than 400 GameFi tokens across networks – the nascent sector lent tools from different places in the blockchain space to help create the play-to-earn (P2E) model.
P2E games allow players to earn money by participating in the in-game economy, completing daily quests, or moving through game levels. Rewards are paid either in cryptocurrencies or in NFTs that can be traded for Bitcoin or stablecoins like USDT. At the same time, P2E games are mostly free-to-play and only some GameFi projects require users to purchase NFTs or crypto assets before they can play.
Therefore, it’s always important to do your own research (DYOR) and evaluate the risks. If a P2E game requires a big investment to start and the rewards are small, then you are likely to lose your initial investment. Some games in the space are mostly a grind just to reap the rewards, others offer a much more game-like experience.
Many of the tools used to operate the finance part of the GameFi project are derived from the DeFi ecosystem, for example, staking and yield farming. Blockchain games can use a combination of NFTs and tokens for users to monetize their time in-game. For example, RomeDAO a self-proclaimed “APYRPG” has also used NFTs and GameFi mechanics to get to a $40 million valuation with a good $24 million sitting in their treasury. Players can stake their Rome to participate in campaigns that give them an increased APY for adding liquidity and by the end of the campaign, players receive an NFT with specific bonuses.
In the GameFi space, most projects are run by decentralized autonomous organizations (DAOs). Allowing the community to vote and have a say in how a game is run and determine its future are the pillars of a decentralized community. This form of governance also gives projects greater flexibility and is focused on catering for the needs of their users. DAOs are also commonly used to transparently raise and distribute funds for games at the early stages of development.
NFTs are in many cases the bread and butter of GameFi projects, by minting in-game NFTs users get uniquely identifiable assets that can be bought and sold on primary and secondary marketplaces. Many of the assets represented in games are stored as NFTs which makes them an important component of current GameFi.
In the metaverse, NFTs are generally used to designate virtual plots of land that can be sold or staked or myriad other things. Star Atlas is among these projects attempting to make a universe where people would own land, mine minerals, and go on missions to get in-game assets that they can sell on the marketplace. According to CEO Michael Wagner, the aim is to create an entire ecosystem of gamers, entrepreneurs, and people who want to earn money all empowering each other. This would in essence be a metaverse with its own self-sustaining economy. According to a metaverse report by Grayscale, they predict the revenue of up to $1 trillion for the metaverse sector in the future.
GameFi – being one of the most popularly anticipated innovations in crypto – has gained a lot of interest from investors and builders. Due to the worldwide pandemic, many have opted for playing video games to pass the time. This phenomenon has dramatically increased the player base over the last two years, with players spending an estimated $11 billion monthly on mobile apps and games.
As a testament to the growth of the space, as of March 31, 35 blockchains were participating in the GameFi sector, with 1,406 game projects in total according to Footprint Analytics. Trading volume at the end of the month was $129 million, up 154% month-over-month. Astonishingly, two game projects – Par War Online and DeFi Kingdoms – have seen their active users increase by more than 25,000% in the past 30 days.
As an example, Axie Infinity’s token that was launched in mid-November 2020, by June 2021 it was trading at around $12. By the time the market top was reached in November and the total crypto market cap peaked at around $3 trillion, ASX was trading between $130 to $160, a 166% increase in value. This is the best possible outcome for a project where it sustains a massive active community constantly growing the value of the ecosystem. In a report from the Blockchain Gaming Alliance (BGA) in late December, they found that “49% of the blockchain industry’s usage comes from games. More than 1.4 million unique active wallets (UAW) connect daily to blockchain games, making it the most used category ahead of DeFi and other verticals.”
The play to earn model has gained a considerable amount of traction because it allows players to earn a passive income for having fun. According to data from Footprint analytics, in 2022, GameFi invсestments in March were $458 million, +307% compared to February. When looking at investment distribution in GameFi, NFTs and Web3 saw the largest increases.
As the number of GameFi projects increases, the influx of blockchains such as BSC has broken the pace of Ethereum in the GameFi sector, contributing to the continued inflow of funding. Unlike traditional games, P2E games give players control over their assets thereby driving adoption. In some countries like the Philippines, when people lost their jobs due to Covid 19, they could earn money by playing a game, some earning even more than their minimum wage.
On the other side of the coin, there are various risks involved when investing in GameFi projects. According to the Chainalysis Crime Report, hacks in DeFi have increased by 1,330% from 2020. The common denominator in most of the hacks is that they are caused by errors in smart contracts that allow hackers to exploit the protocol and steal funds. GameFi is no different, various games have been exploited in the past and due to the increased complexity of games, we can expect more vulnerabilities to appear.
As with any blockchain project or application, there are various attack vectors hackers can use to infiltrate a system. Most of the crypto projects are in some way related to finance and hackers are continually on the lookout for targets. GameFi is no exception when looking at the millions of dollars in value being moved on daily. Attackers most often target the smart contracts that hold or transfer funds.
Although exceptional progress has been made, there are still considerable security risks for new users as well as developers. Many industry best practices are still under development and security needs are evolving daily alongside the technology. This requires projects to do consistent checking for vulnerabilities to stay at the forefront of security practices.
As mentioned above, the most common vulnerability for any protocol is within the smart contract code governing transactions on the network. Transactions encompass all operations between user and project, all transactions between the project, its pools, and complex multi-signature transactions etc. Each one of these smart contracts needs to be full-proof to save on gas fees and prevent exploitation.
For example, if there was a vulnerability in a smart contract holding staked tokens for users, these funds would be at risk until it’s fixed. Typically contract vulnerabilities are exploited through hidden backdoors, issues with price oracles, excessive admin rights, reentrancy attacks, design vulnerabilities, and various other factors.
When looking at the infrastructure on top of which a GameFi project is built – the technology that provides the fundamental security and consensus for the project – the security conditions need to be excellent. At an infrastructure level, common vulnerabilities are the reasons behind 51% of attacks including DDoS attacks, Sybil attacks, double-spending problems, race attacks, eclipse attacks, routing attacks, replay attacks, and some others.
“Zero-day” refers to something that has recently been discovered, “zero” being the number of days since the vendor of the application or service has known about the threat. These exploits are especially dangerous since only the attacker knows about these flaws. This could lead to the attacker selling information to other malicious actors on darknet markets. These kinds of attacks can be prevented via code audits and bug bounties. Having a recovery plan in place is always a good additional safety measure.
Once the attack is initiated, it becomes a race between exploiters and those who want to secure the system. With new methods of distributing value across the blockchain come new vulnerabilities. Those who create crypto projects should be aware of the risks associated with new technologies.
Scams can be prevented through an increase in user education and enhanced vetting in the space. The anonymous and decentralised ethos of blockchain technology allows anyone to create a project. Thus, it’s very easy for those with right technical skills to create new DeFi tokens and get them listed on exchanges, even without a code audit.
The same goes for NFTs and GameFi projects. One of the most common scams is called a rug pull. This relatively new method usually sees “developers” or fake team members running away with investor funds meant for building the project. Over $2.8 billion was stolen in rug pulls during 2021 alone according to the Chainalysis 2022 Crypto Crime Report.
Scams, where malicious actors get a hold of user’s private keys, are quite common in the realm of illicit crypto activity. According to Chainalysis, from 2019 to 2021, almost 30% of all value stolen was from this type of hack. These scams/hacks are quite prevalent and require users to keep on their toes when navigating web 3.0 with their devices because they can be acquired by phishing, malware, keylogging, social engineering, posing as official applications, and other methods.
Recently it has become more common for hackers to target project’s team members. The reason for this is that members usually hold important access codes for smart contracts and wallets that store user funds. In cases like these, hackers typically try to inject malware and viruses into a team member’s computer via phishing attacks. These attacks can steal critical information like private keys.
Since its inception with Crypto Kitties in 2017, the blockchain gaming industry has seen a few hacks and exploits that have seriously hurt the projects affected. In a game like hacking, a malicious actor will use any entry point such as via the project, or through the user connecting to the project.
The most recent GameFi hack this year also steals the title for the biggest hack on record in the crypto industry. The project is ironically also the biggest one in the space, Axie Infinity. Less than a month ago the blockchain game lost approximately $620 million due to a security breach on the Ronin Network. According to their official blog post, “the attacker found a backdoor through our gas-free RPC node, which they abused to get the signature for the Axie DAO validator.” This allowed the attackers to steal 173,600 Ethereum (ETH) and 25.5 million USDC. This exploit was due to an accidental backdoor left in the code. This case is highlighting the need for consistent code reviews and threat monitoring.
Another well known NFT game – WonderHero – catering mostly for mobile devices, saw 80 million WND or $300,000 worth of its native token minted and sold, sending the token price down 50% as well. According to PeckShield, an independent blockchain security firm, it appeared that the private keys of the game’s main wallet were compromised. The post mortem declared that the attack was conducted via a phishing attack where the attackers got hold of the seed phrase of the main wallet. With the newly obtained information, the attackers managed to get the wallet’s private keys and control all assets in the wallet. Avoiding phishing scams by keeping to best security practices is a good way to stay safe from malware that can affect a user’s wallet.
Early in January 2022, the Beast Masters protocol on Binance Smart Chain (BSC) – an NFT game – had a very successful pre-sale and promised investors a game in the new year. After raising an estimated $500,000, the project’s social channels seemed to have disappeared with all the funds. According to BSC news, many of the signs are pointing to a rug pull even though the project had a website, active social media accounts, and an audit.
There are certain decisions that need to be made regarding the safety of a project and its users to ensure they stay away from exploitation. From a project perspective, it’s critical to constantly monitor threats and review smart contract code for vulnerabilities. Projects that can’t afford an expert cybersecurity team on a full-time basis can use cybersecurity services of other projects to help them stay safe by conducting regular audits. Therefore, the decision not to conduct the audit could cause a project to remain vulnerable. Having all the project funds in a single signature wallet makes it easier for hackers to exploit it as well.
From a user perspective, decisions that lead to exploits can be listed as follows:
In the blockchain cybersecurity space, there are various companies like Hacken.io, PeckShield, and CertiK etc. that specialize in securing blockchain and crypto projects. These companies have various services that can help most projects secure themselves against vulnerabilities. Security as a service is becoming more popular. The smart contract audit can vary dramatically in scale and range from testing one function only to reviewing an entire project.
GameFi projects can get audited by third-party cybersecurity firms. Those analyze all the game’s smart contract code and its functionality, both manually and with the help of software. By getting audited and receiving a certification users will also be more attracted to the platform since they feel safer using it. Besides checking smart contracts, audits can monitor whether governance rules are followed and contain no mechanisms that would allow for the developers to play with investors’ funds. Many users could likely have avoided losing funds to rug pulls if they’d stuck to DeFi projects that have undergone an audit.
Third-party security vendors can also help set up bug bounties. Bug bounties allow freelance white hat hackers to continually probe the system to look for entrances but not to exploit the project. These vendors can also conduct penetration tests as well as common attacks, where most vulnerabilities are targeted to ensure there is no immediate emergency. Generally, a project would conduct an audit before launch and then a follow-up if any things were flagged. The next audit is needed after major changes.
Audits also help new users in the ecosystem discern which projects are secure. Projects that successfully pass the audit get certificates stating that their contracts have been checked and can use this as a proof that they are safe (on a smart contract level at least). Some other audits can go even deeper to the level where team members are doxxed and the entire project is verified as squeaky clean.
The cybersecurity sector may play a catalysing role in the growth of the GameFi and broader crypto industry by securing projects and making sure users can transact safely.