In the previous article, we introduced what smart contracts are and how to write our first Hello World contract with Solidity using the Remix IDE.
To recap, our simple Hello World contract is written as follows:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.14;
contract MyContract {
string public ourString = "Hello World!";
}
In this article, we're going to look at how we can change this string to something that a user could input after the smart contract is deployed, in other words how to write data to the blockchain.
This article is based on notes from this Ethereum Blockchain Developer course and is organized as follows:
- Adding a function to update our string
- Deploy the new contract
- Reading vs. writing transactions
Adding a function to update our string
In order to change the output of the public string after the smart contract is deployed, we're first going to create a function.
Every function in Solidity startups with the keyword function
that we'll call updateOurString
, which takes in one argument that is another string
.
It's also important to add the memory
location, which we'll discuss in more detail later, and then add_updateString
. We also have to add the visibility, which in our case will be public
.
Finally, we will update myString
to _updateString
:
pragma solidity 0.8.14;
contract MyContract {
string public ourString = "Hello World!";
function updateOurString(string memory _updateString) public {
ourString = _updateString;
}
}
Stay up to date with AI
Deploy the new contract
Next, after we Deploy the contract we see in our instance that we have two buttons: one for our Hello World string and the other to update our string.
To update our string we can now click the dropdown next to updateOurString
and change the string to "Hello New World!" and hit transact and we'll see the updated string:
Reading vs. writing transactions
From the logs, we can see that everything is a call against a blockchain node, which in our case is the JavaScript environment in Remix (meaning there is no real-world blockchain node).
We can also see that there is a difference between the writing call—the green checkmark— and the [call]
, which is reading a transaction.
The call that is writing a transaction will have an execution cost in order to get mined as it's set to a transaction pool.
The reading transaction is still a transaction, although it's virtually free since it's against your own blockchain node and every blockchain node participating in the network has the same information.
Summary: Reading and Writing Smart Contract Data with Solidity
In this article, we discussed how we can update the string from our Hello World contract after it's been deployed. We also discussed the difference between reading and writing transactions.
In the next article, we'll expand on this introduction to Solidity programming with a more practical project.