Smart Contract Deployer

Smart Contract Deployer

How to write your first Smart Contract?

This guide is for you if you are new to blockchain development and don’t know where to begin, or if you simply want to understand what a smart contract deployer is and how to deploy and communicate with smart contracts. Gain in-depth knowledge on how to write your first smart contract through this article. Understand this from scratch by enrolling in our Cybersecurity Training in Chennai at Softlogic Systems.

We will walk through the procedure for developing and deploying a simple smart contract on the Goerli test network that uses a virtual wallet (Metamask), Solidity, Hardhat, and Alchemy (don’t worry if you don’t know what any of this means yet, we will explain).

The most frequently stated concept in any Blockchain discussion is “Smart Contract,” which has been termed as Blockchain’s most fascinating feature. A Smart Contract serves as the foundation for all Ethereum Applications.

What is a Smart Contract Deployer?

According to Wikipedia A “smart contract” is a computer protocol created to digitally enable, authenticate, or implement the contract’s negotiation process or quality.

According to Nick Szabo, a smart contract is a general-purpose computation that takes place on a Blockchain or distributed ledger.

A smart contract deployer is essentially a contract written into code. A purchase order, in its most basic form, is a contract between a buyer and a seller. Certain conditions must be met in order for the purchase order to be executed successfully. Some of them are below:

  • The buyer successfully paid for the goods.
  • The supplier delivers goods to the buyer in good condition.
  • Goods delivered before the agreed-upon due date at the time of purchase.
  • The purchase order specifies the terms for returning goods.

Smart Contract Language

A Smart Contract language (SCL) is a programming language that is used to either write or compile a Smart Contract. Ethereum Smart Contract languages include Solidity, eWASM, Vyper, and Ethereum bytecode.

Tips to Deploy your First Smart Contract

Step 1: Join the Ethereum Network.

There are numerous methods for making requests to the Ethereum chain. We’ll use a free account on Alchemy, a blockchain developer platform and Web service that enables us to interact with the Ethereum chain without running our own nodes, for simplicity. The platform also includes developer tools for monitoring and analytics, which we’ll use in this tutorial to figure out what’s going on behind the scenes in our smart contract deployment.

Step 2: Develop your App (and API key)

After creating an Alchemy account, you can generate an API key by building an app. We will now be able to send requests to the Goerli test network.

Hover over “Apps” in the nav bar and click “Create App” to access the “Create App” page in your Alchemy Dashboard.

Develop Your App And Api KeyGive the name to your app “Hello World,” provide a brief description, choose “Staging” for the Environment (used for app bookkeeping), and select “Goerli” as your network.

Create AppVerify that you’ve selected the Goerli testnet!

Simply click “Create app,” and you’re done! Your application should be listed in the table below.

Step 3: Register for an Ethereum account (address)

To send and receive transactions, we need an Ethereum account. For this tutorial, we’ll use Metamask, a browser-based virtual wallet for managing your Ethereum account address.

If you want to learn more about how Ethereum transactions work, visit the Ethereum Foundation’s page. You can get a free Metamask account and download it here.

When creating an account, or if you already have one, make sure to select the “Goerli Test Network” in the upper right (to avoid dealing with real money).

Register For An Ethereum Account(Address)

Step 4: Fill a Faucet with ether.

We’ll need some fake Eth to implement our smart contract deployer to the test network. To obtain Eth, go to the Goerli faucet and enter your Goerli account address before clicking “Send Me Eth.” Due to network traffic, it may take a while to obtain your forged Eth. (It took about 30 minutes at the time it was written. You should soon view Eth in your Metamask account!

Step 5: Verify Your Balance

To double-check that our balance is still there, let’s use Alchemy’s composer tool to issue an eth getBalance request. This will return the amount of Eth that we have in our wallet. Check out this video to learn how to use the composer tool!

After entering your Metamask account address and clicking “Send Request,” you should receive the following response:

1 | {“jsonrpc”: “2.0”, “id”: 0, “result”: “0x2B5E3AF16B1880000”}

Step 6: Begin our project

To begin, we’ll need to make a folder for our project. In your command prompt, type:

1 | mkdir hello-world

2 | cd hello-world

Now that we’re in our project folder, we’ll use npm init to get the project started. Follow these instructions if you don’t already have npm installed (we’ll also need Node.js, so download that as well!).

npm init # (or npm init –yes)

It makes no difference how you answer the installation questions, but here’s how we did it for reference:

package name: (hello-world)

version: (1.0.0)

description: hello world smart contract

entry point: (index.js)

test command:

git repository:

keywords:

author:

license: (ISC)

About to write to /Users/…/…/…/hello-world/package.json:

{

“name”: “hello-world”,

“version”: “1.0.0”,

“description”: “hello world smart contract”,

“main”: “index.js”,

“scripts”: {

“test”: “echo \”Error: no test specified\” && exit 1″

},

“author”: “”,

“license”: “ISC”

}

Accept the package .json, and we’re all set!

Step 7: Download Hardhat

A development environment called Hardhat is used to compile, deploy, test, and debug Ethereum programmes. It helps programmers create smart contracts and decentralized applications (dApps) locally before releasing them to a live chain. In our hello-world project, run the following code:

npm install –save-dev hardhat

Step 8: Make a Hardhat project within our hello-world project folder, and then run:

Run the following commands inside our hello-world project folder:

npx hardhat

After that, you should see a welcome message and the option to choose what you want to do. “Create an empty hardhat.config.js” is selected:

– 888    888                      888 888               888– ‘888    888                      888 888               888

– ‘888    888                      888 888               888

– ‘8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888

– ‘888    888     “88b 888P”  d88″ 888 888 “88b     “88b 888

– ‘888    888 .d888888 888    888  888 888  888 .d888888 888

– ‘888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.

– ‘888    888 “Y888888 888     “Y88888 888  888 “Y888888  “Y888

👷 Welcome to Hardhat v2.0.11 👷‍

What do you want to do? …

Create a sample project

❯ Create an empty hardhat.config.js

Quit

This will generate a hardhat.config.js file for us, in which we will specify all of our project’s configuration (on step 13).

Step 9: Include Project Folders.

We’ll make two new folders to keep our project organized. In your command prompt, navigate to the root directory of your hello-world project and type

mkdir contracts

mkdir scripts

contracts/ will house our hello world smart contract code file.

scripts/ will house scripts used to deploy and interact with our contract.

Step 10: Create our Smart Contract

You might be wondering, when are we going to write code?

Start your favorite editor and open the hello-world project (we like VSCode). Smart contracts are written in a language called Solidity, which is what we will use to create our HelloWorld.sol smart contract.

  1. Go to the “contracts” folder and create a new file called HelloWorld.sol.
  2. The Ethereum Foundation has provided a sample Hello World smart contract that we will use for this tutorial. Copy and paste the following contents into your HelloWorld.sol file, and make sure to read the comments to understand what this contract does:

pragma solidity >=0.7.3;contract HelloWorld {

event UpdatedMessages(string oldStr, string newStr);

string public message;

constructor(string memory initMessage) {

message = initMessage;

}

function update(string memory newMessage) public {

string memory oldMsg = message;

message = newMessage;

emit UpdatedMessages(oldMsg, newMessage);

}

}

This is a very simple smart contract deployer that, upon creation, stores a message and can be updated by calling the update function.

Step 11: Add Metamask and Alchemy to your Project.

We’ve made a Metamask wallet, an Alchemy account, and a smart contract; now it’s time to link the three. Every transaction sent from your virtual wallet must be signed with your personal private key. To grant this permission to our programme, we can safely store our private key (and Alchemy API key) in an environment file.

First, Install the dotenv package in your project directory.

npm install dotenv –save

This is a very simple smart contract deployer that, upon creation, stores a message and can be updated by calling the update function.

Otherwise, your environment file will not be recognised as an environment file.

It should not be called process.env,.env-custom, or anything else.

  • To export your private key, follow these steps.
  • See the table below for the HTTP Alchemy API URL.

Add Metamask And Alchemy To Your Project

Your.env file should look something like this:API_URL = “https://eth-goerli.alchemyapi.io/v2/your-api-key”

PRIVATE_KEY = “your-metamask-private-key”

On step 13, we’ll reference these variables in our hardhat.config.js file to connect them to our code.

Step 12: Download and install Ethers.js.

Ethers.js is a library that wraps standard JSON-RPC methods in more user-friendly methods to make it easier to interact with and make requests to Ethereum.

Hardhat makes it extremely simple to integrate Plugins for additional tooling and functionality. For contract deployment, we’ll be using the Ethers plugin (Ethers.js has some super clean contract deployment methods).

Type: in your project directory

npm install –save-dev @nomiclabs/hardhat-ethers “ethers@^5.0.0”

In the next step, we’ll also need ethers in our hardhat.config.js.

Step 13: Make changes to hardhat.config.js.

We’ve already added several dependencies and plugins; now we need to update hardhat.config.js so that our project is aware of them all.

Make the following changes to your hardhat.config.js:

/**

* @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: “goerli”,

networks: {

hardhat: {},

goerli: {

url: API_URL,

accounts: [`0x${PRIVATE_KEY}`]

}

},

}

Step 14: Put our contract together.

Let’s put our contract together to make sure everything is working properly so far. One of the built-in hardhat tasks is compiling.

Execute the below command from the command line:

npx hardhat compile

You may receive a warning about an SPDX license identifier not being provided in the source file, but don’t worry — everything else should be fine!

If that doesn’t work, you can always message in the Alchemy discord.

Step 15: Create our Deployment Script.

Now that our contract has been written and our configuration file is complete, we can write our contract deployment script.

Navigate to the /scripts folder and add the following contents to a new file called deploy.js:

async function main() {

   const HelloWorld = await ethers.getContractFactory(“HelloWorld”);

   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);

  });

Hardhat does an excellent job of explaining what each of these lines of code does; A ContractFactory that works in ethers.

const HelloWorld = await ethers.getContractFactory(“HelloWorld”);

HelloWorld is a factory for instances of our hello world contract, and js is an abstraction used to deploy new smart contracts. Instances are connected to the first signer (owner) by default when using the hardhat-ethers plugin ContractFactory and Contract.

const hello_world = await HelloWorld.deploy();

When you call deploy() on a ContractFactory, the deployment will begin and you’ll get a Promise that resolves to a Contract object. This object contains methods for each of our smart contract functions.

Step 16: Implement our smart contract deployer

We’re finally ready to put our smart contract deployer into action! In the command line, type:

npx hardhat run scripts/deploy.js –network goerli

Then you should see something like:

Contract was sent to the following address: 0xCAFBf889bef0617d9209Cf96f18c850e901A6D61

Please copy and paste this address somewhere safe because we will be using it in later tutorials and you don’t want to lose it.

We should be able to see that our contract address has been successfully deployed if we go to the Goerli etherscan and search for it. Our transaction will look as follows

Implement Our Contract

The From address should be the same as your Metamask account address, and the To address will be “Contract Creation,” but if we click into the transaction, we’ll see our contract address in the To field:

Transaction Details

Congrats! You have just added a smart contract deployer to the Ethereum blockchain.

Let’s go to the Explorer tab in our Alchemy dashboard to see what’s going on behind the scenes. Make sure to filter by app and select “Hello World” if you have multiple Alchemy apps.

Here you can see a few JSON-RPC calls that Hardhat/Ethers made for us when we called the deploy() function. Here, eth sendRawTransaction and eth getTransactionByHash are two crucial requests to take care of. The former is a request to actually write our contract onto the Ropsten chain, while the latter is a request to get data about our action given the hash (a typical pattern when sending transactions).

Conclusion

We have only scratched the surface of solidity by creating our first smart contract deployer. We’ve just seen what it takes to test a smart contract, from deploying it to initiating transactions.

This brings us to the end of this Smart Contract Deployer development blog. We hope you found this blog to be interesting and informative.

Check out our Cybersecurity Courses in Chennai with IBM Certification at Softlogic Systems.

Leave a Comment