// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract Primitives { bool public boo = true;
uint8 public u8 = 1; uint256 public u256 = 456; uint256 public u = 123; // uint is an alias for uint256
int8 public i8 = -1; int256 public i256 = 456; int256 public i = -123; // int is same as int256// minimum and maximum of intint256 public minInt = type(int256).min; int256 public maxInt = type(int256).max;
address public addr = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c; }
// Declare a fixed-size byte array bytes1 a = 0xb5; // [10110101] bytes1 b = 0x56; // [01010110]
// Declare a bytes10 array bytes10 d = 0x68656c6c6f776f726c64; // "helloworld" in hexadecimal
// Declare a bytes32 array bytes32 e = 0x68656c6c6f776f726c6420202020202020202020202020202020202020202020; // "helloworld" padded with spaces in hexadecimal
// Declare a dynamically-sized byte array bytes memory c = "Hello, world!";
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract Variables { // State variables are stored on the blockchain. string public text = "Hello"; uint256 public num = 123;
function doSomething() public { // Local variables are not saved to the blockchain. uint256 i = 456;
// Here are some global variables uint256 timestamp = block.timestamp; // Current block timestamp address sender = msg.sender; // address of the caller } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract Array { // Several ways to initialize an array uint256[] public arr; uint256[] public arr2 = [1, 2, 3]; // Fixed sized array, all elements initialize to 0 uint256[10] public myFixedSizeArr;
function get(uint256 i) public view returns (uint256) { return arr[i]; }
// Solidity can return the entire array. // But this function should be avoided for // arrays that can grow indefinitely in length. function getArr() public view returns (uint256[] memory) { return arr; }
function push(uint256 i) public { // Append to array // This will increase the array length by 1. arr.push(i); }
function pop() public { // Remove last element from array // This will decrease the array length by 1 arr.pop(); }
function getLength() public view returns (uint256) { return arr.length; }
function remove(uint256 index) public { // Delete does not change the array length. // It resets the value at index to it's default value, // in this case 0 delete arr[index]; }
function examples() external pure { // create array in memory, only fixed size can be created uint256[] memory a = new uint256[](5); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract Mapping { // Mapping from address to uint mapping(address => uint256) public myMap;
function get(address _addr) public view returns (uint256) { // Mapping always returns a value. // If the value was never set, it will return the default value. return myMap[_addr]; }
function set(address _addr, uint256 _i) public { // Update the value at this address myMap[_addr] = _i; }
function remove(address _addr) public { // Reset the value to the default value. delete myMap[_addr]; } }
contract NestedMapping { // Nested mapping (mapping from address to another mapping) mapping(address => mapping(uint256 => bool)) public nested;
function get(address _addr1, uint256 _i) public view returns (bool) { // You can get values from a nested mapping // even when it is not initialized return nested[_addr1][_i]; }
function set(address _addr1, uint256 _i, bool _boo) public { nested[_addr1][_i] = _boo; }
function remove(address _addr1, uint256 _i) public { delete nested[_addr1][_i]; } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract Mapping { // Mapping from address to uint mapping(address => uint256) public myMap;
function get(address _addr) public view returns (uint256) { // Mapping always returns a value. // If the value was never set, it will return the default value. return myMap[_addr]; }
function set(address _addr, uint256 _i) public { // Update the value at this address myMap[_addr] = _i; }
function remove(address _addr) public { // Reset the value to the default value. delete myMap[_addr]; } }
contract NestedMapping { // Nested mapping (mapping from address to another mapping) mapping(address => mapping(uint256 => bool)) public nested;
function get(address _addr1, uint256 _i) public view returns (bool) { // You can get values from a nested mapping // even when it is not initialized return nested[_addr1][_i]; }
function set(address _addr1, uint256 _i, bool _boo) public { nested[_addr1][_i] = _boo; }
function remove(address _addr1, uint256 _i) public { delete nested[_addr1][_i]; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract BaseContract { // External function // Can be called from other contracts and via transactions // Cannot be called internally function externalFunc() external pure returns (string memory) { return "External function called"; }
// Public function // Can be called internally or via message calls function publicFunc() public pure returns (string memory) { return "Public function called"; }
// Internal function // Can only be accessed from within the current contract or contracts deriving from it // Cannot be accessed externally function internalFunc() internal pure returns (string memory) { return "Internal function called"; }
// Private function // Can only be accessed from within the current contract // Cannot be accessed from derived contracts or externally function privateFunc() private pure returns (string memory) { return "Private function called"; }
function testFuncs() public view returns (string memory, string memory) { // Call the public and internal functions // Call the external function using "this" return (publicFunc(), this.externalFunc()); } }
contract DerivedContract is BaseContract { function callBaseFuncs() public view returns (string memory, string memory) { // Can call the public and internal functions of the base contract return (publicFunc(), internalFunc()); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
// Free function defined outside of a contract // Always has implicit internal visibility function freeFunction(uint a, uint b) pure returns (uint) { return a + b; }
contract Simple { uint sum;
// Function defined inside a contract // Takes two uint parameters as input function taker(uint a, uint b) public { sum = a + b; }
// Function that returns multiple values // The names of return variables can be omitted function arithmetic(uint a, uint b) public pure returns (uint, uint) { return (a + b, a * b); }
// Function that uses an early return // Must provide return values together with the return statement function earlyReturn(uint a, uint b) public pure returns (uint sum, uint product) { if (a == 0 || b == 0) { return (0, 0); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract Tasks { // Define a new struct type 'Task' with three fields. struct Task { string title; string description; bool done; }
// Declare a dynamic array 'tasks' of 'Task' structs. Task[] public tasks;
// Add a new task to the 'tasks' array. function addTask(string calldata _title, string calldata _description) public { // Create a new temporary 'Task' object in memory. Task memory newTask; newTask.title = _title; newTask.description = _description; newTask.done = false;
// Add the 'newTask' into the 'tasks' array. tasks.push(newTask); }
// Mark a task as done. function markTaskAsDone(uint256 _index) public { // Get a reference to the task in the 'tasks' array using the '_index'. Task storage task = tasks[_index]; task.done = true; }
// Get the details of a task. function getTask(uint256 _index) public view returns (string memory title, string memory description, bool done) { Task storage task = tasks[_index]; return (task.title, task.description, task.done); }
// Update the title of a task. function updateTaskTitle(uint256 _index, string calldata _newTitle) public { Task storage task = tasks[_index]; task.title = _newTitle; // Set the new title of the task }
// Update the description of a task. function updateTaskDescription(uint256 _index, string calldata _newDescription) public { Task storage task = tasks[_index]; task.description = _newDescription; }
// Delete the task from the 'tasks' array using the '_index'. // Note: The 'delete' keyword in Solidity doesn't actually delete the task from the 'tasks' array, // it just sets the task at the given index to its initial default state (i.e., an empty string ("") for 'title' and 'description', and 'false' for 'done'). function deleteTask(uint256 _index) public { delete tasks[_index]; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
// Simple contract with a constructor contract SimpleContract { uint256 public data;
constructor(uint256 _data) { data = _data; // Initialize 'data' with the value passed to the constructor } }
// Contract with a constructor and a function to change the data contract ChangeableContract { uint256 public data;
constructor(uint256 _data) { data = _data; // Initialize 'data' with the value passed to the constructor }
function setData(uint256 _data) public { data = _data; // Change 'data' to the new value passed to the function } }
// Base contract A contract A { string public name;
constructor(string memory _name) { name = _name; // Initialize 'name' with the value passed to the constructor } }
// Contract B inherits from A and has its own data contract B is A { uint256 public data;
constructor(string memory _name, uint256 _data) A(_name) { data = _data; // Initialize 'data' with the value passed to the constructor } }
// Parent constructors are always called in the order of inheritance // regardless of the order of parent contracts listed in the // constructor of the child contract.
// Order of constructors called: // 1. A // 2. B // 3. C contract C is A, B { constructor(string memory _name, uint256 _data) A(_name) B(_name, _data) {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract DataLocations { uint256[] public numbers; // 'numbers' is a state variable and is stored in 'storage'
// 'arr' is a function argument and is stored in 'calldata' function addToNumbers(uint256[] calldata arr) public { for (uint256 i = 0; i < arr.length; i++) { numbers.push(arr[i]); // 'arr[i]' is read from 'calldata' } }
// 'x' is a local variable and is stored in 'memory' function calculateSum(uint256[] calldata arr) public pure returns (uint256) { uint256 sum = 0; // 'sum' is a local variable and is stored in 'memory' for (uint256 i = 0; i < arr.length; i++) { sum += arr[i]; // 'arr[i]' is read from 'calldata' } return sum; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract MyContract { mapping(address => uint) public balance;
function deposit(uint amount) public { // Use require to validate inputs from external calls require(amount > 0, "Deposit amount must be greater than 0");
balance[msg.sender] += amount; }
function withdraw(uint amount) public { // Use require to validate inputs from external calls require(amount <= balance[msg.sender], "Insufficient balance");
balance[msg.sender] -= amount; }
function transfer(address to, uint amount) public { // Use revert to abort execution and revert state changes if (to == address(0)) { revert("Cannot transfer to zero address"); }
// Use require to validate inputs from external calls require(amount <= balance[msg.sender], "Insufficient balance");
// Modifier to check if the caller is the owner of the contract modifier onlyOwner { require(msg.sender == owner, "Caller is not the owner"); _; }
// Modifier to check if multiple parameters are valid modifier validParams(address _addr, uint256 _amount) { require(_addr != address(0), "Invalid address"); require(_amount > 0, "Amount must be greater than zero"); _; }
// Modifier to prevent reentrancy attacks modifier nonReentrant { // Check if the function is currently being executed require(!_currentlyExecuting, "Reentrant call");
// Set the flag to true to signal that the function is being executed _currentlyExecuting = true;
// Execute the rest of the function _;
// Reset the flag to false after the function has finished executing _currentlyExecuting = false; }
// Function to deposit funds into the contract function depositFunds(uint256 _amount) public onlyOwner { balance += _amount; }
// Function that can only be called by the owner and is protected against reentrancy attacks function sensitiveFunction(address _to, uint256 _amount) public onlyOwner nonReentrant validParams(_to, _amount) { // Transfer the specified amount to the specified address balance -= _amount; // This is just an example, in a real contract you would use the transfer function of the address } }
// Struct to hold user data struct User { string name; }
// Mapping from address to User data mapping(address => User) public users;
// Variable to track whether the contract is paused bool public paused = false;
// Function to transfer funds function transferFunds(address receiver, uint256 amount) public { (bool success, ) = receiver.call{value: amount}(""); require(success, "Transfer failed.");
// Emit the event to log the transaction emit Transaction(msg.sender, receiver, amount); }
// Function to register a new user function registerUser(string memory name) public { users[msg.sender] = User(name); emit UserRegistered(msg.sender, name); }
// Function to update a user's information function updateUser(string memory name) public { users[msg.sender].name = name; emit UserUpdated(msg.sender, name); }
// Function to pause the contract function pauseContract() public { paused = true; emit ContractPaused(); }
// Function to resume the contract function resumeContract() public { paused = false; emit ContractResumed(); } }
// Function to deposit Ether into this contract. // Call this function along with some Ether. function deposit() public payable {}
// Function to withdraw all Ether from this contract. // Notice how this function below does not need payable keyword. // It has been defined in the global recipient variable. function withdraw() public { // get the amount of Ether stored in this contract uint256 amount = address(this).balance;
// Function to transfer Ether from this contract to another address function transfer(address payable _to, uint256 _amount) public { // Note that "_to" is declared as payable (bool success,) = _to.call{value: _amount}(""); require(success, "Failed to send Ether"); }
// This function is called when Ether is sent without data receive() external payable { deposit(); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
// Example 1: Receiving Ether contract EtherReceiver { uint public totalReceived;
// This fallback function is used to keep track of the total Ether received by the contract. // It's triggered when Ether is sent to the contract's address in a transaction without data. fallback() external payable { totalReceived += msg.value; } }
// Example 2: Proxy Pattern contract Proxy { address public implementation;
// This fallback function is used to implement the proxy pattern. // Assuming implementation variable has `delegatecall` function. // It catches any calls that don't match any of the proxy's functions and forwards them to the implementation contract. // It's triggered when a function that doesn't exist in the proxy contract is called. fallback() external payable { (bool success, ) = implementation.delegatecall(msg.data); require(success); } }
// Example 3: Default Functionality contract DefaultFunctionality { // Event to emit when the fallback function is triggered event FallbackTriggered(string message);
// This fallback function provides default functionality when no function is specified or the specified function doesn't exist. // It's triggered when the contract is called without specifying any function, or if the function specified doesn't exist in the contract. fallback() external { // Emit an event when the fallback function is triggered emit FallbackTriggered("Fallback function was called."); } }
// Example 4: Fallback with bytes type input and output contract FallbackWithInputOutput { // Event to emit when the fallback function is triggered event FallbackTriggered(string message, bytes input, bytes output);
// This fallback function takes an input, performs some operation, and returns an output. // It's triggered when the contract is called without specifying any function, or if the function specified doesn't exist in the contract. fallback(bytes calldata input) external payable returns (bytes memory) { // Perform some operation with the input bytes memory output = new bytes(input.length); for (uint i = 0; i < input.length; i++) { output[i] = input[i]; }
// Emit an event when the fallback function is triggered emit FallbackTriggered("Fallback function was called.", input, output);
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24;
contract SendEther {
address public sender; uint256 public amount;
mapping(address => uint256) public balances;
function sendViaCall(address payable _to) public payable {
// Remember to update the balance before interactions prevent reentrancy attacks! // Follow Checks-Effects-Interactions pattern balances[msg.sender] -= amount; balances[to] += amount;
// Call returns a boolean value indicating success or failure. // This is the current recommended method to use. (bool sent, bytes memory data) = _to.call{value: msg.value}(""); require(sent, "Failed to send Ether"); } }