2015-12-07 20:16:25 +00:00
.. index :: ! contract
2018-06-19 19:32:03 +00:00
.. _contracts:
2015-12-07 20:16:25 +00:00
##########
Contracts
##########
2016-09-05 14:29:08 +00:00
Contracts in Solidity are similar to classes in object-oriented languages. They
2016-03-10 19:53:13 +00:00
contain persistent data in state variables and functions that can modify these
variables. Calling a function on a different contract (instance) will perform
an EVM function call and thus switch the context such that state variables are
inaccessible.
2015-12-07 20:16:25 +00:00
2017-07-28 05:24:19 +00:00
.. index :: ! contract;creation, constructor
2015-12-07 20:16:25 +00:00
***** ***** ***** ***
Creating Contracts
***** ***** ***** ***
2017-09-13 08:49:19 +00:00
Contracts can be created "from outside" via Ethereum transactions or from within Solidity contracts.
IDEs, such as `Remix <https://remix.ethereum.org/> `_ , make the creation process seamless using UI elements.
2018-07-10 07:17:33 +00:00
Creating contracts programmatically on Ethereum is best done via using the JavaScript API `web3.js <https://github.com/ethereum/web3.js> `_ .
2017-09-13 08:49:19 +00:00
As of today it has a method called `web3.eth.Contract <https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#new-contract> `_
to facilitate contract creation.
2018-05-05 21:45:14 +00:00
When a contract is created, its constructor (a function declared with the
`` constructor `` keyword) is executed once.
2017-05-03 17:24:00 +00:00
A constructor is optional. Only one constructor is allowed, and this means
2016-10-15 22:04:01 +00:00
overloading is not supported.
2015-12-07 20:16:25 +00:00
.. index :: constructor;arguments
2017-09-13 08:49:19 +00:00
Internally, constructor arguments are passed :ref: `ABI encoded <ABI>` after the code of
the contract itself, but you do not have to care about this if you use `` web3.js `` .
2015-12-07 20:16:25 +00:00
If a contract wants to create another contract, the source code
(and the binary) of the created contract has to be known to the creator.
This means that cyclic creation dependencies are impossible.
::
2018-04-06 12:13:58 +00:00
pragma solidity ^0.4.22;
2016-09-05 11:54:54 +00:00
2015-12-07 20:16:25 +00:00
contract OwnedToken {
2015-12-30 09:53:41 +00:00
// TokenCreator is a contract type that is defined below.
// It is fine to reference it as long as it is not used
// to create a new contract.
TokenCreator creator;
address owner;
bytes32 name;
2016-05-05 18:58:02 +00:00
2015-12-30 09:53:41 +00:00
// This is the constructor which registers the
// creator and the assigned name.
2018-03-02 15:44:35 +00:00
constructor(bytes32 _name) public {
2016-09-05 14:29:08 +00:00
// State variables are accessed via their name
// and not via e.g. this.owner. This also applies
// to functions and especially in the constructors,
2017-07-27 05:46:53 +00:00
// you can only call them like that ("internally"),
2016-09-05 14:29:08 +00:00
// because the contract itself does not exist yet.
2015-12-30 09:53:41 +00:00
owner = msg.sender;
// We do an explicit type conversion from `address`
// to `TokenCreator` and assume that the type of
// the calling contract is TokenCreator, there is
// no real way to check that.
creator = TokenCreator(msg.sender);
name = _name;
}
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function changeName(bytes32 newName) public {
2015-12-30 09:53:41 +00:00
// Only the creator can alter the name --
// the comparison is possible since contracts
// are implicitly convertible to addresses.
2016-07-27 07:27:56 +00:00
if (msg.sender == address(creator))
2016-05-11 19:30:31 +00:00
name = newName;
2015-12-30 09:53:41 +00:00
}
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function transfer(address newOwner) public {
2015-12-30 09:53:41 +00:00
// Only the current owner can transfer the token.
if (msg.sender != owner) return;
// We also want to ask the creator if the transfer
// is fine. Note that this calls a function of the
// contract defined below. If the call fails (e.g.
// due to out-of-gas), the execution here stops
// immediately.
if (creator.isTokenTransferOK(owner, newOwner))
owner = newOwner;
}
2015-12-07 20:16:25 +00:00
}
contract TokenCreator {
2015-12-30 09:53:41 +00:00
function createToken(bytes32 name)
2017-12-12 18:47:30 +00:00
public
2015-12-07 20:16:25 +00:00
returns (OwnedToken tokenAddress)
2015-12-30 09:53:41 +00:00
{
// Create a new Token contract and return its address.
// From the JavaScript side, the return type is simply
2017-12-20 09:48:22 +00:00
// `address` , as this is the closest type available in
2015-12-30 09:53:41 +00:00
// the ABI.
return new OwnedToken(name);
}
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function changeName(OwnedToken tokenAddress, bytes32 name) public {
2017-12-20 09:48:22 +00:00
// Again, the external type of `tokenAddress` is
// simply `address` .
2015-12-30 09:53:41 +00:00
tokenAddress.changeName(name);
}
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function isTokenTransferOK(address currentOwner, address newOwner)
public
view
returns (bool ok)
{
2015-12-30 09:53:41 +00:00
// Check some arbitrary condition.
address tokenAddress = msg.sender;
2018-06-13 15:49:41 +00:00
return (keccak256(abi.encodePacked(newOwner)) & 0xff) == (bytes20(tokenAddress) & 0xff);
2015-12-30 09:53:41 +00:00
}
2015-12-07 20:16:25 +00:00
}
.. index :: ! visibility, external, public, private, internal
2017-02-02 23:52:34 +00:00
.. _visibility-and-getters:
2015-12-21 15:54:32 +00:00
2017-02-02 23:52:34 +00:00
***** ***** ***** ***** **
Visibility and Getters
***** ***** ***** ***** **
2015-12-07 20:16:25 +00:00
Since Solidity knows two kinds of function calls (internal
ones that do not create an actual EVM call (also called
a "message call") and external
ones that do), there are four types of visibilities for
functions and state variables.
2018-07-04 16:04:44 +00:00
Functions have to be specified as being `` external `` ,
`` public `` , `` internal `` or `` private `` .
For state variables, `` external `` is not possible.
2015-12-07 20:16:25 +00:00
2016-05-24 17:57:36 +00:00
`` external `` :
2015-12-07 20:16:25 +00:00
External functions are part of the contract
interface, which means they can be called from other contracts and
2016-05-24 17:57:36 +00:00
via transactions. An external function `` f `` cannot be called
internally (i.e. `` f() `` does not work, but `` this.f() `` works).
2015-12-07 20:16:25 +00:00
External functions are sometimes more efficient when
they receive large arrays of data.
2016-05-24 17:57:36 +00:00
`` public `` :
2015-12-07 20:16:25 +00:00
Public functions are part of the contract
interface and can be either called internally or via
2017-02-02 23:52:34 +00:00
messages. For public state variables, an automatic getter
2015-12-07 20:16:25 +00:00
function (see below) is generated.
2016-05-24 17:57:36 +00:00
`` internal `` :
2015-12-07 20:16:25 +00:00
Those functions and state variables can only be
accessed internally (i.e. from within the current contract
2016-05-24 17:57:36 +00:00
or contracts deriving from it), without using `` this `` .
2015-12-07 20:16:25 +00:00
2016-05-24 17:57:36 +00:00
`` private `` :
2015-12-07 20:16:25 +00:00
Private functions and state variables are only
visible for the contract they are defined in and not in
derived contracts.
2015-12-14 15:22:32 +00:00
.. note ::
Everything that is inside a contract is visible to
2016-05-24 17:57:36 +00:00
all external observers. Making something `` private ``
2016-08-18 11:16:01 +00:00
only prevents other contracts from accessing and modifying
2015-12-14 15:22:32 +00:00
the information, but it will still be visible to the
whole world outside of the blockchain.
2015-12-07 20:16:25 +00:00
The visibility specifier is given after the type for
state variables and between parameter list and
return parameter list for functions.
::
2017-12-12 18:47:30 +00:00
pragma solidity ^0.4.16;
2016-09-05 11:54:54 +00:00
2016-05-18 15:11:39 +00:00
contract C {
2017-12-12 18:47:30 +00:00
function f(uint a) private pure returns (uint b) { return a + 1; }
2015-12-30 09:53:41 +00:00
function setData(uint a) internal { data = a; }
uint public data;
2015-12-07 20:16:25 +00:00
}
2016-08-25 17:57:56 +00:00
In the following example, `` D `` , can call `` c.getData() `` to retrieve the value of
`` data `` in state storage, but is not able to call `` f `` . Contract `` E `` is derived from
`` C `` and, thus, can call `` compute `` .
2016-08-25 08:43:17 +00:00
::
2017-07-10 22:07:27 +00:00
// This will not compile
2016-09-05 11:54:54 +00:00
pragma solidity ^0.4.0;
2016-08-25 08:43:17 +00:00
contract C {
2016-08-25 17:57:56 +00:00
uint private data;
2018-06-03 09:25:52 +00:00
function f(uint a) private pure returns(uint b) { return a + 1; }
2017-12-12 18:47:30 +00:00
function setData(uint a) public { data = a; }
2018-06-04 12:00:55 +00:00
function getData() public view returns(uint) { return data; }
2018-06-03 09:25:52 +00:00
function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
2016-08-25 08:43:17 +00:00
}
2016-08-19 14:47:57 +00:00
contract D {
2017-12-12 18:47:30 +00:00
function readData() public {
2016-08-25 19:44:16 +00:00
C c = new C();
2017-12-20 09:48:22 +00:00
uint local = c.f(7); // error: member `f` is not visible
2016-08-25 19:44:16 +00:00
c.setData(3);
2016-08-25 17:57:56 +00:00
local = c.getData();
2017-12-20 09:48:22 +00:00
local = c.compute(3, 5); // error: member `compute` is not visible
2016-08-25 19:44:16 +00:00
}
2016-08-25 08:43:17 +00:00
}
contract E is C {
2017-12-12 18:47:30 +00:00
function g() public {
2016-08-25 19:44:16 +00:00
C c = new C();
2017-11-29 19:21:21 +00:00
uint val = compute(3, 5); // access to internal member (from derived to parent contract)
2016-08-18 11:16:01 +00:00
}
}
2015-12-07 20:16:25 +00:00
2017-02-02 23:52:34 +00:00
.. index :: ! getter;function, ! function;getter
2017-07-28 01:30:53 +00:00
.. _getter-functions:
2015-12-07 20:16:25 +00:00
2017-02-02 23:52:34 +00:00
Getter Functions
================
2015-12-07 20:16:25 +00:00
2017-02-02 23:52:34 +00:00
The compiler automatically creates getter functions for
2016-09-05 14:29:08 +00:00
all **public** state variables. For the contract given below, the compiler will
2016-08-18 11:16:01 +00:00
generate a function called `` data `` that does not take any
arguments and returns a `` uint `` , the value of the state
2016-05-24 17:57:36 +00:00
variable `` data `` . The initialization of state variables can
2015-12-07 20:16:25 +00:00
be done at declaration.
2016-08-25 08:43:17 +00:00
::
2016-09-05 11:54:54 +00:00
pragma solidity ^0.4.0;
2016-08-25 08:43:17 +00:00
contract C {
uint public data = 42;
}
2016-08-25 19:44:16 +00:00
2016-08-25 08:43:17 +00:00
contract Caller {
2016-08-25 19:44:16 +00:00
C c = new C();
2017-12-12 18:47:30 +00:00
function f() public {
2016-08-25 19:44:16 +00:00
uint local = c.data();
}
2016-08-25 08:43:17 +00:00
}
2017-02-02 23:52:34 +00:00
The getter functions have external visibility. If the
2016-05-24 17:57:36 +00:00
symbol is accessed internally (i.e. without `` this. `` ),
2017-05-03 17:24:00 +00:00
it is evaluated as a state variable. If it is accessed externally
2016-08-25 17:57:56 +00:00
(i.e. with `` this. `` ), it is evaluated as a function.
2015-12-07 20:16:25 +00:00
::
2016-09-05 11:54:54 +00:00
pragma solidity ^0.4.0;
2016-08-25 08:43:17 +00:00
contract C {
2016-08-25 19:44:16 +00:00
uint public data;
2017-12-12 18:47:30 +00:00
function x() public {
2016-08-25 19:44:16 +00:00
data = 3; // internal access
uint val = this.data(); // external access
}
2015-12-07 20:16:25 +00:00
}
The next example is a bit more complex:
::
2016-09-05 11:54:54 +00:00
pragma solidity ^0.4.0;
2016-05-18 15:11:39 +00:00
contract Complex {
2016-05-11 19:30:31 +00:00
struct Data {
uint a;
bytes3 b;
mapping (uint => uint) map;
}
mapping (uint => mapping(bool => Data[])) public data;
2015-12-07 20:16:25 +00:00
}
It will generate a function of the following form::
2017-12-12 18:47:30 +00:00
function data(uint arg1, bool arg2, uint arg3) public returns (uint a, bytes3 b) {
2015-12-30 09:53:41 +00:00
a = data[arg1][arg2][arg3].a;
b = data[arg1][arg2][arg3].b;
2015-12-07 20:16:25 +00:00
}
Note that the mapping in the struct is omitted because there
is no good way to provide the key for the mapping.
.. index :: ! function;modifier
2015-12-21 15:54:32 +00:00
.. _modifiers:
2015-12-07 20:16:25 +00:00
***** ***** ***** ***
Function Modifiers
***** ***** ***** ***
2017-05-03 17:24:00 +00:00
Modifiers can be used to easily change the behaviour of functions. For example,
they can automatically check a condition prior to executing the function. Modifiers are
2015-12-07 20:16:25 +00:00
inheritable properties of contracts and may be overridden by derived contracts.
::
2018-07-02 15:02:17 +00:00
pragma solidity >0.4.24;
2016-09-05 11:54:54 +00:00
2015-12-07 20:16:25 +00:00
contract owned {
2018-07-02 14:25:54 +00:00
constructor() public { owner = msg.sender; }
2015-12-30 09:53:41 +00:00
address owner;
// This contract only defines a modifier but does not use
2017-12-20 09:48:22 +00:00
// it: it will be used in derived contracts.
2015-12-30 09:53:41 +00:00
// The function body is inserted where the special symbol
2017-12-20 09:48:22 +00:00
// `_;` in the definition of a modifier appears.
2015-12-30 09:53:41 +00:00
// This means that if the owner calls this function, the
// function is executed and otherwise, an exception is
// thrown.
2016-05-18 15:11:39 +00:00
modifier onlyOwner {
2018-01-03 14:30:01 +00:00
require(
msg.sender == owner,
"Only owner can call this function."
);
2016-09-05 12:54:50 +00:00
_;
2016-05-11 19:30:31 +00:00
}
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract mortal is owned {
2017-12-20 09:48:22 +00:00
// This contract inherits the `onlyOwner` modifier from
// `owned` and applies it to the `close` function, which
// causes that calls to `close` only have an effect if
2015-12-30 09:53:41 +00:00
// they are made by the stored owner.
2017-12-12 18:47:30 +00:00
function close() public onlyOwner {
2015-12-30 09:53:41 +00:00
selfdestruct(owner);
}
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract priced {
2015-12-30 09:53:41 +00:00
// Modifiers can receive arguments:
2016-05-11 19:30:31 +00:00
modifier costs(uint price) {
if (msg.value >= price) {
2016-09-05 12:54:50 +00:00
_;
2016-05-11 19:30:31 +00:00
}
}
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract Register is priced, owned {
2015-12-30 09:53:41 +00:00
mapping (address => bool) registeredAddresses;
uint price;
2016-05-11 19:30:31 +00:00
2018-07-02 14:25:54 +00:00
constructor(uint initialPrice) public { price = initialPrice; }
2016-05-11 19:30:31 +00:00
2016-09-05 14:29:08 +00:00
// It is important to also provide the
2017-12-20 09:48:22 +00:00
// `payable` keyword here, otherwise the function will
2016-09-05 14:29:08 +00:00
// automatically reject all Ether sent to it.
2017-12-12 18:47:30 +00:00
function register() public payable costs(price) {
2015-12-30 09:53:41 +00:00
registeredAddresses[msg.sender] = true;
}
2016-05-11 19:30:31 +00:00
2017-12-12 18:47:30 +00:00
function changePrice(uint _price) public onlyOwner {
2015-12-30 09:53:41 +00:00
price = _price;
}
2015-12-07 20:16:25 +00:00
}
2016-08-06 12:48:59 +00:00
contract Mutex {
bool locked;
modifier noReentrancy() {
2018-01-03 14:30:01 +00:00
require(
!locked,
"Reentrant call."
);
2016-08-06 12:48:59 +00:00
locked = true;
2016-09-05 12:54:50 +00:00
_;
2016-08-06 12:48:59 +00:00
locked = false;
}
/// This function is protected by a mutex, which means that
2017-12-20 09:48:22 +00:00
/// reentrant calls from within `msg.sender.call` cannot call `f` again.
2016-08-06 12:48:59 +00:00
/// The `return 7` statement assigns 7 to the return value but still
/// executes the statement `locked = false` in the modifier.
2017-12-12 18:47:30 +00:00
function f() public noReentrancy returns (uint) {
2018-06-13 15:49:41 +00:00
require(msg.sender.call(""));
2016-08-06 12:48:59 +00:00
return 7;
}
}
2017-05-03 17:24:00 +00:00
Multiple modifiers are applied to a function by specifying them in a
whitespace-separated list and are evaluated in the order presented.
2016-08-06 12:48:59 +00:00
.. warning ::
In an earlier version of Solidity, `` return `` statements in functions
having modifiers behaved differently.
Explicit returns from a modifier or function body only leave the current
modifier or function body. Return variables are assigned and
control flow continues after the "_" in the preceding modifier.
Arbitrary expressions are allowed for modifier arguments and in this context,
all symbols visible from the function are visible in the modifier. Symbols
introduced in the modifier are not visible in the function (as they might
change by overriding).
2015-12-07 20:16:25 +00:00
.. index :: ! constant
2016-10-15 21:34:35 +00:00
***** ***** ***** ***** *** *
Constant State Variables
***** ***** ***** ***** *** *
2015-12-07 20:16:25 +00:00
2017-03-13 12:29:34 +00:00
State variables can be declared as `` constant `` . In this case, they have to be
assigned from an expression which is a constant at compile time. Any expression
2018-07-05 12:32:32 +00:00
that accesses storage, blockchain data (e.g. `` now `` , `` address(this).balance `` or
2017-03-13 12:29:34 +00:00
`` block.number `` ) or
2018-03-05 15:59:33 +00:00
execution data (`` msg.value `` or `` gasleft() `` ) or make calls to external contracts are disallowed. Expressions
2017-03-09 13:39:30 +00:00
that might have a side-effect on memory allocation are allowed, but those that
2017-03-13 12:29:34 +00:00
might have a side-effect on other memory objects are not. The built-in functions
`` keccak256 `` , `` sha256 `` , `` ripemd160 `` , `` ecrecover `` , `` addmod `` and `` mulmod ``
2017-03-27 04:19:08 +00:00
are allowed (even though they do call external contracts).
2017-03-13 12:29:34 +00:00
The reason behind allowing side-effects on the memory allocator is that it
should be possible to construct complex objects like e.g. lookup-tables.
This feature is not yet fully usable.
2017-03-09 13:39:30 +00:00
2017-05-03 17:24:00 +00:00
The compiler does not reserve a storage slot for these variables, and every occurrence is
2017-03-13 12:29:34 +00:00
replaced by the respective constant expression (which might be computed to a single value by the optimizer).
2015-12-07 20:16:25 +00:00
2017-03-03 18:26:54 +00:00
Not all types for constants are implemented at this time. The only supported types are
value types and strings.
2015-12-07 20:16:25 +00:00
::
2016-09-05 11:54:54 +00:00
pragma solidity ^0.4.0;
2015-12-07 20:16:25 +00:00
contract C {
2015-12-30 09:53:41 +00:00
uint constant x = 32**22 + 8;
string constant text = "abc";
2017-03-02 13:41:51 +00:00
bytes32 constant myHash = keccak256("abc");
2015-12-07 20:16:25 +00:00
}
2017-11-21 11:01:59 +00:00
.. index :: ! functions
.. _functions:
***** *** *
Functions
***** *** *
.. index :: ! view function, function;view
2015-12-07 20:16:25 +00:00
2017-08-21 22:41:46 +00:00
.. _view-functions:
2017-06-12 16:33:23 +00:00
2017-08-21 22:41:46 +00:00
View Functions
2017-11-21 11:01:59 +00:00
==============
2016-10-15 21:34:35 +00:00
2017-08-21 22:41:46 +00:00
Functions can be declared `` view `` in which case they promise not to modify the state.
2016-10-15 21:34:35 +00:00
2018-07-04 14:29:52 +00:00
.. note ::
If the compiler's EVM target is Byzantium or newer (default) the opcode
`` STATICCALL `` is used.
2017-08-25 10:12:26 +00:00
The following statements are considered modifying the state:
#. Writing to state variables.
2017-12-20 09:48:22 +00:00
#. :ref: `Emitting events <events>` .
2017-08-25 10:12:26 +00:00
#. :ref: `Creating other contracts <creating-contracts>` .
#. Using `` selfdestruct `` .
#. Sending Ether via calls.
#. Calling any function not marked `` view `` or `` pure `` .
#. Using low-level calls.
#. Using inline assembly that contains certain opcodes.
2016-10-15 21:34:35 +00:00
::
2018-07-04 14:29:52 +00:00
pragma solidity >0.4.24;
2016-10-15 21:34:35 +00:00
contract C {
2017-12-12 18:47:30 +00:00
function f(uint a, uint b) public view returns (uint) {
2017-08-16 19:51:47 +00:00
return a * (b + 42) + now;
2016-10-15 21:34:35 +00:00
}
}
.. note ::
2018-05-08 11:08:22 +00:00
`` constant `` on functions used to be an alias to `` view `` , but this was dropped in version 0.5.0.
2017-08-21 22:41:46 +00:00
.. note ::
Getter methods are marked `` view `` .
2016-10-15 21:34:35 +00:00
2018-01-16 09:31:13 +00:00
.. note ::
2018-07-04 14:29:52 +00:00
Prior to version 0.5.0, the compiler did not use the `` STATICCALL `` opcode
for `` view `` functions.
This enabled state modifications in `` view `` functions through the use of
invalid explicit type conversions.
By using `` STATICCALL `` for `` view `` functions, modifications to the
state are prevented on the level of the EVM.
2018-01-16 09:31:13 +00:00
2017-11-21 11:01:59 +00:00
.. index :: ! pure function, function;pure
2017-08-16 19:51:47 +00:00
.. _pure-functions:
Pure Functions
2017-11-21 11:01:59 +00:00
==============
2017-08-16 19:51:47 +00:00
Functions can be declared `` pure `` in which case they promise not to read from or modify the state.
2018-07-04 14:29:52 +00:00
.. note ::
If the compiler's EVM target is Byzantium or newer (default) the opcode `` STATICCALL `` is used.
2017-08-25 10:12:26 +00:00
In addition to the list of state modifying statements explained above, the following are considered reading from the state:
2017-08-28 10:35:18 +00:00
2017-08-25 10:12:26 +00:00
#. Reading from state variables.
2018-07-05 12:32:32 +00:00
#. Accessing `` address(this).balance `` or `` <address>.balance `` .
2017-08-25 10:12:26 +00:00
#. Accessing any of the members of `` block `` , `` tx `` , `` msg `` (with the exception of `` msg.sig `` and `` msg.data `` ).
#. Calling any function not marked `` pure `` .
#. Using inline assembly that contains certain opcodes.
2017-08-16 19:51:47 +00:00
::
2018-07-04 14:29:52 +00:00
pragma solidity >0.4.24;
2017-08-16 19:51:47 +00:00
contract C {
2017-12-12 18:47:30 +00:00
function f(uint a, uint b) public pure returns (uint) {
2017-08-16 19:51:47 +00:00
return a * (b + 42);
}
}
2018-01-16 09:31:13 +00:00
.. note ::
2018-07-04 14:29:52 +00:00
Prior to version 0.5.0, the compiler did not use the `` STATICCALL `` opcode
for `` pure `` functions.
This enabled state modifications in `` pure `` functions through the use of
invalid explicit type conversions.
By using `` STATICCALL `` for `` pure `` functions, modifications to the
state are prevented on the level of the EVM.
2018-01-16 09:31:13 +00:00
.. warning ::
It is not possible to prevent functions from reading the state at the level
of the EVM, it is only possible to prevent them from writing to the state
(i.e. only `` view `` can be enforced at the EVM level, `` pure `` can not).
2018-05-28 00:58:58 +00:00
It is a non-circumventable runtime checks done by the EVM.
2018-01-16 09:31:13 +00:00
2017-08-16 19:51:47 +00:00
.. warning ::
2018-07-03 09:02:20 +00:00
Before version 0.4.17 the compiler did not enforce that `` pure `` is not reading the state.
2018-05-28 00:58:58 +00:00
It is a compile-time type check, which can be circumvented doing invalid explicit conversions
between contract types, because the compiler can verify that the type of the contract does
not do state-changing operations, but it cannot check that the contract that will be called
at runtime is actually of that type.
2017-08-16 19:51:47 +00:00
2018-07-03 09:02:20 +00:00
.. warning ::
Before version 0.5.0 the compiler did not enforce that `` view `` is not writing the state.
2015-12-07 20:16:25 +00:00
.. index :: ! fallback function, function;fallback
.. _fallback-function:
Fallback Function
2017-11-21 11:01:59 +00:00
=================
2015-12-07 20:16:25 +00:00
A contract can have exactly one unnamed function. This function cannot have
2018-06-28 16:08:45 +00:00
arguments, cannot return anything and has to have `` external `` visibility.
2016-08-25 11:25:30 +00:00
It is executed on a call to the contract if none of the other
2017-05-03 17:24:00 +00:00
functions match the given function identifier (or if no data was supplied at
2015-12-07 20:16:25 +00:00
all).
Furthermore, this function is executed whenever the contract receives plain
2017-08-30 01:31:54 +00:00
Ether (without data). Additionally, in order to receive Ether, the fallback function
must be marked `` payable `` . If no such function exists, the contract cannot receive
Ether through regular transactions.
2018-08-01 11:32:26 +00:00
In the worst case, the fallback function can only rely on 2300 gas being
available (for example when `send` or `transfer` is used), leaving little
room to perform other operations except basic logging. The following operations
will consume more gas than the 2300 gas stipend:
2018-03-02 12:40:17 +00:00
- Writing to storage
- Creating a contract
- Calling an external function which consumes a large amount of gas
- Sending Ether
2015-12-07 20:16:25 +00:00
2018-03-02 05:25:52 +00:00
Like any function, the fallback function can execute complex operations as long as there is enough gas passed on to it.
2016-08-25 19:43:04 +00:00
2017-08-30 01:31:54 +00:00
.. note ::
Even though the fallback function cannot have arguments, one can still use `` msg.data `` to retrieve
any payload supplied with the call.
2016-08-26 15:00:26 +00:00
.. warning ::
2017-06-13 17:08:13 +00:00
Contracts that receive Ether directly (without a function call, i.e. using `` send `` or `` transfer `` )
but do not define a fallback function
2016-08-30 13:37:10 +00:00
throw an exception, sending back the Ether (this was different
before Solidity v0.4.0). So if you want your contract to receive Ether,
2018-07-05 12:32:32 +00:00
you have to implement a payable fallback function.
2016-08-26 15:00:26 +00:00
2017-08-30 01:31:54 +00:00
.. warning ::
A contract without a payable fallback function can receive Ether as a recipient of a `coinbase transaction` (aka `miner block reward` )
or as a destination of a `` selfdestruct `` .
A contract cannot react to such Ether transfers and thus also cannot reject them. This is a design choice of the EVM and Solidity cannot work around it.
2018-07-05 12:32:32 +00:00
It also means that `` address(this).balance `` can be higher than the sum of some manual accounting implemented in a contract (i.e. having a counter updated in the fallback function).
2017-08-30 01:31:54 +00:00
2015-12-07 20:16:25 +00:00
::
2018-07-05 12:32:32 +00:00
pragma solidity >0.4.24;
2016-09-05 11:54:54 +00:00
2015-12-07 20:16:25 +00:00
contract Test {
2016-09-05 14:29:08 +00:00
// This function is called for all messages sent to
// this contract (there is no other function).
// Sending Ether to this contract will cause an exception,
2017-12-20 09:48:22 +00:00
// because the fallback function does not have the `payable`
2016-09-05 14:29:08 +00:00
// modifier.
2018-06-28 16:08:45 +00:00
function() external { x = 1; }
2015-12-30 09:53:41 +00:00
uint x;
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2016-09-05 14:29:08 +00:00
// This contract keeps all Ether sent to it with no way
// to get it back.
contract Sink {
2018-06-28 16:08:45 +00:00
function() external payable { }
2015-12-07 20:16:25 +00:00
}
contract Caller {
2017-12-12 18:47:30 +00:00
function callTest(Test test) public {
2018-07-05 12:32:32 +00:00
address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
2016-09-05 14:29:08 +00:00
// results in test.x becoming == 1.
2018-07-05 12:32:32 +00:00
// If someone sends ether to that contract,
2017-07-10 22:07:27 +00:00
// the transaction will fail and reject the
// Ether.
2018-07-05 12:32:32 +00:00
address(test).send(2 ether);
2016-05-18 15:05:28 +00:00
}
2015-12-07 20:16:25 +00:00
}
2017-11-21 11:01:59 +00:00
.. index :: ! overload
.. _overload-function:
Function Overloading
====================
A Contract can have multiple functions of the same name but with different arguments.
This also applies to inherited functions. The following example shows overloading of the
`` f `` function in the scope of contract `` A `` .
::
2017-12-12 18:47:30 +00:00
2017-11-21 11:01:59 +00:00
pragma solidity ^0.4.16;
contract A {
function f(uint _in) public pure returns (uint out) {
out = 1;
}
function f(uint _in, bytes32 _key) public pure returns (uint out) {
out = 2;
}
}
Overloaded functions are also present in the external interface. It is an error if two
externally visible functions differ by their Solidity types but not by their external types.
::
// This will not compile
pragma solidity ^0.4.16;
contract A {
function f(B _in) public pure returns (B out) {
out = _in;
}
function f(address _in) public pure returns (address out) {
out = _in;
}
}
contract B {
}
Both `` f `` function overloads above end up accepting the address type for the ABI although
they are considered different inside Solidity.
Overload resolution and Argument matching
-----------------------------------------
Overloaded functions are selected by matching the function declarations in the current scope
to the arguments supplied in the function call. Functions are selected as overload candidates
if all arguments can be implicitly converted to the expected types. If there is not exactly one
candidate, resolution fails.
.. note ::
Return parameters are not taken into account for overload resolution.
::
pragma solidity ^0.4.16;
contract A {
function f(uint8 _in) public pure returns (uint8 out) {
out = _in;
}
function f(uint256 _in) public pure returns (uint256 out) {
out = _in;
}
}
2018-04-03 02:22:38 +00:00
Calling `` f(50) `` would create a type error since `` 50 `` can be implicitly converted both to `` uint8 ``
2017-11-21 11:01:59 +00:00
and `` uint256 `` types. On another hand `` f(256) `` would resolve to `` f(uint256) `` overload as `` 256 `` cannot be implicitly
converted to `` uint8 `` .
2015-12-07 20:16:25 +00:00
.. index :: ! event
2016-02-19 11:05:56 +00:00
.. _events:
2015-12-07 20:16:25 +00:00
***** *
Events
***** *
Events 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.
Events are
inheritable members of contracts. When they are called, they cause the
arguments to be stored in the transaction's log - a special data structure
in the blockchain. These logs are associated with the address of
the contract and will be incorporated into the blockchain
and stay there as long as a block is accessible (forever as of
Frontier and Homestead, but this might change with Serenity). Log and
event data is not accessible from within contracts (not even from
2017-05-03 17:24:00 +00:00
the contract that created them).
2015-12-07 20:16:25 +00:00
SPV proofs for logs are possible, so if an external entity supplies
a contract with such a proof, it can check that the log actually
2017-05-03 17:24:00 +00:00
exists inside the blockchain. But be aware that block headers have to be supplied because
the contract can only see the last 256 block hashes.
2015-12-07 20:16:25 +00:00
Up to three parameters can
2016-05-24 17:57:36 +00:00
receive the attribute `` indexed `` which will cause the respective arguments
2018-06-04 17:29:51 +00:00
to be stored in a special data structure as so-called "topics", which allows them to be searched for,
for example when filtering a sequence of blocks for certain events. Events can always
be filtered by the address of the contract that emitted the event. Also,
the hash of the signature of the event is one of the topics except if you
2016-05-24 17:57:36 +00:00
declared the event with `` anonymous `` specifier. This means that it is
2015-12-07 20:16:25 +00:00
not possible to filter for specific anonymous events by name.
2018-06-04 17:29:51 +00:00
If arrays (including `` string `` and `` bytes `` ) are used as indexed arguments, the
Keccak-256 hash of it is stored as topic instead. This is because a topic
can only hold a single word (32 bytes).
2015-12-07 20:16:25 +00:00
2018-06-04 17:29:51 +00:00
All non-indexed arguments will be :ref: `ABI-encoded <ABI>` into the data part of the log.
2016-09-05 14:29:08 +00:00
2015-12-07 20:16:25 +00:00
::
2018-06-07 19:07:07 +00:00
pragma solidity ^0.4.21;
2016-09-05 11:54:54 +00:00
2015-12-07 20:16:25 +00:00
contract ClientReceipt {
2015-12-30 09:53:41 +00:00
event Deposit(
address indexed _from,
bytes32 indexed _id,
uint _value
);
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function deposit(bytes32 _id) public payable {
2018-02-16 16:32:30 +00:00
// Events are emitted using `emit` , followed by
// the name of the event and the arguments
// (if any) in parentheses. Any such invocation
// (even deeply nested) can be detected from
// the JavaScript API by filtering for `Deposit` .
emit Deposit(msg.sender, _id, msg.value);
2015-12-30 09:53:41 +00:00
}
2015-12-07 20:16:25 +00:00
}
The use in the JavaScript API would be as follows:
::
var abi = /* abi as generated by the compiler * /;
var ClientReceipt = web3.eth.contract(abi);
2017-08-16 09:31:50 +00:00
var clientReceipt = ClientReceipt.at("0x1234...ab67" /* address * /);
2015-12-07 20:16:25 +00:00
var event = clientReceipt.Deposit();
// watch for changes
event.watch(function(error, result){
2015-12-30 09:53:41 +00:00
// result will contain various information
2018-06-03 12:36:54 +00:00
// including the arguments given to the `Deposit`
2015-12-30 09:53:41 +00:00
// call.
if (!error)
console.log(result);
2015-12-07 20:16:25 +00:00
});
// Or pass a callback to start watching immediately
var event = clientReceipt.Deposit(function(error, result) {
2015-12-30 09:53:41 +00:00
if (!error)
console.log(result);
2015-12-07 20:16:25 +00:00
});
.. index :: ! log
Low-Level Interface to Logs
===========================
It is also possible to access the low-level interface to the logging
2016-05-24 17:57:36 +00:00
mechanism via the functions `` log0 `` , `` log1 `` , `` log2 `` , `` log3 `` and `` log4 `` .
`` logi `` takes `` i + 1 `` parameter of type `` bytes32 `` , where the first
2015-12-07 20:16:25 +00:00
argument will be used for the data part of the log and the others
as topics. The event call above can be performed in the same way as
::
2017-10-29 13:28:42 +00:00
pragma solidity ^0.4.10;
contract C {
2017-12-12 18:47:30 +00:00
function f() public payable {
2017-10-29 13:28:42 +00:00
bytes32 _id = 0x420042;
log3(
bytes32(msg.value),
bytes32(0x50cb9fe53daa9737b786ab3646f04d0150dc50ef4e75f59509d83667ad5adb20),
2018-05-11 12:06:31 +00:00
bytes32(uint256(msg.sender)),
2017-10-29 13:28:42 +00:00
_id
);
}
}
2015-12-07 20:16:25 +00:00
where the long hexadecimal number is equal to
2018-04-04 06:02:58 +00:00
`` keccak256("Deposit(address,bytes32,uint256)") `` , the signature of the event.
2015-12-07 20:16:25 +00:00
Additional Resources for Understanding Events
==============================================
- `Javascript documentation <https://github.com/ethereum/wiki/wiki/JavaScript-API#contract-events> `_
- `Example usage of events <https://github.com/debris/smart-exchange/blob/master/lib/contracts/SmartExchange.sol> `_
- `How to access them in js <https://github.com/debris/smart-exchange/blob/master/lib/exchange_transactions.js> `_
.. index :: ! inheritance, ! base class, ! contract;base, ! deriving
***** ***** *
Inheritance
***** ***** *
Solidity supports multiple inheritance by copying code including polymorphism.
All function calls are virtual, which means that the most derived function
2016-09-05 14:29:08 +00:00
is called, except when the contract name is explicitly given.
2015-12-07 20:16:25 +00:00
2017-05-03 17:24:00 +00:00
When a contract inherits from multiple contracts, only a single
contract is created on the blockchain, and the code from all the base contracts
is copied into the created contract.
2015-12-07 20:16:25 +00:00
The general inheritance system is very similar to
`Python's <https://docs.python.org/3/tutorial/classes.html#inheritance> `_ ,
especially concerning multiple inheritance.
Details are given in the following example.
::
2018-07-04 16:04:44 +00:00
pragma solidity >0.4.24;
2016-09-05 14:29:08 +00:00
2015-12-07 20:16:25 +00:00
contract owned {
2018-07-04 16:04:44 +00:00
constructor() public { owner = msg.sender; }
2015-12-07 20:16:25 +00:00
address owner;
}
2017-12-20 09:48:22 +00:00
// Use `is` to derive from another contract. Derived
2015-12-07 20:16:25 +00:00
// contracts can access all non-private members including
// internal functions and state variables. These cannot be
// accessed externally via `this` , though.
contract mortal is owned {
2018-07-04 16:04:44 +00:00
function kill() public {
2015-12-30 09:53:41 +00:00
if (msg.sender == owner) selfdestruct(owner);
2015-12-07 20:16:25 +00:00
}
}
// These abstract contracts are only provided to make the
// interface known to the compiler. Note the function
// without body. If a contract does not implement all
// functions it can only be used as an interface.
contract Config {
2017-12-12 18:47:30 +00:00
function lookup(uint id) public returns (address adr);
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract NameReg {
2017-12-12 18:47:30 +00:00
function register(bytes32 name) public;
function unregister() public;
2015-12-07 20:16:25 +00:00
}
2017-12-20 09:48:22 +00:00
// Multiple inheritance is possible. Note that `owned` is
// also a base class of `mortal` , yet there is only a single
// instance of `owned` (as for virtual inheritance in C++).
2015-12-07 20:16:25 +00:00
contract named is owned, mortal {
2018-07-04 16:04:44 +00:00
constructor(bytes32 name) public {
2017-12-12 18:47:30 +00:00
Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970);
2015-12-07 20:16:25 +00:00
NameReg(config.lookup(1)).register(name);
}
2016-11-23 15:40:57 +00:00
// Functions can be overridden by another function with the same name and
// the same number/types of inputs. If the overriding function has different
// types of output parameters, that causes an error.
// Both local and message-based function calls take these overrides
2015-12-07 20:16:25 +00:00
// into account.
2017-12-12 18:47:30 +00:00
function kill() public {
2015-12-07 20:16:25 +00:00
if (msg.sender == owner) {
2017-12-12 18:47:30 +00:00
Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970);
2015-12-07 20:16:25 +00:00
NameReg(config.lookup(1)).unregister();
// It is still possible to call a specific
// overridden function.
mortal.kill();
}
}
}
// If a constructor takes an argument, it needs to be
// provided in the header (or modifier-invocation-style at
// the constructor of the derived contract (see below)).
contract PriceFeed is owned, mortal, named("GoldFeed") {
2017-12-12 18:47:30 +00:00
function updateInfo(uint newInfo) public {
2015-12-07 20:16:25 +00:00
if (msg.sender == owner) info = newInfo;
}
2017-12-12 18:47:30 +00:00
function get() public view returns(uint r) { return info; }
2015-12-07 20:16:25 +00:00
uint info;
}
2016-05-24 17:57:36 +00:00
Note that above, we call `` mortal.kill() `` to "forward" the
2015-12-07 20:16:25 +00:00
destruction request. The way this is done is problematic, as
seen in the following example::
2018-04-20 20:50:00 +00:00
pragma solidity ^0.4.22;
2016-09-05 14:29:08 +00:00
2017-07-10 22:07:27 +00:00
contract owned {
2018-04-20 20:50:00 +00:00
constructor() public { owner = msg.sender; }
2017-07-10 22:07:27 +00:00
address owner;
}
2015-12-07 20:16:25 +00:00
contract mortal is owned {
2017-12-12 18:47:30 +00:00
function kill() public {
2015-12-07 20:16:25 +00:00
if (msg.sender == owner) selfdestruct(owner);
}
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract Base1 is mortal {
2017-12-12 18:47:30 +00:00
function kill() public { /* do cleanup 1 * / mortal.kill(); }
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract Base2 is mortal {
2017-12-12 18:47:30 +00:00
function kill() public { /* do cleanup 2 * / mortal.kill(); }
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract Final is Base1, Base2 {
}
2016-05-24 17:57:36 +00:00
A call to `` Final.kill() `` will call `` Base2.kill `` as the most
2015-12-07 20:16:25 +00:00
derived override, but this function will bypass
2016-05-24 17:57:36 +00:00
`` Base1.kill `` , basically because it does not even know about
`` Base1 `` . The way around this is to use `` super `` ::
2015-12-07 20:16:25 +00:00
2018-04-20 20:50:00 +00:00
pragma solidity ^0.4.22;
2016-09-05 14:29:08 +00:00
2017-07-10 22:07:27 +00:00
contract owned {
2018-04-20 20:50:00 +00:00
constructor() public { owner = msg.sender; }
2017-07-10 22:07:27 +00:00
address owner;
}
2015-12-07 20:16:25 +00:00
contract mortal is owned {
2017-12-12 18:47:30 +00:00
function kill() public {
2015-12-07 20:16:25 +00:00
if (msg.sender == owner) selfdestruct(owner);
}
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract Base1 is mortal {
2017-12-12 18:47:30 +00:00
function kill() public { /* do cleanup 1 * / super.kill(); }
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract Base2 is mortal {
2017-12-12 18:47:30 +00:00
function kill() public { /* do cleanup 2 * / super.kill(); }
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2018-01-23 17:14:56 +00:00
contract Final is Base1, Base2 {
2015-12-07 20:16:25 +00:00
}
Inheritance, "super" and DDD
As explained in "Multiple Inheritance and Linearization" part, "a simple rule to remember is to specify the base classes in the order from “most base-like” to “most derived”". So "contract Final is Base1, Base2" means Final is derived from Base2, derived from Base1, so the final inheritance sequence should be, starting with the most derived contract : Final, Base2, Base1, mortal, owned.
2018-01-24 12:38:47 +00:00
If `` Base2 `` calls a function of `` super `` , it does not simply
2017-11-21 11:01:59 +00:00
call this function on one of its base contracts. Rather, it
2015-12-07 20:16:25 +00:00
calls this function on the next base contract in the final
Inheritance, "super" and DDD
As explained in "Multiple Inheritance and Linearization" part, "a simple rule to remember is to specify the base classes in the order from “most base-like” to “most derived”". So "contract Final is Base1, Base2" means Final is derived from Base2, derived from Base1, so the final inheritance sequence should be, starting with the most derived contract : Final, Base2, Base1, mortal, owned.
2018-01-24 12:38:47 +00:00
inheritance graph, so it will call `` Base1.kill() `` (note that
2015-12-07 20:16:25 +00:00
the final inheritance sequence is -- starting with the most
Inheritance, "super" and DDD
As explained in "Multiple Inheritance and Linearization" part, "a simple rule to remember is to specify the base classes in the order from “most base-like” to “most derived”". So "contract Final is Base1, Base2" means Final is derived from Base2, derived from Base1, so the final inheritance sequence should be, starting with the most derived contract : Final, Base2, Base1, mortal, owned.
2018-01-24 12:38:47 +00:00
derived contract: Final, Base2, Base1, mortal, owned).
2015-12-07 20:16:25 +00:00
The actual function that is called when using super is
not known in the context of the class where it is used,
although its type is known. This is similar for ordinary
virtual method lookup.
2018-03-01 15:59:47 +00:00
.. index :: ! constructor
Constructors
============
2018-05-05 21:45:14 +00:00
A constructor is an optional function declared with the `` constructor `` keyword which is executed upon contract creation.
2018-03-09 13:25:57 +00:00
Constructor functions can be either `` public `` or `` internal `` . If there is no constructor, the contract will assume the
default constructor: `` contructor() public {} `` .
2018-03-01 15:59:47 +00:00
2018-03-02 15:44:35 +00:00
::
2018-07-02 14:46:54 +00:00
pragma solidity >0.4.24;
2018-03-02 15:44:35 +00:00
contract A {
uint public a;
constructor(uint _a) internal {
a = _a;
}
}
contract B is A(1) {
constructor() public {}
}
A constructor set as `` internal `` causes the contract to be marked as :ref: `abstract <abstract-contract>` .
2018-07-02 14:25:54 +00:00
.. warning ::
2018-07-02 14:46:54 +00:00
Prior to version 0.4.22, constructors were defined as functions with the same name as the contract. This syntax was deprecated and is not allowed anymore in version 0.5.0.
2018-03-01 15:59:47 +00:00
2015-12-07 20:16:25 +00:00
.. index :: ! base;constructor
Arguments for Base Constructors
===============================
2018-05-08 17:26:37 +00:00
The constructors of all the base contracts will be called following the
linearization rules explained below. If the base constructors have arguments,
derived contracts need to specify all of them. This can be done in two ways::
2015-12-07 20:16:25 +00:00
2018-04-20 20:50:00 +00:00
pragma solidity ^0.4.22;
2016-09-05 14:29:08 +00:00
2015-12-07 20:16:25 +00:00
contract Base {
2015-12-30 09:53:41 +00:00
uint x;
2018-03-02 15:44:35 +00:00
constructor(uint _x) public { x = _x; }
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2017-12-11 21:00:15 +00:00
contract Derived1 is Base(7) {
constructor(uint _y) public {}
}
contract Derived2 is Base {
constructor(uint _y) Base(_y * _y) public {}
2015-12-07 20:16:25 +00:00
}
2017-05-03 17:24:00 +00:00
One way is directly in the inheritance list (`` is Base(7) `` ). The other is in
2015-12-07 20:16:25 +00:00
the way a modifier would be invoked as part of the header of
2016-05-24 17:57:36 +00:00
the derived constructor (`` Base(_y * _y) `` ). The first way to
2015-12-07 20:16:25 +00:00
do it is more convenient if the constructor argument is a
constant and defines the behaviour of the contract or
describes it. The second way has to be used if the
constructor arguments of the base depend on those of the
2017-12-11 21:00:15 +00:00
derived contract. Arguments have to be given either in the
2018-07-10 07:17:33 +00:00
inheritance list or in modifier-style in the derived constructor.
2017-12-11 21:00:15 +00:00
Specifying arguments in both places is an error.
2015-12-07 20:16:25 +00:00
2018-05-08 17:26:37 +00:00
If a derived contract doesn't specify the arguments to all of its base
contracts' constructors, it will be abstract.
2018-05-05 21:41:47 +00:00
2015-12-07 20:16:25 +00:00
.. index :: ! inheritance;multiple, ! linearization, ! C3 linearization
Multiple Inheritance and Linearization
======================================
Languages that allow multiple inheritance have to deal with
2017-05-03 17:24:00 +00:00
several problems. One is the `Diamond Problem <https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem> `_ .
2018-04-30 14:15:41 +00:00
Solidity is similar to Python in that it uses "`C3 Linearization <https://en.wikipedia.org/wiki/C3_linearization> `_ "
2015-12-07 20:16:25 +00:00
to force a specific order in the DAG of base classes. This
results in the desirable property of monotonicity but
disallows some inheritance graphs. Especially, the order in
2016-05-24 17:57:36 +00:00
which the base classes are given in the `` is `` directive is
2018-04-30 14:15:41 +00:00
important: You have to list the direct base contracts
in the order from "most base-like" to "most derived".
Note that this order is different from the one used in Python.
In the following code, Solidity will give the
2015-12-07 20:16:25 +00:00
error "Linearization of inheritance graph impossible".
::
2017-07-10 22:07:27 +00:00
// This will not compile
2016-09-05 11:54:54 +00:00
pragma solidity ^0.4.0;
2015-12-07 20:16:25 +00:00
contract X {}
contract A is X {}
contract C is A, X {}
2016-05-24 17:57:36 +00:00
The reason for this is that `` C `` requests `` X `` to override `` A ``
(by specifying `` A, X `` in this order), but `` A `` itself
requests to override `` X `` , which is a contradiction that
2015-12-07 20:16:25 +00:00
cannot be resolved.
2017-01-03 18:40:50 +00:00
Inheriting Different Kinds of Members of the Same Name
======================================================
When the inheritance results in a contract with a function and a modifier of the same name, it is considered as an error.
This error is produced also by an event and a modifier of the same name, and a function and an event of the same name.
2017-02-02 23:52:34 +00:00
As an exception, a state variable getter can override a public function.
2017-01-03 18:40:50 +00:00
2015-12-07 20:16:25 +00:00
.. index :: ! contract;abstract, ! abstract contract
2018-03-01 15:59:47 +00:00
.. _abstract-contract:
2015-12-07 20:16:25 +00:00
***** ***** ***** ***
Abstract Contracts
***** ***** ***** ***
2018-03-01 15:59:47 +00:00
Contracts are marked as abstract when at least one of their functions lacks an implementation as in the following example (note that the function declaration header is terminated by `` ; `` )::
2015-12-07 20:16:25 +00:00
2016-09-05 14:29:08 +00:00
pragma solidity ^0.4.0;
2016-05-18 15:11:39 +00:00
contract Feline {
2017-12-12 18:47:30 +00:00
function utterance() public returns (bytes32);
2015-12-07 20:16:25 +00:00
}
2018-03-01 15:59:47 +00:00
Such contracts cannot be compiled (even if they contain implemented functions alongside non-implemented functions), but they can be used as base contracts::
2015-12-07 20:16:25 +00:00
2016-09-05 14:29:08 +00:00
pragma solidity ^0.4.0;
2017-07-10 22:07:27 +00:00
contract Feline {
2017-12-12 18:47:30 +00:00
function utterance() public returns (bytes32);
2017-07-10 22:07:27 +00:00
}
2016-05-18 15:11:39 +00:00
contract Cat is Feline {
2017-12-12 18:47:30 +00:00
function utterance() public returns (bytes32) { return "miaow"; }
2015-12-07 20:16:25 +00:00
}
If a contract inherits from an abstract contract and does not implement all non-implemented functions by overriding, it will itself be abstract.
2018-02-19 18:02:49 +00:00
Note that a function without implementation is different from a :ref: `Function Type <function_types>` even though their syntax looks very similar.
2018-01-23 17:53:18 +00:00
2018-02-19 18:02:49 +00:00
Example of function without implementation (a function declaration)::
2018-01-23 17:53:18 +00:00
function foo(address) external returns (address);
2018-02-19 18:02:49 +00:00
Example of a Function Type (a variable declaration, where the variable is of type `` function `` )::
2018-01-23 17:53:18 +00:00
function(address) external returns (address) foo;
2018-05-05 21:45:14 +00:00
Abstract contracts decouple the definition of a contract from its implementation providing better extensibility and self-documentation and
2018-03-01 15:59:47 +00:00
facilitating patterns like the `Template method <https://en.wikipedia.org/wiki/Template_method_pattern> `_ and removing code duplication.
2018-05-16 08:03:53 +00:00
Abstract contracts are useful in the same way that defining methods in an interface is useful. It is a way for the designer of the abstract contract to say "any child of mine must implement this method".
2018-05-09 10:28:55 +00:00
2018-01-23 17:53:18 +00:00
2017-02-12 15:21:32 +00:00
.. index :: ! contract;interface, ! interface contract
***** *****
Interfaces
***** *****
Interfaces are similar to abstract contracts, but they cannot have any functions implemented. There are further restrictions:
2018-05-29 23:56:45 +00:00
- Cannot inherit other contracts or interfaces.
2018-07-12 12:57:42 +00:00
- All declared functions must be external.
2018-05-29 23:56:45 +00:00
- Cannot define constructor.
- Cannot define variables.
- Cannot define structs.
- Cannot define enums.
2017-02-12 15:21:32 +00:00
Some of these restrictions might be lifted in the future.
2017-05-03 17:24:00 +00:00
Interfaces are basically limited to what the Contract ABI can represent, and the conversion between the ABI and
2017-02-12 15:21:32 +00:00
an Interface should be possible without any information loss.
Interfaces are denoted by their own keyword:
::
2017-07-17 09:24:18 +00:00
pragma solidity ^0.4.11;
2017-02-12 15:21:32 +00:00
interface Token {
2018-07-12 12:57:42 +00:00
function transfer(address recipient, uint amount) external;
2017-02-12 15:21:32 +00:00
}
Contracts can inherit interfaces as they would inherit other contracts.
2016-03-10 14:56:25 +00:00
.. index :: ! library, callcode, delegatecall
2015-12-07 20:16:25 +00:00
.. _libraries:
***** ***** **
Libraries
***** ***** **
Libraries are similar to contracts, but their purpose is that they are deployed
2016-05-24 17:57:36 +00:00
only once at a specific address and their code is reused using the `` DELEGATECALL ``
(`` CALLCODE `` until Homestead)
2015-12-07 20:16:25 +00:00
feature of the EVM. This means that if library functions are called, their code
2016-05-24 17:57:36 +00:00
is executed in the context of the calling contract, i.e. `` this `` points to the
2016-06-17 21:13:03 +00:00
calling contract, and especially the storage from the calling contract can be
2015-12-07 20:16:25 +00:00
accessed. As a library is an isolated piece of source code, it can only access
state variables of the calling contract if they are explicitly supplied (it
2018-01-19 15:52:23 +00:00
would have no way to name them, otherwise). Library functions can only be
called directly (i.e. without the use of `` DELEGATECALL `` ) if they do not modify
the state (i.e. if they are `` view `` or `` pure `` functions),
because libraries are assumed to be stateless. In particular, it is
not possible to destroy a library unless Solidity's type system is circumvented.
2015-12-07 20:16:25 +00:00
2016-05-04 18:41:39 +00:00
Libraries can be seen as implicit base contracts of the contracts that use them.
They will not be explicitly visible in the inheritance hierarchy, but calls
to library functions look just like calls to functions of explicit base
2016-05-24 17:57:36 +00:00
contracts (`` L.f() `` if `` L `` is the name of the library). Furthermore,
`` internal `` functions of libraries are visible in all contracts, just as
2016-05-04 18:41:39 +00:00
if the library were a base contract. Of course, calls to internal functions
use the internal calling convention, which means that all internal types
2018-07-30 12:11:40 +00:00
can be passed and types :ref: `stored in memory <data-location>` will be passed by reference and not copied.
2017-05-03 17:24:00 +00:00
To realize this in the EVM, code of internal library functions
2018-01-26 14:32:11 +00:00
and all functions called from therein will at compile time be pulled into the calling
2017-05-03 17:24:00 +00:00
contract, and a regular `` JUMP `` call will be used instead of a `` DELEGATECALL `` .
2016-05-04 18:41:39 +00:00
2015-12-07 20:16:25 +00:00
.. index :: using for, set
The following example illustrates how to use libraries (but
be sure to check out :ref: `using for <using-for>` for a
more advanced example to implement a set).
::
2018-04-15 21:12:28 +00:00
pragma solidity ^0.4.22;
2016-09-05 11:54:54 +00:00
2015-12-07 20:16:25 +00:00
library Set {
// We define a new struct datatype that will be used to
// hold its data in the calling contract.
struct Data { mapping(uint => bool) flags; }
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
// Note that the first parameter is of type "storage
// reference" and thus only its storage address and not
// its contents is passed as part of the call. This is a
// special feature of library functions. It is idiomatic
2017-12-20 09:48:22 +00:00
// to call the first parameter `self` , if the function can
2015-12-07 20:16:25 +00:00
// be seen as a method of that object.
function insert(Data storage self, uint value)
2017-12-12 18:47:30 +00:00
public
2015-12-07 20:16:25 +00:00
returns (bool)
{
2015-12-30 09:53:41 +00:00
if (self.flags[value])
return false; // already there
self.flags[value] = true;
return true;
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
function remove(Data storage self, uint value)
2017-12-12 18:47:30 +00:00
public
2015-12-30 09:53:41 +00:00
returns (bool)
2015-12-07 20:16:25 +00:00
{
2015-12-30 09:53:41 +00:00
if (!self.flags[value])
return false; // not there
self.flags[value] = false;
return true;
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
function contains(Data storage self, uint value)
2017-12-12 18:47:30 +00:00
public
view
2015-12-30 09:53:41 +00:00
returns (bool)
2015-12-07 20:16:25 +00:00
{
2015-12-30 09:53:41 +00:00
return self.flags[value];
2015-12-07 20:16:25 +00:00
}
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
contract C {
2015-12-30 09:53:41 +00:00
Set.Data knownValues;
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function register(uint value) public {
2015-12-30 09:53:41 +00:00
// The library functions can be called without a
// specific instance of the library, since the
// "instance" will be the current contract.
2017-05-02 12:12:25 +00:00
require(Set.insert(knownValues, value));
2015-12-30 09:53:41 +00:00
}
// In this contract, we can also directly access knownValues.flags, if we want.
2015-12-07 20:16:25 +00:00
}
Of course, you do not have to follow this way to use
2017-12-20 09:48:22 +00:00
libraries: they can also be used without defining struct
2017-05-03 17:24:00 +00:00
data types. Functions also work without any storage
reference parameters, and they can have multiple storage reference
2015-12-07 20:16:25 +00:00
parameters and in any position.
2016-05-24 17:57:36 +00:00
The calls to `` Set.contains `` , `` Set.insert `` and `` Set.remove ``
are all compiled as calls (`` DELEGATECALL `` ) to an external
2015-12-07 20:16:25 +00:00
contract/library. If you use libraries, take care that an
2016-03-10 14:56:25 +00:00
actual external function call is performed.
2016-05-24 17:57:36 +00:00
`` msg.sender `` , `` msg.value `` and `` this `` will retain their values
2017-08-28 10:48:23 +00:00
in this call, though (prior to Homestead, because of the use of `` CALLCODE `` , `` msg.sender `` and
2016-05-24 17:57:36 +00:00
`` msg.value `` changed, though).
2015-12-07 20:16:25 +00:00
2018-07-30 12:11:40 +00:00
The following example shows how to use :ref: `types stored in memory <data-location>` and
2016-05-04 18:41:39 +00:00
internal functions in libraries in order to implement
custom types without the overhead of external function calls:
::
2017-12-12 18:47:30 +00:00
pragma solidity ^0.4.16;
2016-09-05 11:54:54 +00:00
2016-05-18 15:11:39 +00:00
library BigInt {
2016-05-11 19:31:02 +00:00
struct bigint {
uint[] limbs;
}
2018-07-14 21:42:01 +00:00
function fromUint(uint x) internal pure returns (bigint memory r) {
2016-05-11 19:31:02 +00:00
r.limbs = new uint[](1);
r.limbs[0] = x;
}
2018-07-14 21:42:01 +00:00
function add(bigint memory _a, bigint memory _b) internal pure returns (bigint memory r) {
2016-05-11 19:31:02 +00:00
r.limbs = new uint[](max(_a.limbs.length, _b.limbs.length));
uint carry = 0;
for (uint i = 0; i < r.limbs.length; ++i) {
uint a = limb(_a, i);
uint b = limb(_b, i);
r.limbs[i] = a + b + carry;
if (a + b < a || (a + b == uint(-1) && carry > 0))
carry = 1;
else
carry = 0;
}
if (carry > 0) {
// too bad, we have to add a limb
uint[] memory newLimbs = new uint[](r.limbs.length + 1);
2018-06-15 10:30:28 +00:00
uint i;
2016-05-11 19:31:02 +00:00
for (i = 0; i < r.limbs.length; ++i)
newLimbs[i] = r.limbs[i];
newLimbs[i] = carry;
r.limbs = newLimbs;
}
}
2018-07-14 21:42:01 +00:00
function limb(bigint memory _a, uint _limb) internal pure returns (uint) {
2016-05-11 19:31:02 +00:00
return _limb < _a.limbs.length ? _a.limbs[_limb] : 0;
}
2017-12-12 18:47:30 +00:00
function max(uint a, uint b) private pure returns (uint) {
2016-05-11 19:31:02 +00:00
return a > b ? a : b;
}
}
contract C {
2016-05-18 15:11:39 +00:00
using BigInt for BigInt.bigint;
2017-12-12 18:47:30 +00:00
function f() public pure {
2018-06-18 13:58:10 +00:00
BigInt.bigint memory x = BigInt.fromUint(7);
BigInt.bigint memory y = BigInt.fromUint(uint(-1));
BigInt.bigint memory z = x.add(y);
2016-05-11 19:31:02 +00:00
}
}
2016-05-04 18:41:39 +00:00
2015-12-07 20:16:25 +00:00
As the compiler cannot know where the library will be
deployed at, these addresses have to be filled into the
2016-05-18 15:18:39 +00:00
final bytecode by a linker
2016-08-24 03:53:30 +00:00
(see :ref: `commandline-compiler` for how to use the
2015-12-07 20:16:25 +00:00
commandline compiler for linking). If the addresses are not
given as arguments to the compiler, the compiled hex code
2016-05-24 17:57:36 +00:00
will contain placeholders of the form `` __Set______ `` (where
`` Set `` is the name of the library). The address can be filled
2015-12-07 20:16:25 +00:00
manually by replacing all those 40 symbols by the hex
encoding of the address of the library contract.
Restrictions for libraries in comparison to contracts:
2016-08-12 20:29:17 +00:00
- No state variables
- Cannot inherit nor be inherited
2017-03-16 11:20:39 +00:00
- Cannot receive Ether
2015-12-07 20:16:25 +00:00
2016-08-12 20:29:17 +00:00
(These might be lifted at a later point.)
2015-12-07 20:16:25 +00:00
2018-01-19 15:52:23 +00:00
Call Protection For Libraries
=============================
As mentioned in the introduction, if a library's code is executed
using a `` CALL `` instead of a `` DELEGATECALL `` or `` CALLCODE `` ,
it will revert unless a `` view `` or `` pure `` function is called.
The EVM does not provide a direct way for a contract to detect
whether it was called using `` CALL `` or not, but a contract
can use the `` ADDRESS `` opcode to find out "where" it is
currently running. The generated code compares this address
to the address used at construction time to determine the mode
of calling.
More specifically, the runtime code of a library always starts
with a push instruction, which is a zero of 20 bytes at
compilation time. When the deploy code runs, this constant
is replaced in memory by the current address and this
modified code is stored in the contract. At runtime,
this causes the deploy time address to be the first
constant to be pushed onto the stack and the dispatcher
code compares the current address against this constant
for any non-view and non-pure function.
2015-12-07 20:16:25 +00:00
.. index :: ! using for, library
.. _using-for:
***** *** *
Using For
***** *** *
2016-05-24 17:57:36 +00:00
The directive `` using A for B; `` can be used to attach library
2018-07-02 14:25:54 +00:00
functions (from the library `` A `` ) to any type (`` B `` ).
2015-12-07 20:16:25 +00:00
These functions will receive the object they are called on
2018-06-29 10:21:39 +00:00
as their first parameter (like the `` self `` variable in Python).
2015-12-07 20:16:25 +00:00
2016-05-24 17:57:36 +00:00
The effect of `` using A for *; `` is that the functions from
2018-06-29 10:21:39 +00:00
the library `` A `` are attached to *any* type.
2015-12-07 20:16:25 +00:00
2018-06-29 10:21:39 +00:00
In both situations, *all* functions in the library are attached,
even those where the type of the first parameter does not
match the type of the object. The type is checked at the
2015-12-07 20:16:25 +00:00
point the function is called and function overload
resolution is performed.
2018-06-29 10:21:39 +00:00
The `` using A for B; `` directive is active only within the current
contract, including within all of its functions, and has no effect
outside of the contract in which it is used. The directive
may only be used inside a contract, not inside any of its functions.
By including a library, its data types including library functions are
2015-12-07 20:16:25 +00:00
available without having to add further code.
Let us rewrite the set example from the
:ref: `libraries` in this way::
2017-12-12 18:47:30 +00:00
pragma solidity ^0.4.16;
2016-09-05 14:29:08 +00:00
2015-12-07 20:16:25 +00:00
// This is the same code as before, just without comments
library Set {
struct Data { mapping(uint => bool) flags; }
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
function insert(Data storage self, uint value)
2017-12-12 18:47:30 +00:00
public
2015-12-07 20:16:25 +00:00
returns (bool)
{
2015-12-30 09:53:41 +00:00
if (self.flags[value])
return false; // already there
self.flags[value] = true;
return true;
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
function remove(Data storage self, uint value)
2017-12-12 18:47:30 +00:00
public
2015-12-30 09:53:41 +00:00
returns (bool)
2015-12-07 20:16:25 +00:00
{
2015-12-30 09:53:41 +00:00
if (!self.flags[value])
return false; // not there
self.flags[value] = false;
return true;
2015-12-07 20:16:25 +00:00
}
2016-05-05 18:58:02 +00:00
2015-12-07 20:16:25 +00:00
function contains(Data storage self, uint value)
2017-12-12 18:47:30 +00:00
public
view
2015-12-30 09:53:41 +00:00
returns (bool)
2015-12-07 20:16:25 +00:00
{
2015-12-30 09:53:41 +00:00
return self.flags[value];
2015-12-07 20:16:25 +00:00
}
}
contract C {
2015-12-30 09:53:41 +00:00
using Set for Set.Data; // this is the crucial change
Set.Data knownValues;
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function register(uint value) public {
2015-12-30 09:53:41 +00:00
// Here, all variables of type Set.Data have
// corresponding member functions.
// The following function call is identical to
2017-12-20 09:48:22 +00:00
// `Set.insert(knownValues, value)`
2017-04-19 18:12:45 +00:00
require(knownValues.insert(value));
2015-12-30 09:53:41 +00:00
}
2015-12-07 20:16:25 +00:00
}
It is also possible to extend elementary types in that way::
2017-12-12 18:47:30 +00:00
pragma solidity ^0.4.16;
2016-09-05 14:29:08 +00:00
2015-12-07 20:16:25 +00:00
library Search {
2017-12-12 18:47:30 +00:00
function indexOf(uint[] storage self, uint value)
public
view
returns (uint)
{
2015-12-30 09:53:41 +00:00
for (uint i = 0; i < self.length; i++)
if (self[i] == value) return i;
return uint(-1);
}
2015-12-07 20:16:25 +00:00
}
contract C {
2015-12-30 09:53:41 +00:00
using Search for uint[];
uint[] data;
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function append(uint value) public {
2015-12-30 09:53:41 +00:00
data.push(value);
}
2016-05-05 18:58:02 +00:00
2017-12-12 18:47:30 +00:00
function replace(uint _old, uint _new) public {
2015-12-30 09:53:41 +00:00
// This performs the library function call
2016-06-25 12:11:45 +00:00
uint index = data.indexOf(_old);
if (index == uint(-1))
2015-12-30 09:53:41 +00:00
data.push(_new);
else
data[index] = _new;
}
2015-12-07 20:16:25 +00:00
}
Note that all library calls are actual EVM function calls. This means that
if you pass memory or value types, a copy will be performed, even of the
2016-05-24 17:57:36 +00:00
`` self `` variable. The only situation where no copy will be performed
2015-12-07 20:16:25 +00:00
is when storage reference variables are used.