Function Modifiers
Solidity offers a special type of function called a function modifier. You apply modifiers to functions by adding the modifier name in the function declaration. Modifiers are most often used to create conditions that apply to many functions within a contract. We have an access control statement already, in our destroy function. Let's create a function modifier that expresses that condition:
modifier onlyOwner { require(msg.sender == owner); _; }
This function modifier, named onlyOwner, sets a condition on any function that it modifies, requiring that the address stored as the owner of the contract is the same as the address of the transaction's msg.sender. This is the basic design pattern for access control, allowing only the owner of a contract to execute any function that has the onlyOwner modifier.
You may have noticed that our function modifier has a peculiar syntactic "placeholder" in it, an underscore followed by a semicolon (_;). This placeholder is replaced by the code of the function that is being modified. Essentially, the modifier is "wrapped around" the modified function, placing its code in the location identified by the underscore character.
To apply a modifier, you add its name to the function declaration. More than one modifier can be applied to a function; they are applied in the sequence they are declared, as a comma-separated list.
Let's rewrite our destroy function to use the onlyOwner modifier:
function destroy() public onlyOwner { selfdestruct(owner); }
The function modifier's name (onlyOwner) is after the keyword public and tells us that the destroy function is modified by the onlyOwner modifier. Essentially, you can read this as "Only the owner can destroy this contract." In practice, the resulting code is equivalent to "wrapping" the code from onlyOwner around destroy.
Function modifiers are an extremely useful tool because they allow us to write preconditions for functions and apply them consistently, making the code easier to read and, as a result, easier to audit for security. They are most often used for access control, but they are quite versatile and can be used for a variety of other purposes.
Inside a modifier, you can access all the values (variables and arguments) visible to the modified function. In this case, we can access the owner variable, which is declared within the contract. However, the inverse is not true: you cannot access any of the modifier's variables inside the modified function.
Contract Inheritance
Solidity's contract object supports inheritance, which is a mechanism for extending a base contract with additional functionality. To use inheritance, specify a parent contract with the keyword is:
contract Child is Parent { ... }
With this construct, the Child contract inherits all the methods, functionality, and variables of Parent. Solidity also supports multiple inheritance, which can be specified by comma-separated contract names after the keyword is:
contract Child is Parent1, Parent2 { ... }
Contract inheritance allows us to write our contracts in such a way as to achieve modularity, extensibility, and reuse. We start with contracts that are simple and implement the most generic capabilities, then extend them by inheriting those capabilities in more specialized contracts.
In our Faucet contract, we introduced the constructor and destructor, together with access control for an owner, assigned on construction. Those capabilities are quite generic: many contracts will have them. We can define them as generic contracts, then use inheritance to extend them to the Faucet contract.
We start by defining a base contract owned, which has an owner variable, setting it in the contract's constructor:
contract owned { address owner; // Contract constructor: set owner constructor() { owner = msg.sender; } // Access control modifier modifier onlyOwner { require(msg.sender == owner); _; } }
Next, we define a base contract mortal, which inherits owned:
contract mortal is owned { // Contract destructor function destroy() public onlyOwner { selfdestruct(owner); } }
As you can see, the mortal contract can use the onlyOwner function modifier, defined in owned. It indirectly also uses the owner address variable and the constructor defined in owned. Inheritance makes each contract simpler and focused on its specific functionality, allowing us to manage the details in a modular way.
Now we can further extend the owned contract, inheriting its capabilities in Faucet:
contract Faucet is mortal { // Give out ether to anyone who asks function withdraw(uint withdraw_amount) public { // Limit withdrawal amount require(withdraw_amount <= 0.1 ether); // Send the amount to the address that requested it msg.sender.transfer(withdraw_amount); } // Accept any incoming amount function () external payable {} }
By inheriting mortal, which in turn inherits owned, the Faucet contract now has the constructor and destroy functions, and a defined owner. The functionality is the same as when those functions were within Faucet, but now we can reuse those functions in other contracts without writing them again. Code reuse and modularity make our code cleaner, easier to read, and easier to audit.
Error Handling (assert, require, revert)
A contract call can terminate and return an error. Error handling in Solidity is handled by four functions: assert, require, revert, and throw (now deprecated).
When a contract terminates with an error, all the state changes (changes to variables, balances, etc.) are reverted, all the way up the chain of contract calls if more than one contract was called. This ensures that transactions are atomic, meaning they either complete successfully or have no effect on state and are reverted entirely.
The assert and require functions operate in the same way, evaluating a condition and stopping execution with an error if the condition is false. By convention, assert is used when the outcome is expected to be true, meaning that we use assert to test internal conditions. By comparison, require is used when testing inputs (such as function arguments or transaction fields), setting our expectations for those conditions.
We've used require in our function modifier onlyOwner, to test that the message sender is the owner of the contract:
require(msg.sender == owner);
The require function acts as a gate condition, preventing execution of the rest of the function and producing an error if it is not satisfied.
As of Solidity v0.4.22, require can also include a helpful text message that can be used to show the reason for the error. The error message is recorded in the transaction log. So, we can improve our code by adding an error message in our require function:
require(msg.sender == owner, "Only the contract owner can call this function");
The revert and throw functions halt the execution of the contract and revert any state changes. The throw function is obsolete and will be removed in future versions of Solidity; you should use revert instead. The revert function can also take an error message as the only argument, which is recorded in the transaction log.
Certain conditions in a contract will generate errors regardless of whether we explicitly check for them. For example, in our Faucet contract, we don't check whether there is enough ether to satisfy a withdrawal request. That's because the transfer function will fail with an error and revert the transaction if there is insufficient balance to make the transfer:
msg.sender.transfer(withdraw_amount);
However, it might be better to check explicitly and provide a clear error message on failure. We can do that by adding a require statement before the transfer:
require(this.balance >= withdraw_amount, "Insufficient balance in faucet for withdrawal request"); msg.sender.transfer(withdraw_amount);
Additional error-checking code like this will increase gas consumption slightly, but it offers better error reporting than if omitted. You will need to find the right balance between gas consumption and verbose error checking based on the expected use of your contract. In the case of a Faucet contract intended for a testnet, we'd probably err on the side of extra reporting even if it costs more gas. Perhaps for a mainnet contract we'd choose to be frugal with our gas usage instead.
Events
When a transaction completes (successfully or not), it produces a transaction receipt, as we will see in The Ethereum Virtual Machine. The transaction receipt contains log entries that provide information about the actions that occurred during the execution of the transaction. Events are the Solidity high-level objects that are used to construct these logs.
Events are especially useful for light clients and DApp services, which can "watch" for specific events and report them to the user interface, or make a change in the state of the application to reflect an event in an underlying contract.
Event objects take arguments that are serialized and recorded in the transaction logs, in the blockchain. You can supply the keyword indexed before an argument, to make the value part of an indexed table (hash table) that can be searched or filtered by an application.
We have not added any events in our Faucet example so far, so let's do that. We will add two events, one to log any withdrawals and one to log any deposits. We will call these events Withdrawal and Deposit, respectively. First, we define the events in the Faucet contract:
contract Faucet is mortal { event Withdrawal(address indexed to, uint amount); event Deposit(address indexed from, uint amount); [...] }
We've chosen to make the addresses indexed, to allow searching and filtering in any user interface built to access our Faucet.
Next, we use the emit keyword to incorporate the event data in the transaction logs:
// Give out ether to anyone who asks function withdraw(uint withdraw_amount) public { [...] msg.sender.transfer(withdraw_amount); emit Withdrawal(msg.sender, withdraw_amount); } // Accept any incoming amount function () external payable { emit Deposit(msg.sender, msg.value); }
The resulting Faucet.sol contract looks like Faucet8.sol: Revised Faucet contract, with events.
Faucet8.sol: Revised Faucet contract, with events
include::code/Solidity/Faucet8.sol[]
Catching events
OK, so we've set up our contract to emit events. How do we see the results of a transaction and "catch" the events? The web3.js library provides a data structure that contains a transaction's logs. Within those we can see the events generated by the transaction.
Let's use truffle to run a test transaction on the revised Faucet contract. Follow the instructions in Truffle to set up a project directory and compile the Faucet code. The source code can be found in the book's GitHub repository under code/truffle/FaucetEvents.
$ truffle develop truffle(develop)> compile truffle(develop)> migrate Using network 'develop'. Running migration: 1_initial_migration.js Deploying Migrations... ... 0xb77ceae7c3f5afb7fbe3a6c5974d352aa844f53f955ee7d707ef6f3f8e6b4e61 Migrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0 Saving successful migration to network... ... 0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956 Saving artifacts... Running migration: 2_deploy_contracts.js Deploying Faucet... ... 0xfa850d754314c3fb83f43ca1fa6ee20bc9652d891c00a2f63fd43ab5bfb0d781 Faucet: 0x345ca3e014aaf5dca488057592ee47305d9b3e10 Saving successful migration to network... ... 0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0 Saving artifacts... truffle(develop)> Faucet.deployed().then(i => {FaucetDeployed = i}) truffle(develop)> FaucetDeployed.send(web3.utils.toWei(1, "ether")).then(res => \ { console.log(res.logs[0].event, res.logs[0].args) }) Deposit { from: '0x627306090abab3a6e1400e9345bc60c78a8bef57', amount: BigNumber { s: 1, e: 18, c: [ 10000 ] } } truffle(develop)> FaucetDeployed.withdraw(web3.utils.toWei(0.1, "ether")).then(res => \ { console.log(res.logs[0].event, res.logs[0].args) }) Withdrawal { to: '0x627306090abab3a6e1400e9345bc60c78a8bef57', amount: BigNumber { s: 1, e: 17, c: [ 1000 ] } }
After deploying the contract using the deployed function, we execute two transactions. The first transaction is a deposit (using send), which emits a Deposit event in the transaction logs:
Deposit { from: '0x627306090abab3a6e1400e9345bc60c78a8bef57', amount: BigNumber { s: 1, e: 18, c: [ 10000 ] } }
Next, we use the withdraw function to make a withdrawal. This emits a Withdrawal event:
Withdrawal { to: '0x627306090abab3a6e1400e9345bc60c78a8bef57', amount: BigNumber { s: 1, e: 17, c: [ 1000 ] } }
To get these events, we looked at the logs array returned as a result (res) of the transactions. The first log entry (logs[0]) contains an event name in logs[0].event and the event arguments in logs[0].args. By showing these on the console, we can see the emitted event name and the event arguments.
Events are a very useful mechanism, not only for intra-contract communication, but also for debugging during development.
Calling Other Contracts (send, call, callcode, delegatecall)
Calling other contracts from within your contract is a very useful but potentially dangerous operation. We'll examine the various ways you can achieve this and evaluate the risks of each method. In short, the risks arise from the fact that you may not know much about a contract you are calling into or that is calling into your contract. When writing smart contracts, you must keep in mind that while you may mostly expect to be dealing with EOAs, there is nothing to stop arbitrarily complex and perhaps malign contracts from calling into and being called by your code.
Creating a new instance
The safest way to call another contract is if you create that other contract yourself. That way, you are certain of its interfaces and behavior. To do this, you can simply instantiate it, using the keyword new, as in other object-oriented languages. In Solidity, the keyword new will create the contract on the blockchain and return an object that you can use to reference it. Let's say you want to create and call a Faucet contract from within another contract called Token:
contract Token is mortal { Faucet _faucet; constructor() { _faucet = new Faucet(); } }
This mechanism for contract construction ensures that you know the exact type of the contract and its interface. The contract Faucet must be defined within the scope of Token, which you can do with an import statement if the definition is in another file:
import "Faucet.sol"; contract Token is mortal { Faucet _faucet; constructor() { _faucet = new Faucet(); } }
You can optionally specify the value of ether transfer on creation, and pass arguments to the new contract's constructor:
import "Faucet.sol"; contract Token is mortal { Faucet _faucet; constructor() { _faucet = (new Faucet).value(0.5 ether)(); } }
You can also then call the Faucet functions. In this example, we call the destroy function of Faucet from within the destroy function of Token:
import "Faucet.sol"; contract Token is mortal { Faucet _faucet; constructor() { _faucet = (new Faucet).value(0.5 ether)(); } function destroy() ownerOnly { _faucet.destroy(); } }
Note that while you are the owner of the Token contract, the Token contract itself owns the new Faucet contract, so only the Token contract can destroy it.
Addressing an existing instance
Another way you can call a contract is by casting the address of an existing instance of the contract. With this method, you apply a known interface to an existing instance. It is therefore critically important that you know, for sure, that the instance you are addressing is in fact of the type you assume. Let's look at an example:
import "Faucet.sol"; contract Token is mortal { Faucet _faucet; constructor(address _f) { _faucet = Faucet(_f); _faucet.withdraw(0.1 ether) } }
Here, we take an address provided as an argument to the constructor, _f, and we cast it to a Faucet object. This is much riskier than the previous mechanism, because we don't know for sure whether that address actually is a Faucet object. When we call withdraw, we are assuming that it accepts the same arguments and executes the same code as our Faucet declaration, but we can't be sure. For all we know, the withdraw function at this address could execute something completely different from what we expect, even if it is named the same. Using addresses passed as input and casting them into specific objects is therefore much more dangerous than creating the contract yourself.
Raw call, delegatecall
Solidity offers some even more "low-level" functions for calling other contracts. These correspond directly to EVM opcodes of the same name and allow us to construct a contract-to-contract call manually. As such, they represent the most flexible and the most dangerous mechanisms for calling other contracts.
Here's the same example, using a call method:
contract Token is mortal { constructor(address _faucet) { _faucet.call("withdraw", 0.1 ether); } }
As you can see, this type of call is a blind call into a function, very much like constructing a raw transaction, only from within a contract's context. It can expose your contract to a number of security risks, most importantly reentrancy, which we will discuss in more detail in Reentrancy. The call function will return false if there is a problem, so you can evaluate the return value for error handling:
contract Token is mortal { constructor(address _faucet) { if !(_faucet.call("withdraw", 0.1 ether)) { revert("Withdrawal from faucet failed"); } } }
Another variant of call is delegatecall, which replaced the more dangerous callcode. The callcode method will be deprecated soon, so it should not be used.
As mentioned in address object, a delegatecall is different from a call in that the msg context does not change. For example, whereas a call changes the value of msg.sender to be the calling contract, a delegatecall keeps the same msg.sender as in the calling contract. Essentially, delegatecall runs the code of another contract inside the context of the execution of the current contract. It is most often used to invoke code from a library. It also allows you to draw on the pattern of using library functions stored elsewhere, but have that code work with the storage data of your contract.
The delegate call should be used with great caution. It can have some unexpected effects, especially if the contract you call was not designed as a library.
Let's use an example contract to demonstrate the various call semantics used by call and delegatecall for calling libraries and contracts. In CallExamples.sol: An example of different call semantics, we use an event to log the details of each call and see how the calling context changes depending on the call type.
CallExamples.sol: An example of different call semantics
include::code/truffle/CallExamples/contracts/CallExamples.sol[]
As you can see in this example, our main contract is caller, which calls a library calledLibrary and a contract calledContract. Both the called library and the contract have identical calledFunction functions, which emit an event calledEvent. The event calledEvent logs three pieces of data: msg.sender, tx.origin, and this. Each time calledFunction is called it may have a different execution context (with different values for potentially all the context variables), depending on whether it is called directly or through delegatecall.
In caller, we first call the contract and library directly, by invoking calledFunction in each. Then, we explicitly use the low-level functions call and delegatecall to call calledContract.calledFunction. This way we can see how the various calling mechanisms behave.
Let's run this in a Truffle development environment and capture the events, to see how it looks:
truffle(develop)> migrate Using network 'develop'. [...] Saving artifacts... truffle(develop)> web3.eth.accounts[0] '0x627306090abab3a6e1400e9345bc60c78a8bef57' truffle(develop)> caller.address '0x8f0483125fcb9aaaefa9209d8e9d7b9c8b9fb90f' truffle(develop)> calledContract.address '0x345ca3e014aaf5dca488057592ee47305d9b3e10' truffle(develop)> calledLibrary.address '0xf25186b5081ff5ce73482ad761db0eb0d25abfbf' truffle(develop)> caller.deployed().then( i => { callerDeployed = i }) truffle(develop)> callerDeployed.make_calls(calledContract.address).then(res => \ { res.logs.forEach( log => { console.log(log.args) })}) { sender: '0x8f0483125fcb9aaaefa9209d8e9d7b9c8b9fb90f', origin: '0x627306090abab3a6e1400e9345bc60c78a8bef57', from: '0x345ca3e014aaf5dca488057592ee47305d9b3e10' } { sender: '0x627306090abab3a6e1400e9345bc60c78a8bef57', origin: '0x627306090abab3a6e1400e9345bc60c78a8bef57', from: '0x8f0483125fcb9aaaefa9209d8e9d7b9c8b9fb90f' } { sender: '0x8f0483125fcb9aaaefa9209d8e9d7b9c8b9fb90f', origin: '0x627306090abab3a6e1400e9345bc60c78a8bef57', from: '0x345ca3e014aaf5dca488057592ee47305d9b3e10' } { sender: '0x627306090abab3a6e1400e9345bc60c78a8bef57', origin: '0x627306090abab3a6e1400e9345bc60c78a8bef57', from: '0x8f0483125fcb9aaaefa9209d8e9d7b9c8b9fb90f' }
Let's see what happened here. We called the make_calls function and passed the address of calledContract, then caught the four events emitted by each of the different calls. Let's look at the make_calls function and walk through each step.
The first call is:
_calledContract.calledFunction();
Here, we're calling calledContract.calledFunction directly, using the high-level ABI for calledFunction. The event emitted is:
sender: '0x8f0483125fcb9aaaefa9209d8e9d7b9c8b9fb90f', origin: '0x627306090abab3a6e1400e9345bc60c78a8bef57', from: '0x345ca3e014aaf5dca488057592ee47305d9b3e10'
As you can see, msg.sender is the address of the caller contract. The tx.origin is the address of our account, web3.eth.accounts[0], that sent the transaction to caller. The event was emitted by calledContract, as we can see from the last argument in the event.
The next call in make_calls is to the library:
calledLibrary.calledFunction();
It looks identical to how we called the contract, but behaves very differently. Let's look at the second event emitted:
sender: '0x627306090abab3a6e1400e9345bc60c78a8bef57', origin: '0x627306090abab3a6e1400e9345bc60c78a8bef57', from: '0x8f0483125fcb9aaaefa9209d8e9d7b9c8b9fb90f'
This time, the msg.sender is not the address of caller. Instead, it is the address of our account, and is the same as the transaction origin. That's because when you call a library, the call is always delegatecall and runs within the context of the caller. So, when the calledLibrary code was running, it inherited the execution context of caller, as if its code was running inside caller. The variable this (shown as from in the event emitted) is the address of caller, even though it is accessed from within calledLibrary.
The next two calls, using the low-level call and delegatecall, verify our expectations, emitting events that mirror what we just saw.
Gas Considerations
Gas, described in more detail in Gas, is an incredibly important consideration in smart contract programming. Gas is a resource constraining the maximum amount of computation that Ethereum will allow a transaction to consume. If the gas limit is exceeded during computation, the following series of events occurs:
- An "out of gas" exception is thrown.
- The state of the contract prior to execution is restored (reverted).
- All ether used to pay for the gas is taken as a transaction fee; it is not refunded.
Because gas is paid by the user who initiates the transaction, users are discouraged from calling functions that have a high gas cost. It is thus in the programmer's best interest to minimize the gas cost of a contract's functions. To this end, there are certain practices that are recommended when constructing smart contracts, so as to minimize the gas cost of a function call.
Avoid Dynamically Sized Arrays
Any loop through a dynamically sized array where a function performs operations on each element or searches for a particular element introduces the risk of using too much gas. Indeed, the contract may run out of gas before finding the desired result, or before acting on every element, thus wasting time and ether without giving any result at all.
Avoid Calls to Other Contracts
Calling other contracts, especially when the gas cost of their functions is not known, introduces the risk of running out of gas. Avoid using libraries that are not well tested and broadly used. The less scrutiny a library has received from other programmers, the greater the risk of using it.
Estimating Gas Cost
If you need to estimate the gas necessary to execute a certain method of a contract considering its arguments, you could use the following procedure:
var contract = web3.eth.contract(abi).at(address); var gasEstimate = contract.myAweSomeMethod.estimateGas(arg1, arg2, {from: account});
gasEstimate will tell you the number of gas units needed for its execution. It is an estimate because of the Turing completeness of the EVM—it is relatively trivial to create a function that will take vastly different amounts of gas to execute different calls. Even production code can change execution paths in subtle ways, resulting in hugely different gas costs from one call to the next. However, most functions are sensible and estimateGas will give a good estimate most of the time.
To obtain the gas price from the network you can use:
var gasPrice = web3.eth.getGasPrice();
And from there you can estimate the gas cost:
var gasCostInEther = web3.utils.fromWei((gasEstimate * gasPrice), 'ether');
Let's apply our gas estimation functions to estimating the gas cost of our Faucet example, using the code from the book's repository.
Start Truffle in development mode and execute the JavaScript file in gas_estimates.js: Using the estimateGas function, _gas_estimates.js_.
gas_estimates.js: Using the estimateGas function
[source,javascript] ---- var FaucetContract = artifacts.require("./Faucet.sol"); FaucetContract.web3.eth.getGasPrice(function(error, result) { var gasPrice = Number(result); console.log("Gas Price is " + gasPrice + " wei"); // "10000000000000" // Get the contract instance FaucetContract.deployed().then(function(FaucetContractInstance) { // Use the keyword 'estimateGas' after the function name to get the gas // estimation for this particular function (aprove) FaucetContractInstance.send(web3.utils.toWei(1, "ether")); return FaucetContractInstance.withdraw.estimateGas(web3.utils.toWei(0.1, "ether")); }).then(function(result) { var gas = Number(result); console.log("gas estimation = " + gas + " units"); console.log("gas cost estimation = " + (gas * gasPrice) + " wei"); console.log("gas cost estimation = " + FaucetContract.web3.utils.fromWei((gas * gasPrice), 'ether') + " ether"); }); }); ----
Here's how that looks in the Truffle development console:
$ truffle develop truffle(develop)> exec gas_estimates.js Using network 'develop'. Gas Price is 20000000000 wei gas estimation = 31397 units gas cost estimation = 627940000000000 wei gas cost estimation = 0.00062794 ether
It is recommended that you evaluate the gas cost of functions as part of your development workflow, to avoid any surprises when deploying contracts to the mainnet.
Conclusions
In this chapter we started working with smart contracts in detail and explored the Solidity contract programming language. We took a simple example contract, Faucet.sol, and gradually improved it and made it more complex, using it to explore various aspects of the Solidity language. In Smart Contracts and Vyper we will work with Vyper, another contract-oriented programming language. We will compare Vyper to Solidity, showing some of the differences in the design of these two languages and deepening our understanding of smart contract programming.
Smart Contracts and Vyper
Vyper is an experimental, contract-oriented programming language for the Ethereum Virtual Machine that strives to provide superior auditability, by making it easier for developers to produce intelligible code. In fact, one of the principles of Vyper is to make it virtually impossible for developers to write misleading code.
In this chapter we will look at common problems with smart contracts, introduce the Vyper contract programming language, and compare it to Solidity, demonstrating the differences.
Vulnerabilities and Vyper
A recent study analyzed nearly one million deployed Ethereum smart contracts and found that many of these contracts contained serious vulnerabilities. During their analysis, the researchers outlined three basic categories of trace vulnerabilities:
- Suicidal contracts: Smart contracts that can be killed by arbitrary addresses
- Greedy contracts: Smart contracts that can reach a state in which they cannot release ether
- Prodigal contracts: Smart contracts that can be made to release ether to arbitrary addresses
Vulnerabilities are introduced into smart contracts via code. It may be strongly argued that these and other vulnerabilities are not intentionally introduced, but regardless, undesirable smart contract code evidently results in the unexpected loss of funds for Ethereum users, and this is not ideal. Vyper is designed to make it easier to write secure code, or equally to make it more difficult to accidentally write misleading or vulnerable code.
Comparison to Solidity
One of the ways in which Vyper tries to make unsafe code harder to write is by deliberately omitting some of Solidity's features. It is important for those considering developing smart contracts in Vyper to understand what features Vyper does not have, and why. Therefore, in this section, we will explore those features and provide justification for why they have been omitted.
Modifiers
As we saw in the previous chapter, in Solidity you can write a function using modifiers. For example, the following function, changeOwner, will run the code in a modifier called onlyBy as part of its execution:
function changeOwner(address _newOwner) public onlyBy(owner) { owner = _newOwner; }
This modifier enforces a rule in relation to ownership. As you can see, this particular modifier acts as a mechanism to perform a pre-check on behalf of the changeOwner function:
modifier onlyBy(address _account) { require(msg.sender == _account); _; }
But modifiers are not just there to perform checks, as shown here. In fact, as modifiers, they can significantly change a smart contract's environment, in the context of the calling function. Put simply, modifiers are pervasive.
Let's look at another Solidity-style example:
enum Stages { SafeStage, DangerStage, FinalStage } uint public creationTime = now; Stages public stage = Stages.SafeStage; function nextStage() internal { stage = Stages(uint(stage) + 1); } modifier stageTimeConfirmation() { if (stage == Stages.SafeStage && now >= creationTime + 10 days) nextStage(); _; } function a() public stageTimeConfirmation // More code goes here { }
On the one hand, developers should always check any other code that their own code is calling. However, it is possible that in certain situations (like when time constraints or exhaustion result in lack of concentration) a developer may overlook a single line of code. This is even more likely if the developer has to jump around inside a large file while mentally keeping track of the function call hierarchy and committing the state of smart contract variables to memory.
Let's look at the preceding example in a bit more depth. Imagine that a developer is writing a public function called a. The developer is new to this contract and is utilizing a modifier written by someone else. At a glance, it appears that the stageTimeConfirmation modifier is simply performing some checks regarding the age of the contract in relation to the calling function. What the developer may not realize is that the modifier is also calling another function, nextStage. In this simplistic demonstration scenario, simply calling the public function a results in the smart contract's stage variable moving from SafeStage to DangerStage.
Vyper has done away with modifiers altogether. The recommendations from Vyper are as follows: if only performing assertions with modifiers, then simply use inline checks and asserts as part of the function; if modifying smart contract state and so forth, again make these changes explicitly part of the function. Doing this improves auditability and readability, as the reader doesn't have to mentally (or manually) "wrap" the modifier code around the function to see what it does.
Class Inheritance
Inheritance allows programmers to harness the power of prewritten code by acquiring preexisting functionality, properties, and behaviors from existing software libraries. Inheritance is powerful and promotes the reuse of code. Solidity supports multiple inheritance as well as polymorphism, but while these are key features of object-oriented programming, Vyper does not support them. Vyper maintains that the implementation of inheritance requires coders and auditors to jump between multiple files in order to understand what the program is doing. Vyper also takes the view that multiple inheritance can make code too complicated to understand—a view tacitly admitted by the Solidity documentation, which gives an example of how multiple inheritance can be problematic.
Inline Assembly
Inline assembly gives developers low-level access to the Ethereum Virtual Machine, allowing Solidity programs to perform operations by directly accessing EVM instructions. For example, the following inline assembly code adds 3 to memory location 0x80:
3 0x80 mload add 0x80 mstore
Vyper considers the loss of readability to be too high a price to pay for the extra power, and thus does not support inline assembly.
Function Overloading
Function overloading allows developers to write multiple functions of the same name. Which function is used on a given occasion depends on the types of the arguments supplied. Take the following two functions, for example:
function f(uint _in) public pure returns (uint out) { out = 1; } function f(uint _in, bytes32 _key) public pure returns (uint out) { out = 2; }
The first function (named f) accepts an input argument of type uint; the second function (also named f) accepts two arguments, one of type uint and one of type bytes32. Having multiple function definitions with the same name taking different arguments can be confusing, so Vyper does not support function overloading.
Variable Typecasting
There are two sorts of typecasting: implicit and explicit
Implicit typecasting is often performed at compile time. For example, if a type conversion is semantically sound and no information is likely to be lost, the compiler can perform an implicit conversion, such as converting a variable of type uint8 to uint16. The earliest versions of Vyper allowed implicit typecasting of variables, but recent versions do not.
Explicit typecasts can be inserted in Solidity. Unfortunately, they can lead to unexpected behavior. For example, casting a uint32 to the smaller type uint16 simply removes the higher-order bits, as demonstrated here:
uint32 a = 0x12345678; uint16 b = uint16(a); // Variable b is 0x5678 now
Vyper instead has a convert function to perform explicit casts. The convert function (found on line 82 of convert.py):
def convert(expr, context): output_type = expr.args[1].s if output_type in conversion_table: return conversion_table[output_type](expr, context) else: raise Exception("Conversion to {} is invalid.".format(output_type))
Note the use of conversion_table (found on line 90 of the same file), which looks like this:
conversion_table = { 'int128': to_int128, 'uint256': to_unint256, 'decimal': to_decimal, 'bytes32': to_bytes32, }
When a developer calls convert, it references conversion_table, which ensures that the appropriate conversion is performed. For example, if a developer passes an int128 to the convert function, the to_int128 function on line 26 of the same (convert.py) file will be executed. The to_int128 function is as follows:
@signature(('int128', 'uint256', 'bytes32', 'bytes'), 'str_literal') def to_int128(expr, args, kwargs, context): in_node = args[0] typ, len = get_type(in_node) if typ in ('int128', 'uint256', 'bytes32'): if in_node.typ.is_literal and not SizeLimits.MINNUM <= in_node.value <= SizeLimits.MAXNUM: raise InvalidLiteralException( "Number out of range: {}".format(in_node.value), expr ) return LLLnode.from_list( ['clamp', ['mload', MemoryPositions.MINNUM], in_node, ['mload', MemoryPositions.MAXNUM]], typ=BaseType('int128'), pos=getpos(expr) ) else: return byte_array_to_num(in_node, expr, 'int128')
As you can see, the conversion process ensures that no information can be lost; if it could be, an exception is raised. The conversion code prevents truncation as well as other anomalies that would ordinarily be allowed by implicit typecasting.
Choosing explicit over implicit typecasting means that the developer is responsible for performing all casts. While this approach does produce more verbose code, it also improves the safety and auditability of smart contracts.
Preconditions and Postconditions
Vyper handles preconditions, postconditions, and state changes explicitly. While this produces redundant code, it also allows for maximal readability and safety. When writing a smart contract in Vyper, a developer should observe the following three points:
- Condition: What is the current state/condition of the Ethereum state variables?
- Effects: What effects will this smart contract code have on the condition of the state variables upon execution? That is, what will be affected, and what will not be affected? Are these effects congruent with the smart contract's intentions?
- Interaction: After the first two considerations have been exhaustively dealt with, it is time to run the code. Before deployment, logically step through the code and consider all of the possible permanent outcomes, consequences, and scenarios of executing the code, including interactions with other contracts.
Ideally, each of these points should be carefully considered and then thoroughly documented in the code. Doing so will improve the design of the code, ultimately making it more readable and auditable.
Decorators
The following decorators may be used at the start of each function:
- @private: The @private decorator makes the function inaccessible from outside the contract.
- @public: The @public decorator makes the function both visible and executable publicly. For example, even the Ethereum wallet will display such functions when viewing the contract.
- @constant: Functions with the @constant decorator are not allowed to change state variables. In fact, the compiler will reject the entire program (with an appropriate error) if the function tries to change a state variable.
- @payable: Only functions with the @payable decorator are allowed to transfer value.
Vyper implements the logic of decorators explicitly. For example, the Vyper compilation process will fail if a function has both a @payable decorator and a @constant decorator. This makes sense because a function that transfers value has by definition updated the state, so cannot be @constant. Each Vyper function must be decorated with either @public or @private (but not both!).
Function and Variable Ordering
Each individual Vyper smart contract consists of a single Vyper file only. In other words, all of a given Vyper smart contract's code, including all functions, variables, and so forth, exists in one place. Vyper requires that each smart contract's function and variable declarations are physically written in a particular order. Solidity does not have this requirement at all. Let's take a quick look at a Solidity example:
pragma solidity ^0.4.0; contract ordering { function topFunction() external returns (bool) { initiatizedBelowTopFunction = this.lowerFunction(); return initiatizedBelowTopFunction; } bool initiatizedBelowTopFunction; bool lowerFunctionVar; function lowerFunction() external returns (bool) { lowerFunctionVar = true; return lowerFunctionVar; } }
In this example, the function called topFunction is calling another function, lowerFunction. topFunction is also assigning a value to a variable called initiatizedBelowTopFunction. As you can see, Solidity does not require these functions and variables to be physically declared before being called upon by the excecuting code. This is valid Solidity code that will compile successfully.
Vyper's ordering requirements are not a new thing; in fact, these ordering requirements have always been present in Python programming. The ordering required by Vyper is straightforward and logical, as illustrated in this next example:
# Declare a variable called theBool theBool: public(bool) # Declare a function called topFunction @public def topFunction() -> bool: # Assign a value to the already declared function called theBool self.theBool = True return self.theBool # Declare a function called lowerFunction @public def lowerFunction(): # Call the already declared function called topFunction assert self.topFunction()
This shows the correct ordering of functions and variables in a Vyper smart contract. Note how the variable theBool and the function topFunction are declared before they are assigned a value and called, respectively. If theBool was declared below topFunction or if topFunction was declared below lowerFunction this contract would not compile.