0Pricing
Web3 & DApp Development Fundamentals · レッスン

トランザクションとイベントの処理

DAppからトランザクションを送信し、トランザクションの確定を処理し、スマートコントラクトのイベントを監視してUIを更新する方法を学びます。

「トランザクションとイベントの処理」はCoddyKit上の無料Web3 & DApp Development Fundamentalsレッスンです。 これはレッスン3/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWeb3 & DApp Development Fundamentals学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Web3 & DApp Development Fundamentalsコースには全3レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Making DApps Dynamic

So far, you've learned how to connect your DApp to the blockchain and read data. But what if you want to change data or perform actions?

This lesson teaches you how to send transactions from your DApp to modify blockchain state and how to listen for real-time updates using smart contract events.

What is a Blockchain Transaction?

A blockchain transaction is a signed message that changes the state of the blockchain. Every transaction costs a small fee called gas, paid in Ether (ETH).

Common DApp transactions include:

  • Sending Ether to another address.
  • Calling a smart contract function that writes or modifies data.
  • Deploying a new smart contract.

Sending Transactions from Your DApp

To send a transaction that calls a smart contract function, your DApp needs to:

  1. Connect to a blockchain provider (e.g., MetaMask).
  2. Get a signer (the connected user's wallet).
  3. Call the desired contract function, passing any required parameters.

The user's wallet will then prompt them to confirm and sign the transaction.

Calling a Write Function Example

Here's how you might call a simple setValue function on a smart contract using Ethers.js. Remember, contract refers to your instantiated contract object.

// Assuming 'contract' is an Ethers.js Contract instance
// and 'signer' is obtained from the connected wallet.

async function updateValue(newValue) {
  try {
    const tx = await contract.connect(signer).setValue(newValue);
    console.log("Transaction sent: ", tx.hash);
    // Wait for the transaction to be mined
    await tx.wait();
    console.log("Transaction confirmed!");
  } catch (error) {
    console.error("Error sending transaction:", error);
  }
}

Waiting for Transaction Confirmation

After sending a transaction, it's not immediately processed. It goes into a transaction pool and waits to be included in a block by a miner or validator.

The await tx.wait() call is crucial. It pauses your DApp's execution until the transaction is mined and confirmed on the blockchain, ensuring your UI reflects the latest state.

Understanding Transaction Receipts

When tx.wait() resolves, it returns a transaction receipt. This receipt contains important information about the transaction's outcome:

  • blockHash and blockNumber: Where it was included.
  • gasUsed: The actual gas consumed.
  • status: Indicates if the transaction was successful (1) or failed (0).

Always check the status to ensure the contract call executed as expected!

Introducing Smart Contract Events

Smart contract events are a powerful mechanism for your contracts to 'broadcast' information to external applications (like your DApp) when something significant happens.

Think of them as logs or notifications that DApps can listen to. They are a cost-effective way to communicate data from the blockchain without storing it directly on-chain.

Emitting Events in Solidity

In Solidity, you first define an event with its parameters, then use the emit keyword to trigger it within a function. Here's a simple example:

pragma solidity ^0.8.0;

contract MyContract {
  uint public value;

  // Define an event
  event ValueChanged(address indexed user, uint oldValue, uint newValue);

  function setValue(uint _newValue) public {
    uint _oldValue = value;
    value = _newValue;
    // Emit the event
    emit ValueChanged(msg.sender, _oldValue, _newValue);
  }
}

Listening for Events in Your DApp

Your DApp can subscribe to specific events emitted by a contract. When an event occurs, your DApp receives the event data, allowing you to update the UI or trigger other actions in real-time.

This avoids constant 'polling' (repeatedly asking the blockchain for updates), making your DApp more efficient.

// Assuming 'contract' is an Ethers.js Contract instance

contract.on("ValueChanged", (user, oldValue, newValue, event) => {
  console.log(`Value changed by ${user}`);
  console.log(`From ${oldValue} to ${newValue}`);
  // Update your DApp's UI here, e.g., display the new value
  updateDisplay(newValue);
});

console.log("Listening for ValueChanged events...");

Quick Check: Tx & Events

When calling a smart contract function that modifies state from your DApp, what is the primary purpose of using await tx.wait()?

Recap & Next Steps

You've learned how to make your DApps truly interactive!

  • You can now send transactions to modify blockchain state.
  • You know how to wait for confirmation and handle transaction receipts.
  • You understand how smart contract events provide real-time updates to your DApp.

These skills are fundamental for building dynamic and responsive decentralized applications. Keep practicing to master DApp interaction!

よくある質問

「トランザクションとイベントの処理」レッスンは無料ですか?

はい。「トランザクションとイベントの処理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Web3 & DApp Development Fundamentalsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Web3 & DApp Development Fundamentalsコースには全3レッスンが含まれています。

「トランザクションとイベントの処理」で何を学びますか?

DAppからトランザクションを送信し、トランザクションの確定を処理し、スマートコントラクトのイベントを監視してUIを更新する方法を学びます。 ブラウザで直接実行するハンズオンコードでWeb3 & DApp Development Fundamentalsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Web3 & DApp Development Fundamentalsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのWeb3 & DApp Development Fundamentalsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/3です。

「トランザクションとイベントの処理」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このWeb3 & DApp Development Fundamentalsレッスンでコードを書いて実行できますか?

はい。すべてのWeb3 & DApp Development Fundamentalsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. ReactとWeb3フレームワーク
  2. ウォレットの統合
  3. トランザクションとイベントの処理
← Web3 & DApp Development Fundamentalsに戻る