Anatomy of smart contracts
Última edición: , Invalid DateTime
A smart contract is a program that runs at an address on Ethereum. They're made up of data and functions that can execute upon receiving a transaction. Here's an overview of what makes up a smart contract.
Prerequisites
Make sure you've read about smart contracts first. This document assumes you're already familiar with programming languages such as JavaScript or Python.
Data
Any contract data must be assigned to a location: either to storage
or memory
. It's costly to modify storage in a smart contract so you need to consider where your data should live.
Storage
Persistent data is referred to as storage and is represented by state variables. These values get stored permanently on the blockchain. You need to declare the type so that the contract can keep track of how much storage on the blockchain it needs when it compiles.
1// Solidity example2contract SimpleStorage {3 uint storedData; // State variable4 // ...5}6Copiar
1# Vyper example2storedData: int1283Copiar
If you've already programmed object-oriented languages, you'll likely be familiar with most types. However address
should be new to you if you're new to Ethereum development.
An address
type can hold an Ethereum address which equates to 20 bytes or 160 bits. It returns in hexadecimal notation with a leading 0x.
Other types include:
- boolean
- integer
- fixed point numbers
- fixed-size byte arrays
- dynamically-sized byte arrays
- Rational and integer literals
- String literals
- Hexadecimal literals
- Enums
For more explanation, take a look at the docs:
Memory
Values that are only stored for the lifetime of a contract function's execution are called memory variables. Since these are not stored permanently on the blockchain, they are much cheaper to use.
Learn more about how the EVM stores data (Storage, Memory, and the Stack) in the Solidity docs(opens in a new tab).
Environment variables
In addition to the variables you define on your contract, there are some special global variables. They are primarily used to provide information about the blockchain or current transaction.
Examples:
Prop | State variable | Description |
---|---|---|
block.timestamp | uint256 | Current block epoch timestamp |
msg.sender | address | Sender of the message (current call) |
Functions
In the most simplistic terms, functions can get information or set information in response to incoming transactions.
There are two types of function calls:
internal
– these don't create an EVM call- Internal functions and state variables can only be accessed internally (i.e. from within the current contract or contracts deriving from it)
external
– these do create an EVM call- External functions are part of the contract interface, which means they can be called from other contracts and via transactions. An external function
f
cannot be called internally (i.e.f()
does not work, butthis.f()
works).
- External functions are part of the contract interface, which means they can be called from other contracts and via transactions. An external function
They can also be public
or private
public
functions can be called internally from within the contract or externally via messagesprivate
functions are only visible for the contract they are defined in and not in derived contracts
Both functions and state variables can be made public or private
Here's a function for updating a state variable on a contract:
1// Solidity example2function update_name(string value) public {3 dapp_name = value;4}5Copiar
- The parameter
value
of typestring
is passed into the function:update_name
- It's declared
public
, meaning anyone can access it - It's not declared
view
, so it can modify the contract state
View functions
These functions promise not to modify the state of the contract's data. Common examples are "getter" functions – you might use this to receive a user's balance for example.
1// Solidity example2function balanceOf(address _owner) public view returns (uint256 _balance) {3 return ownerPizzaCount[_owner];4}5Copiar
1dappName: public(string)23@view4@public5def readName() -> string:6 return dappName7Copiar
What is considered modifying state:
- Writing to state variables.
- Emitting events(opens in a new tab).
- Creating other contracts(opens in a new tab).
- Using
selfdestruct
. - Sending ether via calls.
- Calling any function not marked
view
orpure
. - Using low-level calls.
- Using inline assembly that contains certain opcodes.
Constructor functions
constructor
functions are only executed once when the contract is first deployed. Like constructor
in many class-based programming languages, these functions often initialize state variables to their specified values.
1// Solidity example2// Initializes the contract's data, setting the `owner`3// to the address of the contract creator.4constructor() public {5 // All smart contracts rely on external transactions to trigger its functions.6 // `msg` is a global variable that includes relevant data on the given transaction,7 // such as the address of the sender and the ETH value included in the transaction.8 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/units-and-global-variables.html#block-and-transaction-properties9 owner = msg.sender;10}11Mostrar todoCopiar
1# Vyper example23@external4def __init__(_beneficiary: address, _bidding_time: uint256):5 self.beneficiary = _beneficiary6 self.auctionStart = block.timestamp7 self.auctionEnd = self.auctionStart + _bidding_time8Copiar
Built-in functions
In addition to the variables and functions you define on your contract, there are some special built-in functions. The most obvious example is:
address.send()
– Soliditysend(address)
– Vyper
These allow contracts to send ETH to other accounts.
Writing functions
Your function needs:
- parameter variable and type (if it accepts parameters)
- declaration of internal/external
- declaration of pure/view/payable
- returns type (if it returns a value)
1pragma solidity >=0.4.0 <=0.6.0;23contract ExampleDapp {4 string dapp_name; // state variable56 // Called when the contract is deployed and initializes the value7 constructor() public {8 dapp_name = "My Example dapp";9 }1011 // Get Function12 function read_name() public view returns(string) {13 return dapp_name;14 }1516 // Set Function17 function update_name(string value) public {18 dapp_name = value;19 }20}21Mostrar todoCopiar
A complete contract might look something like this. Here the constructor
function provides an initial value for the dapp_name
variable.
Events and logs
Events let you communicate with your smart contract from your frontend or other subscribing applications. When a transaction is mined, smart contracts can emit events and write logs to the blockchain that the frontend can then process.
Annotated examples
These are some examples written in Solidity. If you'd like to play with the code, you can interact with them in Remix(opens in a new tab)