I have a field in my contract. It's something like this:
contract MyContract {
string private secretField
}
function getSecretField() public view returns {
... some controls here...
return secretField;
}
I want to reach that secretField from my backend server and protect it from any other requester. What is the best practice for this?
If it's on a public blockchain (mainnet, ropsten testnet, ...), it's always going to be accessible by querying the storage slot containing the secretField value from an off-chain app. No matter the Solidity private visibility modifier because the storage query is performed on a lower layer.
Example: If secretField is the first property of the first defined contract (on this address), its value is stored in storage slot 0.
But if you only want to hide it from on-chain requesters, you can keep the property private and require the getter to be accessed only from a certain address.
// removed `view` because it's going to interact with the transaction data
function getSecretField() public returns {
// reverts if the sender address is not 0x123
require(msg.sender == address(0x123);
return secretField;
}
Note that your backend app is going to have to send a transaction from the 0x123 address in order to access the data. Simple call won't return anything because the getSecretField() is not a view function anymore.
Related
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.
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'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.
Where in the code and what is the proper way to add legal verbiage to my ERC20 Smart Contract?
I've seen a few samples where it gets saved on a variable and then that variable value is referenced in the body of a function using memory.
i.e.
contract MyToken is ERC20, Ownable {
string public processNumber = "0041518-41.1982.8.26.0053";
string public legalBinding = "a lot, a lot of verbiage would go here";
constructor() ERC20("MyToken", "MTK") {
_mint(msg.sender, 9000000 * 10 ** decimals());
}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function setProcessNumber (string memory v) public onlyOwner() {
processNumber = v;
}
function setLegalBinding (string memory v) public onlyOwner() {
legalBinding = v;
}
}
What are those two last functions doing anyway does it ever get executed or just saved in memory?
Is that the correct practice?
Is there a better approach to this?
Where in the code do developers typically add that type of info?
If I'm to save a massive string of text containing all the legal verbiage. on a variable can I save those on a template literal using back-ticks to leverage multiple lines breaks inside the string and so forth?
I would like to go point-by-point to your question :
What are those two last functions doing anyway does it ever get executed or just saved in memory?
These functions are basically overriding the values of these variables, which in your case, are by default initialised at the very beginning of the contract. As we have the onlyOwner() modifier set on these functions, only the owner can change these variables by calling these methods explicitly, and by providing the necessary Gas cost.
Is that the correct practice? Kind-of, Yes
Is there a better approach to this?
The method can be modified to view restriction
Where in the code do developers typically add that type of info?
If you want the value to be a constant, i.e, it should not be changed through out the course of the contract, add the constant modifier. Additionally, you can add make the variable immutable, which means the initial constant value string can be avoided, and the variable can only be initialised with a constant value at first run, and then the value cannot be changed.
If I'm to save a massive string of text containing all the legal verbiage. on a variable can I save those on a template literal using back-ticks to leverage multiple lines breaks inside the string and so forth?
Yes, you can. Please refer here : https://docs.soliditylang.org/en/v0.8.0/internals/layout_in_storage.html?highlight=string
Hope that it helps!
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.