Aduiting Smart Contracts: Best Practices & Pitfalls
Smart contract auditing is crucial to ensure the safety and reliability of decentralized applications on blockchain platforms. As smart contracts are self-executing agreements that hold and manage digital assets, any vulnerability left undetected could lead to significant financial losses, reputational damage, and diminished user confidence. Auditing involves a thorough examination of the smart contract code, identifying potential security risks, and performance bottlenecks.
However, what are the best practices and pitfalls related to smart contract auditing and security, and how does NEAR Protocol’s design enhance smart contract security compared to other Layer1s?
On July 7th, Octopus Network co-hosted a Twitter Space with BlockSec and invited industry experts from the NEAR ecosystem to discuss this topic. Here are the key insights from the discussion.
- Auditing is crucial for security, but it does not guarantee 100% safety. Therefore, it is important to remain humble, recognize “unknown unknowns”, and have a bug bounty program that is transparent and rewards white-hat hackers.
- To ensure long-term security, it is crucial to practice full lifecycle security, which includes four key phases: design, implementation, quality control, and operation. Of these phases, the design and operation phases are the most important. Simplicity in design is the best way to keep the system safe because security risks increase exponentially with system complexity.
- Rust’s design is type-safe, memory-safe, and free of all kinds of undefined behaviors, making it a very reliable language for smart contracts.
- NEAR Protocol’s unique features, including the named and memorable account model, asynchronous cross-contract calls, well-designed NEAR Rust SDK, and DAO-owned smart contract upgradability, enable developers to develop quickly and easily while making attacks harder to execute.
- Auditing NEAR projects takes more time than some Solidity projects. First, Rust is a more complex language. Secondly, certain features of the NEAR Protocol, such as its asynchronous nature, require auditors to invest more time in educating developers. Furthermore, auditing NEAR projects involves monitoring updates and versioning of various Rust SDKs.
Check out the following excerpts to learn more, or you can listen to the audio recording on Spotify.
Vivi: What is the biggest mistake that entrepreneurs or projects make when undergoing smart contract auditing? What are the pitfalls that the audience can learn from and avoid?
Claudio Cossio — Co-Founder, Meta Pool
To start, it’s important to be humble — even if it’s not related to security. Even though you’ve built all the infrastructure behind your protocol and know it inside and out, sometimes bringing in somebody with fresh eyes can raise questions around the design of the smart contract and the way that you deliver products on-chain. When the auditing team or peer reviewers give feedback, it’s important to understand their intentions and build a long-term relationship with them. Keep in mind that they may miss some issues, so take their feedback with a grain of salt and try to see it from their perspective.
Secondly, understand that there will be unknown unknowns. Security is often referred to as a black art, and in web3, where everything is being alpha and beta tested, you can never be 100% secure. There’s always a weakest link, so try to understand where possible attack vectors may occur. Most importantly, understand that the key is to safeguard your users’ assets. You cannot be just adding new pieces of code to the smart contract, you have to be a little bit more strict on your development cycles.
Lastly, make sure you have a bug bounty program. It’s important for people to come forward if they find something that is not working correctly and give your team and auditing partners a chance to look into it. Together, you can collaborate on a solution.
So, in summary, be humble, recognize unknown unknowns, and have a bug bounty program that is transparent and rewarding to white-hat hackers.
Louis Liu — Founder, Octopus Network
For any computational system, security is not just about securing every part of the system, but also maintaining security over time. Therefore, it is essential to practice full lifecycle security. There are four major phases for a blockchain or smart contract system: design, implementation, quality control, and operation. It is vital to emphasize the importance of the design and operation phases. Design determines the highest level of security, and in this phase, we can sacrifice some functionality in exchange for simplicity. Simplicity is the best way to keep the system safe because security risks increase exponentially with system complexity. In terms of operation, many hacks result from simple and avoidable mistakes. Maintenance requires a strictly applied process for any changes made to the smart contracts. As the devil is always in the details, we must carefully consider the operational phase.
Robert Yan — Developer, NEAR Protocol
For those who are new to the crypto space or developing products on web 2.0, it’s important to prioritize a security-first mindset when building smart contracts. Unlike traditional developers who may focus on business logic or even tokenomics, those building smart contracts need to prioritize security from the beginning. It’s critical to be aware of vulnerabilities such as DDoS attacks, reentrancy or oracle manipulation attacks, and other issues that can arise from poor contract design or functions. For example, we have the Skyward Finance incident last year, which is actually not a very sophisticated issue. The incident could have been prevented if the programmer had asked for someone to audit it and ensure its security. Therefore, it’s crucial for developers to be conscious of security and to seek auditing. This should be a top priority for those just starting in the industry.
Matthew Jiang — Director of Security Service, BlockSec
As an auditing firm, I believe that the biggest pitfall for the Web3 project is rushing the auditing process, especially during a bull market. Proper management of the product schedule is crucial, and sufficient time should be allowed for a thorough audit, as the quality of the audit is the most important factor.
The second issue is that some companies select auditing firms based solely on price. They ask for quotations and choose the cheapest option. In my opinion, it may be more appropriate to select based on their experiences in these ecosystems and their auditing methodology, rather than solely focusing on price.
The third thing is that there are so many unknowns. Audit cannot address all the issues. We need to guarantee security across the whole lifecycle of the product.
Vivi: How does using Rust for smart contract development on NEAR address common vulnerabilities? So, for example, how does NEAR’s design enhance smart contract security compared to other Layer1s?
Robert Yan — Developer, NEAR Protocol
Let’s start by talking about Rust, which is a fantastic language and has been one of the most popular languages according to StackOverflow surveys in the past six or seven years. Rust is a beautiful and powerful language that is widely used for system programming, including operating systems, databases and blockchains. It is also a solid language for smart contracts, especially because its first instinct is safety. Its design is typesafe, memory safe, and free of all kinds of undefined behaviors, making it a very reliable language for smart contracts. In addition, Rust has a very powerful tool chain that includes various coding and optimization tools, as well as debugging and code coverage for testing your product. However, Rust is not easy to learn, and its learning curve is a bit steep. This is a good thing, as it results in better engineering skills and practices. Developers who use Rust generally have a good background and foundational skills, resulting in fewer mistakes compared to other languages. Additionally, Rust is less prone to attacks than other languages. In fact, there are fewer attacks in the Rust space, not only in NEAR Protocol but also in other blockchains that use Rust as a smart contract language. This is because less attackers know well about Rust, and it is harder for attackers to understand the code and find issues in Rust. Overall, Rust is an excellent language for smart contract development, and its popularity continues to grow due to its safety and reliability.
Regarding NEAR, we have done a lot of design to make the development experience extremely easy and efficient. This allows for the creation of world-class projects with ease. In regards to security, the first thing to mention is that NEAR uses a very flexible and powerful account model with named and memorable accounts. This is in contrast to other blockchains where you never know what a contract is just by looking at the contract address hash. With NEAR, it is very easy to recognize what the contract is, making users harder to be phished.
Additionally, NEAR has the sharding design which requires an asynchronous cross-contract call , which although can be a bit challenging to implement, makes attacking the system harder. This is because we need to understand how it works and use callbacks to make sure the state remains consistent, and especially when doing some error handling to revert some states. But the asynchronous cross-contract call also makes attack vectors like flashloan attack in other blockchains not possible on NEAR.
The third is we have a well-designed NEAR Rust SDK. I think it is one of the best Rust smart contracts in comparison to other blockchains. It makes experimentation easy, is good for building a quality product, and we have standardized serialization and deserialization of binaries using the Bosch standard we have designed, which is both powerful and efficient. We have many other building blocks as well, such as a well-tested contract standard for FT & NFT, and NEP standards and upgrades. It is very helpful for developers to get started and write the codes in just a few lines.
Lastly, I would like to mention that we have a DAO-owned remote contract upgrade process, which is quite interesting because upgrading in Solidity can be challenging to some extent. However, with NEAR, every contract is designed to be upgradable. We can use the DAO to control the upgradeability of this contract, and perform various upgrades quickly and safely.
Claudio Cossio — Co-Founder, Meta Pool
One of the main reasons we decided to build on NEAR was the ability to run smart contracts on the DAO, which was designed that way. This was particularly important for Lucia, our technical co-founder and the mastermind behind the design of our liquid staking derivatives platform. It’s crucial for the smart contract of liquid staking to be non-custodial, meaning that the user always has control of their assets. This is by design, and it was a key feature when we launched almost two years ago. Even if the smart contract were hacked, the user’s assets would not be compromised, and they could undertake the necessary actions themselves. We would provide the mechanisms for them to do so. While upgradability has its pros and cons, building a DAO on top of a smart contract on NEAR makes it harder for attackers to gain control of the liquid staking smart contract. This is a result of building on a Rust-based blockchain that allows for smart contract upgradability without requiring a fork of the smart contract or a SS snapshot. We have done four upgrades to the smart contract without any issues, thanks to the Rust-based tech stack that we rely on, which doesn’t compromise users’ funds.
In terms of security, we partnered with BlockSec, one of our security audit partners, because they have worked with the NEAR core team and Ref Finance, one of our DeFi partners on NEAR. This was an important factor for us, given that it’s not trivial to understand the ecosystem. Lucia, one of the top 10 developers on NEAR, is involved in the details of audits and the audit pace. We agree with Matthew’s statement that we should not rush into mainnet because we are putting valuable projects or smart contracts in place that users will trust with their NEAR, OCT, or META tokens. It is important for development to take the time to mature into a DApp that can withstand being on mainnet and being scrutinized by bad actors.
In terms of the tech stack, an attacker would need sophisticated technology to attack a smart contract on NEAR, making it a non-trivial task. If the smart contract is not developed properly, low-hanging fruit attack vectors may be open. Therefore, it is critical to have a technical co-founder, like Lucia, who is thorough in the development process of building on NEAR.
Louis Liu — Founder, Octopus Network
When envisioning the architecture of the Octopus network, we sought to build a multichain network around an existing, flourishing DeFi-intensive public blockchain, rather than a minimized hub or relay. This allows the appchain to leverage and compose with DeFi protocols from day one. Instead of implementing the hub or relay in the form of a dedicated layer one blockchain, we do it in the form of a set of smart contracts. Fortunately, thanks to the powerfulness of the NEAR SDK and Rust language, we accomplished this goal in a relatively short period of time. The first version of the Octopus network went live within a year, with shared security and interoperability. The first version consisted of 7000 lines of code, which I think is one of the most complex NEAR smart contracts at that time, but still two orders of magnitude less than Polkadot relay or Cosmos hub. This makes it very powerful. Thanks to the security auditing of professional auditing partners like Halborn, BlockSec, the Octopus network has gone through these two years without any security accidents happening.
We are heading towards the 2.0 network and expect there to be many more assets since we utilize NEAR restaking. The shared security providing side will boom, and we will build bridges between the NEAR and Cosmos ecosystems so that assets will go beyond pure Octopus appchains. This has dramatically increased the security pressure, but I think that by utilizing the experience gained in the past two to three years and with the help of our partners, such as BlockSec, and by sharing experiences within the ecosystem, we can overcome this challenge. Overall, I have faith in our upcoming Octopus 2.0 based on all the factors I mentioned.
Vivi: How is auditing for NEAR projects different from auditing for smart contracts in other languages and ecosystems?
Matthew Jiang — Director of Security Service, BlockSec
The first difference between Rust and Solidity comes from the language itself. Rust is completely different from Solidity and is more difficult to audit as it is more complex. Due to the rich capabilities of Rust, different developers can have rather different code styles even for the same functionality.
Another difference comes from the specific features of the NEAR Protocol. NEAR introduced many great features that do not exist in Ethereum. For example, due to the asynchronous feature of NEAR, developers need to add callback functions to ensure that you handle the rollback of the status properly. Many developers who recently joined the NEAR ecosystem may not understand this feature, so we need to spend a lot of time and effort in education. Especially when the project is rather complex, even experienced developers may miss this point.
Another point that differentiates Rust from Solidity is that Rust provides many SDKs, some maintained by NEAR and some by third parties. Different from solidity, most of the contract code is written from scratch in Ethereum, even if open source libraries provide some of that, developers need to write their own code for most parts. When writing a smart contract in NEAR, these SDKs can always be imported. In this case, we have to go through all the updates of this maintenance to ensure that we are on the same page and that users are using the correct version of the packages.
Vivi: What are the challenges when you’re auditing for projects like Octopus Network and Meta Pool? What are the biggest rewards you think that those teams get from the auditing by your team? Could you give us some specifics and share some stories?
Matthew Jiang — Director of Security Service, BlockSec
The challenges have been mentioned in the previous question. Actually, the audit of Octopus 2.0 is still undergoing. Meanwhile, we are also auditing the Meta Pool and a very critical issue is located. This is just due to the asynchronous feature of NEAR Protocol. If you are in Ethereum and there are some requirements that don’t meet, the whole state will be reverted. In NEAR, it does not and it further results in the issue. With BlockSec’s help, the potential critical issues that may drain the pool can be mitigated.
Follow Octopus Network!
- Website: https://oct.network/
- Twitter: https://twitter.com/oct_network
- Accelerator Program: https://accelerator.oct.network/
- Medium: https://medium.com/oct-network
- Discord: https://discord.gg/6GTJBkZA9Q
- Telegram: https://t.me/octopusnetwork
- Youtube:https://youtube.com/channel/UCkMYDmXdgjCBTBggSEAy0ZQ
- Github: https://github.com/octopus-network
- Docs: https://docs.oct.network/