Alchemy: Create a Hello World Smart Contract

Learn how to create and deploy a simple hello world smart contract.

What is a Smart Contract?

Smart contracts are pieces of computer code that are built to run on blockchain networks to facilitate, verify, or negotiate a contract agreement. Smart contracts can only be initiated under certain conditions that users agree on. Currently, smart contracts are mainly used for transactions such as NFT minting, but they can be used for any piece of code, such as a simple tutorial program known as ‘Hello World’ that prints a return string to the screen.

Read below to learn how to create and deploy a simple hello world smart contract.

Prerequisites:

1. First, download and install S3FS-FUSE on your local environment.

This tool is available on a Linux or macOS system.

2. Set up an Access Key file for use with S3FS-FUSE.

Set up a credentials file for S3FS at ${HOME}/.passwd-s3fs. You will need to save your Filebase Access and Secret keys to this file and give it owner permissions. You can do so with the following commands:

echo ACCESS_KEY_ID:SECRET_ACCESS_KEY > ${HOME}/.passwd-s3fs

chmod 600 ${HOME}/.passwd-s3fs

ACCESS_KEY_ID is your Filebase Access key, and SECRET_ACCESS_KEY is your Filebase Secret key. For more information on Filebase access keys, see here.

3. Mount your bucket.

You can mount a Filebase IPFS bucket with the command:

s3fs mybucket /path/to/mountpoint -o passwd_file=${HOME}/.passwd-s3fs -o url=https://s3.filebase.com

  • mybucket: name of your Filebase bucket

  • /path/to/mountpoint

4. Now, navigate into the mounted Filebase bucket.

cd /path/to/mounted/bucket

5. Then, create a new folder for your project and navigate into that folder:

mkdir helloWorld

cd helloWorld

6. Now, let’s head over to Alchemy and either sign up for an account or login.

7. From the Alchemy dashboard, we need to create an app.

Select the ‘Create App’ button to get started.

8. Create a new app.

For our example, we called our app ‘hello world’. Set the chain to ‘Ethereum’, and the network to ‘Göerli’.

9. Then, from your App’s page, select ‘View Key’:

10. Copy your app’s HTTP Key:

11. Next, head over to the Göerli Faucet and send your wallet some fake ETH to use:

12. Check your wallet to make sure your faucet request was successful.

13. Now that we have everything we need for our project, let’s get started writing our smart contract.

Start by initiating our project. You should still be in the directory /path/to/mounted/bucket/helloWorld.

npm init

Here’s how we answered the installation questions:

14. Download and install Hardhat into your project directory:

npm install –save-dev hardhat

15. Next, create a Hardhat project with the command:

npx hardhat

At the prompt, select the ‘Create an empty hardhat.config.js’ option.

16. Next, create two folders in your project directory with the commands:

mkdir contracts

mkdir scripts

The contracts folder will be used to store our smart contract, and the scripts folder will be used to store scripts used to deploy and interact with the smart contract.

17. Now it’s time to write the smart contract.

Create a new file in the contracts directory and open the file in your preferred IDE such as VsCode. Name this file HelloWorld.sol. Enter the following content into the file:

// Specifies the version of Solidity, using semantic versioning.
// Learn more: <https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#pragma>
pragma solidity >=0.7.3;

// Defines a contract named `HelloWorld`.
// A contract is a collection of functions and data (its state). Once deployed, a contract resides at a specific address on the Ethereum blockchain. Learn more: <https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html>
contract HelloWorld {

   //Emitted when update function is called
   //Smart contract events are a way for your contract to communicate that something happened on the blockchain to your app front-end, which can be 'listening' for certain events and take action when they happen.
   event UpdatedMessages(string oldStr, string newStr);

   // Declares a state variable `message` of type `string`.
   // State variables are variables whose values are permanently stored in contract storage. The keyword `public` makes variables accessible from outside a contract and creates a function that other contracts or clients can call to access the value.
   string public message;

   // Similar to many class-based object-oriented languages, a constructor is a special function that is only executed upon contract creation.
   // Constructors are used to initialize the contract's data. Learn more:<https://solidity.readthedocs.io/en/v0.5.10/contracts.html#constructors>
   constructor(string memory initMessage) {

      // Accepts a string argument `initMessage` and sets the value into the contract's `message` storage variable).
      message = initMessage;
   }

   // A public function that accepts a string argument and updates the `message` storage variable.
   function update(string memory newMessage) public {
      string memory oldMsg = message;
      message = newMessage;
      emit UpdatedMessages(oldMsg, newMessage);
   }
}

18. Next, install the dotenv package with the command:

npm install dotenv –save

19. Then, create a new file called .env with the following content:

API_URL = "ALCHEMY_HTTP_KEY"
PRIVATE_KEY = "METAMASK_PRIVATE_KEY"

Replace ALCHEMY_HTTP_KEY with your Alchemy API key, and replace METAMASK_PRIVATE_KEY with your Metamask private key. For instructions on how to get your Metamask private key, check out this guide.

20. Next, install the Ethers.js library with the following command:

npm install --save-dev @nomiclabs/hardhat-ethers "ethers@^5.0.0"

21. Open the hardhat.config.js file in your code editor.

Enter the following content in this file:

/**
* @type import('hardhat/config').HardhatUserConfig
*/

require('dotenv').config();
require("@nomiclabs/hardhat-ethers");

const { API_URL, PRIVATE_KEY } = process.env;

module.exports = {
   solidity: "0.7.3",
   defaultNetwork: "ropsten",
   networks: {
      hardhat: {},
      ropsten: {
         url: API_URL,
         accounts: [`0x${PRIVATE_KEY}`]
      }
   },
}

Save this file.

22. Now it’s time to compile our contract. Run the command:

npx hardhat compile

23. Then it’s time to deploy our contract.

To do this, we need to write a script called deploy.js. Create a new file called deploy.js in your scripts directory, then enter the following content in the new file:

async function main() {
   const HelloWorld = await ethers.getContractFactory("HelloWorld");

   // Start deployment, returning a promise that resolves to a contract object
   const hello_world = await HelloWorld.deploy("Hello World!");   
   console.log("Contract deployed to address:", hello_world.address);
}

main()
  .then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });

Save this file.

24. Now, run the newly created deploy.js script to deploy your smart contract:

npx hardhat run scripts/deploy.js --network ropsten

This command will return an output similar to:

Contract deployed to address: 0x9137566f9D8C3722066c3eD2372843b07A6688ae

Save this address value.

25. Now, go to the Ropsten etherscan website.

Enter the contract address from the previous step in the search bar. The contract address will bring up something like this:

You can click on the transaction details to view more information, such as the transaction’s To and From addresses, the transaction fee, and the gas fee:

26. You can also navigate to your Alchemy app, where you’ll see some detailed information about the transaction from this view as well:

If you have any questions, please join our Discord server, or send us an email at hello@filebase.com

Last updated