Monad 백서

Monad

원문

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

block range limits low. ## Errors Monad's JSON-RPC error codes aim to be equivalent to Ethereum's, but some codes deviate due to lack of standardization across Ethereum clients. ### Request-level errors (-32601) | Message | Explanation | Common cause | | - | - | - | | Parse error | Unable to parse the JSON-RPC request | Malformed JSON | | Invalid request | The request is structurally invalid | Request exceeds size limit | | Method not found | The method is not part of the JSON-RPC spec | Typo in method name | | Method not supported | The method exists in the spec but is not yet supported by Monad | Calling an unimplemented method | ### Parameter errors (-32602) | Message | Explanation | Common cause | | - | - | - | | Invalid block range | The requested `eth_getLogs` block range exceeds the provider limit | See [block range limits](#block-range-limit-per-call) | | Invalid params | Incorrect parameters for the method | Wrong types, missing required fields, omitted trace options | ### Execution errors (-32603) | Message | Explanation | Common cause | | - | - | - | | Internal error | The request could not be fulfilled | Server-side failure | | Execution reverted | The simulated transaction reverted | Failed `eth_call` or `eth_estimateGas` | | Transaction decoding error | The raw transaction could not be decoded | Invalid RLP in `eth_sendRawTransaction` | ## WebSocket subscriptions Monad's RPC server supports JSON-RPC over WebSocket connections, enabling persistent connections and real-time data via `eth_subscribe`. See the [Geth documentation](https://geth.ethereum.org/docs/interacting-with-geth/rpc/pubsub) for general `eth_subscribe` behavior. Monad extends the standard subscription types with two variants (`monadNewHeads` and `monadLogs`) that include additional data for tracking a block's progression through consensus. See [Speculative Real-Time Data](/monad-arch/realtime-data/spec-realtime) for background on speculative execution and [Block States](/monad-arch/consensus/block-states) for the full block lifecycle. ### Subscription types | Type | Fires when | | - | - | | `newHeads` | A header is emitted when a block is `Proposed` and [speculatively executed](/monad-arch/realtime-data/spec-realtime) | | `logs` | Logs matching the provided filter are emitted when a block is `Proposed` and [speculatively executed](/monad-arch/realtime-data/spec-realtime) | | `monadNewHeads` | The same proposed-block event as `newHeads`, plus subsequent commitment-state updates including `commitState` | | `monadLogs` | The same proposed-block logs as `logs`, plus subsequent commitment-state updates for matching logs including `commitState` | The subscription types `syncing` and `newPendingTransactions` are not supported. ### Speculative subscription behavior `monadNewHeads` and `monadLogs` updates include two additional fields not present in the standard variants: * **`blockId`** — a unique identifier for this specific block proposal (distinct from block number, since multiple proposals can exist for the same height). * **`commitState`** — the block's current [commit state](/monad-arch/consensus/block-states): `Proposed`, `Voted`, `Finalized`, or `Verified`. The same block will typically produce multiple updates as its `commitState` advances through the lifecycle. A block may skip `Voted` and go directly from `Proposed` to `Finalized` when consensus is ahead of execution. When a block fails to finalize, it is abandoned implicitly — the finalization of a different block at the same height supersedes it, but no explicit abandonment event is published. # JSON-RPC Playground Source: https://docs.monad.xyz/reference/json-rpc/playground Interactive JSON-RPC request builder for all Monad RPC methods <RpcForm /> # MPP API Reference Source: https://docs.monad.xyz/reference/mpp/api Reference for the @monad-crypto/mpp package This page is a technical reference for `@monad-crypto/mpp`. For a developer-oriented guide with examples, visit the [overview](/reference/mpp/overview). ## Server ### Example ```ts title="server.ts" highlight={9-13} theme={null} import { monad } from "@monad-crypto/mpp/server"; import { Mppx } from "mppx"; import { privateKeyToAccount } from "viem/accounts"; const account = privateKeyToAccount(process.env.SERVER_PRIVATE_KEY as `0x${string}`); const mppx = Mppx.create({ methods: [ monad({ account, recipient: account.address, // ... parameters below }), ], }); ``` ### Parameters The `monad` server payment method accepts the following parameters. | Parameter | Type | Default | Description | | - | - | - | - | | `amount` | `string` | — | Default payment amount, human-readable (e.g. `"1.50"`) | | `currency` | `string` | USDC | ERC-20 token contract address | | `decimals` | `number` | `6` | Token decimals | | `description` | `string` | — | Human-readable description | | `externalId` | `string` | — | External identifier to echo back in receipt | | `recipient` | `string` | — | Recipient address for payments | | `testnet` | `boolean` | `false` | Testnet mode | | `waitForConfirmation` | `boolean` | `true` | Whether to wait for the charge transaction to confirm on-chain | | `getClient` | `(params: { chainId?: number }) => Client` | — | Function that returns a viem Client for the given chain ID | | `account` | `Account \| Address` | — | Server account used to broadcast `receiveWithAuthorization` transactions. Required when accepting `authorization` payloads. The server pays gas from this account. | | `store` | `Store` | — | Store for transaction hash replay protection. Use a shared store in multi-instance deployments so consumed hashes are visible across all server instances. | ## Client ### Example ```ts title="client.ts" highlight={8-11} theme={null} import { monad } from "@monad-crypto/mpp/client"; import { Mppx } from "mppx/client"; import { privateKeyToAccount } from "viem/accounts"; const account = privateKeyToAccount(process.env.CLIENT_PRIVATE_KEY as `0x${string}`); const mppx = Mppx.create({ methods: [monad({ account, // ... parameters below })], }); // Make a paid request const response = await fetch("http://localhost:3000/premium"); const data = await response.json(); console.log(data); ``` ### Parameters The `monad` client payment method accepts the following parameters. | Parameter | Type | Default | Description | | - | - | - | - | | `account` | `Account \| Address` | — | Wallet account. If omitted, resolved from the viem Client. | | `mode` | `"push" \| "pull"` | Auto | Payment mode. Defaults to `"push"` for JSON-RPC accounts, `"pull"` for local accounts. | | `getClient` | `(params: { chainId?: number }) => Client` | — | Custom viem Client resolver. Uses built-in RPC URLs if not provided. | # MPP Overview Source: https://docs.monad.xyz/reference/mpp/overview Send and accept payments on Monad using the Machine Payments Protocol The [`@monad-crypto/mpp`](https://www.npmjs.com/package/@monad-crypto/mpp) package implements Monad payments for the [Machine Payments Protocol](https://mpp.dev) (MPP). It enables one-time payment processing through ERC-20 token transfers on Monad. This guide covers the Monad-specific `@monad-crypto/mpp` package. For general MPP concepts, see the [MPPX documentation](https://mpp.sh/docs). ## Installation Install the package and its peer dependencies: <Tabs> <Tab title="npm"> ```bash theme={null} npm install @monad-crypto/mpp mppx viem ``` </Tab> <Tab title="pnpm"> ```bash theme={null} pnpm add @monad-crypto/mpp mppx viem ``` </Tab> <Tab title="yarn"> ```bash theme={null} yarn add @monad-crypto/mpp mppx viem ``` </Tab> <Tab title="bun"> ```bash theme={null} bun add @monad-crypto/mpp mppx viem ``` </Tab> </Tabs> ## Server The server defines what payment is required and verifies credentials submitted by clients. Import `monad` from the server entrypoint and pass it to `Mppx.create`. ```ts title="server.ts" theme={null} import { monad } from "@monad-crypto/mpp/server"; import { Mppx } from "mppx"; import { privateKeyToAccount } from "viem/accounts"; const account = privateKeyToAccount(process.env.SERVER_PRIVATE_KEY as `0x${string}`); const mppx = Mppx.create({ methods: [ monad({ account, recipient: account.address, }), ], }); ``` ### Gate an endpoint Use `mppx.charge()` as middleware to require payment before serving a response. ```ts title="server.ts" theme={null} import { Hono } from "hono"; const app = new Hono(); app.get("/premium", mppx.charge(), async (ctx) => { return ctx.json({ message: "Premium content" }); }); export default app; ``` When a client requests `/premium` without a valid payment credential, the server responds with a `402 Payment Required` status and a challenge describing the payment requirements. The client then submits a credential (transaction hash or signed authorization) to complete the payment. ### Testnet By default, the package connects to Monad mainnet (chain ID `143`). To use testnet, set `testnet: true`. ```ts theme={null} monad({ account, recipient: account.address, testnet: true, }) ``` ## Client The client handles wallet interactions and credential creation. Import `monad` from the client entrypoint. With a local private key, the client defaults to **pull mode** — it signs an ERC-3009 authorization without broadcasting a transaction. ```ts title="client.ts" theme={null} import { monad } from "@monad-crypto/mpp/client"; import { Mppx } from "mppx/client"; import { privateKeyToAccount } from "viem/accounts"; const account = privateKeyToAccount(process.env.CLIENT_PRIVATE_KEY as `0x${string}`); const mppx = Mppx.create({ methods: [monad({ account })], }); // Make a paid request const response = await fetch("http://localhost:3000/premium"); const data = await response.json(); console.log(data); ``` ### Push vs pull mode | | Push | Pull | | - | - | - | | **Who pays gas** | Client | Server | | **Transaction** | Client broadcasts ERC-20 `transfer` | Server calls `transferWithAuthorization` | | **Credential** | Transaction hash | Signed ERC-3009 authorization | | **Default for** | JSON-RPC accounts (browser wallets) | Local accounts (private keys) | | **Trade-off** | Client needs gas tokens | Server needs gas tokens | ### Overriding the mode Use the `mode` option to set the payment mode explicitly, regardless of account type. ```ts theme={null} monad({ account, mode: "push", // Always broadcast a transaction }) monad({ account, mode: "pull", // Always sign an authorization }) ``` ### Monkey patch The client `Mppx.create()` function [monkey patches](https://en.wikipedia.org/wiki/Monkey_patch) the Web `fetch` API to use the configured payment method whenever it receives a `402 Payment Required` HTTP response. You can also use `mppx.fetch` directly. ```ts title="client.ts" theme={null} import { monad } from "@monad-crypto/mpp/client"; import { Mppx } from "mppx/client"; import { privateKeyToAccount } from "viem/accounts"; const account = privateKeyToAccount(process.env.CLIENT_PRIVATE_KEY as `0x${string}`); const mppx = Mppx.create({ methods: [monad({ account })], polyfill: false, }); const response = await mppx.fetch("http://localhost:3000/premium"); const data = await response.json(); console.log(data); ``` ## Links * NPM package: [@monad-crypto/mpp](https://www.npmjs.com/package/@monad-crypto/mpp) * GitHub repository: [monad-crypto/monad-ts](https://github.com/monad-crypto/monad-ts) # Staking API Reference Source: https://docs.monad.xyz/reference/staking/api Reference for Monad's staking precompile This page is a technical reference for the staking precompile interface. For a developer-oriented guide to common workflows, visit the [overview](/reference/staking/overview). ## Address | Contract | Address | | - | - | | Staking Precompile | <CopyToClipboard>`0x0000000000000000000000000000000000001000`</CopyToClipboard> | ## Functions and selectors | State-modifying function | Selector | | - | - | | [`addValidator(bytes,bytes,bytes)`](#addvalidator) | `0xf145204c` | | [`delegate(uint64)`](#delegate) | `0x84994fec` | | [`undelegate(uint64,uint256,uint8)`](#undelegate) | `0x5cf41514` | | [`withdraw(uint64,uint8)`](#withdraw) | `0xaed2ee73` | | [`compound(uint64)`](#compound) | `0xb34fea67` | | [`claimRewards(uint64)`](#claimrewards) | `0xa76e2ca5` | | [`changeCommission(uint64,uint256)`](#changecommission) | `0x9bdcc3c8` | | [`externalReward(uint64)`](#externalreward) | `0xe4b3303b` | | View function | Selector | | - | - | | [`getValidator(uint64)`](#getvalidator) | `0x2b6d639a` | | [`getDelegator(uint64,address)`](#getdelegator) | `0x573c1ce0` | | [`getWithdrawalRequest(uint64,address,uint8)`](#getwithdrawalrequest) | `0x56fa2045` | | [`getConsensusValidatorSet(uint32)`](#get-validatorset) | `0xfb29b729` | | [`getSnapshotValidatorSet(uint32)`](#get-validatorset) | `0xde66a368` | | [`getExecutionValidatorSet(uint32)`](#get-validatorset) | `0x7cb074df` | | [`getDelegations(address,uint64)`](#getdelegations) | `0x4fd66050` | | [`getDelegators(uint64,address)`](#getdelegators) | `0xa0843a26` | | [`getEpoch()`](#getepoch) | `0x757991a8` | | [`getProposerValId()`](#getproposervalid) | `0xfbacb0be` | | Syscall function | Selector | | - | - | | [`syscallOnEpochChange(uint64)`](#syscallonepochchange) | `0x1d4e9f02` | | [`syscallReward(address)`](#syscallreward) | `0x791bdcf3` | | [`syscallSnapshot()`](#syscallsnapshot) | `0x157eeb21` | ## Constants | Constant | Meaning | Value | | - | - | - | | `BOUNDARY_BLOCK_PERIOD` | Blocks from boundary block to boundary block | 50,000 blocks | | `EPOCH_DELAY_ROUNDS` | Rounds between the boundary block and the start of each epoch | 5,000 rounds | | `WITHDRAWAL_DELAY` | Number of epochs before unstaked tokens can be withdrawn | 1 epoch | | `MIN_AUTH_ADDRESS_STAKE` | Min MON self-delegated by a validator for active set eligibility | 100,000 MON | | `ACTIVE_VALIDATOR_STAKE` | Min total MON staked with a validator for active set eligibility | 10,000,000 MON | | `ACTIVE_VALSET_SIZE` | Number of validators in the active set | 200 | | `REWARD` | MON reward per block | 18 MON | | `DUST_THRESHOLD` | Minimum amount per individual delegation | 1 gwei (1e9 wei) | | `MAX_COMMISSION` | Maximum commission rate | 100% (1e18) | | `ACCUMULATOR_DENOMINATOR` | Accumulator unit multiplier for accuracy | 1e36 | | `PAGINATED_RESULTS_SIZE` | Max results returned per paginated call | 100 | ## State-modifying functions ### addValidator Creates a validator with an associated delegator account and returns the resultant `validatorId`. **Function selector** ``` addValidator(bytes,bytes,bytes) : 0xf145204c ``` **Function signature** ```solidity theme={null} function addValidator( bytes calldata payload, bytes calldata signedSecpMessage, bytes calldata signedBlsMessage ) external payable returns (uint64 validatorId); ``` **Parameters** 1. `payload` - consists of the following fields, packed together in big endian (equivalent to `abi.encodePacked()` in Solidity): * `bytes secpPubkey` (unique SECP public key used for consensus) * `bytes blsPubkey` (unique BLS public key used for consensus) * `address authAddress` (address used for the validator's delegator account. This address has withdrawal authority for the validator's staked amount) * `uint256 amount` (amount the validator is self-staking. Must equal `msg.value`) * `uint256 commission` (commission charged to delegators multiplied by 1e18, e.g. `10% = 1e17`) 2. `signedSecpMessage` - SECP signature over payload 3. `signedBlsMessage` - BLS signature over payload **Gas cost** 505,125 **Behavior** The function starts by unpacking the payload to retrieve the `secpPubkey`, `blsPubkey`, `authAddress`, `amount`, and `commission`, then verifying that the `signedSecpMessage` and `signedBlsMessage` correspond to the payload signed by the corresponding SECP and BLS private keys. * The validator must provide both a unique BLS key and a unique SECP key. Submissions with any repeated public keys will revert. * Both signatures (`signedSecpMessage` and `signedBlsMessage`) must be valid and must sign over the `payload`. * Multiple validators may share the same `authAddress`. * `msg.value` must be equal or greater than `MIN_AUTH_ADDRESS_STAKE` or the call will revert. * If the `msg.value` is also equal or greater than `ACTIVE_VALIDATOR_STAKE` then the validator will become active in the future: * If `addValidator` was called before the boundary block, then in epoch `n+1`; * Otherwise it will become active in epoch `n+2`. <Accordion title="Pseudocode"> ```solidity theme={null} secp_pubkey, bls_pubkey, auth_address, amount, commission = payload assert amount == msg.value // increment validator id last_val_id = last_val_id + 1; // set uniqueness of keys secp_to_val_id[secp_eth_address] = last_val_id; bls_to_val_id[bls_eth_address] = last_val_id; // set validator info val_execution[last_val_id] = ValExecution{ uint256 stake = msg.value; uint256 commission = commission; bytes secp_pubkey = secp_pubkey; bytes bls_pubkey = bls_pubkey; uint256 address_flags = set_flags(); } // set authority delegator info delegator[last_val_id][input.auth_address] = DelInfo{ uint256 delta_stake = set_stake()[0]; uint256 next_delta_stake = set_stake()[1]; uint64 delta_epoch = set_stake()[2]; uint64 next_delta_epoch = set_stake()[3]; } // set delegator accumulator epoch_acc[last_val_id][getEpoch()] = Accumulator{ uint256 ref_count += 1; } // set flags set_flags(); // push validator id if (val_execution[last_val_id].stake() >= ACTIVE_VALIDATOR_STAKE and last_val_id not in execution_valset): execution_valset.push(last_val_id); return last_val_id; def set_flags(): if msg.value + val_execution[last_val_id].stake() >= ACTIVE_VALIDATOR_STAKE: return ValidatorFlagsOk; if msg.value + val_execution[last_val_id].stake() >= MIN_AUTH_ADDRESS_STAKE return ValidatorFlagsStakeTooLow; def set_stake(): if in_epoch_delay_rounds: delta_stake = 0; next_delta_stake = msg.value; delta_epoch = 0; next_delta_epoch = current_epoch + 2; else: delta_stake = msg.value; next_delta_stake = 0; delta_epoch = current_epoch + 1; next_delta_epoch = 0; return [delta_stake, next_delta_stake, delta_epoch, next_delta_epoch]; ``` </Accordion> **Usage** Here is an example of assembling the payload and signing: ``` def generate_add_validator_call_data_and_sign( secp_pubkey: bytes, bls_pubkey: bytes, auth_address: bytes, amount: int, commission: int secp_privkey: bytes bls_privkey: bytes ) -> bytes: # 1) Encode payload_parts = [ secp_pubkey, bls_pubkey, auth_address, toBigEndian32(amount), toBigEndian32(commission), ] payload = b"".join(payload_parts) # 2) Sign with both keys secp_sig = SECP256K1_SIGN(blake3(payload), secp_privkey) bls_sig = BLS_SIGN(hash_to_curve(payload), bls_privkey) # 3) Solidity encode the payload and two signatures return eth_abi.encode(['bytes', 'bytes', 'bytes'], [payload, secp_sig, bls_sig]) ``` ### delegate Creates a delegator account if it does not exist and increases the delegator's balance. **Function selector** ``` delegate(uint64) : 0x84994fec ``` **Function signature** ```solidity theme={null} function delegate( uint64 validatorId ) external payable returns (bool success); ``` **Parameters** 1. `validatorId` - id of the validator that delegator would like to delegate to 2. `msg.value` - the amount to delegate **Gas cost** 260,850 **Behavior** * The delegator account is determined by `msg.sender`. * `validatorId` must correspond to a valid validator. * `msg.value` must be >= `DUST_THRESHOLD`. * If this delegation causes the validator's total stake to exceed `ACTIVE_VALIDATOR_STAKE`, then the validator will be added to `execution_valset` if not already present. * The delegator stake becomes active * in epoch `n+1` if the request is before the boundary block * in epoch `n+2` otherwise <Accordion title="Pseudocode"> `
프로젝트로 돌아가기