This is a pretty basic question, I'm looking for a function that will load data from either a .txt or .csv file. I have found the import
function but when I tried using this I'm getting an error message.
-
Would be useful for you to share your current implementation and the error you are getting– Julissa DCCommented Nov 10, 2021 at 19:05
-
ParserError: Expected pragma, import directive or contract/interface/library/struct/enum/constant/function definition.– Rick ShawCommented Nov 10, 2021 at 19:47
2 Answers
The answer "no". Solidity cannot handle "txt" or "csv" files directly. In fact, at runtime, all there is the blockchain state. Solidity cannot communicate with the external world (not even via the HTTP protocol).
If you want to load data into your contract, you should encode it using a dynamic-length type such as bytes
, then ABI decode it.
-
A question, if you don't mind. Going off of what you said above, if I have a smart contract and I want to add data to a block from an outside source, I can't do that? An example is I have an initial block and with the next block I want to add information from a text file. With a smart contract I can't do that? Commented Nov 10, 2021 at 20:01
-
I'll take it that the question is "how to write data to an outside file from a smart contract". The answer is "no" again. Smart contracts can only interact with other smart contracts. If you need to index data, check out The Graph. Commented Nov 11, 2021 at 10:01
It is impossible, as worded, in principle.
To elaborate, the blockchain principle requires that all nodes must be able reconstruct the blockchain state from transactions now, and any time in the future. This implies certain limitations.
- functions must be deterministic, so transactions are deterministic
- no external input is possible, except ...
- the only acceptable input is data signed by an externally owned account.
Therefore, if you want to load data into the contract, the usual approach would be to construct a function that accepts input possibly from a privileged user. Parse the CSV etc. on the client side. The client would sign and send elements of the CSV to a function that accepts the input. The contract would be unconcerned with how the client determined what to sign.
Such a procedure could be part of a migration process.
Hope it helps.
-
<br>"Therefore, if you want to load data into the contract, the usual approach would be to construct a function that accepts input possibly from a privileged user. Parse the CSV etc. on the client side. The client would sign and send elements of the CSV to a function that accepts the input. The contract would be unconcerned with how the client determined what to sign." <br/> Would you know of any code examples that are available that covers this? . <li>I apologize for the bad formatting</li> Commented Nov 10, 2021 at 20:27