From ef334243d74b413bfc106f142f328e041d7f501b Mon Sep 17 00:00:00 2001 From: "steinkirch.eth, phd" <1130416+mvonsteinkirch@users.noreply.github.com> Date: Mon, 19 Jun 2023 08:24:32 -0700 Subject: [PATCH] Create overflow.md --- advanced_expert/vulnerabilities/overflow.md | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 advanced_expert/vulnerabilities/overflow.md diff --git a/advanced_expert/vulnerabilities/overflow.md b/advanced_expert/vulnerabilities/overflow.md new file mode 100644 index 0000000..04a107f --- /dev/null +++ b/advanced_expert/vulnerabilities/overflow.md @@ -0,0 +1,54 @@ +## overflow of numbers + +
+ + +
+ +---- + +### unchecked math + +
+ +* overflow and underflow of numbers in solidity 0.8 throw an error. this can be disabled with `unchecked`. +* disabling overflow / underflow check saves gas. + +
+ +``` +contract UncheckedMath { + function add(uint x, uint y) external pure returns (uint) { + // 22291 gas + // return x + y; + + // 22103 gas + unchecked { + return x + y; + } + } + + function sub(uint x, uint y) external pure returns (uint) { + // 22329 gas + // return x - y; + + // 22147 gas + unchecked { + return x - y; + } + } + + function sumOfCubes(uint x, uint y) external pure returns (uint) { + // Wrap complex math logic inside unchecked + unchecked { + uint x3 = x * x * x; + uint y3 = y * y * y; + + return x3 + y3; + } + } +} + +``` + +