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
- Ensure Node.js and npm are Installed:
Download and install Node.js and npm from the Node.js website. - Install Truffle:
npm install -g truffle
- Set Up a Truffle Project:
mkdir my_truffle_project cd my_truffle_project truffle init
2. Write and Compile the Smart Contract
- Create a Smart Contract:
In thecontracts
directory, create a new file namedGreeter.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; } }
- Create a Migration Script:
In themigrations
directory, create a new file named2_deploy_greeter.js
:const Greeter = artifacts.require("Greeter"); module.exports = function(deployer) { deployer.deploy(Greeter, "Hello, JU!"); // Change greeting here };
- Compile the Contract:
truffle compile
3. Deploy the Contract
- Start the Development Network:
Ensure Ganache or Truffle Develop is running. You can use Truffle Develop:truffle develop
- 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
- Create a
scripts
Folder:
Ensure there is a folder namedscripts
in the root directory of your project. - Create a Script File:
In thescripts
directory, create a file namedscripts_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(); };
- Run the Script:
truffle exec scripts/scripts_test.js
5. Troubleshooting
- Ensure Ganache is Running:
Verify that Ganache or Truffle Develop is active when deploying and running scripts. - Check Truffle Configuration:
Ensuretruffle-config.js
is correctly set up for your network. - Reinstall Truffle:
npm uninstall -g truffle npm install -g truffle
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.