Good contract safety is changing into an more and more necessary facet of Web3 growth. Not solely when writing good contracts but additionally when listening to blockchain occasions as decentralized purposes (dapps) depend on correct on-chain knowledge. As you may already know, the best solution to monitor good contract occasions is by establishing a Moralis Web3 stream. So, how do you shield your streams from malicious actors? Nicely, the best means to take action is with a webhook safety operate:
const verifySignature = (req, secret) => { const providedSignature = req.headers["x-signature"] if(!providedSignature) throw new Error("Signature not offered") const generatedSignature= web3.utils.sha3(JSON.stringify(req.physique)+secret) if(generatedSignature !== providedSignature) throw new Error("Invalid Signature") }
Including the snippet above to your Web3 streams ensures that solely Moralis can ship submit requests to your webhook URLs. Because of this, you may be assured that the information offered by the streams is correct and related!
Take a look at the webhook safety documentation web page for extra info on how this works. Additionally, keep in mind to enroll with Moralis if you wish to create your personal Web3 streams. Creating an account is free and solely takes a few seconds!

Overview
Right this moment’s article will cowl the ins and outs of good contract safety. In doing so, this information begins by exploring a number of the widespread safety points in good contracts. From there, we dive straight into greatest practices for good contract safety. Following this, we’ll briefly cowl some outstanding good contract safety instruments. Lastly, to prime issues off, we’ll take a better take a look at how one can safe your Moralis Web3 streams!
Within the article’s final two sections, you’ll familiarize your self with the Moralis Streams API. That is one among many blockchain growth assets supplied by Moralis. Together with a number of enterprise-grade Web3 APIs, Moralis additionally options superb blockchain growth content material on the Web3 weblog. As an example, study Notify API options, tips on how to import OpenZeppelin contracts in Remix, or sort out our Chainlink NFT tutorial!
Additionally, do you know you possibly can entry all Moralis options totally free? All you must do is join with Moralis and instantly leverage these Web3 growth assets!
Methods to Make Good Contracts Extra Safe
Because the Web3 business grows, good contract safety is changing into an more and more necessary facet of blockchain growth. Malicious actors wish to exploit this new business and are in search of flaws in good contract code for private acquire. Because of this, we’ll take a better take a look at good contract safety!

Since Ethereum is probably the most important blockchain for Web3 growth, we’ll concentrate on Ethereum safety greatest practices. Fortuitously, a lot of the ideas on this article apply to good contract growth normally.
However, to know why we’d like these Ethereum safety greatest practices within the first place, the preliminary part will take a better take a look at the foundation of the issue. As such, allow us to kickstart this information by exploring a number of the widespread good contract safety points!
Are There Safety Points in Good Contracts?
Good contract know-how is the spine of the Web3 business, enabling a better diploma of flexibility and innovation. Sadly, the benefits of good contracts are double-edged, because it additionally presents alternatives for bad-faith actors to use vulnerabilities.

The immutability facet of public blockchain networks, like Ethereum, additional complicates the good contract safety situation. As soon as a developer deploys a contract, altering its code to cope with safety flaws is extremely difficult. What’s extra, belongings and funds stolen from good contracts are subsequent to not possible to recuperate. That is one other opposed impact of the varied networks’ immutability traits.
Regardless that conflicting figures are circulating, it’s estimated that the full worth of stolen belongings or losses on account of insufficient good contract safety far exceeds the $1 billion mark. This can be a results of DAO hacks, pockets hacks, frozen wallets, and many others.
The problems above are just a few examples of why builders want to speculate assets towards constructing strong, resilient, and safe good contracts. Good contract safety should be prioritized and regarded an important job for all Web3 builders. Because of this, we’ll take the next second to discover greatest practices for good contract safety!
Greatest Practices for Good Contract Safety
Good contract know-how has and can proceed to rework numerous sectors of the financial system worldwide. This contains industries reminiscent of finance, governance, the web of issues (IoT), and lots of extra. Additionally, because the utilization of good contract know-how continues to develop, it’s changing into more and more necessary to think about good contract safety.

So, what precisely is sensible contract safety? To adequately reply this query, the next sub-sections will discover three elementary greatest practices all builders ought to make use of!
Good Contract Audits
In 2023, builders want to think about good contract safety when growing dapps and different Web3 platforms. Sadly, builders are nonetheless ignoring this and are launching unaudited contracts on numerous blockchain networks.

Hiring a sensible contract auditor prices cash and is probably going, not low cost. Nonetheless, it’s doable to detect flaws by way of an intensive auditing course of, which might save assets down the road. As an example, tens of millions in DeFi have disappeared in hacks that exploited weaknesses in poorly written good contract code.
Good good contract safety auditors observe protocols and confirmed auditing processes to search out flaws in a sensible contract’s code. In doing so, they will spot errors that go unnoticed throughout growth. In some situations, auditors can even assist enhance code by advising on optimizing and fixing good contracts earlier than committing them to the blockchain.
Rigorous Testing
Moreover incessantly performing good contract audits, one other a part of the Ethereum safety greatest practices offered on this tutorial is rigorous testing. When constructing good contracts, you must check your code repeatedly to search out vulnerabilities and bugs.

Repeatedly testing your code is the simplest and simplest way to make sure your contracts carry out as supposed. One risk is to make use of testnets for the varied present blockchain networks to attempt them in an actual setting. Listed here are a number of examples:
- Goerli
- Sepolia
- Mumbai
- The Solana testnet
If you wish to make the most of these networks, you want testnet tokens; to get these, you want taps. The Moralis testnet faucet web page gives a listing of the very best taps for a number of networks. On that web page, you should use the Mumbai faucet to get free MATIC, the Goerli faucet to get Goerli ETH, the Solana faucet to get testnet SOL, or use the Fantom testnet faucet, for instance!
Add Fail-Protected Safety
When growing Ethereum good contracts, you will need to at all times contemplate the danger of failure. As such, a great rule of thumb is to be ready for as many situations as doable. Nonetheless, regardless of the quantity of testing, it’s not possible to cowl all bugs in good contract code. Consequently, part of Ethereum safety greatest practices is implementing fail-safe mechanisms.

Fail-safe mechanisms can restrict the injury of malicious assaults. They’re designed to set off each time one thing irregular occurs inside a sensible contract. Some examples may be:
- Pace Bumps – Pace bumps don’t forestall assaults however decelerate malicious actors, giving admins sufficient time to take motion.
- Circuit Breakers – Circuit breakers forestall the execution of strategies and capabilities when vulnerabilities and bugs are detected.
- Steadiness Limits – Steadiness limits prohibit the full quantity of tokens that may be locked in a contract.
- Charge Limits – Charge limits management how incessantly a operate may be known as inside a given timeframe.
Good Contract Safety Instruments
When writing good contract code, you too can use good contract safety instruments to assist your endeavors. Down beneath, you’ll find three outstanding examples of good contract safety instruments:
- Mythril – This can be a good contract safety instrument developed by ConsenSys. Mythril helps establish good contract vulnerabilities in Ethereum Digital Machine (EVM) byte code.

- Octopus – Octopus is a great contract analytical instrument used to deeply perceive the interior conduct of a contract’s byte code.
- Oyente – That is an audit instrument for figuring out widespread safety vulnerabilities in good contracts. Oyente consists of a validator, explorer, CGF builder, and CoreAnalysis instrument.
Combining the instruments above with good contract safety greatest practices will enable you construct – not solely resilient Ethereum good contracts – however strong good contracts normally!
Moralis Streams for Good Contract Builders
As you now know, constructing strong, resilient, and safe good contracts is an important a part of blockchain programming. As soon as deployed, one other central facet of Web3 growth is to watch good contract occasions!
All good contracts typically emit occasions each time one thing of significance occurs inside them. This will, as an illustration, be a switch occasion each time a token is exchanged. As you possibly can think about, listening to and monitoring these occasions play an necessary position in creating extra compelling person experiences. So, how do you go about listening to good contract occasions?

The best solution to monitor good contracts is with the Moralis Web3 Streams API! With this interface, you possibly can stream knowledge straight into the backend of your initiatives by way of Moralis webhooks. For instance, you possibly can arrange a Web3 stream to watch an Ethereum deal with, get webhooks when an asset is distributed, acquired, staked, and many others., or some other good contract occasion fires based mostly in your filters!
To arrange your personal Web3 stream, all you must do is observe these 5 steps:
- Present an deal with
- Arrange filters and select when to obtain webhooks
- Choose the chain(s) you wish to monitor
- Add a webhook URL
- Obtain webhooks based mostly in your filters
Monitoring good contract occasions doesn’t should be tougher than that when working with Moralis. In case you are additional involved in creating streams, try the official documentation web page to create a stream!
Sadly, even listening to and monitoring a sensible contract can pose safety dangers. Thus, within the coming part, let’s discover safety greatest practices for Moralis and Web3 streams!
Ethereum Safety Greatest Practices and Moralis Streams
When establishing a brand new Web3 stream with Moralis, you must present a webhook URL. That is the placement the place Moralis sends JSON responses by submit requests. Sadly, as these webhook URLs are public and are available from exterior the Moralis ecosystem, they will pose a safety threat if not dealt with accurately!
With out correct countermeasures, anybody with entry to your webhook URL can ship a submit request. Because of this, malicious actors can ship faux JSON responses mimicking the occasions you’re monitoring. So, how do you keep away from this? To reply this query, allow us to begin by trying nearer at an instance.
In preparation for this tutorial, we arrange a Web3 stream listening to Ethereum switch occasions with an quantity better than $50,000. Should you have no idea tips on how to create a stream your self, try the official create a stream utilizing the online UI documentation web page earlier than persevering with.
Subsequent, as soon as we arrange a stream, we join it to an easy JavaScript parameter that listens to all of the submit requests despatched to our webhook URL. Here’s what the JavaScript code appears like:
const specific = require("specific"); const app = specific(); const port = 3000; app.use(specific.json()); app.submit("/webhook", (req, res) => { const webhook = req.physique; console.log(webhook); return res.standing(200).json(); }); app.pay attention(port, () => { console.log(`Listening to streams`); });
Within the instance above, nothing prevents a malicious actor from sending faux JSON responses by submit requests. Let’s check out what which may seem like. Within the picture beneath, we use the Postman platform to ship a submit request to an ngrok-generated webhook URL:

Because of this, we must always get a response containing the ”worth”, ”to”, and ”from” variables as parameters:
{ worth: '500000000000' from: '0x79d11Bc...' to: '0xF73d13DaB...' }
As you possibly can think about, this turns into problematic and poses a safety threat in case your dapps depend on this info. So, how do you forestall this?
Including Webhook Safety
To make sure that all submit requests originate from Moralis, you possibly can add this easy webhook safety operate:
const verifySignature = (req, secret) => { const providedSignature = req.headers["x-signature"] if(!providedSignature) throw new Error("Signature not offered") const generatedSignature= web3.utils.sha3(JSON.stringify(req.physique)+secret) if(generatedSignature !== providedSignature) throw new Error("Invalid Signature") }
The operate above takes two arguments: the request itself and your Moralis API key. As soon as executed, the operate initially verifies that the submit request accommodates an ”x-signature”. From there, it takes the request physique and your API key to generate a signature utilizing the ”web3” bundle. Lastly, it compares the newly generated signature with the offered signature, guaranteeing they match.
For this to work with the code from the earlier part, you additionally must make a number of configurations. First, let’s import the ”web3” and ”dotenv” libraries on the prime of the file:
const dotenv = require("dotenv"); const web3 = require("web3");
Subsequent, you must add your Moralis API key as a variable. Displaying the hot button is a safety threat, which is why you need to create a ”.env” file and add the important thing as an setting variable. To get the important thing, join with Moralis, log in to the admin panel, and click on on the Web3 APIs tab:
With the important thing at your disposal, create a brand new setting variable within the ”.env” file:
MORALIS_API_KEY=”replace_me”
From there, now you can use ”dotenv” to import the important thing safely into your code by these strains:
dotenv.config(); const apiKey = course of.env.MORALIS_API_KEY;
Now, all that continues to be is looking the ”verifySignature()” operate in your route by including the next:
verifySignature(req, apiKey);
All in all, your full code ought to now look one thing like this:
const specific = require("specific"); const app = specific(); const dotenv = require("dotenv"); const web3 = require("web3"); const port = 3000; app.use(specific.json()); dotenv.config(); const apiKey = course of.env.MORALIS_API_KEY; app.submit("/webhook", (req, res) => { verifySignature(req, apiKey); const webhook = req.physique; console.log(webhook); return res.standing(200).json(); }); app.pay attention(port, () => { console.log(`Listening to streams`); }); const verifySignature = (req, secret) => { const providedSignature = req.headers["x-signature"]; if (!providedSignature) throw new Error("Signature not offered"); const generatedSignature = web3.utils.sha3(JSON.stringify(req.physique) + secret); if (generatedSignature !== providedSignature) throw new Error("Invalid Signature"); };
By including the ”verifySignature()” operate, you could have ensured that solely Moralis can ship submit requests to your webhook URL. Because of this, now you can make sure that your Moralis Web3 stream solely gives correct knowledge!
If in case you have any additional questions, try the official webhook safety documentation web page or watch the video from the Moralis YouTube channel down beneath:
Abstract – Good Contract Safety
On this article, we explored the intricacies of good contract safety. In doing so, we began off by diving into some widespread good contract safety points. From there, we took on some Ethereum good contract safety greatest practices. Subsequent, we additionally dove into three outstanding good contract safety instruments. Lastly, to prime issues off, we launched the Moralis Streams API and tips on how to preserve your streams protected and safe!
Should you discovered this tutorial useful, contemplate trying out extra content material right here on the Moralis weblog. For instance, learn our article on Web3 libraries, the place we, amongst different issues, reply the ”what’s ethers.js?” query.
What’s extra, if you wish to get into the Web3 area and grow to be a more adept developer, contemplate enrolling in Moralis Academy! For instance, try the course on Ethereum good contract safety!

Additionally, in case you are severe about changing into a blockchain developer, keep in mind that you may join with Moralis totally free! It solely takes a number of seconds, and you can begin constructing initiatives smarter and extra effectively instantly!