bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 59쪽
ta = await response.json();
console.log(JSON.stringify(data, null, 2));
return { isValid: data.isValid, payload: requestBody };
}
```
### POST `/settle`
Execute the payment on-chain. Facilitator pays gas.
```ts theme={null}
interface NetworkConfig {
chainId: Network;
name: string;
rpcUrl: string;
explorerUrl: string;
usdcAddress: `0x${string}`;
usdcDecimals: number;
chainIdNumber: number;
}
/** POST /settle - Execute the payment on-chain. Facilitator pays gas. */
async function testSettle(
payload: any,
networkConfig: NetworkConfig
): Promise<void> {
console.log("\n--- POST /settle ---");
const response = await fetch(`${FACILITATOR_URL}/settle`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const data = await response.json();
console.log(JSON.stringify(data, null, 2));
if (data.success && data.transaction) {
// Transaction success
} else if (data.errorReason) {
console.log(`Failed: ${data.errorReason}`);
}
}
```
## What's Next?
You've successfully built an x402 payment-enabled app on Monad! Here are some ideas to extend your implementation:
* **Add more payable endpoints** - Create different pricing tiers for various content or API calls
* **Build AI agent integrations** - Enable autonomous agents to pay for and access your APIs
## Resources
* [x402 Protocol Specification](https://www.x402.org/)
* [Monad Developer Discord](https://discord.gg/monaddev)
* [Migration Guide: V1 to V2](https://docs.x402.org/guides/migration-v1-to-v2)
## Need Help?
If you run into issues or have questions, join the [Monad Developer Discord](https://discord.gg/monaddev)
Happy building!
# Asynchronous I/O
Source: https://docs.monad.xyz/monad-arch/concepts/asynchronous-io
*Asynchronous I/O* is a form of input/output processing that allows the CPU to continue executing concurrently while communication is in progress.
Disk and network are orders of magnitude slower than the CPU. Rather than initiating an I/O operation and waiting for the result, the CPU can initiate the I/O operation as soon as it's known that the data will be needed, and continue executing other instructions which do not depend on the result of the I/O operation.
Some rough comparisons for illustration purposes:
<div>
<table>
<thead>
<tr>
<th>Device</th>
<th>Latency</th>
<th>Bandwidth</th>
</tr>
</thead>
<tbody>
<tr>
<td>CPU L3 Cache</td>
<td>10 ns</td>
<td>>400 GB/s</td>
</tr>
<tr>
<td>Memory</td>
<td>100 ns</td>
<td>100 GB/s</td>
</tr>
<tr>
<td>Disk (NVMe SSD)</td>
<td>400 us</td>
<td>380 MB/s</td>
</tr>
<tr>
<td>Network</td>
<td>50 - 200 ms</td>
<td>1 Gb/s (125 MB/s)</td>
</tr>
</tbody>
</table>
</div>
(actual disk stats as reported by fio for random reads of size 2KB - \~190k IOPS)
Fortunately, SSD drives can perform operations concurrently, so the CPU can initiate several requests at the same time, continue executing, and then receive the results of multiple operations around the same time.
Some databases (such as lmdb / mdbx) use memory-mapped storage to read and write to disk. Unfortunately, memory-mapped storage is implemented by the kernel (mmap) and is not asynchronous, so execution is blocked while waiting for the operation to complete.
More about asynchronous I/O can be read [here](https://en.wikipedia.org/wiki/Asynchronous_I/O).
# Concepts
Source: https://docs.monad.xyz/monad-arch/concepts/index
Key concepts that underpin Monad's architecture.
<CardGroup>
<Card title="Asynchronous I/O" href="/monad-arch/concepts/asynchronous-io">
How Monad uses async I/O to keep the CPU productive while communication is in progress
</Card>
<Card title="Pipelining" href="/monad-arch/concepts/pipelining">
Dividing tasks into smaller stages that can be processed in parallel
</Card>
</CardGroup>
# Pipelining
Source: https://docs.monad.xyz/monad-arch/concepts/pipelining
*Pipelining* is a technique for implementing parallelism by dividing tasks into a series of smaller tasks which can be processed in parallel.
Pipelining is used in computer processors to increase the throughput of executing a series of instructions sequentially at the same clock rate. (There are other techniques used in processors to increase throughput as well.) More about instruction-level parallelism (ILP) can be read [here](https://en.wikipedia.org/wiki/Instruction_pipelining).
A simple example of pipelining:
<img alt="Pipelining, Laundry Day" />
<p>Pipelining laundry day. Top: Naive; Bottom: Pipelined. Credit: <a href="https://www.cs.fsu.edu/~hawkes/cda3101lects/chap6/index.html?$$$F6.1.html$$$">Prof. Lois Hawkes, FSU</a></p>
When doing four loads of laundry, the naive strategy is to wash, dry, fold, and store the first load of laundry before starting on the second one. The pipelined strategy is to start washing load 2 when load 1 goes into the dryer. Pipelining gets work done more efficiently by utilizing multiple resources simultaneously.
# Asynchronous Execution
Source: https://docs.monad.xyz/monad-arch/consensus/asynchronous-execution
Pipelined consensus-execution staging
## Summary
Asynchronous Execution is a technique that allows Monad to substantially increase execution throughput by decoupling consensus from execution.
Decoupling consensus from execution allows Monad to substantially increase the execution budget, since execution goes from occupying a small fraction of the block time to occupying the full block time.
## Background: interleaved execution is inefficient
Consensus is the process where nodes come to agreement about the official ordering of transactions. Execution is the process of actually executing those transactions and updating the state.
In Ethereum and most other blockchains, execution is a prerequisite to consensus. When nodes come to consensus on a block, they are agreeing on both (1) the list of transactions in the block, and (2) the merkle root summarizing all of the state after executing that list of transactions. As a result, the leader must execute all of the transactions in the proposed block *before* sharing the proposal, and the validating nodes must execute those transactions *before* responding with a vote.
We refer to this style of blockchain as one that has execution **interleaved** with consensus. In this paradigm, the time budget for execution is extremely limited, since it has to happen twice *and* leave enough time for multiple rounds of cross-globe communication for consensus.
Additionally, since execution will block consensus, the per-block gas limit must be chosen extremely conservatively to ensure that the computation completes on all nodes within the budget even in the worst-case scenario.
The result is that the per-block gas limit is a tiny fraction of the block time. In particular, in Ethereum, the gas limit (30M worst-case gas) corresponds to a roughly 100ms time budget, even though the the block time is 12 seconds:
<img />
<p>Comparing Ethereum execution budget to block time</p>
That's 1% of the block time! In short, interleaving consensus and execution has a massive time-shrinking effect.
What if it didn't have to be this way?
## Asynchronous Execution
Monad decouples consensus from execution, moving execution out of the hot path of consensus into a separate, slightly-lagged swim lane.
**In Monad, nodes come to consensus (i.e. agreement about the official ordering of transactions), without ever executing those transactions.**
That is, the leader proposes an ordering without knowing the resultant state root, and the validating nodes vote on block validity without knowing (for example) whether all of the transactions in the block execute without reverting.
When a block is finalized, every node in the network (validators and full nodes) can execute the block's transactions to produce the latest, agreed-upon state.
As a result of this change, execution can be budgeted the full block time. To see why, consider the somewhat stylized diagrams, in which blue rectangles correspond to execution, and orange rectangles correspond to consensus:
**Interleaved execution**
In interleaved execution, the sum of the execution and consensus budgets equals the block time, and consensus occupies most of the block time.
<img />
<p>Interleaved execution</p>
**Asynchronous execution**
In asynchronous execution, consensus occupies the full block time - and so does execution, because they are occurring in separate swim lanes, *at the same time*:
<img />
<p>Asynchronous execution</p>
**Comparison**
Comparing the two styles side by side, you can see the benefit of the asynchronous style: the execution budget can be significantly expanded to occupy the full block time:
<img />
<p>Top: interleaved; bottom: asynchronous.</p>
## Determined ordering implies state determinism
Although execution lags consensus, the true state of the world is determined as soon as the ordering is determined. Execution is required to unveil the truth, but the truth is already determined.
It's worth noting that in Monad, like in Ethereum, it is fine for transactions in a block to "fail" in the sense that the intuitive outcome did not succeed.(For example, there could be a transaction included in a block in which Bob tries to send 10 tokens to Alice but only has 1 token in his account. The transfer 'fails' but the transaction is still valid.
The outcome of any transaction, including failure, is deterministic.
<img />
<p>Example of transaction determinism even when some transactions fail</p>
## Finer details
### Delayed Merkle Root
As mentioned above, Monad block proposals don't include the merkle root of the state trie, since that would require execution to have already completed.
All nodes should stay in sync because they're all doing the same work. But it'd be nice to be sure! As a precaution, proposals also includes a merkle root from `D` blocks ago, allowing nodes to detect if they're diverging. `D` is a systemwide parameter (currently set in testnet and mainnet to `3`).
Delayed merkle root validity is part of block validity, so if the leader proposes a block but the delayed merkle root is wrong, the block will be rejected.
As a result of this delayed merkle root:
1. After the network comes to consensus (2/3 majority vote) on block `N` (typically upon receiving block `N+2`, which contains a QC-on-QC for block `N`), it means that the network has agreed that the official consequence of block `N-D` is a state rooted in merkle root `M`. Light clients can then query full nodes for merkle proofs of state variable values at block `N-D`.
2. Any node with an error in execution at block `N-D` will fall out of consensus starting at block `N`. This will trigger a rollback on that node to the end state of block `N-D-1`, followed by re-execution of the transactions in block `N-D` (hopefully resulting in the merkle root matching), followed by re-execution of the transactions in block `N-D+1`, `N-D+2`, etc.
Ethereum's approach uses consensus to enforce *state machine replication* in a very strict way: after nodes come to consensus, we know that the supermajority agrees about the official ordering and the state resulting from that ordering. However, this strictness comes at great cost because interleaved execution limits execution throughput. Asynchronous execution achieves state machine replication without this limitation, and the delayed merkle root serves an additional precaution.
<img />
<p>Delayed merkle root</p>
### Reserve balance
Because consensus can only be assumed to have up to the `D`-block delayed view of the global
state, it is necessary to adjust the consensus and execution rules slightly to allow consensus to
safely build blocks that include only transactions whose gas costs can be paid for.
Monad introduces the [Reserve Balance](/developer-essentials/reserve-balance) rules to
ensure this. The rules place light restrictions on when transactions can be
included at consensus time, and imposes some conditions under which transactions will
revert at execution time.
### Speculative execution
In MonadBFT, nodes receive a proposed block `N` at slot `N`, but it is not finalized until slot `N+2`. During the intervening time, a node can still locally execute the proposed block (without the guarantee that it will become voted or finalized). This allows a few nice properties:
1. In the likely event that the proposed block is finalized, the validator node has already done the work and can immediately update its merkle root pointer to the result.
2. Transactions can be simulated (in `eth_call` or `eth_estimateGas`) against the speculative state which is likely more up-to-date.
### Transactions from newly-funded accounts
Because consensus runs slightly ahead of execution, newly-funded accounts which previously had zero balance cannot send transactions until the transfer that credits them with tokens is `D` blocks old.
In practice, this means that if you send tokens from account `A` into an account `B` (which has 0 balance), then you should wait until seeing the transaction receipt (indicative that that block has reached [`Proposed`](/monad-arch/consensus/block-states#proposed) state), and then wait another 1.2 seconds.
Alternatively, depending on the nature of intended transaction from `B`, it may be possible to write a smart contract callable by `A` which combines the funding operation and whatever `B` was intending to do, requiring no delay between funding and spending.
## Block states
See [block states](/monad-arch/consensus/block-states) for a summary of the states through which each block progresses.
# Message Authentication
Source: https://docs.monad.xyz/monad-arch/consensus/authentication
## BLS Multi-Signatures
Certificates (QCs and TCs) can be naively implemented as a vector of ECDSA signatures on the secp256k1 curve. These certificates are explicit and easy to construct and verify. However, the size of the certificate is linear with the number of signers. It poses a limit to scaling because the certificate is included in almost every consensus message, except vote message.
Pairing-based BLS signature on the BLS12-381 curve helps with solving the scaling issue. The signatures can be incrementally aggregated into one signature. Verifying the single valid aggregated signature provides proof that the stakes associated with the public keys have all signed on the message.
BLS signature is much slower than ECDSA signature. So for performance reasons, Monad's implementation of MonadBFT adopts a blended signature scheme where BLS signatures are only used on aggregatable message types (votes and timeouts). Message integrity and authenticity is still provided by ECDSA signatures.
# Block States
Source: https://docs.monad.xyz/monad-arch/consensus/block-states
Block lifecycle
In [MonadBFT](/monad-arch/consensus/monad-bft), a block progresses through [three states](/monad-arch/consensus/monad-bft#block-states-due-to-monadbft).
Additionally, due to [asynchronous execution](/monad-arch/consensus/asynchronous-execution), block finalization is a
separate (earlier) matter from state root verification. As a result of this architecture, each
Monad block can be considered to be in one of four states.
Note that a block's state is from the perspective of a particular observer (any other validator or
full node). As new messages arrive, they allow that observer to progress the block's state locally.
Although the states are defined locally, they correspond to assurance that the rest of the network
will ultimately converge on an outcome consistent with that state.
For example, if a node marks a block as `Finalized`, it is because that node has received a message
carrying sufficient proof that the rest of the network will ultimately converge on enshrining that
block at that block height.
## States
A Monad block is in one of the four states:
1. `Proposed`
2. `Voted`
3. `Finalized`
4. `Verified`
<img />
<p>Classification of historical blocks based on the latest <strong>proposed</strong> block N.</p>
### Proposed
The block has been proposed by a leader but has not been voted upon.
Note: if execution is not lagging behind consensus, a node may
[speculatively execute](/monad-arch/consensus/asynchronous-execution#speculative-execution) the proposed block.
### Voted
We have a [Quorum Certificate (QC)](/monad-arch/consensus/monad-bft#quorum-certificate-qc) in hand for the block,
indicating that it has been voted affirmatively for by a supermajority of validators. (Typically,
this is due to receiving a child block for this block.)
In MonadBFT, `Voted` means the block can be
[speculatively finalized](/monad-arch/consensus/monad-bft#speculative-finality).
### Finalized
We have a QC-squared in hand for the block (that is, we have a
[QC](/monad-arch/consensus/monad-bft#quorum-certificate-qc) for a block that contains a QC on the original block).
This serves as proof that a supermajority of validators have ratified the existence and validity
of a QC on the original block.
Due to the consensus rules of MonadBFT, this means that the block is finalized.
### Verified
A block containing the [delayed merkle root](/monad-arch/consensus/asynchronous-execution#delayed-merkle-root)
has been finalized, meaning that the execution outputs of the block has been agreed upon by a
supermajority of validator nodes.
Concretely, the latest verified block will be the
`latest_finalized_block - execution_delay`.
## Mapping to JSON-RPC commitment levels
Monad uses a different consensus algorithm than Ethereum, but is API compatible with the
[JSON-RPC](/reference/json-rpc/overview) programming interface defined by the
[Geth client](https://geth.ethereum.org/docs/interacting-with-geth/rpc).
Geth communicates consensus information about blocks publicly over JSON-RPC using the tags
`"latest"`, `"safe"`, and `"finalized"`. Here is how they map to Monad's block states:
| Geth RPC state | ...corresponds to Monad block state | Why? |
| - | - | - |
| `"latest"` | `Proposed` | Both states refer to the most recently observed block, before consensus finalizes the result |
| `"safe"` | `Voted` | In Ethereum's LMD-GHOST algorithm, "safe" means something like "extremely unlikely to be reverted, but still theoretically possible"; Monad's voted has a similar meaning |
| `"finalized"` | `Finalized` | This has the same meaning on both chains: not revertible without a hard fork |
<Note>
Geth recognizes two other block tags, `"earliest"` and `"pending"`. These are not consensus
states. The former is a synonym for the genesis block, and the latter does not make sense given
how Monad's [transaction propagation mechanism](/monad-arch/consensus/local-mempool) is
different.
</Note>
## Real-time data and block states
Monad offers several [sources of real-time blockchain data](/monad-arch/realtime-data/data-sources).
To provide the fastest service possible, some data feeds report blockchain data for the latest
block your node knows about, as soon as it learns about it.
As you can see above, the *latest* block your node is aware of -- the most recent block in the
`Proposed` state -- may be *speculatively executed*. Thus, you may see data about blocks that do
not ultimately become part of the Monad blockchain, although this is very rare.
[This page](/monad-arch/realtime-data/spec-realtime) gives an in-depth overview of how the
block state progression works, in case you want to consume real-time data and wish to understand
how speculative execution and real-time data reporting fit together.
To see an explicit example of how this relates to a real data feed, see the
[WebSocket subscriptions](/reference/json-rpc/overview#websocket-subscriptions) section about
[`monadNewHeads`](/reference/json-rpc/overview#speculative-subscription-behavior), an extension to the
[Geth `newHeads` data feed](https://geth.ethereum.org/docs/interacting-with-geth/rpc/pubsub) that
incl프로젝트로 돌아가기