Conexão com um provedor
RPC e carteiras
Conexão com um provedor é uma aula grátis de Web3 & DApp Development Fundamentals no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Web3 & DApp Development Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
JsonRpcProviderconnects to an RPC URL;BrowserProviderwraps wallet injections.getSignerreturns the connected account;new Wallet(key, provider)signs on a backend.- Values are in wei; use
formatEtherto display them. - Keep RPC and private keys in
.env, never in code.
Perguntas Frequentes
A aula “Conexão com um provedor” é grátis?
Sim — o texto completo de “Conexão com um provedor” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Web3 & DApp Development Fundamentals, atualize para CoddyKit PRO. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
O que vou aprender em “Conexão com um provedor”?
RPC e carteiras Você pratica Web3 & DApp Development Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Web3 & DApp Development Fundamentals?
Nenhuma experiência prévia é necessária. Web3 & DApp Development Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Conexão com um provedor”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Web3 & DApp Development Fundamentals?
Sim. Cada aula de Web3 & DApp Development Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Conexão com um provedor
- Leitura de dados de contratos
- Envio de transações
- Escuta de eventos