Skip to content

Instantly share code, notes, and snippets.

View TehilaFavourite's full-sized avatar

Ajaye Favour TehilaFavourite

View GitHub Profile
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Bad approach: Unnecessary state updates
contract BadLocalVariables {
uint256 public total;
function addNumbers(uint256 a, uint256 b) public {
total = a + b; // Consumes gas for state update
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Bad approach: Unnecessary state updates
contract BadConditionalUpdate {
uint256 public counter;
function incrementCounter() public {
counter++; // Consumes gas for state update even if no condition is met
}
// Contract with batch update and separate state updates examples
contract StateUpdateExample {
uint256 public var1;
uint256 public var2;
uint256 public var3;
// Batch update: Set multiple state variables in a single transaction
function batchUpdate(uint256 newValue1, uint256 newValue2, uint256 newValue3) public {
var1 = newValue1;
var2 = newValue2;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Contract that makes an external call to TargetContract
contract CallerContract {
address public targetContract;
constructor(address _targetContract) {
targetContract = _targetContract;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
error CustomError(string message);
contract CustomErrorExample {
uint256 public maxValue = 100;
function setValue(uint256 newValue) public {
// Check if the input exceeds the maximum value allowed
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ExternalCallExample {
address public targetContract;
uint256 public lastResult;
constructor(address _targetContract) {
targetContract = _targetContract;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract RevertAndRequireExample {
uint256 public balance = 1000;
address public owner;
constructor() {
owner = msg.sender;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract InvalidOperationExample {
uint256[] public myArray;
function invalidOperation() public {
// Division by zero
uint256 a = 10;
uint256 b = 0;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract OutOfGasExample {
uint256[] public largeArray;
function addElements(uint256 numElements) public {
// Simulate an expensive operation that consumes a lot of gas
for (uint256 i = 0; i < numElements; i++) {
largeArray.push(i);
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract AssertExample {
uint256 public balance = 1000;
function withdraw(uint256 amount) public {
// Ensure the contract has sufficient balance before withdrawing
assert(balance >= amount);