Web3 & DApp Development Fundamentals · 강의

Ethereum 연결(Web3.js/Ethers.js)

Web3.js 또는 Ethers.js와 같은 JavaScript 라이브러리를 사용하여 웹 프런트엔드와 Ethereum 네트워크를 연결하는 방법을 배웁니다.

레슨 2/311개 단계

Ethereum 연결(Web3.js/Ethers.js)은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web3 & DApp Development Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

DApps & Ethereum Connection

Welcome to connecting your DApp's front-end to the Ethereum network! Just like traditional apps need to talk to a server, decentralized applications (DApps) need a way to communicate with the blockchain.

This communication allows your DApp to read data from the blockchain, like account balances, and send transactions, like transferring tokens or calling smart contract functions.

Web3.js & Ethers.js Libraries

To bridge the gap between your web front-end (written in JavaScript) and the Ethereum blockchain, we use specialized libraries.

  • Web3.js: The original JavaScript library for interacting with Ethereum. It's widely used and robust.
  • Ethers.js: A more modern, lightweight, and often preferred alternative, especially for front-end development, known for its clear API.

Both libraries serve the same core purpose: to make it easy to send and receive data from Ethereum.

Understanding Ethereum Providers

Before your DApp can talk to the blockchain, it needs a provider. A provider is an abstraction that connects your DApp to an Ethereum node.

  • Browser Wallets (e.g., MetaMask): These inject a provider object (window.ethereum) directly into your browser's JavaScript environment.
  • Node Providers (e.g., Infura, Alchemy): These are services that run Ethereum nodes and provide an API endpoint (URL) for your DApp to connect to, usually for read-only access or when a user doesn't have a browser wallet.

The provider handles the low-level network communication.

Setting Up with npm

To use Web3.js or Ethers.js in your project, you'll typically install them using a package manager like npm (Node Package Manager).

First, make sure you have Node.js and npm installed. Then, in your project directory, open your terminal and run one of these commands:

  • For Web3.js: npm install web3
  • For Ethers.js: npm install ethers

Once installed, you can import them into your JavaScript files.

Connecting via MetaMask (Web3.js)

When a user has MetaMask installed, it injects window.ethereum. You can use this object to create a Web3.js instance and request user permission to connect their wallet.

Here's how you'd typically initialize Web3.js:

async function connectWeb3() {
  if (window.ethereum) {
    const web3 = new Web3(window.ethereum);
    try {
      // Request account access if needed
      await window.ethereum.request({ method: 'eth_requestAccounts' });
      console.log('Web3.js connected!');
      return web3;
    } catch (error) {
      console.error('User denied account access or error:', error);
    }
  } else {
    console.log('MetaMask not detected! Install it or use a different provider.');
  }
  return null;
}

// To run this in a browser, you'd call connectWeb3()
// For this runnable example, we'll simulate the connection.
async function main() {
  console.log('Simulating Web3.js connection...');
  const web3Instance = await connectWeb3(); // This would be called in a browser
  if (!web3Instance) {
    console.log('Failed to connect Web3.js (simulated).');
  } else {
    console.log('Web3.js connection successful (simulated)!');
  }
}

main();

Connecting via MetaMask (Ethers.js)

Ethers.js also uses window.ethereum to connect to browser wallets. It uses the concept of a Web3Provider to wrap the injected provider.

This approach offers a clean way to interact with the user's wallet and the network.

const { ethers } = require('ethers'); // In browser, ethers is global

async function connectEthers() {
  if (window.ethereum) {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    try {
      // Request account access
      await provider.send('eth_requestAccounts', []);
      console.log('Ethers.js connected!');
      return provider;
    } catch (error) {
      console.error('User denied account access or error:', error);
    }
  } else {
    console.log('MetaMask not detected! Install it or use a different provider.');
  }
  return null;
}

// To run this in a browser, you'd call connectEthers()
// For this runnable example, we'll simulate the connection.
async function main() {
  console.log('Simulating Ethers.js connection...');
  const ethersProvider = await connectEthers(); // This would be called in a browser
  if (!ethersProvider) {
    console.log('Failed to connect Ethers.js (simulated).');
  } else {
    console.log('Ethers.js connection successful (simulated)!');
  }
}

main();

Reading Data: Get Block Number

Once connected, you can easily read information from the blockchain. A common first step is to get the current block number. This is a read-only operation, meaning it doesn't require a transaction or gas.

Both Web3.js and Ethers.js provide straightforward methods for this.

Get Block Number (Web3.js Example)

Here's how you'd fetch the latest block number using Web3.js after establishing a connection:

// This simulates interaction with a Web3 provider.
// In a real DApp, 'web3' would be an instance connected
// to MetaMask or another Ethereum node.

const web3 = {
  eth: {
    getBlockNumber: async () => {
      // Simulate network call delay
      await new Promise(resolve => setTimeout(resolve, 500));
      return 12345678; // Example block number
    }
  }
};

async function main() {
  console.log("Attempting to get block number with Web3.js...");
  const blockNumber = await web3.eth.getBlockNumber();
  console.log("Current Block Number (Web3.js):", blockNumber);
}

main();

Get Block Number (Ethers.js Example)

And here's the equivalent operation using Ethers.js:

// This simulates interaction with an Ethers.js provider.
// In a real DApp, 'provider' would be connected to
// MetaMask or another Ethereum node.

const provider = {
  getBlockNumber: async () => {
    // Simulate network call delay
    await new Promise(resolve => setTimeout(resolve, 500));
    return 12345679; // Example block number
  }
};

async function main() {
  console.log("Attempting to get block number with Ethers.js...");
  const blockNumber = await provider.getBlockNumber();
  console.log("Current Block Number (Ethers.js):", blockNumber);
}

main();

Quick Check: Provider Role

What is the primary role of an Ethereum provider (like MetaMask or Infura) in a DApp's architecture?

Recap: Connecting DApps

Great job! In this lesson, you learned how DApps connect to the Ethereum network.

  • We explored Web3.js and Ethers.js as key JavaScript libraries for this interaction.
  • We understood the concept of an Ethereum provider (e.g., MetaMask, Infura) as the essential link to the blockchain.
  • You saw how to conceptually set up and initialize these libraries to read basic blockchain data like the current block number.

Next, we'll dive deeper into building a complete DApp!

무료로 시작

AI 튜터와 함께 Web3 & DApp Development Fundamentals을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
29
레슨
105

자주 묻는 질문

“Ethereum 연결(Web3.js/Ethers.js)” 강의는 무료인가요?

네 — “Ethereum 연결(Web3.js/Ethers.js)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.

“Ethereum 연결(Web3.js/Ethers.js)”에서 뭘 배우나요?

Web3.js 또는 Ethers.js와 같은 JavaScript 라이브러리를 사용하여 웹 프런트엔드와 Ethereum 네트워크를 연결하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.

“Ethereum 연결(Web3.js/Ethers.js)” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Web3의 프런트엔드 및 백엔드
  2. Ethereum 연결(Web3.js/Ethers.js)
  3. 기본 DApp 예제
← Web3 & DApp Development Fundamentals(으)로 돌아가기