Comparing chainlink with monad

chainlink

View full →

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/chainlink/SKILL.md

Chainlink

Chainlink provides decentralized oracle infrastructure: price feeds for DeFi pricing, VRF for provably fair randomness, Automation for scheduled/conditional on-chain execution, and CCIP for cross-chain messaging and token transfers.

What You Probably Got Wrong

  • latestRoundData() returns int256, not uint256 — Price can be negative (e.g., oil futures in 2020). Always check answer > 0 before casting.
  • Decimals vary per feed — ETH/USD has 8 decimals, ETH/BTC has 18 decimals, USDC/USD has 8. Always call decimals() or hardcode per known feed. Never assume 8.
  • VRF v2 is deprecated — use VRF v2.5 — VRF v2.5 supports both LINK and native payment, uses requestRandomWords() with a struct parameter, and has a different coordinator interface. Most LLM training data references VRF v2.
  • Staleness is not optional — A price feed can return a stale answer if the oracle network stops updating. You must check updatedAt against a heartbeat threshold. Feeds without staleness checks have caused protocol-draining exploits.
  • roundId can be zero on L2s — On Arbitrum/Optimism sequencer feeds, round semantics differ. Do not rely on roundId for ordering on L2 feeds.
  • CCIP is not Chainlink VRF — They are separate products. CCIP handles cross-chain messaging; VRF handles randomness. Different contracts, different billing.
  • Automation renamed from Keepers — The product is now called Chainlink Automation, not Keepers. The interface names changed: KeeperCompatibleInterface is now AutomationCompatibleInterface.

Price Feeds

AggregatorV3Interface

The core interface for reading Chainlink price data on-chain.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";

contract PriceConsumer {
    AggregatorV3Interface internal immutable priceFeed;

    // ETH/USD heartbeat: 3600s on mainnet, 86400s on Arbitrum
    uint256 private constant STALENESS_THRESHOLD = 3600;

    constructor(address feedAddress) {
        priceFeed = AggregatorV3Interface(feedAddress);
    }

    function getLatestPrice() public view returns (int256 price, uint8 feedDecimals) {
        (
            uint80 roundId,
            int256 answer,
            /* uint256 startedAt */,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();

        if (answer <= 0) revert InvalidPrice();
        if (updatedAt == 0) revert RoundNotComplete();
        if (block.timestamp - updatedAt > STALENESS_THRESHOLD) revert StalePrice();
        if (answeredInRound < roundId) revert StaleRound();

        return (answer, priceFeed.decimals());
    }

    /// @notice Normalize a feed answer to 18 decimals
    function normalizeToWad(int256 answer, uint8 feedDecimals) public pure returns (uint256) {
        if (answer <= 0) revert InvalidPrice();
        if (feedDecimals <= 18) {
            return uint256(answer) * 10 ** (18 - feedDecimals);
        }
        return uint256(answer) / 10 ** (feedDecimals - 18);
    }

    error InvalidPrice();
    error RoundNotComplete();
    error StalePrice();
    error StaleRound();
}

Reading Price Feeds with TypeScript (viem)

import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";

const AGGREGATOR_V3_ABI = parseAbi([
  "function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)",
  "function decimals() external view returns (uint8)",
  "function description() external view returns (string)",
]);

// ETH/USD on Ethereum mainnet
const ETH_USD_FEED = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419" as const;
const STALENESS_THRESHOLD = 3600n;

const client = createPublicClient({
  chain: mainnet,
  transport: http(process.env.RPC_URL),
});

async function getPrice(feedAddress: `0x${string}`) {
  const [roundData, feedDecimals] = await Promise.all([
    client.readContract({
      address: feedAddress,
      abi: AGGREGATOR_V3_ABI,
      functionName: "latestRoundData",
    }),
    client.readContract({
      address: feedAddress,
      abi: AGGREGATOR_V3_ABI,
      functionName: "decimals",
    }),
  ]);

  const [roundId, answer, , updatedAt, answeredInRound] = roundData;

  if (answer <= 0n) throw new Error("Invalid price: non-positive");
  if (updatedAt === 0n) throw new Error("Round not complete");

  const now = BigInt(Math.floor(Date.now() / 1000));
  if (now - updatedAt > STALENESS_THRESHOLD) {
    throw new Error(`Stale price: ${now - updatedAt}s old`);
  }
  if (answeredInRound < roundId) {
    throw new Error("Stale round: answeredInRound < roundId");
  }

  // Normalize to 18 decimals
  const normalized =
    feedDecimals <= 18
      ? answer * 10n ** (18n - BigInt(feedDecimals))
      : answer / 10n ** (BigInt(feedDecimals) - 18n);

  return {
    raw: answer,
    decimals: feedDecimals,
    normalized,
    updatedAt,
  };
}

// Usage
const ethPrice = await getPrice(ETH_USD_FEED);
console.log(`ETH/USD: $${Number(ethPrice.raw) / 10 ** ethPrice.decimals}`);

L2 Sequencer Uptime Feed

On L2s, check the sequencer uptime feed before trusting price data. If the sequencer was recently restarted, prices may be stale while oracles catch up.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";

contract L2PriceConsumer {
    AggregatorV3Interface internal immutable sequencerUptimeFeed;
    AggregatorV3Interface internal immutable priceFeed;

    // Grace period after sequencer comes back online
    uint256 private constant GRACE_PERIOD = 3600;

    constructor(address _sequencerFeed, address _priceFeed) {
        sequencerUptimeFeed = AggregatorV3Interface(_sequencerFeed);
        priceFeed = AggregatorV3Interface(_priceFeed);
    }

    function getPrice() external view returns (int256) {
        (, int256 sequencerAnswer, , uint256 sequencerUpdatedAt, ) =
            sequencerUptimeFeed.latestRoundData();

        // answer == 0 means sequencer is up, answer == 1 means down
        if (sequencerAnswer != 0) revert SequencerDown();
        if (block.timestamp - sequencerUpdatedAt < GRACE_PERIOD) revert GracePeriodNotOver();

        (, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
        if (price <= 0) revert InvalidPrice();
        if (block.timestamp - updatedAt > 86400) revert StalePrice();

        return price;
    }

    error SequencerDown();
    error GracePeriodNotOver();
    error InvalidPrice();
    error StalePrice();
}

VRF v2.5

Chainlink VRF v2.5 provides provably fair, verifiable randomness. It uses subscription-based billing and supports payment in LINK or native token.

Requesting Randomness

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";

contract RandomConsumer is VRFConsumerBaseV2Plus {
    uint256 public immutable subscriptionId;
    bytes32 public immutable keyHash;

    // 200k gas covers most callbacks; increase for complex logic
    uint32 private constant CALLBACK_GAS_LIMIT = 200_000;
    uint16 private constant REQUEST_CONFIRMATIONS = 3;
    uint32 private constant NUM_WORDS = 1;

    mapping(uint256 => address) public requestToSender;
    mapping(address => uint256) public results;

    event RandomnessRequested(uint256 indexed requestId, address indexed requester);
    event RandomnessFulfilled(uint256 indexed requestId, uint256 randomWord);

    constructor(
        uint256 _subscriptionId,
        address _vrfCoordinator,
        bytes32 _keyHash
    ) VRFConsumerBaseV2Plus(_vrfCoordinator) {
        subscriptionId = _subscriptionId;
        keyHash = _keyHash;
    }

    function requestRandom() external returns (uint256 requestId) {
        requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: keyHash,
                subId: subscriptionId,
                requestConfirmations: REQUEST_CONFIRMATIONS,
                callbackGasLimit: CALLBACK_GAS_LIMIT,
                numWords: NUM_WORDS,
                extraArgs: VRFV2PlusClient._argsToBytes(
                    // false = pay with LINK, true = pay with native
                    VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
                )
            })
        );

        requestToSender[requestId] = msg.sender;
        emit RandomnessRequested(requestId, msg.sender);
    }

    function fulfillRandomWords(
        uint256 requestId,
        uint256[] calldata randomWords
    ) internal override {
        address requester = requestToSender[requestId];
        results[requester] = randomWords[0];
        emit RandomnessFulfilled(requestId, randomWords[0]);
    }
}

VRF Subscription Management (TypeScript)

import { createWalletClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

const VRF_COORDINATOR_ABI = parseAbi([
  "function createSubscription() external returns (uint256 subId)",
  "function addConsumer(uint256 subId, address consumer) external",
  "function removeConsumer(uint256 subId, address consumer) external",
  "function getSubscription(uint256 subId) external view returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address subOwner, address[] consumers)",
  "function fundSubscriptionWithNative(uint256 subId) external payable",
]);

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);

const walletClient = createWalletClient({
  account,
  chain: mainnet,
  transport: http(process.env.RPC_URL),
});

// Ethereum mainnet VRF Coordinator v2.5
const VRF_COORDINATOR = "0xD7f86b4b8Cae7D942340FF628F82735b7a20893a" as const;

async function createSubscription() {
  const hash = await walletClient.writeContract({
    address: VRF_COORDINATOR,
    abi: VRF_COORDINATOR_ABI,
    functionName: "createSubscription",
  });
  console.log("Subscription created, tx:", hash);
  return hash;
}

async function addConsumer(subId: bigint, consumerAddress: `0x${string}`) {
  const hash = await walletClient.writeContract({
    address: VRF_COORDINATOR,
    abi: VRF_COORDINATOR_ABI,
    functionName: "addConsumer",
    args: [subId, consumerAddress],
  });
  console.log("Consumer added, tx:", hash);
  return hash;
}

Automation (Keepers)

Chainlink Automation executes on-chain functions when conditions are met. Your contract implements checkUpkeep (off-chain simulation) and performUpkeep (on-chain execution).

AutomationCompatible Contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {AutomationCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol";

contract AutomatedCounter is AutomationCompatibleInterface {
    uint256 public counter;
    uint256 public lastTimestamp;
    uint256 public immutable interval;

    event CounterIncremented(uint256 indexed newValue, uint256 timestamp);

    constructor(uint256 _interval) {
        interval = _interval;
        lastTimestamp = block.timestamp;
    }

    /// @notice Called off-chain by Automation nodes to check if upkeep is needed
    /// @dev Must NOT modify state. Gas cost does not matter (simulated off-chain).
    function checkUpkeep(bytes calldata)
        external
        view
        override
        returns (bool upkeepNeeded, bytes memory performData)
    {
        upkeepNeeded = (block.timestamp - lastTimestamp) >= interval;
        performData = abi.encode(counter);
    }

    /// @notice Called on-chain when checkUpkeep returns true
    /// @dev Re-validate the condition — checkUpkeep result may be stale
    function performUpkeep(bytes calldata) external override {
        if ((block.timestamp - lastTimestamp) < interval) revert UpkeepNotNeeded();

        lastTimestamp = block.timestamp;
        counter += 1;
        emit CounterIncremented(counter, block.timestamp);
    }

    error UpkeepNotNeeded();
}

Log-Triggered Automation

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ILogAutomation, Log} from "@chainlink/contracts/src/v0.8/automation/interfaces/ILogAutomation.sol";

contract LogTriggeredUpkeep is ILogAutomation {
    event ActionPerformed(address indexed sender, uint256 amount);

    /// @notice Called when a matching log event is detected
    function checkLog(Log calldata log, bytes memory)
        external
        pure
        returns (bool upkeepNeeded, bytes memory performData)
    {
        upkeepNeeded = true;
        performData = log.data;
    }

    function performUpkeep(bytes calldata performData) external {
        (address sender, uint256 amount) = abi.decode(performData, (address, uint256));
        emit ActionPerformed(sender, amount);
    }
}

CCIP (Cross-Chain Interoperability Protocol)

CCIP enables sending arbitrary messages and tokens between supported chains.

Sending a Cross-Chain Message

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IRouterClient} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IRouterClient.sol";
import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract CCIPSender {
    IRouterClient public immutable router;
    IERC20 public immutable linkToken;

    event MessageSent(bytes32 indexed messageId, uint64 indexed destinationChain);

    constructor(address _router, address _link) {
        router = IRouterClient(_router);
        linkToken = IERC20(_link);
    }

    function sendMessage(
        uint64 destinationChainSelector,
        address receiver,
        bytes calldata data
    ) external returns (bytes32 messageId) {
        Client.EVM2AnyMessage memory message = Client.EVM2AnyMessage({
            receiver: abi.encode(receiver),
            data: data,
            tokenAmounts: new Client.EVMTokenAmount[](0),
            extraArgs: Client._argsToBytes(
                Client.EVMExtraArgsV2({gasLimit: 200_000, allowOutOfOrderExecution: true})
            ),
            feeToken: address(linkToken)
        });

        uint256 fees = router.getFee(destinationChainSelector, message);
        linkToken.approve(address(router), fees);

        messageId = router.ccipSend(destinationChainSelector, message);
        emit MessageSent(messageId, destinationChainSelector);
    }
}

Receiving a Cross-Chain Message

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {CCIPReceiver} from "@chainlink/contracts-ccip/src/v0.8/ccip/applications/CCIPReceiver.sol";
import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol";

contract CCIPReceiverExample is CCIPReceiver {
    // Allowlist source chains and senders to prevent unauthorized messages
    mapping(uint64 => mapping(address => bool)) public allowlistedSenders;
    address public owner;

    event MessageReceived(
        bytes32 indexed messageId,
        uint64 indexed sourceChainSelector,
        address sender,
        bytes data
    );

    constructor(address _router) CCIPReceiver(_router) {
        owner = msg.sender;
    }

    function allowlistSender(
        uint64 chainSelector,
        address sender,
        bool allowed
    ) external {
        if (msg.sender != owner) revert Unauthorized();
        allowlistedSenders[chainSelector][sender] = allowed;
    }

    function _ccipReceive(Client.Any2EVMMessage memory message) internal override {
        address sender = abi.decode(message.sender, (address));
        if (!allowlistedSenders[message.sourceChainSelector][sender]) {
            revert SenderNotAllowlisted();
        }

        emit MessageReceived(
            message.messageId,
            message.sourceChainSelector,
            sender,
            message.data
        );
    }

    error Unauthorized();
    error SenderNotAllowlisted();
}

Contract Addresses

Last verified: 2025-05-01

Price Feeds

PairEthereum MainnetArbitrum OneBase
ETH/USD0x5f4eC3Df9cbd43714FE2740f5E3616155c5b84190x639Fe6ab55C921f74e7fac1ee960C0B6293ba6120x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70
BTC/USD0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c0x6ce185860a4963106506C203335A2910413708e90x64c911996D3c6aC71f9b455B1E8E7M1BbDC942BAe
USDC/USD0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f60x50834F3163758fcC1Df9973b6e91f0F0F0434aD30x7e860098F58bBFC8648a4311b374B1D669a2bc6B
LINK/USD0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c0x86E53CF1B870786351Da77A57575e79CB55812CB0x17CAb8FE31cA45e4684E33E3D258F20E88B8fD8B

Sequencer Uptime Feeds

ChainAddress
Arbitrum0xFdB631F5EE196F0ed6FAa767959853A9F217697D
Base0xBCF85224fc0756B9Fa45aAb7d2257eC1673570EF
Optimism0x371EAD81c9102C9BF4874A9075FFFf170F2Ee389

VRF v2.5 Coordinators

ChainCoordinator
Ethereum0xD7f86b4b8Cae7D942340FF628F82735b7a20893a
Arbitrum0x3C0Ca683b403E37668AE3DC4FB62F4B29B6f7a3e
Base0xd5D517aBE5cF79B7e95eC98dB0f0277788aFF634

CCIP Routers

ChainRouterChain Selector
Ethereum0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D5009297550715157269
Arbitrum0x141fa059441E0ca23ce184B6A78bafD2A517DdE84949039107694359620
Base0x881e3A65B4d4a04dD529061dd0071cf975F58bCD15971525489660198786

LINK Token

ChainAddress
Ethereum0x514910771AF9Ca656af840dff83E8264EcF986CA
Arbitrum0xf97f4df75117a78c1A5a0DBb814Af92458539FB4
Base0x88Fb150BDc53A65fe94Dea0c9BA0a6dAf8C6e196

Error Handling

Error / SymptomCauseFix
answer <= 0 from price feedFeed returning invalid/negative priceCheck answer > 0 before using; revert or use fallback oracle
block.timestamp - updatedAt > thresholdOracle stopped updating (network congestion, feed deprecation)Implement staleness check with per-feed heartbeat threshold
answeredInRound < roundIdAnswer is from a previous roundReject stale round data
VRF callback revertscallbackGasLimit too low for your fulfillRandomWords logicIncrease callbackGasLimit; test gas usage on fork
VRF request pending indefinitelySubscription underfunded, consumer not added, or wrong keyHashFund subscription, verify consumer is registered, use correct key hash for your chain
Automation performUpkeep not firingcheckUpkeep returns false, upkeep underfunded, or gas price too highDebug checkUpkeep locally; fund upkeep; check min balance requirements
CCIP InsufficientFeeTokenAmountNot enough LINK approved for feesCall router.getFee() first, then approve that amount + buffer
CCIP message not deliveredDestination contract reverts, sender not allowlisted, or chain selector wrongCheck receiver contract, verify allowlist, confirm chain selectors from docs

Security Considerations

Price Feed Safety

  1. Always check staleness — Every latestRoundData() call must validate updatedAt against the feed's heartbeat. ETH/USD on mainnet has a 3600s heartbeat; on Arbitrum it is 86400s. Check Chainlink's feed page for per-feed heartbeats.

  2. Sanity-bound oracle prices — If a feed reports ETH at $0.01 or $1,000,000, something is wrong. Add upper and lower bounds based on reasonable price ranges and revert or pause if breached.

uint256 private constant MIN_ETH_PRICE = 100e8;       // $100
uint256 private constant MAX_ETH_PRICE = 100_000e8;    // $100,000

function getSafePrice(AggregatorV3Interface feed) internal view returns (uint256) {
    (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
    if (answer <= 0) revert InvalidPrice();
    if (block.timestamp - updatedAt > 3600) revert StalePrice();
    if (uint256(answer) < MIN_ETH_PRICE || uint256(answer) > MAX_ETH_PRICE) {
        revert PriceOutOfBounds();
    }
    return uint256(answer);
}
  1. L2 sequencer check — On Arbitrum, Base, and Optimism, always check the sequencer uptime feed. A sequencer outage means oracle updates are delayed; using stale prices during recovery has caused exploits.

  2. Decimal normalization — Never assume 8 decimals. Always call feed.decimals() or use known constants per feed. When combining two feeds (e.g., TOKEN/ETH and ETH/USD), handle decimals carefully to avoid overflow or truncation.

  3. Multi-oracle fallback — For critical DeFi protocols, use Chainlink as primary but have a fallback (e.g., Uniswap TWAP or Pyth) to prevent single oracle dependency from freezing your protocol.

VRF Safety

  • Never use block values (block.timestamp, block.prevrandao) as randomness — they are manipulable by validators.
  • Store the requestId -> user mapping before the callback. The callback is asynchronous and you need to know who requested it.
  • Set callbackGasLimit high enough for your logic but not excessively — you pay for unused gas.

Automation Safety

  • Always re-validate conditions in performUpkeep. The checkUpkeep result may be stale by the time performUpkeep executes on-chain.
  • checkUpkeep runs off-chain in simulation — it cannot modify state. Any state changes will be reverted.

CCIP Safety

  • Always allowlist source chains and sender addresses on your receiver contract. Without this, anyone on any supported chain can send messages to your contract.
  • Handle message failures gracefully. If _ccipReceive reverts, the message can be manually executed later, but your contract should not end up in an inconsistent state from partial execution.

Alternative Oracles

For use cases where Chainlink's push model isn't optimal, consider these alternatives:

Pyth Network (pyth-evm skill) — Pull oracle model where consumers fetch and submit price updates on-demand. Best for: sub-second price freshness (~400ms on Pythnet), confidence intervals (statistical uncertainty bounds), MEV-protected liquidations via Express Relay, and non-EVM chains (Solana, Sui, Aptos). Trade-off: consumers pay gas for price updates (~120-150K gas per feed).

When to use Chainlink vs Pyth:

  • Chainlink: Zero-cost reads (DON sponsors updates), broadest EVM feed coverage (1000+), VRF/CCIP/Automation ecosystem, well-established data quality
  • Pyth: Sub-second freshness, confidence intervals, historical price verification, MEV protection, 50+ EVM chains + non-EVM

See also: redstone skill for another pull oracle alternative.

References

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/monad/SKILL.md

Monad L1 Development

Chain Configuration

Mainnet

PropertyValue
Chain ID143
CurrencyMON (18 decimals)
EVM VersionPectra fork
Block Time400ms
Finality800ms (2 slots)
Block Gas Limit200M
Tx Gas Limit30M
Gas Throughput500M gas/sec
Min Base Fee100 MON-gwei
Node Versionv0.12.7 / MONAD_EIGHT

RPC Endpoints (Mainnet)

URLProviderRate LimitBatchNotes
https://rpc.monad.xyz / wss://rpc.monad.xyzQuickNode25 rps100Default
https://rpc1.monad.xyz / wss://rpc1.monad.xyzAlchemy15 rps100No debug/trace
https://rpc2.monad.xyz / wss://rpc2.monad.xyzGoldsky Edge300/10s10Historical state
https://rpc3.monad.xyz / wss://rpc3.monad.xyzAnkr300/10s10No debug
https://rpc-mainnet.monadinfra.com / wss://rpc-mainnet.monadinfra.comMF20 rps1Historical state

Block Explorers

ExplorerURL
MonadVisionhttps://monadvision.com
Monadscanhttps://monadscan.com
Socialscanhttps://monad.socialscan.io
Visualizationhttps://gmonads.com
TracesPhalcon Explorer, Tenderly
UserOpsJiffyscan

Testnet

PropertyValue
Chain ID10143
RPChttps://testnet-rpc.monad.xyz
WebSocketwss://testnet-rpc.monad.xyz
Explorerhttps://testnet.monadexplorer.com
Faucethttps://testnet.monad.xyz

Key Differences from Ethereum

FeatureEthereumMonad
Block time12s400ms
Finality~12-18 min800ms (2 slots)
Throughput~10 TPS10,000+ TPS
Gas chargingGas usedGas limit
Max contract size24.5 KB128 KB
Blob txns (EIP-4844)SupportedNot supported
Global mempoolYesNo (leader-based forwarding)
Account cold access2,600 gas10,100 gas
Storage cold access2,100 gas8,100 gas
Reserve balanceNone~10 MON per account
TIMESTAMP granularity1 per block2-3 blocks share same second
Precompile 0x0100N/AEIP-7951 secp256r1 (P256)
EIP-7702 min balanceNone10 MON for delegated EOAs
EIP-7702 CREATE/CREATE2AllowedBanned for delegated EOAs
Tx types supported0,1,2,3,40,1,2,4 (no type 3)

Gas Limit Charging Model

Monad charges gas_limit * price_per_gas, NOT gas_used * price_per_gas. This enables asynchronous execution — execution happens after consensus, so gas used isn't known at inclusion time.

gas_paid = gas_limit * price_per_gas
price_per_gas = min(base_price_per_gas + priority_price_per_gas, max_price_per_gas)

Set gas limits explicitly for fixed-cost operations (e.g., 21000 for transfers) to avoid overpaying.

Reserve Balance

Every account maintains a ~10 MON reserve for gas across the next 3 blocks. Transactions that would reduce balance below this threshold are rejected. This prevents DoS during asynchronous execution.

Block Lifecycle & Finality

Proposed → Voted (speculative finality, T+1) → Finalized (T+2) → Verified/state root (T+5)
PhaseLatencyWhen to Use
Voted400msUI updates, most dApps
Finalized800msConservative apps
Verified~2sExchanges, bridges, stablecoins

Quick Start: viem Chain Definition

import { defineChain } from "viem";

export const monad = defineChain({
  id: 143,
  name: "Monad",
  nativeCurrency: { name: "MON", symbol: "MON", decimals: 18 },
  rpcUrls: {
    default: { http: ["https://rpc.monad.xyz"], webSocket: ["wss://rpc.monad.xyz"] },
  },
  blockExplorers: {
    default: { name: "MonadVision", url: "https://monadvision.com" },
    monadscan: { name: "Monadscan", url: "https://monadscan.com" },
  },
});

export const monadTestnet = defineChain({
  id: 10143,
  name: "Monad Testnet",
  nativeCurrency: { name: "MON", symbol: "MON", decimals: 18 },
  rpcUrls: {
    default: { http: ["https://testnet-rpc.monad.xyz"], webSocket: ["wss://testnet-rpc.monad.xyz"] },
  },
  blockExplorers: {
    default: { name: "Monad Explorer", url: "https://testnet.monadexplorer.com" },
  },
  testnet: true,
});

Quick Start: Foundry Setup

Install Monad Foundry Fork

curl -L https://raw.githubusercontent.com/category-labs/foundry/monad/foundryup/install | bash
foundryup --network monad

Project Init

forge init --template monad-developers/foundry-monad my-project

foundry.toml

[profile.default]
src = "src"
out = "out"
libs = ["lib"]
evm_version = "prague"

[rpc_endpoints]
monad = "https://rpc.monad.xyz"
monad_testnet = "https://testnet-rpc.monad.xyz"

[etherscan]
monad = { key = "${ETHERSCAN_API_KEY}", chain = 143, url = "https://api.etherscan.io/v2/api?chainid=143" }
monad_testnet = { key = "${ETHERSCAN_API_KEY}", chain = 10143, url = "https://api.etherscan.io/v2/api?chainid=10143" }

Quick Start: Hardhat Configuration (v2)

const config: HardhatUserConfig = {
  solidity: {
    version: "0.8.28",
    settings: {
      evmVersion: "prague",
      metadata: { bytecodeHash: "ipfs" },
    },
  },
  networks: {
    monadTestnet: {
      url: "https://testnet-rpc.monad.xyz",
      chainId: 10143,
      accounts: [process.env.PRIVATE_KEY!],
    },
    monadMainnet: {
      url: "https://rpc.monad.xyz",
      chainId: 143,
      accounts: [process.env.PRIVATE_KEY!],
    },
  },
  etherscan: {
    customChains: [{
      network: "monadMainnet",
      chainId: 143,
      urls: {
        apiURL: "https://api.etherscan.io/v2/api?chainid=143",
        browserURL: "https://monadscan.com",
      },
    }],
  },
  sourcify: {
    enabled: true,
    apiUrl: "https://sourcify-api-monad.blockvision.org",
    browserUrl: "https://monadvision.com",
  },
};

Deployment

Foundry Deploy (Keystore)

cast wallet import monad-deployer --private-key $(cast wallet new | grep 'Private key:' | awk '{print $3}')

forge create src/MyContract.sol:MyContract \
  --account monad-deployer \
  --rpc-url https://rpc.monad.xyz \
  --broadcast

forge create src/MyToken.sol:MyToken \
  --account monad-deployer \
  --rpc-url https://rpc.monad.xyz \
  --constructor-args "MyToken" "MTK" 18 \
  --broadcast

Foundry Deploy (Script)

forge script script/Deploy.s.sol \
  --account monad-deployer \
  --rpc-url https://rpc.monad.xyz \
  --broadcast \
  --slow

Hardhat Deploy

npx hardhat ignition deploy ignition/modules/Counter.ts --network monadMainnet
npx hardhat ignition deploy ignition/modules/Counter.ts --network monadMainnet --reset

Verification

MonadVision (Sourcify)

forge verify-contract <address> <ContractName> \
  --chain 143 \
  --verifier sourcify \
  --verifier-url https://sourcify-api-monad.blockvision.org/

Monadscan (Etherscan)

forge verify-contract <address> <ContractName> \
  --chain 143 \
  --verifier etherscan \
  --etherscan-api-key $ETHERSCAN_API_KEY \
  --watch

Socialscan

forge verify-contract <address> <ContractName> \
  --chain 143 \
  --verifier etherscan \
  --etherscan-api-key $SOCIALSCAN_API_KEY \
  --verifier-url https://api.socialscan.io/monad-mainnet/v1/explorer/command_api/contract \
  --watch

Hardhat Verify

npx hardhat verify <address> --network monadMainnet

For testnet verification, replace --chain 143 with --chain 10143 and use testnet RPC/explorer URLs.

Opcode Repricing Summary

Cold state access is ~4x more expensive on Monad than Ethereum. Warm access is identical.

Access TypeEthereumMonad
Account (cold)2,60010,100
Storage slot (cold)2,1008,100
Account (warm)100100
Storage slot (warm)100100

Selected precompile repricing:

PrecompileEthereumMonadMultiplier
ecRecover (0x01)3,0006,0002x
ecMul (0x07)6,00030,0005x
ecPairing (0x08)45,000225,0005x
point evaluation (0x0a)50,000200,0004x

Monad-specific precompile: secp256r1 (P256) at 0x0100 for WebAuthn/passkey signature verification (EIP-7951).

EIP-1559 Parameters

ParameterValue
Block gas limit200M
Block gas target160M (80% of limit)
Per-transaction gas limit30M
Min base fee100 MON-gwei
Base fee max step size1/28
Base fee decay factor0.96

The base fee controller increases slower and decreases faster than Ethereum's to prevent blockspace underutilization on a high-throughput chain.

Gas Optimization Tips

  1. Warm your storage — cold reads are 4x more expensive; use access lists (type 1/2 txns) for known slots
  2. Set explicit gas limits — you're charged for the limit, not usage
  3. Batch operations — high throughput means batching is less critical, but still saves gas limit overhead
  4. Avoid unnecessary cold precompile calls — ecPairing is 5x more expensive than Ethereum
  5. Design for parallel execution — per-user mappings over global counters where possible
  6. No blob transactions — use calldata for data availability

Parallel Execution

Monad executes transactions concurrently with optimistic conflict detection. No Solidity changes needed.

  1. Multiple virtual executors process transactions simultaneously
  2. Each generates "pending results" (inputs: SLOADs, outputs: SSTOREs)
  3. Serial commitment validates each result's inputs remain valid
  4. Conflict detected -> re-execute the affected transaction
  5. Results committed in original transaction order

Every transaction executes at most twice. Most transactions don't conflict, achieving near-linear speedup.

Parallel-Friendly Contract Design

PatternParallelizes WellWhy
Per-user mappingsYesIndependent state per user
ERC-20 transfers between different pairsYesDifferent storage slots
Global counter incrementNoAll txns write same slot
AMM swaps on same poolNoSame reserves storage
Independent NFT mints (incremental ID)PartiallytokenId counter serializes

Staking Precompile

Address: 0x0000000000000000000000000000000000001000

Only standard CALL is allowed. STATICCALL, DELEGATECALL, and CALLCODE are not permitted.

Core Functions

FunctionSelectorGas Cost
delegate(uint64)0x84994fec260,850
undelegate(uint64,uint256,uint8)0x5cf41514147,750
compound(uint64)0xb34fea67285,050
claimRewards(uint64)0xa76e2ca5155,375
withdraw(uint64,uint8)0xaed2ee7368,675

Delegate (Solidity)

address constant STAKING = 0x0000000000000000000000000000000000001000;

function delegateToValidator(uint64 validatorId) external payable {
    (bool success,) = STAKING.call{value: msg.value}(
        abi.encodeWithSelector(0x84994fec, validatorId)
    );
    require(success, "Delegation failed");
}

Delegate (viem)

import { encodeFunctionData } from "viem";

const STAKING_ADDRESS = "0x0000000000000000000000000000000000001000";

const hash = await walletClient.sendTransaction({
  to: STAKING_ADDRESS,
  value: parseEther("100"),
  data: encodeFunctionData({
    abi: [{ name: "delegate", type: "function", inputs: [{ name: "validatorId", type: "uint64" }], outputs: [] }],
    functionName: "delegate",
    args: [1n],
  }),
});

EIP-7702 on Monad

Allows EOAs to gain smart contract capabilities via code delegation.

RestrictionDetail
Minimum balanceDelegated EOAs cannot drop below 10 MON
CREATE/CREATE2Banned when delegated EOAs execute as smart contracts
Clearing delegationSend type 0x04 pointing to address(0)
import { walletClient } from "./client";

const authorization = await walletClient.signAuthorization({
  account,
  contractAddress: "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2",
});

const hash = await walletClient.sendTransaction({
  authorizationList: [authorization],
  data: "0xdeadbeef",
  to: walletClient.account.address,
});

WebSocket Subscriptions

Standard eth_subscribe plus Monad-specific extensions:

newHeads        — standard new block headers
logs            — standard log filtering
monadNewHeads   — Monad-specific block headers with extra fields
monadLogs       — Monad-specific log events

Execution Events (Advanced)

For ultra-low-latency data consumption, Monad exposes execution events via shared-memory ring buffers. Consumer runs on same host as node. ~1 microsecond latency. Supported in C, C++, and Rust only.

Use execution events when JSON-RPC can't keep up with 10,000 TPS throughput. For most dApps, standard WebSocket subscriptions are sufficient.

Canonical Contracts

ContractAddress
Wrapped MON (WMON)0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A
Staking Precompile0x0000000000000000000000000000000000001000
Multicall30xcA11bde05977b3631167028862bE2a173976CA11
USDC0x754704Bc059F8C67012fEd69BC8A327a5aafb603
USDT00xe7cd86e13AC4309349F30B3435a9d337750fC82D
WETH0xEE8c0E9f1BFFb4Eb878d8f15f368A02a35481242
WBTC0x0555E30da8f98308EdB960aa94C0Db47230d2B9c
ERC-4337 EntryPoint v0.70x0000000071727De22E5E9d8BAf0edAc6f37da032
Safe0x69f4D1788e39c87893C980c06EdF4b7f686e2938

Supported Transaction Types

TypeNameSupportedNotes
0LegacyYesPre-EIP-155 allowed but discouraged
1EIP-2930 (access list)Yes
2EIP-1559 (dynamic fee)YesRecommended
3EIP-4844 (blob)NoNot supported on Monad
4EIP-7702 (delegation)YesWith Monad-specific restrictions

Smart Contract Tips

  • Gas optimization still matters — even with cheap gas, optimize for users
  • Same security model — all Solidity best practices (CEI, reentrancy guards) apply
  • Parallel-friendly design — contracts with per-user mappings parallelize better than global counters
  • 128 KB contract limit — larger contracts are possible but still optimize for gas
  • No code changes needed for parallelism — it's at the runtime level
  • block.timestamp — 2-3 blocks may share the same second; don't rely on sub-second granularity
  • No blob transactions — EIP-4844 type 3 txns are not supported

Required Tooling Versions

ToolMinimum Version
FoundryMonad fork (foundryup --network monad)
viem2.40.0+
alloy-chains0.2.20+
Hardhat SolidityevmVersion: "prague"

Pre-Deployment Checklist

  • Using Monad Foundry fork or Hardhat with evmVersion: "prague"
  • Correct chain ID (143 mainnet / 10143 testnet)
  • Account funded with MON (remember ~10 MON reserve)
  • Gas limit set explicitly for predictable cost (gas limit is charged, not gas used)
  • Private key in env var, not hardcoded
  • Contract size under 128 KB
  • No EIP-4844 blob transactions (type 3 not supported)
  • Verified on at least one explorer after deploy

Additional Reference

FileContents
docs/architecture.mdMonadBFT consensus, parallel execution, deferred execution, MonadDb, JIT, RaptorCast
docs/deployment.mdFoundry + Hardhat deploy/verify step-by-step guides
docs/gas-and-opcodes.mdGas pricing model, opcode repricing tables, precompile costs
docs/staking.mdStaking precompile ABI, functions, events, epoch mechanics
docs/ecosystem.mdToken addresses, bridges, oracles, indexers, canonical contracts
docs/troubleshooting.mdCommon issues and fixes for Monad development
resources/contract-addresses.mdKey Monad contract addresses
templates/deploy-monad.shShell script for deploying to Monad

AI Skill Finder

Ask me what skills you need

What are you building?

Tell me what you're working on and I'll find the best agent skills for you.