{"id":13619896,"url":"https://github.com/manojpramesh/solidity-cheatsheet","last_synced_at":"2025-04-06T07:14:19.084Z","repository":{"id":37851607,"uuid":"111513785","full_name":"manojpramesh/solidity-cheatsheet","owner":"manojpramesh","description":"Cheat sheet and best practices for solidity. Write smart contracts for Ethereum.","archived":false,"fork":false,"pushed_at":"2022-12-20T21:36:09.000Z","size":34,"stargazers_count":1481,"open_issues_count":3,"forks_count":320,"subscribers_count":37,"default_branch":"master","last_synced_at":"2025-03-30T06:06:45.887Z","etag":null,"topics":["best-practices","blockchain","ethereum","solidity","solidity-cheatsheet"],"latest_commit_sha":null,"homepage":"https://manojpramesh.github.io/solidity-cheatsheet/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/manojpramesh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-21T07:23:10.000Z","updated_at":"2025-03-29T23:47:57.000Z","dependencies_parsed_at":"2023-01-30T02:01:11.927Z","dependency_job_id":null,"html_url":"https://github.com/manojpramesh/solidity-cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manojpramesh%2Fsolidity-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manojpramesh%2Fsolidity-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manojpramesh%2Fsolidity-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/manojpramesh%2Fsolidity-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/manojpramesh","download_url":"https://codeload.github.com/manojpramesh/solidity-cheatsheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247445681,"owners_count":20939961,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["best-practices","blockchain","ethereum","solidity","solidity-cheatsheet"],"created_at":"2024-08-01T21:00:49.936Z","updated_at":"2025-04-06T07:14:19.060Z","avatar_url":"https://github.com/manojpramesh.png","language":null,"funding_links":[],"categories":["Resources","Others","GitHub Repositories","Smart Contracts"],"sub_categories":["Solidity"],"readme":"# Solidity Cheatsheet and Best practices\n\n## Motivation\n\nThis document is a cheatsheet for **Solidity** that you can use to write **Smart Contracts** for **Ethereum** based blockchain.\n\nThis guide is not intended to teach you Solidity from the ground up, but to help developers with basic knowledge who may struggle to get familiar with Smart Contracts and Blockchain because of the Solidity concepts used.\n\n\u003e **Note:** If you have basic knowledge in JavaScript, it's easier to learn Solidity.\n\n\n## Table of contents\n\n- [Solidity Cheatsheet and Best practices](#solidity-cheatsheet-and-best-practices)\n  * [Motivation](#motivation)\n  * [Table of contents](#table-of-contents)\n  * [Version pragma](#version-pragma)\n  * [Import files](#import-files)\n  * [Types](#types)\n    + [Boolean](#boolean)\n    + [Integer](#integer)\n    + [Address](#address)\n      - [balance](#balance)\n      - [transfer and send](#transfer-and-send)\n      - [call](#call)\n      - [delegatecall](#delegatecall)\n      - [callcode](#callcode)\n    + [Array](#array)\n    + [Fixed byte arrays](#fixed-byte-arrays)\n    + [Dynamic byte arrays](#dynamic-byte-arrays)\n    + [Enum](#enum)\n    + [Struct](#struct)\n    + [Mapping](#mapping)\n  * [Control Structures](#control-structures)\n  * [Functions](#functions)\n    + [Structure](#structure)\n    + [Access modifiers](#access-modifiers)\n    + [Parameters](#parameters)\n      - [Input parameters](#input-parameters)\n      - [Output parameters](#output-parameters)\n    + [Constructor](#constructor)\n    + [Function Calls](#function-calls)\n      - [Internal Function Calls](#internal-function-calls)\n      - [External Function Calls](#external-function-calls)\n      - [Named Calls](#named-calls)\n      - [Unnamed function parameters](#unnamed-function-parameters)\n    + [Function type](#function-type)\n    + [Function Modifier](#function-modifier)\n    + [View or Constant Functions](#view-or-constant-functions)\n    + [Pure Functions](#pure-functions)\n    + [Payable Functions](#payable-functions)\n    + [Fallback Function](#fallback-function)\n  * [Contracts](#contracts)\n    + [Creating contracts using `new`](#creating-contracts-using--new-)\n    + [Contract Inheritance](#contract-inheritance)\n      - [Multiple inheritance](#multiple-inheritance)\n      - [Constructor of base class](#constructor-of-base-class)\n    + [Abstract Contracts](#abstract-contracts)\n  * [Interface](#interface)\n  * [Events](#events)\n  * [Library](#library)\n  * [Using - For](#using---for)\n  * [Error Handling](#error-handling)\n  * [Global variables](#global-variables)\n    + [Block variables](#block-variables)\n    + [Transaction variables](#transaction-variables)\n    + [Mathematical and Cryptographic Functions](#mathematical-and-cryptographic-functions)\n    + [Contract Related](#contract-related)\n\n\n## Version pragma\n\n`pragma solidity ^0.5.2;`  will compile with a compiler version  \u003e= 0.5.2 and \u003c 0.6.0.\n\n\n## Import files\n\n`import \"filename\";`\n\n`import * as symbolName from \"filename\";` or `import \"filename\" as symbolName;`\n\n`import {symbol1 as alias, symbol2} from \"filename\";`\n\n\n## Types\n\n### Boolean\n\n`bool` : `true` or `false`\n\nOperators:\n\n- Logical : `!` (logical negation), `\u0026\u0026` (AND), `||` (OR)\n- Comparisons : `==` (equality), `!=` (inequality)\n\n### Integer\n\nUnsigned : `uint8 | uint16 | uint32 | uint64 | uint128 | uint256(uint)`\n\nSigned   : `int8  | int16  | int32  | int64  | int128  | int256(int) `\n\nOperators:\n\n- Comparisons: `\u003c=`, `\u003c`, `==`, `!=`, `\u003e=` and `\u003e`\n- Bit operators: `\u0026`, `|`, `^` (bitwise exclusive or) and `~` (bitwise negation)\n- Arithmetic operators: `+`, `-`, unary `-`, unary `+`, `*`, `/`, `%`, `**` (exponentiation), `\u003c\u003c` (left shift) and `\u003e\u003e` (right shift)\n\n### Address\n\n`address`: Holds an Ethereum address (20 byte value).\n`address payable` : Same as address, but includes additional methods `transfer` and `send`\n\nOperators:\n\n- Comparisons: `\u003c=`, `\u003c`, `==`, `!=`, `\u003e=` and `\u003e`\n\nMethods:\n\n#### balance\n\n- `\u003caddress\u003e.balance (uint256)`: balance of the Address in Wei\n\n#### transfer and send\n\n- `\u003caddress\u003e.transfer(uint256 amount)`: send given amount of Wei to Address, throws on failure\n- `\u003caddress\u003e.send(uint256 amount) returns (bool)`: send given amount of Wei to Address, returns false on failure\n\n#### call\n- `\u003caddress\u003e.call(...) returns (bool)`: issue low-level CALL, returns false on failure\n\n#### delegatecall\n\n- `\u003caddress\u003e.delegatecall(...) returns (bool)`: issue low-level DELEGATECALL, returns false on failure\n\nDelegatecall uses the code of the target address, taking all other aspects (storage, balance, ...) from the calling contract. The purpose of delegatecall is to use library code which is stored in another contract. The user has to ensure that the layout of storage in both contracts is suitable for delegatecall to be used.\n\n```solidity\ncontract A {\n  uint value;\n  address public sender;\n  address a = address(0); // address of contract B\n  function makeDelegateCall(uint _value) public {\n    a.delegatecall(\n        abi.encodePacked(bytes4(keccak256(\"setValue(uint)\")), _value)\n    ); // Value of A is modified\n  }\n}\n\ncontract B {\n  uint value;\n  address public sender;\n  function setValue(uint _value) public {\n    value = _value;\n    sender = msg.sender; // msg.sender is preserved in delegatecall. It was not available in callcode.\n  }\n}\n```\n\n\u003e gas() option is available for call, callcode and delegatecall. value() option is not supported for delegatecall.\n\n#### callcode\n- `\u003caddress\u003e.callcode(...) returns (bool)`: issue low-level CALLCODE, returns false on failure\n\n\u003e Prior to homestead, only a limited variant called `callcode` was available that did not provide access to the original `msg.sender` and `msg.value` values.\n\n### Array\n\nArrays can be dynamic or have a fixed size.\n\n```solidity\nuint[] dynamicSizeArray;\n\nuint[7] fixedSizeArray;\n```\n\n### Fixed byte arrays\n\n`bytes1(byte)`, `bytes2`, `bytes3`, ..., `bytes32`.\n\nOperators:\n\nComparisons: `\u003c=`, `\u003c`, `==`, `!=`, `\u003e=`, `\u003e` (evaluate to bool)\nBit operators: `\u0026`, `|`, `^` (bitwise exclusive or), `~` (bitwise negation), `\u003c\u003c` (left shift), `\u003e\u003e` (right shift)\nIndex access: If x is of type bytesI, then x[k] for 0 \u003c= k \u003c I returns the k th byte (read-only).\n\nMembers\n\n- `.length` : read-only\n\n### Dynamic byte arrays\n\n`bytes`: Dynamically-sized `byte` array. It is similar to `byte[]`, but it is packed tightly in calldata. Not a value-type!\n\n`string`: Dynamically-sized UTF-8-encoded string. It is equal to `bytes` but does not allow length or index access. Not a value-type!\n\n### Enum\n\nEnum works just like in every other language.\n\n```solidity\nenum ActionChoices { \n  GoLeft, \n  GoRight, \n  GoStraight, \n  SitStill \n}\n\nActionChoices choice = ActionChoices.GoStraight;\n```\n\n### Struct\n\nNew types can be declared using struct.\n\n```solidity\nstruct Funder {\n    address addr;\n    uint amount;\n}\n\nFunder funders;\n```\n\n### Mapping\n\nDeclared as `mapping(_KeyType =\u003e _ValueType)`\n\nMappings can be seen as **hash tables** which are virtually initialized such that every possible key exists and is mapped to a value.\n\n**key** can be almost any type except for a mapping, a dynamically sized array, a contract, an enum, or a struct. **value** can actually be any type, including mappings.\n\n\n## Control Structures\n\nMost of the control structures from JavaScript are available in Solidity except for `switch` and `goto`. \n\n- `if` `else`\n- `while`\n- `do`\n- `for`\n- `break`\n- `continue`\n- `return`\n- `? :`\n\n## Functions\n\n### Structure\n\n`function (\u003cparameter types\u003e) {internal|external|public|private} [pure|constant|view|payable] [returns (\u003creturn types\u003e)]`\n\n### Access modifiers\n\n- ```public``` - Accessible from this contract, inherited contracts and externally\n- ```private``` - Accessible only from this contract\n- ```internal``` - Accessible only from this contract and contracts inheriting from it\n- ```external``` - Cannot be accessed internally, only externally. Recommended to reduce gas. Access internally with `this.f`.\n\n### Parameters\n\n#### Input parameters\n\nParameters are declared just like variables and are `memory` variables.\n\n```solidity\nfunction f(uint _a, uint _b) {}\n```\n\n#### Output parameters\n\nOutput parameters are declared after the `returns` keyword\n\n```solidity\nfunction f(uint _a, uint _b) returns (uint _sum) {\n   _sum = _a + _b;\n}\n```\n\nOutput can also be specified using `return` statement. In that case, we can omit parameter name `returns (uint)`.\n\nMultiple return types are possible with `return (v0, v1, ..., vn)`.\n\n\n### Constructor\n\nFunction that is executed during contract deployment. Defined using the `constructor` keyword.\n\n```solidity\ncontract C {\n   address owner;\n   uint status;\n   constructor(uint _status) {\n       owner = msg.sender;\n       status = _status;\n   }\n}\n```\n\n### Function Calls\n\n#### Internal Function Calls\n\nFunctions of the current contract can be called directly (internally - via jumps) and also recursively\n\n```solidity\ncontract C {\n    function funA() returns (uint) { \n       return 5; \n    }\n    \n    function FunB(uint _a) returns (uint ret) { \n       return funA() + _a; \n    }\n}\n```\n\n#### External Function Calls\n\n`this.g(8);` and `c.g(2);` (where c is a contract instance) are also valid function calls, but, the function will be called “externally”, via a message call.\n\n\u003e `.gas()` and `.value()` can also be used with external function calls.\n\n#### Named Calls\n\nFunction call arguments can also be given by name in any order as below.\n\n```solidity\nfunction f(uint a, uint b) {  }\n\nfunction g() {\n    f({b: 1, a: 2});\n}\n```\n\n#### Unnamed function parameters\n\nParameters will be present on the stack, but are not accessible.\n\n```solidity\nfunction f(uint a, uint) returns (uint) {\n    return a;\n}\n```\n\n### Function type\n\nPass function as a parameter to another function. Similar to `callbacks` and `delegates`\n\n```solidity\npragma solidity ^0.4.18;\n\ncontract Oracle {\n  struct Request {\n    bytes data;\n    function(bytes memory) external callback;\n  }\n  Request[] requests;\n  event NewRequest(uint);\n  function query(bytes data, function(bytes memory) external callback) {\n    requests.push(Request(data, callback));\n    NewRequest(requests.length - 1);\n  }\n  function reply(uint requestID, bytes response) {\n    // Here goes the check that the reply comes from a trusted source\n    requests[requestID].callback(response);\n  }\n}\n\ncontract OracleUser {\n  Oracle constant oracle = Oracle(0x1234567); // known contract\n  function buySomething() {\n    oracle.query(\"USD\", this.oracleResponse);\n  }\n  function oracleResponse(bytes response) {\n    require(msg.sender == address(oracle));\n  }\n}\n```\n\n\n### Function Modifier\n\nModifiers can automatically check a condition prior to executing the function.\n\n```solidity\nmodifier onlyOwner {\n    require(msg.sender == owner);\n    _;\n}\n\nfunction close() onlyOwner {\n    selfdestruct(owner);\n}\n```\n\n### View or Constant Functions\n\nFunctions can be declared `view` or `constant` in which case they promise not to modify the state, but can read from them.\n\n```solidity\nfunction f(uint a) view returns (uint) {\n    return a * b; // where b is a storage variable\n}\n```\n\n\u003e The compiler does not enforce yet that a `view` method is not modifying state.\n\n### Pure Functions\n\nFunctions can be declared `pure` in which case they promise not to read from or modify the state.\n\n```solidity\nfunction f(uint a) pure returns (uint) {\n    return a * 42;\n}\n```\n\n### Payable Functions\n\nFunctions that receive `Ether` are marked as `payable` function.\n\n### Fallback Function\n\nA contract can have exactly one **unnamed function**. This function cannot have arguments and cannot return anything. It is executed on a call to the contract if none of the other functions match the given function identifier (or if no data was supplied at all).\n\n```solidity\nfunction() {\n  // Do something\n}\n```\n\n## Contracts\n\n### Creating contracts using `new`\n\nContracts can be created from another contract using `new` keyword. The source of the contract has to be known in advance.\n\n```solidity\ncontract A {\n    function add(uint _a, uint _b) returns (uint) {\n        return _a + _b;\n    }\n}\n\ncontract C {\n    address a;\n    function f(uint _a) {\n        a = new A();\n    }\n}\n```\n\n### Contract Inheritance\n\nSolidity supports multiple inheritance and polymorphism.\n\n```solidity\ncontract owned {\n    function owned() { owner = msg.sender; }\n    address owner;\n}\n\ncontract mortal is owned {\n    function kill() {\n        if (msg.sender == owner) selfdestruct(owner);\n    }\n}\n\ncontract final is mortal {\n    function kill() { \n        super.kill(); // Calls kill() of mortal.\n    }\n}\n```\n\n#### Multiple inheritance\n\n```solidity\ncontract A {}\ncontract B {}\ncontract C is A, B {}\n```\n\n#### Constructor of base class\n\n```solidity\ncontract A {\n    uint a;\n    constructor(uint _a) { a = _a; }\n}\n\ncontract B is A(1) {\n    constructor(uint _b) A(_b) {\n    }\n}\n```\n\n\n### Abstract Contracts\n\nContracts that contain implemented and non-implemented functions. Such contracts cannot be compiled, but they can be used as base contracts.\n\n```solidity\npragma solidity ^0.4.0;\n\ncontract A {\n    function C() returns (bytes32);\n}\n\ncontract B is A {\n    function C() returns (bytes32) { return \"c\"; }\n}\n```\n\n## Interface\n\n`Interfaces` are similar to abstract contracts, but they have restrictions:\n\n- Cannot have any functions implemented.\n- Cannot inherit other contracts or interfaces.\n- Cannot define constructor.\n- Cannot define variables.\n- Cannot define structs.\n- Cannot define enums.\n\n```solidity\npragma solidity ^0.4.11;\n\ninterface Token {\n    function transfer(address recipient, uint amount);\n}\n```\n\n## Events\n\nEvents allow the convenient usage of the EVM logging facilities, which in turn can be used to “call” JavaScript callbacks in the user interface of a dapp, which listen for these events.\n\nUp to three parameters can receive the attribute indexed, which will cause the respective arguments to be searched for.\n\n\u003e All non-indexed arguments will be stored in the data part of the log.\n\n```solidity\npragma solidity ^0.4.0;\n\ncontract ClientReceipt {\n    event Deposit(\n        address indexed _from,\n        bytes32 indexed _id,\n        uint _value\n    );\n\n    function deposit(bytes32 _id) payable {\n        emit Deposit(msg.sender, _id, msg.value);\n    }\n}\n```\n\n## Library\n\nLibraries are similar to contracts, but they are deployed only once at a specific address, and their code is used with [`delegatecall`](#delegatecall) (`callcode`). \n\n```solidity\nlibrary arithmatic {\n    function add(uint _a, uint _b) returns (uint) {\n        return _a + _b;\n    }\n}\n\ncontract C {\n    uint sum;\n\n    function f() {\n        sum = arithmatic.add(2, 3);\n    }\n}\n```\n\n## Using - For\n\n`using A for B;` can be used to attach library functions to any type.\n\n```solidity\nlibrary arithmatic {\n    function add(uint _a, uint _b) returns (uint) {\n        return _a + _b;\n    }\n}\n\ncontract C {\n    using arithmatic for uint;\n    \n    uint sum;\n    function f(uint _a) {\n        sum = _a.add(3);\n    }\n}\n```\n\n## Error Handling\n\n- `assert(bool condition)`: throws if the condition is not met - to be used for internal errors.\n- `require(bool condition)`: throws if the condition is not met - to be used for errors in inputs or external components.\n- `revert()`: abort execution and revert state changes\n\n```solidity\n function sendHalf(address addr) payable returns (uint balance) {\n    require(msg.value % 2 == 0); // Only allow even numbers\n    uint balanceBeforeTransfer = this.balance;\n    addr.transfer(msg.value / 2);\n    assert(this.balance == balanceBeforeTransfer - msg.value / 2);\n    return this.balance;\n}\n```\n\n\u003e Catching exceptions is not yet possible.\n\n## Global variables\n\n### Block variables\n\n- `block.blockhash(uint blockNumber) returns (bytes32)`: hash of the given block - only works for the 256 most recent blocks excluding current\n- `block.coinbase (address)`: current block miner’s address\n- `block.difficulty (uint)`: current block difficulty\n- `block.gaslimit (uint)`: current block gaslimit\n- `block.number (uint)`: current block number\n- `block.timestamp (uint)`: current block timestamp as seconds since unix epoch\n- `now (uint)`: current block timestamp (alias for `block.timestamp`)\n\n### Transaction variables\n\n- `msg.data (bytes)`: complete calldata\n- `msg.gas (uint)`: remaining gas\n- `msg.sender (address)`: sender of the message (current call)\n- `msg.sig (bytes4)`: first four bytes of the calldata (i.e. function identifier)\n- `msg.value (uint)`: number of wei sent with the message\n- `tx.gasprice (uint)`: gas price of the transaction\n- `tx.origin (address)`: sender of the transaction (full call chain)\n\n### Mathematical and Cryptographic Functions\n\n- `addmod(uint x, uint y, uint k) returns (uint)`:\n   compute (x + y) % k where the addition is performed with arbitrary precision and does not wrap around at 2**256.\n- `mulmod(uint x, uint y, uint k) returns (uint)`:\n   compute (x * y) % k where the multiplication is performed with arbitrary precision and does not wrap around at 2**256.\n- `keccak256(...) returns (bytes32)`:\n   compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments\n- `sha256(...) returns (bytes32)`:\n   compute the SHA-256 hash of the (tightly packed) arguments\n- `sha3(...) returns (bytes32)`:\n   alias to keccak256\n- `ripemd160(...) returns (bytes20)`:\n   compute RIPEMD-160 hash of the (tightly packed) arguments\n- `ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)`:\n   recover the address associated with the public key from elliptic curve signature or return zero on error (example usage)\n   \n### Contract Related\n- `this (current contract’s type)`: the current contract, explicitly convertible to Address\n- `selfdestruct(address recipient)`: destroy the current contract, sending its funds to the given Address\n- `suicide(address recipient)`: alias to selfdestruct. Soon to be deprecated.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanojpramesh%2Fsolidity-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmanojpramesh%2Fsolidity-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanojpramesh%2Fsolidity-cheatsheet/lists"}