<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by RedDuck on Medium]]></title>
        <description><![CDATA[Stories by RedDuck on Medium]]></description>
        <link>https://medium.com/@redduck?source=rss-6518f1cd552c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ilasNWohj05PZpMYLI71WA.png</url>
            <title>Stories by RedDuck on Medium</title>
            <link>https://medium.com/@redduck?source=rss-6518f1cd552c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:35:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@redduck/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[We Just Open-Sourced Five Years of Getting Smart Contracts Right in Production.]]></title>
            <link>https://redduck.medium.com/we-just-open-sourced-five-years-of-getting-smart-contracts-right-in-production-0d9143e32156?source=rss-6518f1cd552c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d9143e32156</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solanas]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[RedDuck]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 10:48:17 GMT</pubDate>
            <atom:updated>2026-08-04T10:48:17.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>We Just Open-Sourced Five Years of Getting Smart Contracts Right in Production. It’s Called RedDuck Academy.</h3><p>We’ve shipped <a href="https://academy.redduck.io/">academy.redduck.io</a>.</p><p>It’s free. It’s open-source. And it’s not going to teach you that using <strong>call</strong> instead of <strong>transfer</strong> saves you a handful of gas units.</p><p>If you came here for that, this isn’t the resource for you — and honestly, the internet has enough of it already.</p><h3>What five years actually teaches you</h3><p>RedDuck has spent the last five years in the parts of Web3 that don’t make it into conference talks: reviewing code that’s about to hold real user funds, sitting in incident advisory calls at 3am, and shipping contracts that ended up securing millions, and in some cases billions of dollars in TVL.</p><p>That kind of exposure teaches you something that no blog post about opcode costs ever will: <strong>almost nothing that breaks in production breaks because someone didn’t know a micro-optimization.</strong> It breaks because of bad assumptions, missing invariants, untested economical models, irrational engineering approaches and integrations that made sense in isolation and became a disaster in composition.</p><p>You don’t learn that from a syntax cheat sheet. You learn it from watching real systems succeed, and watching real systems fail, over and over, until a certain kind of judgment starts to form.</p><p>That judgment is what RedDuck Academy is built to transmit.</p><h3>What this actually is</h3><p>RedDuck Academy is our attempt to package the engineering mindset we’ve built over five years of real, adversarial, production-grade work, and hand it to anyone who wants it.</p><p>That means:</p><ul><li><strong>Real projects, not toy examples.</strong> The scenarios are shaped like the systems we’ve actually reviewed and built — with the messiness, ambiguity, and competing constraints that come with real protocols, not sanitized textbook contracts designed to make one lesson look clean.</li><li><strong>Rational, not perfectionist.</strong> Production engineering is a series of trade-offs made under uncertainty and pressure. We’re not interested in teaching an imaginary “perfect” contract that exists nowhere outside of a tutorial. We’re interested in teaching you how to reason about risk, prioritize what actually matters, and ship something defensible.</li><li><strong>Logical thinking over memorization.</strong> We’d rather you understand <em>why</em> a pattern exists and when it breaks down than have you memorize the facts that are based on the pattern itself. Memorized facts fail the moment reality deviates from the learned examples. Reasoning generalizes.</li><li><strong>Engineering mindset, applied to smart contracts.</strong> This isn’t “Solidity syntax with extra steps.” It’s how experienced engineers actually think across all industries, applied to web3 development. When the code they write can move real money and can’t be quietly patched at 2am without consequences, it has to be designed properly.</li></ul><p>No gas-golfing trivia. No “10 tricks to save 200 gas per call” listicles. That content already exists in abundance, and it optimizes for the wrong thing — it teaches people to sound like they know smart contracts without teaching them to actually reason about the systems they’re building.</p><h3>Why it’s free and open-source</h3><p>We didn’t build this to sell it.</p><p>We built it because the gap between “can write Solidity” and “can be trusted to build or review something that holds real value” is enormous, and most of what’s out there doesn’t close that gap — it just teaches syntax faster.</p><p>Making it free removes the only reason not to try it. Making it open-source is the more important decision: <strong>we don’t think we have a monopoly on hard-earned engineering judgment, and we don’t want this to be a static artifact that goes stale the moment we stop updating it.</strong></p><p>We expect people to fork it, challenge it, break our examples, submit better ones, and argue with our reasoning in the open. If parts of it are wrong, or become outdated, or simply reflect blind spots from our own experience, we want that surfaced and fixed by the community actually doing this work — not quietly maintained by us in isolation.</p><p>If you’ve shipped something to production, broken something in production, or fixed something at 3am while everyone else was asleep, you probably have something worth contributing here. We’d genuinely like to see it.</p><h3>Go build something real</h3><p>academy.redduck.io is live now, free, and open for contributions.</p><p>This isn’t for people who want to feel like they know smart contracts. It’s for people who want to actually be ready to design and build systems that hold real value — and who are willing to think, not just memorize, to get there.</p><p>Come take a look. Better yet, come argue with us and make it better.</p><p><strong>→ </strong><a href="https://academy.redduck.io/"><strong>academy.redduck.io</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d9143e32156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ERC8009: What Would Have Stopped the Bybit Hack]]></title>
            <link>https://redduck.medium.com/erc8009-what-would-have-stopped-the-bybit-hack-3b56d1a041c8?source=rss-6518f1cd552c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b56d1a041c8</guid>
            <category><![CDATA[trezor]]></category>
            <category><![CDATA[blind-signing]]></category>
            <category><![CDATA[ledger]]></category>
            <category><![CDATA[hardware-wallet]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[RedDuck]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 19:30:46 GMT</pubDate>
            <atom:updated>2026-06-28T19:30:46.385Z</atom:updated>
            <content:encoded><![CDATA[<p>$1.5 billion. One transaction. The largest crypto theft in history.</p><p>The uncomfortable truth about the Bybit hack is not that the attackers were sophisticated. It’s that the signers did everything right and still lost. They followed a reasonable procedure. The multisig worked exactly as designed. The private keys were never compromised.</p><p>They just couldn’t see what they were signing.</p><h3>What happened in the hack?</h3><p>The Lazarus Group compromised Safe’s frontend and injected JavaScript that silently replaced the transaction Bybit’s signers were about to approve. Each signer connected their Ledger, reviewed what looked like a routine transfer, and confirmed. The Ledger <strong><em>showed a hex hash </em></strong>of the transaction instead of a detailed description of the transaction — which was the only thing Ledger could do — it couldn’t decode what was inside. The signers had no way to know what they were actually signing.</p><p>That’s it. That’s the whole failure.</p><h3>The failure point: blind signing</h3><p>When a Ledger or Trezor device can’t decode a transaction, it shows you the raw hash and asks you to confirm.</p><p>This is called blind signing — you’re approving something you cannot read (good luck inferring something meaningful out of a bunch of hex digits).</p><p>In Bybit’s case, the actual transaction was not a transfer at all. It was a call that replaced the multisig’s implementation with attacker-controlled code. Once three signers confirmed, the attacker had full control of the multisig wallet. This is a point of no return, and the second transaction drained everything.</p><p>What the signers saw when signing the transaction:</p><p>Safe UI: “A routine transfer to hot wallet” ✅<br>Hardware device: “Hash value” ⚠️ (dangerous but frequently ignored)<br>Actual transaction: “Change Multisig Code” ❌ (beyond hope now)</p><h3>Why whitelisting doesn’t generalize</h3><p>The obvious solution people reach for is whitelisting: whitelist known contract addresses and known function selectors, so the device can display something meaningful instead of a hash.</p><p>This works, and some approaches do implement it. Ledger’s Clear Signing Initiative maintains a registry of contracts with their ABIs, so the device can decode transfer(address, uint256) and display it as a human-readable transfer.</p><p>But here’s where it breaks down for Bybit’s case specifically.</p><p>The Safe contract was legitimate. execTransaction is a known Safe function. A whitelist covering &quot;Safe contract + execTransaction&quot; would have given a green light — because those two things checked out. By the way, Safe multisig wallets are deployable instances per multisig. So there is a new address for each deployment, making it harder to consider whitelisting for this scenario. The malicious payload was <em>inside</em> the calldata of that execTransaction: a delegatecall to an attacker contract, nested inside a legitimate call on a trusted address.</p><p>To catch this with whitelisting, you’d need to be able to recognize the patterns of calldata provided. It’s possible theoretically, but it’s an extremely challenging technical task in reality.</p><p>This requires an ever-growing library of dangerous patterns, maintained continuously, covering every protocol and every possible operation that could be abused.</p><p>Whitelisting secures identity (what is the action, what is the protocol). But it can’t secure behavior.</p><h3>ERC8009: show consequences, not calldata</h3><p>ERC8009 takes a different approach entirely. Instead of asking <em>“where is this transaction going?”</em>, it asks <em>“what will this transaction do to my balances?”</em></p><p>The transaction is simulated before signing. The result — specifically, what balance changes will occur — is shown on the hardware device screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Ee75GSD3v0UJ3ZPsVkpLFA.png" /><figcaption><em>Trezor screen showing +2.8 USDC and -0.01 ETH as a result of transaction</em></figcaption></figure><p>The signer doesn’t need to understand what the transaction even does. They just need to see whether the consequences match what they expected to sign.</p><h3>What the simulation would have shown on February 21</h3><p>The malicious transaction moved zero ETH. Its only effect was changing the Safe’s implementation contract to an attacker-controlled address.</p><p>The Safe UI claimed: <strong>“transfer to hot wallet”</strong>. ERC8009 would have shown: <strong>“0 ETH moved”</strong>.</p><p>That contradiction alone ends the attack. No signer confirms a transaction when the simulation shows nothing is moving, but they expected ETH to move.</p><h3>“But couldn’t the simulation be faked too?”</h3><p>Yes — if the simulation runs on the same compromised machine serving the malicious frontend, an attacker could fake the output.</p><p>This is why the architecture matters. The expected balance changes are passed to the ERC8009 contracts and enforced there, and hardware wallets that support ERC8009 can display these balance changes directly on the hardware screen.</p><p>The attacker can manipulate a browser tab. They cannot change what appears on the physical device screen. That’s the trust boundary ERC8009 relies on, and it’s the same trust boundary that makes hardware wallets meaningful in the first place.</p><h3>Multisig: now covered</h3><p>There was one important gap in earlier versions of ERC8009: multisig signing flows.</p><p>In a multisig, signing and execution are separated. Signer A approves a transaction that doesn’t execute until B and C also sign. This made it unclear how to apply simulation-based clear signing when each signer’s action is independent of execution.</p><p>This is now resolved. ERC8009 has been extended to support multisig flows — the executor of the transaction can see simulated consequences of the collective transaction on their hardware device before confirming it.</p><p>Bybit’s setup — three independent signers each approving a Safe transaction — is exactly the flow that is now covered.</p><h3>Why it scales</h3><p>Address whitelisting has to keep up with every new contract deployed. That’s a losing race — millions of new addresses every year, across hundreds of protocols, with arbitrary call combinations.</p><p>ERC8009 doesn’t care about any of that. There are technical solutions that fully ignore the environment constraints, rather than trying to work with them. ERC8009 is one of them. Balance changes are the ground truth regardless of how deep the call chain goes, how new the protocol is, or how complex the interface is. You cannot construct a transaction that drains a wallet and have a simulation say nothing changes.</p><p>The property is generic by design.</p><h3>Where things are now</h3><p>ERC8009 is a proposed standard. There is a working implementation, including multisig support, and a demo with hardware wallets.</p><ul><li>Spec and demos: <a href="https://erc8009.xyz/">ERC8009.xyz</a></li><li>Formal proposal: <a href="https://github.com/ethereum/ERCs/pull/1184">ethereum/ERCs #1184</a></li><li>Discussion: <a href="https://ethereum-magicians.org/t/erc-8009-proxy-clear-signing/25199">Ethereum Magicians</a></li></ul><p>The Bybit hack was not the first attack that blind signing made possible. Radiant Capital ($50M), WazirX ($230M), and others before them followed the same pattern. It will not be the last — until hardware devices can show signers what a transaction actually does.</p><p>That’s what ERC8009 is for.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b56d1a041c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebranding]]></title>
            <link>https://redduck.medium.com/rebranding-f6e0ee71eff9?source=rss-6518f1cd552c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6e0ee71eff9</guid>
            <category><![CDATA[news]]></category>
            <dc:creator><![CDATA[RedDuck]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 14:01:57 GMT</pubDate>
            <atom:updated>2025-06-29T14:01:57.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYun9EtMI-PzfeLtB2ndlQ.jpeg" /></figure><p>RedDuck is Rebranding — with Purpose</p><p>RedDuck relaunches as a blockchain partner for teams that build with reason</p><p>Today, we’re introducing the new face of RedDuck — not just a fresh look, but a clearer stance. We’re no longer just a web3 development studio. We’re a consulting and engineering partner for blockchain products.</p><p>→ no over-engineering</p><p>→ no vague promises</p><p>→ only clean, functional systems that solve real problems</p><p>The brand may look different — but the mindset hasn’t changed.</p><p>We’ve always built with intention. Now we say it out loud.</p><p>In the coming weeks, we’ll share insights from our team, break down engineering decisions, and showcase what we mean by lean blockchain architecture.</p><p>RedDuck. Build with reason.</p><p><a href="http://redduck.io/">redduck.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6e0ee71eff9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vesting contract implemented in 3 different ways.]]></title>
            <link>https://redduck.medium.com/vesting-contract-implemented-in-3-different-ways-bdd7e7be3fa?source=rss-6518f1cd552c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdd7e7be3fa</guid>
            <category><![CDATA[vesting]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[token-vesting]]></category>
            <dc:creator><![CDATA[RedDuck]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 10:20:39 GMT</pubDate>
            <atom:updated>2025-06-29T10:19:15.174Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, in this article, we will show you 3 different approaches to implementing a Vesting contract.</p><p>A vesting contract is a contract that allows owners of projects to allocate tokens for their users but makes the users themselves take the tokens out of the vesting contract. Such an operation is called a “claim”.</p><p>To claim, of course, users need to prove to the contract, that they have the right to do so. For that, the owner of the project has to perform some action that will make the contract confident that the certain user indeed can claim.</p><p>There are three ways to do it that we know so far:<br>1) Populate a mapping (address =&gt; uint256) that will return the uint256 amount that a user with a specific address can claim.<br>2) Use the Merkle Tree root hash as storage (it’s just a compressed bytes32 field) and provide the cryptographic proof that an address is contained in the bytes32 hashed variable every time a user makes a claim. Reference: <a href="https://redduck.medium.com/off-chain-storage-pattern-in-solidity-merkle-tree-d277be4453f4">https://redduck.medium.com/off-chain-storage-pattern-in-solidity-merkle-tree-d277be4453f4</a><br>3) Use the owner’s signatures so that the contract can verify that the claim is legitimate. The messages like “Address 0x.…11 can claim 100 tokens” will be signed by the owner’s private key and the contract will be able to verify that, if both signature and message is provided by the user during claim.</p><p>Let’s take a look at all the implementation of all the three methods above.</p><h3>On-chain solution (mapping)</h3><p>A default, normal solution, would be to use a mapping of addresses and their corresponding claimable amounts:</p><pre>contract DefaultVesting is Ownable {</pre><pre>    mapping (address =&gt; uint256) claimableAmount;</pre><pre>    IERC20 immutable _token;</pre><pre>    constructor(IERC20 vestedToken) {</pre><pre>        _token = vestedToken;</pre><pre>    }</pre><pre>    function vestTokensMany(address[] calldata toArray, uint256[] calldata amountArray) external onlyOwner { <br>       for (uint256 i = 0; i &lt; toArray.length; i++) {<br>           claimableAmount[toArray[i]] = amountArray[i];<br>       }<br>    }</pre><pre>    function claimTokens(uint256 amount) external {</pre><pre>        require(canClaimTokens(amount), &quot;cannot claim&quot;);</pre><pre>        claimableAmount[msg.sender] -= amount;</pre><pre>        _token.transfer(msg.sender, amount);</pre><pre>    }</pre><pre><strong>    function canClaimTokens(uint256 amount) private view returns (bool) {</strong></pre><pre><strong>       return claimableAmount[msg.sender] &gt;= amount;</strong></pre><pre><strong>    }</strong></pre><pre>}</pre><p><strong>Pros:<br></strong>1. Simplicity. It’s really very easy to implement that.<br>2. Everything is stored on-chain, so there is a bit more transparency and security.</p><p><strong>Cons:</strong><br>1. VestTokensMany is not optimised to high amount of data (like 1000 addresses). It could cost up to 10000$ dollars on Ethereum chain to initialize many addresses.<br>2. Lack of transparency: If the amount of data is high and we can’t initialise the mapping from one transaction, it means that we can always change the vested amounts/addresses and it’s not transparent to users.</p><h3>Gas-Optimised solution: Merkle Tree</h3><p>We need to get rid of the code that makes us execute N steps in order to add N addresses. Then we will be able to get rid of that con about costly vestTokensMany function.</p><p>So, let’s make it work with less data. Merkle Trees can help us with that. This approach uses the Merkle root tree algorithm described in this article: <a href="https://redduck.medium.com/off-chain-storage-pattern-in-solidity-merkle-tree-d277be4453f4">https://redduck.medium.com/off-chain-storage-pattern-in-solidity-merkle-tree-d277be4453f4</a>)</p><p>The code below, using the Merkle root trees, is demonstrated.</p><pre>contract MerkleVesting is Ownable {</pre><pre>   bytes32 claimMerkleRoot;</pre><pre>   mapping (address =&gt; bool) addressClaim;</pre><pre>   IERC20 immutable _token;</pre><pre><br>   constructor(IERC20 vestedToken) {</pre><pre>      _token = vestedToken;</pre><pre>   }</pre><pre>   function vestTokens(bytes32 merkleRoot) external onlyOwner {</pre><pre>      claimMerkleRoot = merkleRoot;</pre><pre>   }</pre><pre>   function claimTokens(uint256 amount, bytes32[] calldata merkleProof) external {</pre><pre>       require(canClaimTokens(amount, merkleProof), &quot;cannot claim&quot;);</pre><pre>       addressClaim[msg.sender] = true;</pre><pre>       _token.transfer(msg.sender, amount);</pre><pre>   }</pre><pre>  <strong> function canClaimTokens(uint256 amount, bytes32[] calldata merkleProof) private view returns (bool) {<br>    return addressClaim[msg.sender] == false &amp;&amp;<br>           MerkleProof.verify(merkleProof, claimMerkleRoot,<br>           keccak256(abi.encodePacked(msg.sender, amount)));</strong></pre><pre><strong>    }</strong></pre><pre>}</pre><p>We avoid spending N on-chain steps to initialise N addresses, because we shrink all those addresses into one hash off-chain, and we just spend one step to initialise the data on-chain (claimMerkleRoot field). However, this field won’t be able to work stand-alone, unlike the mapping. It will require an additional argument to be always provided during a claim — bytes32[] merkleProof. This proof will contain log2(N) amount of addresses that are connected to the msg.sender address in the tree, and it is required to prove that the pair {msg.sender, amount} exists in the tree.</p><p><strong>Pros:</strong><br>1. Fast speed: the complexities are O(1) for vestTokens, O(logN) for claimTokens where N is the amount of vested addresses.<br>2. Security: The merkle root trees could be used with a multi signature wallet, and it would mean high security, just like with on-chain solution. <br>3. Fast invalidation of vested amounts and addresses. To change the vested addresses or amounts, we can easily change just one field (as opposed to iterating all keys in the mapping).<br>4. Decentralization / Transparency - We could disallow to modify the vested addresses/amounts if we want to. So, #3 is optional, and we can disallow to modify anything, which was even not possible with the mapping solution.</p><p><strong>Cons:</strong><br>1. It would require keeping storage somewhere off-chain.<br>2. Usually it’s harder for the users to use the smart contracts directly (although it’s not very hard).</p><h4>Alternative off-chain solution: Owner signatures</h4><pre>contract SignatureVesting is Ownable {</pre><pre>   using ECDSA for bytes32;</pre><pre>   mapping (bytes =&gt; bool) signatureClaim;</pre><pre>   IERC20 immutable _token;</pre><pre>   constructor(IERC20 vestedToken) {</pre><pre>        _token = vestedToken;</pre><pre>    }</pre><pre>    function claimTokens(uint256 amount, uint256 nonce, bytes calldata signature) external {</pre><pre>        require(canClaimTokens(amount, nonce, signature), &quot;sig&quot;);</pre><pre>        signatureClaim[signature] = true;</pre><pre>        _token.transfer(msg.sender, amount);</pre><pre>   }</pre><pre>   <strong>function canClaimTokens(uint256 amount, uint256 nonce, bytes calldata signature) private view returns (bool) {</strong></pre><pre><strong>        bytes32 message = keccak256(abi.encodePacked(msg.sender, amount, nonce, address(this)));</strong></pre><pre><strong>        return signatureClaim[signature] == false &amp;&amp; message.toEthSignedMessageHash().recover(signature) == owner();</strong></pre><pre><strong>    }</strong></pre><pre>}</pre><p>This approach is fundamentally different. See, we don’t even have a vestTokens function. The reason for that is that it is basically like the mapping solution, but a virtual one. When a mapping is populated on-chain, you sign a transaction and send it immediately. In this scenario, you just sign a transaction and give it to the user that would claim later. And they provide the signature of that transaction to the contract, and contract basically executes both transactions at the same time: vest and claim transactions. This way the owner does not need to spend their funds in order to initialise the contract with a state, only users do, and they only pay for their record in the mapping.</p><p>So, instead of us sending a transaction every time we want to populate a user’s address into the vesting contract, we just sign this transaction data, give it to the user outside of Solidity smart contracts, and whenever this user wants to claim, they can do so by providing the signature we gave them. The contract will check the signature and if it’s valid, it will allow the user to claim tokens. It is like a virtual mapping, that exists off-chain.</p><p>It’s obvious pro is that it’s complexity is O(1) for both initialisation and claim functions, unlike the previous solutions.</p><p>Of course, it sounds cool, but there are a lot of drawbacks when using the signatures approach. The cons are listed below:</p><h4>Replay attacks</h4><p>Firstly, signatures could be re-used by a user many times. <br>But this has a solution - firstly, we need to store in a mapping a register of used/unused signatures (like we do with the signatureClaim field). Also, we need to store more data for security, like the contract address and the nonce of the signature, to avoid replay attacks. But, even if we do so, we still can get a replay attack if we deploy the same contract with the same address onto another chain and don’t specify a different nonce in the new contract, that is different from the previous contract’s nonce.</p><h4>Centralisation</h4><p>We need a private key to produce the signature. So, the whole idea is circling around one guy with access to one private key. Gnosis safe won’t help here (even if it had EIP 1271 implemented) because a signature is at the end produced by just one private key by one person. If it gets stolen, then the hacker could generate whatever signature they want, and claim all the tokens.<br>Whereas Merkle root and mapping solutions could be used with gnosis safe multi-signature wallet for more security.</p><p>So, regarding an off-chain solution, the Merkle root tree would be more secure, and also robust, because if we decide to change user’s claim amounts, it will be much harder to patch the smart contract to ignore previously generated signatures, and only accept new signatures with new claim amounts, whereas for the merkle tree solution, we just need to update the root hash.</p><h4>Unsolvable lack of transparency</h4><p>The fact that all the signatures exist off-chain, means that there can be more signatures produced by the owner, for instance, that would allow himself or his friend to drain the whole balance of the contract. This is unsolvable due to the nature of the solution — we don’t have the vestTokens function, we don’t know where the data exists.</p><h3>Summary</h3><p>In general, Merkle Trees seem to be the most relevant way. They have low computational complexity, high decentralisation, easy invalidation of data, transparency towards users, low security risks, and can contain high amount of addresses. The only case when they are not applicable is when you have limited development time or skillset on the project, and you don’t want to bother because the amount of addresses you need to vest is not high.</p><p>Here’s a table to compare the three solutions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgUF8aWAt6pO25eaPuGdbg.jpeg" /><figcaption>Comparison table</figcaption></figure><h3>References</h3><p>The repo where you can play with the smart contracts described above is located at this URL:</p><p><a href="https://github.com/RedDuck-Software/Example-Vesting">GitHub - RedDuck-Software/Example-Vesting: This is an example of the vesting contracts.</a></p><h3>Contacts</h3><p>If you have any questions about this or want a project to be developed, you could contact me:</p><p>Telegram — @RedDuckUA<br>Email — mark.virchenko@redduck.io</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdd7e7be3fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Off-chain storage pattern in Solidity: Merkle Tree]]></title>
            <link>https://redduck.medium.com/off-chain-storage-pattern-in-solidity-merkle-tree-d277be4453f4?source=rss-6518f1cd552c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d277be4453f4</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[off-chain-transactions]]></category>
            <category><![CDATA[merkle-tree]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <dc:creator><![CDATA[RedDuck]]></dc:creator>
            <pubDate>Sun, 29 May 2022 17:51:44 GMT</pubDate>
            <atom:updated>2023-11-21T17:35:07.401Z</atom:updated>
            <content:encoded><![CDATA[<p>In Solidity, sometimes you need to add a big amount of data to the smart contract. Adding a big amount of data costs a lot of gas and hence sometimes is not possible to do. For example, you need to whitelist thousands of users or add thousands of addresses into a vesting contract. In this article, I will tell you how to resolve such tasks with the use of Merkle Trees.</p><h3>Merkle Tree Algorithm</h3><p>Merkle trees allow us to compress a list of data of any length into one single hash. The compressing algorithm works by creating pairs of elements, summing the pairs, and hashing the sums of the pairs. This process repeats, until, we receive a single <strong>root hash</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*B0YH6wuBHh5oLzR-dfM0OQ.png" /><figcaption>Merkle Root Tree — Structure of hashes, ending with a hash of all hashes in the root.</figcaption></figure><p>This allows us to compress a list of any length into one single 256 bits hash. <br>But, of course, we can’t extract the value back from the hash. But, fortunately, we don’t need to do it.</p><p>Ok, we’ve compressed the data into one hash. Now we can pass this hash onto a smart contract. This would cost us a low amount of gas because passing a 256 bits hash into a smart contract costs less than passing thousands of them. Now we are passing one.</p><p>Now we have the list (in a compressed way) on our contract. The values in the list could be of any type, whether it’s an address, unit, or a more complicated type. We have two possible operations to do on that list and their corresponding algorithms:</p><p><strong>Modify</strong> (Add/Remove element, change details of an element):<br>1) Change the data off-chain <br>2) Re-calculate the hash<br>3) Pass the new hash onto the contract.<br><strong>Read</strong> (Check if the element exists, gather the element’s details):<br>1) Accept as parameters: (data of the element, <strong>cryptographic proof </strong>that<strong> </strong>this element is in the list)<br>2) <strong>Prove</strong> that this element exists in the root hash i.e. in the list <br>3) Read details about the passed element as a parameter.<br>4) Do whatever is required next. (e.g. if it’s a vesting contract - send tokens to the address)</p><h4>How cryptographic proof for Read works</h4><p>How do we prove that an element is in the Merkle tree?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USIrykQDNiUDs1ER_R4BkQ.png" /><figcaption>Hashes are required to get the top hash and prove that <strong>hK </strong>is in the hash</figcaption></figure><p>To prove that an <strong>element</strong> <em>(</em><strong><em>hK</em></strong> <em>on the picture)</em> is in the hash, we have to assemble the hash again, and it’s mandatory to use the <strong>hK </strong>hash during the assembling because we want to prove that <strong>hK</strong> is in the list. If we assemble the top hash with explicit usage of the <strong>element’s hash (hK),</strong> it means that the element’s hash is contained in the top hash. So, a smart contract function, that wants to check if an <strong>element</strong> is in the root, should re-create the <strong>root</strong> hash itself, using the <strong>element</strong>’s hash and other hashes nearby it, and check, if the result is the same as the root hash. If the result is the same, it means, that the root hash contains the hash of the element.</p><p>You might think, what is the point of this, if we assemble the hash again, we will need to do the same number of steps, as the number of elements, or even more? “<em>We could’ve added those elements to the mapping</em>”. But actually, we don’t need <em>all</em> the elements to assemble the root hash. As you can see in the picture above, we only need to have those nodes (hashes), that allow us to calculate the next level of the tree.</p><p>So, we start off with the element that we should verify — <strong>hK</strong>. What is the other element we need to get higher in the tree? It will be the <strong>element’s</strong> <strong>pair (hL)</strong>. Now, we’ve gotten one level up — <strong>hKL</strong>. What is the next hash we need? It is <strong>hIJ</strong>. But, as you can see, we did not need hI and hJ, we only needed <strong>hIJ</strong>. So, we’ve saved 2 steps — <em>one-half of the steps so far</em>. Alright, we’ve got <strong>hKL</strong> and <strong>hIJ</strong>, and we’ve gotten to the next level — <strong>hIJKL</strong>. What’s the hash we need to get higher? It is <strong>hMNOP</strong>, and we can take its hash, we don’t need the extra processing of the 6 hashes below it. Again, we’ve saved another half of the steps. Good, let’s go next, we’ve processed <strong>hMNOP</strong> + <strong>hIJKL</strong>, and now we are on <strong>hIJKLMNOP.</strong> What does it cost us to get onto the next level? one step — combining <strong>hIJKLMNOP</strong> with <strong>hABCDEFGH</strong>. Congratulations, we’ve got to the <strong>hABCDEFGHIJKLMNOP</strong> now, and we can check, if the resulting hash is the same, as it is recorded in the smart contract. If it is, it means that the <strong>hK</strong> hash is contained in the top <strong>hABCDEFGHIJKLMNOP</strong> hash.</p><h4>The computational complexity of the proof</h4><p>If we only need one step to get one level up the tree - it’s not so hard to calculate the complexity. The complexity of proving that an element is in the tree is the <strong>height</strong> of the tree. In this case, the height is <strong>4</strong>, and the number of elements is <strong>16</strong>. This means, that the complexity of verifying that an element is in the tree is <strong>O(logN)</strong>.</p><p>This means, that on the level of the smart contract, the complexities are as follows:<br><strong>- Modify</strong> [whole list] - <strong>O(1)</strong> (we need to replace the root hash value in a variable);<br><strong>- Read - O(logN)</strong> (we need to verify that an element is in the tree, and then we can continue reading its details and work with it).</p><h4>Examples</h4><ol><li><strong>A vesting contract, where you need to populate 10,000 addresses that can claim tokens.</strong> You can’t submit 10,000 addresses nor to the array, or to a mapping. Instead, you could store the addresses off-chain, and only submit the top root hash to the smart contract. When a person wants to claim, they need to submit <strong>Merkle proof</strong> (cryptographic proof we’ve discussed above) and the value of their node in the tree, which is {address, amount of tokens} object. Once you’ve re-created the top-level hash with this object and other hashes that the Merkle proof contains, you can see if it matches the one recorded in the smart contract. If it does, it means you can be sure that such an object {address, amount of tokens} exists in the tree. Then, you can send them the tokens they want to claim and register in a mapping that this address has already claimed their tokens.<br><strong><em>Note</em></strong>: in a traditional on-chain scenario, adding 10,000 addresses into a mapping would cost approximately 50,000 $. By using Merkle root hash instead of mapping, we would save 50,000$.</li><li><strong>NFT / ERC20 token, where only whitelisted users can use the token.</strong><br>In this scenario, we could store in the hash, that stores the addresses that can use the token, and every time somebody wants to make a transfer or call some function that marks them as whitelisted, they need to provide <strong><em>Merkle proof</em></strong> that proves that they are in the whitelist.</li><li><strong>Any contract with a whitelist, not just NFT/ERC20, for instance, also a launchpad</strong>. There are also many other applications, I will be updating the article every time I find a new scenario where it could be useful.</li></ol><h3>Conclusions</h3><p>In this article, I’ve explained to you one way to store big amounts of data in a single variable. Adding thousands of addresses even within a single transaction to a mapping in Solidity costs a lot of gas, which could even exceed block gas limits. On the Ethereum chain, such an operation, if possible at all, would cost tens of thousands of dollars. So, this pattern allows developers to work with huge data amounts in Solidity, and find easy solutions for such problems as whitelisting users for NFTs, or submitting addresses into a vesting contract.</p><p>This is just one pattern of fixing such an issue, and there are more. I will explain them in upcoming articles, and I will also create articles that show our experience creating contracts with such solutions, that passed an audit and went to production, with a high number of users and high TVL.</p><p>If you have any questions about this or want a project to be developed, you could contact me:</p><p>Telegram — @RedDuckUA<br>Email — mark.virchenko@redduck.io</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d277be4453f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>