DEV Community

ESTHER NAISIMOI
ESTHER NAISIMOI

Posted on

1

Solidity Cheatsheet: A Quick Reference Guide

Image of Solidity Contract
Basic Structure of a Solidity Contract

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

contract MyContract {
    // State variables
    uint public myNumber;

    // Constructor
    constructor(uint _num) {
        myNumber = _num;
    }

    // Function to update state variable
    function setNumber(uint _num) public {
        myNumber = _num;
    }

    // Function to retrieve state variable
    function getNumber() public view returns (uint) {
        return myNumber;
    }
}
Enter fullscreen mode Exit fullscreen mode

Contract Structure

**Contracts **are the fundamental building blocks in Solidity, similar to classes in object-oriented programming.

  1. State Variables Permanently stored in contract storage, state variables represent the contract's state.
  2. Functions Functions are executable units of code within a contract.
  3. Events Events allow logging to the Ethereum blockchain for frontend applications.

Data Types in Solidity
Value Types

  1. bool: true or false
  2. int/uint: signed and unsigned integers 3.** address**: Ethereum address
  3. bytes: dynamic array of bytes
    Reference Types

  4. arrays: fixed or dynamic size

  5. struct: custom defined type

  6. mapping: hash tables

Function Visibility and Modifiers

Function Visibility
Visibility Modifiers

  1. public - Accessible from anywhere.Can be called internally or via messages. Generates a getter function for state variables.
  2. private - Only within the contract.Only visible for the contract they are defined in. 3.** internal** - Within the contract and derived contracts.Only accessible internally and by derived contracts.
  3. *external *- Only callable from outside the contract.Can be called from other contracts and transactions. Cannot be called internally.

Function Modifiers

  1. pure - No state modifications
  2. view - Reads state but doesn’t modify it
  3. payable - Accepts Ether

Gas Optimization Techniques

Image description

  1. Use uint256 Prefer uint256 for integers when possible.
  2. Avoid Loops Minimize loops to reduce gas consumption.
  3. Use Events Emit events instead of storing data.
  4. Optimize Storage Pack variables to save storage slots

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more