Homework 1 – Truffle Smart Contract Interaction
Setup • Compile • Deploy • Interact • Troubleshoot

Guide to Interacting with a Smart Contract Using Truffle

Follow these steps exactly. Use a local dev network (Ganache or Truffle Develop). Keep terminal output as proof of completion.

Reference repo
GitHub: Greeter example

1. Setting Up the Environment

  1. Ensure Node.js and npm are Installed:
    Download and install Node.js and npm from the Node.js website.
  2. Install Truffle:
    npm install -g truffle
  3. Set Up a Truffle Project:
    mkdir my_truffle_project
    cd my_truffle_project
    truffle init

2. Write and Compile the Smart Contract

  1. Create a Smart Contract:
    In the contracts directory, create a new file named Greeter.sol:
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    contract Greeter {
        string public greeting;
    
    constructor(string memory _greeting) {
            greeting = _greeting;
        }
    
        function greet() public view returns (string memory) {
            return greeting;
        }
    }
  2. Create a Migration Script:
    In the migrations directory, create a new file named 2_deploy_greeter.js:
    const Greeter = artifacts.require("Greeter");
    
    module.exports = function(deployer) {
      deployer.deploy(Greeter, "Hello, JU!"); // Change greeting here
    };
  3. Compile the Contract:
    truffle compile

3. Deploy the Contract

  1. Start the Development Network:
    Ensure Ganache or Truffle Develop is running. You can use Truffle Develop:
    truffle develop
  2. Deploy the Contract:
    In a new terminal window (while Truffle Develop is running), deploy the contract:
    truffle migrate

4. Interact with the Contract Using a Script

  1. Create a scripts Folder:
    Ensure there is a folder named scripts in the root directory of your project.
  2. Create a Script File:
    In the scripts directory, create a file named scripts_test.js:
    const Greeter = artifacts.require("Greeter");
    
    module.exports = async function(callback) {
      try {
        // Get the deployed instance of the contract
        const instance = await Greeter.deployed();
    
        // Print the address of the deployed contract
        console.log("Contract address:", instance.address);
    
        // Call the greet function
        const greeting = await instance.greet();
        console.log("Greeting:", greeting);
    
      } catch (error) {
        console.error(error);
      }
      callback();
    };
  3. Run the Script:
    truffle exec scripts/scripts_test.js

5. Troubleshooting

6. Example Output

When running the script, you should see:

Contract address: 0x... (your contract address)
Greeting: Hello, JU!

This guide covers the entire process from setting up the environment to interacting with your smart contract.