[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-10607":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":10,"languages":10,"totalLinesOfCode":10,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":14,"stars7d":14,"stars30d":15,"stars90d":14,"forks30d":14,"starsTrendScore":14,"compositeScore":16,"rankGlobal":10,"rankLanguage":10,"license":17,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":20,"topics":21,"createdAt":10,"pushedAt":10,"updatedAt":26,"readmeContent":27,"aiSummary":28,"trendingCount":14,"starSnapshotCount":14,"syncStatus":29,"lastSyncTime":30,"discoverSource":31},10607,"solidity-cheatsheet","manojpramesh\u002Fsolidity-cheatsheet","manojpramesh","Cheat sheet and best practices for solidity. Write smart contracts for Ethereum.","https:\u002F\u002Fmanojpramesh.github.io\u002Fsolidity-cheatsheet\u002F",null,1510,322,35,0,1,20.53,"MIT License",false,"master",true,[22,23,24,25,5],"best-practices","blockchain","ethereum","solidity","2026-06-12 02:02:24","# 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> Older versions of this cheatsheet can be found in Git tags.\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      - [Unchecked arithmetic](#unchecked-arithmetic)\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    + [Data locations](#data-locations)\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      - [Receive vs Fallback](#receive-vs-fallback)\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  * [Units](#units)\n  * [Error Handling](#error-handling)\n    + [Custom Errors](#custom-errors)\n    + [Try \u002F Catch](#try--catch)\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.8.34;` will compile with a compiler version `>= 0.8.34` and `\u003C 0.9.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), `&&` (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`, `==`, `!=`, `>=` and `>`\n- Bit operators: `&`, `|`, `^` (bitwise exclusive or) and `~` (bitwise negation)\n- Arithmetic operators: `+`, `-`, unary `-`, unary `+`, `*`, `\u002F`, `%`, `**` (exponentiation), `\u003C\u003C` (left shift) and `>>` (right shift)\n\n> Arithmetic overflow and underflow checks are enabled by default in Solidity `0.8.x`. Use `unchecked { ... }` only when you intentionally want wrapping behavior.\n\n#### Unchecked arithmetic\n\nUse `unchecked` to disable the default overflow and underflow checks inside a specific block.\n\n```solidity\nfunction add(uint256 a, uint256 b) public pure returns (uint256) {\n    unchecked {\n        return a + b;\n    }\n}\n```\n\n### Address\n\n`address`: Holds an Ethereum address (20 byte value).\n\n`address payable`: Same as address, but is used for addresses that can receive `Ether`.\n\nOperators:\n\n- Comparisons: `\u003C=`, `\u003C`, `==`, `!=`, `>=` and `>`\n\nMethods:\n\n#### balance\n\n- `\u003Caddress>.balance (uint256)`: balance of the Address in Wei\n\n#### transfer and send\n\n- `\u003Caddress payable>.transfer(uint256 amount)`: send given amount of Wei to Address, throws on failure\n- `\u003Caddress payable>.send(uint256 amount) returns (bool)`: send given amount of Wei to Address, returns false on failure\n\n> In the current version of Solidity, `transfer` and `send` are considered legacy patterns. Prefer `call{value: amount}(\"\")` and always check the returned success value.\n\n#### call\n\n- `\u003Caddress>.call(bytes memory data) returns (bool, bytes memory)`: issue low-level `CALL`\n\n```solidity\n(bool success, bytes memory result) = target.call{value: amount}(data);\n```\n\n#### delegatecall\n\n- `\u003Caddress>.delegatecall(bytes memory data) returns (bool, bytes memory)`: issue low-level `DELEGATECALL`\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 or proxy 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    uint256 value;\n    address public sender;\n    address target;\n\n    function makeDelegateCall(uint256 _value) public {\n        (bool success, ) = target.delegatecall(\n            abi.encodeWithSignature(\"setValue(uint256)\", _value)\n        );\n        require(success, \"delegatecall failed\");\n    }\n}\n\ncontract B {\n    uint256 value;\n    address public sender;\n\n    function setValue(uint256 _value) public {\n        value = _value;\n        sender = msg.sender;\n    }\n}\n```\n\n> Use call options such as `{gas: gasAmount}` and `{value: amount}` instead of the older `.gas()` and `.value()` syntax.\n\n#### callcode\n\n`callcode` is obsolete and should not be used in modern Solidity.\n\n### Array\n\nArrays can be dynamic or have a fixed size.\n\n```solidity\nuint256[] dynamicSizeArray;\n\nuint256[7] fixedSizeArray;\n```\n\n### Fixed byte arrays\n\n`bytes1`, `bytes2`, `bytes3`, ..., `bytes32`.\n\nOperators:\n\nComparisons: `\u003C=`, `\u003C`, `==`, `!=`, `>=`, `>` (evaluate to bool)\n\nBit operators: `&`, `|`, `^` (bitwise exclusive or), `~` (bitwise negation), `\u003C\u003C` (left shift), `>>` (right shift)\n\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.\n\n`string`: Dynamically-sized UTF-8 encoded string. It is similar to `bytes`, but does not allow length or index access directly.\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    uint256 amount;\n}\n\nFunder funder;\n```\n\n### Mapping\n\nDeclared as `mapping(_KeyType => _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 any built-in value type, `bytes`, `string`, contract type, or enum. **value** can be almost any type, including mappings, arrays and structs.\n\n### Data locations\n\nReference types such as arrays, structs, `bytes` and `string` use data locations.\n\n- `storage` - persistent state stored on-chain\n- `memory` - temporary data for the current call\n- `calldata` - read-only input data for external calls\n\n```solidity\nstring public name;\n\nfunction setName(string calldata _name) external {\n    name = _name;\n}\n```\n\n> Mappings can only exist in `storage`.\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 while`\n- `for`\n- `break`\n- `continue`\n- `return`\n- `? :`\n- `try` `catch`\n- `unchecked`\n\n## Functions\n\n### Structure\n\n`function \u003CfunctionName>(\u003Cparameter types>) {internal|external|public|private} [pure|view|payable] [virtual|override] [returns (\u003Creturn types>)]`\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 directly internally, only externally. Access internally with `this.f(...)` or by using an internal helper function\n\n### Parameters\n\n#### Input parameters\n\nParameters are declared just like variables. Reference types should use an explicit data location such as `memory` or `calldata`.\n\n```solidity\nfunction f(uint256 _a, uint256 _b) public pure {}\n```\n\n#### Output parameters\n\nOutput parameters are declared after the `returns` keyword\n\n```solidity\nfunction f(uint256 _a, uint256 _b) public pure returns (uint256 _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 (uint256)`.\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    uint256 status;\n\n    constructor(uint256 _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() internal pure returns (uint256) {\n        return 5;\n    }\n\n    function funB(uint256 _a) public pure returns (uint256 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> Call options such as `{gas: gasAmount, value: amount}` 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(uint256 a, uint256 b) public pure {}\n\nfunction g() public pure {\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(uint256 a, uint256) public pure returns (uint256) {\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\ncontract Oracle {\n    struct Request {\n        bytes data;\n        function(bytes memory) external callback;\n    }\n\n    Request[] requests;\n    event NewRequest(uint256);\n\n    function query(bytes memory data, function(bytes memory) external callback) external {\n        requests.push(Request(data, callback));\n        emit NewRequest(requests.length - 1);\n    }\n\n    function reply(uint256 requestID, bytes memory response) external {\n        requests[requestID].callback(response);\n    }\n}\n\ncontract OracleUser {\n    Oracle public oracle;\n\n    constructor(address _oracle) {\n        oracle = Oracle(_oracle);\n    }\n\n    function buySomething() external {\n        oracle.query(bytes(\"USD\"), this.oracleResponse);\n    }\n\n    function oracleResponse(bytes memory) external {\n        require(msg.sender == address(oracle), \"only oracle\");\n    }\n}\n```\n\n\n### Function Modifier\n\nModifiers can automatically check a condition prior to executing the function.\n\n```solidity\naddress owner;\nuint256 status;\n\nmodifier onlyOwner() {\n    require(msg.sender == owner, \"not owner\");\n    _;\n}\n\nfunction setStatus(uint256 _status) public onlyOwner {\n    status = _status;\n}\n```\n\n### View or Constant Functions\n\nFunctions can be declared `view` in which case they promise not to modify the state, but can read from it. Older examples may use `constant`, but `view` is the current syntax.\n\n```solidity\nuint256 b;\n\nfunction f(uint256 a) public view returns (uint256) {\n    return a * b;\n}\n```\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(uint256 a) public pure returns (uint256) {\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 a `receive()` function and a `fallback()` function. These functions cannot return anything. `receive()` is executed on plain Ether transfers with empty calldata. `fallback()` is executed if none of the other functions match the given function identifier.\n\n#### Receive vs Fallback\n\n- `receive()` is called when the calldata is empty and Ether is sent\n- `fallback()` is called when no other function matches\n- `fallback()` can also be marked `payable` if it should receive Ether\n\n```solidity\nreceive() external payable {\n    \u002F\u002F Receive Ether\n}\n\nfallback() external payable {\n    \u002F\u002F 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(uint256 _a, uint256 _b) public pure returns (uint256) {\n        return _a + _b;\n    }\n}\n\ncontract C {\n    A a;\n\n    function f() public {\n        a = new A();\n    }\n}\n```\n\n### Contract Inheritance\n\nSolidity supports multiple inheritance and polymorphism.\n\n```solidity\ncontract Owned {\n    address owner;\n\n    constructor() {\n        owner = msg.sender;\n    }\n}\n\ncontract Mortal is Owned {\n    function close() public virtual {\n        require(msg.sender == owner, \"not owner\");\n    }\n}\n\ncontract Final is Mortal {\n    function close() public override {\n        super.close();\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    uint256 a;\n\n    constructor(uint256 _a) {\n        a = _a;\n    }\n}\n\ncontract B is A {\n    constructor(uint256 _b) A(_b) {}\n}\n```\n\n\n### Abstract Contracts\n\nContracts that contain implemented and non-implemented functions. Such contracts cannot be deployed, but they can be used as base contracts.\n\n```solidity\nabstract contract A {\n    function c() public view virtual returns (bytes32);\n}\n\ncontract B is A {\n    function c() public pure override returns (bytes32) {\n        return \"c\";\n    }\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, but can inherit other interfaces.\n- Cannot define constructor.\n- Cannot define state variables.\n- Can define structs, enums, errors and events.\n\n```solidity\ninterface Token {\n    function transfer(address recipient, uint256 amount) external returns (bool);\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 searchable.\n\n> All non-indexed arguments will be stored in the data part of the log.\n\n```solidity\ncontract ClientReceipt {\n    event Deposit(\n        address indexed _from,\n        bytes32 indexed _id,\n        uint256 _value\n    );\n\n    function deposit(bytes32 _id) external 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 can be reused by other contracts. Public library functions use `delegatecall`; internal ones are included in the caller.\n\n```solidity\nlibrary Arithmetic {\n    function add(uint256 _a, uint256 _b) internal pure returns (uint256) {\n        return _a + _b;\n    }\n}\n\ncontract C {\n    uint256 sum;\n\n    function f() public {\n        sum = Arithmetic.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 Arithmetic {\n    function add(uint256 _a, uint256 _b) internal pure returns (uint256) {\n        return _a + _b;\n    }\n}\n\ncontract C {\n    using Arithmetic for uint256;\n\n    uint256 sum;\n\n    function f(uint256 _a) public {\n        sum = _a.add(3);\n    }\n}\n```\n\n## Units\n\nEther units:\n\n- `wei`\n- `gwei`\n- `ether`\n\nTime units:\n\n- `seconds`\n- `minutes`\n- `hours`\n- `days`\n- `weeks`\n\n```solidity\nuint256 public oneEther = 1 ether;\nuint256 public oneMinute = 1 minutes;\n```\n\n> Time units are simple suffixes for readability. Older examples may include `years`, but that is not supported in the current version of Solidity.\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- Custom errors can also be used with `revert MyError(...)`\n\n### Custom Errors\n\nCustom errors are a gas-efficient way to return structured failure information.\n\n```solidity\naddress owner;\n\nerror Unauthorized(address caller);\n\nfunction adminOnly() public view {\n    if (msg.sender != owner) revert Unauthorized(msg.sender);\n}\n```\n\n```solidity\nerror SendFailed();\n\nfunction sendHalf(address payable addr) public payable returns (uint256 balance) {\n    require(msg.value % 2 == 0, \"Only allow even numbers\");\n    uint256 balanceBeforeTransfer = address(this).balance;\n\n    (bool success, ) = addr.call{value: msg.value \u002F 2}(\"\");\n    if (!success) revert SendFailed();\n\n    assert(address(this).balance == balanceBeforeTransfer - msg.value \u002F 2);\n    return address(this).balance;\n}\n```\n\n> Catching exceptions is possible using `try\u002Fcatch` for external calls and contract creation.\n\n### Try \u002F Catch\n\n`try\u002Fcatch` can be used with external function calls and contract creation.\n\n```solidity\ntry otherContract.doWork() returns (uint256 value) {\n    return value;\n} catch {\n    revert(\"external call failed\");\n}\n```\n\n## Global variables\n\n### Block variables\n\n- `blockhash(uint256 blockNumber) returns (bytes32)`: hash of the given block - only works for the 256 most recent blocks excluding current\n- `block.coinbase (address)`: current block validator or miner address\n- `block.gaslimit (uint256)`: current block gaslimit\n- `block.number (uint256)`: current block number\n- `block.timestamp (uint256)`: current block timestamp as seconds since unix epoch\n- `block.chainid (uint256)`: current chain id\n- `block.basefee (uint256)`: current block base fee\n- `block.prevrandao (uint256)`: randomness value provided by the beacon chain\n\n### Transaction variables\n\n- `msg.data (bytes)`: complete calldata\n- `gasleft() returns (uint256)`: 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 (uint256)`: number of wei sent with the message\n- `tx.gasprice (uint256)`: 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(uint256 x, uint256 y, uint256 k) returns (uint256)`:\n   compute `(x + y) % k` where the addition is performed with arbitrary precision and does not wrap around at `2**256`.\n- `mulmod(uint256 x, uint256 y, uint256 k) returns (uint256)`:\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 arguments\n- `sha256(...) returns (bytes32)`:\n   compute the SHA-256 hash of the arguments\n- `ripemd160(...) returns (bytes20)`:\n   compute RIPEMD-160 hash of the 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\n\n> Older examples may use `sha3(...)`. In recent versions of Solidity use `keccak256(...)`.\n\n### Contract Related\n\n- `this (current contract's type)`: the current contract, explicitly convertible to Address\n- `address(this).balance (uint256)`: balance of the current contract in Wei\n- `selfdestruct(address payable recipient)`: destroy the current contract, sending its funds to the given Address. Use with caution.\n\n> Older examples may use `now` and `suicide`. In recent versions of Solidity use `block.timestamp` and `selfdestruct`.\n","该项目是一个Solidity速查表和最佳实践指南，旨在帮助开发者为以太坊编写智能合约。核心功能包括提供详细的语法、类型系统、控制结构、函数定义等Solidity编程语言的关键概念与用法，并涵盖了智能合约开发中常见的陷阱及优化建议。技术特点上，它不仅列举了Solidity的基础知识，还深入讲解了一些高级特性如委托调用、错误处理机制等。适合于已有一定基础但希望快速查阅Solidity相关知识点或寻找代码示例的区块链开发者使用，在实际项目开发过程中能够作为非常实用的参考手册。",2,"2026-06-11 03:29:19","top_topic"]