Solidity Ref

Solidity Ref

June 2, 2021

Language that targets the EVM.

Basic template

pragma solidity __version__

contract NameOfContract {
	// state variables

	// public makes accessible from other contracts (like a global variable on the chain)

	// event can react from a trigger

	// error provide info on why fail

	// functions

	// fallback function if anything is called
}

General

  • constructor called at beginning
  • msg is a global variable
    • Can check whether msg.sender is another smart contract

State variables

  • mapping is hash table

  • constant state variable cannot be changed

Function types

  • payable for sending ether
  • view cannot mutate state variables
  • pure more strict cannot view
    • can’t really be enforced
  • public can be called anywhere
  • external cannot be called internally, only externally
  • internal can only be used within, base/derived
  • private only contract

Events

  • event publish events out to the blockchain log
// define event
event Approval(address indexed owner, address indexed spender, uint256 value);
// emit event
emit Approval(msg.sender, spender, value);

require() is like assert, function will fail at transaction time (there is now compile-time, transaction time, run-time)

At beginning of function:

function lockInGuess(uint8 n) public payable {
        require(guesser == 0);
  • selfdestruct(address)
    • call it to destroy contract and send remaining ether to you

Fallback function

  • called when non-existent function called on contract

  • marked external

  • can’t return anything, only has one

  • no name

  • also for receiving, just add payable to it.

  • if call transfer is called, fallback automatically called

function() external payable {}

Interfaces

interface IName {
    function approve(address spender, uint256 value) public;
}
  • can be used to call functions on an existing contract (without using all the behavior, just the signature).
  • also for inheritance and implementation of functions
Contract Test is CalculatorInterface {

Call contract from contract

address active_contract_addr = 0x601E749eED9def332E6d814b233eca7B400D1342;

interface ActiveContract {

}

function approve2(address spender, uint256 value) public {
    ActiveContract ac = ActiveContract(active_contract_addr)

base function virtual means can be overriden,

override means its overridden

Memory vs storage memory like RAM, wiped storage remains

ABI

  • encode and decode (seralize) contracts

More resources