DEV Community

Cover image for Solidity Security: The Significance of CHECK-EFFECTS-INTERACTION Pattern in Smart Contracts
Decipher with Zaryab
Decipher with Zaryab

Posted on • Updated on

Solidity Security: The Significance of CHECK-EFFECTS-INTERACTION Pattern in Smart Contracts

𝘛𝘰 𝘢𝘭𝘭 𝘵𝘩𝘦 𝘚𝘔𝘈𝘙𝘛 𝘊𝘰𝘯𝘵𝘳𝘢𝘤𝘵 𝘋𝘦𝘷𝘴 𝘰𝘶𝘵 𝘵𝘩𝘦𝘳𝘦, 📢
⚠️ 𝙉𝙀𝙑𝙀𝙍 𝙑𝙄𝙊𝙇𝘼𝙏𝙀 𝙏𝙃𝙀 𝘾𝙃𝙀𝘾𝙆-𝙀𝙁𝙁𝙀𝘾𝙏𝙎-𝙄𝙉𝙏𝙀𝙍𝘼𝘾𝙏𝙄𝙊𝙉 𝙋𝘼𝙏𝙏𝙀𝙍𝙉 ⚠️

Building a secure smart contract does require adhering to the Best Practices.
And one of the most crucial practices to keep in mind is the 𝐂𝐇𝐄𝐂𝐊 𝐄𝐅𝐅𝐄𝐂𝐓𝐒 𝐈𝐍𝐓𝐄𝐑𝐀𝐂𝐓𝐈𝐎𝐍 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 while making External Calls.

𝐖𝐇𝐀𝐓 𝐞𝐱𝐚𝐜𝐭𝐥𝐲 𝐝𝐨𝐞𝐬 𝐢𝐭 𝐦𝐞𝐚𝐧?
In simple terms, it means that while designing a function in solidity, any state modification in the function must happen before an external call is made.

𝐖𝐇𝐘 𝐔𝐬𝐞 𝐭𝐡𝐢𝐬 𝐏𝐚𝐭𝐭𝐞𝐫𝐧?
Remember the DAO Hack of 2016 where the attacker drained 3.6 million ETH?
Well, one of the Imperative reasons behind that hack was the Violation of Check-Effects-Interaction patterns in function code.

𝙒𝙝𝙮 𝙗𝙚 𝙘𝙖𝙧𝙚𝙛𝙪𝙡 𝙬𝙝𝙚𝙣 𝙀𝙭𝙚𝙘𝙪𝙩𝙞𝙣𝙜 𝙀𝙭𝙩𝙚𝙧𝙣𝙖𝙡 𝘾𝙖𝙡𝙡𝙨?
An external call technically shifts the control over execution to another contract or a Third Party. This allows the Third-party contract to leverage from the fact that the Contract State didn't change before the external call.

It leads to an extremely undesirable scenario where a malicious actor can re-enter the contract and disturb the expected flow. Thus, leading to a potential Re-entrancy Scenario.
Check-Effects-Pattern

𝐇𝐎𝐖 𝐝𝐨𝐞𝐬 𝐭𝐡𝐢𝐬 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 𝐒𝐞𝐜𝐮𝐫𝐞 𝐂𝐨𝐧𝐭𝐫𝐚𝐜𝐭𝐬?
Let's understand this by breaking down the 3 imperative steps in this pattern. (𝘔𝘰𝘴𝘵 𝘪𝘮𝘱𝘰𝘳𝘵𝘢𝘯𝘵𝘭𝘺, 𝘐𝘯 𝘵𝘩𝘦 𝘦𝘹𝘢𝘤𝘵 𝘰𝘳𝘥𝘦𝘳)

  1. 𝗖𝗛𝗘𝗖𝗞
    The first part is to implement a 𝘾𝙃𝙀𝘾𝙆 or input validations(𝘸𝘪𝘵𝘩 𝘳𝘦𝘲𝘶𝘪𝘳𝘦 𝘰𝘳 𝘢𝘴𝘴𝘦𝘳𝘵 𝘴𝘵𝘢𝘵𝘦𝘮𝘦𝘯𝘵𝘴) to ensure that arguments passed are valid and the function is ready to be executed.

  2. 𝗘𝗙𝗙𝗘𝗖𝗧𝗦
    Resolve all the 𝙀𝙁𝙁𝙀𝘾𝙏𝙎 to the State of the Contract. This part involves optimistically modifying the State Variables to a valid state in the protocol.

  3. 𝗜𝗡𝗧𝗘𝗥𝗔𝗖𝗧𝗜𝗢𝗡
    The final step should include any 𝙄𝙉𝙏𝙀𝙍𝘼𝘾𝙏𝙄𝙊𝙉 with other external contracts. This is the step that should include any external call that is being made from the function, at the very end of the function.

✧ 🎀 𝗜𝗻 𝗮 𝗡𝗨𝗧𝗦𝗛𝗘𝗟𝗟 🎀 ✧
External calls must be the very last thing that you should do in a function. 𝘼𝙣𝙮 𝙨𝙩𝙖𝙩𝙚 𝙫𝙖𝙧𝙞𝙖𝙗𝙡𝙚 𝙢𝙤𝙙𝙞𝙛𝙞𝙘𝙖𝙩𝙞𝙤𝙣 𝙢𝙪𝙨𝙩 𝙝𝙖𝙥𝙥𝙚𝙣 𝙗𝙚𝙛𝙤𝙧𝙚 𝙖𝙣 𝙚𝙭𝙩𝙚𝙧𝙣𝙖𝙡 𝙘𝙖𝙡𝙡 𝙞𝙨 𝙚𝙭𝙚𝙘𝙪𝙩𝙚𝙙 𝙞𝙣 𝙤𝙧𝙙𝙚𝙧 𝙩𝙤 𝙖𝙫𝙤𝙞𝙙 𝙖 𝙧𝙚-𝙚𝙣𝙩𝙧𝙖𝙣𝙘𝙮 𝙨𝙘𝙚𝙣𝙖𝙧𝙞𝙤.

Moreover, even if attackers try to re-enter a function that follows the CHECK-EFFECTS-INTERACTION pattern, they cannot really abuse the State of the contract as it has been already modified before the external call is made.

Discussion (0)