What are primitive data types in Solidity?
Primitive data types in solidity are: – boolean
– uint
– int
– address
What are different variable types in Solidity?
There are 3 types of variables in Solidity – local – declared inside a function – not stored on the blockchain – state – declared outside a function – stored on the blockchain – global (provides information about the blockchain)
What is a constant in Solidity?
Constants are variables that cannot be modified. Their value is hard coded and using constants can save gas cost.
What is immutable variables in Solidity?
Immutable variables are like constants. Values of immutable variables can be set inside the constructor but cannot be modified afterwards.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Immutable {
// coding convention to uppercase constant variables
address public immutable MY_ADDRESS;
uint public immutable MY_UINT;
constructor(uint _myUint) {
MY_ADDRESS = msg.sender;
MY_UINT = _myUint;
}
}
How do you read from a state variable?
To read from a state variable you can define a getter function this can be done without sending a transaction like so:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract SimpleStorage {
// State variable to store a number
uint public num;
// You can read from a state variable without sending a transaction.
function get() public view returns (uint) {
return num;
}
}
How do you write to a state variable?
To write or update a state variable you need to send a transaction. You can define a function like so:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract SimpleStorage {
// State variable to store a number
uint public num;
// You need to send a transaction to write to a state variable.
function set(uint _num) public {
num = _num;
}
}
What is ether and wei?
Ether is Ethereum’s native currency. Transactions are paid with ether
. Similar to how one dollar is equal to 100 cent, one ether
is equal to 1018 wei
.
What is gas in Ethereum?
The pricing mechanism employed on the Ethereum blockchain to calculate the costs of smart contracts operations and transaction fees.
How much ether
do you need to pay for a transaction?
You pay gas spent * gas price
amount of ether
, where
gas
is a unit of computationgas spent
is the total amount ofgas
used in a transactiongas price
is how muchether
you are willing to pay pergas
Transactions with higher gas price have higher priority to be included in a block.
Unspent gas will be refunded.
What is Gas Limit in Solidity?
There are 2 upper bounds to the amount of gas you can spend
gas limit
(max amount of gas you’re willing to use for your transaction, set by you)-
block gas limit
(max amount of gas allowed in a block, set by the network)// SPDX-License-Identifier: MIT pragma solidity ^0.8.10;
contract Gas { uint public i = 0;
// Using up all of the gas that you send causes your transaction to fail. // State changes are undone. // Gas spent are not refunded. function forever() public { // Here we run a loop until all of the gas are spent // and the transaction fails while (true) { i += 1; } } }
How do you define an If/Else statement in Solidity?
Solidity supports conditional statements if
, else if
and else
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract IfElse {
function foo(uint x) public pure returns (uint) {
if (x < 10) {
return 0;
} else if (x < 20) {
return 1;
} else {
return 2;
}
}
function ternary(uint _x) public pure returns (uint) {
// if (_x < 10) {
// return 1;
// }
// return 2;
// shorthand way to write if / else statement
return _x < 10 ? 1 : 2;
}
}
How do you define a for loop in Solidity?
For loop in solidity can be defined as follows:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Loop {
function loop() public {
// for loop
for (uint i = 0; i < 10; i++) {
if (i == 3) {
// Skip to next iteration with continue
continue;
}
if (i == 5) {
// Exit loop with break
break;
}
}
}
}
Caution: Don’t write loops that are unbounded as this can hit the gas limit, causing your transaction to fail.
How do you define a while loop in Solidity?
// Solidity program to
// demonstrate the use
// of 'While loop'
pragma solidity ^0.8.0;
// Creating a contract
contract Types {
// Declaring a dynamic array
uint[] data;
// Declaring state variable
uint8 j = 0;
// Defining a function to
// demonstrate While loop'
function loop(
) public returns(uint[] memory){
while(j < 5) {
j++;
data.push(j);
}
return data;
}
}
Caution: Don’t write loops that are unbounded as this can hit the gas limit, causing your transaction to fail.
What is a mapping in Solidity?
Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type.
How do you define a array in Solidity?
Array can have a compile-time fixed size or a dynamic size and can be defined as follows:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Array {
// Several ways to initialize an array
uint[] public arr;
uint[] public arr2 = [1, 2, 3];
// Fixed sized array, all elements initialize to 0
uint[10] public myFixedSizeArr;
function get(uint i) public view returns (uint) {
return arr[i];
}
// Solidity can return the entire array.
// But this function should be avoided for
// arrays that can grow indefinitely in length.
function getArr() public view returns (uint[] memory) {
return arr;
}
function push(uint i) public {
// Append to array
// This will increase the array length by 1.
arr.push(i);
}
function pop() public {
// Remove last element from array
// This will decrease the array length by 1
arr.pop();
}
function getLength() public view returns (uint) {
return arr.length;
}
function remove(uint index) public {
// Delete does not change the array length.
// It resets the value at index to it's default value,
// in this case 0
delete arr[index];
}
function examples() external {
// create array in memory, only fixed size can be created
uint[] memory a = new uint[](5);
}
}
How do you define a mapping in Solidity?
Maps are created with the syntax mapping(keyType => valueType)
.
The keyType
can be any built-in value type, bytes, string, or any contract.
valueType
can be any type including another mapping or an array.
Mappings are not iterable.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Mapping {
// Mapping from address to uint
mapping(address => uint) public myMap;
function get(address _addr) public view returns (uint) {
// Mapping always returns a value.
// If the value was never set, it will return the default value.
return myMap[_addr];
}
function set(address _addr, uint _i) public {
// Update the value at this address
myMap[_addr] = _i;
}
function remove(address _addr) public {
// Reset the value to the default value.
delete myMap[_addr];
}
}
What are enum in Solidity?
Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Enum {
// Enum representing shipping status
enum Status {
Pending,
Shipped,
Accepted,
Rejected,
Canceled
}
// Default value is the first element listed in
// definition of the type, in this case "Pending"
Status public status;
// Returns uint
// Pending - 0
// Shipped - 1
// Accepted - 2
// Rejected - 3
// Canceled - 4
function get() public view returns (Status) {
return status;
}
// Update status by passing uint into input
function set(Status _status) public {
status = _status;
}
// You can update to a specific enum like this
function cancel() public {
status = Status.Canceled;
}
// delete resets the enum to its first value, 0
function reset() public {
delete status;
}
}
What are structs in Solidity?
Solidity allows user to create their own data type in the form of structure. The struct contains a group of elements with a different data type. Generally, it is used to represent a record. To define a structure struct keyword is used, which creates a new data type. Example code to use structs in solidity:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Todos {
struct Todo {
string text;
bool completed;
}
// An array of 'Todo' structs
Todo[] public todos;
function create(string memory _text) public {
// 3 ways to initialize a struct
// - calling it like a function
todos.push(Todo(_text, false));
// key value mapping
todos.push(Todo({text: _text, completed: false}));
// initialize an empty struct and then update it
Todo memory todo;
todo.text = _text;
// todo.completed initialized to false
todos.push(todo);
}
// Solidity automatically created a getter for 'todos' so
// you don't actually need this function.
function get(uint _index) public view returns (string memory text, bool completed) {
Todo storage todo = todos[_index];
return (todo.text, todo.completed);
}
// update text
function update(uint _index, string memory _text) public {
Todo storage todo = todos[_index];
todo.text = _text;
}
// update completed
function toggleCompleted(uint _index) public {
Todo storage todo = todos[_index];
todo.completed = !todo.completed;
}
}
What are various memory locations used to store solidity variables?
Variables are declared as either storage
, memory
or calldata
to explicitly specify the location of the data.
storage
– variable is a state variable (store on blockchain)memory
– variable is in memory and it exists while a function is being calledcalldata
– special data location that contains function arguments
Example:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract DataLocations {
uint[] public arr;
mapping(uint => address) map;
struct MyStruct {
uint foo;
}
mapping(uint => MyStruct) myStructs;
function f() public {
// call _f with state variables
_f(arr, map, myStructs[1]);
// get a struct from a mapping
MyStruct storage myStruct = myStructs[1];
// create a struct in memory
MyStruct memory myMemStruct = MyStruct(0);
}
function _f(
uint[] storage _arr,
mapping(uint => address) storage _map,
MyStruct storage _myStruct
) internal {
// do something with storage variables
}
// You can return memory variables
function g(uint[] memory _arr) public returns (uint[] memory) {
// do something with memory array
}
function h(uint[] calldata _arr) external {
// do something with calldata array
}
}
How do you define a function in Solidity?
There are several ways to return outputs from a function. Public functions cannot accept certain data types as inputs or outputs
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Function {
// Functions can return multiple values.
function returnMany()
public
pure
returns (
uint,
bool,
uint
)
{
return (1, true, 2);
}
// Return values can be named.
function named()
public
pure
returns (
uint x,
bool b,
uint y
)
{
return (1, true, 2);
}
// Return values can be assigned to their name.
// In this case the return statement can be omitted.
function assigned()
public
pure
returns (
uint x,
bool b,
uint y
)
{
x = 1;
b = true;
y = 2;
}
// Use destructuring assignment when calling another
// function that returns multiple values.
function destructuringAssignments()
public
pure
returns (
uint,
bool,
uint,
uint,
uint
)
{
(uint i, bool b, uint j) = returnMany();
// Values can be left out.
(uint x, , uint y) = (4, 5, 6);
return (i, b, j, x, y);
}
// Cannot use map for either input or output
// Can use array for input
function arrayInput(uint[] memory _arr) public {}
// Can use array for output
uint[] public arr;
function arrayOutput() public view returns (uint[] memory) {
return arr;
}
}
What is a view function in Solidity?
View
function declares that no state will be changed.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract View{
uint public x = 1;
// Promise not to modify the state.
function addToX(uint y) public view returns (uint) {
return x + y;
}
}
What is a pure function in Solidity?
Pure
function declares that no state variable will be changed or read.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Pure {
uint public x = 1;
// Promise not to modify or read from the state.
function add(uint i, uint j) public pure returns (uint) {
return i + j;
}
}
Leave a Reply