0Pricing
Web3 & DApp Development Fundamentals · Lezione

Invio delle transazioni

Scrivere sulla chain

Invio delle transazioni è una lezione Web3 & DApp Development Fundamentals gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Web3 & DApp Development Fundamentals, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 connect or 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 value override; estimate cost with estimateGas.
  • Handle failures with try/catch and mind the account nonce.

Domande Frequenti

La lezione «Invio delle transazioni» è gratuita?

Sì — il testo completo di «Invio delle transazioni» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Web3 & DApp Development Fundamentals, passa a CoddyKit PRO. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.

Cosa imparerò in «Invio delle transazioni»?

Scrivere sulla chain Eserciti Web3 & DApp Development Fundamentals con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Web3 & DApp Development Fundamentals?

Non è richiesta alcuna esperienza precedente. Web3 & DApp Development Fundamentals su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Invio delle transazioni»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Web3 & DApp Development Fundamentals?

Sì. Ogni lezione Web3 & DApp Development Fundamentals include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Connessione a un provider
  2. Lettura dei dati dei contratti
  3. Invio delle transazioni
  4. Ascolto degli eventi
← Torna a Web3 & DApp Development Fundamentals