DeveloperBreeze

Solidity Cheatsheet

Solidity is the primary programming language used to write smart contracts on the Ethereum blockchain. This cheatsheet provides a quick reference to the key syntax, functions, and concepts in Solidity, covering everything from basic syntax to advanced features.

---

1. Basic Structure

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ContractName {
    // State variables
    uint public myUint;
    string public myString;

    // Constructor
    constructor() {
        // Initialization code
    }

    // Functions
    function setMyUint(uint _value) public {
        myUint = _value;
    }

    function getMyUint() public view returns (uint) {
        return myUint;
    }
}

---

2. Data Types

  • Value Types:

- bool: true or false

- int: Signed integers (e.g., int256, int128)

- uint: Unsigned integers (e.g., uint256, uint128)

- address: Holds a 20-byte Ethereum address

- bytes1, bytes32: Fixed-size byte arrays

  • Reference Types:

- string: Dynamically-sized UTF-8 encoded string

- bytes: Dynamically-sized byte array

- array: Fixed or dynamic array

- mapping: Key-value store (e.g., mapping(address => uint))

---

3. Visibility Specifiers

  • public: Accessible externally and internally

  • internal: Accessible only within the contract and derived contracts

  • private: Accessible only within the contract

  • external: Accessible only externally (cannot be called internally without this)

---

4. State Variables and Constants

uint public myVariable;
address private owner;
bool internal isActive;

uint constant MY_CONSTANT = 10;
address immutable MY_ADDRESS = msg.sender;

---

5. Functions

  • Function Modifiers:

- view: Indicates that the function does not modify the state.

- pure: Indicates that the function does not read or modify the state.

- payable: Indicates that the function can receive Ether.

function setMyUint(uint _value) public {
    myUint = _value;
}

function getMyUint() public view returns (uint) {
    return myUint;
}

function add(uint a, uint b) public pure returns (uint) {
    return a + b;
}

function deposit() public payable {
    // Function to receive Ether
}

---

6. Modifiers

Modifiers are used to change the behavior of functions.

modifier onlyOwner() {
    require(msg.sender == owner, "Not the owner");
    _;
}

function setMyUint(uint _value) public onlyOwner {
    myUint = _value;
}

---

7. Events

Events allow logging of data on the blockchain, which can be listened to by external applications.

event MyEvent(address indexed from, uint value);

function triggerEvent(uint _value) public {
    emit MyEvent(msg.sender, _value);
}

---

8. Structs and Enums

  • Structs: Define custom data types.

struct User {
    uint id;
    string name;
}

User public user;

function setUser(uint _id, string memory _name) public {
    user = User(_id, _name);
}

  • Enums: Define enumerated lists.

enum State { Created, Locked, Inactive }
State public state;

function setState(State _state) public {
    state = _state;
}

---

9. Mappings

Mappings are key-value stores, often used to associate addresses with balances.

mapping(address => uint) public balances;

function updateBalance(address _address, uint _amount) public {
    balances[_address] = _amount;
}

function getBalance(address _address) public view returns (uint) {
    return balances[_address];
}

---

10. Inheritance

Solidity supports single inheritance. Contracts can inherit from other contracts.

contract Base {
    uint public data;

    function setData(uint _data) public {
        data = _data;
    }
}

contract Derived is Base {
    function getData() public view returns (uint) {
        return data;
    }
}

---

11. Interfaces

Interfaces define a contract's functions without implementing them, allowing different contracts to interact.

interface MyInterface {
    function setData(uint _data) external;
    function getData() external view returns (uint);
}

contract MyContract is MyInterface {
    uint private data;

    function setData(uint _data) external override {
        data = _data;
    }

    function getData() external view override returns (uint) {
        return data;
    }
}

---

12. Libraries

Libraries are similar to contracts but are meant to hold reusable code. They cannot hold state.

library Math {
    function add(uint a, uint b) internal pure returns (uint) {
        return a + b;
    }
}

contract MyContract {
    using Math for uint;

    function calculate(uint a, uint b) public pure returns (uint) {
        return a.add(b);
    }
}

---

13. Fallback and Receive Functions

Fallback and receive functions handle direct payments to contracts.

  • Fallback: Called when no other function matches or if no data is provided.

  • Receive: Specifically handles Ether transfers.

// Fallback function
fallback() external payable {
    // Logic to execute when no other function matches
}

// Receive function
receive() external payable {
    // Logic to execute when contract receives Ether directly
}

---

14. Error Handling

Use require, assert, and revert for error handling.

  • require: Checks conditions and reverts if false. Used for input validation.

  • assert: Used to check for conditions that should never be false.

  • revert: Explicitly reverts the transaction, optionally providing an error message.

function withdraw(uint _amount) public {
    require(_amount <= balances[msg.sender], "Insufficient balance");
    balances[msg.sender] -= _amount;
}

function divide(uint a, uint b) public pure returns (uint) {
    assert(b != 0);
    return a / b;
}

function doSomething(uint _value) public {
    if (_value < 10) {
        revert("Value too low");
    }
}

---

15. Assembly

Inline assembly allows for low-level operations and optimizations.

function multiply(uint a, uint b) public pure returns (uint) {
    uint result;
    assembly {
        result := mul(a, b)
    }
    return result;
}

---

16. Gas Optimization Tips

  • Use memory over storage for temporary variables.

  • Group multiple storage updates in a single transaction.

  • Avoid complex computations within loops.

  • Use immutable and constant for variables that do not change.

  • Leverage view and pure functions to save gas on reads.

---

17. Common Design Patterns

  • Ownable Pattern: Restricts access to certain functions to the contract owner.

  • Pausable Pattern: Allows the contract to be paused or unpaused.

  • Upgradable Contracts: Use proxy patterns to upgrade contract logic while preserving state.

  • ERC20/721 Tokens: Standards for implementing tokens.

---

18. ERC Standards

  • ERC20: Standard interface for fungible tokens.

  • ERC721: Standard interface for non-fungible tokens (NFTs).

  • ERC1155: Standard for multi-token contracts.

---

19. Best Practices

  • Always validate inputs with require.

  • Use SafeMath or Solidity's built-in overflow checks for arithmetic.

  • Limit gas consumption by optimizing functions.

  • Write unit tests for every contract function.

  • Audit and review contracts before deploying to the mainnet.

---

20. Deployment and Testing Tools

  • Remix IDE: Web-based IDE for writing and testing smart contracts.

  • Truffle: Development framework for Ethereum smart contracts.

  • Hardhat: Flexible development environment for Ethereum.

  • Ganache: Personal blockchain for Ethereum development.

---

This Solidity cheatsheet covers the essential concepts and syntax needed to start writing and optimizing smart contracts. As you develop more complex contracts, always consider security, gas efficiency, and best practices to ensure your contracts are robust and cost-effective.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Non-Primitive Data Types (Objects, Arrays, and Functions)

  let person = {
    name: "Alice",
    age: 25,
    isStudent: true,
  };
  • Accessing Properties:
  • Dot notation:

Dec 11, 2024
Read More
Code
javascript

Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

Sometimes, you might receive raw responses in formats other than JSON, such as a query string or plain text. Here’s how to handle and process raw responses:

use Illuminate\Support\Facades\Http;

$response = Http::post('https://api.example.com/endpoint', [
    'key1' => 'value1',
    'key2' => 'value2',
]);

$rawResponse = $response->body(); // Get the raw response as a string
dd($rawResponse);

Oct 24, 2024
Read More
Tutorial

Understanding `crypto.randomBytes` and `ethers.randomBytes`: A Comparison

Both crypto.randomBytes and ethers.randomBytes generate cryptographically secure random bytes, meaning the bytes are suitable for use in cryptographic applications such as key generation, encryption, and other security-sensitive operations.

  • Use crypto.randomBytes when:
  • You are building Node.js applications without blockchain-specific functionality.
  • You want to avoid adding external dependencies.
  • Use ethers.randomBytes when:
  • You are developing Ethereum-related applications and already have ethers.js in your project.
  • You want the flexibility of generating random bytes with minimal configuration, defaulting to 32 bytes for Ethereum addresses or private keys.

Oct 24, 2024
Read More
Tutorial

How to Query ERC-20 Token Balances and Transactions Using Ethers.js and Etherscan API

Now let’s query the ERC-20 token transfer history for a specific wallet address using the Etherscan API.

const axios = require('axios');

// Replace with your Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';

// Replace with the wallet address you want to query
const address = '0xYourEthereumAddress';

// Replace with the ERC-20 token contract address
const contractAddress = '0xTokenContractAddress';

// Etherscan API URL to fetch ERC-20 token transactions
const url = `https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=${contractAddress}&address=${address}&startblock=0&endblock=99999999&sort=asc&apikey=${apiKey}`;

async function getTokenTransactions() {
    try {
        // Make the API request to Etherscan
        const response = await axios.get(url);
        const transactions = response.data.result;

        // Log the token transactions
        transactions.forEach(tx => {
            console.log(`
                From: ${tx.from}
                To: ${tx.to}
                Value: ${ethers.utils.formatUnits(tx.value, 18)} Tokens
                Transaction Hash: ${tx.hash}
            `);
        });
    } catch (error) {
        console.error('Error fetching token transactions:', error);
    }
}

// Call the function to get the token transactions
getTokenTransactions();

Oct 24, 2024
Read More
Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

  • Etherscan:
  • Primarily a block explorer and data provider. It offers read-only access to Ethereum blockchain data such as transaction histories, balances, token transfers, and more.
  • Does not allow real-time interaction with the blockchain (e.g., sending transactions).
  • Ideal for querying historical data and performing analytics on blockchain data.
  • Infura:
  • Provides full node access to the Ethereum network, allowing developers to interact with the blockchain in real-time.
  • Supports read and write operations, such as sending transactions, deploying smart contracts, and interacting with dApps.
  • Best for applications that require real-time interaction with Ethereum, such as decentralized apps (dApps).

You should use Etherscan when you need to read data from the Ethereum blockchain, such as querying transaction details, wallet balances, or token transfers. Etherscan is a powerful tool for building blockchain explorers or applications that focus on data analytics.

Oct 24, 2024
Read More
Tutorial

Sending Transactions and Interacting with Smart Contracts Using Infura and Ethers.js

node contractInteraction.js

If everything is set up correctly, the script will output the token balance of the specified wallet.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

   https://api.etherscan.io/api?module=account&action=tokentx&address=0xYourEthereumAddress&startblock=0&endblock=99999999&sort=asc&apikey=YOUR_API_KEY
   https://api.etherscan.io/api?module=proxy&action=eth_gasPrice&apikey=YOUR_API_KEY

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

Once you've successfully retrieved the balance, you can expand your script to add more features. For example:

  • Check the balance of other Ethereum addresses (not just your wallet).
  • Send ETH to other addresses.
  • Interact with smart contracts using Ethers.js.

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

Although token burns can increase the scarcity of a token, they are not without risk:

  • Overuse: If token burns are overused or if the project relies too heavily on them to drive up value, it can create instability in the market.
  • Misuse: Token burns can be misused by projects to manipulate token value artificially, without creating any real underlying value or utility for the token.
  • Irreversibility: Once tokens are sent to a burn address like "0x000000000000000000000000000000000000dead," they cannot be retrieved, even if the burn was done accidentally.

Oct 24, 2024
Read More
Tutorial

ETH vs WETH: Understanding the Difference and Their Roles in Ethereum

Ethereum predates the ERC-20 token standard, which was introduced to standardize token creation on the blockchain. Since ETH doesn't conform to this standard, it cannot be directly used in many decentralized applications that rely on ERC-20 tokens. WETH solves this problem by allowing ETH holders to wrap their ETH into an ERC-20 compatible token that can be used across a wide range of DeFi protocols and dApps.

WETH essentially bridges the gap between ETH and the broader ERC-20 ecosystem, allowing ETH to function seamlessly in DeFi, token swaps, and other smart contract interactions.

Oct 24, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
javascript

Easy JavaScript Tutorial for Beginners

<p id="text">This is a paragraph.</p>
<button onclick="changeText()">Change Text</button>

<script>
function changeText() {
    document.getElementById('text').innerHTML = "Text changed!";
}
</script>
<p id="styledText">This text will be styled.</p>
<button onclick="changeStyle()">Change Style</button>

<script>
function changeStyle() {
    document.getElementById('styledText').style.color = "red";
    document.getElementById('styledText').style.fontSize = "24px";
}
</script>

Sep 18, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

In this example:

  • We create a new XMLHttpRequest object and open a GET request to the JSONPlaceholder API (a fake online REST API).
  • When the request is successful (status code 200), we parse the JSON data and display it on the page.

Sep 18, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

Deeply nested code can be difficult to follow and debug. Break down complex logic into smaller, modular functions.

  // Deeply nested code
  function processOrder(order) {
      if (order.isValid) {
          if (order.paymentProcessed) {
              if (order.itemsInStock) {
                  shipOrder(order);
              }
          }
      }
  }

  // Refactored code
  function processOrder(order) {
      if (!order.isValid) return;
      if (!order.paymentProcessed) return;
      if (!order.itemsInStock) return;
      shipOrder(order);
  }

Sep 02, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

If you're working on a Node.js project, you can install Axios using npm:

npm install axios

Sep 02, 2024
Read More
Tutorial
javascript

Understanding JavaScript Classes

class Counter {
  #count = 0;

  increment() {
    this.#count++;
    console.log(this.#count);
  }

  getCount() {
    return this.#count;
  }
}

const counter = new Counter();
counter.increment(); // Output: 1
console.log(counter.getCount()); // Output: 1
console.log(counter.#count); // Error: Private field '#count' must be declared in an enclosing class

Getters and setters allow you to define methods that are executed when a property is accessed or modified. This can be useful for validating data or performing side effects.

Sep 02, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

Blockchain development is a rapidly growing field with a wide range of tools, libraries, and frameworks available to facilitate the development, testing, and deployment of decentralized applications (DApps) and smart contracts. This cheatsheet provides a comprehensive overview of the most important blockchain development tools, libraries, and frameworks.

  • Description: A development framework for Ethereum that provides a suite of tools for writing, testing, and deploying smart contracts.
  • Key Features:
  • Built-in smart contract compilation, linking, deployment, and binary management.
  • Scriptable deployment & migrations framework.
  • Network management for deploying to different networks.
  • Interactive console for direct contract interaction.
  • Testing framework using Mocha and Chai.
  • Website: Truffle

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

Next, you need to compile your contract to ensure there are no errors.

  • Run the following command in your terminal:

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

  • Write your smart contract in Remix IDE, regularly checking the gas estimates.
  • Deploy the contract on a test network using Truffle or Hardhat.
  • Use Solidity Coverage to generate a gas report and identify optimization opportunities.

Writing gas-efficient smart contracts is a balance between functionality, security, and cost. Here are some best practices to follow:

Aug 22, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!