<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Fran Roberts Blog</title>
        <link>https://franroberts.site/blog/</link>
        <description>Fran Roberts Blog</description>
        <lastBuildDate>Fri, 08 May 2026 00:00:00 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <language>en</language>
        <item>
            <title><![CDATA[A short crypto reading list for people who actually want to build]]></title>
            <link>https://franroberts.site/blog/crypto-reading-list-2026/</link>
            <guid>https://franroberts.site/blog/crypto-reading-list-2026/</guid>
            <pubDate>Fri, 08 May 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Every couple of months someone messages me asking where to start with crypto. Not "should I buy some" — they mean "I want to build something on-chain, where do I read." The honest answer is that most "intro to crypto" content is bad: it is either price-chart bait or a 90-minute YouTube lecture that could have been a paragraph.]]></description>
            <content:encoded><![CDATA[<p>Every couple of months someone messages me asking where to start with crypto. Not "should I buy some" — they mean "I want to build something on-chain, where do I read." The honest answer is that most "intro to crypto" content is bad: it is either price-chart bait or a 90-minute YouTube lecture that could have been a paragraph.</p>
<p>This post is the short list of links I actually send. Each one earned its spot by being something I have either learned from or sent to a working developer who came back less confused.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="start-with-the-primary-sources">Start with the primary sources<a href="https://franroberts.site/blog/crypto-reading-list-2026/#start-with-the-primary-sources" class="hash-link" aria-label="Direct link to Start with the primary sources" title="Direct link to Start with the primary sources" translate="no">​</a></h2>
<p>Read these before anything else. They are short, free, and they are what every secondary explainer is paraphrasing.</p>
<ul>
<li class=""><a href="https://bitcoin.org/bitcoin.pdf" target="_blank" rel="noopener noreferrer" class="">Bitcoin: A Peer-to-Peer Electronic Cash System</a> — Satoshi's original whitepaper. Nine pages. You will not understand every line on the first read and that is fine; the structure is what matters.</li>
<li class=""><a href="https://ethereum.org/en/whitepaper/" target="_blank" rel="noopener noreferrer" class="">Ethereum Whitepaper</a> — Buterin's original 2014 paper. Read this once you understand Bitcoin, because half of it is "here is what Bitcoin can't do."</li>
<li class=""><a href="https://ethereum.github.io/yellowpaper/paper.pdf" target="_blank" rel="noopener noreferrer" class="">Ethereum Yellow Paper</a> — The formal spec. You don't need to read this cover to cover, but you should know it exists and skim the EVM section once.</li>
</ul>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="protocol-docs-that-are-worth-your-time">Protocol docs that are worth your time<a href="https://franroberts.site/blog/crypto-reading-list-2026/#protocol-docs-that-are-worth-your-time" class="hash-link" aria-label="Direct link to Protocol docs that are worth your time" title="Direct link to Protocol docs that are worth your time" translate="no">​</a></h2>
<ul>
<li class=""><a href="https://ethereum.org/en/developers/docs/" target="_blank" rel="noopener noreferrer" class="">ethereum.org developer docs</a> — The closest thing the ecosystem has to a canonical tutorial site. Start at the Foundational topics, not the Stack section.</li>
<li class=""><a href="https://docs.soliditylang.org/" target="_blank" rel="noopener noreferrer" class="">Solidity docs</a> — The language reference for smart contracts. The "Solidity by Example" appendix is the fastest path to reading existing contracts.</li>
<li class=""><a href="https://eips.ethereum.org/" target="_blank" rel="noopener noreferrer" class="">EIPs (Ethereum Improvement Proposals)</a> — Every standard you will ever interact with (ERC-20, ERC-721, ERC-4337) is here. Bookmark it.</li>
<li class=""><a href="https://docs.vyperlang.org/" target="_blank" rel="noopener noreferrer" class="">Vyper docs</a> — Worth a skim even if you write Solidity, because seeing the same concepts in a different syntax sharpens your mental model.</li>
</ul>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="tooling-in-the-order-you-will-need-it">Tooling, in the order you will need it<a href="https://franroberts.site/blog/crypto-reading-list-2026/#tooling-in-the-order-you-will-need-it" class="hash-link" aria-label="Direct link to Tooling, in the order you will need it" title="Direct link to Tooling, in the order you will need it" translate="no">​</a></h2>
<ul>
<li class=""><a href="https://book.getfoundry.sh/" target="_blank" rel="noopener noreferrer" class="">Foundry book</a> — The current default toolchain for new Solidity projects. <code>forge</code>, <code>cast</code>, <code>anvil</code>. Learn this before Hardhat unless your team is already on Hardhat.</li>
<li class=""><a href="https://hardhat.org/docs" target="_blank" rel="noopener noreferrer" class="">Hardhat docs</a> — Still widely used, especially in older codebases. Worth knowing if you are reading other people's repos.</li>
<li class=""><a href="https://docs.openzeppelin.com/contracts/" target="_blank" rel="noopener noreferrer" class="">OpenZeppelin Contracts</a> — Audited reference implementations of every common standard. Read the source. Do not roll your own ERC-20.</li>
<li class=""><a href="https://wagmi.sh/" target="_blank" rel="noopener noreferrer" class="">wagmi</a> and <a href="https://viem.sh/" target="_blank" rel="noopener noreferrer" class="">viem</a> — The current recommended frontend stack for talking to chains from React. ethers.js is fine but the ecosystem has moved.</li>
</ul>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="security-which-you-should-read-before-you-ship-anything">Security, which you should read before you ship anything<a href="https://franroberts.site/blog/crypto-reading-list-2026/#security-which-you-should-read-before-you-ship-anything" class="hash-link" aria-label="Direct link to Security, which you should read before you ship anything" title="Direct link to Security, which you should read before you ship anything" translate="no">​</a></h2>
<ul>
<li class=""><a href="https://swcregistry.io/" target="_blank" rel="noopener noreferrer" class="">Smart Contract Weakness Classification (SWC)</a> — Catalog of known vulnerability classes. Do a pass through this before your first deploy.</li>
<li class=""><a href="https://github.com/x676f64/secureum-mind_map" target="_blank" rel="noopener noreferrer" class="">Secureum's Solidity 201</a> — Mind map of audit-relevant concepts. Dense, link-heavy, and free.</li>
<li class=""><a href="https://rekt.news/" target="_blank" rel="noopener noreferrer" class="">Rekt News</a> — Postmortems of real exploits. Read it the way pilots read NTSB reports — for the specific failure modes, not the drama.</li>
<li class=""><a href="https://github.com/crytic/building-secure-contracts" target="_blank" rel="noopener noreferrer" class="">Trail of Bits' Building Secure Contracts</a> — A working engineer's guide. The "not-so-smart-contracts" examples in particular are worth a Saturday.</li>
</ul>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="defi-if-that-is-the-rabbit-hole-you-are-in">DeFi, if that is the rabbit hole you are in<a href="https://franroberts.site/blog/crypto-reading-list-2026/#defi-if-that-is-the-rabbit-hole-you-are-in" class="hash-link" aria-label="Direct link to DeFi, if that is the rabbit hole you are in" title="Direct link to DeFi, if that is the rabbit hole you are in" translate="no">​</a></h2>
<ul>
<li class=""><a href="https://defillama.com/" target="_blank" rel="noopener noreferrer" class="">DeFiLlama</a> — Aggregator of TVL across chains and protocols. Useful for sanity-checking which protocols are actually being used vs. which are just being talked about.</li>
<li class=""><a href="https://uniswap.org/whitepaper-v3.pdf" target="_blank" rel="noopener noreferrer" class="">Uniswap v3 whitepaper</a> — Concentrated liquidity is the most interesting AMM design idea of the last few years and the paper is readable.</li>
<li class=""><a href="https://www.paradigm.xyz/writing" target="_blank" rel="noopener noreferrer" class="">Paradigm research</a> — Posts from the Paradigm team. Heavy on cryptography and mechanism design, but they explain things properly.</li>
</ul>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="newsletters-and-feeds-that-dont-waste-your-time">Newsletters and feeds that don't waste your time<a href="https://franroberts.site/blog/crypto-reading-list-2026/#newsletters-and-feeds-that-dont-waste-your-time" class="hash-link" aria-label="Direct link to Newsletters and feeds that don't waste your time" title="Direct link to Newsletters and feeds that don't waste your time" translate="no">​</a></h2>
<ul>
<li class=""><a href="https://weekinethereumnews.com/" target="_blank" rel="noopener noreferrer" class="">Week in Ethereum News</a> — Boring on purpose. Just a list of what shipped, what was discussed, and what is coming.</li>
<li class=""><a href="https://www.bankless.com/" target="_blank" rel="noopener noreferrer" class="">Bankless</a> — More opinionated, sometimes too far into hype, but their protocol deep-dives are good.</li>
<li class=""><a href="https://vitalik.eth.limo/" target="_blank" rel="noopener noreferrer" class="">Vitalik's blog</a> — The signal-to-noise here is unreasonable. Read the posts on rollups, account abstraction, and quadratic funding first.</li>
</ul>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="a-note-on-what-i-left-out">A note on what I left out<a href="https://franroberts.site/blog/crypto-reading-list-2026/#a-note-on-what-i-left-out" class="hash-link" aria-label="Direct link to A note on what I left out" title="Direct link to A note on what I left out" translate="no">​</a></h2>
<p>I deliberately did not link any "learn Solidity in 30 days" courses, any token-price sites, or anything from a project that would benefit financially from you reading it. The list above is biased toward primary sources and toolchain docs because those are the things that age well. A YouTube tutorial from 2022 is mostly wrong now; the Solidity docs are not.</p>
<p>If a link here breaks or goes stale, that's a signal — let me know on <a href="https://github.com/franrob-projects" target="_blank" rel="noopener noreferrer" class="">GitHub</a> and I'll cut it. Reading lists rot fast in this space.</p>]]></content:encoded>
            <category>Ethereum</category>
            <category>Blockchain</category>
            <category>DeFi</category>
            <category>Solidity</category>
            <category>Tooling</category>
        </item>
        <item>
            <title><![CDATA[Why I opened a wayfinding PR against ethereum.org]]></title>
            <link>https://franroberts.site/blog/ethereum-org-docs-wayfinding/</link>
            <guid>https://franroberts.site/blog/ethereum-org-docs-wayfinding/</guid>
            <pubDate>Wed, 22 Apr 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[The developer docs on ethereum.org are thorough. If you sit down and read them like a textbook, they work. The problem is nobody reads docs like a textbook. People turn up with a goal (I want to deploy a contract, I want to run a node, I want to understand the EVM) and they want the fastest path to that goal.]]></description>
            <content:encoded><![CDATA[<p>The developer docs on ethereum.org are thorough. If you sit down and read them like a textbook, they work. The problem is nobody reads docs like a textbook. People turn up with a goal (I want to deploy a contract, I want to run a node, I want to understand the EVM) and they want the fastest path to that goal.</p>
<p><a href="https://ethereum.org/en/developers/docs/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/images/ef-logo.png" alt="Ethereum developer documentation" class="img_ev3q"></a></p>
<p>I opened <a href="https://github.com/ethereum/ethereum-org-website/pull/18016" target="_blank" rel="noopener noreferrer" class="">PR #18016</a> today to add a small wayfinding section to two pages. This is the reasoning.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-the-hub-page-looked-like">What the hub page looked like<a href="https://franroberts.site/blog/ethereum-org-docs-wayfinding/#what-the-hub-page-looked-like" class="hash-link" aria-label="Direct link to What the hub page looked like" title="Direct link to What the hub page looked like" translate="no">​</a></h2>
<p>The developer docs hub (<code>/developers/docs/</code>) opens with two paragraphs of intro copy, then three section lists: Foundational topics, Ethereum stack, Advanced. Those three lists are long, and the ordering is pedagogical (things in the right conceptual sequence) rather than task-oriented (things in the order you need them to do X).</p>
<p>If I know I want to write a smart contract, I still have to scan three lists and guess which entry point will start me somewhere useful. The answer is somewhere in the middle of Foundational topics, but you'd never know that from the hub.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-change">The change<a href="https://franroberts.site/blog/ethereum-org-docs-wayfinding/#the-change" class="hash-link" aria-label="Direct link to The change" title="Direct link to The change" translate="no">​</a></h2>
<p>Two additive blocks, both structured the same way:</p>
<ul>
<li class=""><strong>On the hub page</strong>, a new "Pick a starting point" section above the module lists. Four goal-based entry points (dapp, smart contract, node or staking, read the protocol in order), each linking straight to the first page on the right path.</li>
<li class=""><strong>On the intro-to-ethereum page</strong>, a mirrored "Where to go next" section at the end, so readers who finish the intro aren't dropped back onto the generic nav.</li>
</ul>
<p>No existing pages were touched, no modules reordered, no new routes. The linked target pages all exist already.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="why-do-this-as-an-additive-change-rather-than-a-rewrite">Why do this as an additive change rather than a rewrite<a href="https://franroberts.site/blog/ethereum-org-docs-wayfinding/#why-do-this-as-an-additive-change-rather-than-a-rewrite" class="hash-link" aria-label="Direct link to Why do this as an additive change rather than a rewrite" title="Direct link to Why do this as an additive change rather than a rewrite" translate="no">​</a></h2>
<p>The docs site is community-maintained and translated into 25 languages. Every paragraph of lead copy is a translation unit that has to get re-translated when it changes. A wayfinding insert that lives above the existing content is cheap to land, cheap to translate, and cheap to revert if the reviewers disagree with the framing.</p>
<p>A rewrite of the intro copy would have been more satisfying, but it would also be ten times the argument to have. Start small. See if the pattern lands.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="why-this-matters-for-the-protocol-not-just-the-docs">Why this matters for the protocol, not just the docs<a href="https://franroberts.site/blog/ethereum-org-docs-wayfinding/#why-this-matters-for-the-protocol-not-just-the-docs" class="hash-link" aria-label="Direct link to Why this matters for the protocol, not just the docs" title="Direct link to Why this matters for the protocol, not just the docs" translate="no">​</a></h2>
<p>Ethereum has a developer acquisition problem that lives partly at the docs layer. Every minute a dapp developer spends scanning three lists to find "where does the thing I need start" is a minute they might spend pointing their cursor at Solana's docs instead. Wayfinding is not the glamorous part of the docs stack, but it is what pushes a reader from "I am looking" to "I am building".</p>
<p>Goal-based entry points are a pattern that Stripe, Vercel, and Supabase all use on their docs hubs for this reason. It is genuinely uncontroversial in the wider API-docs world. Putting the same pattern in place on ethereum.org is low-risk, and any pushback tells us useful things about how the maintainers see the target reader.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-id-do-next-if-this-lands">What I'd do next if this lands<a href="https://franroberts.site/blog/ethereum-org-docs-wayfinding/#what-id-do-next-if-this-lands" class="hash-link" aria-label="Direct link to What I'd do next if this lands" title="Direct link to What I'd do next if this lands" translate="no">​</a></h2>
<p>If PR #18016 merges, the same pattern is worth adding to a couple more hub-style pages:</p>
<ul>
<li class="">The root of <code>developers/tutorials/</code>, which currently has no goal-based filter at all.</li>
<li class="">The smart-contracts landing page, where readers likely want to pick between "I'm shipping a token", "I'm building a protocol", and "I'm auditing someone else's contract" more than they want the full curriculum.</li>
</ul>
<p>Both are larger changes. They need the first one to land first so there's a pattern to point at.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="how-to-pressure-test-a-docs-pr">How to pressure-test a docs PR<a href="https://franroberts.site/blog/ethereum-org-docs-wayfinding/#how-to-pressure-test-a-docs-pr" class="hash-link" aria-label="Direct link to How to pressure-test a docs PR" title="Direct link to How to pressure-test a docs PR" translate="no">​</a></h2>
<p>If you're thinking about contributing docs to a protocol repo, one thing that helps reviewers say yes faster: list the target pages in the PR body and confirm they exist. Half of drive-by docs PRs link to pages that were renamed two quarters ago. A maintainer who has to verify every link in a forty-line diff will bounce the PR out of habit.</p>
<p>The other thing that helps: scope tightly, name the convention you're adopting (in this case, the ethereum.org <code>{#kebab-id}</code> heading-ID rule), and mention what you didn't change so the reviewer knows where the blast radius stops.</p>]]></content:encoded>
            <category>Ethereum</category>
            <category>docs</category>
            <category>open-source</category>
        </item>
        <item>
            <title><![CDATA[Ethereum in March 2026: Glamsterdam, post-quantum, and what developers need to watch]]></title>
            <link>https://franroberts.site/blog/ethereum-glamsterdam-post-quantum-2026/</link>
            <guid>https://franroberts.site/blog/ethereum-glamsterdam-post-quantum-2026/</guid>
            <pubDate>Thu, 26 Mar 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Two things are dominating Ethereum developer conversations right now. The Glamsterdam upgrade is taking shape as the most significant protocol change since the Merge, and the Ethereum Foundation just launched a dedicated post-quantum security hub with more than ten client teams already running interoperability devnets. Neither is finished, but both are far enough along that developers should be paying attention.]]></description>
            <content:encoded><![CDATA[<p>Two things are dominating Ethereum developer conversations right now. The Glamsterdam upgrade is taking shape as the most significant protocol change since the Merge, and the Ethereum Foundation just launched a dedicated post-quantum security hub with more than ten client teams already running interoperability devnets. Neither is finished, but both are far enough along that developers should be paying attention.</p>
<p><a href="https://ethereum.org/en/roadmap/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/images/ef-logo.png" alt="Ethereum developer roadmap" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="glamsterdam-whats-actually-in-it">Glamsterdam: what's actually in it<a href="https://franroberts.site/blog/ethereum-glamsterdam-post-quantum-2026/#glamsterdam-whats-actually-in-it" class="hash-link" aria-label="Direct link to Glamsterdam: what's actually in it" title="Direct link to Glamsterdam: what's actually in it" translate="no">​</a></h2>
<p>Glamsterdam is slated for H1 2026, with a community-referenced target of June. Developers are careful to call that aspirational, but the EIP lineup is more settled than at the equivalent stage of previous upgrades.</p>
<p>Two EIPs are confirmed as headliners.</p>
<p><strong>EIP-7732: Enshrined Proposer-Builder Separation (ePBS)</strong></p>
<p>MEV-Boost is currently off-protocol middleware. Validators run it voluntarily, and the separation between block proposers and block builders exists by convention rather than by protocol rule. EIP-7732 moves PBS into the consensus layer itself.</p>
<p>The practical difference: today's relay-dependent system has multiple points where a relay operator can censor transactions or extract additional value. With ePBS enshrined, the separation becomes a protocol guarantee rather than a market convention. For developers building DeFi protocols or anything where transaction ordering matters, this is meaningful. The playing field for MEV becomes more predictable.</p>
<p>The <a href="https://blog.quicknode.com/ethereum-glamsterdam-upgrade-whats-coming-in-h1-2026/" target="_blank" rel="noopener noreferrer" class="">Ethereum Glamsterdam upgrade documentation</a> has a solid breakdown of the mechanics.</p>
<p><strong>EIP-7928: Block-Level Access Lists (BALs)</strong></p>
<p>This one is less visible to application developers but arguably more impactful for throughput. BALs require that a block pre-declares which accounts and contracts it will touch before execution begins. Nodes can use this information to parallelize transaction validation rather than running everything sequentially.</p>
<p>The gas limit is increasing from 60 million to 200 million per block. Without BALs, a higher gas limit would make block validation slower and push nodes toward higher hardware requirements. BALs are what make that increase practical, by enabling nodes to distribute execution work.</p>
<p>The projected outcome is roughly 10,000 TPS on L1, up from the current effective rate around 1,000 TPS. That is not a typo. If it ships as described, it fundamentally changes the economics of building on L1 versus L2.</p>
<p><strong>EIP-7904: Gas repricing</strong></p>
<p>Gas costs are being realigned to better reflect actual computational resources. The headline number is a 78% reduction for both simple ETH transfers and complex smart contract interactions. This is partly possible because the gas limit increase changes the unit economics, and partly because some operations have been mispriced relative to their actual node cost for years.</p>
<p>For developers, the main implication is that your existing gas estimates will be wrong after this ships. Plan to re-profile contracts against a post-7904 testnet before assuming your optimization work carries over.</p>
<p>Over 25 additional EIPs are under consideration. The <a href="https://www.datawallet.com/crypto/ethereum-glamsterdam-upgrade-explained" target="_blank" rel="noopener noreferrer" class="">Glamsterdam EIP tracker</a> is worth bookmarking if you want to follow the deliberations.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-post-quantum-initiative">The post-quantum initiative<a href="https://franroberts.site/blog/ethereum-glamsterdam-post-quantum-2026/#the-post-quantum-initiative" class="hash-link" aria-label="Direct link to The post-quantum initiative" title="Direct link to The post-quantum initiative" translate="no">​</a></h2>
<p>Separately from Glamsterdam, the Ethereum Foundation launched <a href="https://ethereum.org/" target="_blank" rel="noopener noreferrer" class="">pq.ethereum.org</a> this week as a central hub for its post-quantum cryptography roadmap. The site consolidates specs, EIPs, research papers, open-source repositories, and a detailed FAQ.</p>
<p>More than ten client teams are running weekly post-quantum interoperability devnets. This is coordinated, not experimental.</p>
<p>The context: current estimates for a cryptographically relevant quantum computer cluster around 2032. Ethereum's post-quantum components are targeted for the "L" or "M" fork, currently projected around 2029. That's a tight window for a decentralized protocol where coordination takes years.</p>
<p>The specific threats are well-understood. Ethereum's current cryptography relies on ECDSA for signatures and BLS12-381 for consensus. Both are vulnerable to Shor's algorithm on a sufficiently powerful quantum computer. An attacker with quantum capability could derive private keys from public keys, which would break account security at the protocol level.</p>
<p>The migration approach has two main components:</p>
<ul>
<li class=""><strong>Hash-based signatures</strong> for accounts. The EF is funding work on the <a href="https://ethereum.org/en/roadmap/" target="_blank" rel="noopener noreferrer" class="">Poseidon hash function</a> with a $1 million prize aimed at strengthening it against both classical and quantum attacks. Poseidon is faster than SHA-256 in ZK proof contexts, which matters for the overall roadmap.</li>
<li class=""><strong>Native account abstraction</strong> as the migration path. EIP-7702 (which allows EOAs to temporarily behave like smart wallets) and the ERC-4337 ecosystem provide the infrastructure for wallets to switch signature schemes without requiring users to move funds to new addresses.</li>
</ul>
<p>The multi-year timeline means this is not something application developers need to act on immediately. But if you are building wallet infrastructure or anything that makes assumptions about the signature scheme of an account, the direction of travel is clear: ECDSA is eventually going away.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="developer-activity-overall">Developer activity overall<a href="https://franroberts.site/blog/ethereum-glamsterdam-post-quantum-2026/#developer-activity-overall" class="hash-link" aria-label="Direct link to Developer activity overall" title="Direct link to Developer activity overall" translate="no">​</a></h2>
<p>One piece of broader context worth knowing: developer activity across the ecosystem has contracted. Weekly active developers on Ethereum are down roughly 34% over three months, with Solana and Base showing larger drops. The <a href="https://www.mexc.com/news/879536" target="_blank" rel="noopener noreferrer" class="">MEXC developer activity report for March 2026</a> tracks this. The prevailing explanation is that AI repositories are absorbing engineering capacity that previously went to blockchain projects.</p>
<p>This has a practical consequence for open-source projects: maintainer bandwidth is thinner than it was in 2024. If you depend on a library that has slowed down, it might be worth checking when it last merged a PR.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-to-do-now">What to do now<a href="https://franroberts.site/blog/ethereum-glamsterdam-post-quantum-2026/#what-to-do-now" class="hash-link" aria-label="Direct link to What to do now" title="Direct link to What to do now" translate="no">​</a></h2>
<p>For most application developers, Glamsterdam's immediate priority is the testnet phase. When EIP-7904 gas repricing lands on Sepolia, run your contracts against it and update your gas estimates. The 78% reduction is significant enough that hardcoded gas limits in client code will break.</p>
<p>For teams building wallets or key management infrastructure, the post-quantum roadmap is worth reading end-to-end. The 2029 target for protocol-level changes is closer than it sounds given the implementation and migration lead time involved.</p>
<p>The <a href="https://ethereum.org/en/roadmap/" target="_blank" rel="noopener noreferrer" class="">Ethereum roadmap page</a> is kept reasonably current. For client-level updates, the <a href="https://github.com/ethereum/pm" target="_blank" rel="noopener noreferrer" class="">AllCoreDevs call notes</a> are published after each meeting and are the most reliable source for what's actually being decided.</p>
<hr>
<p>Sources:</p>
<ul>
<li class=""><a href="https://www.coindesk.com/tech/2026/03/25/ethereum-foundation-prepares-for-quantum-threat-with-new-cryptography-roadmap" target="_blank" rel="noopener noreferrer" class="">Ethereum Foundation launches post-quantum security hub</a></li>
<li class=""><a href="https://www.coindesk.com/tech/2026/03/25/the-protocol-ethereum-faces-make-or-break-moment-as-scaling-quantum-and-ai-pressures-mount" target="_blank" rel="noopener noreferrer" class="">The Protocol: Ethereum roadmap updates so far in 2026</a></li>
<li class=""><a href="https://blog.quicknode.com/ethereum-glamsterdam-upgrade-whats-coming-in-h1-2026/" target="_blank" rel="noopener noreferrer" class="">Ethereum Glamsterdam upgrade explained</a></li>
<li class=""><a href="https://www.datawallet.com/crypto/ethereum-glamsterdam-upgrade-explained" target="_blank" rel="noopener noreferrer" class="">Glamsterdam EIPs breakdown</a></li>
<li class=""><a href="https://www.mexc.com/news/879536" target="_blank" rel="noopener noreferrer" class="">Top actively developed crypto projects, March 2026</a></li>
<li class=""><a href="https://www.analyticsinsight.net/ethereum/ethereums-2026-roadmap-scaling-security-and-quantum-readiness-explained" target="_blank" rel="noopener noreferrer" class="">Ethereum post-quantum cryptography roadmap</a></li>
</ul>]]></content:encoded>
            <category>Ethereum</category>
            <category>Blockchain</category>
            <category>Security</category>
            <category>Layer 2</category>
        </item>
        <item>
            <title><![CDATA[Solidity 0.8.x: what changed and why it matters]]></title>
            <link>https://franroberts.site/blog/solidity-0-8-changes/</link>
            <guid>https://franroberts.site/blog/solidity-0-8-changes/</guid>
            <pubDate>Wed, 04 Feb 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[The jump from Solidity 0.7 to 0.8 was more significant than most version bumps. The biggest change was built-in overflow checking, but there were others that affected both how you write contracts and how you reason about security. Here's a practical rundown of the 0.8.x series changes that are still relevant.]]></description>
            <content:encoded><![CDATA[<p>The jump from Solidity 0.7 to 0.8 was more significant than most version bumps. The biggest change was built-in overflow checking, but there were others that affected both how you write contracts and how you reason about security. Here's a practical rundown of the 0.8.x series changes that are still relevant.</p>
<p><a href="https://docs.soliditylang.org/en/latest/changelog.html" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/images/ef-logo.png" alt="Solidity language documentation" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="overflow-and-underflow-checking">Overflow and underflow checking<a href="https://franroberts.site/blog/solidity-0-8-changes/#overflow-and-underflow-checking" class="hash-link" aria-label="Direct link to Overflow and underflow checking" title="Direct link to Overflow and underflow checking" translate="no">​</a></h2>
<p>Before 0.8, arithmetic on <code>uint</code> and <code>int</code> types would silently wrap around on overflow. This was the source of real vulnerabilities. The infamous BEC token exploit in 2018 used integer overflow to mint billions of tokens from thin air.</p>
<p>In 0.8.0, overflow and underflow cause a revert automatically:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">uint256 a = type(uint256).max;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">uint256 b = a + 1; // Reverts in 0.8, wraps to 0 in 0.7</span><br></span></code></pre></div></div>
<p>The <code>SafeMath</code> library from OpenZeppelin was the standard way to handle this in 0.7 and earlier. In 0.8.x, you don't need it for basic arithmetic. OpenZeppelin still maintains it for compatibility but it's functionally redundant now.</p>
<p>If you intentionally need wrapping arithmetic (for bit manipulation or certain hashing patterns), use the <code>unchecked</code> block:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">function increment(uint256 x) external pure returns (uint256) {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    unchecked {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        return x + 1; // Will wrap on overflow, no revert</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Using <code>unchecked</code> is also a gas optimization. The overflow check has a cost. For loops where you can guarantee no overflow, <code>unchecked { i++; }</code> is a common pattern.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="custom-errors-084">Custom errors (0.8.4)<a href="https://franroberts.site/blog/solidity-0-8-changes/#custom-errors-084" class="hash-link" aria-label="Direct link to Custom errors (0.8.4)" title="Direct link to Custom errors (0.8.4)" translate="no">​</a></h2>
<p>Described in an earlier post, but worth repeating here for completeness. Custom errors are significantly cheaper than string reverts and more informative than empty reverts:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">error Unauthorized(address caller, bytes32 requiredRole);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">function adminFunction() external {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    if (!hasRole(ADMIN_ROLE, msg.sender)) {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        revert Unauthorized(msg.sender, ADMIN_ROLE);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Error selectors are 4 bytes. A string revert encoding "Unauthorized" is much larger.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="immutable-variables-080-improved-in-086">Immutable variables (0.8.0, improved in 0.8.6)<a href="https://franroberts.site/blog/solidity-0-8-changes/#immutable-variables-080-improved-in-086" class="hash-link" aria-label="Direct link to Immutable variables (0.8.0, improved in 0.8.6)" title="Direct link to Immutable variables (0.8.0, improved in 0.8.6)" translate="no">​</a></h2>
<p><code>immutable</code> was introduced before 0.8 but solidified in this series. Variables declared <code>immutable</code> can be set in the constructor and nowhere else. They're read from bytecode rather than storage, saving gas:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract MyContract {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    address public immutable owner;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    uint256 public immutable deploymentBlock;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    constructor() {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        owner = msg.sender;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        deploymentBlock = block.number;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>From 0.8.8 onward, <code>immutable</code> variables don't need to be initialized in every code path of the constructor. Earlier versions required initialization on all paths.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="user-defined-value-types-088">User-defined value types (0.8.8)<a href="https://franroberts.site/blog/solidity-0-8-changes/#user-defined-value-types-088" class="hash-link" aria-label="Direct link to User-defined value types (0.8.8)" title="Direct link to User-defined value types (0.8.8)" translate="no">​</a></h2>
<p>You can now define types that wrap primitive types:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">type Price is uint128;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">type TokenId is uint256;</span><br></span></code></pre></div></div>
<p>These are distinct types at the Solidity level. You can't accidentally pass a <code>Price</code> where a <code>TokenId</code> is expected. Zero runtime overhead.</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">function transfer(TokenId id, address to) external { ... }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">Price p = Price.wrap(100);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">TokenId t = TokenId.wrap(1);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">transfer(p, msg.sender); // Compile error: wrong type</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">transfer(t, msg.sender); // Works</span><br></span></code></pre></div></div>
<p>Useful for contracts that deal with many different numeric types and where accidental type confusion would be a bug.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="using-a-for-b-global-0813"><code>using A for B</code> global (0.8.13)<a href="https://franroberts.site/blog/solidity-0-8-changes/#using-a-for-b-global-0813" class="hash-link" aria-label="Direct link to using-a-for-b-global-0813" title="Direct link to using-a-for-b-global-0813" translate="no">​</a></h2>
<p>Previously, <code>using SafeERC20 for IERC20</code> only applied within the contract that declared it. From 0.8.13, you can declare library usage at the file level and it applies throughout:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">// At file level, not inside a contract</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">using SafeERC20 for IERC20 global;</span><br></span></code></pre></div></div>
<p>Mostly a convenience feature for large codebases.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="named-parameters-in-function-calls-0818">Named parameters in function calls (0.8.18)<a href="https://franroberts.site/blog/solidity-0-8-changes/#named-parameters-in-function-calls-0818" class="hash-link" aria-label="Direct link to Named parameters in function calls (0.8.18)" title="Direct link to Named parameters in function calls (0.8.18)" translate="no">​</a></h2>
<p>You can name arguments in function calls, similar to named parameters in Python:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">function createOrder(address token, uint256 amount, uint256 deadline) external { }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">// Named call, order doesn't matter</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">createOrder({ deadline: block.timestamp + 1 days, token: USDC, amount: 1000e6 });</span><br></span></code></pre></div></div>
<p>Helpful for functions with many parameters where the order isn't obvious.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="checking-your-version">Checking your version<a href="https://franroberts.site/blog/solidity-0-8-changes/#checking-your-version" class="hash-link" aria-label="Direct link to Checking your version" title="Direct link to Checking your version" translate="no">​</a></h2>
<p>The <a href="https://docs.soliditylang.org/en/latest/changelog.html" target="_blank" rel="noopener noreferrer" class="">Solidity changelog</a> is the authoritative record. For a specific feature, it's the fastest way to check which version introduced it. When inheriting a codebase, look at the pragma version and cross-reference against the changelog to understand which features and behaviors apply.</p>
<p>Most active projects target 0.8.20 or later. Older codebases sometimes pin to 0.6 or 0.7 for stability or because they rely on pre-0.8 behavior. Always check the pragma before assuming 0.8 defaults apply.</p>]]></content:encoded>
            <category>Solidity</category>
            <category>Ethereum</category>
            <category>Security</category>
        </item>
        <item>
            <title><![CDATA[Wallet UX and the MetaMask developer API]]></title>
            <link>https://franroberts.site/blog/metamask-developer-api/</link>
            <guid>https://franroberts.site/blog/metamask-developer-api/</guid>
            <pubDate>Mon, 15 Dec 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[MetaMask has around 30 million monthly active users. For most Ethereum applications, it's the primary wallet. Understanding what the MetaMask API can actually do helps you build a better user experience, and knowing its limitations helps you avoid building around them.]]></description>
            <content:encoded><![CDATA[<p>MetaMask has around 30 million monthly active users. For most Ethereum applications, it's the primary wallet. Understanding what the MetaMask API can actually do helps you build a better user experience, and knowing its limitations helps you avoid building around them.</p>
<p><a href="https://docs.metamask.io/wallet/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://docs.metamask.io/img/metamask-logo.svg" alt="MetaMask developer documentation" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-provider-object">The provider object<a href="https://franroberts.site/blog/metamask-developer-api/#the-provider-object" class="hash-link" aria-label="Direct link to The provider object" title="Direct link to The provider object" translate="no">​</a></h2>
<p>MetaMask injects a provider object into the browser at <code>window.ethereum</code>. This is how your application communicates with the user's wallet. The basic pattern:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">if</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">typeof</span><span class="token plain"> </span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token plain"> </span><span class="token operator">===</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"undefined"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token comment" style="color:rgb(98, 114, 164)">// MetaMask not installed</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">return</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token comment" style="color:rgb(98, 114, 164)">// Request account access</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> accounts </span><span class="token operator">=</span><span class="token plain"> </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">await</span><span class="token plain"> </span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">request</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">method</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"eth_requestAccounts"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> address </span><span class="token operator">=</span><span class="token plain"> accounts</span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token number">0</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><br></span></code></pre></div></div>
<p><code>eth_requestAccounts</code> prompts the user to connect. After connecting, you have the user's address but nothing else. You can't sign transactions or messages without explicit user approval for each action.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="checking-the-network">Checking the network<a href="https://franroberts.site/blog/metamask-developer-api/#checking-the-network" class="hash-link" aria-label="Direct link to Checking the network" title="Direct link to Checking the network" translate="no">​</a></h2>
<p>Users aren't always on the network your application expects. Check and handle the mismatch:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> chainId </span><span class="token operator">=</span><span class="token plain"> </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">await</span><span class="token plain"> </span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">request</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> </span><span class="token literal-property property">method</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"eth_chainId"</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">if</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">chainId </span><span class="token operator">!==</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"0x1"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token comment" style="color:rgb(98, 114, 164)">// Not on Ethereum mainnet</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">try</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">await</span><span class="token plain"> </span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">request</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">method</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"wallet_switchEthereumChain"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">params</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> </span><span class="token literal-property property">chainId</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"0x1"</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">catch</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">error</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">if</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">error</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">code</span><span class="token plain"> </span><span class="token operator">===</span><span class="token plain"> </span><span class="token number">4902</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token comment" style="color:rgb(98, 114, 164)">// Chain not added to MetaMask</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><br></span></code></pre></div></div>
<p>Listen for network changes too:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">on</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token string" style="color:rgb(255, 121, 198)">"chainChanged"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token parameter">chainId</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token arrow operator">=&gt;</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">location</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">reload</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"> </span><span class="token comment" style="color:rgb(98, 114, 164)">// simplest approach</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="sending-transactions">Sending transactions<a href="https://franroberts.site/blog/metamask-developer-api/#sending-transactions" class="hash-link" aria-label="Direct link to Sending transactions" title="Direct link to Sending transactions" translate="no">​</a></h2>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> txHash </span><span class="token operator">=</span><span class="token plain"> </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">await</span><span class="token plain"> </span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">request</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">method</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"eth_sendTransaction"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">params</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token keyword module" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token operator">:</span><span class="token plain"> address</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">to</span><span class="token operator">:</span><span class="token plain"> contractAddress</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">data</span><span class="token operator">:</span><span class="token plain"> encodedCalldata</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">value</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"0x0"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><br></span></code></pre></div></div>
<p>MetaMask pops up a confirmation dialog showing the transaction details and estimated gas. The user approves or rejects. You get the transaction hash back (not a receipt; you still need to wait for the transaction to be mined).</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="eth_signtypeddata_v4">eth_signTypedData_v4<a href="https://franroberts.site/blog/metamask-developer-api/#eth_signtypeddata_v4" class="hash-link" aria-label="Direct link to eth_signTypedData_v4" title="Direct link to eth_signTypedData_v4" translate="no">​</a></h2>
<p>For signing structured data (EIP-712), use <code>eth_signTypedData_v4</code>. This produces a user-friendly signature prompt that shows the decoded data fields rather than a raw hex string.</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> signature </span><span class="token operator">=</span><span class="token plain"> </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">await</span><span class="token plain"> </span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">request</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">method</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"eth_signTypedData_v4"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">params</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    address</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token known-class-name class-name">JSON</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">stringify</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">domain</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> </span><span class="token literal-property property">name</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"MyApp"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token literal-property property">version</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"1"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token literal-property property">chainId</span><span class="token operator">:</span><span class="token plain"> </span><span class="token number">1</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token literal-property property">verifyingContract</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"0x..."</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">types</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        </span><span class="token literal-property property">Order</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">          </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> </span><span class="token literal-property property">name</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"amount"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token literal-property property">type</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"uint256"</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">          </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> </span><span class="token literal-property property">name</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"token"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token literal-property property">type</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"address"</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        </span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">primaryType</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"Order"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">message</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> </span><span class="token literal-property property">amount</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"1000000"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token literal-property property">token</span><span class="token operator">:</span><span class="token plain"> tokenAddress </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><br></span></code></pre></div></div>
<p>Permit signatures (EIP-2612) use this pattern to allow spending without a separate <code>approve</code> transaction.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="metamask-snaps">MetaMask Snaps<a href="https://franroberts.site/blog/metamask-developer-api/#metamask-snaps" class="hash-link" aria-label="Direct link to MetaMask Snaps" title="Direct link to MetaMask Snaps" translate="no">​</a></h2>
<p>MetaMask Snaps allow third-party developers to extend MetaMask's functionality. A Snap is a sandboxed JavaScript program that runs inside MetaMask and can:</p>
<ul>
<li class="">Display custom UI in transaction confirmation dialogs</li>
<li class="">Support non-EVM chains</li>
<li class="">Add custom RPC methods</li>
<li class="">Manage key derivation for other chains</li>
</ul>
<p>The <a href="https://docs.metamask.io/snaps/" target="_blank" rel="noopener noreferrer" class="">MetaMask Snaps documentation</a> covers the full API. Snaps require user approval to install and run in a restricted environment.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="common-ux-mistakes">Common UX mistakes<a href="https://franroberts.site/blog/metamask-developer-api/#common-ux-mistakes" class="hash-link" aria-label="Direct link to Common UX mistakes" title="Direct link to Common UX mistakes" translate="no">​</a></h2>
<p><strong>Don't assume the user is connected.</strong> The connected state can change. Listen for <code>accountsChanged</code> events.</p>
<p><strong>Don't block the whole UI if MetaMask isn't installed.</strong> Offer a link to install and allow users to browse without connecting.</p>
<p><strong>Minimize signature requests.</strong> Every MetaMask popup is friction. Batch operations where you can. Use off-chain signatures (EIP-712) for actions that don't need immediate on-chain settlement.</p>
<p><strong>Show transaction status.</strong> MetaMask's confirmation dialog disappears once the user approves. Your UI needs to show pending, confirmed, and failed states using the transaction hash.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="using-viem-or-ethers-instead-of-raw-windowethereum">Using viem or ethers instead of raw window.ethereum<a href="https://franroberts.site/blog/metamask-developer-api/#using-viem-or-ethers-instead-of-raw-windowethereum" class="hash-link" aria-label="Direct link to Using viem or ethers instead of raw window.ethereum" title="Direct link to Using viem or ethers instead of raw window.ethereum" translate="no">​</a></h2>
<p>Working directly with <code>window.ethereum</code> is low-level. Libraries like viem and ethers.js wrap it with better types and abstractions:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword module" style="color:rgb(189, 147, 249);font-style:italic">import</span><span class="token plain"> </span><span class="token imports punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token imports"> createWalletClient</span><span class="token imports punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token imports"> custom </span><span class="token imports punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword module" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"viem"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword module" style="color:rgb(189, 147, 249);font-style:italic">import</span><span class="token plain"> </span><span class="token imports punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token imports"> mainnet </span><span class="token imports punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword module" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"viem/chains"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> client </span><span class="token operator">=</span><span class="token plain"> </span><span class="token function" style="color:rgb(80, 250, 123)">createWalletClient</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">chain</span><span class="token operator">:</span><span class="token plain"> mainnet</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">transport</span><span class="token operator">:</span><span class="token plain"> </span><span class="token function" style="color:rgb(80, 250, 123)">custom</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token dom variable" style="color:rgb(189, 147, 249);font-style:italic">window</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">ethereum</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><br></span></code></pre></div></div>
<p>The <a href="https://docs.metamask.io/wallet/" target="_blank" rel="noopener noreferrer" class="">MetaMask developer documentation</a> is the authoritative reference for the full API including the Snaps API and the MetaMask institutional API for enterprise use.</p>]]></content:encoded>
            <category>Ethereum</category>
            <category>Tooling</category>
        </item>
        <item>
            <title><![CDATA[Understanding account abstraction (EIP-4337)]]></title>
            <link>https://franroberts.site/blog/account-abstraction-eip4337/</link>
            <guid>https://franroberts.site/blog/account-abstraction-eip4337/</guid>
            <pubDate>Tue, 07 Oct 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Account abstraction has been discussed in Ethereum for years. EIP-4337 implemented it without requiring a protocol change, which is why it shipped when others didn't. If you're building wallet infrastructure or any user-facing application that involves transactions, understanding AA is becoming essential.]]></description>
            <content:encoded><![CDATA[<p>Account abstraction has been discussed in Ethereum for years. EIP-4337 implemented it without requiring a protocol change, which is why it shipped when others didn't. If you're building wallet infrastructure or any user-facing application that involves transactions, understanding AA is becoming essential.</p>
<p><a href="https://docs.erc4337.io/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://docs.erc4337.io/assets/images/ERC-4337-team-logo-white.png" alt="ERC-4337 account abstraction standard" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-problem-with-eoas">The problem with EOAs<a href="https://franroberts.site/blog/account-abstraction-eip4337/#the-problem-with-eoas" class="hash-link" aria-label="Direct link to The problem with EOAs" title="Direct link to The problem with EOAs" translate="no">​</a></h2>
<p>Ethereum has two account types: externally owned accounts (EOAs) and contract accounts. EOAs are controlled by a private key. Contract accounts run code.</p>
<p>The limitations of EOAs have frustrated users and developers:</p>
<ul>
<li class="">One key controls everything. Lose the key, lose the account.</li>
<li class="">Transactions must be signed by the private key. No multi-sig natively.</li>
<li class="">Gas must be paid in ETH. Users holding only ERC-20 tokens can't transact.</li>
<li class="">No batching. Multiple operations require multiple transactions.</li>
<li class="">No automation. Scheduled or conditional transactions aren't possible.</li>
</ul>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="eip-4337s-approach">EIP-4337's approach<a href="https://franroberts.site/blog/account-abstraction-eip4337/#eip-4337s-approach" class="hash-link" aria-label="Direct link to EIP-4337's approach" title="Direct link to EIP-4337's approach" translate="no">​</a></h2>
<p>Rather than modifying the Ethereum protocol, EIP-4337 introduces a new transaction type called a <code>UserOperation</code>. Users submit UserOperations to a mempool of bundlers. Bundlers aggregate them into a regular transaction that calls an EntryPoint contract.</p>
<p>The EntryPoint contract:</p>
<ol>
<li class="">Validates each UserOperation against its wallet contract</li>
<li class="">Calls the wallet contract to execute the operation</li>
<li class="">Handles gas payment, possibly from a Paymaster</li>
</ol>
<p>The key insight: validation and execution are delegated to a smart contract wallet. That contract defines its own rules for what a valid operation looks like. This enables custom signature schemes, multi-sig, session keys, and more.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="key-components">Key components<a href="https://franroberts.site/blog/account-abstraction-eip4337/#key-components" class="hash-link" aria-label="Direct link to Key components" title="Direct link to Key components" translate="no">​</a></h2>
<p><strong>Smart contract wallet</strong>: your account is a contract. It can have any validation logic. Common examples: Safe (Gnosis Safe), Biconomy smart wallets, ZeroDev kernel wallets.</p>
<p><strong>Bundler</strong>: aggregates UserOperations and submits them to the EntryPoint. Acts like a miner/validator for the AA mempool. Must be MEV-aware. <a href="https://www.stackup.sh/" target="_blank" rel="noopener noreferrer" class="">Stackup</a> and <a href="https://www.pimlico.io/dashboard" target="_blank" rel="noopener noreferrer" class="">Pimlico</a> provide bundler infrastructure.</p>
<p><strong>Paymaster</strong>: a contract that sponsors gas for users. Enables gasless transactions (the dapp pays) or payment in ERC-20 tokens. The Paymaster deposits ETH into the EntryPoint to cover gas costs. The <a href="https://dashboard.pimlico.io/" target="_blank" rel="noopener noreferrer" class="">Pimlico dashboard</a> lets you manage Paymaster balances and see sponsored transaction activity.</p>
<p><strong>EntryPoint</strong>: the singleton contract that all AA transactions go through. Audited by OpenZeppelin and others. Currently at version 0.7. The <a href="https://github.com/eth-infinitism/account-abstraction" target="_blank" rel="noopener noreferrer" class="">EntryPoint contract source</a> is the reference implementation.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="building-with-eip-4337">Building with EIP-4337<a href="https://franroberts.site/blog/account-abstraction-eip4337/#building-with-eip-4337" class="hash-link" aria-label="Direct link to Building with EIP-4337" title="Direct link to Building with EIP-4337" translate="no">​</a></h2>
<p>To create a smart wallet and send UserOperations, most teams use an SDK rather than implementing the low-level protocol directly.</p>
<p>Using the Biconomy SDK:</p>
<div class="language-typescript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-typescript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">import</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> createSmartAccountClient </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"@biconomy/account"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">import</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> createWalletClient</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> http </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"viem"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> smartAccount </span><span class="token operator">=</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">await</span><span class="token plain"> </span><span class="token function" style="color:rgb(80, 250, 123)">createSmartAccountClient</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  signer</span><span class="token operator">:</span><span class="token plain"> walletClient</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  bundlerUrl</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"https://bundler.biconomy.io/api/v2/1/YOUR_KEY"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  paymasterUrl</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"https://paymaster.biconomy.io/api/v1/1/YOUR_KEY"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token comment" style="color:rgb(98, 114, 164)">// Send a transaction (gas paid by paymaster)</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> tx </span><span class="token operator">=</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">await</span><span class="token plain"> smartAccount</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token function" style="color:rgb(80, 250, 123)">sendTransaction</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  to</span><span class="token operator">:</span><span class="token plain"> recipientAddress</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  value</span><span class="token operator">:</span><span class="token plain"> </span><span class="token function" style="color:rgb(80, 250, 123)">parseEther</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token string" style="color:rgb(255, 121, 198)">"0.1"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><br></span></code></pre></div></div>
<p>The <a href="https://docs.biconomy.io/" target="_blank" rel="noopener noreferrer" class="">Biconomy documentation</a> covers the full integration, including session keys (delegated signing permissions) and batched transactions.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="session-keys">Session keys<a href="https://franroberts.site/blog/account-abstraction-eip4337/#session-keys" class="hash-link" aria-label="Direct link to Session keys" title="Direct link to Session keys" translate="no">​</a></h2>
<p>One of the most useful AA primitives for gaming and DeFi. Instead of signing every transaction with your main key, you delegate limited permissions to a "session key" for a period of time.</p>
<p>For example: allow this session key to call <code>approve</code> on this specific token contract, up to 100 USDC, for the next 24 hours. The session key can sign transactions within those permissions without bothering the user. The main key can revoke the session key at any time.</p>
<p>This is how most web3 games avoid the "approve every action" UX problem.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="where-aa-stands-now">Where AA stands now<a href="https://franroberts.site/blog/account-abstraction-eip4337/#where-aa-stands-now" class="hash-link" aria-label="Direct link to Where AA stands now" title="Direct link to Where AA stands now" translate="no">​</a></h2>
<p>EIP-4337 is live on mainnet and all major L2s. The infrastructure is maturing. Bundler availability and Paymaster services are increasingly reliable. The main limitation is that AA wallets are newer and have smaller recovery ecosystems than traditional hardware wallets.</p>
<p>Native account abstraction (where the protocol itself natively supports smart wallets without the workaround) is planned for future Ethereum upgrades, including EIP-7702 which allows EOAs to temporarily behave like smart wallets.</p>
<p>The <a href="https://www.erc4337.io/" target="_blank" rel="noopener noreferrer" class="">ERC-4337 resources page</a> maintains a list of compatible wallets, bundlers, and paymasters.</p>]]></content:encoded>
            <category>Ethereum</category>
            <category>Blockchain</category>
        </item>
        <item>
            <title><![CDATA[Testing DeFi protocols with Foundry]]></title>
            <link>https://franroberts.site/blog/testing-defi-foundry/</link>
            <guid>https://franroberts.site/blog/testing-defi-foundry/</guid>
            <pubDate>Fri, 22 Aug 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Foundry has become a serious alternative to Hardhat for smart contract development, and for testing DeFi protocols specifically, it has some compelling advantages. Tests are written in Solidity, the fork feature is fast, and fuzzing is built in without additional setup. Here's a practical overview of how to use it effectively.]]></description>
            <content:encoded><![CDATA[<p>Foundry has become a serious alternative to Hardhat for smart contract development, and for testing DeFi protocols specifically, it has some compelling advantages. Tests are written in Solidity, the fork feature is fast, and fuzzing is built in without additional setup. Here's a practical overview of how to use it effectively.</p>
<p><a href="https://getfoundry.sh/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/images/ef-logo.png" alt="Foundry: fast Ethereum development toolkit" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="why-foundry-for-defi-testing">Why Foundry for DeFi testing<a href="https://franroberts.site/blog/testing-defi-foundry/#why-foundry-for-defi-testing" class="hash-link" aria-label="Direct link to Why Foundry for DeFi testing" title="Direct link to Why Foundry for DeFi testing" translate="no">​</a></h2>
<p>The main appeal is writing tests in Solidity rather than JavaScript. For testing complex DeFi interactions, you don't have to bridge the mental model between the contract code and the test code. You use the same types, the same patterns.</p>
<p>The other big advantage is speed. Foundry's test runner (Forge) is significantly faster than Hardhat for large test suites. When you're running hundreds of tests with mainnet forks, this matters.</p>
<p>The <a href="https://book.getfoundry.sh/" target="_blank" rel="noopener noreferrer" class="">Foundry book</a> is the primary documentation and is genuinely comprehensive.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="project-setup">Project setup<a href="https://franroberts.site/blog/testing-defi-foundry/#project-setup" class="hash-link" aria-label="Direct link to Project setup" title="Direct link to Project setup" translate="no">​</a></h2>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">curl -L https://foundry.paradigm.xyz | bash</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">foundryup</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">forge init my-project</span><br></span></code></pre></div></div>
<p>Project structure:</p>
<div class="language-text codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-text codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">src/          Contract source files</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">test/         Test files (*.t.sol convention)</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">script/       Deployment and interaction scripts</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">lib/          Dependencies installed via forge install</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="basic-test-structure">Basic test structure<a href="https://franroberts.site/blog/testing-defi-foundry/#basic-test-structure" class="hash-link" aria-label="Direct link to Basic test structure" title="Direct link to Basic test structure" translate="no">​</a></h2>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">// test/MyProtocol.t.sol</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">pragma solidity ^0.8.24;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">import {Test} from "forge-std/Test.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">import {MyProtocol} from "../src/MyProtocol.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract MyProtocolTest is Test {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    MyProtocol protocol;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    address user = makeAddr("user");</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function setUp() public {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        protocol = new MyProtocol();</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        vm.deal(user, 10 ether); // give the test user some ETH</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function test_depositAndWithdraw() public {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        vm.prank(user);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        protocol.deposit{value: 1 ether}();</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        assertEq(protocol.balanceOf(user), 1 ether);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        vm.prank(user);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        protocol.withdraw(1 ether);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        assertEq(protocol.balanceOf(user), 0);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p><code>vm.prank</code> makes the next call come from a specified address. <code>vm.deal</code> sets an address's ETH balance. <code>makeAddr</code> creates a deterministic test address from a label.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="forking-mainnet">Forking mainnet<a href="https://franroberts.site/blog/testing-defi-foundry/#forking-mainnet" class="hash-link" aria-label="Direct link to Forking mainnet" title="Direct link to Forking mainnet" translate="no">​</a></h2>
<p>Foundry's fork support lets you test against real mainnet state:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">forge test --fork-url $MAINNET_RPC_URL</span><br></span></code></pre></div></div>
<p>Or pin to a specific block for reproducibility:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">forge test --fork-url $MAINNET_RPC_URL --fork-block-number 20000000</span><br></span></code></pre></div></div>
<p>In your test, you can also fork at a specific point and then manipulate state:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">function test_liquidation() public {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    address borrower = 0xabc...; // a real mainnet address</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    vm.deal(borrower, 0);        // drain ETH to force undercollateralization</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    // Check the liquidation works</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    protocol.liquidate(borrower);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="fuzzing">Fuzzing<a href="https://franroberts.site/blog/testing-defi-foundry/#fuzzing" class="hash-link" aria-label="Direct link to Fuzzing" title="Direct link to Fuzzing" translate="no">​</a></h2>
<p>Foundry runs property-based fuzzing automatically on functions prefixed with <code>testFuzz_</code>:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">function testFuzz_depositAmount(uint256 amount) public {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    vm.assume(amount &gt; 0 &amp;&amp; amount &lt;= 100 ether);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    vm.deal(user, amount);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    vm.prank(user);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    protocol.deposit{value: amount}();</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    assertEq(protocol.balanceOf(user), amount);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Foundry generates random inputs and tries to find a failing case. The default run count is 256; increase it with <code>--fuzz-runs</code> for more thorough testing.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="invariant-testing">Invariant testing<a href="https://franroberts.site/blog/testing-defi-foundry/#invariant-testing" class="hash-link" aria-label="Direct link to Invariant testing" title="Direct link to Invariant testing" translate="no">​</a></h2>
<p>Invariant tests define properties that must hold true across any sequence of function calls. More powerful than fuzzing individual functions:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract ProtocolInvariantTest is Test {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    MyProtocol protocol;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function setUp() public {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        protocol = new MyProtocol();</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        targetContract(address(protocol));</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    // This function is called after every random sequence of transactions</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function invariant_solvency() public view {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        // Total deposits must always be &gt;= total withdrawals</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        assertGe(address(protocol).balance, protocol.totalDeposits());</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Foundry randomly calls functions on the target contracts and checks the invariant after each sequence. This catches bugs that unit tests miss.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="useful-cheatcodes-for-defi">Useful cheatcodes for DeFi<a href="https://franroberts.site/blog/testing-defi-foundry/#useful-cheatcodes-for-defi" class="hash-link" aria-label="Direct link to Useful cheatcodes for DeFi" title="Direct link to Useful cheatcodes for DeFi" translate="no">​</a></h2>
<p>Beyond <code>vm.prank</code> and <code>vm.deal</code>:</p>
<ul>
<li class=""><code>vm.warp(timestamp)</code>: set <code>block.timestamp</code></li>
<li class=""><code>vm.roll(blockNumber)</code>: set <code>block.number</code></li>
<li class=""><code>vm.expectRevert()</code>: assert the next call reverts</li>
<li class=""><code>vm.expectEmit()</code>: assert a specific event is emitted</li>
<li class=""><code>deal(token, address, amount)</code>: set an ERC-20 token balance for an address</li>
</ul>
<p>The full cheatcode reference is in the <a href="https://book.getfoundry.sh/cheatcodes/" target="_blank" rel="noopener noreferrer" class="">Forge standard library docs</a>.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="gas-snapshots">Gas snapshots<a href="https://franroberts.site/blog/testing-defi-foundry/#gas-snapshots" class="hash-link" aria-label="Direct link to Gas snapshots" title="Direct link to Gas snapshots" translate="no">​</a></h2>
<p>Foundry tracks gas usage and can fail tests if gas increases unexpectedly:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">forge snapshot           # Creates .gas-snapshot</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">forge snapshot --check   # Fails if gas increased vs snapshot</span><br></span></code></pre></div></div>
<p>Useful for catching accidental regressions in gas efficiency.</p>
<p>Foundry and Hardhat aren't mutually exclusive. Many teams use Foundry for Solidity tests and Hardhat for deployment scripts and JavaScript integrations. The tools compose reasonably well.</p>]]></content:encoded>
            <category>DeFi</category>
            <category>Tooling</category>
            <category>Solidity</category>
        </item>
        <item>
            <title><![CDATA[Polygon zkEVM: what developers need to know]]></title>
            <link>https://franroberts.site/blog/polygon-zkevm-developers/</link>
            <guid>https://franroberts.site/blog/polygon-zkevm-developers/</guid>
            <pubDate>Thu, 03 Jul 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Polygon zkEVM has been in production on mainnet since March 2023. It's a ZK rollup that aims for full EVM equivalence, meaning existing Solidity contracts and Ethereum tooling should work without modification. Here's a practical assessment of where it stands and what you actually need to know before deploying.]]></description>
            <content:encoded><![CDATA[<p>Polygon zkEVM has been in production on mainnet since March 2023. It's a ZK rollup that aims for full EVM equivalence, meaning existing Solidity contracts and Ethereum tooling should work without modification. Here's a practical assessment of where it stands and what you actually need to know before deploying.</p>
<p><a href="https://docs.polygon.technology/zkEVM/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://docs.polygon.technology/img/zkEVM/zkevm.svg" alt="Polygon zkEVM architecture diagram" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-evm-equivalence-means-in-practice">What "EVM equivalence" means in practice<a href="https://franroberts.site/blog/polygon-zkevm-developers/#what-evm-equivalence-means-in-practice" class="hash-link" aria-label="Direct link to What &quot;EVM equivalence&quot; means in practice" title="Direct link to What &quot;EVM equivalence&quot; means in practice" translate="no">​</a></h2>
<p>There are several degrees of EVM compatibility in the ZK rollup space:</p>
<ul>
<li class=""><strong>EVM compatible</strong>: supports Solidity but may have differences in opcodes or behavior</li>
<li class=""><strong>EVM equivalent</strong>: matches Ethereum's EVM behavior as closely as possible</li>
<li class=""><strong>Type 2 zkEVM</strong>: Vitalik's classification for rollups that match EVM behavior but may differ at the Ethereum node level</li>
</ul>
<p>Polygon zkEVM targets Type 2 equivalence. In practice this means most contracts deploy without changes, but there are edge cases. The <a href="https://docs.polygon.technology/zkEVM/" target="_blank" rel="noopener noreferrer" class="">Polygon zkEVM documentation</a> maintains a compatibility reference.</p>
<p>Known differences: the SELFDESTRUCT opcode behaves differently (it doesn't actually delete the contract in the same way). Some precompile behaviors differ. For contracts that don't touch these edges, deployment is straightforward.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="setting-up-your-development-environment">Setting up your development environment<a href="https://franroberts.site/blog/polygon-zkevm-developers/#setting-up-your-development-environment" class="hash-link" aria-label="Direct link to Setting up your development environment" title="Direct link to Setting up your development environment" translate="no">​</a></h2>
<p>The network details for Polygon zkEVM mainnet:</p>
<ul>
<li class="">Chain ID: 1101</li>
<li class="">RPC URL: <code>https://zkevm-rpc.com</code></li>
<li class="">Block explorer: <a href="https://zkevm.polygonscan.com/" target="_blank" rel="noopener noreferrer" class="">zkevm.polygonscan.com</a></li>
</ul>
<p>For testnet (Cardona):</p>
<ul>
<li class="">Chain ID: 2442</li>
<li class="">RPC URL: <code>https://rpc.cardona.zkevm-rpc.com</code></li>
</ul>
<p>Add these to your Hardhat config:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token literal-property property">networks</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">polygonZkEVM</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">url</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"https://zkevm-rpc.com"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">accounts</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token plain">process</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">env</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token constant" style="color:rgb(189, 147, 249)">PRIVATE_KEY</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">chainId</span><span class="token operator">:</span><span class="token plain"> </span><span class="token number">1101</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">polygonZkEVMTestnet</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">url</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"https://rpc.cardona.zkevm-rpc.com"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">accounts</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token plain">process</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">env</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token constant" style="color:rgb(189, 147, 249)">PRIVATE_KEY</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">chainId</span><span class="token operator">:</span><span class="token plain"> </span><span class="token number">2442</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="bridging-to-polygon-zkevm">Bridging to Polygon zkEVM<a href="https://franroberts.site/blog/polygon-zkevm-developers/#bridging-to-polygon-zkevm" class="hash-link" aria-label="Direct link to Bridging to Polygon zkEVM" title="Direct link to Bridging to Polygon zkEVM" translate="no">​</a></h2>
<p>Assets move between Ethereum mainnet and Polygon zkEVM via the official bridge. The <a href="https://bridge.zkevm-rpc.com/" target="_blank" rel="noopener noreferrer" class="">Polygon zkEVM bridge interface</a> handles the UI. Withdrawals are faster than optimistic rollups because ZK proofs don't require a challenge period. In practice, batch proof generation means withdrawals take a few hours, not 7 days.</p>
<p>The bridge contract is on mainnet at a verified address. Always use the official bridge rather than third-party bridges for significant amounts.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="gas-on-polygon-zkevm">Gas on Polygon zkEVM<a href="https://franroberts.site/blog/polygon-zkevm-developers/#gas-on-polygon-zkevm" class="hash-link" aria-label="Direct link to Gas on Polygon zkEVM" title="Direct link to Gas on Polygon zkEVM" translate="no">​</a></h2>
<p>Gas is priced in ETH (the same token as Ethereum mainnet). Fee levels are significantly lower than mainnet, though they vary based on L1 data publication costs. The <a href="https://gasstation.polygon.technology/zkevm" target="_blank" rel="noopener noreferrer" class="">zkEVM gas station</a> gives current fee estimates.</p>
<p>Polygon zkEVM batches many L2 transactions into a single L1 transaction. The L2 fee you pay partially reflects the amortized cost of that L1 batch. When L1 gas prices spike, L2 fees increase.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="contract-verification">Contract verification<a href="https://franroberts.site/blog/polygon-zkevm-developers/#contract-verification" class="hash-link" aria-label="Direct link to Contract verification" title="Direct link to Contract verification" translate="no">​</a></h2>
<p>Use the <a href="https://zkevm.polygonscan.com/" target="_blank" rel="noopener noreferrer" class="">Polygon zkEVM block explorer</a> for contract verification, or configure Hardhat's verify plugin:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token literal-property property">etherscan</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">apiKey</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">polygonZkEVM</span><span class="token operator">:</span><span class="token plain"> process</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">env</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token constant" style="color:rgb(189, 147, 249)">POLYGONSCAN_API_KEY</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">customChains</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">network</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"polygonZkEVM"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">chainId</span><span class="token operator">:</span><span class="token plain"> </span><span class="token number">1101</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">urls</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        </span><span class="token literal-property property">apiURL</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"https://api-zkevm.polygonscan.com/api"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        </span><span class="token literal-property property">browserURL</span><span class="token operator">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"https://zkevm.polygonscan.com"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="how-proof-generation-works">How proof generation works<a href="https://franroberts.site/blog/polygon-zkevm-developers/#how-proof-generation-works" class="hash-link" aria-label="Direct link to How proof generation works" title="Direct link to How proof generation works" translate="no">​</a></h2>
<p>Polygon zkEVM uses a prover to generate ZK validity proofs for transaction batches. The prover is computationally intensive and runs on Polygon's infrastructure (not decentralized yet). Proofs are submitted to an on-chain verifier contract on Ethereum mainnet.</p>
<p>The proving system is based on PLONK and the Hermez proving scheme. The <a href="https://docs.polygon.technology/zkEVM/spec/zkasm/" target="_blank" rel="noopener noreferrer" class="">zkEVM technical specification</a> goes deep on the internals if you need to understand how EVM opcodes map to ZK circuits.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="comparing-to-arbitrum-and-optimism">Comparing to Arbitrum and Optimism<a href="https://franroberts.site/blog/polygon-zkevm-developers/#comparing-to-arbitrum-and-optimism" class="hash-link" aria-label="Direct link to Comparing to Arbitrum and Optimism" title="Direct link to Comparing to Arbitrum and Optimism" translate="no">​</a></h2>
<p>For application developers, the main differences:</p>
<p>Polygon zkEVM: faster withdrawals, ZK-based security, newer ecosystem, smaller TVL
Arbitrum/Optimism: larger ecosystem, more liquidity, longer track record, 7-day optimistic withdrawal period</p>
<p>The choice usually comes down to which ecosystem your users are in. If you're starting fresh, both are reasonable choices. Running on multiple chains with a unified frontend is common.</p>]]></content:encoded>
            <category>Layer 2</category>
            <category>Ethereum</category>
            <category>Tooling</category>
        </item>
        <item>
            <title><![CDATA[Writing good blockchain documentation]]></title>
            <link>https://franroberts.site/blog/writing-blockchain-documentation/</link>
            <guid>https://franroberts.site/blog/writing-blockchain-documentation/</guid>
            <pubDate>Mon, 19 May 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Blockchain documentation is uniquely difficult to write well. The audience spans protocol researchers who think in cryptographic primitives and developers who just want to make a transaction. The technology changes faster than most documentation teams can keep up with. And incorrect documentation can have direct financial consequences in a way that most software docs don't. Here's what I've learned writing in this space.]]></description>
            <content:encoded><![CDATA[<p>Blockchain documentation is uniquely difficult to write well. The audience spans protocol researchers who think in cryptographic primitives and developers who just want to make a transaction. The technology changes faster than most documentation teams can keep up with. And incorrect documentation can have direct financial consequences in a way that most software docs don't. Here's what I've learned writing in this space.</p>
<p><a href="https://ethereum.org/en/developers/docs/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/images/ef-logo.png" alt="Ethereum developer documentation" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="know-which-layer-youre-documenting">Know which layer you're documenting<a href="https://franroberts.site/blog/writing-blockchain-documentation/#know-which-layer-youre-documenting" class="hash-link" aria-label="Direct link to Know which layer you're documenting" title="Direct link to Know which layer you're documenting" translate="no">​</a></h2>
<p>Blockchain stack layers have distinct audiences and different documentation needs:</p>
<p><strong>Protocol layer</strong>: consensus, peer-to-peer networking, cryptography. Audience is researchers and core developers. Precision matters more than accessibility. The <a href="https://ethereum.github.io/yellowpaper/paper.pdf" target="_blank" rel="noopener noreferrer" class="">Ethereum Yellow Paper</a> is protocol-layer documentation at its most rigorous.</p>
<p><strong>Developer tooling</strong>: smart contract development, deployment, testing. Audience is engineers building applications. Concrete examples and working code matter most. Hardhat and Foundry do this well.</p>
<p><strong>Application layer</strong>: wallets, DeFi protocols, NFT platforms. Audience is end users who may have no technical background. Clarity and consequence-awareness matter. Most protocols underinvest here.</p>
<p>The mistake is writing for the wrong layer. Developer documentation written for a non-technical audience is condescending and useless. Application documentation written for developers leaves users confused about what they're actually clicking.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="code-samples-are-non-negotiable">Code samples are non-negotiable<a href="https://franroberts.site/blog/writing-blockchain-documentation/#code-samples-are-non-negotiable" class="hash-link" aria-label="Direct link to Code samples are non-negotiable" title="Direct link to Code samples are non-negotiable" translate="no">​</a></h2>
<p>In blockchain documentation, a code sample that doesn't work is worse than no code sample. It creates false confidence. Someone copies it, deploys it, and learns on mainnet that it's wrong.</p>
<p>Test every code sample. For Solidity, that means compiling it and ideally running it against a test. For JavaScript that interacts with contracts, test it against a local node.</p>
<p>Hardhat and Foundry both make this easier. The <a href="https://github.com/NomicFoundation/hardhat/tree/main/docs" target="_blank" rel="noopener noreferrer" class="">Hardhat documentation repository</a> shows how they keep their own docs tested. For SDK documentation, connecting examples to an automated test suite is the gold standard.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="version-everything">Version everything<a href="https://franroberts.site/blog/writing-blockchain-documentation/#version-everything" class="hash-link" aria-label="Direct link to Version everything" title="Direct link to Version everything" translate="no">​</a></h2>
<p>Solidity changes. Library interfaces change. Network upgrades change assumptions. Documentation that doesn't say which version it applies to is unreliable for anyone who reads it six months later.</p>
<p>Minimum: put a "last updated" date and a version on every significant page. Better: use versioned documentation that's tied to library releases. Docusaurus (which this site uses) supports versioned docs natively.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="address-the-user-dashboard-early">Address the user dashboard early<a href="https://franroberts.site/blog/writing-blockchain-documentation/#address-the-user-dashboard-early" class="hash-link" aria-label="Direct link to Address the user dashboard early" title="Direct link to Address the user dashboard early" translate="no">​</a></h2>
<p>For protocols with a user interface, documentation that only covers the API or SDK is missing most users. The people who interact with a DeFi protocol through its dashboard vastly outnumber developers integrating it. Write the dashboard documentation first, or at minimum, give it equal weight.</p>
<p>Good examples:</p>
<ul>
<li class=""><a href="https://support.uniswap.org/hc/en-us" target="_blank" rel="noopener noreferrer" class="">Uniswap interface documentation</a></li>
<li class=""><a href="https://docs.aave.com/faq/" target="_blank" rel="noopener noreferrer" class="">Aave user guides</a></li>
<li class=""><a href="https://support.metamask.io/" target="_blank" rel="noopener noreferrer" class="">MetaMask user documentation</a></li>
</ul>
<p>These are written for people who don't know what an ABI is. They explain the consequences of actions ("you will pay gas," "this transaction cannot be undone") not just the mechanics.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="explain-what-can-go-wrong">Explain what can go wrong<a href="https://franroberts.site/blog/writing-blockchain-documentation/#explain-what-can-go-wrong" class="hash-link" aria-label="Direct link to Explain what can go wrong" title="Direct link to Explain what can go wrong" translate="no">​</a></h2>
<p>Blockchain transactions are irreversible. Documentation that only explains the happy path is incomplete. For every significant action:</p>
<ul>
<li class="">What happens if the transaction fails? (funds returned? partial execution?)</li>
<li class="">What are the gas cost estimates and what affects them?</li>
<li class="">What are the time constraints?</li>
<li class="">What are the security considerations?</li>
</ul>
<p>The <a href="https://ethereum.org/en/developers/docs/" target="_blank" rel="noopener noreferrer" class="">Ethereum.org documentation</a> does this reasonably well for core concepts. For protocol-specific docs, it's rarer.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="handling-deprecations">Handling deprecations<a href="https://franroberts.site/blog/writing-blockchain-documentation/#handling-deprecations" class="hash-link" aria-label="Direct link to Handling deprecations" title="Direct link to Handling deprecations" translate="no">​</a></h2>
<p>Old blockchain documentation doesn't go away. It gets indexed, linked to, and found. If you deprecate a function or change a pattern, actively redirect. Don't just add a notice to the old page. Change the URL to redirect, update your changelog, and if the old pattern was dangerous, explain why.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="write-for-skeptical-readers">Write for skeptical readers<a href="https://franroberts.site/blog/writing-blockchain-documentation/#write-for-skeptical-readers" class="hash-link" aria-label="Direct link to Write for skeptical readers" title="Direct link to Write for skeptical readers" translate="no">​</a></h2>
<p>Blockchain documentation readers have often been burned before. They're reading carefully because they're about to do something with financial consequences. Write for that level of attention.</p>
<p>That means: say what something does exactly, not what it's "designed to do" or "intended to do." State limitations explicitly. If there's a known edge case, document it even if it's rare. Link to the relevant contract or code so readers can verify claims.</p>
<p>Trust is harder to build and easier to lose in this space than in typical software documentation.</p>]]></content:encoded>
            <category>Blockchain</category>
            <category>Tooling</category>
        </item>
        <item>
            <title><![CDATA[MEV and transaction ordering]]></title>
            <link>https://franroberts.site/blog/mev-transaction-ordering/</link>
            <guid>https://franroberts.site/blog/mev-transaction-ordering/</guid>
            <pubDate>Fri, 25 Apr 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[MEV (maximal extractable value, formerly "miner extractable value") is one of those topics that seems like an obscure research area until you realize it affects almost every transaction on Ethereum. If you're building DeFi protocols or have wondered why your transactions sometimes get sandwiched, this is worth understanding.]]></description>
            <content:encoded><![CDATA[<p>MEV (maximal extractable value, formerly "miner extractable value") is one of those topics that seems like an obscure research area until you realize it affects almost every transaction on Ethereum. If you're building DeFi protocols or have wondered why your transactions sometimes get sandwiched, this is worth understanding.</p>
<p><a href="https://transparency.flashbots.net/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://www.flashbots.net/badge.svg" alt="Flashbots MEV transparency dashboard" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-mev-is">What MEV is<a href="https://franroberts.site/blog/mev-transaction-ordering/#what-mev-is" class="hash-link" aria-label="Direct link to What MEV is" title="Direct link to What MEV is" translate="no">​</a></h2>
<p>Ethereum validators (and previously miners) choose which transactions to include in a block and in what order. MEV is the additional revenue that can be extracted by manipulating this ordering.</p>
<p>The simple version: if your transaction will move a price, a searcher can insert their own transactions before and after yours to profit from the movement at your expense.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-sandwich-attack">The sandwich attack<a href="https://franroberts.site/blog/mev-transaction-ordering/#the-sandwich-attack" class="hash-link" aria-label="Direct link to The sandwich attack" title="Direct link to The sandwich attack" translate="no">​</a></h2>
<p>The most visible form of MEV for regular users. You submit a transaction to swap token A for token B on a DEX. A searcher (bot) sees your pending transaction in the mempool and:</p>
<ol>
<li class="">Buys token B before your transaction executes (front-runs, moving the price against you)</li>
<li class="">Your transaction executes at the worse price</li>
<li class="">The searcher sells token B after your transaction (back-runs, at the new higher price)</li>
</ol>
<p>The searcher profits. You got a worse price than expected. Your DEX's slippage tolerance determines how much you can lose.</p>
<p>Setting a low slippage tolerance helps, but if the tolerance is too tight, legitimate transactions fail during volatile periods.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="arbitrage-mev">Arbitrage MEV<a href="https://franroberts.site/blog/mev-transaction-ordering/#arbitrage-mev" class="hash-link" aria-label="Direct link to Arbitrage MEV" title="Direct link to Arbitrage MEV" translate="no">​</a></h2>
<p>Not all MEV is harmful to users. Arbitrage between DEXes is MEV that improves market efficiency. If ETH is cheaper on Uniswap than on Curve, a searcher's arbitrage transaction corrects the discrepancy. This is MEV but it benefits the market.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="liquidation-mev">Liquidation MEV<a href="https://franroberts.site/blog/mev-transaction-ordering/#liquidation-mev" class="hash-link" aria-label="Direct link to Liquidation MEV" title="Direct link to Liquidation MEV" translate="no">​</a></h2>
<p>In lending protocols (Aave, Compound), undercollateralized positions can be liquidated by anyone who calls the liquidation function first. Searchers monitor positions and compete to be first when a position becomes liquidatable. The competition is good for the protocol (positions get liquidated promptly) but searchers extract the liquidation bonus.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-mev-supply-chain">The MEV supply chain<a href="https://franroberts.site/blog/mev-transaction-ordering/#the-mev-supply-chain" class="hash-link" aria-label="Direct link to The MEV supply chain" title="Direct link to The MEV supply chain" translate="no">​</a></h2>
<p>Pre-merge, miners received MEV extraction tools directly. Post-merge, the structure is more complex:</p>
<ul>
<li class=""><strong>Searchers</strong>: bots that identify MEV opportunities and craft transactions</li>
<li class=""><strong>Builders</strong>: aggregate transactions from searchers and the public mempool into blocks, optimizing for revenue</li>
<li class=""><strong>Validators</strong>: choose which built block to propose, typically accepting the highest payment</li>
</ul>
<p>MEV-Boost, developed by Flashbots, is the dominant system. Validators run MEV-Boost as middleware and accept blocks from external builders. Around 90% of Ethereum blocks are built with MEV-Boost.</p>
<p>The <a href="https://transparency.flashbots.net/" target="_blank" rel="noopener noreferrer" class="">Flashbots dashboard</a> tracks MEV-Boost adoption, block builder market share, and MEV activity in real time.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="flashbots-and-private-mempools">Flashbots and private mempools<a href="https://franroberts.site/blog/mev-transaction-ordering/#flashbots-and-private-mempools" class="hash-link" aria-label="Direct link to Flashbots and private mempools" title="Direct link to Flashbots and private mempools" translate="no">​</a></h2>
<p>Flashbots created a private mempool (mev-share) where searchers submit transaction bundles directly to block builders. This keeps transactions out of the public mempool where they'd be visible to competing searchers. For users, <a href="https://protect.flashbots.net/" target="_blank" rel="noopener noreferrer" class="">Flashbots Protect</a> routes transactions through this private channel to reduce sandwich attack exposure.</p>
<p>Most major wallets and DEX aggregators have built in some form of MEV protection by default.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="for-defi-developers">For DeFi developers<a href="https://franroberts.site/blog/mev-transaction-ordering/#for-defi-developers" class="hash-link" aria-label="Direct link to For DeFi developers" title="Direct link to For DeFi developers" translate="no">​</a></h2>
<p>If you're building a DEX or protocol that involves large price moves, think about MEV at the design level:</p>
<ul>
<li class="">Commit-reveal schemes prevent front-running for certain actions</li>
<li class="">Batch auctions (like CoW Protocol uses) prevent sandwich attacks by settling all trades in a batch at a uniform clearing price</li>
<li class="">TWAP oracles spread price updates over time, reducing the value of single-block manipulation</li>
</ul>
<p>The <a href="https://eigenphi.io/" target="_blank" rel="noopener noreferrer" class="">EigenPhi MEV dashboard</a> is useful for analyzing MEV activity on specific protocols. Before launch, simulate what a searcher would do with your protocol's functions.</p>
<p>MEV isn't going away. The question for protocol designers is whether the MEV your protocol creates benefits users, harms them, or can be redirected back to the protocol itself.</p>]]></content:encoded>
            <category>Ethereum</category>
            <category>Blockchain</category>
        </item>
        <item>
            <title><![CDATA[Cross-chain bridge security]]></title>
            <link>https://franroberts.site/blog/cross-chain-bridge-security/</link>
            <guid>https://franroberts.site/blog/cross-chain-bridge-security/</guid>
            <pubDate>Fri, 14 Mar 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Cross-chain bridges have been the single biggest source of losses in DeFi. The Ronin bridge lost $625 million. Wormhole lost $320 million. Nomad lost $190 million. These aren't edge cases. Bridges are genuinely hard to secure, and understanding why is useful if you're building anything that crosses chains.]]></description>
            <content:encoded><![CDATA[<p>Cross-chain bridges have been the single biggest source of losses in DeFi. The Ronin bridge lost $625 million. Wormhole lost $320 million. Nomad lost $190 million. These aren't edge cases. Bridges are genuinely hard to secure, and understanding why is useful if you're building anything that crosses chains.</p>
<p><a href="https://l2beat.com/bridges/summary" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://l2beat.com/meta-images/publications/interoperability-page.png" alt="L2Beat bridge risk assessment" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="why-bridges-exist">Why bridges exist<a href="https://franroberts.site/blog/cross-chain-bridge-security/#why-bridges-exist" class="hash-link" aria-label="Direct link to Why bridges exist" title="Direct link to Why bridges exist" translate="no">​</a></h2>
<p>Blockchains don't natively communicate with each other. Bitcoin doesn't know about Ethereum's state. Arbitrum's state is separate from mainnet's even though it settles there. Bridges allow assets to move between chains by representing assets from one chain on another.</p>
<p>The basic pattern: lock assets on the source chain, mint a representative token on the destination chain. To go back, burn the representative token and unlock the original.</p>
<p>The security question: who decides that the lock happened and the mint is authorized?</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-trust-spectrum">The trust spectrum<a href="https://franroberts.site/blog/cross-chain-bridge-security/#the-trust-spectrum" class="hash-link" aria-label="Direct link to The trust spectrum" title="Direct link to The trust spectrum" translate="no">​</a></h2>
<p>Bridges sit on a spectrum from trust-minimized to highly trusted:</p>
<p><strong>Native bridges</strong> (like Optimism's official bridge) use the rollup's own security mechanism. To withdraw from Optimism to mainnet, you submit a proof verified by the Ethereum settlement contract. There's a 7-day challenge period for optimistic proofs. Trust assumption: the rollup protocol itself. The <a href="https://docs.optimism.io/builders/app-developers/bridging/standard-bridge" target="_blank" rel="noopener noreferrer" class="">Optimism bridge documentation</a> describes how this works.</p>
<p><strong>Light client bridges</strong> verify block headers of the source chain on the destination chain. Expensive but closer to trustless. Near Rainbow Bridge works this way.</p>
<p><strong>Multisig bridges</strong> use a set of validators who must reach consensus before minting on the destination chain. Ronin used a multisig with 9 validators, 5 of which were Axie Infinity team members. An attacker compromised 5 keys. This is the common failure mode.</p>
<p><strong>Oracle/relayer bridges</strong> trust a set of relayers to pass messages between chains. Nomad had a bug in its merkle root verification that allowed any message to be forged. Once discovered, anyone could copy the exploit transaction and drain the bridge.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="common-vulnerability-patterns">Common vulnerability patterns<a href="https://franroberts.site/blog/cross-chain-bridge-security/#common-vulnerability-patterns" class="hash-link" aria-label="Direct link to Common vulnerability patterns" title="Direct link to Common vulnerability patterns" translate="no">​</a></h2>
<p><strong>Private key compromise</strong>: validators' private keys are stolen or leaked. Best mitigation: hardware security modules (HSMs), geographic and organizational distribution of key holders, and minimizing how many entities need to hold keys.</p>
<p><strong>Smart contract bugs</strong>: logic errors in the bridge contract itself. Wormhole's exploit was a signature verification bypass. Thorough auditing and formal verification reduce this risk but can't eliminate it.</p>
<p><strong>Governance attacks</strong>: if the bridge is upgradeable and upgrade control is held by a small group, an attacker who gains control of that group can upgrade the contract to steal funds.</p>
<p><strong>Replay attacks</strong>: a message signed for one chain can be replayed on another if chain IDs aren't correctly included in signatures.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-better-looks-like">What better looks like<a href="https://franroberts.site/blog/cross-chain-bridge-security/#what-better-looks-like" class="hash-link" aria-label="Direct link to What better looks like" title="Direct link to What better looks like" translate="no">​</a></h2>
<p>The safest bridges for large value transfer are currently the native rollup bridges, which inherit Ethereum's security. They're slower for withdrawals but the trust assumptions are the same as Ethereum itself.</p>
<p>For speed with reasonable security, ZK bridges are improving. A ZK validity proof can verify that events happened on the source chain without a challenge period. zkBridge research from Berkeley and commercial implementations from projects like Succinct Labs are pushing this forward.</p>
<p>The <a href="https://l2beat.com/bridges/summary" target="_blank" rel="noopener noreferrer" class="">L2Beat bridge risk assessment</a> scores bridges on their security model. It's a useful reference before routing large amounts through an unfamiliar bridge.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="for-developers-building-on-top-of-bridges">For developers building on top of bridges<a href="https://franroberts.site/blog/cross-chain-bridge-security/#for-developers-building-on-top-of-bridges" class="hash-link" aria-label="Direct link to For developers building on top of bridges" title="Direct link to For developers building on top of bridges" translate="no">​</a></h2>
<p>If your protocol assumes bridged assets will always be 1:1 with their source chain counterparts, a bridge exploit can leave you holding depegged tokens. Think through what happens if a bridge you rely on is compromised:</p>
<ul>
<li class="">Does your contract accept any ERC-20 claiming to be wETH?</li>
<li class="">Do you have any assumptions about token supply being bounded?</li>
<li class="">What happens if liquidity disappears from a pool you depend on?</li>
</ul>
<p>These aren't hypotheticals. They've happened to protocols that didn't think through bridge failure modes.</p>]]></content:encoded>
            <category>Blockchain</category>
            <category>Security</category>
            <category>Layer 2</category>
        </item>
        <item>
            <title><![CDATA[Running a local Ethereum node]]></title>
            <link>https://franroberts.site/blog/running-ethereum-node/</link>
            <guid>https://franroberts.site/blog/running-ethereum-node/</guid>
            <pubDate>Fri, 28 Feb 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Running your own Ethereum node is worth doing at least once even if you end up using a hosted RPC service in production. The visibility you get into how the network actually works is useful, and in some contexts having your own node is important for reliability or privacy.]]></description>
            <content:encoded><![CDATA[<p>Running your own Ethereum node is worth doing at least once even if you end up using a hosted RPC service in production. The visibility you get into how the network actually works is useful, and in some contexts having your own node is important for reliability or privacy.</p>
<p><a href="https://ethereum.org/en/developers/docs/nodes-and-clients/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/content/developers/docs/nodes-and-clients/eth1eth2client.png" alt="Ethereum execution and consensus client architecture" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-kind-of-node">What kind of node?<a href="https://franroberts.site/blog/running-ethereum-node/#what-kind-of-node" class="hash-link" aria-label="Direct link to What kind of node?" title="Direct link to What kind of node?" translate="no">​</a></h2>
<p>There are a few distinct roles:</p>
<p><strong>Full node</strong>: stores the entire blockchain state and validates all transactions and blocks. Can serve RPC requests. Does not participate in consensus. This is what you want for development and general use.</p>
<p><strong>Archive node</strong>: stores all historical states (not just current state). Required for queries like "what was the balance of address X at block 15,000,000." Much larger storage requirement (several TB for Ethereum mainnet).</p>
<p><strong>Validator node</strong>: participates in proof-of-stake consensus by proposing and attesting to blocks. Requires 32 ETH staked. Different operational concerns than a full node.</p>
<p>For development work, you usually want a local development node (Hardhat or Anvil) rather than a mainnet node. For querying mainnet state, a hosted RPC or your own synced node.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="client-diversity">Client diversity<a href="https://franroberts.site/blog/running-ethereum-node/#client-diversity" class="hash-link" aria-label="Direct link to Client diversity" title="Direct link to Client diversity" translate="no">​</a></h2>
<p>Post-merge, an Ethereum node is actually two clients: an execution client and a consensus client.</p>
<p><strong>Execution clients</strong> handle EVM execution, the transaction pool, and the JSON-RPC interface:</p>
<ul>
<li class="">Geth (Go Ethereum): most widely used</li>
<li class="">Nethermind (C#)</li>
<li class="">Besu (Java)</li>
<li class="">Reth (Rust): newer, growing in adoption</li>
</ul>
<p><strong>Consensus clients</strong> handle proof-of-stake consensus, block proposals, and attestations:</p>
<ul>
<li class="">Lighthouse (Rust)</li>
<li class="">Prysm (Go)</li>
<li class="">Teku (Java)</li>
<li class="">Lodestar (TypeScript)</li>
</ul>
<p>The Ethereum Foundation tracks client diversity at <a href="https://clientdiversity.org/" target="_blank" rel="noopener noreferrer" class="">clientdiversity.org</a>. Geth dominates the execution layer, which is a genuine risk to the network. If you're running a node, using an alternative execution client contributes to resilience.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="running-geth-locally">Running Geth locally<a href="https://franroberts.site/blog/running-ethereum-node/#running-geth-locally" class="hash-link" aria-label="Direct link to Running Geth locally" title="Direct link to Running Geth locally" translate="no">​</a></h2>
<p>Install Geth from <a href="https://geth.ethereum.org/downloads" target="_blank" rel="noopener noreferrer" class="">geth.ethereum.org</a>:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain"># Sync mainnet (takes days)</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">geth --syncmode snap</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"># Or sync a testnet (much faster)</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">geth --sepolia --syncmode snap</span><br></span></code></pre></div></div>
<p>Snap sync downloads recent state without replaying all historical blocks. It's the default and fastest way to get a synced node.</p>
<p>Geth exposes a JSON-RPC interface by default:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">geth --http --http.api eth,net,web3</span><br></span></code></pre></div></div>
<p>You can then point your local tools at <code>http://localhost:8545</code>.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-geth-dashboard">The Geth dashboard<a href="https://franroberts.site/blog/running-ethereum-node/#the-geth-dashboard" class="hash-link" aria-label="Direct link to The Geth dashboard" title="Direct link to The Geth dashboard" translate="no">​</a></h2>
<p>Geth includes a monitoring dashboard accessible via <code>geth attach</code>:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">geth attach http://localhost:8545</span><br></span></code></pre></div></div>
<p>This opens a JavaScript console where you can query the node directly:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">eth</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">blockNumber</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">eth</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">getBalance</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token string" style="color:rgb(255, 121, 198)">"0x..."</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">eth</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">syncing</span><br></span></code></pre></div></div>
<p>For a web dashboard, <a href="https://ethstats.net/" target="_blank" rel="noopener noreferrer" class="">Ethstats</a> tracks nodes that have opted in. The <a href="https://github.com/fjl/geth-metrics" target="_blank" rel="noopener noreferrer" class="">Grafana dashboards maintained by Ethereum Foundation</a> work with Geth's Prometheus metrics for more detailed monitoring.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="anvil-for-local-development">Anvil for local development<a href="https://franroberts.site/blog/running-ethereum-node/#anvil-for-local-development" class="hash-link" aria-label="Direct link to Anvil for local development" title="Direct link to Anvil for local development" translate="no">​</a></h2>
<p>For development, Anvil (part of Foundry) is faster and more convenient than running Geth:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">anvil</span><br></span></code></pre></div></div>
<p>Anvil starts a local chain with 10 pre-funded accounts. You can configure block time, chain ID, and fork from mainnet state. For forking:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">anvil --fork-url https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY</span><br></span></code></pre></div></div>
<p>This gives you a local chain that starts from mainnet's current state. Transactions are instant and you can manipulate any account's balance or nonce.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="when-to-use-a-hosted-rpc">When to use a hosted RPC<a href="https://franroberts.site/blog/running-ethereum-node/#when-to-use-a-hosted-rpc" class="hash-link" aria-label="Direct link to When to use a hosted RPC" title="Direct link to When to use a hosted RPC" translate="no">​</a></h2>
<p>For production applications, most teams use hosted RPC providers: Alchemy, Infura, QuickNode, or similar. The tradeoffs compared to a self-hosted node:</p>
<ul>
<li class="">No hardware requirements or maintenance</li>
<li class="">SLAs and support</li>
<li class="">Additional APIs (NFT APIs, trace APIs, webhooks)</li>
<li class="">Privacy: the provider sees all your queries</li>
<li class="">Cost: free tiers are generous but scale-dependent</li>
</ul>
<p>The <a href="https://ethereum.org/en/developers/docs/nodes-and-clients/" target="_blank" rel="noopener noreferrer" class="">Ethereum node documentation</a> covers the full picture. Running a node is more accessible than it was a few years ago. A modern consumer machine with a 2TB SSD can sync and run mainnet comfortably.</p>]]></content:encoded>
            <category>Ethereum</category>
            <category>Tooling</category>
            <category>Blockchain</category>
        </item>
        <item>
            <title><![CDATA[NFT contract architecture beyond ERC-721]]></title>
            <link>https://franroberts.site/blog/nft-contract-architecture/</link>
            <guid>https://franroberts.site/blog/nft-contract-architecture/</guid>
            <pubDate>Fri, 17 Jan 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[ERC-721 gets most of the attention in NFT discussions because it's where the standard started. But the ecosystem has moved considerably since 2018. If you're building an NFT project now, you have better options depending on what you're actually trying to do.]]></description>
            <content:encoded><![CDATA[<p>ERC-721 gets most of the attention in NFT discussions because it's where the standard started. But the ecosystem has moved considerably since 2018. If you're building an NFT project now, you have better options depending on what you're actually trying to do.</p>
<p><a href="https://docs.openzeppelin.com/contracts/5.x/erc721" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://openzeppelin-docs-v2.netlify.app/social.png" alt="OpenZeppelin ERC-721 documentation" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="erc-721-basics">ERC-721 basics<a href="https://franroberts.site/blog/nft-contract-architecture/#erc-721-basics" class="hash-link" aria-label="Direct link to ERC-721 basics" title="Direct link to ERC-721 basics" translate="no">​</a></h2>
<p>The standard defines ownership: a token ID maps to an address, and the contract tracks who owns what. The minimal interface includes <code>ownerOf</code>, <code>balanceOf</code>, <code>transferFrom</code>, <code>approve</code>, and <code>setApprovalForAll</code>.</p>
<p>The <a href="https://eips.ethereum.org/EIPS/eip-721" target="_blank" rel="noopener noreferrer" class="">ERC-721 specification</a> is short enough to read in full. Understanding it before importing an implementation is worth the ten minutes.</p>
<p>The main implementation people use is OpenZeppelin's. The <a href="https://docs.openzeppelin.com/contracts/5.x/erc721" target="_blank" rel="noopener noreferrer" class="">ERC-721 docs</a> cover the extensions: <code>ERC721URIStorage</code> for per-token metadata URIs, <code>ERC721Enumerable</code> for on-chain enumeration (expensive but sometimes necessary), and <code>ERC721Burnable</code>.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-gas-cost-of-minting-at-scale">The gas cost of minting at scale<a href="https://franroberts.site/blog/nft-contract-architecture/#the-gas-cost-of-minting-at-scale" class="hash-link" aria-label="Direct link to The gas cost of minting at scale" title="Direct link to The gas cost of minting at scale" translate="no">​</a></h2>
<p>The core ERC-721 standard stores ownership in a mapping from token ID to address. Minting a token requires a write to this mapping: one <code>SSTORE</code> per mint, which is 20,000 gas for a new slot.</p>
<p>For a 10,000-piece collection where everyone mints at once, this adds up. The community has developed a few solutions.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="erc-721a">ERC-721A<a href="https://franroberts.site/blog/nft-contract-architecture/#erc-721a" class="hash-link" aria-label="Direct link to ERC-721A" title="Direct link to ERC-721A" translate="no">​</a></h2>
<p>Developed by the Azuki team, <a href="https://www.azuki.com/erc721a" target="_blank" rel="noopener noreferrer" class="">ERC-721A</a> optimizes for batch minting. Instead of writing ownership data for every token in a batch, it uses a lazy initialization scheme where ownership is inferred from sequential batch records.</p>
<p>The tradeoff: individual transfers cost slightly more because the contract may need to resolve implicit ownership. For mint-heavy, low-transfer scenarios (typical NFT drops), ERC-721A is a significant improvement.</p>
<p>The <a href="https://chiru-labs.github.io/ERC721A/" target="_blank" rel="noopener noreferrer" class="">ERC-721A documentation</a> covers the implementation details and how to use the library.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="erc-1155-for-multi-token-contracts">ERC-1155 for multi-token contracts<a href="https://franroberts.site/blog/nft-contract-architecture/#erc-1155-for-multi-token-contracts" class="hash-link" aria-label="Direct link to ERC-1155 for multi-token contracts" title="Direct link to ERC-1155 for multi-token contracts" translate="no">​</a></h2>
<p>ERC-1155 lets a single contract manage both fungible and non-fungible tokens. Instead of one contract per token type, you have one contract with multiple token IDs.</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract GameItems is ERC1155 {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    uint256 public constant GOLD = 0;     // fungible</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    uint256 public constant SWORD = 1;    // semi-fungible</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    uint256 public constant SHIELD = 2;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>ERC-1155 also supports batch transfers, which reduces gas costs when moving multiple token types at once.</p>
<p>For gaming applications where you have many item types and don't need each to be individually unique, ERC-1155 is usually more appropriate than ERC-721.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="on-chain-versus-off-chain-metadata">On-chain versus off-chain metadata<a href="https://franroberts.site/blog/nft-contract-architecture/#on-chain-versus-off-chain-metadata" class="hash-link" aria-label="Direct link to On-chain versus off-chain metadata" title="Direct link to On-chain versus off-chain metadata" translate="no">​</a></h2>
<p>The <code>tokenURI</code> function returns a URL pointing to a JSON file with the token's metadata (name, description, image). Where that JSON lives matters.</p>
<p><strong>Centralized server</strong>: easy to set up, easy to change, a single point of failure. If the server goes down, NFT marketplaces can't display the metadata.</p>
<p><strong>IPFS</strong>: content-addressed storage. The URI encodes the content hash, so the metadata can't be changed and can be served by anyone with a copy. The <a href="https://nft.storage/" target="_blank" rel="noopener noreferrer" class="">NFT Storage</a> service provides free IPFS pinning for NFT metadata.</p>
<p><strong>Fully on-chain</strong>: the metadata is stored in the contract itself, usually as base64-encoded SVG for the image. Expensive to deploy, impossible to change, completely decentralized. Projects like Nouns NFT use this approach.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="royalties">Royalties<a href="https://franroberts.site/blog/nft-contract-architecture/#royalties" class="hash-link" aria-label="Direct link to Royalties" title="Direct link to Royalties" translate="no">​</a></h2>
<p>ERC-2981 is the standard for on-chain royalty information. It adds a <code>royaltyInfo(tokenId, salePrice)</code> function that returns who should receive royalties and how much:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@openzeppelin/contracts/token/common/ERC2981.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract MyNFT is ERC721, ERC2981 {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    constructor() ERC721("MyNFT", "MNFT") {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        _setDefaultRoyalty(msg.sender, 500); // 5% in basis points</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Marketplace support for ERC-2981 is inconsistent. OpenSea, Blur, and others handle royalties in different ways with different enforcement mechanisms.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="testing-and-deployment">Testing and deployment<a href="https://franroberts.site/blog/nft-contract-architecture/#testing-and-deployment" class="hash-link" aria-label="Direct link to Testing and deployment" title="Direct link to Testing and deployment" translate="no">​</a></h2>
<p>For NFT projects with presales, whitelists, and public mints, structure your tests around the different sale phases. Each phase has different access control requirements and different minting logic. Testing them in isolation and in sequence both matter.</p>
<p>The <a href="https://book.getfoundry.sh/" target="_blank" rel="noopener noreferrer" class="">Foundry book</a> has good examples of testing NFT contracts. Foundry's <code>vm.prank</code> for impersonating accounts and <code>vm.deal</code> for setting ETH balances are particularly useful for mint testing.</p>]]></content:encoded>
            <category>NFT</category>
            <category>Solidity</category>
            <category>Ethereum</category>
        </item>
        <item>
            <title><![CDATA[How Chainlink oracles work]]></title>
            <link>https://franroberts.site/blog/chainlink-oracles/</link>
            <guid>https://franroberts.site/blog/chainlink-oracles/</guid>
            <pubDate>Sun, 08 Dec 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Oracles are one of the more misunderstood pieces of blockchain infrastructure. The blockchain itself has no access to off-chain data. It can't fetch an API, check a stock price, or know what the weather is. Oracles bridge that gap. Chainlink is the dominant oracle network, and understanding how it works matters if you're building anything that relies on external data.]]></description>
            <content:encoded><![CDATA[<p>Oracles are one of the more misunderstood pieces of blockchain infrastructure. The blockchain itself has no access to off-chain data. It can't fetch an API, check a stock price, or know what the weather is. Oracles bridge that gap. Chainlink is the dominant oracle network, and understanding how it works matters if you're building anything that relies on external data.</p>
<p><a href="https://docs.chain.link/data-feeds/price-feeds/addresses" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://docs.chain.link/images/logo.png" alt="Chainlink decentralized oracle network" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-oracle-problem">The oracle problem<a href="https://franroberts.site/blog/chainlink-oracles/#the-oracle-problem" class="hash-link" aria-label="Direct link to The oracle problem" title="Direct link to The oracle problem" translate="no">​</a></h2>
<p>A blockchain's strength is that every node independently verifies every computation. If a contract's logic depends on off-chain data (an asset price, for example), that data has to come from somewhere. Whoever provides the data can manipulate the outcome.</p>
<p>A centralized oracle just moves the trust problem. If one entity provides the price feed, they can lie. The solution is decentralization: aggregate data from multiple independent sources and use a consensus mechanism to produce a reliable value.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="how-chainlink-works">How Chainlink works<a href="https://franroberts.site/blog/chainlink-oracles/#how-chainlink-works" class="hash-link" aria-label="Direct link to How Chainlink works" title="Direct link to How Chainlink works" translate="no">​</a></h2>
<p>Chainlink runs a decentralized network of oracle nodes. For a price feed:</p>
<ol>
<li class="">Multiple independent node operators fetch data from several premium data providers</li>
<li class="">Nodes submit responses on-chain</li>
<li class="">A deviation threshold or heartbeat triggers an aggregation update</li>
<li class="">The on-chain aggregator contract computes a median value and makes it available</li>
</ol>
<p>The decentralization is meaningful. Corrupting a Chainlink feed would require compromising many independent node operators simultaneously. Not impossible, but expensive.</p>
<p>Node operators are required to hold LINK tokens as a stake. Bad behavior results in lost stake.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="reading-a-price-feed">Reading a price feed<a href="https://franroberts.site/blog/chainlink-oracles/#reading-a-price-feed" class="hash-link" aria-label="Direct link to Reading a price feed" title="Direct link to Reading a price feed" translate="no">​</a></h2>
<p>The API is simple:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract PriceConsumer {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    AggregatorV3Interface internal priceFeed;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    constructor() {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        // ETH/USD feed on mainnet</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function getLatestPrice() public view returns (int) {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        (</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">            uint80 roundId,</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">            int answer,</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">            uint startedAt,</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">            uint updatedAt,</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">            uint80 answeredInRound</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        ) = priceFeed.latestRoundData();</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        require(updatedAt &gt; 0, "Round not complete");</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        require(block.timestamp - updatedAt &lt; 1 hours, "Stale price");</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        return answer;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Two things worth noting: always check that <code>updatedAt</code> is recent (stale price check), and check that <code>answeredInRound &gt;= roundId</code> to catch edge cases where a round didn't complete properly.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="decimals">Decimals<a href="https://franroberts.site/blog/chainlink-oracles/#decimals" class="hash-link" aria-label="Direct link to Decimals" title="Direct link to Decimals" translate="no">​</a></h2>
<p>Chainlink feeds use different decimal places depending on the feed. Most price feeds use 8 decimals. Check the <code>decimals()</code> function on the aggregator, or look up the feed on the <a href="https://docs.chain.link/data-feeds/price-feeds/addresses" target="_blank" rel="noopener noreferrer" class="">Chainlink data feeds documentation</a>.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-chainlink-feed-registry">The Chainlink feed registry<a href="https://franroberts.site/blog/chainlink-oracles/#the-chainlink-feed-registry" class="hash-link" aria-label="Direct link to The Chainlink feed registry" title="Direct link to The Chainlink feed registry" translate="no">​</a></h2>
<p>For contracts that work with multiple assets, the <a href="https://docs.chain.link/data-feeds/feed-registry" target="_blank" rel="noopener noreferrer" class="">Feed Registry</a> lets you query any feed by base and quote currency rather than hardcoding individual feed addresses:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@chainlink/contracts/src/v0.8/interfaces/FeedRegistryInterface.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@chainlink/contracts/src/v0.8/Denominations.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">int256 price = registry.getPrice(Denominations.BTC, Denominations.USD);</span><br></span></code></pre></div></div>
<p>Available on Ethereum mainnet but not on all testnets.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="automation-formerly-keepers">Automation (formerly Keepers)<a href="https://franroberts.site/blog/chainlink-oracles/#automation-formerly-keepers" class="hash-link" aria-label="Direct link to Automation (formerly Keepers)" title="Direct link to Automation (formerly Keepers)" translate="no">​</a></h2>
<p>Chainlink also runs an automation network for triggering contract functions on a schedule or based on conditions. Instead of a centralized server calling your contract, Chainlink's network of nodes monitors your contract and calls it when conditions are met.</p>
<p>The <a href="https://automation.chain.link/" target="_blank" rel="noopener noreferrer" class="">Chainlink Automation dashboard</a> is where you register upkeeps and monitor their execution. Useful for things like liquidation bots, token rebasing, or any function that needs to run reliably without a centralized trigger.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="vrf">VRF<a href="https://franroberts.site/blog/chainlink-oracles/#vrf" class="hash-link" aria-label="Direct link to VRF" title="Direct link to VRF" translate="no">​</a></h2>
<p><a href="https://docs.chain.link/vrf" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://docs.chain.link/_astro/vrf-logo.DiFmClfi.svg" alt="Chainlink VRF" class="img_ev3q"></a></p>
<p>For verifiable randomness, Chainlink VRF provides random values that are cryptographically provable on-chain. The contract can verify that the random value wasn't manipulated by the oracle. The <a href="https://docs.chain.link/vrf" target="_blank" rel="noopener noreferrer" class="">VRF documentation</a> covers the integration, which is slightly more involved than price feeds because it uses a request-response pattern.</p>
<p>Most DeFi exploits that involved oracle manipulation used on-chain price manipulation (DEX spot prices) rather than compromised Chainlink feeds. That's not a coincidence.</p>]]></content:encoded>
            <category>DeFi</category>
            <category>Blockchain</category>
            <category>Ethereum</category>
        </item>
        <item>
            <title><![CDATA[Solidity tips I wish I knew earlier]]></title>
            <link>https://franroberts.site/blog/solidity-tips/</link>
            <guid>https://franroberts.site/blog/solidity-tips/</guid>
            <pubDate>Wed, 20 Nov 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Some things in Solidity are counterintuitive, and you tend to learn them the hard way. This is a collection of things that would have saved me time earlier. Not foundational concepts, just practical gotchas and shortcuts.]]></description>
            <content:encoded><![CDATA[<p>Some things in Solidity are counterintuitive, and you tend to learn them the hard way. This is a collection of things that would have saved me time earlier. Not foundational concepts, just practical gotchas and shortcuts.</p>
<p><a href="https://docs.soliditylang.org/en/latest/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/images/ef-logo.png" alt="Solidity language documentation" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="division-truncates-always">Division truncates, always<a href="https://franroberts.site/blog/solidity-tips/#division-truncates-always" class="hash-link" aria-label="Direct link to Division truncates, always" title="Direct link to Division truncates, always" translate="no">​</a></h2>
<p>Solidity has no floating point. Division always truncates toward zero. This is obvious once you know it, but it causes subtle bugs when you're not thinking about it.</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">// If a = 10, b = 3:</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">uint256 result = a / b; // result = 3, not 3.33...</span><br></span></code></pre></div></div>
<p>For calculations where precision matters, scale up before dividing. If you're computing a percentage, work in basis points (1 bps = 0.01%):</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">// 50% of amount using basis points</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">uint256 fee = (amount * 5000) / 10000;</span><br></span></code></pre></div></div>
<p>Divide last whenever possible.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="uint-is-uint256"><code>uint</code> is <code>uint256</code><a href="https://franroberts.site/blog/solidity-tips/#uint-is-uint256" class="hash-link" aria-label="Direct link to uint-is-uint256" title="Direct link to uint-is-uint256" translate="no">​</a></h2>
<p><code>uint</code> and <code>uint256</code> are the same type. Same for <code>int</code> and <code>int256</code>. I still write <code>uint256</code> explicitly for clarity, but you'll see both in the wild.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="custom-errors-are-cheaper-than-string-reverts">Custom errors are cheaper than string reverts<a href="https://franroberts.site/blog/solidity-tips/#custom-errors-are-cheaper-than-string-reverts" class="hash-link" aria-label="Direct link to Custom errors are cheaper than string reverts" title="Direct link to Custom errors are cheaper than string reverts" translate="no">​</a></h2>
<p>Before Solidity 0.8.4, you could only revert with a string:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">require(amount &gt; 0, "Amount must be positive");</span><br></span></code></pre></div></div>
<p>Strings are expensive in calldata. Custom errors cost much less:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">error AmountMustBePositive();</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">function deposit(uint256 amount) external {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    if (amount == 0) revert AmountMustBePositive();</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Custom errors also support parameters, which makes them more informative than strings for debugging:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">error InsufficientBalance(address user, uint256 available, uint256 requested);</span><br></span></code></pre></div></div>
<p>The <a href="https://docs.soliditylang.org/en/latest/contracts.html#errors-and-the-revert-statement" target="_blank" rel="noopener noreferrer" class="">Solidity docs on custom errors</a> have the full spec.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="function-visibility-defaults">Function visibility defaults<a href="https://franroberts.site/blog/solidity-tips/#function-visibility-defaults" class="hash-link" aria-label="Direct link to Function visibility defaults" title="Direct link to Function visibility defaults" translate="no">​</a></h2>
<p>If you don't specify visibility on a function, Solidity will refuse to compile in recent versions. But understanding the difference matters:</p>
<ul>
<li class=""><code>external</code>: can only be called from outside the contract (or via <code>this.functionName()</code> internally, which is awkward). More efficient than <code>public</code> because it can read calldata directly.</li>
<li class=""><code>public</code>: can be called externally and internally. Creates a getter automatically for state variables.</li>
<li class=""><code>internal</code>: like <code>protected</code> in other languages. Callable from the contract and derived contracts.</li>
<li class=""><code>private</code>: only from the contract itself.</li>
</ul>
<p>For functions that should be part of the public interface, use <code>external</code> by default and only upgrade to <code>public</code> if you need internal calls.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="immutable-versus-constant"><code>immutable</code> versus <code>constant</code><a href="https://franroberts.site/blog/solidity-tips/#immutable-versus-constant" class="hash-link" aria-label="Direct link to immutable-versus-constant" title="Direct link to immutable-versus-constant" translate="no">​</a></h2>
<p><code>constant</code> is for values known at compile time. <code>immutable</code> is for values set once in the constructor and never changed:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">uint256 public constant MAX_SUPPLY = 1_000_000e18;  // compile-time</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">address public immutable owner;                       // set in constructor</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">constructor() {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    owner = msg.sender;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Both avoid SLOAD costs (they're inlined). Use <code>constant</code> where you can, <code>immutable</code> where the value depends on deployment parameters.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="number-literals-with-underscores">Number literals with underscores<a href="https://franroberts.site/blog/solidity-tips/#number-literals-with-underscores" class="hash-link" aria-label="Direct link to Number literals with underscores" title="Direct link to Number literals with underscores" translate="no">​</a></h2>
<p>Solidity allows underscores in number literals as visual separators:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">uint256 public constant MAX = 1_000_000;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">uint256 public constant RATE = 1_500_000_000; // Easier to read than 1500000000</span><br></span></code></pre></div></div>
<p>No effect on the value, just readability.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="abiencode-versus-abiencodepacked"><code>abi.encode</code> versus <code>abi.encodePacked</code><a href="https://franroberts.site/blog/solidity-tips/#abiencode-versus-abiencodepacked" class="hash-link" aria-label="Direct link to abiencode-versus-abiencodepacked" title="Direct link to abiencode-versus-abiencodepacked" translate="no">​</a></h2>
<p><code>abi.encode</code> pads values to 32 bytes. <code>abi.encodePacked</code> concatenates without padding.</p>
<p><code>abi.encodePacked</code> is smaller but has a hash collision risk when used with dynamic types. For example, <code>encodePacked(["a", "bc"])</code> and <code>encodePacked(["ab", "c"])</code> produce the same output. Don't use <code>abi.encodePacked</code> with multiple dynamic values that users control.</p>
<p>For Merkle leaf hashing, double-hash the value to prevent second preimage attacks:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(addr))));</span><br></span></code></pre></div></div>
<p>OpenZeppelin's <code>@openzeppelin/merkle-tree</code> library does this automatically.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-solidity-docs-are-actually-good">The Solidity docs are actually good<a href="https://franroberts.site/blog/solidity-tips/#the-solidity-docs-are-actually-good" class="hash-link" aria-label="Direct link to The Solidity docs are actually good" title="Direct link to The Solidity docs are actually good" translate="no">​</a></h2>
<p>I put off reading the <a href="https://docs.soliditylang.org/en/latest/" target="_blank" rel="noopener noreferrer" class="">Solidity language reference</a> for too long. It's well-written and covers things you won't find in tutorials. Worth reading end-to-end at least once.</p>]]></content:encoded>
            <category>Solidity</category>
            <category>Ethereum</category>
            <category>Tooling</category>
        </item>
        <item>
            <title><![CDATA[DeFi protocol design patterns]]></title>
            <link>https://franroberts.site/blog/defi-design-patterns/</link>
            <guid>https://franroberts.site/blog/defi-design-patterns/</guid>
            <pubDate>Fri, 11 Oct 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[DeFi protocols deal with a specific combination of constraints that you don't encounter in most software: code that's public and immutable, assets that move automatically based on logic, and adversaries who will find and exploit any mistake. Patterns that work well in these conditions have emerged from a few years of production experience and some expensive failures.]]></description>
            <content:encoded><![CDATA[<p>DeFi protocols deal with a specific combination of constraints that you don't encounter in most software: code that's public and immutable, assets that move automatically based on logic, and adversaries who will find and exploit any mistake. Patterns that work well in these conditions have emerged from a few years of production experience and some expensive failures.</p>
<p><a href="https://docs.chain.link/data-feeds" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://docs.chain.link/images/logo.png" alt="Chainlink Data Feeds" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="checks-effects-interactions">Checks-effects-interactions<a href="https://franroberts.site/blog/defi-design-patterns/#checks-effects-interactions" class="hash-link" aria-label="Direct link to Checks-effects-interactions" title="Direct link to Checks-effects-interactions" translate="no">​</a></h2>
<p>This is the most fundamental pattern and the one most often violated by people new to Solidity.</p>
<p>The rule: in any function that modifies state and interacts with external contracts, do things in this order:</p>
<ol>
<li class=""><strong>Checks</strong> - validate inputs and preconditions (<code>require</code> statements)</li>
<li class=""><strong>Effects</strong> - update your contract's state</li>
<li class=""><strong>Interactions</strong> - call external contracts</li>
</ol>
<p>Violating this opens reentrancy vulnerabilities. If you call an external contract before updating state, that external contract can call back into your function and see the old (unchanged) state.</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">// Vulnerable</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">function withdraw(uint256 amount) external {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    require(balances[msg.sender] &gt;= amount);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    (bool success,) = msg.sender.call{value: amount}(""); // External call first</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    require(success);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    balances[msg.sender] -= amount; // State update after</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">// Fixed</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">function withdraw(uint256 amount) external {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    require(balances[msg.sender] &gt;= amount);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    balances[msg.sender] -= amount; // State update first</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    (bool success,) = msg.sender.call{value: amount}("");</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    require(success);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="pull-over-push-payments">Pull over push payments<a href="https://franroberts.site/blog/defi-design-patterns/#pull-over-push-payments" class="hash-link" aria-label="Direct link to Pull over push payments" title="Direct link to Pull over push payments" translate="no">​</a></h2>
<p>When your contract needs to distribute funds to multiple recipients, don't iterate and push. Let recipients pull their own funds.</p>
<p>Push: iterate over recipients and send. If one send fails (malicious contract, out of gas), the entire distribution fails.</p>
<p>Pull: record what each address is owed. Each recipient calls a <code>claim()</code> function to withdraw their own funds.</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">mapping(address =&gt; uint256) public pendingWithdrawals;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">function distribute(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    for (uint256 i = 0; i &lt; recipients.length; i++) {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        pendingWithdrawals[recipients[i]] += amounts[i];</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">function withdraw() external {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    uint256 amount = pendingWithdrawals[msg.sender];</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    pendingWithdrawals[msg.sender] = 0;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    payable(msg.sender).transfer(amount);</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="emergency-stops">Emergency stops<a href="https://franroberts.site/blog/defi-design-patterns/#emergency-stops" class="hash-link" aria-label="Direct link to Emergency stops" title="Direct link to Emergency stops" translate="no">​</a></h2>
<p>For contracts that handle significant TVL, a pause mechanism is valuable. Uniswap V3 doesn't have one (by design, to be trustless), but many protocols do.</p>
<p>The tradeoff: a pause gives you a circuit breaker if something goes wrong, but it also means the team can freeze user funds. How that risk is managed matters.</p>
<p>Best practice: make pause/unpause governed by a multisig or time-locked governance contract, not a single EOA. The <a href="https://app.safe.global/" target="_blank" rel="noopener noreferrer" class="">Safe (formerly Gnosis Safe) dashboard</a> is the standard for multisig governance in DeFi.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="immutable-versus-upgradeable">Immutable versus upgradeable<a href="https://franroberts.site/blog/defi-design-patterns/#immutable-versus-upgradeable" class="hash-link" aria-label="Direct link to Immutable versus upgradeable" title="Direct link to Immutable versus upgradeable" translate="no">​</a></h2>
<p>Most DeFi protocols choose between two extremes:</p>
<p><strong>Immutable contracts</strong> (Uniswap, Compound's early versions) can never be changed. Users can verify exactly what code will run forever. The downside: bugs can't be patched.</p>
<p><strong>Upgradeable contracts</strong> (via transparent or UUPS proxy patterns) allow the team to patch bugs and add features. The downside: the upgrade admin can change behavior arbitrarily, which is a trust assumption users have to accept.</p>
<p>Some protocols use a hybrid: immutable core contracts with upgradeable periphery.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="oracle-security">Oracle security<a href="https://franroberts.site/blog/defi-design-patterns/#oracle-security" class="hash-link" aria-label="Direct link to Oracle security" title="Direct link to Oracle security" translate="no">​</a></h2>
<p>DeFi protocols that need price data use oracles. On-chain prices from DEX spot prices are manipulable in a single transaction (flash loans). Chainlink provides decentralized off-chain price feeds that are much harder to manipulate.</p>
<p>If your protocol uses spot prices from a DEX as an oracle, you are one large flash loan away from an exploit. The <a href="https://docs.chain.link/data-feeds" target="_blank" rel="noopener noreferrer" class="">Chainlink Data Feeds documentation</a> covers how to integrate their feeds correctly, including how to check that a feed is fresh before using it.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="testing-against-mainnet-state">Testing against mainnet state<a href="https://franroberts.site/blog/defi-design-patterns/#testing-against-mainnet-state" class="hash-link" aria-label="Direct link to Testing against mainnet state" title="Direct link to Testing against mainnet state" translate="no">​</a></h2>
<p>For protocols that interact with existing DeFi infrastructure (Uniswap, Aave, Curve), testing against a mainnet fork is important. Hardhat and Foundry both support forking mainnet state, which lets you test realistic scenarios with real liquidity and real token balances.</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token comment" style="color:rgb(98, 114, 164)">// hardhat.config.js</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token literal-property property">networks</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token literal-property property">hardhat</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token literal-property property">forking</span><span class="token operator">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">url</span><span class="token operator">:</span><span class="token plain"> process</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">env</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token constant" style="color:rgb(189, 147, 249)">MAINNET_RPC_URL</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token literal-property property">blockNumber</span><span class="token operator">:</span><span class="token plain"> </span><span class="token number">20000000</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token comment" style="color:rgb(98, 114, 164)">// Pin to a specific block for reproducibility</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><br></span></code></pre></div></div>
<p>The patterns here aren't exotic. Most DeFi exploits come from violating basic principles rather than novel attack vectors. Get the fundamentals right and review them with that in mind before shipping.</p>]]></content:encoded>
            <category>DeFi</category>
            <category>Solidity</category>
            <category>Security</category>
        </item>
        <item>
            <title><![CDATA[Merkle trees in blockchain: more than just verification]]></title>
            <link>https://franroberts.site/blog/merkle-trees-blockchain/</link>
            <guid>https://franroberts.site/blog/merkle-trees-blockchain/</guid>
            <pubDate>Mon, 02 Sep 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Merkle trees come up constantly in blockchain contexts. They're the reason you can verify a transaction was included in a block without downloading the entire chain, and they show up in smart contracts more often than people expect. Here's a practical look at how they work and where you'll actually encounter them.]]></description>
            <content:encoded><![CDATA[<p>Merkle trees come up constantly in blockchain contexts. They're the reason you can verify a transaction was included in a block without downloading the entire chain, and they show up in smart contracts more often than people expect. Here's a practical look at how they work and where you'll actually encounter them.</p>
<p><a href="https://ethereum.org/en/roadmap/verkle-trees/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://ethereum.org/content/roadmap/verkle-trees/verkle.png" alt="Ethereum verkle tree diagram" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-structure">The structure<a href="https://franroberts.site/blog/merkle-trees-blockchain/#the-structure" class="hash-link" aria-label="Direct link to The structure" title="Direct link to The structure" translate="no">​</a></h2>
<p>A Merkle tree is a binary tree where every leaf node is a hash of some data, and every non-leaf node is a hash of its two children. The root (Merkle root) is a single hash that commits to all the data in the leaves.</p>
<div class="language-text codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-text codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">         Root</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        /    \</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      H12    H34</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      / \    / \</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    H1  H2 H3  H4</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    |   |  |   |</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">   d1  d2 d3  d4</span><br></span></code></pre></div></div>
<p>If any piece of data changes, every hash above it in the tree changes, and the root changes. The root is a fingerprint for the entire dataset.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="why-theyre-useful">Why they're useful<a href="https://franroberts.site/blog/merkle-trees-blockchain/#why-theyre-useful" class="hash-link" aria-label="Direct link to Why they're useful" title="Direct link to Why they're useful" translate="no">​</a></h2>
<p>The key property: you can prove that a specific piece of data is in the set by providing a "proof" that's logarithmic in size relative to the total dataset.</p>
<p>To prove d3 is in the tree, you provide [H4, H12]. The verifier can compute:</p>
<ol>
<li class="">H34 = hash(H3, H4) where H3 = hash(d3)</li>
<li class="">Root = hash(H12, H34)</li>
</ol>
<p>If the computed root matches the known root, d3 is in the tree. You've proven inclusion with only two hashes instead of all four data items.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="ethereums-use-of-merkle-trees">Ethereum's use of Merkle trees<a href="https://franroberts.site/blog/merkle-trees-blockchain/#ethereums-use-of-merkle-trees" class="hash-link" aria-label="Direct link to Ethereum's use of Merkle trees" title="Direct link to Ethereum's use of Merkle trees" translate="no">​</a></h2>
<p>Ethereum uses a modified structure called a Merkle Patricia Trie for state, transactions, and receipts. Each block header contains three roots:</p>
<ul>
<li class=""><code>stateRoot</code>: the root of the entire account state</li>
<li class=""><code>transactionsRoot</code>: the root of all transactions in the block</li>
<li class=""><code>receiptsRoot</code>: the root of all transaction receipts</li>
</ul>
<p>Light clients can verify transaction inclusion by requesting a Merkle proof from a full node without storing the entire state. This is what makes it practical to run Ethereum on resource-constrained devices.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="smart-contract-allowlists">Smart contract allowlists<a href="https://franroberts.site/blog/merkle-trees-blockchain/#smart-contract-allowlists" class="hash-link" aria-label="Direct link to Smart contract allowlists" title="Direct link to Smart contract allowlists" translate="no">​</a></h2>
<p>The most common application of Merkle trees in contract development is allowlists. Instead of storing thousands of addresses in a mapping (expensive), you store only the Merkle root:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">bytes32 public merkleRoot;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">function claim(bytes32[] calldata proof) external {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    bytes32 leaf = keccak256(abi.encodePacked(msg.sender));</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    require(MerkleProof.verify(proof, merkleRoot, leaf), "Invalid proof");</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    // proceed with claim</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>OpenZeppelin's <code>MerkleProof</code> library handles the verification. The full documentation is at <a href="https://docs.openzeppelin.com/contracts/5.x/api/utils#MerkleProof" target="_blank" rel="noopener noreferrer" class="">docs.openzeppelin.com/contracts/5.x/api/utils#MerkleProof</a>.</p>
<p>The offchain part is generating proofs for users. The <code>@openzeppelin/merkle-tree</code> JavaScript library handles this:</p>
<div class="language-javascript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-javascript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword module" style="color:rgb(189, 147, 249);font-style:italic">import</span><span class="token plain"> </span><span class="token imports punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token imports"> </span><span class="token imports maybe-class-name">StandardMerkleTree</span><span class="token imports"> </span><span class="token imports punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword module" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"@openzeppelin/merkle-tree"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> tree </span><span class="token operator">=</span><span class="token plain"> </span><span class="token maybe-class-name">StandardMerkleTree</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">of</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">addresses</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">map</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token parameter">a</span><span class="token plain"> </span><span class="token arrow operator">=&gt;</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token plain">a</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token string" style="color:rgb(255, 121, 198)">"address"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> root </span><span class="token operator">=</span><span class="token plain"> tree</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token property-access">root</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token comment" style="color:rgb(98, 114, 164)">// For a specific address:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">for</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token plain">i</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain"> v</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">of</span><span class="token plain"> tree</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">entries</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token keyword control-flow" style="color:rgb(189, 147, 249);font-style:italic">if</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">v</span><span class="token punctuation" style="color:rgb(248, 248, 242)">[</span><span class="token number">0</span><span class="token punctuation" style="color:rgb(248, 248, 242)">]</span><span class="token plain"> </span><span class="token operator">===</span><span class="token plain"> userAddress</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">const</span><span class="token plain"> proof </span><span class="token operator">=</span><span class="token plain"> tree</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token method function property-access" style="color:rgb(80, 250, 123)">getProof</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">i</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><br></span></code></pre></div></div>
<p>Store the root on-chain and distribute proofs to users off-chain (IPFS, an API, or just a JSON file).</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="verkle-trees">Verkle trees<a href="https://franroberts.site/blog/merkle-trees-blockchain/#verkle-trees" class="hash-link" aria-label="Direct link to Verkle trees" title="Direct link to Verkle trees" translate="no">​</a></h2>
<p>Ethereum's roadmap includes migrating from Merkle Patricia Tries to Verkle trees for state storage. Verkle trees produce much smaller proofs, which is important for stateless clients. The cryptography is more complex (it uses polynomial commitments rather than hash functions), but the interface for developers is similar. The <a href="https://ethereum.org/en/roadmap/verkle-trees/" target="_blank" rel="noopener noreferrer" class="">Ethereum roadmap page</a> has a high-level explanation.</p>
<p>Merkle trees are one of those foundational concepts that keep reappearing in different forms. Understanding them makes a lot of other blockchain primitives easier to reason about.</p>]]></content:encoded>
            <category>Blockchain</category>
            <category>Ethereum</category>
        </item>
        <item>
            <title><![CDATA[Indexing blockchain data with The Graph]]></title>
            <link>https://franroberts.site/blog/indexing-with-the-graph/</link>
            <guid>https://franroberts.site/blog/indexing-with-the-graph/</guid>
            <pubDate>Wed, 14 Aug 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Reading data from a blockchain sounds simple until you try to do it at scale. You can query a node for a specific transaction or block, but if you want to answer questions like "what are all the transfers to this address in the last month sorted by value," you're in trouble. That's what The Graph solves.]]></description>
            <content:encoded><![CDATA[<p>Reading data from a blockchain sounds simple until you try to do it at scale. You can query a node for a specific transaction or block, but if you want to answer questions like "what are all the transfers to this address in the last month sorted by value," you're in trouble. That's what The Graph solves.</p>
<p><a href="https://thegraph.com/studio/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://thegraph.com/explorer/images/bg-blur.png" alt="The Graph Studio: deploy and manage subgraphs" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-problem-with-direct-node-queries">The problem with direct node queries<a href="https://franroberts.site/blog/indexing-with-the-graph/#the-problem-with-direct-node-queries" class="hash-link" aria-label="Direct link to The problem with direct node queries" title="Direct link to The problem with direct node queries" translate="no">​</a></h2>
<p>Ethereum nodes expose a JSON-RPC API. It's designed for writing transactions and reading current state, not for analytical queries. If you want historical event data, you'd need to index every block yourself, store the relevant events, and build query infrastructure around it.</p>
<p>Most teams don't want to do that. The Graph is an indexing protocol that does this work for you via subgraphs.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-a-subgraph-is">What a subgraph is<a href="https://franroberts.site/blog/indexing-with-the-graph/#what-a-subgraph-is" class="hash-link" aria-label="Direct link to What a subgraph is" title="Direct link to What a subgraph is" translate="no">​</a></h2>
<p>A subgraph is a configuration that tells The Graph how to index a specific contract's events and state. You define:</p>
<ul>
<li class="">Which contract(s) to watch</li>
<li class="">Which events to process</li>
<li class="">How to transform event data into a schema</li>
<li class="">GraphQL entities to expose</li>
</ul>
<p>The Graph's indexer nodes watch the blockchain, process events as they're emitted, and make the indexed data queryable via GraphQL.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="setting-up-a-subgraph">Setting up a subgraph<a href="https://franroberts.site/blog/indexing-with-the-graph/#setting-up-a-subgraph" class="hash-link" aria-label="Direct link to Setting up a subgraph" title="Direct link to Setting up a subgraph" translate="no">​</a></h2>
<p>The Graph has a hosted service and a decentralized network. For development, the hosted service is easier to start with. The <a href="https://thegraph.com/studio/" target="_blank" rel="noopener noreferrer" class="">Graph Studio dashboard</a> is where you create and deploy subgraphs.</p>
<p>Install the CLI:</p>
<div class="language-bash codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-bash codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">npm install -g @graphprotocol/graph-cli</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">graph init --product hosted-service</span><br></span></code></pre></div></div>
<p>This generates the boilerplate. The key file is <code>subgraph.yaml</code>:</p>
<div class="language-yaml codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-yaml codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token key atrule">specVersion</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> 0.0.5</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token key atrule">schema</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token key atrule">file</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> ./schema.graphql</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token key atrule">dataSources</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">-</span><span class="token plain"> </span><span class="token key atrule">kind</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> ethereum</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token key atrule">name</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> MyToken</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token key atrule">network</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> mainnet</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token key atrule">source</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">address</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"0xabc..."</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">abi</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> ERC20</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">startBlock</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> </span><span class="token number">18000000</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token key atrule">mapping</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">kind</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> ethereum/events</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">apiVersion</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> 0.0.7</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">language</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> wasm/assemblyscript</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">entities</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        </span><span class="token punctuation" style="color:rgb(248, 248, 242)">-</span><span class="token plain"> Transfer</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">abis</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        </span><span class="token punctuation" style="color:rgb(248, 248, 242)">-</span><span class="token plain"> </span><span class="token key atrule">name</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> ERC20</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">          </span><span class="token key atrule">file</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> ./abis/ERC20.json</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">eventHandlers</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        </span><span class="token punctuation" style="color:rgb(248, 248, 242)">-</span><span class="token plain"> </span><span class="token key atrule">event</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> Transfer(indexed address</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain">indexed address</span><span class="token punctuation" style="color:rgb(248, 248, 242)">,</span><span class="token plain">uint256)</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">          </span><span class="token key atrule">handler</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> handleTransfer</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">      </span><span class="token key atrule">file</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> ./src/mapping.ts</span><br></span></code></pre></div></div>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="writing-mapping-handlers">Writing mapping handlers<a href="https://franroberts.site/blog/indexing-with-the-graph/#writing-mapping-handlers" class="hash-link" aria-label="Direct link to Writing mapping handlers" title="Direct link to Writing mapping handlers" translate="no">​</a></h2>
<p>Mappings are written in AssemblyScript (a TypeScript-like language that compiles to WebAssembly). Each event handler receives the event and updates entities:</p>
<div class="language-typescript codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-typescript codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">import</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> Transfer </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"../generated/MyToken/ERC20"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">import</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> TransferEvent </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">from</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"../generated/schema"</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">export</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">function</span><span class="token plain"> </span><span class="token function" style="color:rgb(80, 250, 123)">handleTransfer</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">event</span><span class="token operator">:</span><span class="token plain"> Transfer</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token operator">:</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">void</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">let</span><span class="token plain"> transfer </span><span class="token operator">=</span><span class="token plain"> </span><span class="token keyword" style="color:rgb(189, 147, 249);font-style:italic">new</span><span class="token plain"> </span><span class="token class-name">TransferEvent</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain">event</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">transaction</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">hash</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token function" style="color:rgb(80, 250, 123)">toHex</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  transfer</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">from </span><span class="token operator">=</span><span class="token plain"> event</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">params</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">from</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  transfer</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">to </span><span class="token operator">=</span><span class="token plain"> event</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">params</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">to</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  transfer</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">amount </span><span class="token operator">=</span><span class="token plain"> event</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">params</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">value</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  transfer</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">blockNumber </span><span class="token operator">=</span><span class="token plain"> event</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token plain">block</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token builtin" style="color:rgb(189, 147, 249)">number</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  transfer</span><span class="token punctuation" style="color:rgb(248, 248, 242)">.</span><span class="token function" style="color:rgb(80, 250, 123)">save</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token punctuation" style="color:rgb(248, 248, 242)">;</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><br></span></code></pre></div></div>
<p>The <code>generated/</code> directory is created by <code>graph codegen</code> from your ABI and schema. Always run codegen after changing either.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="querying-the-subgraph">Querying the subgraph<a href="https://franroberts.site/blog/indexing-with-the-graph/#querying-the-subgraph" class="hash-link" aria-label="Direct link to Querying the subgraph" title="Direct link to Querying the subgraph" translate="no">​</a></h2>
<p>Once deployed, your subgraph exposes a GraphQL endpoint. You can query it from any client:</p>
<div class="language-graphql codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-graphql codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token property-query">transferEvents</span><span class="token punctuation" style="color:rgb(248, 248, 242)">(</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token attr-name" style="color:rgb(241, 250, 140)">first</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> </span><span class="token number">100</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token attr-name" style="color:rgb(241, 250, 140)">orderBy</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> </span><span class="token property">blockNumber</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token attr-name" style="color:rgb(241, 250, 140)">orderDirection</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> </span><span class="token property">desc</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token attr-name" style="color:rgb(241, 250, 140)">where</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"> </span><span class="token attr-name" style="color:rgb(241, 250, 140)">to</span><span class="token punctuation" style="color:rgb(248, 248, 242)">:</span><span class="token plain"> </span><span class="token string" style="color:rgb(255, 121, 198)">"0xabc..."</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">)</span><span class="token plain"> </span><span class="token punctuation" style="color:rgb(248, 248, 242)">{</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token property">from</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token property">to</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token property">amount</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    </span><span class="token property">blockNumber</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">  </span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><span class="token plain"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain"></span><span class="token punctuation" style="color:rgb(248, 248, 242)">}</span><br></span></code></pre></div></div>
<p>The <a href="https://thegraph.com/explorer" target="_blank" rel="noopener noreferrer" class="">Graph Explorer</a> has a built-in query interface for published subgraphs where you can experiment before integrating.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="pagination-and-performance">Pagination and performance<a href="https://franroberts.site/blog/indexing-with-the-graph/#pagination-and-performance" class="hash-link" aria-label="Direct link to Pagination and performance" title="Direct link to Pagination and performance" translate="no">​</a></h2>
<p>The default limit per query is 100 entities, max 1000. For large datasets you need to paginate using <code>skip</code> and <code>first</code>, or use cursor-based pagination with <code>id_gt</code>.</p>
<p>Be careful with deeply nested queries. GraphQL makes it easy to write queries that fan out exponentially. Test with realistic data volumes before shipping.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="subgraph-studio-dashboard">Subgraph Studio dashboard<a href="https://franroberts.site/blog/indexing-with-the-graph/#subgraph-studio-dashboard" class="hash-link" aria-label="Direct link to Subgraph Studio dashboard" title="Direct link to Subgraph Studio dashboard" translate="no">​</a></h2>
<p>The <a href="https://thegraph.com/studio/" target="_blank" rel="noopener noreferrer" class="">Subgraph Studio</a> dashboard shows indexing status, query counts, and error logs for your subgraphs. If an entity isn't appearing in queries, the indexing logs in Studio are the first place to look. Errors in your mapping handlers surface there.</p>
<p>The Graph is one of those tools that feels like significant overhead to set up but pays for itself quickly once you have more than a few data requirements. The alternative (maintaining your own event indexer) is significantly more work.</p>]]></content:encoded>
            <category>Blockchain</category>
            <category>Tooling</category>
            <category>Ethereum</category>
        </item>
        <item>
            <title><![CDATA[Writing secure smart contracts with OpenZeppelin]]></title>
            <link>https://franroberts.site/blog/secure-contracts-openzeppelin/</link>
            <guid>https://franroberts.site/blog/secure-contracts-openzeppelin/</guid>
            <pubDate>Fri, 05 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Smart contract security is one of those topics that's easy to read about and surprisingly hard to internalize until something breaks. OpenZeppelin's contracts library is widely used precisely because it encodes a lot of hard-won security lessons. Here's what you should actually understand about it rather than just copy-pasting imports.]]></description>
            <content:encoded><![CDATA[<p>Smart contract security is one of those topics that's easy to read about and surprisingly hard to internalize until something breaks. OpenZeppelin's contracts library is widely used precisely because it encodes a lot of hard-won security lessons. Here's what you should actually understand about it rather than just copy-pasting imports.</p>
<p><a href="https://docs.openzeppelin.com/contracts/5.x/" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://openzeppelin-docs-v2.netlify.app/social.png" alt="OpenZeppelin Contracts" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="what-openzeppelin-is-and-isnt">What OpenZeppelin is and isn't<a href="https://franroberts.site/blog/secure-contracts-openzeppelin/#what-openzeppelin-is-and-isnt" class="hash-link" aria-label="Direct link to What OpenZeppelin is and isn't" title="Direct link to What OpenZeppelin is and isn't" translate="no">​</a></h2>
<p>OpenZeppelin Contracts is an audited, community-maintained library of Solidity implementations. Using it reduces your attack surface because the base implementations have been reviewed far more thoroughly than most team-written code.</p>
<p>What it isn't: a guarantee that your contract is secure. You can import OpenZeppelin's ERC-20 and still write vulnerable code in your application logic. The library covers the building blocks, not the business logic.</p>
<p>The full documentation and source code is at <a href="https://docs.openzeppelin.com/contracts/5.x/" target="_blank" rel="noopener noreferrer" class="">docs.openzeppelin.com</a>.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="ownable-and-access-control">Ownable and access control<a href="https://franroberts.site/blog/secure-contracts-openzeppelin/#ownable-and-access-control" class="hash-link" aria-label="Direct link to Ownable and access control" title="Direct link to Ownable and access control" translate="no">​</a></h2>
<p>The simplest access pattern is <code>Ownable</code>, which designates a single address as the contract owner:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@openzeppelin/contracts/access/Ownable.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract MyProtocol is Ownable {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    constructor() Ownable(msg.sender) {}</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function adminFunction() external onlyOwner {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        // Only the owner can call this</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>For more complex systems, <code>AccessControl</code> is more appropriate. It lets you define multiple roles with different permissions:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@openzeppelin/contracts/access/AccessControl.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract MyProtocol is AccessControl {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p><a href="https://docs.openzeppelin.com/contracts/5.x/access-control" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://docs.openzeppelin.com/contracts/5.x/access-control-multiple.svg" alt="OpenZeppelin AccessControl role diagram" class="img_ev3q"></a></p>
<p>The <a href="https://docs.openzeppelin.com/contracts/5.x/access-control" target="_blank" rel="noopener noreferrer" class="">AccessControl docs</a> cover the full API. One thing to understand: <code>DEFAULT_ADMIN_ROLE</code> is the admin for all roles by default, and whoever holds it can grant any role. Plan your role hierarchy carefully.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="reentrancyguard">ReentrancyGuard<a href="https://franroberts.site/blog/secure-contracts-openzeppelin/#reentrancyguard" class="hash-link" aria-label="Direct link to ReentrancyGuard" title="Direct link to ReentrancyGuard" translate="no">​</a></h2>
<p>Reentrancy is one of the most notorious Ethereum vulnerabilities. The DAO hack in 2016 was a reentrancy attack. The pattern: a contract calls an external contract, which calls back into the original contract before the first call finishes.</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract Vault is ReentrancyGuard {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function withdraw(uint256 amount) external nonReentrant {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        // Safe to interact with external contracts here</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>The <code>nonReentrant</code> modifier sets a flag at the start and clears it at the end. Any reentrant call will revert because the flag is still set. Simple and effective.</p>
<p>The alternative is to follow the checks-effects-interactions pattern: do all your state updates before making any external calls. Both approaches are valid. I prefer using <code>nonReentrant</code> on withdrawal functions as defense in depth even when the logic appears safe.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="pausable">Pausable<a href="https://franroberts.site/blog/secure-contracts-openzeppelin/#pausable" class="hash-link" aria-label="Direct link to Pausable" title="Direct link to Pausable" translate="no">​</a></h2>
<p>For contracts that handle significant value, the ability to pause is a useful emergency mechanism:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@openzeppelin/contracts/utils/Pausable.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract MyProtocol is Pausable, Ownable {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    constructor() Ownable(msg.sender) {}</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function pause() external onlyOwner { _pause(); }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function unpause() external onlyOwner { _unpause(); }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function deposit(uint256 amount) external whenNotPaused {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        // Can't be called while paused</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>Pausable functionality should be governed carefully in production. An owner who can pause is a centralization risk. Many protocols use a multisig or timelocked governance for pause control.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="safeerc20">SafeERC20<a href="https://franroberts.site/blog/secure-contracts-openzeppelin/#safeerc20" class="hash-link" aria-label="Direct link to SafeERC20" title="Direct link to SafeERC20" translate="no">​</a></h2>
<p>As mentioned in my ERC-20 post, some tokens don't return a bool from <code>transfer</code>. <code>SafeERC20</code> handles the wrapping:</p>
<div class="language-solidity codeBlockContainer_Ckt0 theme-code-block" style="--prism-color:#F8F8F2;--prism-background-color:#282A36"><div class="codeBlockContent_QJqH"><pre tabindex="0" class="prism-code language-solidity codeBlock_bY9V thin-scrollbar" style="color:#F8F8F2;background-color:#282A36"><code class="codeBlockLines_e6Vv"><span class="token-line" style="color:#F8F8F2"><span class="token plain">import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">contract MyContract {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    using SafeERC20 for IERC20;</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain" style="display:inline-block"></span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    function moveTokens(IERC20 token, address to, uint256 amount) internal {</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">        token.safeTransfer(to, amount); // Won't silently fail</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">    }</span><br></span><span class="token-line" style="color:#F8F8F2"><span class="token plain">}</span><br></span></code></pre></div></div>
<p>If you're interacting with arbitrary ERC-20 tokens, always use <code>SafeERC20</code>.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="upgradeable-contracts">Upgradeable contracts<a href="https://franroberts.site/blog/secure-contracts-openzeppelin/#upgradeable-contracts" class="hash-link" aria-label="Direct link to Upgradeable contracts" title="Direct link to Upgradeable contracts" translate="no">​</a></h2>
<p>OpenZeppelin also maintains an upgradeable contracts variant where state is stored in a proxy and logic can be swapped. The <a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/" target="_blank" rel="noopener noreferrer" class="">Upgrades plugins</a> for Hardhat and Foundry automate the safety checks.</p>
<p>Upgradeable contracts come with their own set of pitfalls around storage layout and initialization. Read the <a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/faq" target="_blank" rel="noopener noreferrer" class="">upgrade safety docs</a> before using them in production. The short version: never use constructor logic, always use initializers, and be very careful about adding storage variables in upgrades.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="defender-for-monitoring">Defender for monitoring<a href="https://franroberts.site/blog/secure-contracts-openzeppelin/#defender-for-monitoring" class="hash-link" aria-label="Direct link to Defender for monitoring" title="Direct link to Defender for monitoring" translate="no">​</a></h2>
<p>If you're using OpenZeppelin Defender, the <a href="https://defender.openzeppelin.com/#/sentinel" target="_blank" rel="noopener noreferrer" class="">Defender monitor dashboard</a> lets you set up alerts for specific contract events. Useful for catching unusual patterns before they become incidents.</p>
<p>The security properties of a contract matter just as much as its functionality. Reading through the OpenZeppelin source code is a worthwhile exercise even when you're not directly using a particular contract. The patterns it encodes are worth understanding.</p>]]></content:encoded>
            <category>Solidity</category>
            <category>Security</category>
            <category>Ethereum</category>
        </item>
        <item>
            <title><![CDATA[Layer 2 scaling: rollups, plasma, and what actually shipped]]></title>
            <link>https://franroberts.site/blog/layer2-scaling-solutions/</link>
            <guid>https://franroberts.site/blog/layer2-scaling-solutions/</guid>
            <pubDate>Tue, 18 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[The scaling debate in Ethereum has been going on for years. In 2024 the picture is clearer than it was in 2021 because we can look at what's actually running in production. This is a breakdown of the main approaches and where they stand.]]></description>
            <content:encoded><![CDATA[<p>The scaling debate in Ethereum has been going on for years. In 2024 the picture is clearer than it was in 2021 because we can look at what's actually running in production. This is a breakdown of the main approaches and where they stand.</p>
<p><a href="https://l2beat.com/scaling/summary" target="_blank" rel="noopener noreferrer" class=""><img decoding="async" loading="lazy" src="https://l2beat.com/meta-images/publications/interoperability-page.png" alt="L2Beat: Layer 2 scaling tracker" class="img_ev3q"></a></p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="the-core-problem">The core problem<a href="https://franroberts.site/blog/layer2-scaling-solutions/#the-core-problem" class="hash-link" aria-label="Direct link to The core problem" title="Direct link to The core problem" translate="no">​</a></h2>
<p>Ethereum's base layer processes roughly 15-30 transactions per second. At peak demand, this creates a fee auction where users bid gas to get their transactions included. For most applications, paying $5-50 in fees for a simple action is a non-starter.</p>
<p>Layer 2 solutions move computation off the main chain while using it for settlement and security. The tradeoff is complexity.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="optimistic-rollups">Optimistic rollups<a href="https://franroberts.site/blog/layer2-scaling-solutions/#optimistic-rollups" class="hash-link" aria-label="Direct link to Optimistic rollups" title="Direct link to Optimistic rollups" translate="no">​</a></h2>
<p>Optimistic rollups batch transactions off-chain and post compressed transaction data to Ethereum. The "optimistic" part: they assume all transactions are valid by default and rely on fraud proofs to catch invalid state transitions.</p>
<p>If someone tries to commit a fraudulent state, a challenger submits a fraud proof on-chain and the invalid state gets rolled back. The challenge period (typically 7 days) is what makes optimistic rollups slower for withdrawals back to L1.</p>
<p>Arbitrum and Optimism are the main production systems. Both have their own dashboards where you can inspect transactions and bridge activity:</p>
<ul>
<li class=""><a href="https://arbiscan.io/" target="_blank" rel="noopener noreferrer" class="">Arbitrum dashboard</a></li>
<li class=""><a href="https://optimistic.etherscan.io/" target="_blank" rel="noopener noreferrer" class="">Optimism dashboard</a></li>
</ul>
<p>Both run the EVM, which means most Ethereum contracts deploy to them without modification.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="zk-rollups">ZK rollups<a href="https://franroberts.site/blog/layer2-scaling-solutions/#zk-rollups" class="hash-link" aria-label="Direct link to ZK rollups" title="Direct link to ZK rollups" translate="no">​</a></h2>
<p>ZK rollups batch transactions and generate a cryptographic proof (a validity proof) that the batch is correct. The proof is posted to Ethereum and verified on-chain. No challenge period, because there's no assumption of correctness.</p>
<p>The tradeoff has historically been EVM compatibility. Generating ZK proofs for arbitrary EVM execution is computationally intensive and technically difficult. This is what "zkEVM" efforts like Polygon zkEVM, zkSync Era, and Scroll are trying to solve.</p>
<p>zkSync has a public explorer at <a href="https://explorer.zksync.io/" target="_blank" rel="noopener noreferrer" class="">explorer.zksync.io</a> where you can watch L2 blocks and proof submissions to L1 in real time.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="state-channels">State channels<a href="https://franroberts.site/blog/layer2-scaling-solutions/#state-channels" class="hash-link" aria-label="Direct link to State channels" title="Direct link to State channels" translate="no">​</a></h2>
<p>State channels are the oldest layer 2 concept. Two parties lock funds in an on-chain contract and then exchange signed messages off-chain. They only go on-chain to open or close the channel, or to resolve a dispute.</p>
<p>The Lightning Network on Bitcoin is the most successful state channel implementation. On Ethereum, state channels never got much traction for general use because they only work well for repeated interactions between the same parties. For anything with many participants or infrequent transactions, rollups are more practical.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="plasma">Plasma<a href="https://franroberts.site/blog/layer2-scaling-solutions/#plasma" class="hash-link" aria-label="Direct link to Plasma" title="Direct link to Plasma" translate="no">​</a></h2>
<p>Plasma was a big topic around 2018-2019. The idea is to create child chains that periodically commit to Ethereum. Users can exit back to L1 by submitting a proof.</p>
<p>In practice, Plasma has significant usability problems. The exit mechanism is complicated, data availability is hard to guarantee, and the UX for users is bad. Most teams that were building Plasma systems pivoted to rollups. Polygon PoS is sometimes described as a Plasma variant, though the comparison is rough.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="choosing-a-layer-2">Choosing a layer 2<a href="https://franroberts.site/blog/layer2-scaling-solutions/#choosing-a-layer-2" class="hash-link" aria-label="Direct link to Choosing a layer 2" title="Direct link to Choosing a layer 2" translate="no">​</a></h2>
<p>For most application developers, the decision comes down to:</p>
<ol>
<li class="">Do you need full EVM compatibility? Optimistic rollups have a longer track record here.</li>
<li class="">How important are fast withdrawals to L1? ZK rollups win on this.</li>
<li class="">What's the user ecosystem like? Arbitrum and Optimism have the most existing users and liquidity.</li>
</ol>
<p>The <a href="https://l2beat.com/" target="_blank" rel="noopener noreferrer" class="">L2Beat dashboard</a> tracks all the major Layer 2 systems, their TVL, security models, and upgrade risk. It's the best single resource for comparing options.</p>
<h2 class="anchor anchorTargetStickyNavbar_Vzrq" id="data-availability">Data availability<a href="https://franroberts.site/blog/layer2-scaling-solutions/#data-availability" class="hash-link" aria-label="Direct link to Data availability" title="Direct link to Data availability" translate="no">​</a></h2>
<p>One thing the rollup debates often skip: where does the transaction data live? Rollups post data to Ethereum calldata, which is expensive. EIP-4844 (blob transactions) reduced this cost significantly. Some systems use external data availability layers (Celestia, EigenDA) to reduce costs further, which introduces additional trust assumptions.</p>
<p>This is an active area of development and the tradeoffs are still shaking out.</p>]]></content:encoded>
            <category>Ethereum</category>
            <category>Layer 2</category>
            <category>Blockchain</category>
        </item>
    </channel>
</rss>