0Pricing
Blockchain Smart Contracts with Solidity · Pelajaran

Berinteraksi dengan Kontrak yang Telah di-Deployment

Pelajari cara berinteraksi dengan kontrak pintar yang telah di-deployment menggunakan pengujian JavaScript dan perintah konsol.

Berinteraksi dengan Kontrak yang Telah di-Deployment adalah pelajaran Blockchain Smart Contracts with Solidity gratis di CoddyKit. Ini adalah pelajaran 3 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Blockchain Smart Contracts with Solidity, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Blockchain Smart Contracts with Solidity mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Why Interact with Contracts?

After deploying your smart contract, the real fun begins: interacting with it! This means calling its functions, reading its data, and sending transactions.

Interacting is crucial for:

  • Testing: Ensuring your contract behaves as expected.
  • dApp Frontends: Letting users connect and use your contract.
  • Automation: Building scripts that perform actions on the blockchain.

Your Interaction Toolkit

When working with Hardhat or Truffle, you have powerful tools to interact with deployed contracts:

  • Hardhat Console / Truffle Console: An interactive command line environment for quick tests and debugging.
  • JavaScript Tests: Automated scripts that deploy (or connect to) contracts and verify their behavior.
  • Custom Scripts: Standalone JavaScript files for more complex, repeatable interactions.

We'll focus on the console and JS tests today.

Hardhat Console: The Sandbox

The Hardhat Console provides a convenient way to interact with your contracts and the blockchain directly from your terminal. It uses a Hardhat Runtime Environment (HRE) that already has ethers.js and your compiled contract artifacts loaded.

To start the console, open your terminal in your Hardhat project directory and run:

npx hardhat console

This will launch an interactive JavaScript environment.

Connect to Your Contract

Before you can call functions, you need to "connect" to your deployed contract. This involves getting its address and creating an ethers.js Contract object that represents it.

Here's how you might do it in a Hardhat script (or directly in the console):

const { ethers } = require("hardhat");

async function main() {
  // First, get the ContractFactory for your contract
  const Counter = await ethers.getContractFactory("Counter");

  // Replace with the actual address where your contract is deployed
  const deployedAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3";

  // Attach to the deployed contract using its address
  const counter = await Counter.attach(deployedAddress);

  console.log("Connected to Counter at:", counter.address);
}

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

Calling View Functions

Functions marked as view or pure don't change the blockchain state. They are free to call and simply return data. You can call them directly from your contract instance.

Let's read the current count from our Counter contract. Note that ethers.js returns BigNumber objects for large numbers, so we often use .toString() to display them.

const { ethers } = require("hardhat");

async function main() {
  const Counter = await ethers.getContractFactory("Counter");
  const deployedAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3";
  const counter = await Counter.attach(deployedAddress);

  // Call the getCount view function
  const currentCount = await counter.getCount();
  console.log("Current count is:", currentCount.toString());
}

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

Sending Transactions

To change the state of your contract (e.g., update a variable, transfer tokens), you need to send a transaction. These calls cost gas and require a signer (your account).

After sending a transaction, you usually await its confirmation to ensure it's mined on the blockchain. Let's increment our counter:

const { ethers } = require("hardhat");

async function main() {
  const Counter = await ethers.getContractFactory("Counter");
  const deployedAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3";
  const counter = await Counter.attach(deployedAddress);

  console.log("Incrementing count...");
  const tx = await counter.increment();
  await tx.wait(); // Wait for the transaction to be mined

  const newCount = await counter.getCount();
  console.log("Count after increment:", newCount.toString());
}

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

Automated Interaction Tests

While the console is great for quick checks, automated JavaScript tests are essential for robust development. They allow you to:

  • Define expected behaviors.
  • Run tests repeatedly and quickly.
  • Catch regressions when you make changes.

Hardhat integrates seamlessly with testing frameworks like Mocha and Chai, using ethers.js for contract interaction.

Writing an Interaction Test

A typical Hardhat test file uses describe for test suites and it for individual tests. Inside an it block, you'll connect to your contract and then call its functions, asserting the results.

Remember to replace the deployedAddress with your contract's actual address on your test network.

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Counter Contract Interaction", function () {
  let counter;
  const deployedAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; // Your contract address

  before(async function () {
    const CounterFactory = await ethers.getContractFactory("Counter");
    counter = await CounterFactory.attach(deployedAddress);
  });

  it("should read the initial count correctly", async function () {
    const initialCount = await counter.getCount();
    expect(initialCount.toString()).to.equal("0");
  });

  it("should increment the count via transaction", async function () {
    const initialCount = await counter.getCount();
    await counter.increment();
    const finalCount = await counter.getCount();
    expect(finalCount.toString()).to.equal(initialCount.add(1).toString());
  });
});

Smart Interaction Tips

Keep these tips in mind for effective contract interaction:

  • Always Verify Addresses: Double-check the contract address you're interacting with.
  • Understand Gas: State-changing transactions consume gas. Estimate costs for mainnet deployments.
  • Handle Errors: Use try-catch blocks for transactions, as they can revert.
  • Use Events: Listen for contract events to get structured data about transactions.
  • Test Thoroughly: Write comprehensive tests for all critical functions and edge cases.

Quick Check: Interaction Types

You've learned about two main ways to interact with smart contract functions: reading state (view/pure functions) and changing state (transaction functions).

Which of the following statements about these interactions is TRUE?

Recap: Interacting with Contracts

You've successfully learned how to interact with your deployed smart contracts!

  • We explored using the Hardhat Console for immediate, interactive testing.
  • You saw how to connect to a deployed contract instance.
  • We differentiated between calling `view` functions (free, read-only) and sending transactions (costs gas, changes state).
  • Finally, we covered the importance of automated JavaScript tests for reliable contract interaction.

Next, you're ready to explore state management and storage patterns in Solidity!

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Berinteraksi dengan Kontrak yang Telah di-Deployment” gratis?

Ya — teks lengkap “Berinteraksi dengan Kontrak yang Telah di-Deployment” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Blockchain Smart Contracts with Solidity, upgrade ke CoddyKit PRO. Kursus Blockchain Smart Contracts with Solidity mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Berinteraksi dengan Kontrak yang Telah di-Deployment”?

Pelajari cara berinteraksi dengan kontrak pintar yang telah di-deployment menggunakan pengujian JavaScript dan perintah konsol. Kamu berlatih Blockchain Smart Contracts with Solidity dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Blockchain Smart Contracts with Solidity?

Tidak diperlukan pengalaman sebelumnya. Blockchain Smart Contracts with Solidity di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 3 dari 4.

Berapa lama pelajaran “Berinteraksi dengan Kontrak yang Telah di-Deployment” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Blockchain Smart Contracts with Solidity ini?

Ya. Setiap pelajaran Blockchain Smart Contracts with Solidity menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Menyiapkan Hardhat atau Truffle
  2. Mengompilasi dan Melakukan Deployment Kontrak
  3. Berinteraksi dengan Kontrak yang Telah di-Deployment
  4. Menulis dan Menjalankan Pengujian Kontrak
← Kembali ke Blockchain Smart Contracts with Solidity