I'm doing a research about Ethereum smart contracts security and I need to send some extra data (for example some json data) beside or inside a new smart contract when I'm deploying that contract on the network. Is it possible and how can I do it?
-
Should smart contract's code have an access to the data? Should the data be stored in the blockchain, or maybe it would be enough to store the data off-chain, and only store the hash of the data on-chain?– Mikhail VladimirovCommented Jul 3, 2020 at 13:54
-
Only Ethereum client (like hyperledger besu that i'm using) needs to access and read the data.– Morteza AmirmohseniCommented Jul 3, 2020 at 18:19
2 Answers
There are different ways to to this. First, you may just embed the data into smart contract's code like this:
contract Foo {
string public constant bar = "Hello, World!";
}
Second, you may pass the data as a constructor parameter:
contract Foo {
constructor (string memory _bar) public {
}
}
In this example, constructor doesn't do anything with the data. However, off-chain applications will still be able to access the data. To make such accsss more convenient, you may log the data in event:
contract Foo {
event Bar (string bar);
constructor (string memory _bar) public {
emit Bar (_bar);
}
}
If you want the data to be accessible by other functions of this smart contract, you may save it into a storage variable:
contract Foo {
string private bar;
constructor (string memory _bar) public {
bar = _bar;
}
}
If you need the data to be accessible by other smart contracts, make the storage variable public:
contract Foo {
string public bar;
constructor (string memory _bar) public {
bar = _bar;
}
}
If you don't need the ability to read the data, but only to verify it, consider storing, only the hash of the data:
contract Foo {
bytes32 public barHash;
constructor (string memory _bar) public {
barHash = keccak256 (bytes (_bar));
}
}
or even pass only the hash to save gas on deployment:
contract Foo {
bytes32 public barHash;
constructor (bytes32 _barHash) public {
barHash = _barHash;
}
}
Hope this would help.
You can put in the data field any arbitrary data, but the transaction has a size limit, is about 780kB AFAIK.