Web3 & DApp Development Fundamentals · 课时

连接到提供者

RPC 与钱包

第 1 / 4 课13 个步骤

连接到提供者 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Talking to a Blockchain

To interact with Ethereum from JavaScript you need a provider — an object that connects to a node and lets you read chain data and send transactions.

Libraries like ethers.js and web3.js wrap the JSON-RPC protocol nodes speak.

Providers vs Signers

Two key abstractions:

  • Provider — read-only connection to the chain (balances, blocks, view calls).
  • Signer — holds a private key and can sign and send transactions.

You read with a provider and write with a signer.

A JSON-RPC Provider

The most common provider connects to an RPC endpoint such as Infura, Alchemy, or a local node:

const { ethers } = require("ethers"); const provider = new ethers.JsonRpcProvider( "https://mainnet.example-rpc.io/KEY" );

With it you can immediately query public chain data.

const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider(
  "https://mainnet.example-rpc.io/KEY"
);

Reading Network Info

Once connected, query basic network state:

const network = await provider.getNetwork(); console.log(network.chainId); const block = await provider.getBlockNumber(); console.log("Latest block:", block);

The chainId identifies which network you are on (1 = mainnet).

const network = await provider.getNetwork();
console.log(network.chainId);

const block = await provider.getBlockNumber();
console.log("Latest block:", block);

Checking a Balance

Get an account's ETH balance through the provider:

const balance = await provider.getBalance("0xAbc..."); console.log(ethers.formatEther(balance), "ETH");

The raw value is in wei (a BigInt); formatEther converts it to a human-readable ETH string.

const balance = await provider.getBalance("0xAbc...");
console.log(ethers.formatEther(balance), "ETH");

Browser Wallets

In a browser dApp, the wallet (like MetaMask) injects a provider at window.ethereum. Wrap it with a BrowserProvider:

const provider = new ethers.BrowserProvider(window.ethereum); await provider.send("eth_requestAccounts", []);

The eth_requestAccounts call prompts the user to connect.

const provider = new ethers.BrowserProvider(window.ethereum);
await provider.send("eth_requestAccounts", []);

Getting a Signer

From a browser provider, obtain the connected account's signer:

const signer = await provider.getSigner(); console.log("Connected as:", await signer.getAddress());

This signer can now send transactions approved by the user in their wallet.

const signer = await provider.getSigner();
console.log("Connected as:", await signer.getAddress());

Wallet from a Private Key

On a backend you can create a signer from a private key. Connect it to a provider so it can broadcast:

const wallet = new ethers.Wallet( process.env.PRIVATE_KEY, provider );

Never hardcode private keys — load them from environment variables.

const wallet = new ethers.Wallet(
  process.env.PRIVATE_KEY,
  provider
);

web3.js Comparison

web3.js is the older alternative. Its connection looks like:

const { Web3 } = require("web3"); const web3 = new Web3("https://mainnet.example-rpc.io/KEY"); const block = await web3.eth.getBlockNumber();

Concepts map closely, but ethers.js separates providers and signers more cleanly.

const { Web3 } = require("web3");
const web3 = new Web3("https://mainnet.example-rpc.io/KEY");
const block = await web3.eth.getBlockNumber();

Keeping Secrets Safe

RPC keys and private keys are sensitive:

  • Store them in .env, never in source control.
  • Use read-only providers in front-end code.
  • Private keys belong only on secure backends or in the user's own wallet.

Default and Fallback Providers

ethers can combine several backends for reliability. A fallback provider queries multiple endpoints and agrees on a result:

const provider = ethers.getDefaultProvider("mainnet", { alchemy: process.env.ALCHEMY_KEY, infura: process.env.INFURA_KEY, });

If one backend is down, others keep your app working.

const provider = ethers.getDefaultProvider("mainnet", {
  alchemy: process.env.ALCHEMY_KEY,
  infura: process.env.INFURA_KEY,
});

Quick Check

Test your understanding of providers and signers.

Recap

You learned to connect to a blockchain.

  • A provider reads chain data; a signer sends transactions.
  • JsonRpcProvider connects to an RPC URL; BrowserProvider wraps wallet injections.
  • getSigner returns the connected account; new Wallet(key, provider) signs on a backend.
  • Values are in wei; use formatEther to display them.
  • Keep RPC and private keys in .env, never in code.
免费开始

用 AI 导师学习 Web3 & DApp Development Fundamentals — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
29
课程
105

常见问题解答

「连接到提供者」课时是免费的吗?

是的 — 「连接到提供者」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

「连接到提供者」这节课中我会学到什么?

RPC 与钱包 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「连接到提供者」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 连接到提供者
  2. 读取合约数据
  3. 发送交易
  4. 监听事件
← 返回 Web3 & DApp Development Fundamentals