Basic Solidity

What is Solidity?

Solidity is a statically typed curly-braces programming language designed for developing smart contracts that run on the Ethereum Virtual Machine (EVM).

Solidity File Extension

A Solidity file is always saved with an .sol extension.

Import Statement

Just like JavaScript , you can import other files within a Solidity file and use a symbol for that file. You also have to specify the path of the file property.

import "filename" as symbolName;

syntax


pragma solidity ^0.8.1;
contract MyContract{
// Write code
}

Data Types

Data type is a particular kind of data defined by the values it can take.

Boolean :

  • Logical :
    • ! -> Logical negation
    • && -> AND
    • || -> OR
  • Comparisons :
    • == equality
    • != inequality

Bitwise Operators

&AND
|OR
^Bitwise XOR
~Bitwise negation , tilde
<<Left Shift
>>Right Shift

Arithmetic Operators

+Addition
Subtraction
*Multiplication
/Division
%Modulus
++Increment
Decrement

Relation Operators

<=Less than or equal to
<Less than
==equal to
!=Not equal to
>=Grater than or equal to
>Greater than

Assignment Opertors

=Simple Assignment
+=Add Assignment
-=Subtract Assignment
*=Multiply Assignment
/=Divide Assignment
%=Modulus Assignment

Value types :

Boolean

This data type accepts only two values. True or False.

Integer

This data type is used to store integer values, int and uint are used to declare singed and unsigned integer respectively.

Address

Address hold a 20-byte value which represents the size of an Ethereum address. An address can be use to get balance or to transfer a balance by balance and transfer method respectively.

Bytes and Strings

Bytes are used to store a fixed-sized character set while the string is used to store the character set equal to or more than a byte. The length of bytes is form 1 to 32, while the string has a dynamic length.

Enums

it is used to create user-defined data types, used to assign a name to an integral constant which makes the contract more readable, maintainable , and less prone to errors. Options of enums can be represented by unsigned integer values starting from 0.

Reference Types

Arrays

An array is group of variables of the same data type in which variable has a particular location known as an index. By using the index location, the desired variable can be accessed.

Array can be dynamic or fixed size array.

uint[] dynamicSizeArray;
 uint[10] fixedSizeArray;

Struct


struct product {
  string name;
  uint price;
  uint product_id;
}

Mapping

Mapping is a most used reference type, that stores the data in a key-value pair where a key can be any types. it is like a hash table or dictionary as in any other programming language, where data can be retrieved by key.


mapping(_KeyType => _ValueType)

_KeyType can be any built-in types plus bytes and string. No reference type or complex objects are allowed.

_ValueType – can be any type.

Function Visibility Specifiers


function myFunction() <visibility specifier> returns (bool) {
    return true;
}

publicvisible externally and internally (creates a getter function for storage/state variables)
private only visible in the current contract
externalonly visible externally (only for functions) – i.e. can only be message-called (via this.func)
internalonly visible internally

Modifiers

purefor functions: Disallows modification or access of state.
viewfor functions: Disallows modification of state.
payablefor functions: Allows them to receive Ether together with a call.
constantfor state variables: Disallows assignment (except initialisation),
does not occupy storage slot.
immutablefor state variables: Allows exactly one assignment at construction
time and is constant afterwards. Is stored in code.
anonymousfor events: Does not store event signature as topic.
indexedfor event parameters: Stores the parameter as topic.
virtualfor functions and modifiers: Allows the function’s or modifier’s
behaviour to be changed in derived contracts.
overrideStates that this function, modifier or public state variable changes the behaviour of a function or modifier in a base contract.

Global Variables

this (current contract’s type)the current contract, explicitly convertible to address or address payable
superthe contract one level higher in the inheritance hierarchy
selfdestruct(address payable recipient)destroy the current contract, sending its funds to the given address
<address>.balance (uint256)balance of the Address in Wei

<address>.code (bytes memory)code at the Address (can be empty)
<address>.codehash (bytes32)the codehash of the Address
<address payable>.send(uint256 amount) returns (bool)send given amount of Wei to Address, returns false on failure
<address payable>.transfer(uint256 amount)send given amount of Wei to Address, throws on failure
msg.sender (address)sender of the message (current call)
msg.data (bytes)complete calldata
msg.sig (bytes4)first four bytes of the calldata (i.e. function identifier)
msg.value (uint)number of wei sent with the message
tx.gasprice (uint)gas price of the transaction
tx.origin (address)sender of the transaction (full call chain)
block.basefee (uint)current block’s base fee (EIP-3198 and EIP-1559)
block.chainid (uint)current chain id
block.coinbase (address payable)current block miner’s address
block.difficulty (uint)current block difficulty
block.gaslimit (uint)current block gaslimit
block.number (uint)current block number
block.timestamp (uint)current block timestamp in seconds since Unix epoch
gasleft() returns (uint256)remaining gas
assert(bool condition)abort execution and revert state changes if condition is false (use for internal error)
require(bool condition)abort execution and revert state changes if condition is false (use for malformed input or error in external component)

require(bool condition, string memory message)abort execution and revert state changes if condition is false (use for malformed input or error in external component). Also provide error message.
revert()abort execution and revert state changes
revert(string memory message)abort execution and revert state changes providing an explanatory string
blockhash(uint blockNumber) returns (bytes32)hash of the given block – only works for 256 most recent blocks
keccak256(bytes memory) returns (bytes32)compute the Keccak-256 hash of the input
sha256(bytes memory) returns (bytes32)compute the SHA-256 hash of the input
ripemd160(bytes memory) returns (bytes20)compute the RIPEMD-160 hash of the input
ecrecover(bytes32 hash, uint8 v, bytes32 r,
 bytes32 s) returns (address)
recover address associated with the public key from elliptic curve signature, return zero on error
learn more

Reserved Keywords

afteraliasapplyauto
bytecasecopyofdefault
definefinalimplementsin
inlineletmacromatch
mutablenullofpartial
promisereferencerelocatablesealed
sizeofstaticsupportsswitch
typedeftypeofvar

I hope you like this article.

Also Read :