Monad 백서

Monad

원문

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

ry` duplicates the latest `baseFeePerGas` when `newest_block` is `latest`. Don't count it twice in charts or averages. See [Gas Pricing](/developer-essentials/gas-pricing) and the JSON-RPC [fee estimation notes](/reference/json-rpc/overview#fee-estimation). ## Handle transaction lifecycle A successful `eth_sendRawTransaction` means "accepted by this RPC node" — not a guarantee the transaction will land or succeed. The RPC node may accept it before checking nonce and balance against the latest state. Distinguish three stages: | Stage | What to show | Signal | | - | - | - | | Submitted | Pending | `eth_sendRawTransaction` returns a hash | | Included and executed locally | Completed or failed | `eth_getTransactionReceipt` returns a receipt | | Finalized | Finalized | The receipt's block number is at or below the block returned for the `finalized` tag | If an account just received MON and is about to spend it, wait until the receiving transaction's receipt block is at least `k` blocks behind the current block. Currently `k = 3` (\~1.2 seconds), but this can change. If a spend drops an undelegated account below 10 MON, wait `k` blocks before another MON spend. After undelegating, wait `k` blocks before emptying the account. Monad has no global mempool. Don't use `txpool_content` or `newPendingTransactions` for pending state. Instead: * Track local pending nonces for transactions you submitted. * Reconcile against receipts and `eth_getTransactionCount`. * Use `txpool_statusByAddress` or `txpool_statusByHash` for node-level pending status. * Scope pending lists to the user's account, not the whole network. ## Simulation and RPC differences `debug_trace*` methods don't return opcode-level struct logs. Use call-frame or prestate tracers for simulation and risk previews. WebSocket subscriptions: `newHeads`, `logs`, plus Monad-specific `monadNewHeads` and `monadLogs` for pre-finalization data. The `syncing` and `newPendingTransactions` WebSocket subscription types are not supported. See [WebSocket subscriptions](/reference/json-rpc/overview#websocket-subscriptions). Full nodes may serve recent state, but not arbitrary old state. Check RPC capability before showing past-state UI or old-block simulation, and link to an archive endpoint when needed. See [Historical Data](/developer-essentials/historical-data). ## EIPs and EVM differences Monad supports transaction types 0, 1, 2, and 4. Type 3 blob transactions are not supported. | Feature | Status | Wallet implication | | - | - | - | | EIP-4844 | Not supported | Reject type 3 transaction construction with a clear error. | | EIP-7702 | Supported with Monad-specific restrictions | A delegated EOA can hold less than 10 MON, but any transaction that lowers its balance below 10 MON reverts. Delegated account code also cannot run `CREATE` or `CREATE2`. | Monad has larger contract-size limits than Ethereum and some opcode repricing. Use Monad-specific thresholds for deploy-size warnings, and re-estimate per chain rather than hardcoding opcode costs. See [Differences from Ethereum](/developer-essentials/differences). ## Recipes ### Apply a chain-specific gas-limit margin Use Category Labs' 7.5% fixed-buffer result as a Monad starting point, then tune from production data — success rates, retries, and out-of-gas events. Basis points avoid floating-point rounding errors. ```ts theme={null} const DEFAULT_GAS_LIMIT_MARGIN_BPS = 15_000n // 1.5x const GAS_LIMIT_MARGIN_BPS_BY_CHAIN: Record<number, bigint> = { // 7.5% buffer. Measure against your wallet's transaction mix. 143: 10_750n, 10143: 10_750n, } export const applyGasLimitMargin = ({ chainId, estimatedGas, }: { chainId: number estimatedGas: bigint }) => { const margin = GAS_LIMIT_MARGIN_BPS_BY_CHAIN[chainId] ?? DEFAULT_GAS_LIMIT_MARGIN_BPS return (estimatedGas * margin + 9_999n) / 10_000n } ``` ### Warn on manual gas-limit overspend ```ts theme={null} const CHAINS_CHARGING_GAS_LIMIT = new Set([143, 10143]) // Warn only on egregious overrides — not normal 1.5–2x safety buffers. const OVERSPEND_WARNING_MULTIPLIER = 10n export const shouldWarnGasLimitOverspend = ({ chainId, gasLimit, recommendedGasLimit, }: { chainId: number gasLimit: bigint recommendedGasLimit: bigint }) => { if (!CHAINS_CHARGING_GAS_LIMIT.has(chainId)) return false if (recommendedGasLimit <= 0n || gasLimit < 21_000n) return false return gasLimit > recommendedGasLimit * OVERSPEND_WARNING_MULTIPLIER } ``` Show this inline and require explicit acknowledgement before signing. Reset the acknowledgement when the user changes the gas limit. ### Wait for receipt and finality The manual loop below works with standard RPC. If your RPC supports it, `eth_sendRawTransactionSync` is the shorter path. ```ts theme={null} const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) const hexToBigInt = (hex: string) => BigInt(hex) export const waitForReceipt = async (provider: EIP1193Provider, txHash: string) => { while (true) { // A receipt means the transaction has executed locally on this RPC node. const receipt = await provider.request({ method: "eth_getTransactionReceipt", params: [txHash], }) if (receipt) return receipt await sleep(400) } } export const waitUntilFinalized = async (provider: EIP1193Provider, receiptBlockNumber: string) => { while (true) { // Compare the receipt's block with the node's finalized commitment level. const finalizedBlock = await provider.request({ method: "eth_getBlockByNumber", params: ["finalized", false], }) if (hexToBigInt(finalizedBlock.number) >= hexToBigInt(receiptBlockNumber)) return await sleep(400) } } ``` Use receipts for ordinary status. Wait for finality before crediting bridges, deposits, or irreversible off-chain settlement. ## Learning resources <CardGroup> <Card title="Gas Pricing" href="/developer-essentials/gas-pricing"> How Monad charges gas and how EIP-1559 works on Monad </Card> <Card title="JSON-RPC Overview" href="/reference/json-rpc/overview"> RPC differences, block tags, WebSockets, limits, and errors </Card> <Card title="Reserve Balance" href="/developer-essentials/reserve-balance"> When accounts can spend below the 10 MON reserve </Card> <Card title="EIP-7702 on Monad" href="/developer-essentials/eip-7702"> Delegated EOA behavior and Monad-specific restrictions </Card> <Card title="Historical Data" href="/developer-essentials/historical-data"> Current-state and historical-state availability </Card> </CardGroup> # Advanced topics Source: https://docs.monad.xyz/execution-events/advanced ## When are events published? Execution events are recorded roughly "as they are happening" inside the execution daemon: you see a `BLOCK_START` event at roughly the same moment that the execution daemon beings processing a new block, followed by the start of the first transaction (a `TXN_HEADER_START` event) about 1 millisecond later. Most transaction-related events are recorded less than one microsecond after the transaction they describe has completed. Execution of a typical transaction will emit a few dozen events, but large transactions can emit hundreds of events. The `TXN_EVM_OUTPUT` event -- which is recorded as soon as the transaction is finished -- provides a summary accounting of how many more events related to that transaction will follow (how many logs, how many call frames, etc.), so that memory to store the subsequent event data can be preallocated. For example in Rust, [`Vec::reserve`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve) is often called here. An event like `TXN_EVM_OUTPUT` is referred as a "header event" in the documentation: it is an event whose content describes some summary information and the number of subsequent, related events that will be recorded later with more details. All these events are recorded as soon as the transaction is "committed" to the currently-executing block. This happens before the block has finished executing, and should not be confused with the unrelated notion of "commitment" in the consensus algorithm. Although there are complex speculative execution optimizations inside the execution daemon, the recording of a transaction takes place when all work on a particular transaction has finished. This is referred to as "transaction commit" time. This is a different than the block-at-a-time style update you would see in, for example, the Geth real-time events WebSocket protocol (which our RPC server also [supports](/reference/websockets)). Certain properties of the block (its hash, its state root, etc.) are not known at the time you see a transaction's events, because the rest of the block is still executing. If you would like block-at-a-time updates, the Rust SDK contains [some utilities](/execution-events/rust-api#block-level-utilities) which will aggregate the events back into complete, block-oriented updates. One thing to be careful of: although transactions are always committed to a block in index order, they might be recorded out of order. That is, you must assume that the set of execution events that make up transactions 2 and 3 could be "mixed together" in any order. This is because of optimizations in the event recording code path. However, *for a particular transaction* (e.g., transaction 3) events pertaining to that transaction are always recorded in the same order: first all of the logs, then all the call frames, then all the state access records. Each of these is recorded in *index order*, i.e., log 2 is always recorded before log 3. Consider the following diagram: ``` ╔═Events═════════════════════════════╗ ║ ║ ║ ┌───────────────────────────────┐ ║ ║ │ event type: TXN_EVM_OUTPUT │ ║ ║ │ transaction: 1 │ ║ ║ │ log count: 2 │ ║ ║ └───────────────────────────────┘ ║ ║ ║ ║ ┌───────────────────────────────┐ ║ ║ │ event type: TXN_LOG │ ║ ║ │ transaction: 1 │ ║ ║ │ log index: 0 │ ║ ║ │ <log details> │ ║ ║ └───────────────────────────────┘ ║ ║ ║ ║ ┌───────────────────────────────┐ ║ ║ │ event type: TXN_EVM_OUTPUT │ ║ ║ │ transaction: 0 │ ║ ║ │ log count: 3 │ ║ ║ └───────────────────────────────┘ ║ ║ ║ ║ ┌───────────────────────────────┐ ║ ║ │ event type: TXN_LOG │ ║ ║ │ transaction: 0 │ ║ ║ │ log index: 0 │ ║ ║ │ <log details> │ ║ ║ └───────────────────────────────┘ ║ ║ ║ ║ ┌───────────────────────────────┐ ║ ║ │ event type: TXN_LOG │ ║ ║ │ transaction: 0 │ ║ ║ │ log index: 1 │ ║ ║ │ <log details> │ ║ ║ └───────────────────────────────┘ ║ ║ ║ ║ ┌───────────────────────────────┐ ║ ║ │ event type: TXN_LOG │ ║ ║ │ transaction: 1 │ ║ ║ │ log index: 1 │ ║ ║ │ <log details> │ ║ ║ └───────────────────────────────┘ ║ ║ ║ ║ ┌───────────────────────────────┐ ║ ║ │ event type: TXN_LOG │ ║ ║ │ transaction: 0 │ ║ ║ │ log index: 2 │ ║ ║ │ <log details> │ ║ ║ └───────────────────────────────┘ ║ ║ ║ ╚════════════════════════════════════╝ ``` A few things to note here: * Unlike most diagrams in the documentation, the events are shown in a simplified, "merged" form; in real events, some of this information is stored in the event descriptor and some is stored in the event payload, but they're combined to make the diagram simpler * It shows two transactions, with transaction indices 0 and 1. Although transaction 0 completes first in the EVM, its `TXN_EVM_OUTPUT` event is recorded *after* than the `TXN_EVM_OUTPUT` of transaction 1 * Events from the transactions are interleaved: sometimes the next one relates to transaction 0, sometimes to transaction 1, and there is no meaningful order between them * Despite the transactions being out-of-order with respect to each other, all the events associated with a particular transaction are always in relative order, i.e., the log indicies for a particular transaction will always be seen in `log_index` order, as above This is easy to understand if you imagine all of a transaction's events being recorded by a different thread. For a particular transaction, its thread always records that transaction's events in order, but the "transaction threads" themselves race against each other, recording in a non-deterministic order. This is similar to what really happens, except the transactions are recorded on [fibers](https://en.wikipedia.org/wiki/Fiber_\(computer_science\)) rather than full threads. ## Sequence numbers and the lifetime detection algorithm All event descriptors are tagged with an incrementing sequence number starting at 1. Sequence numbers are 64-bit unsigned integers which do not repeat unless the execution daemon is restarted. Zero is not valid sequence number. Also note that the sequence number modulo the descriptor array size equals the array index where the *next* event descriptor will be located. This is shown below with a concrete example where the descriptor array size is 64. Note that the last valid index in the array is 63, then access wraps around to the beginning of the array at index 0. ``` ◇ │ ╔═...═════════════════════════Event descriptor array═══╬═══════════════════...═╗ ║ │ ║ ║ ┌─Event────────┐┌─Event────────┐┌─Event────────┐ │ ┌─Event─────────┐ ║ ║ │ ││ ││ │ │ │ │ ║ ║ │ seqnum = 318 ││ seqnum = 319 ││ seqnum = 320 │ │ │ seqnum = 256 │ ║ ║ │ ││ ││ │ │ │ │ ║ ║ └──────────────┘└──▲───────────┘└──────────────┘ │ └───────────────┘ ║ ║ 61 │ 62 63 │ 0 ║ ╚═...════════════════════╬═════════════════════════════╬═══════════════════...═╝ │ │ ■ ◇ Next event Ring buffer wrap-around to ┌──────────────────────────────┐ zero is here │last read sequence number │ │(last_seqno) is initially 318 │ └──────────────────────────────┘ ``` In this example: * We keep track of the "last seen sequence number" (`last_seqno`) which has value `318` to start; being the "last" sequence number means we have already finished reading the event with this sequence number, which lives at array index `61` * `318 % 64` is `62`, so we will find the potential next event at that index *if* it has been produced * Observe that the sequence number of the item at index `62` is `319`, which is the last seen sequence number plus 1 (`319 == 318 + 1`). This means that event `319` has been produced, and its data can be safely read from that slot * When we're ready to advance to the next event, the last seen sequence number will be incremented to `319`. As before, we can find the *next* event (if it has been produced) at `319 % 64 == 63`. The event at this index bears the sequence number `320`, which is again the last seen sequence number + 1, therefore this event is also valid * When advancing a second time, we increment the last seen sequence number to `320`. This time, the event at index `320 % 64 == 0` is *not* `321`, but is a smaller number, `256`. This means the next event has not been written yet, and we are seeing an older event in the same slot. We've seen all of the currently available events, and will need to check again later once a new event is written * Alternatively we might have seen a much larger sequence number, like `384` (`320 + 64`). This would mean that we consumed events too slowly, so slowly that the 63 events in the range `[321, 384)` were produced in the meantime. These were subsequently overwritten, and are now lost. They can be replayed using services external to event ring API, but *within* the event ring API itself there is no way to recover them ## Lifetime of an event payload, zero copy vs. memcpy APIs Because of the descriptor overwrite behavior, an event descriptor might be overwritten by the execution daemon while a reader is still examining its data. To deal with this, the reader API makes a copy of the event descriptor. If it detects that the event descriptor changed during the copy operation, it reports a gap. Copying an event descriptor is fast, because it is only a single cache line in size. This is not the case for event payloads, which could potentially be very large. This means a `memcpy(3)` of an event payload could be expensive, and it would be advantageous to read the payload bytes directly from the payload buffer's shared memory segment: a "zero-copy" API. This exposes the user to the possibility that the event payload could be overwritten while still using it, so two solutions are provided: 1. A simple detection mechanism allows payload overwrite to be detected at any time: the writer keeps track of the minimum payload offset value (*before* modular arithmetic is applied) that is still valid. If the offset value in the event descriptor is smaller than this, it is no longer safe to read the event payload 2. A payload `memcpy`-style API is also provided. This uses the detection mechanism above in the following way: first, the payload is copied to a user-provided buffer. Before returning, it checks if the lifetime remained valid after the copy finished. If so, then an overwrite did not occur during the copy, so the copy must be valid. Otherwise, the copy is invalid The reason to prefer the zero-copy APIs is that they do less work. The reason to prefer memcpy APIs is that it is not always easy (or possible) to "undo" the work you did if you find out later that the event payload was corrupted by an overwrite while you were working with it. The most logical thing to do in that case is start by copying the data to stable location, and if the copy isn't valid, to never start the operation. An example user of the zero-copy API is the `eventwatch` example C program, which can turn events into printed strings that are sent to `stdout`. The expensive work of formatting a hexdump of the event payload is performed using the original payload memory. If an overwrite happened during the string formatting, the hexdump output buffer will be wrong, but that is OK: it will not be sent to `stdout` until the end. Once formatting is complete, `eventwatch` checks if the payload expired and if so, writes an error to `stderr` instead of writing the formatted buffer to `stdout`. Whether you should copy or not depends on the characteristics of the reader, namely how easily it can deal with "aborting" processing. ## Location of event ring files For performance reasons, we prefer that event ring files be created on a [hugetlbfs](https://www.kernel.org/doc/html/v4.18/admin-guide/mm/hugetlbpage.html#hugetlbpage) in-memory filesystem. Files created on such a filesystem will be backed by physically-contiguous large pages, which improves performance by about 15% in internal benchmarks. This can be a hassle though: it is unusual for a program to require that a file be placed on a *particular kind* of filesystem, and this requirement adds some overhead. In practice, this means additional configuration steps that a system administrator must perform when setting up a Monad node, and some additional concepts that SDK users must learn about. The issues are: 1. A hugetlbfs filesystem must be mounted somewhere on the host; usually by default (e.g., on a Ubuntu default installation) there will not be a hugetlbfs filesystem already present 2. Whomever configures a hugetlbfs filesystem must make sure that any user that needs to open the event ring file has the appropriate permissions 3. The path to the event ring file (which will be somewhere on that filesystem) must be passed into all programs that need to open it; since we don't know where the administrator will mount the filesystem, we can't easily hard-code a location for it in either the documentation or the source code To simplify the developer experience as much as possible, we follow three conventions. Each convention adds more "convenience default behavior" so that everything will "just work" for most users, but you are free to ignore any of the conventions and do things in your own way. <Note title="hugetlbfs is not required"> The event ring library does not require a hugetlbfs filesystem: it can work with *any* kind of regular file. The C function that maps
프로젝트로 돌아가기