배포된 계약과 상호작용하기
JavaScript 테스트와 콘솔 명령을 사용하여 배포한 스마트 계약과 상호작용하는 방법을 알아봅니다.
배포된 계약과 상호작용하기은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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 consoleThis 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-catchblocks 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!
AI 튜터와 함께 Blockchain Smart Contracts with Solidity을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“배포된 계약과 상호작용하기” 강의는 무료인가요?
네 — “배포된 계약과 상호작용하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
“배포된 계약과 상호작용하기”에서 뭘 배우나요?
JavaScript 테스트와 콘솔 명령을 사용하여 배포한 스마트 계약과 상호작용하는 방법을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“배포된 계약과 상호작용하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Hardhat 또는 Truffle 설정
- 계약 컴파일 및 배포
- 배포된 계약과 상호작용하기
- 컨트랙트 테스트 작성 및 실행