Monad 백서

Monad

원문

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

using Remix </Card> </CardGroup> ## Verify Smart Contract <CardGroup> <Card title="Foundry" href="/guides/verify-smart-contract/foundry"> Verify a smart contract on Monad using Foundry </Card> <Card title="Hardhat" href="/guides/verify-smart-contract/hardhat"> Verify a smart contract on Monad using Hardhat </Card> </CardGroup> ## Uniswap v4 Hooks <CardGroup> <Card title="Uniswap v4 Hooks" href="/guides/uniswap-v4-hooks"> Build, test, and deploy custom liquidity pool behavior on Monad </Card> </CardGroup> ## Indexing <CardGroup> <Card title="GhostGraph" href="/guides/indexers/ghost"> Index transfers with GhostGraph </Card> <Card title="Envio" href="/guides/indexers/tg-bot-using-envio"> Index transfers for a telegram bot using Envio </Card> <Card title="QuickNode Streams" href="/guides/indexers/quicknode-streams"> Index transfers using QuickNode Streams </Card> </CardGroup> ## Connectivity <CardGroup> <Card title="Reown AppKit" href="/guides/reown-guide"> Connect a wallet to your app with Reown AppKit </Card> </CardGroup> ## NFTs <CardGroup> <Card title="ERC-6551 (Token-Bound Accounts)" href="/guides/erc-6551"> Give every NFT its own account with Tokenbound on Monad </Card> </CardGroup> ## AI <CardGroup> <Card title="MCP Server" href="/guides/monad-mcp"> Build an MCP server to interact with Monad Testnet </Card> <Card title="x402 on Monad" href="/guides/x402-guide"> How to setup x402-enabled endpoints with Monad support </Card> </CardGroup> ## Execution Events <CardGroup> <Card title="Set up Execution Events" href="/guides/execution-events/setup"> Configure your Monad node to enable execution events </Card> <Card title="Consume Events in Rust" href="/guides/execution-events/consume-rust"> Build a Rust application to read execution events </Card> </CardGroup> # How to index token transfers with GhostGraph Source: https://docs.monad.xyz/guides/indexers/ghost ## Introduction In this guide, you will create an ERC20 token on Monad Testnet and index its transfers with [GhostGraph](https://docs.tryghost.xyz/). You'll learn how to: * Deploy a basic ERC20 token contract * Test the contract locally * Deploy to Monad Testnet * Set up event tracking with GhostGraph ## Prerequisites Before starting, ensure you have: * Node.js installed (v16 or later) * Git installed * [Foundry](https://github.com/foundry-rs/foundry) installed * Some MONAD testnet tokens (for gas fees) * Basic knowledge of Solidity and ERC20 tokens ## Project Setup First, clone the starter repository: ```sh theme={null} git clone https://github.com/chrischang/cat-token-tutorial.git cd cat-token-tutorial ``` ## CatToken Contract Implementation The `src/CatToken.sol` contract implements a basic ERC20 token with a fixed supply. Here's the code: ```solidity lines title="src/CatToken.sol" theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract CatToken is ERC20 { /** * @dev Constructor that gives msg.sender all existing tokens. * Initial supply is 1 billion tokens. */ constructor() ERC20("CatToken", "CAT") { // Mint initial supply of 1 billion tokens to deployer // This will emit a Transfer event that GhostGraph can index _mint(msg.sender, 1_000_000_000 * 10 ** decimals()); } } ``` This implementation: * Creates a token with name "CatToken" and symbol "CAT" * Mints 1 billion tokens to the deployer's address * Uses OpenZeppelin's battle-tested ERC20 implementation ## Testing the Contract Navigate to the test file `test/CatToken.t.sol`: ```solidity lines title="test/CatToken.t.sol" theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "forge-std/Test.sol"; import "../src/CatToken.sol"; contract CatTokenTest is Test { CatToken public token; address public owner; address public user; function setUp() public { owner = address(this); user = address(0x1); token = new CatToken(); } function testInitialSupply() public view { assertEq(token.totalSupply(), 1_000_000_000 * 10**18); assertEq(token.balanceOf(owner), 1_000_000_000 * 10**18); } function testTransfer() public { uint256 amount = 1_000_000 * 10**18; token.transfer(user, amount); assertEq(token.balanceOf(user), amount); assertEq(token.balanceOf(owner), 999_000_000 * 10**18); } } ``` Run the tests: ```sh theme={null} forge test -vv ``` ## Deployment Setup ### 1. Create a `.env` file: ```sh theme={null} cp .env.example .env ``` ### 2. Add your credentials to `.env` file: ```sh theme={null} PRIVATE_KEY=your_private_key_here MONAD_TESTNET_RPC=https://testnet-rpc.monad.xyz ``` ### 3. Create deployment script `script/DeployCatToken.s.sol`: ```solidity lines title="script/DeployCatToken.s.sol" theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "forge-std/Script.sol"; import "../src/CatToken.sol"; contract DeployCatToken is Script { function run() external { // Retrieve private key from environment uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY"); vm.startBroadcast(deployerPrivateKey); CatToken token = new CatToken(); vm.stopBroadcast(); // Log the token address - this will be needed for GhostGraph indexing and submit transactions console.log("CatToken deployed to:", address(token)); } } ``` ## Deploying CatToken on Monad Testnet ### 1. Load environment variables: ```sh theme={null} source .env ``` ### 2. Deploy the contract: ```sh theme={null} forge script script/DeployCatToken.s.sol \ --rpc-url $MONAD_TESTNET_RPC \ --broadcast ``` Save the deployed contract address for the next steps. Remember to add `TOKEN_ADDRESS` into your `.env` file You should now have ```sh theme={null} PRIVATE_KEY=your_private_key_here MONAD_TESTNET_RPC=https://testnet-rpc.monad.xyz TOKEN_ADDRESS=0x... ``` ## Verify Smart Contract ### 1. Load environment variables: ```sh theme={null} source .env ``` ### 2. Verify the contract: ```sh theme={null} forge verify-contract \ --rpc-url $MONAD_TESTNET_RPC \ --verifier sourcify \ --verifier-url 'https://sourcify-api-monad.blockvision.org/' \ $TOKEN_ADDRESS \ src/CatToken.sol:CatToken ``` After verification, you should see the contract verified on the [MonadVision](https://testnet.monadvision.com). You should see a checkmark and the banner stating the contract source code verified. <img alt="Verified Contract" /> ## Script for Token Transfers Transactions Onchain We perform some token transfer transactions onchain to trigger the `Transfer` event that GhostGraph will index. View the transfer script `script/TransferCatTokens.s.sol`: ```solidity lines title="script/TransferCatTokens.s.sol" theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "forge-std/Script.sol"; import "../src/CatToken.sol"; contract TransferCatTokens is Script { function run() external { uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY"); address token = vm.envAddress("TOKEN_ADDRESS"); vm.startBroadcast(deployerPrivateKey); // Send tokens to test addresses CatToken(token).transfer(address(0x1), 1000 * 10**18); CatToken(token).transfer(address(0x2), 2000 * 10**18); CatToken(token).transfer(address(0x3), 3000 * 10**18); vm.stopBroadcast(); } } ``` Run the below command to execute transfers: ```sh theme={null} forge script script/TransferCatTokens.s.sol \ --rpc-url $MONAD_TESTNET_RPC \ --broadcast ``` You have now deployed your ERC-20 contract and submitted transactions on the Monad testnet. Let’s track these onchain events with GhostGraph. ## Setting Up GhostGraph Indexing 1. Visit [GhostGraph](https://tryghost.xyz/) and click sign up for an account 2. Create a new GhostGraph <img alt="create_ghost_graph" /> 3. Copy and paste this into `events.sol` file. We are interested in tracking token flow. Let’s insert this event here. To learn more about events: [https://docs.tryghost.xyz/ghostgraph/getting-started/define-events](https://docs.tryghost.xyz/ghostgraph/getting-started/define-events) ```solidity lines title="events.sol" theme={null} interface Events { event Transfer(address indexed from, address indexed to, uint256 value); } ``` 4. Copy and paste this into `schema.sol` file. In this case, we are creating a few struct which we will use to save entity into the Ghost database. To learn more about schema: [https://docs.tryghost.xyz/ghostgraph/getting-started/define-schema](https://docs.tryghost.xyz/ghostgraph/getting-started/define-schema) ```solidity lines title="schema.sol" theme={null} struct Global { string id; uint256 totalHolders; } struct User { address id; uint256 balance; } struct Transfer { string id; address from; address to; uint256 amount; uint64 block; address emitter; uint32 logIndex; bytes32 transactionHash; uint32 txIndex; uint32 timestamp; } ``` 5. Click on `generate code` button to generate `indexer.sol` file along with some other readonly files. This file will be where the logic and transformations resides. 6. Copy and paste this into `indexer.sol` be sure to insert your token address to the `CAT_TESTNET_TOKEN_CONTRACT_ADDRESS` variable. ```solidity lines title="indexer.sol" theme={null} // SPDX-License-Identifier: MIT pragma solidity 0.8.19; import "./gen_schema.sol"; import "./gen_events.sol"; import "./gen_base.sol"; import "./gen_helpers.sol"; contract MyIndex is GhostGraph { using StringHelpers for EventDetails; using StringHelpers for uint256; using StringHelpers for address; address constant CAT_TESTNET_TOKEN_CONTRACT_ADDRESS = <INSERT YOUR TOKEN ADDRESS>; function registerHandles() external { graph.registerHandle(CAT_TESTNET_TOKEN_CONTRACT_ADDRESS); } function onTransfer(EventDetails memory details, TransferEvent memory ev) external { // Get global state to track holder count Global memory global = graph.getGlobal("1"); // Handle sender balance if (ev.from != address(0)) { // Skip if minting User memory sender = graph.getUser(ev.from); if (sender.balance == ev.value) { // User is transferring their entire balance global.totalHolders -= 1; // Decrease holder count } sender.balance -= ev.value; graph.saveUser(sender); } // Handle receiver balance User memory receiver = graph.getUser(ev.to); if (receiver.balance == 0 && ev.value > 0) { // New holder global.totalHolders += 1; // Increase holder count } receiver.balance += ev.value; graph.saveUser(receiver); // Save global state graph.saveGlobal(global); // Create and save transfer record Transfer memory transfer = graph.getTransfer(details.uniqueId()); transfer.from = ev.from; transfer.to = ev.to; transfer.amount = ev.value; // Store transaction metadata transfer.block = details.block; transfer.emitter = details.emitter; transfer.logIndex = details.logIndex; transfer.transactionHash = details.transactionHash; transfer.txIndex = details.txIndex; transfer.timestamp = details.timestamp; graph.saveTransfer(transfer); } } ``` 7. Compile and deploy your GhostGraph. After a few seconds, you should see GhostGraph has successfully indexed your contract. <img alt="ghostgraph_playground" /> 8. Clicking on the playground will take you to the GraphQL playground, where you can ensure the data is indexed correctly. Let’s copy and paste this into our playground and click the play button to fetch the data from GhostGraph. ```graphql lines title="GraphQL Playground" theme={null} query FetchRecentTransfers { transfers( orderBy: "block", orderDirection: "desc" limit: 50 ) { items { amount block emitter from id logIndex timestamp to transactionHash txIndex } } } ``` <img alt="graphql_playground" /> <Tip> Try submitting additional transactions by running the transfer script again. You should see that GhostGraph automatically indexes the new transactions. </Tip> ## Conclusion You have now successfully created a GhostGraph to track onchain data for your contract. The next step is to connect it to your frontend. The Ghost team has created end-to-end tutorials on how to do just that [here](https://docs.tryghost.xyz/blog/connect_ghost_graph_to_frontend/) # Use an Indexer Source: https://docs.monad.xyz/guides/indexers/index <CardGroup> <Card title="GhostGraph" href="/guides/indexers/ghost"> Index transfers with GhostGraph </Card> <Card title="Envio" href="/guides/indexers/tg-bot-using-envio"> Index transfers for a telegram bot using Envio </Card> <Card title="Envio HyperSync" href="/guides/indexers/token-snapshot-hypersync"> Query token data with Envio HyperSync </Card> <Card title="QuickNode Streams" href="/guides/indexers/quicknode-streams"> Index transfers using QuickNode Streams </Card> </CardGroup> # How to index every WMON transfer using QuickNode Streams Source: https://docs.monad.xyz/guides/indexers/quicknode-streams In this guide, you will learn how to use QuickNode Streams to index every [WMON](https://testnet.monadvision.com/token/0xFb8bf4c1CC7a94c73D209a149eA2AbEa852BC541) transfer, including internal transactions, on Monad Testnet. ## What is QuickNode Streams? [QuickNode Streams](https://www.quicknode.com/docs/streams/getting-started) is a web3 data streaming solution supporting real-time and historical Monad data that offers: * **Reliable Data Delivery** - Exactly-once, guaranteed delivery, seamlessly integrating with your data lake. Streams ensures every block, receipt, or trace is delivered exactly-once in the order of dataset finality, preventing issues like corrupt or missing data * **Real-Time Data Consistency** - Consistent, live data streaming * **Efficient Historical Data Handling** - Configurable date ranges and destinations for streamlined historical data management * **Easy Integration** - Simple setup through a user-friendly interface * **Transparent User Experience** - Clear logging, metrics, and usage tracking ## Setup Guide ### 1. Initial setup 1. Sign up for [QuickNode](https://dashboard.quicknode.com/?prompt=signup) and log into your dashboard. 2. Click on "Streams" in the left sidebar. <img alt="QuickNode Dashboard" /> 3. Click on "Create Stream". <img alt="Create Stream Button" /> ### 2. Configure Stream range 1. Give your stream a name. In this example we will name it `monad-quicknode-stream`. 2. In the "Network" section, select `Monad` from the dropdown. 3. In the "Stream Start" section you can choose to start the stream from the latest block or from a specific block number. <img alt="Stream Configuration" /> 4. In the "Stream End" section you can choose to end the stream until manually paused or at a specific block number. 5. In the "Latest block delay" section, you can set a block number as a delay in receiving data. For this guide we will receive data as soon as it is available.<br /><br />For example: If the block delay is `3`, you will receive data only when there is **new data available** for `3` blocks including latest block, this helps in case there is a reorg. 6. In the "Restream on reorg" section you can decide if you would like to get updated data restreamed in case of a reorg. For this guide we will keep this off. 7. Once done click "Next". <img alt="Additional Settings" /> ### 3. Set up dataset 1. In the "Dataset" dropdown you can select the dataset of your choice according to the use case. For this guide we will select `Block with Receipts` since we want to filter logs with events emitted by WMON contract. * Optional: Enable "Batch messages" to receive multiple blocks in a single message. This can be useful when the stream is not starting from the latest block. <img alt="Dataset Selection" /> 2. Feel free to test it out by entering a block number and clicking "Fetch payload". <img alt="Raw Payload Example" /> ### 4. Create WMON Transfer filter 1. In the "Modify the stream payload" section, you can define filters by clicking **"Customize your payload"**. For this guide, we will filter to only retrieve receipts involving WMON transfers. <img alt="modify stream image" /> 2. QuickNode has a set of filter templates. Select the **Decoded ERC20 transfers** template: <img alt="image for filter" /> 3. The editor will appear: <img alt="image of filter editor" /> The current filter allows all ERC20 transfers through. Replace the filter code with: ```js lines theme={null} function main(stream) { const erc20Abi = `[{ "anonymous": false, "inputs": [ {"indexed": true, "type": "address", "name": "from"}, {"indexed": true, "type": "address", "name": "to"}, {"indexed": false, "type": "uint256", "name": "value"} ], "name": "Transfer", "type": "event" }]`; const data = stream.data ? stream.data : stream; // Decodes logs from the receipts that match the Transfer event ABI var result = decodeEVMReceipts(data[0].receipts, [erc20Abi]); // Filter for receipts with decoded logs result = result.filter(receipt => { // Check if there are any ERC20 transfers if(receipt.decodedLogs) { // Check if there are any WMON transfers receipt.decodedLogs = receipt.decodedLogs.filter(log => log.address == "0xFb8bf4c1CC7a94c73D209a149eA2AbEa852BC541"); // Return receipt if there logs which indicate a WMON transfer. return receipt.decodedLogs.length > 0; } // Return nothing if there are no ERC20 transfers. return false; }); return { result }; } ``` 4. Test the filter with "Run test" <img alt="run test image" /> 5. "Save & close" to save the filter. <img alt="save & close image" /> 6. Click "Next" ### 5. Set up Stream destination For this guide we will keep the stream destination simple and use `Webhook` as the "Destination Type". 1. Let's use a site like [Svix Play](https://www.svix.com/play/) to quickly get a webhook and test the stream. <img alt="svix play image" /> 2. Copy the webhook url from Svix Play: <img alt="svix play copy url image" /> 3. In QuickNode: * Select `Webhook` as destination type * Paste your webhook URL * We can keep the rest of the settings as default <img alt="webhook dropdown image" /> 4. Click on "Check Connection" to test the webhook url. Check if you received the "PING" message in the Svix Play dashboard. <img alt="check connection image" /> <img alt="ping message image" /> 5. Click "Send Payload" to send a test payload to the webhook. <img alt="add send payload image" /> <img alt="svix payload image" /> 6. Finally click "Create a Stream" to create the stream. <img alt="create stream image" /> ### 6. Launch and Monitor You should now be able to see the stream delivering the messages to the webhook! <img alt="stream delivering image" /> <img alt="svix streaming receiving message video" /> You can pause the stream by clicking the switch in the top right corner. <img alt="pause switch image" /> ## Next Steps * Monitor your stream's performance in the QuickNode dashboard * Adjust filter parameters as needed * Connect to your production webhook endpoint when ready Your stream will now track all WMON transfers until manually paused or until reaching your specified end block. # How to build a transfer notification bot with Envio HyperIndex Source: https://docs.monad.xyz/guides/indexers/tg-bot-using-envio In this guide, you will learn how to use [Envio](https://envio.dev/) HyperIndex to create a Telegram bot that sends notifications whenever WMON tokens are transferred on the Monad Testnet. We'll walk through setting up both the indexer and the Telegram bot. Envio HyperIndex is an open development framework for building blockchain application backends. It offers real-time indexing, automatic indexer generation from contract addresses, and triggers for external API calls. ## Prerequisites You'll need the following installed: * Node.js v18 or newer * pnpm v8 or newer * Docker Desktop (required for running the Envio indexer locally) ## Setting up the project First, create and enter a new directory: ```shell theme={null} mkdir envio-mon && cd envio-mon ``` ### Get the contract ABI 1. Create an `abi.json` file:
프로젝트로 돌아가기