Envío de transacciones
Escribir en la cadena
Envío de transacciones es una lección gratuita de Web3 & DApp Development Fundamentals en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Web3 & DApp Development Fundamentals, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Writing to the Chain
Changing contract state — transferring tokens, minting, voting — requires a transaction. Transactions must be signed and cost gas.
For this you need a signer, not just a provider.
A Contract with a Signer
To send transactions, create the contract with a signer or connect an existing instance to one:
const contract = new ethers.Contract(
address,
abi,
signer
);
// or
const writable = readOnly.connect(signer);Now state-changing functions become available.
const contract = new ethers.Contract(
address,
abi,
signer
);
// or
const writable = readOnly.connect(signer);Sending a Transaction
Calling a write function sends a transaction and returns a transaction response immediately — before it is mined:
const tx = await contract.transfer(
recipient,
ethers.parseUnits("10", 18)
);
console.log("Sent:", tx.hash);The hash identifies the pending transaction.
const tx = await contract.transfer(
recipient,
ethers.parseUnits("10", 18)
);
console.log("Sent:", tx.hash);Waiting for Confirmation
The transaction is not final until it is mined. Wait for the receipt:
const receipt = await tx.wait();
console.log("Mined in block:", receipt.blockNumber);
console.log("Status:", receipt.status);A status of 1 means success; 0 means it reverted.
const receipt = await tx.wait();
console.log("Mined in block:", receipt.blockNumber);
console.log("Status:", receipt.status);Waiting for More Blocks
For higher confidence against reorgs, wait for several confirmations:
// Wait for 3 confirmations
const receipt = await tx.wait(3);More confirmations mean it is increasingly unlikely the transaction will be reversed.
// Wait for 3 confirmations
const receipt = await tx.wait(3);Sending ETH with a Call
Payable functions accept ETH. Pass a value override as the last argument:
const tx = await contract.deposit({
value: ethers.parseEther("0.5"),
});
await tx.wait();The value is in wei; parseEther converts from a human amount.
const tx = await contract.deposit({
value: ethers.parseEther("0.5"),
});
await tx.wait();Estimating Gas
Before sending, you can estimate how much gas a call will use:
const gas = await contract.transfer
.estimateGas(recipient, amount);
console.log("Estimated gas:", gas);If the function would revert, estimation throws — a useful early warning.
const gas = await contract.transfer
.estimateGas(recipient, amount);
console.log("Estimated gas:", gas);Setting Gas Overrides
You can override gas parameters when needed, for example on EIP-1559 chains:
const tx = await contract.transfer(recipient, amount, {
gasLimit: 100000,
maxFeePerGas: ethers.parseUnits("30", "gwei"),
maxPriorityFeePerGas: ethers.parseUnits("2", "gwei"),
});Usually the wallet picks sensible defaults, so override only when you must.
const tx = await contract.transfer(recipient, amount, {
gasLimit: 100000,
maxFeePerGas: ethers.parseUnits("30", "gwei"),
maxPriorityFeePerGas: ethers.parseUnits("2", "gwei"),
});Handling Failures
Transactions can fail by reverting, being underpriced, or by user rejection in a wallet. Wrap sends in try/catch:
try {
const tx = await contract.transfer(to, amount);
await tx.wait();
} catch (err) {
console.error("Transaction failed:", err.shortMessage);
}try {
const tx = await contract.transfer(to, amount);
await tx.wait();
} catch (err) {
console.error("Transaction failed:", err.shortMessage);
}Nonces and Ordering
Each account has a nonce — a counter ensuring transactions execute in order. ethers manages it automatically, but if you send many transactions quickly you may set it manually to avoid collisions:
const tx = await contract.mint({ nonce: 42 });Mismatched nonces cause transactions to get stuck or replaced.
const tx = await contract.mint({ nonce: 42 });Reading Events from a Receipt
After mining, you can inspect the events emitted by your transaction from the receipt logs:
const receipt = await tx.wait();
for (const log of receipt.logs) {
const parsed = contract.interface.parseLog(log);
if (parsed) console.log(parsed.name, parsed.args);
}This confirms the contract did what you expected.
const receipt = await tx.wait();
for (const log of receipt.logs) {
const parsed = contract.interface.parseLog(log);
if (parsed) console.log(parsed.name, parsed.args);
}Quick Check
Test your understanding of sending transactions.
Recap
You learned to send state-changing transactions.
- Writes require a signer; attach one with
connector at construction. - A write call returns a pending tx;
tx.wait()gives the mined receipt. - Check
receipt.status; wait for more confirmations against reorgs. - Send ETH via a
valueoverride; estimate cost withestimateGas. - Handle failures with try/catch and mind the account nonce.
Aprende Web3 & DApp Development Fundamentals con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 29
- Lecciones
- 105
Preguntas frecuentes
¿La lección «Envío de transacciones» es gratis?
Sí — el texto completo de «Envío de transacciones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Web3 & DApp Development Fundamentals, actualiza a CoddyKit PRO. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.
¿Qué aprenderé en «Envío de transacciones»?
Escribir en la cadena Practicas Web3 & DApp Development Fundamentals con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Web3 & DApp Development Fundamentals?
No se requiere experiencia previa. Web3 & DApp Development Fundamentals en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Envío de transacciones»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Web3 & DApp Development Fundamentals?
Sí. Cada lección de Web3 & DApp Development Fundamentals incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Conexión a un provider
- Lectura de datos de contratos
- Envío de transacciones
- Escucha de eventos