I am basically setting up a smart contract where if a second transaction isnt in same block the first transaction should fail.
A long time ago I saw documentation which showed how to get the current state I think it called it.
Which suggested it was possible to get information such as the block ID at the time the transaction was being confirmed.
I do not have any example at the moment as I can't find any information to test which is why I am asking here.
So does anybody know a way for the contract to check if another transaction is in the current block?
Thanks alot for any help.
I am basically setting up a smart contract where if a second transaction isnt in same block the first transaction should fail.
I'm uncertain what exactly it is you're trying to do but I can't imagine this is a secure operation in practice. Ultimately the second transaction will not have any way to guarantee that the first transaction is the one that actually ends up getting mined in that current block (it could be replaced by a replacement/cancel tx, or it could have insufficient gas price and get mined in the next block, etc).
All that being said, you can use the contract state to store persistent data in the contract on-chain, but that state won't be updated until it a 'mined' contract call updates it. In other words, you won't be able to check if a tx is in the same block, but you can check if a tx is in a previous block.
pragma solidity >=0.4.0 <0.9.0;
contract SimpleStorage {
mapping (string => blockNumber) public transactions;
function recordMyTransaction(string memory _id) public {
transactions[_id] = block.number;
}
function executeThingIfTransactionExists(string memory _id) public {
// string comparison
require(transactions[_id] != 0);
// ... do the thing
}
}
See solidity 0.8.7 docs.
Otherwise, you could do something like this using an oracle. But again, no guarantee that the transaction you're looking at is the one that goes through.
Related
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.
I am making a decentralized crowd funding smart contract in solidity to learn more about the language.
The contract is able to store many crowdfunding projects in a mapping that looks like this
struct CrowdFundingProject{
address author,
string description,
string title,
uint goal,
bool exists
}
mapping(uint, CrowdFundingProject) public projects;
uint lastProject = 0;
the key of the mapping is an autoincremented number. When you create a project it looks like this:
function createProject(string title, string desc, uint goal) public{
CrowdFundingProject newProject;
newProject.author = msg.sender;
newProject.title = title;
newProject.description = desc;
newProject.goal = goal;
newProject.exists = true;
lastProject += 1;
projects[lastProject] = newProject;
}
But i belive that this could cause problems, for example, if user A ran the function createProject and just when the EVM is executing lastProject += 1; User B runs the function too, making that if lastProject was equal to 100 it is now 101 at the same time that projects[lastProject] = newProject; wasn't done executing for user A, both would have a project with the ID 101. which would overwrite the project for user A and just leave the one for user B.
Is this correct? If so, my other approach is instead of directly adding the project as project[lastProject] it would be better to do something like
lastProject += 1;
uint myProjectsId = lastProject - 1;
projects[myProjectsId] = newProject;
I don't know if this approach would cause any sort of error, or if the overwriting error is even possible, so i want to make sure:
Can an error like the overlapping IDs happen?
If so: Would the second approach that I proposed come with any weird behavior?
if user A ran the function createProject and just when the EVM is executing lastProject += 1; User B runs the function too
The EVM executes transactions in series, not in parallel.
Transactions in each block are ordered in a way that the block miner chooses. Most miners simply order from largest gasPrice to smallest.
So based on the provided code, there's no way to overwrite the projects key, even if two separate transactions execute the createProject() function in the same block: The transaction with larger gasPrice will get project ID 100, and the other will execute milliseconds later and will get project ID 101.
There's an attack vector called frontrunning, related to ordering transactions in the block based on their gasPrice. It might be useful to read up about it, for example there's a great article describing the basics.
Your code is vulnerable to this vector, but it practically doesn't matter because the attacker could only frontrun someone and steal their desired project ID (leaving the original project creator with ID higher by 1). Usual incentives for frontrunners are stealing ETH and tokens (and your code doesn't show working with ETH nor tokens).
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.
I have ERC-20 token smart-contract which methods I call using sendSignedTransaction from web3.js. After I know transaction is succesfully mined I need to check contract method execution result. How do I do it if all I have is transaction hash?
Example: method transferFrom(from, to, tokens) returns true or false depending on whether transferring was successful. So if I try to transfer 100 tokens from empty wallet, contract method will return false.
Upd: Okay, as I understood there is no way of determining method outcome using txHash after transaction is mined and confirmed. Then which ways exists to handle this case? How can I make sure that tokens were transferred?
You can emit an event inside your contract code ( actually in ERC20 standard there is always a transfer event present ) and then inside web3js, read all the events till latest block using this line of code:
Events = Contract.eventName({}, {fromBlock: 0, toBlock: 'latest'});
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.