Tag: lesson
Prince Harry insisted ‘those Brits need to learn a lesson’ ahead of Oprah interview
Atari’s 50th anniversary celebration gives players a hands-on lesson in video gaming history
Announced earlier this year, Atari’s 50th anniversary celebration release, known as Atari 50, was formally launched on Friday across most major console and PC platforms. The collection provides users with a combination of old, new, and reimagined games, as well as interactive timelines and information highlighting Atari’s history and contributions…
An investing lesson from the falling Rolls-Royce share price
The Rolls-Royce share price has tumbled 40% in a year. What has shareholder Christopher Ruane learnt — and how will he respond?
The post An investing lesson from the falling Rolls-Royce share price appeared first on The Motley Fool UK.
EDEN CONFIDENTIAL: Prue Leith reveals etiquette lesson from Prince Philip
Learn Solidity lesson 23. Loops and conditionals.
Solidity has loops and conditionals similar to other programming languages. Its syntax is pretty much the same as C, Java, and JavaScript, so this chapter should be straightforward for anyone who is used to programming in languages like the ones above.
if/else/else if
When the program finds some kind of fork in its flow, where it must follow a certain path if a condition is satisfied, we have a conditional. For this type of situation we use the keywords if/else.
if (condition) {
...
code to be executed if the condition is satisfied.
...
} else {
...
code to be executed if the condition is not satisfied.
...
}
The condition must be an expression that returns true or false, such as x > 3 or (y < 1 && z == 4). Note that Solidity does not convert the value 1 to true and neither convert an empty string to false.
Often, instead of using if/else, it is better to use require to check a condition. They don’t have the same effect and should be used according to the code’s purpose.
Let’s suppose that we want a function to be correctly executed only if the sender of the transaction is an address previously registered in the variable owner. We could have the following.
function onlyOwner() public {
if (msg.sender === owner) {
... some code
}
}
If the sender is not the address of owner, the above function will have no effect, but the transaction will be valid and will not throw an error. This is usually not what we want. We could improve this function to throw an error, as below.
function onlyOwner() public {
if (msg.sender == owner) {
... some code
} else
revert("Sender not owner");
}
}
The transaction will be rolled back if the owner is not the sender of the transaction, via the revert method. The above conditional is common in other programming languages, but in Solidity it is better to use the require method in such cases.
function onlyOwner() public {
require(msg.sender == owner, "Sender not owner");
... some code
}
If the condition inside require is false, the transaction will roll back. As a second parameter, we can send an error message to the sender of the transaction.
Solidity also accepts the else if expression, which allows you to chain conditionals, as below.
if (condition) {... code ...}
else if (condition) {... code ...}
...
else {... code ...}
In other programming languages, the above chained conditional can be replaced by using switch, but this keyword does not exist in Solidity. In the above scenario, we must use multiple if’s.
while, do while and for loops
When we want a block of code to run multiple times, we use some form of loop. Let’s start by looking at the use of while, which executes a block of code while a certain condition is true.
while (condition) {
// code to be executed
}
Inside a loop we can use two keywords: break and continue. If the EVM encounters a break inside a loop, it will exit the loop and continue the flow of code after the loop. If it finds a continue it will skip the rest of the code block and go back to the conditional, for one more iteration of the loop. Let’s see examples.
uint8 last;
uint8 i;
while(i < 10) {
last = i;
i++;
if (i==5) break;
} // last => 4
First we define a variable i that will act as a counter. The variable last will store the last value of the counter inside the conditional. For each iteration, we increment the counter.
When the variable i reaches the value of 4, in the loop block it is incremented to 5 (through the expression i++, which is equivalent to i=i+1). The conditional (i==5) will then be true, break will be executed and the loop is terminated.
An example using the continue keyword is shown below.
uint8 total;
uint8 i;
while(i < 10) {
i++;
if (i==5) continue;
total++;
} // total => 9
The above loop will be executed 10 times, as the variable i will run from 0 to 9. However, the variable total will end up with a value of 9, not 10. This happens because when i is 5, the condition (i==5) will be true and continue will be executed. This way the loop will go back to the beginning and the increment of the variable total will not be executed for that particular iteration.
The do while loop is similar to the while loop, the difference is that the condition is checked after the code block is executed, not at the beginning.
In the example below, at least the first iteration is executed, even though the condition is explicitly false.
uint8 value;
do {
value = 10;
} while(false); // value => 10
In the examples above, three essential ingredients were needed: a counter, a conditional, and a way to increment the counter. These three ingredients are easily implemented using the for loop.
for (initialize the counter; conditional; increment) {
// code to be executed
}
Let’s write an example to iterate over an array and change all of its entries.
uint[] memory array = new uint[](5);
for(uint i=0; i < array.length; i++) {
array[i] = i;
} // array => [0,1,2,3,4]
You have to be a little careful when using loops in Solidity, especially for adding/changing state variables. Managing state variables is one of the most gas-intensive operations on Ethereum, so a loop that makes multiple changes to state variables can consume a lot of gas.
Thanks for reading!
Comments and suggestions about this article are welcome.
Any contribution is welcome. www.buymeacoffee.com/jpmorais
Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing
Also, Read
- The Best Crypto Tax Software | CoinTracking Review
- Stackedinvest Review | Kraken Review | bitFlyer Review
- Best Crypto Lending Platforms | Leveraged Token
- Best Crypto Charting Tool | Best Crypto Exchange
- Bitsler Review |WazirX vs CoinSwitch vs CoinDCX
Learn Solidity lesson 23. Loops and conditionals. was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.
Learn Solidity lesson 20. Address type methods.
The address type is one of the most used in Solidity, as it indicates accounts on the blockchain.
Every account has a balance in the base coin. In the case of the Ethereum network, an account has a balance in Ether. On other EVM-compatible blockchains, such as Polygon, the balance is in some native token of the network, such as MATIC for Polygon.
In Solidity, it is possible to retrieve coin/token balance information that an account has, from within a contract. This is done using the balance property of a variable of type address, as below.
address myAddress = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
myAddress.balance; // returns uint256
I’m using an address from an account created by Remix. The value myAddress.balance is of type uint256. We can also use an address literal expression to access the balance property, as below.
0x5B38Da6a701c568545dCfcB03FcB875f56beddC4.balance;
The account balance returns with its entire value, including all decimal places. In the case of Ethereum, the value returns in Wei.
A very common use is to check the account balance of the contract itself. In Solidity, there is the object this, which indicates the current contract instance. We can use this to retrieve the contract address, via address(this). So we can recover the balance of the contract.
address(this).balance; // returns uint256
It is also possible to retrieve the contract bytecode using the code property, as below.
address(this).code; // returns bytes
The code of a contract is a variable of type bytes. We can retrieve the bytecode of any contract through its address.
Sending Ether
We can send Ether (or the base coin/token of the blockchain) to any account on the network, from within contracts. There is more than one method to do this and we will see the difference between them.
The account that sends Ether from within a contract is the account for the contract itself, so it is necessary to have a positive balance in Ether to be able to send it.
It should be noted that only payable addresses have such methods. Attempting to invoke the (address).transfer method, for example, for an address that is not of type payable will throw an error.
If the address is not payable, it is possible to cast the variable, as below.
payable(address).(...);
transfer
The method transfer sends Ether to a given address. If while sending Ether an error occurs, the entire transaction is reverted. Let’s write a contract to send Ether with this method.
contract Addresses {
constructor() payable {}
function sendEther(address payable _address) public {
_address.transfer(10 ether);
}
}
We first send Ether to the contract at deploy time. For this you need to use the payable modifier in the constructor. To be able to receive value when invoked, functions must be of type payable. The constructor function is the one invoked at deploy time.
The amount of 10 Ethers will be sent to an account whose address is an argument of the function sendEther. Note that the function parameter is of type address payable, not just address. This is necessary to use the method transfer.
Solidity has 3 value units: wei, gwei and ether. In the above example we are using the unit ether.
One occurrence that can cause the method transfer to revert is the contract account does not have sufficient balance. Another possibility is to try to send Ether to a contract account that does not have a payable function.
send
Another possibility is to use the method send to send Ether to an account. Let’s see this in the statement below.
_address.send(10 ether);
The difference between transfer and send is that the send method does not revert on an error. It returns true/false if the sending is successful /failure.
It is possible (and almost always desirable) to test the return of the send method, as follows.
bool success = _address.send(10 ether);
if (!success) {
revert();
}
We haven’t studied all the ingredients of the code above, but let’s try to understand it. The method send returns true or false, depending on the success of sending Ether. In the example above, the return is assigned to the variable success.
Then we check if the variable success has the value of false, in the expression if (!success) (reads ‘’if not success’’). If it was not successful, we execute the method revert(), which reverts the transaction.
call
The method call is not only used to send Ether to a certain account, but also to interact with a certain contract account, being able to invoke functions. However, it is possible to use this method to only send Ether, as this is an option when sending a transaction to any account (either external or contract).
We’ll have a lot more to say about the method call in another lesson. For the moment, let’s just see how to use it to send Ether.
_address.call{value: 10 ether}("");
As the method call can invoke a contract function, it must returns two values: a generic value, which is the return of the executed function, and the information whether the transaction was successful or not.
This means that the call method returns a pair of values. The first return parameter is boolean, while the second is of type bytes. As we are only interested in knowing the success or failure of sending Ether, we can use the code below.
(bool success, ) = _address.call{value: 10 ether}("");
We just grab the information whether the Ether sending was a success or not, and ignore the other parameter.
Should I use transfer, send or call?
There is a difference that we need to know between using transfer, send and call. The first 2 methods only forward 2300 units of gas to the target account, which is just enough to carry out the Ether transfer. The call method forwards all available gas to the target account.
Let me explain. The purpose of the call method is much broader than just sending Ether. It will call a function in another contract, and it is not possible to know how much gas this function will require. Therefore, all available gas is forwarded.
Care must be taken when invoking functions from other contracts. They can use the forwarded gas to carry out malicious operations, including hacking the contract that sent the call. Not only this can be done as it was done in the exploit called reentrancy.
Until recently, it was recommended to use the transfer method to transfer Ether. The transfer method forwards only 2300 units of gas, in order to prevent the receiving account from using the available gas for some malicious attitude.
However, currently the recommended method is to use call. The idea is that the Ethereum gas table is flexible, and it may be that in the future to ship Ether will cost more than 2300 units of gas. This could somehow break a compatibility between versions.
Anyway, you need to understand the difference between these 3 methods and know how each one works.
Call, delegatecall and staticcall.
The method call is used to invoke functions in other contracts, but it is not the only option. It is possible to interact with other contracts in a simpler way through its interface, without using any of the methods described in this lesson.
Both the call method, as well as the methods delegatecall and staticcall are low-level, where it is necessary to explicitly encode the function and the arguments that will be sent.
The methods call and staticcall have many similarities, however delegatecall introduces some differences. It is mostly used to invoke functions in contracts that act as libraries.
The use of such methods is a more advanced subject and will be studied in more detail in a future lesson.
Thanks for reading!
Comments and suggestions about this article are welcome.
Any contribution is welcome. www.buymeacoffee.com/jpmorais
Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing
Also, Read
- Bookmap Review | 5 Best Crypto Exchanges in the USA
- Crypto Trading bots | CoinGate Review
- The Best Crypto Hardware wallet | Bitbns Review
- 10 Best Crypto Exchange in Singapore | Buy AXS
- Red Dog Casino Review | Swyftx Review
Learn Solidity lesson 20. Address type methods. was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.