Monad 백서

Monad

원문

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

gth || idsLength === 0) return null; // Parse each id/value pair const results: { tokenId: string; value: bigint }[] = []; for (let i = 0; i < idsLength; i++) { const idStart = idsLengthStart + 64 + i * 64; const valueStart = valuesLengthStart + 64 + i * 64; const tokenId = BigInt("0x" + data.slice(idStart, idStart + 64)).toString(); const value = BigInt("0x" + data.slice(valueStart, valueStart + 64)); results.push({ tokenId, value }); } return results; } ``` ### Querying Multiple Event Types When working with ERC-1155 tokens, we can optimize by querying both TransferSingle and TransferBatch events in a single request: ```typescript lines title="lib/multi-event.ts" theme={null} const query = { from_block: 0, logs: [ { address: [contractAddress], topics: [[TRANSFER_SINGLE, TRANSFER_BATCH]], // Both ERC-1155 events }, ], field_selection: { log: ["topic0", "topic1", "topic2", "topic3", "data"], }, }; ``` Then route based on `topic0`: ```typescript lines theme={null} for (const log of block.logs) { if (log.topic0 === TRANSFER_SINGLE) { const parsed = parseTransferSingle(log.data); // handle single transfer... } else if (log.topic0 === TRANSFER_BATCH) { const parsed = parseTransferBatch(log.data); // handle batch transfer... } } ``` ## Get Latest Block To verify you've synced all available data, you can check the current chain height: ```typescript lines title="lib/height.ts" theme={null} async function getLatestBlock(apiKey: string): Promise<number> { const response = await fetch(`${HYPERSYNC_URL}/height`, { headers: { "Authorization": `Bearer ${apiKey}` }, }); const data = await response.json(); return data.height; } ``` ## Common Mistakes ### 1. Forgetting pagination HyperSync returns partial results. Always check `next_block`: ```typescript theme={null} // Wrong - only gets first page const response = await queryHypersync(contract, 0); // Right - loop until done while (response.next_block) { // continue querying... } ``` ### 2. Requesting unused fields Every field adds to response size. Be explicit: ```typescript theme={null} // Wrong - fetches everything field_selection: { log: ["*"] } // Right - only what you need field_selection: { log: ["topic0", "topic2", "topic3"] } ``` ### 3. Using libraries for simple parsing HyperSync returns raw hex. Native BigInt handles it: ```typescript theme={null} // Unnecessary - adds dependency import { decodeAbiParameters } from "viem"; // Sufficient - native JS const value = BigInt("0x" + data.slice(2, 66)); ``` ### 4. Not filtering burned tokens Address `0x000...000` means burned: ```typescript theme={null} const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; // Filter them out const active = ownership.filter(([, owner]) => owner !== ZERO_ADDRESS); ``` ## API Reference ### POST /query Query event logs. **Request body:** | Field | Type | Description | | - | - | - | | `from_block` | number | Starting block (inclusive) | | `to_block` | number | Ending block (optional) | | `logs` | array | Log filters | | `logs[].address` | string\[] | Contract addresses to filter | | `logs[].topics` | string\[]\[] | Topic filters (OR within array, AND across arrays) | | `field_selection.log` | string\[] | Fields to return | **Response:** | Field | Type | Description | | - | - | - | | `data` | array | Blocks containing matching logs | | `data[].logs` | array | Matching logs in block | | `next_block` | number | Next block to query (pagination) | ### GET /height Get current chain height. **Response:** | Field | Type | Description | | - | - | - | | `height` | number | Latest block number | ## Summary Envio HyperSync lets you query any contract's event history across Monad with a single paginated API — no node to run, no indexer to maintain. The `/query` endpoint accepts topic and address filters, and `/height` gives you the current chain tip. Check out the [full HyperSync documentation](https://docs.envio.dev/docs/HyperSync/overview) for additional query types and options. From here, you could extend this pattern to build airdrop eligibility checkers, governance voting power snapshots, or multi-token portfolio trackers. ## Next Steps * [Envio docs](https://docs.envio.dev/docs/HyperSync/overview) - Full HyperSync documentation * [API tokens](https://envio.dev/app/api-tokens) - Get your free API key # Customize and publish a hook Source: https://docs.monad.xyz/guides/uniswap-v4-hooks/customize-and-publish On this page, you will customize Counter, find contract addresses, and prepare your hook for mainnet. ## Customize the hook Open [`src/Counter.sol`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/src/Counter.sol). It inherits OpenZeppelin's `BaseHook`: ```solidity theme={null} import {BaseHook} from "@openzeppelin/uniswap-hooks/src/base/BaseHook.sol"; ``` `BaseHook` restricts external callbacks to the configured `PoolManager` and validates the hook address against `getHookPermissions()` during construction. The counter enables four callbacks: `beforeSwap`, `afterSwap`, `beforeAddLiquidity`, and `beforeRemoveLiquidity`. For example, its swap callback increments a counter for the current pool: ```solidity theme={null} function _beforeSwap(address, PoolKey calldata key, SwapParams calldata, bytes calldata) internal override returns (bytes4, BeforeSwapDelta, uint24) { beforeSwapCount[key.toId()]++; return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0); } ``` The return values acknowledge the callback, leave swap accounting unchanged, and request no fee override. If you enable or disable a callback, update both `getHookPermissions()` and the address flags in [`DeployHook.s.sol`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/script/monad/DeployHook.s.sol); changing the code or constructor arguments requires a new CREATE2 calculation. For a custom hook, also test unauthorized callback calls, state isolation across pools, both swap directions, exact-input and exact-output swaps, and failure paths. A callback's `sender` is the caller of the manager, often Universal Router or PositionManager; do not assume it identifies the end user or trust arbitrary `hookData` as authentication. ## Monad Testnet contract addresses The tutorial uses the following deployments on chain ID `10143`. The same addresses are listed in [`shared-infrastructure.json`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/shared-infrastructure.json), at the root of the example repository. | Contract | Monad Testnet address | | - | - | | PoolManager | `0x451D64ab3b650040d2aE1886602b97ed6eDc643d` | | PositionManager | `0x3Bb14E3D0Cd50aBe3EdACa06d06c29C78676C31A` | | PositionDescriptor | `0x1548b69E74BdD834c2e552a5c673acf921Aa7B11` | | StateView | `0xB639209539c61BaF67AC04876315786F8D0b153c` | | V4Quoter | `0x869834d127b230283fe63E0d0A9bEB67216a94C7` | | Universal Router 2.1.1 | `0x1b7bFCd2870329B987191910D85c22C7287f3c22` | | Permit2 | `0x000000000022D473030F116dDEE9F6B43aC78BA3` | | WMON | `0xFb8bf4c1CC7a94c73D209a149eA2AbEa852BC541` | | UnsupportedProtocol | `0xF5fa008BdB979427545c40fecE80d8cdEE4177C2` | The PoolManager has no owner or protocol-fee controller. The PoolManager and periphery addresses differ from Uniswap’s mainnet deployments. Permit2 uses the same address on both networks. ## Deploying on Monad Mainnet Monad Mainnet uses chain ID `143` and RPC `https://rpc.monad.xyz`. Use its PoolManager, `0x188d586ddcf52439676ca21a244753fa19f9ea8e`, from Uniswap’s [deployment list](https://developers.uniswap.org/docs/protocols/v4/deployments#monad-143). The example’s [`DeployHook.s.sol`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/script/monad/DeployHook.s.sol) deliberately accepts only chain ID `10143`. To adapt it for mainnet, change that check to `143` and supply the mainnet PoolManager through `POOL_MANAGER`. The script passes this address to the hook’s constructor and to [`NamespacedHookMiner.find`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/src/NamespacedHookMiner.sol), which searches for a salt with the required permission bits. The CREATE2 factory address is the same on both networks. The hook address also depends on the salt and initialization code, including constructor arguments. Because the PoolManager address changes, calculate the hook address again for mainnet. Test your custom hook and its pool interactions before deploying it with real liquidity. ### Existing Monad hooks The [Uniswap hook registry includes Monad](https://github.com/Uniswap/hooklist/tree/main/hooks/monad). Registry inclusion is not a security audit or a prerequisite for deploying a hook. The registry's Doppler entry for [`UniswapV4ScheduledMulticurveInitializerHook`](https://github.com/Uniswap/hooklist/blob/main/hooks/monad/0x580ca49389d83b019d07E17e99454f2F218e2dc0.json) restricts initialization and liquidity additions to an authorized initializer and blocks swaps until its configured start time. Its source is an example of launch controls implemented with hooks. ## Publish and extend your hook Publish and verify source code, document enabled permissions and administrator powers, and test the full pool lifecycle before using a custom hook with real liquidity. A hook revert can prevent the associated pool operation from completing. To make a deployed mainnet hook discoverable, follow the [hook registry contribution instructions](https://github.com/Uniswap/hooklist#submit-a-hook) for `hooks/monad`. Registry metadata does not automatically make a pool available in every router or interface; check each integration's support for your hook's behavior. For further examples, explore [OpenZeppelin Uniswap Hooks](https://github.com/OpenZeppelin/uniswap-hooks), [Uniswap's hook guides](https://developers.uniswap.org/docs/protocols/v4/guides/hooks/getting-started), and the [Monad hook registry](https://github.com/Uniswap/hooklist/tree/main/hooks/monad). # Deploy the hook and test tokens Source: https://docs.monad.xyz/guides/uniswap-v4-hooks/deploy On this page, you will deploy a Counter hook and two mock tokens on Monad Testnet. ## Prerequisites Complete [Setup](/guides/uniswap-v4-hooks/setup) first. Run the commands from your `monad-hook` directory with the account, RPC, and contract addresses loaded in the same shell. The addresses come from [`shared-infrastructure.json`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/shared-infrastructure.json) in that directory. If you opened a new shell, restore the environment variables from Setup’s [account configuration](/guides/uniswap-v4-hooks/setup#prepare-a-testnet-account) and [address exports](/guides/uniswap-v4-hooks/setup#load-the-contract-addresses). ## Deploy the mock tokens Create the manifest directory if you have not already done so: ```sh theme={null} mkdir -p deployments ``` Run [`DeployMockTokens.s.sol`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/script/monad/DeployMockTokens.s.sol) in simulation mode first. It deploys two 18-decimal `MockERC20` contracts and writes `deployments/tokens.json` with `.tokenA` and `.tokenB`: ```sh theme={null} FOUNDRY_PROFILE=monad_testnet forge script \ script/monad/DeployMockTokens.s.sol:DeployMockTokens \ --network monad --rpc-url "$MONAD_TESTNET_RPC_URL" \ --account monad-hooks-testnet \ --sender "$DEPLOYER" ``` Inspect the predicted addresses and gas estimate, then broadcast once: ```sh theme={null} FOUNDRY_PROFILE=monad_testnet forge script \ script/monad/DeployMockTokens.s.sol:DeployMockTokens \ --network monad --rpc-url "$MONAD_TESTNET_RPC_URL" \ --account monad-hooks-testnet \ --sender "$DEPLOYER" \ --broadcast --slow ``` After a successful broadcast, load the deployed token addresses: ```sh theme={null} export TOKEN_A="$(jq -er .tokenA deployments/tokens.json)" export TOKEN_B="$(jq -er .tokenB deployments/tokens.json)" ``` Both tokens have public `mint` and `burn` methods for testing. ## Mine and deploy the hook `Counter` enables four callbacks: `beforeSwap`, `afterSwap`, `beforeAddLiquidity`, and `beforeRemoveLiquidity`. Uniswap encodes these permissions in the hook address; Counter’s permission bits are `0x0ac0`. [`DeployHook.s.sol`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/script/monad/DeployHook.s.sol) finds a CREATE2 salt that produces an address with those bits, then deploys the hook through the factory at `0x4e59b44847b379578588920cA78FbF26c0B4956C`. It takes `POOL_MANAGER` as the constructor argument and writes the result to `deployments/hook.json`. Simulate the deployment: ```sh theme={null} FOUNDRY_PROFILE=monad_testnet forge script \ script/monad/DeployHook.s.sol:DeployHook \ --network monad --rpc-url "$MONAD_TESTNET_RPC_URL" \ --account monad-hooks-testnet \ --sender "$DEPLOYER" ``` Broadcast only after the simulation succeeds: ```sh theme={null} FOUNDRY_PROFILE=monad_testnet forge script \ script/monad/DeployHook.s.sol:DeployHook \ --network monad --rpc-url "$MONAD_TESTNET_RPC_URL" \ --account monad-hooks-testnet \ --sender "$DEPLOYER" \ --broadcast --slow ``` Read the hook address from the manifest and verify it: ```sh theme={null} export HOOK_ADDRESS="$(jq -er .hook deployments/hook.json)" cast code "$HOOK_ADDRESS" --rpc-url "$MONAD_TESTNET_RPC_URL" cast call "$HOOK_ADDRESS" "poolManager()(address)" --rpc-url "$MONAD_TESTNET_RPC_URL" ``` The `poolManager()` result should match `POOL_MANAGER`. ## Next step Continue to [Pool lifecycle](/guides/uniswap-v4-hooks/pool-lifecycle) to create a pool and trigger the hook’s callbacks. # Build with Uniswap v4 Hooks Source: https://docs.monad.xyz/guides/uniswap-v4-hooks/index Build, test, and deploy custom Uniswap v4 pool behavior on Monad with Foundry. [Uniswap v4 hooks](https://developers.uniswap.org/docs/protocols/v4/concepts/hooks) let you add custom logic to liquidity pools. In this guide, you will build and deploy a `Counter` hook on Monad Testnet, create a pool with two mock tokens, and run swaps that trigger its callbacks. ## What are hooks? Uniswap v4 stores pools in a shared contract called the `PoolManager`. A hook is a separate smart contract that the manager calls at selected points in a pool's lifecycle: | Operation | Callbacks | | - | - | | Initialize a pool | `beforeInitialize`, `afterInitialize` | | Add liquidity | `beforeAddLiquidity`, `afterAddLiquidity` | | Remove liquidity | `beforeRemoveLiquidity`, `afterRemoveLiquidity` | | Swap | `beforeSwap`, `afterSwap` | | Donate to liquidity providers | `beforeDonate`, `afterDonate` | You choose the hook when initializing a pool. Its address is part of the `PoolKey`, alongside the two currencies, fee, and tick spacing. Changing the hook address creates a different pool identity; it does not update an existing pool. One hook can serve multiple pools, so pool-specific state should be keyed by `PoolId`. Hooks execute synchronously within the transaction. They do not run on a timer: scheduled strategies also need transactions from users or automation. See Uniswap's [hooks overview](https://developers.uniswap.org/docs/protocols/v4/concepts/hooks) and [core contracts](https://github.com/Uniswap/v4-core). ## Common use cases | Use case | Example behavior | | - | - | | Launch controls | Reject swaps before a launch time or restrict who can add initial liquidity. | | Dynamic fees | Adjust swap fees based on pool activity or market conditions. | | Limit orders and scheduled execution | Execute an order when a swap reaches a target price. Time-based strategies still need an external transaction to trigger execution. | | LP incentives and analytics | Track liquidity changes and swaps to calculate rewards or collect pool statistics. | ## Testnet walkthrough The [example project](https://github.com/monad-developers/uniswap-v4-hooks-example) contains the hook, Foundry scripts, and tests. It uses contracts already deployed on Monad Testnet (chain ID `10143`): | Contract | Purpose | | - | - | | `PoolManager` | Stores pool state and calls the hook. | | `PositionManager` | Adds and removes liquidity; issues a position NFT to your account. | | `UniversalRouter` | Executes swaps. | | `Permit2` | Handles token approvals and transfers for the router and position manager. | | `V4Quoter` and `StateView` | Quote swaps and read pool state. | Anyone can use these testnet contracts. Their addresses are in [`shared-infrastructure.json`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/main/shared-infrastructure.json) at the root of the example project. The PoolManager and periphery addresses differ from Uniswap’s official mainnet deployments. You deploy your own hook and two mock tokens. The mock tokens are publicly mintable and have no monetary value. ## Follow the guide Follow the pages in order, running commands from the same `monad-hook` directory. <CardGroup> <Card title="Setup" href="/guides/uniswap-v4-hooks/setup"> Clone the pinned example and its submodules, install Node dependencies, run local tests, and prepare a testnet account. </Card> <Card title="Deploy" href="/guides/uniswap-v4-hooks/deploy"> Deploy the Counter hook and two mock tokens. </Card> <Card title="Pool lifecycle" href="/guides/uniswap-v4-hooks/pool-lifecycle"> Initialize a pool, mint an owned PositionManager NFT, swap through Universal Router, remove liquidity, and revoke approvals. </Card> <Card title="Customize and publish" href="/guides/uniswap-v4-hooks/customize-and-publish"> Change the hook’s behavior and prepare it for mainnet. </Card> </CardGroup> # Exercise and verify the pool Source: https://docs.monad.xyz/guides/uniswap-v4-hooks/pool-lifecycle On this page, you will initialize a testnet pool, mint an owned position, swap through Universal Router, remove liquidity, and revoke approvals. ## Prerequisites Complete [Deploy](/guides/uniswap-v4-hooks/deploy) and confirm the hook and both mock-token deployments. Run from the same `monad-hook` directory. It contains [`shared-infrastructure.json`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/shared-infrastructure.json); the deployment scripts created `deployments/tokens.json` and `deployments/hook.json`. If you opened a new shell, restore the account, network, and contract addresses: ```sh theme={null} export DEPLOYER="$(cast wallet address --account monad-hooks-testnet)" export MONAD_TESTNET_RPC_URL="https://testnet-rpc.monad.xyz" export EXPECTED_CHAIN_ID=10143 export SHARED_INFRA="shared-infrastructure.json" export POOL_MANAGER="$(jq -er .poolManager "$SHARED_INFRA")" export POSITION_MANAGER="$(jq -er .positionManager "$SHARED_INFRA")" export UNIVERSAL_ROUTER="$(jq -er .universalRouter "$SHARED_INFRA")" export STATE_VIEW="$(jq -er .stateView "$SHARED_INFRA")" export QUOTER="$(jq -er .quoter "$SHARED_INFRA")" export POSITION_DESCRIPTOR="$(jq -er .positionDescriptor "$SHARED_INFRA")" export PERMIT2="$(jq -er .permit2 "$SHARED_INFRA")" export WMON="$(jq -er .wrappedNative "$SHARED_INFRA")" export TOKEN_A="$(jq -er .tokenA deployments/tokens.json)" export TOKEN_B="$(jq -er .tokenB deployments/tokens.json)" export HOOK_ADDRESS="$(jq -er .hook deployments/hook.json)" ``` The script uses `deployments/position.json` to identify your NFT after it is minted. ## Initialize and exercise one pool [`PoolLifecycle.s.sol`](https://github.com/monad-developers/uniswap-v4-hooks-example/blob/c3cc78a88f10e5ba141cd6fb632f31db83c0daf8/script/monad/PoolLifecycle.s.sol) runs each operation as a separate
프로젝트로 돌아가기