Monad 백서

Monad

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 26쪽

```shell theme={null} touch abi.json ``` 2. Copy the [WrappedMonad](https://testnet.monadvision.com/token/0xFb8bf4c1CC7a94c73D209a149eA2AbEa852BC541?tab=Contract) ABI from the explorer <img alt="image of explorer" /> 3. Paste the ABI into your `abi.json` file ### Initialize the project Run the initialization command: ```shell theme={null} pnpx envio init ``` Follow the prompts: 1. Press Enter when asked for a folder name (to use current directory) 2. Select `TypeScript` as your language 3. Choose `Evm` as the blockchain ecosystem 4. Select `Contract Import` for initialization 5. Choose `Local ABI` as the import method 6. Enter `./abi.json` as the path to your ABI file 7. Select only the `Transfer` event to index 8. Choose `<Enter Network Id>` and input `10143` (Monad Testnet chain ID) 9. Enter `WrappedMonad` as the contract name 10. Input the contract address: `0xFb8bf4c1CC7a94c73D209a149eA2AbEa852BC541` 11. Select `I'm finished` since we're only indexing one contract 12. Choose whether to create or add an existing API token. If you choose to create a new token, you'll be taken to a page that looks like this: <img alt="new API token view" /> Once the project is initialized, you should see the following project structure in your project directory. <img alt="envio dashboard" /> Add the following code to `config.yaml` file, to make transaction hash available in event handler: ```yaml lines title="config.yaml" theme={null} # default config... field_selection: transaction_fields: - hash ``` *More details about the `field_selection` config [here](https://docs.envio.dev/docs/HyperIndex/configuration-file#field-selection)* ## Starting the indexer Start Docker Desktop. To start the indexer run the following command in the project directory: ```shell theme={null} pnpx envio dev ``` You should see something similar to the below image in your terminal; this means that the indexer is syncing and will eventually reach the tip of the chain. <img alt="envio indexer syncing" /> You will also see this page open in your browser automatically, the password is `testing`. <img alt="hasura local page" /> We can use this interface to query the indexer using GraphQL. Results will depend on the sync progress: <img alt="query interface" /> Currently, the indexer is catching up to the tip of the chain. Once syncing is complete the indexer will be able to identify latest WMON transfers. We can shut down the indexer for now, so we can proceed with Telegram integration. ## Creating the Telegram bot 1. Visit [BotFather](https://t.me/botfather) to create your bot and get an API token 2. Add these environment variables to your `.env` file: ``` ENVIO_BOT_TOKEN=<your_bot_token> ENVIO_TELEGRAM_CHAT_ID=<your_chat_id> ``` To get your chat ID: 1. Create a Telegram group and add your bot 2. Send `/start` to the bot: `@YourBot /start` 3. Visit `https://api.telegram.org/bot<YourBOTToken>/getUpdates` 4. Look for the channel chat ID (it should start with "-") <Note> If you don't see the chat ID, try removing and re-adding the bot to the group. </Note> The Telegram bot is now ready. ## Integrating Telegram API to HyperIndex Event Handler Create a folder `libs` inside `src` folder in the project directory, create a file inside it `telegram.ts` and add the following code ```ts lines title="src/libs/telegram.ts" theme={null} import axios from "axios"; import { CHAT_ID, BOT_TOKEN } from "../constants"; export const sendMessageToTelegram = async (message: string): Promise<void> => { try { const apiUrl = `https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`; await axios.post(apiUrl, { chat_id: CHAT_ID, text: message, parse_mode: "HTML", }); } catch (error) { console.error("Error sending message:", error); } }; ``` You will come across some errors, let's fix them. Install `axios` package ```bash theme={null} pnpm i axios ``` Create a file in `src` folder called `constants.ts` and add the following code: ```ts lines title="src/constants.ts" theme={null} export const EXPLORER_URL_MONAD = "https://testnet.monadvision.com/"; // Threshold for WMON transfer amount above which the bot sends a notification export const THRESHOLD_WEI: string = process.env.ENVIO_THRESHOLD_WEI ?? "1000000000000000000"; // in wei export const BOT_TOKEN = process.env.ENVIO_BOT_TOKEN; // Telegram bot token export const CHAT_ID = process.env.ENVIO_TELEGRAM_CHAT_ID; // WMON Transfers Notification Channel ID // Function to get explorer url for the provided address export const explorerUrlAddress = (address: string) => EXPLORER_URL_MONAD + "address/" + address; // Function to get explorer url for the provided transaction hash export const explorerUrlTx = (txHash: string) => EXPLORER_URL_MONAD + "tx/" + txHash; ``` We can now edit the `EventHandlers.ts` in `src` folder, to add the code for sending the telegram message: ```ts lines title="src/EventHandlers.ts" theme={null} import { WrappedMonad, } from "generated"; import { isIndexingAtHead, weiToEth } from "./libs/helpers"; import { sendMessageToTelegram } from "./libs/telegram"; import { THRESHOLD_WEI, explorerUrlAddress, explorerUrlTx } from "./constants"; // Other event handlers can be removed... WrappedMonad.Transfer.handler(async ({ event, context }) => { const from_address = event.params.src; const to_address = event.params.dst; if (isIndexingAtHead(event.block.timestamp) && event.params.wad >= BigInt(THRESHOLD_WEI)) { // Only send a message when the indexer is indexing event from the time it was started and not historical transfers, and only message if the transfer amount is greater than or equal to THRESHOLD_WEI. // Example message // WMON Transfer ALERT: A new transfer has been made by 0x65C3564f1DD63eA81C11D8FE9a93F8FFb5615233 to 0xBA5Cf1c0c1238F60832618Ec49FC81e8C7C0CF01 for 2.0000 WMON! 🔥 - View on Explorer const msg = `WMON Transfer ALERT: A new transfer has been made by <a href="${explorerUrlAddress(from_address)}">${from_address}</a> to <a href="${explorerUrlAddress(to_address)}">${to_address}</a> for ${weiToEth(event.params.wad)} WMON! 🔥 - <a href="${explorerUrlTx( event.transaction.hash )}">View on Explorer</a>`; await sendMessageToTelegram(msg); } }); ``` Let us now fix the import error. Create a file called `helpers.ts` in `src/libs` folder, paste the following code in it: ```ts lines title="src/libs/helpers.ts" theme={null} // Used to ensure notifications are only sent while indexing at the head and not historical sync const INDEXER_START_TIMESTAMP = Math.floor(new Date().getTime() / 1000); export const isIndexingAtHead = (timestamp: number): boolean => { return timestamp >= INDEXER_START_TIMESTAMP; } // Convert wei to ether for human readability export const weiToEth = (bigIntNumber: bigint): string => { // Convert BigInt to string const numberString = bigIntNumber.toString(); const decimalPointsInEth = 18; // Extract integer part and decimal part const integerPart = numberString.substring( 0, numberString.length - decimalPointsInEth ); const decimalPart = numberString.slice(-decimalPointsInEth); // Insert decimal point const decimalString = (integerPart ? integerPart : "0") + "." + decimalPart.padStart(decimalPointsInEth, "0"); // Add negative sign if necessary return decimalString.slice(0, -14); }; ``` That's it! We can now run the indexer, and the telegram bot will start sending messages in the telegram channel when the indexer detects a WMON transfer! <img alt="example bot message" /> *Note: Screenshot was taken before message format was changed. The message will be slightly different if you followed the guide.* <Note> You may not immediately start seeing messages because the indexer take some time to catch up to the tip of the the recent blocks. The bot will only send notifications for transfers when the indexer detects a WMON transfer in finalized blocks, with timestamp greater than or equal to the indexer start time. </Note> # How to query token data with Envio HyperSync Source: https://docs.monad.xyz/guides/indexers/token-snapshot-hypersync In this guide, you will learn how to efficiently compute token ownership for ERC-721, ERC-20, and ERC-1155 contracts on Monad, using Envio HyperSync to accelerate the process. ## Background A common problem for EVM developers is the "historical balance problem" - recovering the full mapping of accounts to balances for an ERC-20, ERC-721, or ERC-1155 token. Solidity doesn't keep track of the keys in a mapping; values are stored in the appropriate storage slot after hashing the key. Therefore, to recover the balances, a typical strategy is to replay all transfer events for that token and compute the rolling sum. Envio HyperSync is an indexer that allows developers to query millions of blockchain events in seconds. In this guide, we'll use data from HyperSync to reconstruct the historical balances for a token. ## Prerequisites * Node.js 18+ * Free HyperSync API key from [envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) ## HyperSync Endpoints <div> <table> <thead> <tr> <th>Network</th> <th>URL</th> </tr> </thead> <tbody> <tr> <td>Testnet</td> <td> <CopyToClipboard>`https://monad-testnet.hypersync.xyz`</CopyToClipboard> </td> </tr> <tr> <td>Mainnet</td> <td> <CopyToClipboard>`https://monad.hypersync.xyz`</CopyToClipboard> </td> </tr> </tbody> </table> </div> ## Ingredients This guide surveys how to reconstruct balances for all three of the most popular token standards - ERC-20, ERC-721, and ERC-1155. Each uses some common ingredients, while requiring different logic to assemble the end reuslt. ### Querying Transfer Events First, let's write some code to query **all** of the Transfer events for our contract, filtering for the appropriate signature. ERC-20 and ERC-721 use the `Transfer` event below, while ERC-1155 uses the `TransferSingle` and `TransferBatch` events: | Event | Signature | | - | - | | `Transfer(address,address,uint256)` | `0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef` | | `TransferSingle(address,address,address,uint256,uint256)` | `0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62` | | `TransferBatch(address,address,address,uint256[],uint256[])` | `0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb` | ```typescript lines title="lib/signatures.ts" theme={null} // ERC-20 and ERC-721 share the same Transfer signature const TRANSFER_EVENT = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; // ERC-1155 events const TRANSFER_SINGLE = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"; const TRANSFER_BATCH = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb"; ``` Here is code for querying the events for an ERC-20 contract: ```typescript lines title="lib/hypersync.ts" theme={null} const HYPERSYNC_URL = "https://monad-testnet.hypersync.xyz"; // keccak256("Transfer(address,address,uint256)") - same for ERC-20 and ERC-721 const TRANSFER_SIGNATURE = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; async function queryTransfers(contractAddress: string, apiKey: string) { const response = await fetch(`${HYPERSYNC_URL}/query`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}`, }, body: JSON.stringify({ from_block: 0, logs: [ { address: [contractAddress], topics: [[TRANSFER_SIGNATURE]], }, ], field_selection: { log: ["topic0", "topic1", "topic2", "topic3", "data"], }, }), }); return response.json(); } ``` ### Field Selection To optimize our queries, we should only request the fields we actually need. This reduces response size and speeds up queries significantly. Different token standards encode data in different topics: **ERC-721** (tokenId in topic3): ```json theme={null} { "log": ["topic0", "topic2", "topic3"] } ``` **ERC-20** (value in data): ```json theme={null} { "log": ["topic0", "topic1", "topic2", "data"] } ``` **ERC-1155** (id and value in data): ```json theme={null} { "log": ["topic0", "topic1", "topic2", "topic3", "data"] } ``` ### Parsing Log Data Now that we have the raw event data, we need to parse it into usable values. Topics are 32-byte hex strings where addresses are left-padded with zeros, occupying the last 20 bytes: ```typescript lines title="lib/parse.ts" theme={null} function parseAddress(topic: string): string { return "0x" + topic.slice(-40).toLowerCase(); } function parseTokenId(topic: string): string { return BigInt(topic).toString(); } function parseValue(data: string): bigint | null { if (!data || data === "0x") return null; return BigInt(data); } ``` > **Note:** `parseValue` returns the raw token value as a `bigint`. ERC-20 tokens have a `decimals` property (typically 18) — divide by `10n ** BigInt(decimals)` to convert to a human-readable amount. ### Pagination HyperSync returns paginated results to handle large datasets efficiently. We need to continue querying until `next_block` is undefined to get all transfers: ```typescript lines title="lib/paginate.ts" theme={null} async function fetchAllTransfers(contractAddress: string, apiKey: string) { const ownership = new Map<string, string>(); let fromBlock = 0; let hasMore = true; while (hasMore) { const response = await queryHypersync(contractAddress, fromBlock, apiKey); // Process logs for (const block of response.data) { for (const log of block.logs) { const to = parseAddress(log.topic2); const tokenId = parseTokenId(log.topic3); ownership.set(tokenId, to); } } // Check for more pages if (response.next_block && response.next_block > fromBlock) { fromBlock = response.next_block; } else { hasMore = false; } } return ownership; } ``` Now we can start putting it all together. ## ERC-721 Balance Snapshot For ERC-721, we will reconstruct the current ownership state by replaying all Transfer events. For NFTs, the last transfer for each token ID determines the current owner: ```typescript lines title="app/api/snapshot/route.ts" theme={null} import { NextRequest, NextResponse } from "next/server"; const HYPERSYNC_URL = "https://monad-testnet.hypersync.xyz"; // keccak256("Transfer(address,address,uint256)") - same for ERC-20 and ERC-721 const TRANSFER_SIGNATURE = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; function parseAddress(topic: string): string { return "0x" + topic.slice(-40).toLowerCase(); } function parseTokenId(topic: string): string { return BigInt(topic).toString(); } interface HypersyncLog { topic0: string; topic2: string; topic3: string; } interface HypersyncResponse { data: { logs: HypersyncLog[] }[]; next_block?: number; } async function queryHypersync( contractAddress: string, fromBlock: number, apiKey: string ): Promise<HypersyncResponse> { const response = await fetch(`${HYPERSYNC_URL}/query`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}`, }, body: JSON.stringify({ from_block: fromBlock, logs: [{ address: [contractAddress], topics: [[TRANSFER_SIGNATURE]] }], field_selection: { log: ["topic0", "topic2", "topic3"] }, }), }); if (!response.ok) { throw new Error(`HyperSync error: ${response.status}`); } return response.json(); } export async function GET(request: NextRequest) { const contract = request.nextUrl.searchParams.get("contract"); const apiKey = process.env.HYPERSYNC_BEARER_TOKEN; if (!contract || !apiKey) { return NextResponse.json({ error: "Missing parameters" }, { status: 400 }); } // Track current owner for each tokenId const ownership = new Map<string, string>(); let fromBlock = 0; let hasMore = true; while (hasMore) { const response = await queryHypersync(contract, fromBlock, apiKey); for (const block of response.data) { for (const log of block.logs) { const to = parseAddress(log.topic2); const tokenId = parseTokenId(log.topic3); ownership.set(tokenId, to); // Last transfer wins } } if (response.next_block && response.next_block > fromBlock) { fromBlock = response.next_block; } else { hasMore = false; } } // Filter out burned tokens const snapshot = Array.from(ownership.entries()) .filter(([, owner]) => owner !== ZERO_ADDRESS) .map(([tokenId, owner]) => ({ tokenId, owner })); return NextResponse.json({ snapshot }); } ``` ## ERC-20 Balance Snapshot For ERC-20 tokens, we need to sum all transfers to calculate current balances. Unlike NFTs where we track ownership, ERC-20 balances require summing all incoming and outgoing transfers for each address. First, query ERC-20 transfers with the right field selection (topic1 for `from`, topic2 for `to`, and `data` for the value): ```typescript lines title="lib/erc20.ts" theme={null} async function queryERC20Transfers( contractAddress: string, fromBlock: number, apiKey: string ): Promise<HypersyncResponse> { const response = await fetch(`${HYPERSYNC_URL}/query`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}`, }, body: JSON.stringify({ from_block: fromBlock, logs: [{ address: [contractAddress], topics: [[TRANSFER_SIGNATURE]] }], field_selection: { log: ["topic0", "topic1", "topic2", "data"] }, }), }); if (!response.ok) { throw new Error(`HyperSync error: ${response.status}`); } return response.json(); } ``` Then reconstruct balances by summing all transfers: ```typescript lines title="lib/erc20.ts" theme={null} async function getERC20Balances(contractAddress: string, apiKey: string) { const balances = new Map<string, bigint>(); let fromBlock = 0; let hasMore = true; while (hasMore) { const response = await queryERC20Transfers(contractAddress, fromBlock, apiKey); for (const block of response.data) { for (const log of block.logs) { const from = parseAddress(log.topic1); const to = parseAddress(log.topic2); const value = parseValue(log.data); if (value === null) continue; // Subtract from sender if (from !== ZERO_ADDRESS) { const current = balances.get(from) || 0n; balances.set(from, current - value); } // Add to receiver if (to !== ZERO_ADDRESS) { const current = balances.get(to) || 0n; balances.set(to, current + value); } } } if (response.next_block && response.next_block > fromBlock) { fromBlock = response.next_block; } else { hasMore = false; } } // Filter positive balances, sort descending return Array.from(balances.entries()) .filter(([, balance]) => balance > 0n) .sort((a, b) => (b[1] > a[1] ? 1 : -1)) .map(([address, balance]) => ({ address, balance: balance.toString() })); } ``` ## ERC-1155 Balance Snapshot ERC-1155 tokens work differently from ERC-20 and ERC-721. They store `id` and `value` in the data field rather than topics, requiring more complex parsing: ```typescript lines title="lib/erc1155.ts" theme={null} // TransferSingle: data = id (32 bytes) + value (32 bytes) function parseTransferSingle(data: string): { tokenId: string; value: bigint } | null { if (!data || data.length < 130) return null; const tokenId = BigInt("0x" + data.slice(2, 66)).toString(); const value = BigInt("0x" + data.slice(66, 130)); return { tokenId, value }; } // TransferBatch: ABI-encoded arrays function parseTransferBatch(data: string): { tokenId: string; value: bigint }[] | null { if (!data || data.length < 258) return null; // Decode offsets const idsOffset = Number(BigInt("0x" + data.slice(2, 66))); const valuesOffset = Number(BigInt("0x" + data.slice(66, 130))); // Read array lengths const idsLengthStart = 2 + idsOffset * 2; const idsLength = Number(BigInt("0x" + data.slice(idsLengthStart, idsLengthStart + 64))); const valuesLengthStart = 2 + valuesOffset * 2; const valuesLength = Number(BigInt("0x" + data.slice(valuesLengthStart, valuesLengthStart + 64))); if (idsLength !== valuesLen
프로젝트로 돌아가기