Blockchain / Ethereum and DApps Development

Deploying and Interacting with Smart Contracts

In this tutorial, you will learn how to deploy and interact with smart contracts on the Ethereum network.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores Ethereum blockchain and building decentralized applications (DApps).

1. Introduction

1.1. Tutorial's Goal

This tutorial aims to guide you through the process of deploying and interacting with smart contracts on the Ethereum network.

1.2. What Will You Learn?

By the end of this tutorial, you should be able to:
- Understand what smart contracts are
- Learn how to write and deploy smart contracts
- Interact with deployed smart contracts

1.3. Prerequisites

Before starting with this tutorial, you should have:
- Basic understanding of blockchain technology
- Basic knowledge of Solidity, the programming language for Ethereum smart contracts
- Installed Node.js and npm
- Installed the Truffle Suite, which includes Truffle, Ganache, and Drizzle

2. Step-by-Step Guide

2.1. What is a Smart Contract?

A smart contract is a self-executing contract with the terms of the agreement directly written into code.

2.2. Writing a Smart Contract

We will start by writing a simple smart contract in Solidity. Save the following code as SimpleStorage.sol:

pragma solidity ^0.5.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}

This contract has a single variable storedData and two functions to set and get its value.

2.3. Deploying a Smart Contract

We will use Truffle to compile and deploy our contract. First, let's compile it with truffle compile.

Next, we need to create a migration script for deployment. In the migrations directory, create a new file 2_deploy_contracts.js:

var SimpleStorage = artifacts.require("./SimpleStorage.sol");

module.exports = function(deployer) {
  deployer.deploy(SimpleStorage);
};

Now we can deploy our contract to Ganache (a local Ethereum blockchain) with truffle migrate.

2.4. Interacting with a Smart Contract

With our contract deployed, we can interact with it using Truffle Console. Start the console with truffle console and get an instance of our deployed contract:

let instance = await SimpleStorage.deployed()

Now you can call the contract's methods:

await instance.set(100)
await instance.get()

The get() function should return 100.

3. Code Examples

3.1. Example 1: Writing and Deploying a Smart Contract

First, write the contract in Solidity:

pragma solidity ^0.5.0;

contract HelloWorld {
    string public message;

    constructor(string memory initMessage) public {
        message = initMessage;
    }

    function update(string memory newMessage) public {
        message = newMessage;
    }
}

This contract stores a message and allows it to be updated. Save it as HelloWorld.sol.

Next, create a migration script:

var HelloWorld = artifacts.require("./HelloWorld.sol");

module.exports = function(deployer) {
  deployer.deploy(HelloWorld, "Hello, World!");
};

This script will deploy the HelloWorld contract and initialize the message to "Hello, World!".

3.2. Example 2: Interacting with a Smart Contract

Get an instance of the deployed HelloWorld contract:

let instance = await HelloWorld.deployed()

Now you can call the contract's methods:

console.log(await instance.message())
await instance.update("Hello, Ethereum!")
console.log(await instance.message())

The first console.log() should print "Hello, World!", and the second should print "Hello, Ethereum!".

4. Summary

In this tutorial, you've learned what smart contracts are, how to write, deploy, and interact with them on the Ethereum network.

5. Practice Exercises

5.1. Exercise 1: Write and deploy a smart contract that stores and retrieves a user's age.

Tip: This is similar to the SimpleStorage contract, but with a different variable type.

5.2. Exercise 2: Write and deploy a smart contract that allows adding and retrieving items from a list.

Tip: Use a Solidity array to store the items.

5.3. Exercise 3: Extend the HelloWorld contract to store messages from different users. Each user can update their own message, but not others'.

Tip: Use a Solidity mapping to store the messages.

6. Next Steps

To continue learning about smart contracts and Ethereum development, consider exploring more complex contract interactions, integrating with front-end applications, and deploying to a testnet or mainnet.

7. Additional Resources

  • Solidity documentation: https://solidity.readthedocs.io/
  • Truffle Suite documentation: https://trufflesuite.com/docs/
  • Ethereum development tutorials: https://ethereum.org/greeter

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help