<?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 Jhon Zuluaga on Medium]]></title>
        <description><![CDATA[Stories by Jhon Zuluaga on Medium]]></description>
        <link>https://medium.com/@jhonzusa?source=rss-47c9c2a00716------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VDSjDOvzbb1Q9pifDptYVA.jpeg</url>
            <title>Stories by Jhon Zuluaga on Medium</title>
            <link>https://medium.com/@jhonzusa?source=rss-47c9c2a00716------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:55:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jhonzusa/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[How to Test Smart Contracts Like a Senior Engineer — 129 Tests with Hardhat, TypeScript &…]]></title>
            <link>https://medium.com/@jhonzusa/how-to-test-smart-contracts-like-a-senior-engineer-129-tests-with-hardhat-typescript-f842aabc8842?source=rss-47c9c2a00716------2</link>
            <guid isPermaLink="false">https://medium.com/p/f842aabc8842</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[hard-hat]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Jhon Zuluaga]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 23:26:07 GMT</pubDate>
            <atom:updated>2026-06-22T23:26:07.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzQnzxJ07VeU16WTo4u_gw.png" /></figure><h3>How to Test Smart Contracts Like a Senior Engineer — 129 Tests with Hardhat, TypeScript &amp; OpenZeppelin v5</h3><p><em>A complete, production-ready guide to smart contract testing — from your first </em><em>expect to end-to-end business flow simulation.</em></p><h3>Why Testing Smart Contracts Is Non-Negotiable</h3><p>In traditional software, a bug in production means a hotfix. In smart contracts, a bug in production means <strong>losing real money — permanently.</strong></p><p>The DAO hack (2016): $60M drained via reentrancy. Nomad Bridge (2022): $190M exploited in hours. Euler Finance (2023): $197M gone in a single transaction. Every one of these attacks could have been caught by a proper test suite.</p><p>If you’re building on Ethereum or any EVM chain, testing is not optional. It’s the difference between shipping a protocol and shipping a liability.</p><p>In this article, I’ll walk you through building a <strong>129-test suite</strong> for a real decentralized crowdfunding protocol — covering unit tests, security patterns, custom errors, events, and a full end-to-end functional simulation across 4 business scenarios.</p><p>All code is available on GitHub: 👉 <a href="https://github.com/JhonZuluaga007/crowdfunding-protocol-solidity">crowdfunding-protocol-solidity</a></p><h3>What We’re Testing</h3><p>The protocol is a decentralized crowdfunding system built with:</p><ul><li><strong>Solidity 0.8.20</strong> — EVM target: Paris</li><li><strong>OpenZeppelin v5</strong> — Ownable, ReentrancyGuard, Pausable</li><li><strong>Hardhat 2.28.6</strong> — development and test environment</li><li><strong>ethers.js v6</strong> — BigInt-native Ethereum library</li><li><strong>TypeChain</strong> — auto-generated TypeScript bindings</li><li><strong>TypeScript 5.x strict mode</strong> — throughout the entire toolchain</li></ul><h3>Business rules (enforced on-chain):</h3><ul><li>Any account can <strong>create a project</strong> with an id, name, description, and fundraising goal</li><li>Any account <strong>except the author</strong> can fund an open project with ETH</li><li>ETH is transferred <strong>directly to the author</strong> on each contribution — the contract holds no funds</li><li>Only the <strong>project author</strong> can open/close their project</li><li>The <strong>contract owner</strong> can pause all operations in an emergency</li></ul><h3>Project Structure</h3><pre>crowdfunding-protocol-solidity/<br>├── contracts/<br>│   ├── core/<br>│   │   └── CrowdFundingOZ.sol        ← Production contract<br>│   ├── interfaces/<br>│   │   └── ICrowdFunding.sol          ← Public interface<br>│   └── learning/                      ← Educational progression (CrowdFunding1–6)<br>├── scripts/<br>│   └── deployCrowdFundingOZ.ts<br>├── test/<br>│   ├── CrowdFundingOZ.test.ts         ← Unit tests (18 tests)<br>│   ├── functional/<br>│   │   └── simulate.ts                ← E2E simulation (4 scenarios)<br>│   └── learning/                      ← 111 tests across learning contracts<br>├── hardhat.config.ts<br>└── tsconfig.json</pre><h3>The Production Contract</h3><p>Before writing tests, let’s understand what we’re testing.</p><h3>The Interface: ICrowdFunding.sol</h3><p>Every production contract starts with an interface. This enforces the public API contract and makes future upgrades predictable.</p><pre>// SPDX-License-Identifier: GPL-3.0<br>pragma solidity 0.8.20;</pre><pre>interface ICrowdFunding {<br>    enum FundraisingState { Opened, Closed }</pre><pre>    struct Contribution {<br>        address contributor;<br>        uint256 value;<br>    }</pre><pre>    event ProjectCreated(<br>        string indexed projectId,<br>        string name,<br>        string description,<br>        uint256 fundraisingGoal,<br>        address indexed author<br>    );</pre><pre>    event ProjectFunded(<br>        string indexed projectId,<br>        uint256 indexed value,<br>        address indexed contributor<br>    );</pre><pre>    event ProjectStateChanged(<br>        string indexed id,<br>        FundraisingState state<br>    );</pre><pre>    function createProject(<br>        string memory id,<br>        string memory name,<br>        string memory description,<br>        uint256 fundraisingGoal<br>    ) external;</pre><pre>    function fundProject(uint256 projectIndex) external payable;</pre><pre>    function changeProjectState(<br>        FundraisingState newState,<br>        uint256 projectIndex<br>    ) external;</pre><pre>    function getProjectsCount() external view returns (uint256 count);</pre><pre>    function getContributions(string memory projectId)<br>        external view returns (Contribution[] memory);<br>}</pre><h3>The Implementation: CrowdFundingOZ.sol</h3><pre>// SPDX-License-Identifier: GPL-3.0<br>pragma solidity 0.8.20;</pre><pre>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/Pausable.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/ReentrancyGuard.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/Address.sol&quot;;<br>import &quot;./interfaces/ICrowdFunding.sol&quot;;</pre><pre>contract CrowdFundingOZ is ICrowdFunding, Ownable, ReentrancyGuard, Pausable {<br>    using Address for address payable;</pre><pre>    // Custom errors — 30-50% cheaper gas than require strings<br>    error GoalMustBeGreaterThanZero();<br>    error AuthorCannotFundOwnProject();<br>    error ProjectNotReceivingFunds();<br>    error FundValueMustBeGreaterThanZero();<br>    error CallerIsNotProjectAuthor();<br>    error StateAlreadyCurrent();</pre><pre>    struct Project {<br>        string id;<br>        string name;<br>        string description;<br>        address payable author;<br>        FundraisingState state;<br>        uint256 fundraisingGoal;<br>        uint256 funds;<br>    }</pre><pre>    Project[] private s_projects;<br>    mapping(string =&gt; Contribution[]) private s_contributions;</pre><pre>    constructor() Ownable(msg.sender) {}</pre><pre>    function createProject(<br>        string memory id,<br>        string memory name,<br>        string memory description,<br>        uint256 fundraisingGoal<br>    ) external whenNotPaused {<br>        if (fundraisingGoal == 0) revert GoalMustBeGreaterThanZero();</pre><pre>        Project memory newProject = Project({<br>            id: id,<br>            name: name,<br>            description: description,<br>            author: payable(msg.sender),<br>            state: FundraisingState.Opened,<br>            fundraisingGoal: fundraisingGoal,<br>            funds: 0<br>        });</pre><pre>        s_projects.push(newProject);<br>        emit ProjectCreated(id, name, description, fundraisingGoal, msg.sender);<br>    }</pre><pre>    function fundProject(uint256 projectIndex)<br>        external payable nonReentrant whenNotPaused<br>    {<br>        Project storage project = s_projects[projectIndex];</pre><pre>        if (project.author == msg.sender) revert AuthorCannotFundOwnProject();<br>        if (project.state == FundraisingState.Closed)<br>            revert ProjectNotReceivingFunds();<br>        if (msg.value == 0) revert FundValueMustBeGreaterThanZero();</pre><pre>        // CEI pattern: Effects before Interactions<br>        project.funds += msg.value;<br>        s_contributions[project.id].push(<br>            Contribution({ contributor: msg.sender, value: msg.value })<br>        );</pre><pre>        emit ProjectFunded(project.id, msg.value, msg.sender);</pre><pre>        // Interaction last — safe with Address.sendValue()<br>        project.author.sendValue(msg.value);<br>    }</pre><pre>    function changeProjectState(<br>        FundraisingState newState,<br>        uint256 projectIndex<br>    ) external {<br>        Project storage project = s_projects[projectIndex];</pre><pre>        if (project.author != msg.sender) revert CallerIsNotProjectAuthor();<br>        if (project.state == newState) revert StateAlreadyCurrent();</pre><pre>        project.state = newState;<br>        emit ProjectStateChanged(project.id, newState);<br>    }</pre><pre>    function getProjectsCount() external view returns (uint256) {<br>        return s_projects.length;<br>    }</pre><pre>    function getContributions(string memory projectId)<br>        external view returns (Contribution[] memory)<br>    {<br>        return s_contributions[projectId];<br>    }</pre><pre>    function pause() external onlyOwner { _pause(); }<br>    function unpause() external onlyOwner { _unpause(); }<br>}</pre><h3>Why this security architecture matters</h3><p>Layer Mechanism Protects against Reentrancy ReentrancyGuard + nonReentrant The DAO-style attacks ETH transfer Address.sendValue() 2300 gas limit issues State safety CEI pattern Read-after-write exploits Emergency Pausable Zero-day vulnerabilities Access control Ownable + author check Unauthorized state changes Gas efficiency Custom errors 30–50% cheaper reverts</p><h3>Setting Up the Test Environment</h3><h3>Install dependencies</h3><pre>git clone https://github.com/JhonZuluaga007/crowdfunding-protocol-solidity.git<br>cd crowdfunding-protocol-solidity<br>npm install</pre><h3>Compile contracts and generate TypeChain bindings</h3><pre>npm run compile</pre><p>Expected output:</p><pre>Compiled 26 Solidity files successfully (evm target: paris).</pre><p>TypeChain auto-generates typed TypeScript bindings in typechain-types/ — this gives you full IntelliSense on contract methods in your tests.</p><h3>hardhat.config.ts</h3><pre>import { HardhatUserConfig } from &quot;hardhat/config&quot;;<br>import &quot;@nomicfoundation/hardhat-toolbox&quot;;</pre><pre>const config: HardhatUserConfig = {<br>  solidity: {<br>    version: &quot;0.8.20&quot;,<br>    settings: {<br>      evmVersion: &quot;paris&quot;,<br>      optimizer: { enabled: true, runs: 200 },<br>    },<br>  },<br>};</pre><pre>export default config;</pre><h3>Unit Tests: The Production Contract</h3><p>File: test/CrowdFundingOZ.test.ts</p><pre>npm run test:oz  # runs only the production contract tests</pre><h3>The fixture pattern — deploy once, reuse everywhere</h3><p>The most important pattern in Hardhat testing is loadFixture. It deploys your contract once and snapshots the blockchain state — then resets to that snapshot before each test. This makes your suite <strong>fast and isolated</strong>.</p><pre>import { loadFixture } from &quot;@nomicfoundation/hardhat-toolbox/network-helpers&quot;;<br>import { expect } from &quot;chai&quot;;<br>import hre from &quot;hardhat&quot;;</pre><pre>describe(&quot;CrowdFundingOZ&quot;, function () {</pre><pre>  async function deployCrowdFundingFixture() {<br>    const [owner, author, contributor1, contributor2, contributor3] =<br>      await hre.ethers.getSigners();</pre><pre>    const CrowdFundingOZ = await hre.ethers.getContractFactory(&quot;CrowdFundingOZ&quot;);<br>    const crowdFunding = await CrowdFundingOZ.deploy();</pre><pre>    return { crowdFunding, owner, author, contributor1, contributor2, contributor3 };<br>  }</pre><h3>Deployment tests</h3><pre>describe(&quot;Deployment&quot;, function () {<br>    it(&quot;Should set the right owner&quot;, async function () {<br>      const { crowdFunding, owner } = await loadFixture(deployCrowdFundingFixture);<br>      expect(await crowdFunding.owner()).to.equal(owner.address);<br>    });</pre><pre>    it(&quot;Should start unpaused&quot;, async function () {<br>      const { crowdFunding } = await loadFixture(deployCrowdFundingFixture);<br>      expect(await crowdFunding.paused()).to.equal(false);<br>    });</pre><pre>    it(&quot;Should start with zero projects&quot;, async function () {<br>      const { crowdFunding } = await loadFixture(deployCrowdFundingFixture);<br>      expect(await crowdFunding.getProjectsCount()).to.equal(0);<br>    });<br>  });</pre><h3>createProject tests — happy path + error cases</h3><pre>describe(&quot;createProject&quot;, function () {<br>    it(&quot;Should create a project successfully&quot;, async function () {<br>      const { crowdFunding, author } = await loadFixture(deployCrowdFundingFixture);</pre><pre>      await crowdFunding.connect(author).createProject(<br>        &quot;project-1&quot;,<br>        &quot;My Project&quot;,<br>        &quot;A great project&quot;,<br>        hre.ethers.parseEther(&quot;10&quot;)<br>      );</pre><pre>      expect(await crowdFunding.getProjectsCount()).to.equal(1);<br>    });</pre><pre>    it(&quot;Should emit ProjectCreated event&quot;, async function () {<br>      const { crowdFunding, author } = await loadFixture(deployCrowdFundingFixture);<br>      const goal = hre.ethers.parseEther(&quot;10&quot;);</pre><pre>      await expect(<br>        crowdFunding.connect(author).createProject(<br>          &quot;project-1&quot;, &quot;My Project&quot;, &quot;Description&quot;, goal<br>        )<br>      )<br>        .to.emit(crowdFunding, &quot;ProjectCreated&quot;)<br>        .withArgs(&quot;project-1&quot;, &quot;My Project&quot;, &quot;Description&quot;, goal, author.address);<br>    });</pre><pre>    it(&quot;Should revert with GoalMustBeGreaterThanZero when goal is 0&quot;, async function () {<br>      const { crowdFunding, author } = await loadFixture(deployCrowdFundingFixture);</pre><pre>      await expect(<br>        crowdFunding.connect(author).createProject(&quot;p1&quot;, &quot;Name&quot;, &quot;Desc&quot;, 0)<br>      ).to.be.revertedWithCustomError(crowdFunding, &quot;GoalMustBeGreaterThanZero&quot;);<br>    });</pre><pre>    it(&quot;Should revert with EnforcedPause when contract is paused&quot;, async function () {<br>      const { crowdFunding, owner, author } = await loadFixture(deployCrowdFundingFixture);</pre><pre>      await crowdFunding.connect(owner).pause();</pre><pre>      await expect(<br>        crowdFunding.connect(author).createProject(<br>          &quot;p1&quot;, &quot;Name&quot;, &quot;Desc&quot;, hre.ethers.parseEther(&quot;1&quot;)<br>        )<br>      ).to.be.revertedWithCustomError(crowdFunding, &quot;EnforcedPause&quot;);<br>    });<br>  });</pre><h3>fundProject tests — the most critical section</h3><pre>describe(&quot;fundProject&quot;, function () {</pre><pre>    async function deployWithProjectFixture() {<br>      const base = await deployCrowdFundingFixture();<br>      await base.crowdFunding.connect(base.author).createProject(<br>        &quot;project-1&quot;, &quot;Test Project&quot;, &quot;Description&quot;,<br>        hre.ethers.parseEther(&quot;10&quot;)<br>      );<br>      return base;<br>    }</pre><pre>    it(&quot;Should fund a project and transfer ETH to author&quot;, async function () {<br>      const { crowdFunding, author, contributor1 } =<br>        await loadFixture(deployWithProjectFixture);</pre><pre>      const fundAmount = hre.ethers.parseEther(&quot;1&quot;);<br>      const authorBalanceBefore = await hre.ethers.provider.getBalance(author.address);</pre><pre>      await crowdFunding.connect(contributor1).fundProject(0, { value: fundAmount });</pre><pre>      const authorBalanceAfter = await hre.ethers.provider.getBalance(author.address);<br>      expect(authorBalanceAfter - authorBalanceBefore).to.equal(fundAmount);<br>    });</pre><pre>    it(&quot;Should emit ProjectFunded event&quot;, async function () {<br>      const { crowdFunding, contributor1 } =<br>        await loadFixture(deployWithProjectFixture);</pre><pre>      const fundAmount = hre.ethers.parseEther(&quot;0.5&quot;);</pre><pre>      await expect(<br>        crowdFunding.connect(contributor1).fundProject(0, { value: fundAmount })<br>      )<br>        .to.emit(crowdFunding, &quot;ProjectFunded&quot;)<br>        .withArgs(&quot;project-1&quot;, fundAmount, contributor1.address);<br>    });</pre><pre>    it(&quot;Should record contribution in history&quot;, async function () {<br>      const { crowdFunding, contributor1 } =<br>        await loadFixture(deployWithProjectFixture);</pre><pre>      const fundAmount = hre.ethers.parseEther(&quot;0.5&quot;);<br>      await crowdFunding.connect(contributor1).fundProject(0, { value: fundAmount });</pre><pre>      const contributions = await crowdFunding.getContributions(&quot;project-1&quot;);<br>      expect(contributions.length).to.equal(1);<br>      expect(contributions[0].contributor).to.equal(contributor1.address);<br>      expect(contributions[0].value).to.equal(fundAmount);<br>    });</pre><pre>    it(&quot;Should revert when author funds own project&quot;, async function () {<br>      const { crowdFunding, author } =<br>        await loadFixture(deployWithProjectFixture);</pre><pre>      await expect(<br>        crowdFunding.connect(author).fundProject(0, {<br>          value: hre.ethers.parseEther(&quot;1&quot;)<br>        })<br>      ).to.be.revertedWithCustomError(crowdFunding, &quot;AuthorCannotFundOwnProject&quot;);<br>    });</pre><pre>    it(&quot;Should revert when funding a closed project&quot;, async function () {<br>      const { crowdFunding, author, contributor1 } =<br>        await loadFixture(deployWithProjectFixture);</pre><pre>      // Close the project<br>      await crowdFunding.connect(author).changeProjectState(1, 0); // 1 = Closed</pre><pre>      await expect(<br>        crowdFunding.connect(contributor1).fundProject(0, {<br>          value: hre.ethers.parseEther(&quot;1&quot;)<br>        })<br>      ).to.be.revertedWithCustomError(crowdFunding, &quot;ProjectNotReceivingFunds&quot;);<br>    });</pre><pre>    it(&quot;Should revert when msg.value is zero&quot;, async function () {<br>      const { crowdFunding, contributor1 } =<br>        await loadFixture(deployWithProjectFixture);</pre><pre>      await expect(<br>        crowdFunding.connect(contributor1).fundProject(0, { value: 0 })<br>      ).to.be.revertedWithCustomError(crowdFunding, &quot;FundValueMustBeGreaterThanZero&quot;);<br>    });<br>  });</pre><h3>Emergency stop tests</h3><pre>describe(&quot;Pause / Unpause&quot;, function () {<br>    it(&quot;Should pause the contract&quot;, async function () {<br>      const { crowdFunding, owner } = await loadFixture(deployCrowdFundingFixture);</pre><pre>      await crowdFunding.connect(owner).pause();<br>      expect(await crowdFunding.paused()).to.equal(true);<br>    });</pre><pre>    it(&quot;Should revert if non-owner tries to pause&quot;, async function () {<br>      const { crowdFunding, author } = await loadFixture(deployCrowdFundingFixture);</pre><pre>      await expect(<br>        crowdFunding.connect(author).pause()<br>      ).to.be.revertedWithCustomError(crowdFunding, &quot;OwnableUnauthorizedAccount&quot;);<br>    });</pre><pre>    it(&quot;Should unpause and restore operations&quot;, async function () {<br>      const { crowdFunding, owner, author } =<br>        await loadFixture(deployCrowdFundingFixture);</pre><pre>      await crowdFunding.connect(owner).pause();<br>      await crowdFunding.connect(owner).unpause();</pre><pre>      // Should work again after unpause<br>      await expect(<br>        crowdFunding.connect(author).createProject(<br>          &quot;p1&quot;, &quot;Name&quot;, &quot;Desc&quot;, hre.ethers.parseEther(&quot;1&quot;)<br>        )<br>      ).to.not.be.reverted;<br>    });<br>  });</pre><h3>Run the Full Test Suite</h3><pre>npm test</pre><p>Expected output:</p><pre>CrowdFundingOZ<br>    Deployment<br>      ✔ Should set the right owner<br>      ✔ Should start unpaused<br>      ✔ Should start with zero projects<br>    createProject<br>      ✔ Should create a project successfully<br>      ✔ Should emit ProjectCreated event<br>      ✔ Should revert with GoalMustBeGreaterThanZero when goal is 0<br>      ✔ Should revert with EnforcedPause when contract is paused<br>    fundProject<br>      ✔ Should fund a project and transfer ETH to author<br>      ✔ Should emit ProjectFunded event<br>      ✔ Should record contribution in history<br>      ✔ Should revert when author funds own project<br>      ✔ Should revert when funding a closed project<br>      ✔ Should revert when msg.value is zero</pre><pre>  ... (111 more tests across learning contracts)</pre><pre>  129 passing (370ms)</pre><h3>The Educational Progression: From Zero to Production</h3><p>One of the most valuable parts of this project is the contracts/learning/ directory — a step-by-step progression showing exactly how the production contract was built.</p><p>Contract Concept introduced variables/Identity.sol State variables, constructor, basic types functions/Fund.sol Payable functions, ETH transfer enums/User.sol Enums as state representation errors/Asset.sol Custom errors with parameters events/Asset.sol Events and off-chain indexing functionModifiers/Permission.sol OZ Ownable, onlyOwner modifier project/CrowdFunding1.sol Basic constructor-based project project/CrowdFunding6.sol FundraisingState enum, full struct project/CrowdFunding.sol Array of projects, contribution mapping</p><p>Each learning contract has its own test file. This makes the test suite an educational tool as much as a safety net.</p><h3>End-to-End Functional Simulation</h3><p>Unit tests validate individual functions in isolation. But real protocols need <strong>sequential validation</strong> — does the system behave correctly across multiple interactions on a live blockchain?</p><pre>npx hardhat run test/functional/simulate.ts</pre><p>The simulation runs 4 complete business scenarios on a <strong>single shared blockchain instance</strong> (no loadFixture resets between scenarios):</p><h3>Scenario 1 — Happy Path</h3><pre>=== SCENARIO 1: Happy Path ===<br>✅ Project alpha created<br>💸 Contributor 1 funded 0.5 ETH — author balance increased<br>💸 Contributor 2 funded 1.0 ETH — project.funds: 1.5 ETH<br>🔒 Fund closed project — reverts with ProjectNotReceivingFunds (expected)<br>✅ Project reopened by author<br>💸 Contributor 3 funded 0.5 ETH — goal reached</pre><h3>Scenario 2 — Multiple Projects</h3><pre>=== SCENARIO 2: Multiple Projects ===<br>✅ Author 1 created project-A, Author 2 created project-B<br>💸 Contributions isolated — getContributions() verified per project<br>📋 getProjectsCount() == 2</pre><h3>Scenario 3 — Emergency Stop</h3><pre>=== SCENARIO 3: Emergency Stop ===<br>🔒 createProject blocked while paused — EnforcedPause (expected)<br>🔒 fundProject blocked while paused — EnforcedPause (expected)<br>✅ Both operations restored after unpause</pre><h3>Scenario 4 — Access Control</h3><pre>=== SCENARIO 4: Access Control ===<br>🔒 Non-author changeProjectState — CallerIsNotProjectAuthor (expected)<br>🔒 Author funds own project — AuthorCannotFundOwnProject (expected)<br>🔒 Non-owner pause attempt — OwnableUnauthorizedAccount (expected)<br>✅ Ownership transferred and verified</pre><pre>ALL SCENARIOS PASSED — 0 failures</pre><h3>Deploy to Testnet (Sepolia)</h3><p>Once your tests pass, deploy to Sepolia to verify on a real network:</p><pre># 1. Configure environment<br>cp .env.example .env<br># Edit .env:<br># SEPOLIA_RPC_URL=https://sepolia.infura.io/v3/YOUR_KEY<br># PRIVATE_KEY=0xYOUR_PRIVATE_KEY<br># ETHERSCAN_API_KEY=YOUR_ETHERSCAN_KEY</pre><pre># 2. Deploy<br>npm run deploy:sepolia</pre><p>Expected output:</p><pre>CrowdFundingOZ deployed to: 0x...<br>Owner: 0x...<br>Paused: false</pre><h3>Key Takeaways</h3><p>After building 129 tests for a production smart contract protocol, here are the patterns that matter most:</p><p><strong>1. Always use </strong><strong>loadFixture</strong> — it snapshots blockchain state and resets before each test. Without it, tests contaminate each other and you get false positives.</p><p><strong>2. Test custom errors with </strong><strong>revertedWithCustomError</strong> — not .to.be.reverted. The specific error matters for security audits.</p><p><strong>3. Verify events with </strong><strong>.to.emit().withArgs()</strong> — events are the only off-chain record of on-chain state changes. Test them precisely.</p><p><strong>4. CEI pattern is non-negotiable</strong> — always update state before making external calls. ReentrancyGuard is a safety net, not a substitute for the pattern.</p><p><strong>5. Use </strong><strong>Address.sendValue() over </strong><strong>.transfer()</strong> — .transfer() has a 2300 gas limit that fails for contract recipients. sendValue forwards all gas safely.</p><p><strong>6. Combine unit tests + functional simulation</strong> — unit tests catch individual bugs, simulation validates real sequential workflows. You need both.</p><p><strong>7. Custom errors over require strings</strong> — 30–50% cheaper gas on revert, better tooling support, cleaner ABI.</p><h3>What’s Next</h3><ul><li><strong>Chainlink VRF</strong> — replace the predictable project ID with verifiable on-chain randomness</li><li><strong>Upgrade to OZ v5 Ownable2Step</strong> — safer ownership transfer with two-step confirmation</li><li><strong>Foundry</strong> — parallel test suite with forge test for gas snapshots and fuzz testing</li><li><strong>Slither + Mythril</strong> — static analysis for deeper vulnerability detection</li></ul><h3>Resources</h3><ul><li><a href="https://github.com/JhonZuluaga007/crowdfunding-protocol-solidity">GitHub Repository</a></li><li><a href="https://hardhat.org/docs">Hardhat Documentation</a></li><li><a href="https://docs.openzeppelin.com/contracts/5.x/">OpenZeppelin v5 Contracts</a></li><li><a href="https://docs.ethers.org/v6/">ethers.js v6 Documentation</a></li><li><a href="https://consensys.github.io/smart-contract-best-practices/">Ethereum Smart Contract Security Best Practices</a></li></ul><p><em>If this was useful, give the repo a ⭐ on GitHub and follow me for more Web3 engineering content.</em></p><p><em>→ GitHub: </em><a href="https://github.com/JhonZuluaga007"><em>JhonZuluaga007</em></a> <em>→ LinkedIn: </em><a href="https://linkedin.com/in/jhonzusa"><em>jhonzusa</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f842aabc8842" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>