In this tutorial, we will cover Solidity syntax, specifically on using the using - for
keyword, error handling, global variables, mathematical and cryptographic functions, and contract-related keywords.
The using A for B;
syntax in Solidity can be used to attach library functions to any type. For example, the following code attaches a library function called add
from the arithmatic
library to the uint
type:
library arithmatic {
function add(uint _a, uint _b) returns (uint) {
return _a + _b;
}
}
contract C {
using arithmatic for uint;
uint sum;
function f(uint _a) {
sum = _a.add(3);
}
}
In the above code, the library arithmatic
contains a function called add
that takes two uint
arguments and returns their sum. We then use the using arithmatic for uint
syntax to attach the add
function to the uint
type. This allows us to call the add
function on any uint
variable, as shown in the f
function.
Solidity provides three functions for error handling: assert
, require
, and revert
.
assert(bool condition)
: throws if the condition is not met. This function is used for internal errors that should never occur, and its failure indicates a bug in the code.require(bool condition)
: throws if the condition is not met. This function is used for errors in inputs or external components.revert()
: abort execution and revert state changes. This function is used to explicitly trigger a revert without any error message.function sendHalf(address addr) payable returns (uint balance) {
require(msg.value % 2 == 0); // Only allow even numbers
uint balanceBeforeTransfer = this.balance;
addr.transfer(msg.value / 2);
assert(this.balance == balanceBeforeTransfer - msg.value / 2);
return this.balance;
}
In the above code, the require
function checks that the msg.value
is an even number. If it is not, the function will throw an error and the transaction will be reverted. The assert
function checks that the balance of the contract before and after the transfer is as expected. If it is not, the function will throw an error and the transaction will be reverted.
Solidity provides several global variables that can be used in smart contract development. These include block variables and transaction variables.
block.blockhash(uint blockNumber) returns (bytes32)
: hash of the given block - only works for the 256 most recent blocks excluding currentblock.coinbase (address)
: current block miner’s addressblock.difficulty (uint)
: current block difficultyblock.gaslimit (uint)
: current block gaslimitblock.number (uint)
: current block number