Module V-Part 2
Module V-Part 2
Part II - Solidity
The Solidity Language
It has features like inheritance, libraries, and the ability to define composite data
types.
The basic layout of the Solidity source file contains following in order:
Each Solidity contract/library source file should have the version of Solidity
compiler specified.
The version of the compiler should be specified first thing in the source file.
If a source file is of this version, it means the file will compile with 0.4.4 and higher
versions in the 0.4.x branch, up to version 0.5.0 where 0.5.0 is not included.
It is recommended that the Solidity version should be locked and specified without
the ^ (caret) sign, as follows:
This ensures that the specific compiler version will always be used.
Importing other source files
Solidity supports an import statement to import other source files.
import "path/to/file/filename.sol";
In the preceding example, the absolute path of the file should be specified.
Comments
Comments can be added in the Solidity source code file in a manner similar to
C-language.
Multiple line comments are enclosed in /* and */, whereas single line comments
start with //.
A sample solidity program
Structure of a contract
Each Solidity contract can contain declarations of one or many state variables,
constants, a constructor function, enumerations types, function modifiers, events,
functions, and struct types.
We can also define special kinds of contracts called libraries and interfaces.
The state variables defined in contract are values that are permanently stored in
contract storage over the Ethereum blockchain.
The variables defined outside of the method/function body are accessible to the
whole contract.
contract VariableStorage {
uint balanceAmount; //uint256 storage variable
//...
}
2. Custom types for constants with enum
Enums can be used to create a custom data type with a fixed set of constant values.
Enums will have integer values assigned, starting from 0 and ascending to the number of states
defined in enum.
contract Loan {
//Enum for LoanStatus
enum LoanStatus { Pending,
Created,
Funded,
Finished,
Defaulted
}
LoanStatus status; //Enum variable declaration
function setValue() public {
status = LoanStatus.Created;
}
}
3. Custom data types with struct
Structs are custom-defined data types that can group multiple variables in a single struct
variable to form a new type.
By default, all struct values are initialized using their default values.
For example, uint values will be initialized with 0; bool values will be initialized with false;
and address values will be initialized with 0x0.
contract LoanStruct {
//Definition of struct
struct LoanData {
address borrower;
address lender;
uint256 loanAmount;
}
}
4. Function modifiers
The modifiers are used to check the pre- and post-conditions before calling a
method.
The function modifiers are also used to maintain the access and role-based
control on the contract.
The definition says that the withdraw function can only be allowed to call from the
owner address:
contract AccountContract { Function modifier
definition
address public owner;
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_; //Rest of the function body execution
} Modifier called along with
‘withdraw()’
function withdraw() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
Solidity contracts do not have a way to generate logs when they are executed.
When events are emitted, its data is stored in the transaction's log.
When writing a contract or library definition, all of the state variables and local
variables must have the data type specified along with its declaration.
We can create your own custom type by using the data types supported by
Solidity; for example, using the struct variable.
Value types: The data types whose values are copied when passed as method
arguments. These are int, uint, bool, and address.
Reference types: The data types whose references are copied when passed as
method arguments. These are array and struct.
Some int and uint value types in Solidity support various sizes to reduce gas
consumption and storage space.
You should choose the appropriate value type based on your data requirements.
The bool and address value types do not have different sizes, as their size is fixed.
Solidity supports the bool data type that can store values such as true or false.
The address data type represents the public address of an external account or a
smart contract.
An address data type stores 20 bytes value that represents an Ethereum address.
The address type has only one member property, that is, .balance.
<address>.balance
This returns the current ether balance of an address as uint256 and is represented
in wei.
<address>.transfer(uint256 amount)
In the call, address is the public address of external account or contract account,
and the amount parameter is always specified in wei.
Sending ether using send
The .send() function is used to send ether units in wei to another external account
or contract account.
The only difference is that this call returns a bool result to indicate that the .send
operation succeeded or not.
Solidity control structures
do...while loop: Also supports do...while loop constructs NB: Give examples from C
break keyword: To exit from the loop that is currently being executed on a certain
condition
continue keyword: To continue the loop for the next iteration upon a certain
condition
These are quite useful when external interfaces are required to be notified of any
change or event in the contract.
Logs cannot be accessed from the contracts but are used as a mechanism to
notify change of state or the occurrence of an event (meeting a condition) in the
contract.
pragma solidity ^0.4.0;
contract valueChecker
{
uint8 price=10;
event valueEvent(bool returnValue);
function Matcher(uint8 x) public returns (bool)
{
if (x>=price)
{
valueEvent(true);
return true;
}
} The valueEvent event will return true if the x parameter passed to function
} Matcher is equal to or greater than 10
Inheritance
The derived contract has access to all non-private members of the parent contract:
Keyword for
inheritance
Libraries are deployed only once at a specific address and their code is called via
CALLCODE or DELEGATECALL opcode of the EVM.
They are similar to contracts and act as base contracts to the calling contracts.
First, it needs to be imported and then it can be used anywhere in the code.
Imports library
example
Limitations of Library
Functions in Solidity are modules of code that are associated with a contract.
Function signature: Functions in Solidity are identified by its signature, which is the
first four bytes of the Keccak-256 hash of its full signature string.
Input parameters of a function
Public: By default, functions are public. They can be called either internally or
using messages.
Internal: Internal functions are visible to other derived contracts from the parent
contract.
Private: Private functions are only visible to the same contract they are declared
in.
Error handling in Solidity
In Solidity code, when certain conditions are met, you can throw an exception and
fail the transactions.
You can check for method input argument's correctness and revert the transaction
if arguments are not in order.
When a transaction is reverted or failed, all of its state changes and variable
modifications are reverted.
Also, the gas consumption it has consumed till the revert of the transaction will be
consumed and sent to miner, and the rest of the remaining gas will be refunded
back to the transaction initiator.
require(bool condition): This reverts the transaction if the Boolean condition is not
met.
require(bool condition, string message): Same as the previous bullet point, but
provides a message.
revert(): This aborts the execution of a transaction and reverts all state changes.
revert(string reason): This aborts the execution of a transaction and reverts all
state changes. Also shows error message.
Case Studies:
Voting: https://docs.soliditylang.org/en/v0.8.17/solidity-by-example.html#voting
You can find some other use cases too from the above URL.