Read-only Functions Iteration Cost - ethereum

I am developing smart contracts for some use-cases and currently I'm working on optimization of smart contracts. I am confused with something that I found interesting on Hitchiker's Guide. In the section 4- Iterating the contract code
// returns true if proof is stored
// *read-only function*
function hasProof(bytes32 proof) constant returns (bool) {
for (uint256 i = 0; i < proofs.length; i++) {
if (proofs[i] == proof) {
return true;
}
}
return false;
}
For this code above, He states that "Note that every time we want to check if a document was notarized, we need to iterate through all existing proofs. This makes the contract spend more and more gas on each check as more documents are added. "
There is no doubt that the proper way of implementing it is to use mapping instead of array structure. Here is the point that makes me confused. It's read-only function and it is not a transaction that affects blockchain. When I observed my netstats, it does not show any transaction when this function is called(Actually, it is what I expected before calling this function).
I don't think that he misunderstood the mechanism, could someone clean my mind about this comment?

Roman’s answer is not correct. Constant functions still consume gas. However, you don’t pay for the gas usage when it runs in the local EVM. If a constant function is called from a transaction, it is not free. Either way, you are still consuming gas and loops are a good way to consume a lot.
EDIT - Here is an example to illustrate the point
pragma solidity ^0.4.19;
contract LoopExample {
bytes32[] proofs;
function addProof(bytes32 proof) public {
if (!hasProof(proof))
proofs.push(proof);
}
function hasProof(bytes32 proof) public constant returns (bool) {
for (uint256 i = 0; i < proofs.length; i++) {
if (proofs[i] == proof) {
return true;
}
}
return false;
}
}
And here are the gas consumption results for calling addProof 4 times:
addProof("a"): 41226
addProof("b"): 27023
addProof("c"): 27820
addProof("d"): 28617
You kind of have to ignore the very first call. The reason that one is more expense than the rest is because the very first push to proofs will cost more (no storage slot is used before the 1st call, so the push will cost 20000 gas). So, the relevant part for this question is to look at the cost of addProof("b") and then the increase with each call afterwards. The more items you add, the more gas the loop will use and eventually you will hit an out of gas exception.
Here is another example where you are only calling a constant function from the client:
pragma solidity ^0.4.19;
contract LoopExample {
function constantLoop(uint256 iterations) public constant {
uint256 someVal;
for (uint256 i = 0; i < iterations; i++) {
someVal = uint256(keccak256(now, i));
}
}
}
Here, if you call this through Remix, you'll see something like this in the output (Notice the comment on gas usage):
Finally, if you try to run this constant method from a client using too many iterations, you will get an error:
$ truffle console
truffle(development)> let contract;
undefined
truffle(development)> LoopExample.deployed().then(function(i) { contract = i; });
undefined
truffle(development)> contract.constantLoop.call(999);
[]
truffle(development)> contract.constantLoop.call(9999);
[]
truffle(development)> contract.constantLoop.call(99999);
Error: VM Exception while processing transaction: out of gas
at Object.InvalidResponse (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\errors.js:38:1)
at C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\requestmanager.js:86:1
at C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\truffle-provider\wrapper.js:134:1
at XMLHttpRequest.request.onreadystatechange (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\httpprovider.js:128:1)
at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:64:1)
at XMLHttpRequest._setReadyState (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:354:1)
at XMLHttpRequest._onHttpResponseEnd (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:509:1)
at IncomingMessage.<anonymous> (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:469:1)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)

Most of the people will say constant functions will not consume gas. That will not correct because, constant functions execute on the local node's hardware using it's own copy of the blockchain. This makes the actions inherently read-only because they are never actually broadcast to the network.
Lets assume I've contract having isEmp constant function, when I call estimateGas() it should return 0 if constant method's are not consuming gas. But its returning 23301.
truffle> contractObj.isEmp.estimateGas(web3.eth.accounts[0])
23301
Here is my solidity code
function isEmp(address employee) public constant returns(bool) {
return emps[employee];
}
Hence above experiment is proved that it will consume gas.

The thing is that constant (now it's called view) functions are getting the information from previously executed normal functions. Why? Because view functions are accessing the storage of the contract that created in creation of the contract and changed with functions that changes it if you write the function that way. For example:
contract calculateTotal{
uint256 balance;
constructor(uint256 _initialBalance){
balance=_initialBalance;
}
function purchaseSmth(uint256 _cost) external {
balance=balance-_cost;
}
function getBalance() external view returns(uint256){
return balance;
}
}
Now when you create this contract you set the balance, that way balance already calculated and you don't need to be recalculated because it will be the same. When you change that balance value with purchaseSmth the balance will be recalculated and storage value of balance is going to change. That means that function will change the blockchain's storage. But again you are paying for these executions because the blockchain must be changed. But view functions are not changing any storage value. They are just getting the previously calculated value that standing in blockchain already. When you make some calculations in the view functions like: return balance*10; the execution does not affects blockchain. The calculation of it will be done by your device. Not by any miner.
If we look at the answer of #AdamKipnis we see that constant/view function is not consuming any gas by itself if you call it rightaway. Because it will be always calculated before. First the constructor will create it as empty array. Then when you call the hasProof you will see an empty array. Then when you use addProof it will change the proofArray. But the price is going bigger because it uses the hasProof function in it. If it wasn't there then the price would not go up forever. However If you call the hasProof function manually then your computer(if it is a node) will execute that loop locally eitherway if that function has it or not. But any storage, status changing execution will be directed to miners because of the blockchain logic. Someone else should execute that code and verify it If that change is possible in that transaction and If there is no error in the code.
When you use a wallet like metamask wallet in some cases you can see the errors before making any transactions(executions). But that is not a verified error until you make the transaction and a miner executes that code then finds that this code has some errors or it is doing, changing something in a way that it shouldnt be possible. Like trying to transferring to yourself some bnb from another person's wallet. That execution can't happen because It is not your wallet to transfer the bnb from. It sounds obvious but random miners should validate that execution to making a block that includes your transaction in it with other executions in per block transaction limit boundary in that time.
EDIT: The device, computer, hardware is the node. Node can be you or if you use a remote node for your executions than the node will do everything your device will not. Like cloud computing. Because you would'nt have a ledger if you were not a node.

It will only cost gas if the constant (view or pure) function is executed or called by another external smart contract, that is not the owner of that function. But if it is called from within the smart contract that declared the constant (view or pure) function, then no gas will be used.
Just like when you use a class member function in another class in other programming languages by creating an object of that class. But in solidity this will cost you regardless of the fact that it's a constant function or not.
So when Jitendra Kumar. Balla did an experiment that showed it will cost gas, the gas shown there is the estimated gas cost if it is called by another smart contract but not from within the smart contract.

Related

Advantage/Disadvantage between Chainlink VRF and an off-chain random number transaction performed by your server?

As I understand it Chainlink VRF uses the request-response approach for providing contracts with a "trusted random number". You (the developer) create a smart contract and inherit the Chainlink VRFConsumerBase contract, declare a storage variable that will hold your random number result, then initialize some keyhash & chainlink oracle address, and implement a function ( lets say abc() ) that calls Chainlinks "requestRandomness()" function. You then override the internal "fulfillRandomness()" function and set the returned random number on your storage variable.
Short flow:
Fund your smart contract with LINK, make a transaction call to abc()
Wait for Chainlinks Oracle to make a transaction call to your contract "fulfillRandomness()" and set the random number result on your storage variable.
Rather than using this approach wouldn’t it be sufficient to just write a smart contract that emits a "RequestRandom" Event and have a personal server running that listens for the RequestRandom event of your contract and have that server then generate a random number and make an authorized transaction to my contract to set that generated random number on it.
contract MyRandom {
event RequestRandom(uint seed);
address public myServerWallet;
uint public myRandomNumber;
constructor(address a) {
myServerWallet = a;
}
function makeRandomRequest(uint seed) external {
emit RequestRandom(seed);
}
function setRandomResult(uint result) external {
require(msg.sender == myServerWallet, "Only server may call");
myRandomNumber = result;
}
}
What would be the difference between this approach vs Chainlink VRF? Am I sacrificing some type of security by using this approach?
Tried the server approach above. It does work but still curious on advantage/disadvantage.

What information are visible in transaction after a call to a payable function?

I was wondering what information are publicly visible and intelligible when an EOA (external ownable address) calls a payable function on a smart contract, with some parameters and a return value.
Let us say I have the smart contract function below, the question is: 'is the return value visible somewhere on the blockchain?'. I am using Solidity 0.8.12.
function askForSecretCode(uint time) external payable returns (bytes32) {
require(msg.value == 42, 'Need to pay 42 wei.');
secretCodes[secretCodesNum] = keccak256(abi.encodePacked(msg.sender, time);
return keccak256(abi.encodePacked(msg.sender, time);
}
Anyone can see the input time param value as a part of a transaction invoking the askForSecretCode function.
Even though if you don't publish the contract source code, the bytecode is public, and there are decompilers that can (with some error rate) help generate source code back from the bytecode. So let's assume that the source code is available as well.
From the source code (or usually even from the pseudocode generated by the decompiler), anyone can determine the storage slot of secretCodesNum (which from the context seems to be a property of the contract) and retrieve its value using the eth_getStorageAt RPC method, including historical values.
Using these secretCodesNum values, they can use the same method to determine storage slots of any secretCodes[secretCodesNum] and their values.
TLDR: Never ever store private data on the blockchain.

How do I send ether and data from a smart contract to an EOA?

I'm trying to create a "real" transaction from inside a smart contract to an EOA. This is so that I can attach data/input_data to send to it.
I've read several resources on this but I've come to contradictory information: some say it's impossible, some say that call() can achieve this. I've been testing multiple methods and have not come to see that it is possible.
Here's a simple example of what I'm trying to achieve:
pragma solidity 0.8.6;
contract Simple {
uint32 value;
constructor() payable {
// Contract is initialized with 0.5 ether
value = 22;
}
function foo() public {
require(address(this).balance >= 0.1 ether);
// Along with transfering ether, I want to send some data to the EOA,
// for example, whichever value is in the variable "value"
payable(msg.sender).transfer(0.1 ether);
}
}
On a "normal" transaction, it is possible to set the field "input data" (normally used to make function calls when sending a transaction to a smart contract), which allows us to send data on a transaction from an EOA to another EOA. I was able to achieve this already.
But, from my understanding, contracts "can't" create transactions; they only create "internal transactions" (informal name) that are associated with the "parent transaction" (transaction that called the contract in the first place) and therefore don't have the data field. But they're able to call another contract on the network, so I assume they're able to send some data along the network, right?
Furthermore, this question seems to imply that the low level call() method is able to achieve this. I've tried multiple approaches but have not been able to reproduce the wanted behaviour.
msg.sender.call{value: 0.1 ether}("data", value); // Doesn't work
msg.sender.call{value: 0.1 ether}(value); // Doesn't work
msg.sender.call{value: 0.1 ether}(abi.encodeWithSignature(value)) // Doesn't work
At some point, I did find my message on a block's "extra data", but from my understanding, this was written there by the miner for some reason.
So, to sum it up, is it possible to, from a contract, send ether + message to an EOA account? How would I achieve this?
Edit: Fixed the function name, which was a reserved keyword.
function msg() public {
This function name is a bit problematic, because you're overriding the global msg variable, and can't use the msg.sender.
So I changed the function name to generic foo().
function foo() public {
msg.sender.call{value: 0.1 ether}
Since Solidity 0.8, an address is not payable by default (source: docs). So if you want to send them the native currency (in case of Ethereum, that's ETH), you need to cast the address to payable first.
payable(msg.sender).call{value: 0.1 ether}
Finally to the data sending part.
At some point, I did find my message on a block's "extra data", but from my understanding, this was written there by the miner for some reason.
I'm not exactly sure, but it seems like you stumbled upon the correct field, which is simply the data field of the raw transaction, and the blockchain explorer probably named it "extra data". The data field is not filled by the miner, but by the transaction creator.
Since you're sending an integer, and the data field is bytes (array of bytes), you need to encode it to bytes. In your case:
abi.encode(value)
To you put it all together:
pragma solidity 0.8.6;
contract Simple {
uint value;
constructor() payable {
value = 22;
}
function foo() public {
require(address(this).balance >= 0.1 ether);
payable(msg.sender).call{value: 0.1 ether}(abi.encode(value));
}
}
When you execute the foo() function (and the contract has enough funds), it will create an internal transaction (some blockchain explorers might use a different name) to the msg.sender with value 0.1 ether and the decimal 22 encoded as hex 16 in the data field.

Smart contract good practice for reentrancy attacks

I'm a rookie working with solidity and blockchain technologies and I was reading some good practices to improve my code.
And I have a question about a code that I'm not quite understanding very well:
Source: https://github.com/ConsenSys/smart-contract-best-practices/blob/master/docs/known_attacks.md
// INSECURE
mapping (address => uint) private userBalances;
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
require(msg.sender.call.value(amountToWithdraw)()); // At this point, the caller's code is executed, and can call withdrawBalance again
userBalances[msg.sender] = 0;
}
In the above code is said to be insecure because a malicious agent can call the step 2 require the amount of times we wants. My question regarding this is, how the malicious agent can call misuse this and call that line of code more than 1 time. I'm clearly missing something here.
This is known as a reentrancy attack.
This is insecure because the user's balance is set to 0 only after the withdrawal has been processed. Moreover, the withdrawal is processed by using evm's CALL opcode, which passes control to the receiving address.
If the receiving address is a contract, it can hijack this transfer using the fallback function. Inside this fallback function, it can check to see if the balance of the sending contract exceeds the amount that was transferred. If it does, it will call withdrawBalance again, until the withdrawal contract's balance has been depleted.
A simple attacker contract may look something like:
contract Attacker {
function startattack() {
victim.withdrawBalance();
}
function() payable {
if (victim.balance > msg.value) {
victim.withdrawBalance();
}
}
}
By calling startattack, you initiate a withdrawal. When the require(msg.sender.call.value(amountToWithdraw)()); line is executed, it runs the code in the fallback function. At this point, msg.value is userBalances[msg.sender]. The attacker can check if the victim's contract still has more ether available than userBalances[msg.sender], and run a withdrawal again (which will result in this process looping until the balance drops below userBalances[msg.sender]).
This can be avoided by switching the order of lines to:
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
userBalances[msg.sender] = 0;
require(msg.sender.call.value(amountToWithdraw)());
}
Now, even if the attacker calls withdrawBalance again, the user's balance has already been set to 0, and further withdrawal will not be possible.

eth.estimateGas fails with contract address as second parameter

Newbie.
There is a go-ethereum method:
eth.estimateGas({from:'firstAccount', to:'secondAccount'})
that works well,
but same method with contract address like:
eth.estimateGas({from:'firstAccount', to:'contractAddr'})
fails with error
gas required exceeds allowance or always failing transaction
I have looked into go-ethereum source code and it has the line, that contains proposal to use contract address as second parameter:
https://github.com/ethereum/go-ethereum/blob/master/accounts/abi/bind/base.go#L221
The question is: is there any possibily to use eth.estimateGas with contract address as second parameter and how to avoid above error?
Thank you.
You're not specifying what you're executing in the contract, so there's nothing to estimate. When you estimateGas for a transfer to an EOA account, there is no contract code to execute, so there is no message data to be sent as part of the transaction object. If you're estimating gas on a contract call, you need to include the data for the contract.
For example, if you want to estimate gas to setValue(2) method in this contract
pragma solidity ^0.4.19;
contract SimpleContract {
uint256 _value;
function setValue(uint256 value) public {
_value = value;
}
}
your call would be
var data = '552410770000000000000000000000000000000000000000000000000000000000000002';
eth.estimateGas({from: fromAccount, to: contractAddress, data});
The value for data comes from encoding the function signature and the parameter value(s). You can use a simple tool (like https://abi.hashex.org) to generate this. You just enter the function name along with the parameter argument types and their values, and it will generate the message data for you. You can also do this using web3js.
EDIT - I neglected to consider contracts with fallback functions. Executing estimateGas on a contract without passing in message data provide the estimate for contracts that have a fallback function. If the contract does not have a fallback function, the call will fail.