<?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 Christian Inyekaka on Medium]]></title>
        <description><![CDATA[Stories by Christian Inyekaka on Medium]]></description>
        <link>https://medium.com/@christianinyekaka?source=rss-fca51910fb50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KEigshVWYTqx_EFwieBO2Q@2x.jpeg</url>
            <title>Stories by Christian Inyekaka on Medium</title>
            <link>https://medium.com/@christianinyekaka?source=rss-fca51910fb50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:28:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christianinyekaka/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 Deploy Your Smart Contract on Virtual TestNet(Without Faucet Headaches)]]></title>
            <link>https://coinsbench.com/how-to-deploy-your-smart-contract-on-virtual-testnet-without-faucet-headaches-c2332f90ea48?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2332f90ea48</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[virtual]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[testnet]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 13:56:44 GMT</pubDate>
            <atom:updated>2025-03-31T10:36:03.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UhCKci_OkwsTUqq2.png" /></figure><p>One major challenge developers face with public testnets is obtaining test tokens from faucets. Many testnets require developers to request tokens through faucets, which often have limited supply, long wait times, or strict rate limits. In some cases, faucets run out of tokens entirely, forcing developers to search for alternative sources or wait for replenishment. Additionally, some faucets impose verification steps, such as social media authentication or CAPTCHA challenges, adding unnecessary friction to the development process. These constraints can delay testing, disrupt workflows, and slow down smart contract deployment.</p><p>This is where Virtual TestNets provide a game-changing solution, allowing developers to bypass faucet limitations entirely. With a private testnet, developers have unlimited access to test tokens and complete control over the environment. This enables them to thoroughly test smart contracts under conditions similar to production, ensuring they behave as expected before deployment to the mainnet. By simulating real-world scenarios without public network limitations, Virtual TestNets provide a faster, more reliable, and cost-effective testing framework for blockchain development.</p><h3>Prerequisites</h3><p>Before proceeding, ensure you have the following:</p><ol><li><strong>Basic Solidity Understanding</strong> (write simple smart contracts)</li><li><strong>Node.js v18+ &amp; TypeScript</strong> (<a href="https://nodejs.org/">installation guide</a>)</li><li><strong>Tenderly Account</strong> (<a href="https://dashboard.tenderly.co/register">free signup</a>)</li><li><strong>Tenderly CLI Installed</strong> <em>(If not, follow the installation steps </em><a href="https://github.com/Tenderly/tenderly-cli"><em>here</em></a><em>)</em></li><li><strong>MetaMask</strong> installed (<a href="https://metamask.io/">download</a>)</li></ol><h3>Step 1: Creating a Virtual TestNet on Tenderly</h3><p>Navigate to your dashboard and click on Create Virtual RPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HxGJ1nLmqkACqOJjvAB_A.png" /></figure><p>Fill in the required options and click Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmO-G_DyrhwzQPKKVR8Obw.png" /></figure><p>Add the newly created Virtual TestNet to MetaMask</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Iv1PpH_ae3PUQjvwf2gHg.png" /></figure><p>Fund your wallet with test tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jm5W9u6zXbQhg2V-bgf4YQ.png" /></figure><p>You can add any amount (even one billion tokens if needed).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V15hdUCip5KRK21ULDAC5w.png" /></figure><p>The transaction will be visible on our virtual Etherscan, and the balance will be reflected in your wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaB98KuS8Jcez94vNHagjQ.png" /></figure><h3>Step 2: Installing the Hardhat Plugin</h3><p>To deploy our smart contract on Tenderly, we need to install a Hardhat plugin. Run the following command:</p><pre>npm install --save-dev @tenderly/hardhat-tenderly</pre><h3>Step 3: Updating hardhat.config.ts</h3><p>Update your hardhat.config.ts file to match the configuration below:</p><pre>import { HardhatUserConfig } from &quot;hardhat/config&quot;;<br>import &quot;@nomicfoundation/hardhat-toolbox&quot;;<br>import * as tenderly from &quot;@tenderly/hardhat-tenderly&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br><br>const config: HardhatUserConfig = {<br>  solidity: &quot;0.8.28&quot;,<br>  networks: {<br>    virtualChain: {<br>      url: process.env.VIRTUAL_CHAIN_URL || &quot;&quot;,<br>      accounts: [process.env.PRIVATE_KEY || &quot;&quot;],<br>    },<br>  },<br>  tenderly: {<br>    project: process.env.TENDERLY_PROJECT || &quot;&quot;,<br>    username: process.env.TENDERLY_USERNAME || &quot;&quot;,<br>  },<br>};<br><br>export default config;</pre><h4>Important:</h4><p>Make sure your .env file contains the following variables:</p><pre>VIRTUAL_CHAIN_URL=&lt;Your Virtual TestNet URL&gt;<br>PRIVATE_KEY=&lt;Your Wallet Private Key&gt; //the account that will deploy<br><br>//https://docs.tenderly.co/account/projects/account-project-slug<br>TENDERLY_PROJECT=&lt;Your Tenderly Project Name&gt;<br>TENDERLY_USERNAME=&lt;Your Tenderly Username&gt;</pre><h3>Step 4: Deploying Your Contract</h3><p>Make sure you have a script for deploying your smart contract, then run this command:</p><p><em>Replace </em><em>./ignition/modules/Deploy.s.ts with the actual path of your deployment script file.</em></p><pre><br>npx hardhat ignition deploy ./ignition/modules/Deploy.s.ts --network virtualChain  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Esl2Jy5fWg9w5CvM19wswg.png" /></figure><p>Once completed, you will see the Integrate and Deploy tab marked as completed, indicating that the contract has been successfully deployed. You can now send transactions to it and interact with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAwLzkbJudww2n9AdIs5uw.png" /></figure><p>Here is our transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZA57FdxTd5aRP4ku6Tqhg.png" /></figure><h3>Conclusion</h3><p>By following these steps, you can efficiently deploy and test your smart<strong> </strong>contracts on a Virtual TestNet without the limitations of public testnets. This setup ensures faster testing, complete control, and a production-like environment, allowing you to confidently deploy your contracts on the mainnet. Happy coding! 🚀</p><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2332f90ea48" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/how-to-deploy-your-smart-contract-on-virtual-testnet-without-faucet-headaches-c2332f90ea48">How to Deploy Your Smart Contract on Virtual TestNet(Without Faucet Headaches)</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple ERC-4626 Yield-Bearing in Solidity]]></title>
            <link>https://coinsbench.com/building-a-simple-erc-4626-yield-bearing-in-solidity-eccf3d9bf37f?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/eccf3d9bf37f</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 17:37:00 GMT</pubDate>
            <atom:updated>2025-01-11T17:37:00.337Z</atom:updated>
            <content:encoded><![CDATA[<p>The DeFi (Decentralized Finance) ecosystem thrives on innovative protocols that enhance user experience and profitability. In this guide, we’ll implement a yield-bearing vault using the ERC-4626 standard. The vault will manage user deposits, yield generation, and withdrawals while providing transparency and standardized functionality.</p><h3>What Are Yield-Bearing Vaults?</h3><p>Yield-bearing vaults are DeFi smart contracts that optimize returns on cryptocurrency assets by pooling and allocating them across various protocols. Users deposit tokens into these vaults and receive vault-specific tokens (vTokens) representing their share of pooled assets and earnings. The vaults employ automated strategies such as lending, borrowing, staking, and liquidity provision to maximize yield while simplifying the process for users.</p><p>They are generally secure due to rigorous audits and are widely used by platforms like Aave, Compound, and Curve for efficient fund management and passive income generation.</p><h3>What is ERC-4626?<a href="https://www.quicknode.com/guides/ethereum-development/smart-contracts/how-to-use-erc-4626-with-your-smart-contract#what-is-erc-4626">​</a></h3><p>The <strong>ERC-4626 Tokenized Vault Standard</strong> is a protocol for creating tokenized vaults representing yield-bearing token shares. It provides a standardized API for managing such vaults and extends the ERC-20 token standard to enable users to profit from staked assets.</p><h3>Key Features:</h3><ol><li><strong>Deposits and Redeems</strong>: Facilitates the seamless deposit of underlying tokens and redemption of yield-bearing vault tokens.</li><li><strong>Conversion Rates</strong>: Standardized methods to calculate the exchange rate between underlying tokens and vault shares.</li><li><strong>Vault Balances</strong>: Tracks user balances and total vault holdings uniformly.</li><li><strong>Interfaces</strong>: Provides consistent APIs for integration with other DeFi protocols.</li><li><strong>Events</strong>: Emits standardized events for actions like deposits, withdrawals, and transfers for improved transparency and tracking.</li></ol><p>ERC-4626 simplifies integration, improves efficiency, and enhances user experience across tokenized vault implementations.</p><h3>Prerequisites</h3><ul><li>Understanding of Ethereum and smart contracts.</li><li>Familiarity with ERC-20 and ERC-4626 standards.</li><li>Understanding of Solidity for smart contract development.</li><li>JavaScript/TypeScript for testing and interaction.</li><li>Understanding of Hardhat</li></ul><h3>Folder Structure</h3><pre>📦vault<br> ┣ 📂cache<br> ┃ ┗ 📜solidity-files-cache.json<br> ┣ 📂contracts<br> ┃ ┣ 📜Token.sol             # ERC20 Token contract<br> ┃ ┗ 📜Vault.sol             # ERC4626 Vault contract<br> ┣ 📂ignition<br> ┃ ┗ 📂modules<br> ┃ ┃ ┗ 📜vault.ts            # Deployment script<br> ┣ 📂test<br> ┃ ┗ 📜test.ts               # Unit tests for contracts<br> ┣ 📜.gitignore              # Ignore unnecessary files for version control<br> ┣ 📜hardhat.config.ts       # Hardhat project configuration<br> ┣ 📜package-lock.json       # NPM dependency lock file<br> ┣ 📜package.json            # NPM package manifest<br> ┣ 📜README.md               # Project documentation<br> ┗ 📜tsconfig.json           # TypeScript configuration</pre><h4>Dependencies</h4><p>We will use OpenZeppelin’s libraries for standardized and secure implementations of ERC-20 and ERC-4626.</p><p>Install the dependency with:</p><pre>npm i @openzeppelin/contracts</pre><h3>Contracts</h3><h4>1. ERC-20 Token Contract (Token.sol)</h4><p>This is the asset token users will deposit into the vault. It inherits from OpenZeppelin’s ERC20 contract.</p><pre>// SPDX-License-Identifier: MIT<br>// Compatible with OpenZeppelin Contracts ^5.0.0<br>pragma solidity ^0.8.27;<br>import {ERC20} from &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;; <br>import {ERC20Burnable} from &quot;@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol&quot;;<br>import {ERC20Pausable} from &quot;@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol&quot;;<br>import {ERC20Permit} from &quot;@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol&quot;;<br>import {Ownable} from &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>contract Emma is ERC20, ERC20Burnable, ERC20Pausable, Ownable, ERC20Permit {<br>    constructor()<br>        ERC20(&quot;Emma&quot;, &quot;EUSD&quot;)<br>        Ownable(msg.sender)<br>        ERC20Permit(&quot;Emma&quot;)<br>    {<br>        _mint(msg.sender, 18 * 10 ** decimals());<br>    }<br><br>    function pause() public onlyOwner {<br>        _pause();<br>    }<br><br>    function unpause() public onlyOwner {<br>        _unpause();<br>    }<br><br>    function mint(address to, uint256 amount) public onlyOwner {<br>        _mint(to, amount);<br>    }<br><br>    // The following functions are overrides required by Solidity.<br><br>    function _update(address from, address to, uint256 value)<br>        internal<br>        override(ERC20, ERC20Pausable)<br>    {<br>        super._update(from, to, value);<br>    }<br>}</pre><p>Yield-Bearing Vault Contract (Vault.sol)</p><h3>Step 1: Setting up the contract with the right imports</h3><p>The first step is to declare the SPDX license identifier, specify the Solidity version, and import the ERC-4626 contract from a trusted source. This allows us to inherit the functionality from the ERC-4626 standard and extend it with our features.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.27;<br>import &quot;@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol&quot;;</pre><ul><li><strong>SPDX-License-Identifier</strong>: Defines the license type for the contract.</li><li><strong>Solidity version 0.8.27</strong>: The version of Solidity used for compiling the contract.</li><li><strong>ERC-4626 Import</strong>: The ERC-4626 standard from OpenZeppelin</li></ul><h3>Step 2: Defining the Contract and Inheriting ERC-4626</h3><p>Next, we define the contract and inherit from the ERC-4626 library. This gives us all the standard functionality of ERC-4626, such as deposit, withdrawal, and share issuance.</p><pre>contract TokenVault is ERC4626 </pre><h3>Step 3: Tracking User Shares with a Mapping</h3><p>We need a way to track the number of shares each user has in the vault. A mapping allows us to store this information, where the key is the user’s address and the value is the number of shares they hold.</p><pre>    mapping(address =&gt; uint256) public shareHolder;</pre><h3>Step 4: events for transparency</h3><p>we are going to emit an event when a deposition is made and a withdraw</p><pre>    event Deposit(address indexed user, uint256 amount);<br>    event Withdraw(address indexed user, uint256 amount);</pre><h3>Step 5: Creating the Constructor</h3><p>The constructor will initialize the vault with the appropriate ERC-20 token (the asset users will deposit), the vault token name, and the vault token symbol.</p><pre>  constructor(<br>        ERC20 _asset,<br>        string memory _name,<br>        string memory _symbol<br>    )  ERC4626(_asset) ERC20(_name,_symbol) {<br>    }</pre><ul><li><strong>_asset</strong>: The address of the ERC-20 token that will be deposited into the vault.</li><li><strong>_name and </strong><strong>_symbol</strong>: The name and symbol of the vault’s token (the vTokens that represent the shares of the vault).</li></ul><p>This constructor sets up the asset token, name, and symbol, and calls the constructor of the ERC-4626 contract.</p><h3>Step 6: The Deposit Function</h3><p>Now, we create the _deposit function. This function allows users to deposit their tokens into the vault and receive vault tokens (shares) in return. These shares represent their stake in the vault and can be redeemed later.</p><pre> function _deposit(uint _assets) external {<br>        require(_assets &gt; 0, &quot;Deposit less than Zero&quot;);<br>        deposit(_assets, msg.sender);<br>        shareHolder[msg.sender] += _assets;<br>        emit Deposit(msg.sender, _assets);<br>    }</pre><ul><li><strong>require(_assets &gt; 0)</strong>: Ensures that the deposit amount is greater than zero.</li><li><strong>deposit(_assets, msg.sender)</strong>: Calls the ERC-4626 deposit function to transfer the tokens to the vault and mint the corresponding vault tokens.</li><li><strong>shareHolder[msg.sender] += _assets</strong>: Increases the user’s share balance by the amount of tokens they deposited.</li><li>emit Deposit(msg.sender,_assets): emits an event with the address of the deposer and the amount deposed</li></ul><h3>Step 7: The Withdraw Function</h3><p>The _withdraw function allows users to redeem their shares in exchange for the original deposit amount plus in our case 10% yield earned. Here we calculate the yield and allow withdrawals based on the shares the user holds.</p><pre> function _withdraw(uint _shares, address _receiver) external {<br>        require(_shares &gt; 0, &quot;withdraw must be greater than Zero&quot;);<br>        require(_receiver != address(0), &quot;Zero Address&quot;);<br>        require(shareHolder[msg.sender] &gt; 0, &quot;Not a share holder&quot;);<br>        require(shareHolder[msg.sender] &gt;= _shares, &quot;Not enough shares&quot;);<br>        uint256 yield = (10 * _shares) / 100;<br>        uint256 assets = _shares + yield;<br>        redeem(assets, _receiver, msg.sender);<br>        shareHolder[msg.sender] -= _shares;<br>        emit Withdraw(msg.sender, _shares);<br>    }</pre><ul><li><strong>require(_shares &gt; 0)</strong>: Ensures the withdrawal amount is greater than zero.</li><li><strong>require(_receiver != address(0))</strong>: Ensures the receiver address is not a zero address.</li><li><strong>require(shareHolder[msg.sender] &gt;= _shares)</strong>: Verifies the user has enough shares to withdraw.</li><li><strong>uint256 percent = (10 * _shares) / 100</strong>: Calculates a 10% yield on the shares being withdrawn.</li><li><strong>redeem(assets, _receiver, msg.sender)</strong>: Calls the ERC-4626 redeem function to transfer the underlying asset tokens to the receiver and burn the user&#39;s shares.</li><li><strong>shareHolder[msg.sender] -= _shares</strong>: Decreases the user’s share balance after the withdrawal.</li><li>emit Withdrawal(msg. sender,_assets): emits an event with the address of the user that wants to withdraw and the amount withdrawn</li></ul><h3>Step 8: Helper Function for User Balance</h3><p>Finally, we create a function to return the total share balance of a specific user, so they can check how much they have.</p><pre><br>function totalAssetOfUser( address _user) external view returns (uint256) {<br>        return shareHolder[_user];<br>     }</pre><p>Here’s the complete VaultToken smart contract:</p><pre>// SPDX-License-Identifier: MIT<br>// Compatible with OpenZeppelin Contracts ^5.0.0<br>pragma solidity ^0.8.27;<br>import &quot;@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol&quot;;<br>import &quot;@openzeppelin/contracts/interfaces/IERC20.sol&quot;;<br><br><br><br>contract TokenVault is ERC4626 {<br>    mapping(address =&gt; uint256) public shareHolder;<br>    event Deposit(address indexed user, uint256 amount);<br>    event Withdraw(address indexed user, uint256 amount);<br><br>    constructor(<br>        ERC20 _asset,<br>        string memory _name,<br>        string memory _symbol<br>    )  ERC4626(_asset) ERC20(_name,_symbol) {<br>    }<br><br>   <br>    function _deposit(uint _assets) external {<br>        require(_assets &gt; 0, &quot;Deposit less than Zero&quot;);<br>        deposit(_assets, msg.sender);<br>        shareHolder[msg.sender] += _assets;<br>        emit Deposit(msg.sender, _assets);<br>    }<br><br>   <br>    function _withdraw(uint _shares, address _receiver) external {<br>        require(_shares &gt; 0, &quot;withdraw must be greater than Zero&quot;);<br>        require(_receiver != address(0), &quot;Zero Address&quot;);<br>        require(shareHolder[msg.sender] &gt; 0, &quot;Not a share holder&quot;);<br>        require(shareHolder[msg.sender] &gt;= _shares, &quot;Not enough shares&quot;);<br>        uint256 yield = (10 * _shares) / 100;<br>        uint256 assets = _shares + yield;<br>        redeem(assets, _receiver, msg.sender);<br>        shareHolder[msg.sender] -= _shares;<br>        emit Withdraw(msg.sender, _shares);<br>    }<br>     function totalAssetOfUser( address _user) external view returns (uint256) {<br>        return shareHolder[_user];<br>     }<br><br>    <br>}</pre><h3>Testing</h3><h4>Sample Test in test/test.ts</h4><pre>import {<br>  time,<br>  loadFixture,<br>} from &quot;@nomicfoundation/hardhat-toolbox/network-helpers&quot;;<br>import { anyValue } from &quot;@nomicfoundation/hardhat-chai-matchers/withArgs&quot;;<br>import { expect } from &quot;chai&quot;;<br>import hre from &quot;hardhat&quot;;<br><br>describe(&quot;Lock&quot;, function () {<br>  <br>  async function deployOneYearLockFixture() {<br>    <br>    const [owner, emma, liz, jr] = await hre.ethers.getSigners();<br><br>    const Token = await hre.ethers.getContractFactory(&quot;Emma&quot;);<br>    const token = await Token.deploy();<br>    const Vault = await hre.ethers.getContractFactory(&quot;TokenVault&quot;);<br>    const vault = await Vault.deploy(token.target, &quot;EToken&quot;, &quot;ETK&quot;);<br><br>    return { owner, token, emma, liz, jr, vault };<br>  }<br><br>  describe(&quot;Deployment&quot;, function () {<br>    it(&quot;Should set the right token address&quot;, async function () {<br>      const { token, vault } = await loadFixture(deployOneYearLockFixture);<br><br>      expect(vault.target).to.be.properAddress;<br>      expect(vault.target).to.be.properAddress;<br>    });<br>    it(&quot;Should set the right token name&quot;, async function () {<br>      const { token, vault } = await loadFixture(deployOneYearLockFixture);<br><br>      expect(await vault.name()).to.equal(&quot;EToken&quot;);<br>    });<br>  });<br>  describe(&quot;Deposit&quot;, function () {<br>    it(&quot;should deposit fund and withdraw with yield intrest of 10 %&quot;, async function name() {<br>      const { token, vault, emma } = await loadFixture(<br>        deployOneYearLockFixture<br>      );<br>      await token.mint(emma.address, 1000);<br>      await token.connect(emma).approve(vault.target, 1000);<br>      await vault.connect(emma)._deposit(100);<br>      expect(await vault.balanceOf(emma.address)).to.equal(100);<br>      expect(await token.balanceOf(emma.address)).to.equal(900);<br>      expect(await token.balanceOf(vault.target)).to.equal(100);<br>      await vault.connect(emma)._withdraw(50, emma.address);<br>      expect(await vault.balanceOf(emma.address)).to.equal(45);<br>      expect(await token.balanceOf(emma.address)).to.equal(955);<br>      expect(await token.balanceOf(vault.target)).to.equal(45);<br>      <br>    });<br>it(&quot;should revert&quot;, async function name() {<br>      const { token, vault, emma } = await loadFixture(<br>        deployOneYearLockFixture<br>      );<br>      await token.mint(emma.address, 1000);<br>      await token.connect(emma).approve(vault.target, 1000);<br>      await vault.connect(emma)._deposit(100);<br>      expect(await vault.balanceOf(emma.address)).to.equal(100);<br>      expect(await token.balanceOf(emma.address)).to.equal(900);<br>      expect(await token.balanceOf(vault.target)).to.equal(100);<br>      expect(vault.connect(emma)._withdraw(100, emma.address)).to.revertedWith(<br>        &#39;ERC4626ExceededMaxRedeem(&quot;0x70997970C51812dc3A010C7d01b50e0d17dc79C8&quot;, 55, 45)&#39;<br>      );<br>      <br>    });<br>  });<br>});</pre><p>Emma’s balance is 1000 EUSD, as we just deposited 100 wei of ESDC, and now her balance is 900 EUSD because we minted only 1000 EUSD, of which 100 are now deposited in the TokenVault contract.</p><p>Let’s withdraw our asset tokens along with the yield in exchange for shares/vUSDC by interacting with the <strong>_withdraw</strong> function. we tried to withdraw 50 plus the 10% we got 55 and our balance became 955 EUSD.</p><p>Now, there is a catch. If we attempt to withdraw all the tokens we deposited, we will encounter an error. This is because the contract does not have a sufficient asset balance. If we do the calculation, 100VUSDC would equate to 110 EUSDC (100 from the original deposit plus 10 from yield), but the contract only has 100 wei of EUSDC.</p><h3>Conclusion</h3><p>If you’ve made it this far, congratulations! You are well on your way to becoming a SmartContract expert. This guide demonstrates how to implement a simple vault that enables users to deposit tokens, earn yield, and withdraw their assets with minimal complexity. By leveraging the standardized API of ERC-4626, developers can integrate their vaults seamlessly into the broader DeFi ecosystem.</p><p>While this implementation offers a foundational understanding of ERC-4626 vaults, it is essential to address real-world challenges like yield generation, liquidity management, and security. Connecting the vault to yield sources such as lending protocols or staking mechanisms and incorporating robust testing and auditing practices will prepare the system for production environments.</p><p>With proper enhancements, an ERC-4626 vault can unlock new opportunities for DeFi users, providing passive income while simplifying asset management. This standard’s versatility and efficiency make it a cornerstone for the next generation of decentralized financial applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eccf3d9bf37f" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/building-a-simple-erc-4626-yield-bearing-in-solidity-eccf3d9bf37f">Building a Simple ERC-4626 Yield-Bearing in Solidity</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a terminal-based quiz game in JavaScript using Node.js: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@christianinyekaka/creating-a-terminal-based-quiz-game-in-javascript-using-node-js-a-step-by-step-guide-8ee04e358920?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ee04e358920</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 20:16:31 GMT</pubDate>
            <atom:updated>2024-12-24T20:16:31.578Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, you’ll learn how to create an interactive terminal-based quiz game using JavaScript and Node.js. This project is ideal for beginners looking to practice core programming concepts, such as modular code, error handling, and user input management. By the end of this tutorial, you’ll have a fun and functional game to play and share with friends! Let’s dive in!</p><h3>Features of the Quiz Game</h3><ol><li><strong>Interactive Gameplay</strong>: Players can select a topic, answer multiple-choice questions, and receive immediate feedback.</li><li><strong>Score Tracking</strong>: The game keeps track of the player’s score, displaying it after every question.</li><li><strong>Continuous Flow</strong>: Once a topic is selected, the game asks questions until the player decides to quit.</li><li><strong>User-Friendly Design</strong>: The interface includes clear instructions, a welcome banner(generated using <a href="http://patorjk.com/software/taag/">Text to ASCII Art Generator</a> site), and a seamless experience.</li></ol><h3>Game Workflow</h3><p>Here’s the step-by-step workflow of the game:</p><ol><li>Display a welcome banner.</li><li>Ask the player to choose a topic (e.g., Coding Questions or General Knowledge).</li><li>Continuously display questions from the selected topic.</li><li>Allow the player to quit at any time by typing “quit”.</li><li>Display the final score when the game ends.</li></ol><h3>folder Structure</h3><pre>quizGame<br> ┣ data.js<br> ┣ index.js<br> ┣ package.json<br> ┗ questionGenerator.js</pre><h3>Implementation</h3><h4>data.js</h4><pre>export const generalKnowledgeQA = [<br>  { question: &quot;What is the capital of France?&quot;, answer: &quot;Paris&quot; },<br>  { question: &quot;Who wrote &#39;Romeo and Juliet&#39;?&quot;, answer: &quot;William Shakespeare&quot; },<br>  {<br>    question: &quot;What is the smallest planet in our solar system?&quot;,<br>    answer: &quot;Mercury&quot;,<br>  }.<br>//add more questions<br> <br>];<br>export const codingQuestions = [<br>  {<br>    question: &quot;What is a closure in JavaScript?&quot;,<br>    answer:<br>      &quot;A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing.&quot;,<br>  },<br>  {<br>    question:<br>      &quot;What is the difference between var, let, and const in JavaScript?&quot;,<br>    answer:<br>      &quot;var is function-scoped, while let and const are block-scoped. const is used for variables that should not be reassigned.&quot;,<br>  },<br> <br><br>  // Add more questions<br>];</pre><p>This is the file where we get our questions and answers.</p><h4>QuestionsGenerator.js</h4><pre>import { codingQuestions, generalKnowledgeQA } from &quot;./data.js&quot;;<br><br>export default function generateQuestionWithAssertions(type) {<br>  // Validate input type<br>  let dataSource = [];<br>  if (type === &quot;codingQuestions&quot;) {<br>    dataSource = codingQuestions;<br>  } else if (type === &quot;generalKnowledgeQA&quot;) {<br>    dataSource = generalKnowledgeQA;<br>  } else {<br>    throw new Error(<br>      &quot;Invalid type. Choose &#39;codingQuestions&#39; or &#39;generalKnowledgeQA&#39;.&quot;<br>    );<br>  }<br><br>  // Ensure there are enough questions to create assertions<br>  if (dataSource.length &lt; 4) {<br>    throw new Error(&quot;Not enough questions in the data source.&quot;);<br>  }<br><br>  // Select 4 unique random questions<br>  const questions = [];<br>  const usedIndices = new Set();<br>  while (questions.length &lt; 4) {<br>    const randomIndex = Math.floor(Math.random() * dataSource.length);<br>    if (!usedIndices.has(randomIndex)) {<br>      questions.push(dataSource[randomIndex]);<br>      usedIndices.add(randomIndex);<br>    }<br>  }<br><br>  // Pick one question as the main question<br>  const choosingQuestionRandomIndex = Math.floor(Math.random() * questions.length);<br>  const mainQst =questions[choosingQuestionRandomIndex];<br><br>  // Shuffle the questions to serve as assertions<br>  let currentIndex = questions.length;<br>  while (currentIndex !== 0) {<br>    const randomIndex = Math.floor(Math.random() * currentIndex);<br>    currentIndex--;<br>    [questions[currentIndex], questions[randomIndex]] = [<br>      questions[randomIndex],<br>      questions[currentIndex],<br>    ];<br>  }<br>  const indexofAnswer = questions.findIndex((question) =&gt; question === mainQst);<br><br>  const assertions = {<br>    a: questions[0].answer,<br>    b: questions[1].answer,<br>    c: questions[2].answer,<br>    d: questions[3].answer,<br>  };<br>  const correctAnswer = assertions[Object.keys(assertions)[indexofAnswer]];<br><br>  return {<br>    q: mainQst,<br>    assertions,<br>    correctAnswer,<br>  };<br>}</pre><h3>Features in the Code</h3><h3>1. Dynamic Data Handling</h3><ul><li>The function accepts a type parameter (e.g., &quot;codingQuestions&quot; or &quot;generalKnowledgeQA&quot;) and dynamically selects the appropriate dataset.</li><li>It validates the type to ensure it&#39;s either &quot;codingQuestions&quot; or &quot;generalKnowledgeQA&quot;, preventing invalid input.</li></ul><h3>2. Randomization of Questions</h3><ul><li><strong>Random Question Selection</strong>: Four unique random questions are selected from the chosen dataset using a while loop and a Set to track used indices.</li><li>This ensures no duplicate questions appear in the assertions.</li></ul><h3>3. Randomized Assertions</h3><ul><li>The function shuffles the selected questions to create randomized multiple-choice assertions using the <strong>Fisher-Yates Shuffle Algorithm</strong>:</li></ul><pre>let currentIndex = questions.length;<br> while (currentIndex !== 0) { <br>  const randomIndex = Math.floor(Math.random() * currentIndex); <br>  currentIndex--;  <br> [questions[currentIndex], questions[randomIndex]] = [questions[randomIndex],     questions[currentIndex],   ];<br> }</pre><ul><li>This ensures that the correct answer appears in a random position every time.</li></ul><h3>4. Mapping Assertions to Options</h3><ul><li>After shuffling, the answers are mapped to options a, b, c, and d:</li></ul><pre>const assertions = {  <br> a: questions[0].answer, <br>  b: questions[1].answer,  <br> c: questions[2].answer, <br>  d: questions[3].answer, <br>};</pre><ul><li>This makes presenting options to the user in a structured format easier.</li></ul><h3>5. Identification of Correct Answer</h3><ul><li>The function identifies the correct answer by locating the original question in the shuffled list:</li></ul><pre>const indexofAnswer = questions.findIndex((question) =&gt; question === qst);<br> const correctAnswer = assertions[Object.keys(assertions)[indexofAnswer]];</pre><ul><li>This ensures the correct answer is correctly mapped to its randomized position (e.g., a, b, etc.).</li></ul><h3>6. Validation and Error Handling</h3><ul><li>The code includes robust error handling:</li><li>Ensures the dataset is valid and the type matches an expected value.</li><li>Checks if the dataset has at least four questions to avoid insufficient data errors:</li></ul><pre>if (dataSource.length &lt; 4) { <br>  throw new Error(&quot;Not enough questions in the data source.&quot;);<br> }</pre><h3>7. Returns a Structured Object</h3><ul><li>The function returns an object with:</li><li>The main question (q)</li><li>The randomized assertions (assertions)</li><li>The correct answer (correctAnswer)</li></ul><p>Example output:</p><pre>{   q: { question: &quot;What is JavaScript?&quot;,<br> answer: &quot;A programming language&quot; }, <br>  assertions: { a: &quot;HTML&quot;, b: &quot;CSS&quot;, c: &quot;A programming language&quot;, d: &quot;Python&quot;<br> },   correctAnswer: &quot;c&quot; }</pre><h4>index.js</h4><pre>import * as readline from &quot;node:readline/promises&quot;;<br>import { stdin as input, stdout as output } from &quot;node:process&quot;;<br>import generateQuestionWithAssertions from &quot;./questionGenerator.js&quot;;<br><br>async function gameInterface() {<br>  const rl = readline.createInterface({ input, output });<br><br>  const welcomeBanner = `<br><br>  ██╗    ███████████╗     ██████╗██████╗███╗   ██████████╗    ████████╗██████╗     ██████████╗  █████████╗     ██████╗ █████╗███╗   ██████████╗<br>  ██║    ████╔════██║    ██╔════██╔═══██████╗ ██████╔════╝    ╚══██╔══██╔═══██╗    ╚══██╔══██║  ████╔════╝    ██╔════╝██╔══██████╗ ██████╔════╝<br>  ██║ █╗ ███████╗ ██║    ██║    ██║   ████╔████╔███████╗         ██║  ██║   ██║       ██║  ████████████╗      ██║  ████████████╔████╔███████╗  <br>  ██║███╗████╔══╝ ██║    ██║    ██║   ████║╚██╔╝████╔══╝         ██║  ██║   ██║       ██║  ██╔══████╔══╝      ██║   ████╔══████║╚██╔╝████╔══╝  <br>  ╚███╔███╔██████████████╚██████╚██████╔██║ ╚═╝ █████████╗       ██║  ╚██████╔╝       ██║  ██║  █████████╗    ╚██████╔██║  ████║ ╚═╝ █████████╗<br>   ╚══╝╚══╝╚══════╚══════╝╚═════╝╚═════╝╚═╝     ╚═╚══════╝       ╚═╝   ╚═════╝        ╚═╝  ╚═╝  ╚═╚══════╝     ╚═════╝╚═╝  ╚═╚═╝     ╚═╚══════╝<br>                                                                                                                                               <br>  <br>                                                                                            <br>  Welcome to the Quiz Game! Test your knowledge and have fun! 🎉<br>  `;<br>  console.log(welcomeBanner);<br><br>  let score = 0;<br><br>  // Ask the user to choose a question set<br>  const questionSet = await rl.question(<br>    &quot;Choose a set of questions: 1) Coding Questions 2) General Knowledge: &quot;<br>  );<br><br>  let data;<br>  if (questionSet === &quot;1&quot;) {<br>    console.log(&quot;You selected Coding Questions! 🖥️&quot;);<br>  } else if (questionSet === &quot;2&quot;) {<br>    console.log(&quot;You selected General Knowledge! 🌍&quot;);<br>  } else {<br>    console.log(<br>      &quot;Invalid choice. Exiting the game. Please restart and choose 1 or 2.&quot;<br>    );<br>    rl.close();<br>    return;<br>  }<br><br>  console.log(<br>    &quot;Game Started! Answer the questions or type &#39;quit&#39; to end the game.&quot;<br>  );<br>  console.log(&quot;Your current score will be displayed after each question.&quot;);<br><br>  while (true) {<br>    // Generate a question<br>    if (questionSet === &quot;1&quot;) {<br>      data = generateQuestionWithAssertions(&quot;codingQuestions&quot;);<br>    } else if (questionSet === &quot;2&quot;) {<br>      data = generateQuestionWithAssertions(&quot;generalKnowledgeQA&quot;);<br>    }<br><br>    console.log(`\nQuestion: ${data.q.question}`);<br>    console.log(`a) ${data.assertions.a}`);<br>    console.log(`b) ${data.assertions.b}`);<br>    console.log(`c) ${data.assertions.c}`);<br>    console.log(`d) ${data.assertions.d}`);<br><br>    const answer = await rl.question(<br>      &quot;Your answer (a/b/c/d or &#39;quit&#39; to exit): &quot;<br>    );<br>    if (answer.toLowerCase() === &quot;quit&quot;) {<br>      console.log(`Thanks for playing! Your final score is: ${score}`);<br>      break;<br>    }<br><br>    if (data.correctAnswer === data.assertions[answer]) {<br>      console.log(&quot;Correct Answer! 🎉&quot;);<br>      score++;<br>    } else {<br>      console.log(`Wrong Answer! 😞 The correct answer was: ${data.q.answer}`);<br>    }<br><br>    console.log(`Your current score is: ${score}`);<br>  }<br><br>  rl.close();<br>}<br><br>gameInterface();</pre><h3>Key Features in the Code</h3><p><strong>Welcome Banner</strong>:</p><ul><li>A visually appealing ASCII art banner welcomes players to the game.</li><li>This adds a fun, engaging start to the experience.</li></ul><pre>const welcomeBanner = `<br><br>  ██╗    ███████████╗     ██████╗██████╗███╗   ██████████╗    ████████╗██████╗     ██████████╗  █████████╗     ██████╗ █████╗███╗   ██████████╗<br>  ██║    ████╔════██║    ██╔════██╔═══██████╗ ██████╔════╝    ╚══██╔══██╔═══██╗    ╚══██╔══██║  ████╔════╝    ██╔════╝██╔══██████╗ ██████╔════╝<br>  ██║ █╗ ███████╗ ██║    ██║    ██║   ████╔████╔███████╗         ██║  ██║   ██║       ██║  ████████████╗      ██║  ████████████╔████╔███████╗  <br>  ██║███╗████╔══╝ ██║    ██║    ██║   ████║╚██╔╝████╔══╝         ██║  ██║   ██║       ██║  ██╔══████╔══╝      ██║   ████╔══████║╚██╔╝████╔══╝  <br>  ╚███╔███╔██████████████╚██████╚██████╔██║ ╚═╝ █████████╗       ██║  ╚██████╔╝       ██║  ██║  █████████╗    ╚██████╔██║  ████║ ╚═╝ █████████╗<br>   ╚══╝╚══╝╚══════╚══════╝╚═════╝╚═════╝╚═╝     ╚═╚══════╝       ╚═╝   ╚═════╝        ╚═╝  ╚═╝  ╚═╚══════╝     ╚═════╝╚═╝  ╚═╚═╝     ╚═╚══════╝<br>                                                                                                                                               <br>  <br>                                                                                            <br>  Welcome to the Quiz Game! Test your knowledge and have fun! 🎉<br>  `;</pre><p><strong>Question Set Selection</strong>:</p><ul><li>The user selects a topic to begin (e.g., Coding Questions or General Knowledge).</li><li>This ensures personalized gameplay.</li></ul><pre>  const questionSet = await rl.question(<br>    &quot;Choose a set of questions: 1) Coding Questions 2) General Knowledge: &quot;<br>  );<br><br>  let data;<br>  if (questionSet === &quot;1&quot;) {<br>    console.log(&quot;You selected Coding Questions! 🖥️&quot;);<br>  } else if (questionSet === &quot;2&quot;) {<br>    console.log(&quot;You selected General Knowledge! 🌍&quot;);<br>  } else {<br>    console.log(<br>      &quot;Invalid choice. Exiting the game. Please restart and choose 1 or 2.&quot;<br>    );<br>    rl.close();<br>    return;<br>  }<br><br>  console.log(<br>    &quot;Game Started! Answer the questions or type &#39;quit&#39; to end the game.&quot;<br>  );<br>  console.log(&quot;Your current score will be displayed after each question.&quot;);</pre><p><strong>Continuous Gameplay</strong>:</p><ul><li>The while (true) loop ensures that the game keeps presenting questions until the player types &quot;quit&quot;.</li><li>This removes the need to confirm whether to start the game repeatedly.</li></ul><pre>while (true) {<br>    // Generate a question<br>    if (questionSet === &quot;1&quot;) {<br>      data = generateQuestionWithAssertions(&quot;codingQuestions&quot;);<br>    } else if (questionSet === &quot;2&quot;) {<br>      data = generateQuestionWithAssertions(&quot;generalKnowledgeQA&quot;);<br>    }<br><br>    console.log(`\nQuestion: ${data.q.question}`);<br>    console.log(`a) ${data.assertions.a}`);<br>    console.log(`b) ${data.assertions.b}`);<br>    console.log(`c) ${data.assertions.c}`);<br>    console.log(`d) ${data.assertions.d}`);<br><br>    const answer = await rl.question(<br>      &quot;Your answer (a/b/c/d or &#39;quit&#39; to exit): &quot;<br>    );<br>    if (answer.toLowerCase() === &quot;quit&quot;) {<br>      console.log(`Thanks for playing! Your final score is: ${score}`);<br>      break;<br>    }<br><br>    if (data.correctAnswer === data.assertions[answer]) {<br>      console.log(&quot;Correct Answer! 🎉&quot;);<br>      score++;<br>    } else {<br>      console.log(`Wrong Answer! 😞 The correct answer was: ${data.q.answer}`);<br>    }<br><br>    console.log(`Your current score is: ${score}`);<br>  }</pre><p><strong>Score Tracking</strong>:</p><ul><li>A score variable keeps track of correct answers.</li><li>The score is displayed after every question, giving instant feedback to the player.</li></ul><pre><br>  let score = 0;</pre><p><strong>Quit Option</strong>:</p><ul><li>Players can exit the game anytime by typing &quot;quit&quot;.</li><li>This provides flexibility and a natural end to the gameplay.</li></ul><pre>const answer = await rl.question(<br>      &quot;Your answer (a/b/c/d or &#39;quit&#39; to exit): &quot;<br>    );<br>    if (answer.toLowerCase() === &quot;quit&quot;) {<br>      console.log(`Thanks for playing! Your final score is: ${score}`);<br>      break;<br>    }</pre><h3>How It Works</h3><ol><li><strong>Modules</strong>: The game uses Node.js’s readline module to handle user input in the terminal.</li><li><strong>Dynamic Question Generation</strong>: The generateQuestionWithAssertions function dynamically creates questions and their respective answer options.</li><li><strong>User Feedback</strong>: After each answer, the game provides feedback on whether the player’s choice was correct.</li></ol><h3>final OutPut</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0Ktd-brWtAYJxhmlfm5ug.jpeg" /><figcaption>This is the final game using Chalk package</figcaption></figure><h3>Conclusion</h3><p>This quiz game is a fun and interactive way to practice JavaScript while creating a meaningful project. It teaches essential concepts like handling user input, loops, conditionals, and modular programming. You can further enhance this game with additional features and personalization to make it more engaging.</p><p>So, why wait? Start coding your own quiz game today and let the learning — and fun — begin!</p><p>Tip: Use chalk or inquirer package for colorful and intuitive terminal prompts</p><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ee04e358920" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Security and Performance in RESTful APIs with Twilio, Proxy Server, and Caching]]></title>
            <link>https://medium.com/@christianinyekaka/enhancing-security-and-performance-in-restful-apis-with-twilio-proxy-server-and-caching-0cd6f1a3ac74?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cd6f1a3ac74</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 15:57:21 GMT</pubDate>
            <atom:updated>2024-08-17T15:57:21.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blKV751Qcnth0kc7DY9Xng.jpeg" /></figure><p>Hello, and welcome to this tutorial! In this tutorial, we will explore how to enhance your application by integrating user verification via phone number using Twilio. We will also discuss the importance of using a proxy server to secure your backend by blocking any direct access, and how to implement caching to reduce database queries, thereby boosting your app’s performance.</p><h3><strong>Prerequisites</strong></h3><p>Before diving in, make sure you have some experience or understanding of the following tools and concepts:</p><ul><li><strong>TypeScript</strong></li><li><strong>TypeORM</strong></li><li><strong>SQL</strong></li><li><strong>Node.js &amp; NPM</strong></li><li><strong>JSON Web Tokens (JWT)</strong></li><li><strong>Caching</strong></li><li><strong>Proxy Server</strong></li><li><strong>Twilio</strong></li></ul><p>If you’re not familiar with these technologies, don’t worry! I’ll explain each one as we use them in our project.</p><p><strong>What is Twilio?</strong></p><blockquote>Twilio Inc. is an American cloud communications company based in San Francisco, California. It provides programmable communication tools for making and receiving phone calls, sending and receiving text messages, and performing other communication functions using its web service APIs.wikipedia</blockquote><p>Twilio equips developers with tools to easily integrate communication capabilities into applications. These include APIs such as the Programmable Messaging API, Conversations API, and Verify API, which facilitate sending and receiving SMS, MMS, and OTT messages (such as WhatsApp and Messenger) at scale.</p><p><strong>What is a Proxy Server?</strong></p><p>A proxy server acts as an intermediary between a client (such as a front-end application) and a main server. When a client makes a request, the request first goes through the proxy server, which then forwards it to the main server. The main server processes the request and sends the response back to the proxy server, which, in turn, forwards it to the client.</p><p>Proxy servers can provide several benefits, including:</p><ul><li><strong>Security</strong>: By hiding the main server’s IP address, proxy servers can protect against certain types of cyber attacks.</li><li><strong>Anonymity</strong>: Clients can remain anonymous by masking their IP addresses through the proxy.</li><li><strong>Load Balancing</strong>: Proxy servers can distribute requests across multiple servers to ensure even load distribution, improving performance and reliability.</li><li><strong>Caching</strong>: They can cache responses from the main server, allowing quicker retrieval of frequently requested resources and reducing the load on the main server.</li></ul><p>Using a proxy server in our application can enhance both security and performance, as it acts as a gatekeeper for incoming and outgoing requests.</p><h3>what is cache(caching)</h3><p>Caching is a technique used in computer science and information technology to store frequently accessed or computed data in a temporary storage area known as a “cache.” The primary purpose of caching is to improve data access and retrieval speeds, reduce latency, and enhance overall system performance.</p><blockquote>Read more information <a href="https://medium.com/@christianinyekaka/building-a-rest-api-with-typescript-express-typeorm-authentication-authorization-and-postgres-e87d07d1af08">here</a></blockquote><p>Now, install additional dependencies:</p><pre>npm install express dotenv bcrypt jsonwebtoken concurrently memory-cache twilio http-proxy-middleware</pre><p>Here’s what each of the installed packages does:</p><ul><li><strong>Express</strong> is a web framework for Node.js used for server creation</li><li><strong>dotenv </strong>helps<strong> </strong>read all the environment variables</li><li><strong>bcrypt</strong> is used to encrypt a password</li><li><strong>jsonwebtoken</strong> are often used to identify a user, as well as to transmit information about the user, and the tokens are often used for authentication and authorization in web applications</li><li><strong>concurrently</strong> is a Node.js utility that allows you to run multiple npm scripts concurrently in a single terminal</li><li><strong>memory-cache</strong> is a simple in-memory caching library for Node.js. It provides a way to store data in memory so that it can be quickly accessed and retrieved</li><li><strong>Twilio</strong> is a powerful API for sending and receiving SMS, voice calls, and other forms of communication. In this context, it’s used to handle phone verification by sending verification codes to users during the registration or login process.</li><li><strong>http-proxy-middleware</strong>: is a Node.js middleware that can be used to proxy requests to other servers or APIs. It’s particularly useful in development for routing requests from the front-end to a back-end server.</li></ul><h3>Install TypeScript type definitions for these dependencies:</h3><p>Since we are working with TypeScript, it is a good idea to install @types for our dependencies.</p><pre>npm i @types/express @types/bcrypt @types/jsonwebtoken @types/memory-cache</pre><p>Folder Structure:</p><pre> CarCollection<br> ┣ src<br> ┃ ┣ controllers<br> ┃ ┃ ┣ auth.controllers.ts<br> ┃ ┃ ┣ cars.controllers.ts<br> ┃ ┃ ┗ user.controller.ts<br> ┃ ┣ entity<br> ┃ ┃ ┣ Cars.ts<br> ┃ ┃ ┗ User.ts<br> ┃ ┣ helpers<br> ┃ ┃ ┣ encrypt.ts<br> ┃ ┃ ┣ jwt.ts<br> ┃ ┃ ┗ twillo.ts<br> ┃ ┣ lib<br> ┃ ┃ ┣ app.dtos.ts<br> ┃ ┃ ┗ interfaces.ts<br> ┃ ┣ middleware<br> ┃ ┃ ┗ auth.middleware.ts<br> ┃ ┣ migration<br> ┃ ┃ ┣ 1722594304243-users.ts<br> ┃ ┃ ┗ 1722594981759-cars.ts<br> ┃ ┣ routes<br> ┃ ┃ ┣ auth.routes.ts<br> ┃ ┃ ┣ Car.routes.ts<br> ┃ ┃ ┗ User.routes.ts<br> ┃ ┣ data-source.ts<br> ┃ ┣ index.ts<br> ┃ ┗ proxy.ts<br> ┣ .env<br> ┣ .gitignore<br> ┣ package-lock.json<br> ┣ package.json<br> ┣ README.md<br> ┗ tsconfig.json</pre><h3>package.json</h3><p>Update package.json file with the following dependencies</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90db8cfa282afb754861d6ec91300e0c/href">https://medium.com/media/90db8cfa282afb754861d6ec91300e0c/href</a></iframe><h4>servers</h4><h4>src/proxy.ts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1da6570032f6041658b054a21acf4ce/href">https://medium.com/media/e1da6570032f6041658b054a21acf4ce/href</a></iframe><p>This code creates a proxy server that forwards requests from http://localhost:3000/v1 to http://localhost:5000, allowing cross-origin requests with CORS. It also adds a custom header with a SHA-256 hash of the request method and a secret for validating and securing the request.</p><h4>Proxy Middleware</h4><pre>app.use(<br>  &quot;/v1&quot;,<br>  createProxyMiddleware({<br>    target: &quot;http://localhost:5000&quot;,<br>    changeOrigin: true,<br>    pathRewrite: {<br>      &quot;^/v1&quot;: &quot;&quot;,<br>    },<br>    on: {<br>      proxyReq: (proxyReq, req, res) =&gt; {<br>        // Set custom header<br>        const hash = createHmac(&quot;sha256&quot;, KEY)<br>          .update(req.method + SECRET)<br>          .digest(&quot;hex&quot;);<br><br>        proxyReq.setHeader(&quot;x-added&quot;, hash);<br>      },<br>    },<br>  })<br>);</pre><ul><li><strong>createProxyMiddleware</strong>: Configures the proxy middleware to forward requests.</li><li><strong>target</strong>: Specifies the target server to which requests will be proxied, in our case, <a href="http://localhost:5000.">http://localhost:5000.</a></li><li><strong>changeOrigin</strong>: Modifies the Origin header to the target URL. This is useful to prevent the target server from rejecting requests due to an unrecognized origin.</li><li><strong>pathRewrite</strong>: Modifies the request URL path before it is sent to the target server. Here, it removes /v1 from the request path.</li><li>For example, a request to /v1/api/users will be proxied to /api/users on the target server.</li><li><strong>on.proxyReq</strong>: An event listener that is triggered before the request is sent to the target. It adds a custom header x-added containing a hash.</li><li><strong>createHmac</strong>: Uses the SHA-256 algorithm to create a hash from the request method (req.method) and a secret (SECRET). This hash is included in the x-added header to provide a request validation and integrity check.</li><li><strong>setHeader</strong>: Adds the custom header to the proxied request. This is used by the target server to verify the authenticity of the request.</li></ul><h4>src/index.ts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23e01fb169eaee7294983ce1b0e56574/href">https://medium.com/media/23e01fb169eaee7294983ce1b0e56574/href</a></iframe><p>This is our main server, which our proxy server will direct calls to. It includes middleware that restricts direct access, processing requests only via the proxy</p><h3>src/data-source.ts</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a695f857853daf0300e32572a9a9730/href">https://medium.com/media/6a695f857853daf0300e32572a9a9730/href</a></iframe><p>This file handles database configuration, including reading environment variables.</p><blockquote>Note: Make sure your .env file contains the necessary database connection details.</blockquote><h3>Entities</h3><p>These define the structure of the database tables:</p><h4>User.ts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98a0669a45ea217ef5251c08bdcda0e2/href">https://medium.com/media/98a0669a45ea217ef5251c08bdcda0e2/href</a></iframe><h4>Car.ts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb7ed5c5eade99fa2c1770bd06a596df/href">https://medium.com/media/fb7ed5c5eade99fa2c1770bd06a596df/href</a></iframe><h4>Middlewares</h4><p>The following middleware functions are designed to enhance the security and functionality of our application by handling authentication, restricting direct access, and verifying phone numbers during registration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a15d5b17360e1921b0a158bf415828/href">https://medium.com/media/d8a15d5b17360e1921b0a158bf415828/href</a></iframe><h4>1. Authentication Middleware (auth method)</h4><p><strong>Purpose</strong>: To ensure that the incoming request has a valid JSON Web Token (JWT) and to attach the user information to the request.</p><p><strong>Steps</strong>:</p><ul><li>Extracts the token from the Authorization header.</li><li>Verifies the token using a JWT helper function.</li><li>Checks if the user information is already cached to reduce database hits.</li><li>If not cached, retrieves the user from the database and caches it.</li><li>Attaches the user information to the request object (req[&quot;current-user&quot;]) and proceeds to the next middleware or route handler.</li></ul><h4>2. Block Direct Access Middleware (blockDirectAccess method)</h4><p><strong>Purpose</strong>: To block any direct access to the server that doesn’t come through the proxy server.</p><p><strong>Steps</strong>:</p><ul><li>Retrieves the custom header x-added set by the proxy server.</li><li>Computes a hash using the request method and a secret key.</li><li>Compares the computed hash with the received header value.</li><li>Allows access only if the hashes match, indicating the request is from the proxy server.</li></ul><h4>3. Phone Verification Middleware (phoneVerification method)</h4><p><strong>Purpose</strong>: To ensure that the provided phone number during user registration is unique.</p><p><strong>Steps</strong>:</p><ul><li>Checks if the phone field is present in the request body.</li><li>Queries the database to see if a user with the given phone number already exists.</li><li>If the phone number is unique, it allows the request to proceed; otherwise, it returns a 400 status with an error message.</li></ul><h4>Helpers</h4><p>These classes provide essential functionality for encrypting passwords, handling JSON Web Tokens, and managing phone number verifications using Twilio.</p><h4>encrypt.ts</h4><p>The Encrypt class handles password encryption and comparison using the bcrypt library. This is essential to securely store passwords in a hashed format rather than plain text.</p><pre>import * as bcrypt from &quot;bcrypt&quot;;<br><br>export class encrypt {<br>  static encryptPassword(password: string) {<br>    return bcrypt.hashSync(password, 10);<br>  }<br>  static comparePassword(password: string, hash: string) {<br>    return bcrypt.compareSync(password, hash);<br>  }<br>}</pre><ul><li><strong>encryptPassword</strong>: Takes a plain-text password and returns a hashed version using bcrypt. This hashed password is what gets stored in the database.</li><li><strong>comparePassword</strong>: Compares a plain-text password with a hashed password to verify if they match. This is used during the login process.</li></ul><h4>jwt.ts</h4><p>The JsonWebToken class provides methods for signing and verifying JSON Web Tokens (JWT), leveraging the jsonwebtoken library.</p><pre>import * as jwt from &quot;jsonwebtoken&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>import { Ipayload } from &quot;../lib/interfaces&quot;;<br>dotenv.config();<br><br>export class jsonwebtoken {<br>  static async sign(payload: Ipayload) {<br>    return jwt.sign(payload, process.env.JWT_SECRET, {<br>      expiresIn: process.env.JWT_EXPIRATION,<br>    });<br>  }<br>  static async verify(token: string): Promise&lt;Ipayload&gt; {<br>    return jwt.verify(token, process.env.JWT_SECRET) as Ipayload;<br>  }<br>}</pre><ul><li><strong>sign</strong>: Generates a JWT for a given payload using a secret key and an expiration time. This is typically used during user authentication.</li><li><strong>verify</strong>: Validates a given JWT and extracts the payload. This is used to authenticate and authorize users on protected routes.</li></ul><h4>twilio.ts</h4><p>The TwilioActions class interacts with the Twilio API to send and verify SMS-based verification codes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b803b061a6270794a2b4c68df8ac8e/href">https://medium.com/media/69b803b061a6270794a2b4c68df8ac8e/href</a></iframe><ul><li><strong>sendVerificationCode</strong>: Sends a verification code to the specified phone number via SMS using Twilio&#39;s verification service.</li><li><strong>verifyCode</strong>: Checks if the provided verification code matches the one sent to the specified phone number.</li></ul><blockquote>Note: Read more on <a href="https://medium.com/@ututuv/structuring-typescript-project-in-express-with-phone-number-authentication-using-twilio-f914e2356974">Structuring TypeScript project in Express with phone number authentication using Twilio</a></blockquote><h4>lib/app.dtos.ts</h4><pre>import { Icar, IUser } from &quot;./interfaces&quot;;<br><br>export class CarDto {<br>  car: Icar;<br>  owner: IUser;<br>}<br><br>export class usersDto {<br>  user: IUser[];<br>}</pre><p>This file contains Data Transfer Objects (DTOs), which define the structure of the data that will be returned to the user. DTOs ensure that only the necessary information is passed to the client.</p><h4>interfaces.ts</h4><pre>export interface Ipayload {<br>  id: string;<br>}<br><br>export type IUser = {<br>  id: string;<br>  name: string;<br>  email: string;<br>  createdAt: Date;<br>  updatedAt: Date;<br>};<br><br>export interface Icar {<br>  id: string;<br>  name: string;<br>  brand: string;<br>  model: string;<br>  year: number;<br>  fuel: string;<br>  transmission: string;<br>  price: number;<br>  color: string;<br>  mileage: number;<br>  description: string;<br>  image: string;<br>  status: string;<br>  createdAt: Date;<br>  updatedAt: Date;<br>}</pre><p>This file defines interfaces and type declarations that structure the data used across the application, ensuring consistent data handling</p><h4>controllers</h4><h4>auth.controller.ts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/123ab30c2c1feb09609f1e1cf5159167/href">https://medium.com/media/123ab30c2c1feb09609f1e1cf5159167/href</a></iframe><p>The AuthController is responsible for managing user authentication, including:</p><ul><li><strong>Login</strong>: Verifying credentials, caching, and token generation.</li><li><strong>Registration</strong>: Creating new users and sending verification codes.</li><li><strong>Verification</strong>: Validating verification codes and updating user status.</li></ul><h4>Key Methods:</h4><h4><strong>login:</strong></h4><ul><li><strong>Function</strong>: Authenticates the user by validating the email and password.</li><li><strong>Caching</strong>: Checks if user data is cached by email. If cached, returns a JWT token directly.</li><li><strong>Password Verification</strong>: Uses a helper function encrypt.comparePassword to verify the password.</li><li><strong>Two-Factor Authentication</strong>: If the user is not verified, a verification code is sent via Twilio, and the login process is halted until verification is completed.</li><li><strong>JWT Generation</strong>: On successful login, a JWT token is generated and returned to the user.</li><li><strong>Caching Strategy</strong>: Caches user data for 30 minutes after successful login to speed up future requests.</li></ul><h4><strong>register</strong>:</h4><ul><li><strong>Function</strong>: Registers a new user.</li><li><strong>Password Encryption</strong>: The password is encrypted before being saved to the database.</li><li><strong>Twilio Integration</strong>: A verification code is sent to the user’s phone number after registration.</li><li><strong>Cache Invalidation</strong>: Clears the user cache after registration to avoid stale data.</li></ul><h4><strong>verifyCode</strong>:</h4><ul><li><strong>Function</strong>: Verifies the code sent to the user’s phone number.</li><li><strong>Verification Process</strong>: Checks the verification status returned by Twilio. If approved, the user is marked as verified.</li><li><strong>JWT Generation</strong>: After successful verification, a JWT token is issued to the user.</li><li><strong>Cache Management</strong>: Invalidates cache entries related to the user upon successful verification to ensure consistency.</li></ul><h4>cars. controllers.ts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6afc93c0d44af5576e220259929800f3/href">https://medium.com/media/6afc93c0d44af5576e220259929800f3/href</a></iframe><p>This controller handles CRUD (Create, Read, Update, Delete) operations for cars in our application. It utilizes caching to optimize performance and reduce database load, particularly for read operations.</p><h4>Key Methods:</h4><h4><strong>getAllCars</strong>:</h4><ul><li><strong>Function</strong>: Retrieves all cars from the database.</li><li><strong>Caching</strong>: Checks if cars data is cached and returns it if available. Otherwise, it fetches data from the database and stores it in cache.</li></ul><h4><strong>getCarById</strong>:</h4><ul><li><strong>Function</strong>: Retrieves a car by its ID.</li><li><strong>Caching</strong>: Similar to getAllCars, this method checks if the specific car&#39;s data is cached.</li></ul><h4><strong>createCar</strong>:</h4><ul><li><strong>Function</strong>: Adds a new car to the database.</li><li><strong>Caching</strong>: Invalidates the cache for all cars, ensuring that the cache is refreshed with the newly created car.</li></ul><h4><strong>updateCar</strong>:</h4><ul><li><strong>Function</strong>: Updates information on an existing car.</li><li><strong>Authorization</strong>: Ensures that only the owner of the car can update it.</li><li><strong>Caching</strong>: Clears the cache for the specific car and all cars, ensuring that the cache remains consistent.</li></ul><h4><strong>deleteCar</strong>:</h4><ul><li><strong>Function</strong>: Deletes a car by its ID.</li><li><strong>Authorization</strong>: Ensures that only the owner of the car can delete it.</li><li><strong>Caching</strong>: Invalidates the cache for the deleted car and all cars.</li></ul><h4>user.controllers.ts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93cd5328f0a9a57b09bf6bb3c2fbb483/href">https://medium.com/media/93cd5328f0a9a57b09bf6bb3c2fbb483/href</a></iframe><p>This controller manages the user data, including retrieval, updating, and deletion of users. It also handles caching to optimize the performance of read operations.</p><h4>Key Methods:</h4><h4><strong>getAllUsers</strong>:</h4><ul><li><strong>Function</strong>: Retrieves all users from the database.</li><li><strong>Caching</strong>: Checks if the users data is cached, and returns it if available. Otherwise, fetches from the database and stores it in the cache.</li></ul><h4><strong>getUser</strong>:</h4><ul><li><strong>Function</strong>: Retrieves a user by their ID.</li><li><strong>Caching</strong>: Checks if the specific user’s data is cached and returns it if available.</li></ul><h4><strong>updateUser</strong>:</h4><ul><li><strong>Function</strong>: Updates user details such as name and email.</li><li><strong>Caching</strong>: Clears the cache for the updated user and the list of all users, as well as for any cars associated with that user.</li></ul><h4><strong>deleteUser</strong>:</h4><ul><li><strong>Function</strong>: Deletes a user by their ID.</li><li><strong>Caching</strong>: Clears the cache for the deleted user, all users, and any cars associated with the user.</li></ul><h4>Routes</h4><h4>auth.routes.ts</h4><p>This router handles authentication-related operations such as login, registration, and account activation</p><pre>import express from &quot;express&quot;;<br>import { AuthController } from &quot;../controllers/auth.controllers&quot;;<br>import { middlewares } from &quot;../middleware/auth.middleware&quot;;<br><br>const authRouter = express.Router();<br><br>authRouter.post(&quot;/login&quot;, AuthController.login.bind(AuthController));<br>authRouter.post(<br>  &quot;/rigester&quot;,<br>  middlewares.phoneVerification,<br>  AuthController.register.bind(AuthController)<br>);<br>authRouter.post(&quot;/activate&quot;, AuthController.verifyCode.bind(AuthController));<br><br>export { authRouter };</pre><h4>user.routes.ts</h4><p>This router manages user-related operations, such as fetching user data, updating user profiles, and deleting users.</p><pre>import * as express from &quot;express&quot;;<br>import { AuthController } from &quot;../controllers/auth.controllers&quot;;<br>import { middlewares } from &quot;../middleware/auth.middleware&quot;;<br>import { UserController } from &quot;../controllers/user.controller&quot;;<br><br>const UserRouter = express.Router();<br><br>UserRouter.get(<br>  &quot;/all&quot;,<br>  middlewares.auth,<br>  UserController.getAllUsers.bind(AuthController)<br>);<br>UserRouter.get(<br>  &quot;/:id&quot;,<br>  middlewares.auth,<br>  UserController.getUser.bind(UserController)<br>);<br><br>UserRouter.patch(<br>  &quot;/&quot;,<br>  middlewares.auth,<br>  UserController.updateUser.bind(UserController)<br>);<br>UserRouter.delete(<br>  &quot;/delete&quot;,<br>  middlewares.auth,<br>  UserController.deleteUser.bind(UserController)<br>);<br><br>export { UserRouter };</pre><h4>car.routes.ts</h4><p>This router is responsible for managing operations related to cars, such as listing all cars, getting a specific car, creating, updating, and deleting cars</p><pre>import express from &quot;express&quot;;<br>import { CarsController } from &quot;../controllers/cars.controllers&quot;;<br>import { middlewares } from &quot;../middleware/auth.middleware&quot;;<br><br>const CarRouter = express.Router();<br><br>CarRouter.get(<br>  &quot;/cars&quot;,<br>  middlewares.auth,<br>  CarsController.getAllCars.bind(CarsController)<br>);<br><br>CarRouter.get(<br>  &quot;/car/:id&quot;,<br>  middlewares.auth,<br>  CarsController.getCarById.bind(CarsController)<br>);<br><br>CarRouter.post(<br>  &quot;/car&quot;,<br>  middlewares.auth,<br>  CarsController.createCar.bind(CarsController)<br>);<br><br>CarRouter.patch(<br>  &quot;/car/:id&quot;,<br>  middlewares.auth,<br>  CarsController.updateCar.bind(CarsController)<br>);<br><br>CarRouter.delete(<br>  &quot;/car&quot;,<br>  middlewares.auth,<br>  CarsController.deleteCar.bind(CarsController)<br>);<br><br>export { CarRouter };</pre><h4>Testing</h4><p>Run the following to start our application in development mode</p><pre>npm run start:dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iW8FgNA_9W5-q5XpHjyIA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*_WH0AXS296EB6ZOdi3yIJQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sn8HWu9QxkS1plSTObsy5A.jpeg" /><figcaption>verification code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*joaA1NfGwzQx7npOiADvWA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*qSsAiHHS1VN-dDAw-0CFNA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*vKWkTFyRM9Q15eMul3cIgg.jpeg" /><figcaption>blocking all direct access to the main server</figcaption></figure><p>Follow similar steps to test other endpoints like login, fetching a specific user, updating a user, creating a car, etc. Ensure that you handle different edge cases such as missing parameters, invalid inputs, unauthorized access, etc.</p><h3>Conclusion</h3><p>Building a robust and secure Node.js application involves multiple critical steps, from setting up a well-structured architecture to implementing secure authentication, user verification, and efficient routing. This guide has walked you through the process of setting up user registration, verification, and authentication endpoints, along with implementing essential middleware for security and caching to optimize performance.</p><h4>Thank you for being part of this tutorial, and best of luck with your future projects!!!!!!!</h4><p>Full project in my <a href="https://github.com/chrisBokotaII/CarCollection.git">GitHub</a></p><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cd6f1a3ac74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain-Based ROSCA: Implementing On-Chain Verification for Secure Fund Claims]]></title>
            <link>https://coinsbench.com/blockchain-based-rosca-implementing-on-chain-verification-for-secure-fund-claims-b9e9b4607eac?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e9b4607eac</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[rosca]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 12:16:43 GMT</pubDate>
            <atom:updated>2024-07-07T12:16:43.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*B4pb8iOBBwRE9a36Rs5-XQ.jpeg" /></figure><p><strong>Rotating savings and credit association (ROSCA)</strong>. This traditional form of cooperative savings and lending involves a group of individuals who agree to contribute a fixed amount of money to a common fund at regular intervals (e.g., monthly). Each period, the entire collected amount is given to one member of the group. The process repeats until all members have received the lump sum once.</p><p>ROSCA has various names in different cultures and regions, such as:</p><ul><li><strong>Tanda</strong> in Mexico and parts of Latin America</li><li><strong>Susu</strong> in West Africa and the Caribbean</li><li><strong>Chit fund</strong> or <strong>Kuri</strong> in India</li><li><strong>Pasanaku</strong> in Bolivia</li><li><strong>Partnerhand</strong> in Guyana</li></ul><p>In this article, we will implement ROSCA on the blockchain, leveraging the benefits of decentralization, transparency, and automation. This implementation makes the system more reliable and less dependent on mutual trust.</p><h3>Contract Implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91733e96864545a34bff87f93e549fe8/href">https://medium.com/media/91733e96864545a34bff87f93e549fe8/href</a></iframe><h3>Features of the Smart Contract</h3><p><strong>Participant Registration and Staking:</strong></p><ul><li>Participants must register and stake a certain amount of ETH before joining the ROSCA.</li><li>This stake can act as a commitment bond and be forfeited if the participant fails to meet their obligations.</li></ul><p><strong>Contribution Collection:</strong></p><ul><li>Participants send their contributions (e.g., 1 ETH) to the smart contract at regular intervals.</li></ul><p><strong>Penalty:</strong></p><ul><li>If a participant fails to contribute at regular intervals, the manager will call the penalty function to check if all participants have contributed. If not, their stake amount is deducted.</li></ul><p><strong>Recipient Selection:</strong></p><ul><li>The contract maintains a list of participants and distributes the collected funds to one participant each period based on the predetermined order.</li></ul><p><strong>On-Chain Verification:</strong></p><ul><li>The contract verifies each participant’s contribution and staking status before allowing them to claim the funds.</li><li>The claimer must hash a message, and the manager signs it to release the funds to the current claimer.</li></ul><p><em>Note: learn more about on-chain verification </em><a href="https://medium.com/@ututuv/implementing-referral-claiming-system-smart-contract-4544a427554c"><em>here</em></a></p><h3>Test Implementation</h3><p>Testing is crucial to identify and fix any potential issues before deploying the contract on the mainnet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d679fec5ad2c6c74f47d1750ed8292e8/href">https://medium.com/media/d679fec5ad2c6c74f47d1750ed8292e8/href</a></iframe><p>In the file below, we add specific test cases to check for different reverts and ensure the smart contract functions as expected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f560fe650585d37b498c1cc5583d4e6/href">https://medium.com/media/8f560fe650585d37b498c1cc5583d4e6/href</a></iframe><p>Add more test cases to test other cases</p><h3>Conclusion</h3><p>Implementing a Rotating Savings and Credit Association (ROSCA) on the blockchain brings significant improvements to this traditional savings method. By leveraging blockchain technology, we enhance transparency, automation, and security, reducing the reliance on mutual trust among participants.</p><p>The smart contract designed in this article demonstrates how to manage participant registration and staking, contribution collection, recipient selection, and on-chain verification for claiming funds. These features ensure that the ROSCA operates smoothly and fairly, with each participant receiving their lump sum in turn.</p><p>Key benefits of this implementation include:</p><ul><li><strong>Decentralization:</strong> Eliminates the need for a central authority, distributing control and trust across all participants.</li><li><strong>Transparency:</strong> Every transaction and action within the ROSCA is recorded on the blockchain, making the process fully transparent and auditable.</li><li><strong>Automation:</strong> Smart contracts automate the collection and distribution of funds, reducing the administrative burden and the potential for errors.</li><li><strong>Security:</strong> On-chain verification and manager approval via cryptographic signatures ensure that only authorized participants can claim funds.</li></ul><p>By modernizing ROSCA with blockchain technology, we can preserve its community-based nature while providing enhanced reliability and security. This implementation can serve as a foundation for further innovations in cooperative finance, benefiting individuals and communities worldwide.</p><p><em>Thank you🙏</em></p><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e9b4607eac" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/blockchain-based-rosca-implementing-on-chain-verification-for-secure-fund-claims-b9e9b4607eac">Blockchain-Based ROSCA: Implementing On-Chain Verification for Secure Fund Claims</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Account Security with Recovery Phrase]]></title>
            <link>https://medium.com/@christianinyekaka/enhancing-account-security-with-recovery-phrase-c82d32731a5a?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c82d32731a5a</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[recovery]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 09:20:37 GMT</pubDate>
            <atom:updated>2024-04-07T09:20:37.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*mXg-JR8XvWmh_GMyPWsf_w.png" /></figure><h3>Introduction</h3><p>The recovery phrase feature enhances the security and usability of user accounts by providing a mechanism for account recovery in case the user forgets their password. Instead of relying solely on traditional password reset methods, users are provided with a set of recovery phrases during account creation. This recovery phrase serves as an alternative method for account recovery, adding an extra layer of security and redundancy to the system.</p><h4><strong>Benefits of Recovery Phrase:</strong></h4><ol><li><strong>Improved Security:</strong> Recovery phrase provides an additional layer of security beyond traditional password-based authentication. In the event of a forgotten password or compromised account, recovery phrase is a reliable method for account recovery without compromising security.</li><li><strong>Reduced Reliance on Email:</strong> Unlike traditional password reset mechanisms that often rely on email-based verification, recovery phrase offers a more direct and secure means of account recovery. Users no longer need to rely solely on email communication, which can be vulnerable to interception or account takeover.</li><li><strong>Usability and Accessibility: </strong>Recovery phrase simplifies the account recovery process for users by providing a straightforward method for regaining access to their accounts. This improves overall usability and accessibility, especially for users who may encounter difficulties with email-based recovery methods.</li><li><strong>Privacy and Confidentiality: </strong>Recovery phrase is known only to the user, enhancing privacy and confidentiality. Unlike email-based recovery, which may involve sharing personal information over insecure channels, recovery phrases allow users to securely regain access to their accounts without disclosing sensitive information.</li></ol><h3>Prerequisites:</h3><p>Before proceeding with the implementation of the recovery phrase feature, it’s essential to have a foundational understanding of the following technologies and tools:</p><ul><li>TypeScript</li><li>TypeORM</li><li>PostgreSQL</li><li>Node.js &amp; NPM</li><li>JSON Web Tokens (JWT)</li></ul><h3>Project Setup</h3><p>To begin, we’ll create a new project using TypeORM init</p><pre>npx typeorm init --name nmemonic --database postgres</pre><blockquote>Note: you can replace postgres with the database you are using :mysql, mariadb, postgres, cockroachdb, sqlite, mssql, sap, spanner, oracle, mongodb, cordova, react-native, expo, nativescript.</blockquote><p>This command will generate a new project in the mnemonic directory with the following files:</p><pre>MyProject<br>├── src                   // place of your TypeScript code<br>│   ├── entity            // place where your entities (database models) are stored<br>│   │   └── User.ts       // sample entity<br>│   ├── migration         // place where your migrations are stored<br>│   ├── data-source.ts    // data source and all connection configuration<br>│   └── index.ts          // start point of your application<br>├── .gitignore            // standard gitignore file<br>├── package.json          // node module dependencies<br>├── README.md             // simple readme file<br>└── tsconfig.json         // TypeScript compiler options</pre><p>we are going to add and modify some files in the generated project. So our project folder structure will look something like this :</p><pre>mnemonic<br> ┣ src<br> ┃ ┣ controllers<br> ┃ ┃ ┗ user.controllers.ts<br> ┃ ┣ entity<br> ┃ ┃ ┗ User.ts<br> ┃ ┣ helpers<br> ┃ ┃ ┣ crypto.ts<br> ┃ ┃ ┣ encrypt.ts<br> ┃ ┃ ┗ jwt.token.ts<br> ┃ ┣ middleware<br> ┃ ┃ ┗ authMiddleware.ts<br> ┃ ┣ migration<br> ┃ ┣ routes<br> ┃ ┃ ┗ user.routes.ts<br> ┃ ┣ data-source.ts<br> ┃ ┗ index.ts<br> ┣ .env<br> ┣ .gitignore<br> ┣ package-lock.json<br> ┣ package.json<br> ┣ README.md<br> ┗ tsconfig.json</pre><p>Let’s download some additional dependencies that we are going to use in our project and their types</p><pre>npm install express dotenv bcrypt jsonwebtoken concurrently cors<br>npm i @types/express @types/bcrypt @types/jsonwebtoken @types/cors</pre><p>Here’s what each of the installed packages do:</p><ol><li><strong>express:</strong> Express is a minimal and flexible Node.js web application framework that provides robust features for building web and mobile applications. It simplifies the process of creating APIs and handling HTTP requests and responses.</li><li><strong>dotenv:</strong> Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. It helps securely manage configuration settings and sensitive information such as API keys and database credentials.</li><li><strong>bcrypt: </strong>Bcrypt is a widely-used library for hashing passwords. It provides a secure way to hash passwords before storing them in a database, making it difficult for attackers to reverse-engineer or brute-force passwords.</li><li><strong>jsonwebtoken:</strong> Jsonwebtoken (JWT) is a compact and self-contained way of securely transmitting information between parties as a JSON object. It’s commonly used for authentication and authorization in web applications, providing a stateless mechanism for securely identifying users.</li><li><strong>concurrently:</strong> Concurrently is a utility tool that allows running multiple commands concurrently.</li><li><strong>cors:</strong> Cross-Origin Resource Sharing (CORS) is a mechanism that allows web servers to specify which origins are permitted to access the resources on a server. The cors package provides middleware to enable CORS in Express applications, allowing controlled access to resources from different origins.</li></ol><h3>package.json</h3><pre>{<br>  &quot;name&quot;: &quot;menemonic&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;description&quot;: &quot;Awesome project developed with TypeORM.&quot;,<br>  &quot;type&quot;: &quot;commonjs&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;watch&quot;: &quot;tsc -w&quot;,<br>    &quot;dev&quot;: &quot;nodemon build/index.js&quot;,<br>    &quot;start:dev&quot;: &quot;concurrently \&quot;tsc -w\&quot; \&quot;nodemon build/index.js\&quot;&quot;,<br>    &quot;build&quot;: &quot;tsc&quot;,<br>    &quot;start&quot;: &quot;ts-node src/index.ts&quot;,<br>    &quot;typeorm&quot;: &quot;typeorm-ts-node-commonjs&quot;,<br>    &quot;migration&quot;: &quot; npm run typeorm migration:run -- -d ./src/data-source.ts&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;@types/node&quot;: &quot;^16.11.10&quot;,<br>    &quot;ts-node&quot;: &quot;10.9.1&quot;,<br>    &quot;typeorm&quot;: &quot;^0.3.20&quot;,<br>    &quot;typescript&quot;: &quot;4.5.2&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@types/bcrypt&quot;: &quot;^5.0.2&quot;,<br>    &quot;@types/cors&quot;: &quot;^2.8.17&quot;,<br>    &quot;@types/express&quot;: &quot;^4.17.21&quot;,<br>    &quot;@types/jsonwebtoken&quot;: &quot;^9.0.6&quot;,<br>    &quot;axios&quot;: &quot;^1.6.8&quot;,<br>    &quot;bcrypt&quot;: &quot;^5.1.1&quot;,<br>    &quot;concurrently&quot;: &quot;^8.2.2&quot;,<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;dotenv&quot;: &quot;^16.4.5&quot;,<br>    &quot;express&quot;: &quot;^4.18.3&quot;,<br>    &quot;jsonwebtoken&quot;: &quot;^9.0.2&quot;,<br>    &quot;pg&quot;: &quot;^8.4.0&quot;,<br>    &quot;reflect-metadata&quot;: &quot;^0.1.13&quot;<br>  }<br>}</pre><h3>src/index.ts</h3><pre>import { AppDataSource } from &quot;./data-source&quot;;<br>import * as express from &quot;express&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>import * as cors from &quot;cors&quot;;<br>import { Request, Response } from &quot;express&quot;;<br>import &quot;reflect-metadata&quot;;<br>import { UserRouter } from &quot;./routes/user.routes&quot;;<br>dotenv.config();<br><br>const app = express();<br>app.use(express.json());<br>app.use(cors());<br>const { PORT = 3000 } = process.env;<br>app.use(&quot;/api&quot;, UserRouter);<br>app.get(&quot;*&quot;, (req: Request, res: Response) =&gt; {<br>  res.status(505).json({ message: &quot;Bad Request&quot; });<br>});<br><br>AppDataSource.initialize()<br>  .then(async () =&gt; {<br>    app.listen(PORT, () =&gt; {<br>      console.log(&quot;Server is running on http://localhost:&quot; + PORT);<br>    });<br>    console.log(&quot;Data Source has been initialized!&quot;);<br>  })<br>  .catch((error) =&gt; console.log(error));</pre><p>In this File, we set up a basic Express server with middleware, route handling, and database initialization, making it ready to handle incoming HTTP requests.</p><h3>src/data-source.ts</h3><pre>import &quot;reflect-metadata&quot;;<br>import { DataSource } from &quot;typeorm&quot;;<br><br>import * as dotenv from &quot;dotenv&quot;;<br>import { User } from &quot;./entity/User&quot;;<br><br>dotenv.config();<br><br>const { DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD, DB_DATABASE, NODE_ENV } =<br>  process.env;<br><br>export const AppDataSource = new DataSource({<br>  type: &quot;postgres&quot;,<br>  host: DB_HOST,<br>  port: parseInt(DB_PORT || &quot;5432&quot;),<br>  username: DB_USERNAME,<br>  password: DB_PASSWORD,<br>  database: DB_DATABASE,<br>  synchronize: NODE_ENV === &quot;dev&quot; ? true : false,<br>  logging: NODE_ENV === &quot;dev&quot; ? true : false,<br>  entities: [User],<br>  migrations: [__dirname + &quot;/migration/*.ts&quot;],<br>  subscribers: [],<br>});</pre><p>In this file, we initialize the AppDataSource instance, configuring it to connect to our PostgreSQL database and setting up synchronization and logging options based on the environment. It also specifies the entities and migration files to be used by TypeORM for database operations.</p><blockquote>Note: Make sure in your .env file you have all the database credentials step up correctly</blockquote><h3>Entities</h3><p>These define the structure of the database tables:</p><h4>User Entity</h4><pre>import {<br>  Entity,<br>  PrimaryGeneratedColumn,<br>  Column,<br>  CreateDateColumn,<br>  UpdateDateColumn,<br>} from &quot;typeorm&quot;;<br><br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn(&quot;uuid&quot;)<br>  id: string;<br><br>  @Column()<br>  name: string;<br>  @Column()<br>  email: string;<br><br>  @Column()<br>  password: string;<br>  @Column()<br>  recovery: string;<br><br>  @CreateDateColumn()<br>  createdAt: string;<br>  @UpdateDateColumn()<br>  updatedAt: string;<br>}</pre><h3><strong>src/helpers</strong></h3><h4>crypto.ts</h4><pre>import * as crypto from &quot;crypto&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br><br>function splitEncryptedText(encryptedText: string) {<br>  return {<br>    ivString: encryptedText.slice(0, 32),<br>    encryptedDataString: encryptedText.slice(32),<br>  };<br>}<br><br>export default class Security {<br>  encoding: BufferEncoding = &quot;hex&quot;;<br><br>  <br>  getkey() {<br>    const secret = process.env.KEY;<br>    const key = crypto<br>      .createHash(&quot;sha256&quot;)<br>      .update(String(secret))<br>      .digest(&quot;base64&quot;);<br>    const bytes = Buffer.from(key, &quot;base64&quot;);<br>    return bytes;<br>  }<br><br>  key = this.getkey();<br>  encrypt(plaintext: string) {<br>    /*console.log(this.key)*/;<br>    try {<br>      const iv = crypto.randomBytes(16);<br>      const cipher = crypto.createCipheriv(&quot;aes-256-cbc&quot;, this.key, iv);<br>      console.log(cipher);<br>      const encrypted = Buffer.concat([<br>        cipher.update(plaintext, &quot;utf-8&quot;),<br>        cipher.final(),<br>      ]);<br><br>      return iv.toString(this.encoding) + encrypted.toString(this.encoding);<br>    } catch (e) {<br>      console.error(e);<br>    }<br>  }<br><br>  decrypt(cipherText: string) {<br>    const { encryptedDataString, ivString } = splitEncryptedText(cipherText);<br><br>    try {<br>      const iv = Buffer.from(ivString, this.encoding);<br>      const encryptedText = Buffer.from(encryptedDataString, this.encoding);<br><br>      const decipher = crypto.createDecipheriv(&quot;aes-256-cbc&quot;, this.key, iv);<br><br>      const decrypted = decipher.update(encryptedText);<br>      return Buffer.concat([decrypted, decipher.final()]).toString();<br>    } catch (e) {<br>      console.error(e);<br>    }<br>  }<br>}</pre><p><strong>Functionalities:</strong></p><p>splitEncryptedText: This is a utility function that splits the encrypted text into its initialization vector (IV) and encrypted data parts.</p><p>Security: this class encapsulates encryption and decryption methods:</p><p>getkey(): Generates the encryption key of 32 bytes using a SHA-256 hash of our KEY stored in our environment variable file.</p><p>encrypt(plaintext): Encrypts the plaintext using AES-256-CBC cipher algorithm with a randomly generated IV.</p><p>decrypt(cipherText): Decrypts the cipher text using the AES-256-CBC cipher algorithm with the provided key and IV.</p><h4>encrypt.ts</h4><pre>import * as bcrypt from &quot;bcrypt&quot;;<br><br>export class Encrypt {<br>  static async hashPassword(password: string) {<br>    const salt = await bcrypt.genSalt(10);<br>    const hash = await bcrypt.hash(password, salt);<br>    return hash;<br>  }<br>  static async comparePassword(password: string, hash: string) {<br>    return await bcrypt.compare(password, hash);<br>  }<br>}</pre><p>we do not want to store our passwords as plain text in our database it will make it vulnerable to attack. These methods provide a convenient and secure way to handle password hashing and comparison, which are essential for securely managing user authentication in web applications. By using bcrypt, passwords are securely hashed with salts, making them resistant to common cryptographic attacks such as brute force and rainbow table attacks. Now even if an attacker gains access to the hashed passwords, it would be extremely difficult and time-consuming to reverse-engineer them back to the original passwords.</p><h4>jwt.token.ts</h4><pre>import * as jwt from &quot;jsonwebtoken&quot;;<br>export class JwtTokens {<br>  static async generateToken(payload: any) {<br>    return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: &quot;1h&quot; });<br>  }<br>  static async verifyToken(token: string) {<br>    return jwt.verify(token, process.env.JWT_SECRET);<br>  }<br>  static async genratepassResetToken(payload: any) {<br>    return jwt.sign(payload, process.env.JWT_SECRET2, { expiresIn: &quot;120s&quot; });<br>  }<br>  static async verifyToken2(token: string) {<br>    return jwt.verify(token, process.env.JWT_SECRET2);<br>  }<br>}</pre><p>In this file, we’ve created a class, which serves as a utility for generating and verifying JSON Web Tokens (JWTs). Within this class, we&#39;ve implemented methods tailored for two distinct purposes:</p><p><strong>Authentication Token:</strong></p><p>This token is crafted to facilitate user authentication upon login or signup processes. It grants users access to protected endpoints that require authentication.</p><p><strong>Password Reset Token:</strong></p><p>Following the submission of a correct recovery phrase, this token is generated to facilitate secure password reset functionality for users. To maintain a higher level of security and restrict the window of opportunity for potential misuse, this token has a shorter lifespan, typically lasting only a couple of minutes.</p><h3>Middleware</h3><h4>authMiddleware.ts</h4><pre>import { NextFunction, Request, Response } from &quot;express&quot;;<br>import { JwtTokens } from &quot;../helpers/jwt.token&quot;;<br><br>export class Auth {<br>  static async authentication(req: Request, res: Response, next: NextFunction) {<br>    try {<br>      const header = req.headers.authorization;<br>      if (!header) throw new Error(&quot;missing header&quot;);<br>      const token = header.split(&quot; &quot;)[1];<br>      if (!token) throw new Error(&quot;no tkone provided&quot;);<br>      const decode = await JwtTokens.verifyToken(token);<br>      if (!decode) throw new Error(&quot; unthorized&quot;);<br>      req[&quot;currentUser&quot;] = decode;<br>      next();<br>    } catch (error) {<br>      console.error(&quot;An erroe occured :&quot;, error);<br>      const errorMessage = error.message || &quot;An Unexpeded error&quot;;<br>      return res.status(500).json({ error: errorMessage });<br>    }<br>  }<br>  static async restMiddleware(req: Request, res: Response, next: NextFunction) {<br>    try {<br>      const header = req.headers.authorization;<br>      if (!header) throw new Error(&quot;missing header&quot;);<br>      const token = header.split(&quot; &quot;)[1];<br>      if (!token) throw new Error(&quot;no tkone provided&quot;);<br>      const decode = await JwtTokens.verifyToken2(token);<br>      if (!decode) throw new Error(&quot; unthorized&quot;);<br>      req[&quot;currentUser&quot;] = decode;<br>      next();<br>    } catch (error) {<br>      console.error(&quot;An erroe occured :&quot;, error);<br>      const errorMessage = error.message || &quot;An Unexpeded error&quot;;<br>      return res.status(500).json({ error: errorMessage });<br>    }<br>  }<br>}</pre><p>In web development frameworks like Express.js, middleware functions act as gatekeepers for incoming HTTP requests. These functions intercept requests before they reach the intended route handler, enabling crucial functionalities like access control and authorization. Within our Auth class, we leverage middleware to verify tokens passed in the request header. This verification process ensures that only authorized users with valid tokens can access specific routes and prevents unauthorized modifications, such as a malicious user changing another user&#39;s password.</p><h3>Controllers</h3><h4>user.controllers.ts</h4><pre>import axios from &quot;axios&quot;;<br>import { Request, Response } from &quot;express&quot;;<br>import { User } from &quot;../entity/User&quot;;<br>import { AppDataSource } from &quot;../data-source&quot;;<br>import { JwtTokens } from &quot;../helpers/jwt.token&quot;;<br>import { Encrypt } from &quot;../helpers/encrypt&quot;;<br>import Security from &quot;../helpers/crypto&quot;;<br><br>export class UserControllers {<br>  private userRepo = AppDataSource.getRepository(User);<br>  private security = new Security();<br>  private errorHandler(error: Error, req: Request, res: Response) {<br>    console.error(&quot;An error occurred:&quot;, error);<br>    const errorMessage = error.message || &quot;An unexpected error occurred&quot;;<br>    return res.status(500).json({ error: errorMessage });<br>  }<br>  async create(req: Request, res: Response) {<br>    try {<br>      const { name, email, password } = req.body;<br>      const phrases = async () =&gt; {<br>        return await axios.get(<br>          `https://random-word-api.herokuapp.com/word?number=10&amp;length=5`<br>        );<br>      };<br>      const user = new User();<br>      user.name = name;<br>      user.email = email;<br>      user.password = await Encrypt.hashPassword(password);<br>      //@ts-ignore<br>      user.recovery = this.security.encrypt(<br>        JSON.stringify((await phrases()).data)<br>      );<br>      await this.userRepo.save(user);<br>      const token = await JwtTokens.generateToken({ id: user.id });<br><br>      return res.status(201).json({<br>        message: &quot;User created successfully&quot;,<br>        data: user,<br>        jwt: token,<br>      });<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>  async login(req: Request, res: Response) {<br>    try {<br>      const { email, password } = req.body;<br>      const user = await this.userRepo.findOneBy({ email });<br>      if (!user) {<br>        throw new Error(&quot;user not found&quot;);<br>      }<br>      console.log(user, user.password, password);<br>      const isPasswordValid = await Encrypt.comparePassword(<br>        password,<br>        user.password<br>      );<br>      if (!isPasswordValid) {<br>        throw new Error(&quot;invalid password&quot;);<br>      }<br>      const token = await JwtTokens.generateToken({ id: user.id });<br>      return res.status(200).json({<br>        message: &quot;Login successful&quot;,<br>        token,<br>      });<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>  async getAllUsers(req: Request, res: Response) {<br>    try {<br>      const users = await this.userRepo.find();<br>      <br>      console.log(parse);<br>      return res.status(200).json({<br>        message: &quot;successs&quot;,<br>        data: users,<br>      });<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>  async getUserById(req: Request, res: Response) {<br>    try {<br>      const { id } = req.params;<br>      const user = await this.userRepo.findOneBy({ id });<br>      user.recovery = JSON.parse(this.security.decrypt(user.recovery));<br>      return res.status(200).json({<br>        message: &quot;successs&quot;,<br>        data: user,<br>      });<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>//TODO: only the user can update his/her identity<br>  async updateUser(req: Request, res: Response) {<br>    try {<br>      const { id } = req.params;<br>      const { name, email } = req.body;<br>      const user = await this.userRepo.findOneBy({ id });<br>      user.name = name;<br>      user.email = email;<br><br>      await this.userRepo.save(user);<br>      return res.status(200).json({<br>        message: &quot;User updated successfully&quot;,<br>        data: user,<br>      });<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>  async updatePassword(req: Request, res: Response) {<br>    try {<br>      const { id } = req[&quot;currentUser&quot;];<br>      const { newpassword } = req.body;<br>      const user = await this.userRepo.findOne({ where: { id } });<br>      user.password = await Encrypt.hashPassword(newpassword);<br>      await this.userRepo.save(user);<br>      return res.status(200).json({<br>        message: &quot;Password updated successfully&quot;,<br>      });<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>  async checkphrase(req: Request, res: Response) {<br>    try {<br>      console.log(req.params);<br>      const { email } = req.params;<br>      const { phrases } = req.body;<br>      const user = await this.userRepo.findOne({ where: { email } });<br><br>      const parse = JSON.stringify(phrases);<br>      const decode = JSON.stringify(this.security.decrypt(user.recovery));<br>      console.log(JSON.stringify(parse), decode);<br>      const token = await JwtTokens.genratepassResetToken({ id: user.id });<br>      if (decode === JSON.stringify(parse)) {<br>        return res.status(200).json({<br>          message: &quot;success&quot;,<br>          token,<br>        });<br>      } else {<br>        throw new Error(&quot;invalid recovery phrase&quot;);<br>      }<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>  async showphrases(req: Request, res: Response) {<br>    try {<br>      const { id } = req[&quot;currentUser&quot;];<br>      const { password } = req.body;<br><br>      const user = await this.userRepo.findOne({ where: { id } });<br>      const comparePassword = await Encrypt.comparePassword(<br>        password,<br>        user.password<br>      );<br>      if (!comparePassword) {<br>        throw new Error(&quot;please put correct password&quot;);<br>      }<br>      return res.status(200).json({<br>        message: &quot;success&quot;,<br>        data: JSON.parse(this.security.decrypt(user.recovery)),<br>      });<br>    } catch (error) {<br>      this.errorHandler(error, req, res);<br>    }<br>  }<br>}</pre><p><em>Tip: I recommend you to try and use </em><a href="https://www.npmjs.com/package/bip39"><em>bip39</em></a><em> to Generate a random phrase.</em></p><ul><li>The userRepo property is initialized with a repository obtained from AppDataSource to interact with the User entity.</li><li>An instance of the Security class is created and stored in the security property for encryption and decryption tasks.</li></ul><p><strong>Error Handling:</strong></p><ul><li>The errorHandler method is a private helper function responsible for logging errors and sending appropriate error responses.</li></ul><p><strong>User Creation (</strong><strong>create):</strong></p><ul><li>Handles the creation of a new user.</li><li>Retrieves user details (name, email, password) from the request body.</li><li>Generates a set of random recovery phrase using an external API call and encrypts them.</li><li>Saves the user entity to the database and returns a successful response with a JWT token.</li></ul><p><strong>User Login (</strong><strong>login):</strong></p><ul><li>Validates user credentials (email and password) provided in the request body.</li><li>Retrieves the user from the database based on the provided email.</li><li>Compares the hashed password with the provided password using bcrypt.</li><li>If authentication succeeds, generates and returns a JWT token for the user.</li></ul><p><strong>Get All Users (</strong><strong>getAllUsers):</strong></p><ul><li>Fetches all users from the database.</li></ul><p><strong>Get User by ID (</strong><strong>getUserById):</strong></p><ul><li>Fetches a user by their ID from the database.</li><li>Decrypts the recovery phrase for the user and returns the user details.</li></ul><p><strong>Update User (</strong><strong>updateUser):</strong></p><ul><li>Updates user details (name and email) based on the provided ID.</li><li>Saves the updated user entity to the database and returns a successful response.</li></ul><p><strong>Update Password (</strong><strong>updatePassword):</strong></p><ul><li>Updates the password for the current user.</li><li>Retrieves the user ID from the request’s currentUser property.</li><li>Hashes the new password using bcrypt and updates the user’s password in the database.</li></ul><p><strong>Check Recovery Phrase (</strong><strong>checkphrase):</strong></p><ul><li>Verifies the recovery phrase provided by the user.</li><li>Compares the decrypted recovery phrase from the user entity with the provided phrase.</li><li>If the phrases match, generates a token for password reset.</li></ul><p><strong>Show Recovery Phrases (</strong><strong>showphrases):</strong></p><ul><li>Retrieves the recovery phrase for the current user.</li><li>Requires the user to provide their password for verification.</li><li>kDecrypts and returns the recovery phrase if the password is Correct</li></ul><h3>Routers</h3><pre>import * as express from &quot;express&quot;;<br>import { UserControllers } from &quot;../controllers/user.controllers&quot;;<br>import { Auth } from &quot;../middleware/authMiddleware&quot;;<br><br>const UserRouter = express.Router();<br>const controllers = new UserControllers();<br>UserRouter.post(&quot;/create&quot;, controllers.create.bind(controllers));<br>UserRouter.get(&quot;/users&quot;, controllers.getAllUsers.bind(controllers));<br>UserRouter.get(&quot;/user/:id&quot;, controllers.getUserById.bind(controllers));<br>UserRouter.post(&quot;/check/:email&quot;, controllers.checkphrase.bind(controllers));<br>UserRouter.put(<br>  &quot;/changepassword&quot;,<br>  Auth.restMiddleware,<br>  controllers.updatePassword.bind(controllers)<br>);<br>UserRouter.post(&quot;/login&quot;, controllers.login.bind(controllers));<br>UserRouter.post(<br>  &quot;/showphrases&quot;,<br>  Auth.authentication,<br>  controllers.showphrases.bind(controllers)<br>);<br>export { UserRouter };</pre><p>this setup establishes the routing structure for handling user-related operations, binds controller methods to their corresponding routes, and applies middleware for authentication and authorization where necessary to secure the endpoints. I know I suck at naming my routes but do better than me. consider using more descriptive route names (e.g., /register instead of /create, /reset-password instead of /check/:email).</p><h3>conclusion</h3><p>In conclusion, the integration of recovery phrase represents a pivotal advancement in account security and user convenience. By introducing an extra layer of protection beyond passwords, recovery phrase addresses common vulnerabilities such as forgotten credentials and compromised accounts. As outlined in the introduction, the advantages are manifold, offering enhanced security and usability.</p><p>Moreover, recovery phrase ensures compliance with data protection regulations, providing a secure and regulatory-compliant solution for account recovery. Ultimately, they empower users with greater control over their accounts while enabling organizations to bolster security measures, foster trust, and adhere to stringent data protection standards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c82d32731a5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a REST API: A Hexagonal Approach with TypeScript, TypeORM, PostgreSQL, and JWT]]></title>
            <link>https://medium.com/@christianinyekaka/building-a-rest-api-a-hexagonal-approach-with-typescript-typeorm-postgresql-and-jwt-946d372860ee?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/946d372860ee</guid>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 11:23:02 GMT</pubDate>
            <atom:updated>2024-03-15T11:23:02.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*hrG741toCxgYEWKDqVmFuw.png" /><figcaption>Wikipedia image</figcaption></figure><p>Building robust and maintainable APIs is crucial for creating successful applications in today&#39;s software development landscape. In this article, we will explore how to develop a REST API using TypeScript, TypeORM, PostgreSQL, and JWT authentication, following the principles of Hexagonal Architecture. By leveraging these technologies and architectural principles, we can create scalable, modular, and secure APIs that are easy to understand and maintain.</p><p><strong>What is Hexagonal Architecture?</strong></p><p>Hexagonal Architecture, also known as Ports and Adapters Architecture or Clean Architecture, is a design pattern that emphasizes separating concerns and decoupling dependencies in software systems. The core idea is to organize the application into layers, where the business logic (the core domain) resides at the center, surrounded by ports (interfaces) that define interactions with external systems, and adapters that implement those interactions.</p><p><strong>Why Use Hexagonal Architecture?</strong></p><p>Hexagonal Architecture offers several benefits:</p><ol><li><strong>Modularity</strong>: The architecture promotes modularity by separating concerns into distinct layers. This makes it easier to understand, maintain, and extend the codebase.</li><li><strong>Testability</strong>: By decoupling the core domain logic from external dependencies, such as databases or frameworks, writing unit tests and mock external dependencies during testing becomes easier.</li><li><strong>Flexibility</strong>: Hexagonal Architecture allows for flexibility in choosing and swapping out external dependencies without affecting the core domain logic. This makes it easier to adapt to changing requirements or technology shifts.</li><li><strong>Scalability</strong>: The modular nature of the architecture makes it easier to scale the application horizontally or vertically as the system grows in complexity or user base.</li></ol><h3>Prerequisites:</h3><p>Before diving in, ensure you have some experience or understanding of the following tools:</p><ul><li>TypeScript</li><li>TypeORM</li><li>SQL</li><li>Node.js &amp; NPM</li><li>JSON Web Tokens (JWT)</li></ul><h4>Project Setup</h4><p>Create a new project</p><pre>mkdir hexagon<br>cd hexagon<br>npm init -y</pre><p>Now, let’s install dependencies:</p><pre>npm install express dotenv bcrypt jsonwebtoken concurrently <br>npm install typeorm --save<br>npm install pg --save<br>npm install @types/node --save-dev<br>npm install reflect-metadata --save<br></pre><p>Here’s what each of the installed packages does:</p><ul><li><strong>Express</strong> is a web framework for Node.js used for server creation</li><li><strong>dotenv </strong>helps<strong> </strong>read all the environment variables</li><li><strong>bcrypt</strong> is used to encrypt a password</li><li><strong>jsonwebtoken</strong> are often used to identify a user, as well as to transmit information about the user, and the tokens are often used for authentication and authorization in web applications</li><li><strong>concurrently</strong> is a Node.js utility that allows you to run multiple npm scripts concurrently in a single terminal</li><li><strong>TypeORM</strong> is an Object-Relational Mapping (ORM) library for TypeScript and JavaScript. It simplifies database interactions by allowing developers to work with objects and classes, rather than directly interacting with the database.</li><li><strong>pg</strong> is the Node.js driver for PostgreSQL, a popular open-source relational database management system. It allows Node.js applications to connect to and interact with PostgreSQL databases</li><li><strong>reflect-metadata</strong> is a package used to enable reflection metadata for TypeScript. Reflection metadata allows TypeScript code to inspect and manipulate the types of objects and their properties at runtime</li><li><strong>@types/node</strong> is a package that provides TypeScript type definitions for the Node.js runtime environment and core modules.</li></ul><h3>Install TypeScript type definitions for these dependencies:</h3><p>Since we are working with TypeScript, it is a good idea to install @types for our dependencies.</p><pre>npm i @types/express @types/bcrypt @types/jsonwebtoken </pre><h4>Folder structure</h4><pre><br>Hexagon<br> ┣ src<br> ┃ ┣ adapters<br> ┃ ┃ ┣ database<br> ┃ ┃ ┃ ┗ data-source.ts<br> ┃ ┃ ┣ helpers<br> ┃ ┃ ┃ ┗ encrypt.ts<br> ┃ ┃ ┣ http<br> ┃ ┃ ┃ ┣ controllers<br> ┃ ┃ ┃ ┃ ┣ Cars.controllers.ts<br> ┃ ┃ ┃ ┃ ┗ User.controllers.ts<br> ┃ ┃ ┃ ┣ middleware<br> ┃ ┃ ┃ ┃ ┗ Authentication.ts<br> ┃ ┃ ┃ ┗ routes<br> ┃ ┃ ┃ ┃ ┣ car.routes.ts<br> ┃ ┃ ┃ ┃ ┗ user.routes.ts<br> ┃ ┃ ┗ secondaryAdapter<br> ┃ ┃ ┃ ┣ typeOrmCarsRepo.ts<br> ┃ ┃ ┃ ┗ typeOrmUserRepo.ts<br> ┃ ┣ core<br> ┃ ┃ ┣ entity<br> ┃ ┃ ┃ ┣ Cars.ts<br> ┃ ┃ ┃ ┗ User.ts<br> ┃ ┃ ┣ migration<br> ┃ ┃ ┣ ports<br> ┃ ┃ ┃ ┣ CarsRepositoryPort.ts<br> ┃ ┃ ┃ ┗ UserRepositoryPort.ts<br> ┃ ┃ ┗ services<br> ┃ ┃ ┃ ┣ carService.ts<br> ┃ ┃ ┃ ┗ userService.ts<br> ┃ ┗ index.ts<br> ┣ .env<br> ┣ .gitignore<br> ┣ package-lock.json<br> ┣ package.json<br> ┣ README.md<br> ┗ tsconfig.json</pre><p>package.json</p><pre>{<br>  &quot;name&quot;: &quot;Hexagon&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;description&quot;: &quot;Awesome project developed with TypeORM.&quot;,<br>  &quot;type&quot;: &quot;commonjs&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;@types/bcrypt&quot;: &quot;^5.0.2&quot;,<br>    &quot;@types/cors&quot;: &quot;^2.8.17&quot;,<br>    &quot;@types/jsonwebtoken&quot;: &quot;^9.0.6&quot;,<br>    &quot;@types/node&quot;: &quot;^16.11.10&quot;,<br>    &quot;ts-node&quot;: &quot;10.7.0&quot;,<br>    &quot;typescript&quot;: &quot;4.5.2&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@types/express&quot;: &quot;^4.17.21&quot;,<br>    &quot;bcrypt&quot;: &quot;^5.1.1&quot;,<br>    &quot;concurrently&quot;: &quot;^8.2.2&quot;,<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;dotenv&quot;: &quot;^16.4.5&quot;,<br>    &quot;express&quot;: &quot;^4.18.3&quot;,<br>    &quot;jsonwebtoken&quot;: &quot;^9.0.2&quot;,<br>    &quot;pg&quot;: &quot;^8.4.0&quot;,<br>    &quot;reflect-metadata&quot;: &quot;^0.1.13&quot;,<br>    &quot;typeorm&quot;: &quot;0.3.17&quot;<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;watch&quot;: &quot;tsc -w&quot;,<br>    &quot;dev&quot;: &quot;nodemon build/index.js&quot;,<br>    &quot;start:dev&quot;: &quot;concurrently \&quot;tsc -w\&quot; \&quot;nodemon build/index.js\&quot;&quot;,<br>    &quot;build&quot;: &quot;tsc&quot;,<br>    &quot;start&quot;: &quot;ts-node src/index.ts&quot;,<br>    &quot;typeorm&quot;: &quot;typeorm-ts-node-commonjs&quot;,<br>    &quot;migration&quot;: &quot; npm run typeorm migration:run -- -d ./src/data-source.ts&quot;<br>  }<br>}</pre><p>The package.json file in our project serves multiple purposes such as :</p><ol><li>Dependency Management: Lists all dependencies and their versions, used by package managers like npm or yarn for installation.</li><li>Script Execution: Defines custom scripts for automating tasks such as building, testing, and deployment.</li><li>Versioning and Publishing: Contains metadata for reusable packages or libraries, including name, version, description, author, and license.</li><li>Project Configuration: Includes configuration options for various tools and libraries used in the project, such as ESLint, TypeScript, Babel, and Webpack.</li><li>Lock File Management: Generates lock files (package-lock.json or yarn.lock) to ensure deterministic dependency resolution and consistent builds across different environments.</li></ol><p><strong>Tsconfig file</strong></p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;lib&quot;: [&quot;es5&quot;, &quot;es6&quot;],<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;outDir&quot;: &quot;./build&quot;,<br>    &quot;emitDecoratorMetadata&quot;: true,<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;sourceMap&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true<br>  }<br>}</pre><p>this tsconfig.json file provides configuration options to compile TypeScript code into ECMAScript 5-compatible JavaScript using CommonJS modules, with support for experimental decorators, strict type-checking, and source map generation.</p><h4><strong>src/core/entity/User.ts &amp; Cars.ts</strong></h4><pre>//User Entity//<br>import {<br>  Entity,<br>  PrimaryGeneratedColumn,<br>  Column,<br>  CreateDateColumn,<br>  UpdateDateColumn,<br>  OneToMany,<br>} from &quot;typeorm&quot;;<br>import { Cars } from &quot;./Cars&quot;;<br><br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn(&quot;uuid&quot;)<br>  id!: string;<br><br>  @Column()<br>  fullName!: string;<br><br>  @Column()<br>  email!: string;<br><br>  @Column()<br>  password!: string;<br>  @OneToMany(() =&gt; Cars, (cars) =&gt; cars.user, {<br>    onDelete: &quot;SET NULL&quot;,<br>    onUpdate: &quot;CASCADE&quot;,<br>  })<br>  cars!: Cars[];<br>  @CreateDateColumn()<br>  createdAt!: Date;<br><br>  @UpdateDateColumn()<br>  updatedAt!: Date;<br>}</pre><pre>//Cars entity//<br>import {<br>  Column,<br>  CreateDateColumn,<br>  Entity,<br>  JoinColumn,<br>  ManyToOne,<br>  PrimaryGeneratedColumn,<br>  UpdateDateColumn,<br>} from &quot;typeorm&quot;;<br>import { User } from &quot;./User&quot;;<br><br>@Entity()<br>export class Cars {<br>  @PrimaryGeneratedColumn(&quot;uuid&quot;)<br>  id!: string;<br>  @Column()<br>  name!: string;<br>  @Column()<br>  brand!: string;<br>  @Column()<br>  color!: string;<br>  @ManyToOne(() =&gt; User, (user) =&gt; user.cars, {<br>    onDelete: &quot;SET NULL&quot;,<br>    onUpdate: &quot;CASCADE&quot;,<br>  })<br>  @JoinColumn({ name: &quot;user_id&quot; })<br>  user!: User;<br><br>  @CreateDateColumn()<br>  createdAt!: Date;<br>  @UpdateDateColumn()<br>  updatedAt!: Date;<br>}</pre><p>In these files, we define two entities representing users and cars. They establish a one-to-many and many-to-one relationship. The options for onDelete and onUpdate are set to set null and cascade to manage the relationship if the user is deleted or updated.</p><h4>src/core/ports/CarsRepositoryPort.ts &amp;UserRepositoryPort.ts</h4><pre>import { User } from &quot;../entity/User&quot;;<br><br>export interface UserRepositoryPort {<br>  findAll(): Promise&lt;User[]&gt;;<br>  findByEmail(email: string): Promise&lt;User|null&gt;;<br>  findId(id: string): Promise&lt;User|null&gt;;<br>  createUser(user: User): Promise&lt;User&gt;;<br>  deleteUser(id: string): Promise&lt;boolean&gt;;<br>  updateUser(id: string, user: User): Promise&lt;User&gt;;<br>}<br></pre><pre>import { Cars } from &quot;../entity/Cars&quot;;<br><br>export interface CarsRepositoryPort {<br>  findAll(): Promise&lt;Cars[]&gt;;<br>  findByOne(param: string): Promise&lt;Cars | null&gt;;<br>  saveCar(user: Cars, id: string): Promise&lt;Cars&gt;;<br>  deleteCar(id: string): Promise&lt;boolean&gt;;<br>  updateCar(id: string, user: Cars): Promise&lt;Cars&gt;;<br>}</pre><p>These files contain interfaces that define the contract between the application&#39;s core domain logic and the external data sources or repositories.</p><p>Those interfaces define methods for performing CRUD (Create, Read, Update, Delete) operations on User and Car entities.</p><h4><strong>src/core/services/carService.ts &amp;&amp; userService.ts</strong></h4><p>The UserService class constructor accepts an instance of a UserRepositoryPort interface, allowing it to interact with user data through the methods defined in the interface. The class provides methods for performing various user-related operations, including retrieving all users, creating a new user, updating a user&#39;s information, deleting a user, and finding a user by ID or email.</p><pre>import { User } from &quot;../entity/User&quot;;<br>import { UserRepositoryPort } from &quot;../ports/UserRepositoryPort&quot;;<br><br>export class UserService {<br>  constructor(private readonly userRepository: UserRepositoryPort) {}<br><br>  //user<br>  async getUsers(): Promise&lt;User[]&gt; {<br>    return await this.userRepository.findAll();<br>  }<br>  async createUser(user: User): Promise&lt;User&gt; {<br>    return await this.userRepository.createUser(user);<br>  }<br>  async updateUser(id: string, user: User): Promise&lt;User&gt; {<br>    return await this.userRepository.updateUser(id, user);<br>  }<br>  async deleteUser(id: string): Promise&lt;boolean&gt; {<br>    return await this.userRepository.deleteUser(id);<br>  }<br>  async getUser(id: string): Promise&lt;User | null&gt; {<br>    return await this.userRepository.findId(id);<br>  }<br>  async getUserByEmail(email: string): Promise&lt;User | null&gt; {<br>    return await this.userRepository.findByEmail(email);<br>  }<br>}</pre><pre>import { Cars } from &quot;../entity/Cars&quot;;<br>import { User } from &quot;../entity/User&quot;;<br>import { CarsRepositoryPort } from &quot;../ports/CarsRepositoryPort&quot;;<br>import { UserRepositoryPort } from &quot;../ports/UserRepositoryPort&quot;;<br><br>export class CarService {<br>  constructor(<br>    private readonly carsRepository: CarsRepositoryPort,<br>    private readonly userRepository: UserRepositoryPort<br>  ) {}<br>  async getCars(): Promise&lt;Cars[]&gt; {<br>    return await this.carsRepository.findAll();<br>  }<br>  async createCar(car: Cars, userId: string): Promise&lt;Cars&gt; {<br>    const user = await this.userRepository.findId(userId);<br>    car.user = user as User;<br>    return await this.carsRepository.saveCar(car, userId);<br>  }<br>  async updateCar(id: string, car: Cars): Promise&lt;Cars&gt; {<br>    return await this.carsRepository.updateCar(id, car);<br>  }<br>  async deleteCar(id: string): Promise&lt;boolean&gt; {<br>    return await this.carsRepository.deleteCar(id);<br>  }<br>  async getCar(param: string): Promise&lt;Cars | null&gt; {<br>    return await this.carsRepository.findByOne(param);<br>  }<br>}</pre><p>The CarService class constructor accepts instances of both CarsRepositoryPort and UserRepositoryPort interfaces, enabling it to interact with car and user data sources. The class provides methods for performing CRUD operations on car entities, including retrieving all cars, creating a new car for a user, updating a car&#39;s information, deleting a car, and finding a car by a parameter.</p><p>These service classes encapsulate the application’s business logic, abstracting away the details of data access and manipulation. They serve as intermediaries between the application’s core domain logic and the data access layer, promoting modularity, testability, and maintainability.</p><h4>src/adapters/database/data-sorce.ts</h4><pre>import &quot;reflect-metadata&quot;;<br>import { DataSource } from &quot;typeorm&quot;;<br><br>import * as dotenv from &quot;dotenv&quot;;<br>import { User } from &quot;../../core/entity/User&quot;;<br>import { Cars } from &quot;../../core/entity/Cars&quot;;<br><br>dotenv.config();<br><br>const { DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD, DB_DATABASE, NODE_ENV } =<br>  process.env;<br><br>export const AppDataSource = new DataSource({<br>  type: &quot;postgres&quot;,<br>  host: DB_HOST,<br>  port: parseInt(DB_PORT || &quot;5432&quot;),<br>  username: DB_USERNAME,<br>  password: DB_PASSWORD,<br>  database: DB_DATABASE,<br>  synchronize: NODE_ENV === &quot;dev&quot; ? true : false,<br>  logging: NODE_ENV === &quot;dev&quot; ? true : false,<br>  entities: [User, Cars],<br>  migrations: [__dirname + &quot;/migration/*.ts&quot;],<br>  subscribers: [],<br>});</pre><p>This file handles database configuration, including reading environment variables. Make sure your .env file contains the necessary database connection details.</p><h4>src/adapters/helpers/encrypt.ts</h4><pre>import * as bycrpt from &quot;bcrypt&quot;;<br>import * as jwt from &quot;jsonwebtoken&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br>const { JWT_SECRET = &quot;&quot; } = process.env;<br>interface payload {<br>  id: string;<br>}<br>export class Ecrypt {<br>  static async passwaorEncrypt(pass: string) {<br>    return bycrpt.hashSync(pass, 10);<br>  }<br>  static async comparePass(pass: string, hash: string) {<br>    return bycrpt.compareSync(pass, hash);<br>  }<br>  static async generateToken(payload: payload) {<br>    return jwt.sign(payload, JWT_SECRET, { expiresIn: &quot;1d&quot; });<br>  }<br>}</pre><p>This file contains utility functions for encrypting passwords, comparing passwords, and generating JWT tokens.</p><p>These utility functions provide essential functionality for securely handling user authentication and authorization within the application. They abstract away the complexity of password hashing and JWT token generation, ensuring that sensitive information remains protected.</p><h4>src/adapters/http/contollers/Cars.controllers.ts &amp; User.controllers.ts</h4><pre>import { Request, Response } from &quot;express&quot;;<br>import { UserService } from &quot;../../../core/services/userService&quot;;<br>import { User } from &quot;../../../core/entity/User&quot;;<br>import { Ecrypt } from &quot;../../helpers/encrypt&quot;;<br><br>export class UserController {<br>  constructor(private userService: UserService) {}<br><br>  async getAllUsers(req: Request, res: Response) {<br>    const users = await this.userService.getUsers();<br>    if (!users) {<br>      return res.status(404).json({ message: &quot;No users found&quot; });<br>    }<br>    return res.status(200).json(users);<br>  }<br>  async getUser(req: Request, res: Response) {<br>    const { id } = req.params;<br>    const user = await this.userService.getUser(id);<br>    if (!user) {<br>      return res.status(404).json({ message: &quot;User not found&quot; });<br>    }<br>    return res.status(200).json(user);<br>  }<br>  async createUser(req: Request, res: Response) {<br>    const { fullName, email, password } = req.body;<br>    const encryptedPassword = await Ecrypt.passwaorEncrypt(password);<br>    const newUser = await this.userService.createUser({<br>      fullName: fullName,<br>      email: email,<br>      password: encryptedPassword,<br>    } as User);<br>    if (!newUser) {<br>      return res.status(400).json({ message: &quot;User already exists&quot; });<br>    }<br>    const token = await Ecrypt.generateToken({ id: newUser.id });<br>    return res.status(201).json({ user: newUser, token });<br>  }<br>  async updateUser(req: Request, res: Response) {<br>    const { id } = req.params;<br>    const user = req.body as User;<br>    const updatedUser = await this.userService.updateUser(id, user);<br>    if (!updatedUser) {<br>      return res.status(404).json({ message: &quot;User not found&quot; });<br>    }<br>    return res.status(200).json(updatedUser);<br>  }<br>  async deleteUser(req: Request, res: Response) {<br>    const { id } = req.params;<br>    const deleted = await this.userService.deleteUser(id);<br>    if (!deleted) {<br>      return res.status(404).json({ message: &quot;User not found&quot; });<br>    }<br>    return res.status(204).json();<br>  }<br>  async getUserByEmail(req: Request, res: Response) {<br>    const { email } = req.params;<br>    const user = await this.userService.getUserByEmail(email);<br>    if (!user) {<br>      return res.status(404).json({ message: &quot;User not found&quot; });<br>    }<br>    return res.status(200).json(user);<br>  }<br>}</pre><pre>import { Request, Response } from &quot;express&quot;;<br>import { CarsRepositoryPort } from &quot;../../../core/ports/CarsRepositoryPort&quot;;<br>import { CarService } from &quot;../../../core/services/carService&quot;;<br><br>export class CarsController {<br>  constructor(private carsService: CarService) {}<br><br>  async getCars(req: Request, res: Response): Promise&lt;Response&gt; {<br>    const cars = await this.carsService.getCars();<br>    if (!cars) {<br>      return res.status(404).json({ message: &quot;No cars found&quot; });<br>    }<br>    return res.status(200).json(cars);<br>  }<br>  async getCar(req: Request, res: Response): Promise&lt;Response&gt; {<br>    const { id } = req.params;<br>    const car = await this.carsService.getCar(id);<br>    if (!car) {<br>      return res.status(404).json({ message: &quot;Car not found&quot; });<br>    }<br>    return res.status(200).json(car);<br>  }<br>  async createCar(req: Request, res: Response): Promise&lt;Response&gt; {<br>    const car = req.body;<br>    //@ts-ignore<br>    const { id } = req[&quot;currentUser&quot;];<br>    const newCar = await this.carsService.createCar(car, id);<br>    return res.status(201).json(newCar);<br>  }<br>  async updateCar(req: Request, res: Response): Promise&lt;Response&gt; {<br>    const { id } = req.params;<br>    const car = req.body;<br>    const updatedCar = await this.carsService.updateCar(id, car);<br>    if (!updatedCar) {<br>      return res.status(404).json({ message: &quot;Car not found&quot; });<br>    }<br>    return res.status(200).json(updatedCar);<br>  }<br>  async deleteCar(req: Request, res: Response): Promise&lt;Response&gt; {<br>    const { id } = req.params;<br>    const deleted = await this.carsService.deleteCar(id);<br>    if (!deleted) {<br>      return res.status(404).json({ message: &quot;Car not found&quot; });<br>    }<br>    return res.status(204).json();<br>  }<br>}</pre><p>These controller classes define methods to handle various HTTP requests (GET, POST, PUT, DELETE) related to users and cars. They interact with the corresponding service classes (UserService and CarService) to perform business logic and communicate with the database through repository ports (UserRepositoryPort and CarsRepositoryPort). Additionally, the Ecrypt helper class is used for password encryption and JWT token generation in the UserController. Each method returns an appropriate HTTP response based on the success or failure of the operation.</p><h4>src/adapters/http/middleware/middleware.ts</h4><pre>import { NextFunction, Request, Response } from &quot;express&quot;;<br>import * as jwt from &quot;jsonwebtoken&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br><br>export class Middleware {<br>  static async verifyToken(req: Request, res: Response, next: NextFunction) {<br>    const header = req.headers.authorization;<br>    if (!header) {<br>      return res.status(401).json({ message: &quot;Unauthorized&quot; });<br>    }<br>    const token = header.split(&quot; &quot;)[1];<br>    if (!token) {<br>      return res.status(401).json({ message: &quot;Unauthorized&quot; });<br>    }<br>    const decoded = jwt.verify(token, process.env.JWT_SECRET || &quot;&quot;);<br>    if (!decoded) {<br>      return res.status(401).json({ message: &quot;Unauthorized&quot; });<br>    }<br>    //@ts-expect-error<br>    req[&quot;currentUser&quot;] = decoded;<br><br>    next();<br>  }<br>  static async errorHandler(<br>    error: Error,<br>    req: Request,<br>    res: Response,<br>    next: NextFunction<br>  ) {<br>    console.error(`Error: ${error.message}`);<br>    return res.status(500).json({ message: &quot;Internal server error&quot; });<br>  }<br>}</pre><p><strong>vifyToken</strong></p><p>This middleware function checks if the authorization header is present in the request. If not, it returns a 401 Unauthorized response. If the header is present, it extracts the JWT token from the header and verifies it using the secret key stored in the environment variables. If the token is valid, it attaches the decoded token payload to the request object (req[&quot;currentUser&quot;]) and calls the next() function to pass control to the next middleware or route handler. If the token is invalid or verification fails, it returns a 401 Unauthorized response.</p><p><strong>errorHandler</strong></p><p>This middleware function handles errors that occur during request processing.</p><h4>src/adapters/HTTP/secondaryAdapter /typeOrmCarsRepo.ts &amp; typeOrmUserRepo.ts</h4><pre>import { User } from &quot;../../core/entity/User&quot;;<br>import { UserRepositoryPort } from &quot;../../core/ports/UserRepositoryPort&quot;;<br>import { AppDataSource } from &quot;../database/data-source&quot;;<br><br>export class TypeOrmUserRepositoryPort implements UserRepositoryPort {<br>  private userRepository = AppDataSource.getRepository(User);<br>  async findAll(): Promise&lt;User[]&gt; {<br>    const users = await this.userRepository.find({ relations: [&quot;cars&quot;] });<br><br>    return users;<br>  }<br>  async findByEmail(email: string): Promise&lt;User | null&gt; {<br>    const user = this.userRepository.findOne({<br>      where: { email },<br>    });<br>    return user;<br>  }<br>  async findId(id: string): Promise&lt;User | null&gt; {<br>    const user = this.userRepository.findOne({<br>      where: { id },<br>      relations: [&quot;cars&quot;],<br>    });<br>    return user;<br>  }<br>  async updateUser(id: string, user: User): Promise&lt;User&gt; {<br>    const userToUpdate = await this.userRepository.findOne({ where: { id } });<br>    if (!userToUpdate) {<br>      throw new Error(&quot;User not found&quot;);<br>    }<br>    userToUpdate.email = user.email;<br>    userToUpdate.fullName = user.fullName;<br><br>    return await this.userRepository.save(userToUpdate);<br>  }<br>  async deleteUser(id: string): Promise&lt;boolean&gt; {<br>    const userToDelete = await this.userRepository.findOne({ where: { id } });<br>    if (!userToDelete) {<br>      throw new Error(&quot;User not found&quot;);<br>    }<br>    await this.userRepository.remove(userToDelete);<br>    return true;<br>  }<br>  async createUser(user: User): Promise&lt;User&gt; {<br>    const newUser = await this.userRepository.save(user);<br>    return newUser;<br>  }<br>}</pre><pre>import { CarsRepositoryPort } from &quot;../../core/ports/CarsRepositoryPort&quot;;<br>import { Cars } from &quot;../../core/entity/Cars&quot;;<br>import { User } from &quot;../../core/entity/User&quot;;<br>import { AppDataSource } from &quot;../database/data-source&quot;;<br><br>export class typeOrmCarsRepo implements CarsRepositoryPort {<br>  private carsRepository = AppDataSource.getRepository(Cars);<br>  private usersRepository = AppDataSource.getRepository(User);<br>  async findAll(): Promise&lt;Cars[]&gt; {<br>    const cars = this.carsRepository.find({ relations: [&quot;user&quot;] });<br>    return cars;<br>  }<br>  async findByOne(param: string): Promise&lt;Cars | null&gt; {<br>    const car = this.carsRepository.findOne({<br>      where: { id: param },<br>      relations: [&quot;user&quot;],<br>    });<br>    return car;<br>  }<br>  async saveCar(user: Cars, id: string): Promise&lt;Cars&gt; {<br>    const owner = await this.usersRepository.findOne({ where: { id } });<br>    const car = new Cars();<br>    car.name = user?.name;<br>    car.brand = user?.brand;<br>    car.color = user?.color;<br>    car.user = owner as User;<br><br>    return this.carsRepository.save(car);<br>  }<br>  async deleteCar(id: string): Promise&lt;boolean&gt; {<br>    const carToDelete = await this.carsRepository.findOne({ where: { id } });<br>    if (!carToDelete) {<br>      throw new Error(&quot;Car not found&quot;);<br>    }<br><br>    await this.carsRepository.remove(carToDelete);<br>    return true;<br>  }<br>  async updateCar(id: string, user: Cars): Promise&lt;Cars&gt; {<br>    const carToUpdate = await this.carsRepository.findOne({ where: { id } });<br>    if (!carToUpdate) {<br>      throw new Error(&quot;Car not found&quot;);<br>    }<br>    carToUpdate.name = user?.name;<br>    carToUpdate.brand = user?.brand;<br>    carToUpdate.color = user?.color;<br>    return this.carsRepository.save(carToUpdate);<br>  }<br>}</pre><p>These files provide implementations of repository ports defined in the UserRepositoryPort and CarsRepositoryPort interfaces. They utilize TypeORM to perform database operations on the User and Cars entities.</p><ul><li>TypeOrmUserRepositoryPort: Implements methods for CRUD operations related to users. It interacts with the User entity using TypeORM and provides functionalities like finding users by email or ID, updating and deleting users, and creating new users.</li><li>typeOrmCarsRepo: Implements methods for CRUD operations related to cars. It interacts with the Cars entity using TypeORM and provides functionalities like finding cars by ID, updating and deleting cars, and creating new cars. It also handles the relationship between cars and users by associating cars with their respective owners.</li></ul><p>These implementations encapsulate the database interactions and provide a clean interface for the application’s core logic to interact with the underlying data storage layer.</p><h4>src/adapters/htpp/routes/car.routes.ts &amp; user.routes.ts</h4><pre>import * as express from &quot;express&quot;;<br>import { TypeOrmUserRepositoryPort } from &quot;../../secondaryAdapter/typeOrmUserRepo&quot;;<br>import { UserController } from &quot;../controllers/User.controllers&quot;;<br>import { UserService } from &quot;../../../core/services/userService&quot;;<br>import { Middleware } from &quot;../middleware/Middleware&quot;;<br><br>const router = express.Router();<br>const userRepository = new TypeOrmUserRepositoryPort();<br>const userService = new UserService(userRepository);<br>const userController = new UserController(userService);<br><br>router.get(&quot;/users&quot;, userController.getAllUsers.bind(userController));<br>router.post(&quot;/user/create&quot;, userController.createUser.bind(userController));<br>router.get(<br>  &quot;/user/:id&quot;,<br>  Middleware.verifyToken,<br>  userController.getUser.bind(userController)<br>);<br>router.put(<br>  &quot;/user/:id&quot;,<br>  Middleware.verifyToken,<br>  userController.updateUser.bind(userController)<br>);<br>router.delete(<br>  &quot;/user/:id&quot;,<br>  Middleware.verifyToken,<br>  userController.deleteUser.bind(userController)<br>);<br>router.get(<br>  &quot;/user/:email&quot;,<br>  Middleware.verifyToken,<br>  userController.getUserByEmail.bind(userController)<br>);<br><br>export default router;<br></pre><pre>import * as express from &quot;express&quot;;<br>import { CarService } from &quot;../../../core/services/carService&quot;;<br>import { TypeOrmUserRepositoryPort } from &quot;../../secondaryAdapter/typeOrmUserRepo&quot;;<br>import { typeOrmCarsRepo } from &quot;../../secondaryAdapter/typeOrmCarsRepo&quot;;<br>import { CarsController } from &quot;../controllers/Cars.controllers&quot;;<br>import { Middleware } from &quot;../middleware/Middleware&quot;;<br>const carRepository = new typeOrmCarsRepo();<br>const userRepository = new TypeOrmUserRepositoryPort();<br>const carService = new CarService(carRepository, userRepository);<br>const CarsControllers = new CarsController(carService);<br><br>const router = express.Router();<br><br>router.get(<br>  &quot;/cars&quot;,<br>  Middleware.verifyToken,<br>  CarsControllers.getCars.bind(CarsControllers)<br>);<br>router.get(<br>  &quot;/car/:id&quot;,<br>  Middleware.verifyToken,<br>  CarsControllers.getCar.bind(CarsControllers)<br>);<br>router.post(<br>  &quot;/car/create&quot;,<br>  Middleware.verifyToken,<br>  CarsControllers.createCar.bind(CarsControllers)<br>);<br>router.put(<br>  &quot;/car/:id&quot;,<br>  Middleware.verifyToken,<br>  CarsControllers.updateCar.bind(CarsControllers)<br>);<br>router.delete(<br>  &quot;/car/:id&quot;,<br>  Middleware.verifyToken,<br>  CarsControllers.deleteCar.bind(CarsControllers)<br>);<br>export { router as carRoutes };</pre><p>These route files define the endpoints for handling various operations related to users and cars. Each route is associated with a specific controller method responsible for processing the incoming requests and generating appropriate responses. The Middleware.verifyToken middleware is used to authenticate requests by verifying JWT tokens before allowing access to protected routes.</p><p><strong>why I used bind()</strong></p><p>The bind() method in JavaScript is used to create a new function that, when called, has its this keyword set to a specific value, which is provided as the first argument to bind(). This method is commonly used in situations where you want to ensure that a function is called with a specific context, regardless of how it&#39;s invoked.</p><p>In the context of Express.js route handlers, bind() is often used to ensure that the this context inside the controller methods remains bound to the controller instance itself. This is important because when you define route handlers in Express, they are detached from the instance of the object they belong to, and their this context is not automatically bound.</p><p>Let’s take a closer look :</p><pre>const carsController = new CarsController(carService);<br>router.get(&quot;/cars&quot;, Middleware.verifyToken, carsController.getCars.bind(carsController));</pre><ul><li>carsController.getCars.bind(carsController) creates a new function where the this context is explicitly bound to the carsController instance.</li><li>When Express invokes the getCars method in response to an incoming request, it will maintain the correct this context, ensuring that the method can access the properties and methods of the carsController instance as expected.</li></ul><p>Without using bind(), the this context inside the getCars method would be undefined or bound to the global object (window in the browser, global in Node.js), which could lead to errors or unexpected behavior when accessing instance properties or methods.</p><p>In short, bind() is used in Express.js route handlers to ensure that the correct this context is maintained when invoking controller methods, allowing for proper encapsulation and access to instance-specific functionality.</p><h4>src/index.ts</h4><pre>import * as express from &quot;express&quot;;<br>import router from &quot;./adapters/http/routes/user.routes&quot;;<br>import { AppDataSource } from &quot;./adapters/database/data-source&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>import * as cors from &quot;cors&quot;;<br>import &quot;reflect-metadata&quot;;<br>import { Middleware } from &quot;./adapters/http/middleware/Middleware&quot;;<br>import { carRoutes } from &quot;./adapters/http/routes/car.routes&quot;;<br>dotenv.config();<br>const app = express();<br>const PORT = process.env.PORT || 3000;<br><br>app.use(express.json());<br>app.use(cors());<br>app.use(Middleware.errorHandler);<br>app.use(&quot;/auth&quot;, router);<br>app.use(&quot;/api&quot;, carRoutes);<br>app.get(&quot;*&quot;, (req: express.Request, res: express.Response) =&gt; {<br>  res.status(404).json({ message: &quot;Page not found&quot; });<br>});<br>AppDataSource.initialize()<br>  .then(() =&gt; {<br>    console.log(&quot;database started!!!!!!!!!&quot;);<br>    app.listen(PORT, () =&gt; {<br>      console.log(`Server is running on port ${PORT}`);<br>    });<br>  })<br>  .catch((error) =&gt; {<br>    console.log(error);<br>  });</pre><p>This file sets up the basic infrastructure for the application, including middleware, routing, error handling, and database initialization, and then starts the server to listen for incoming requests on the specified port.</p><h4>Testing</h4><p>To test your API, you can use tools like Postman, cURL, or any other HTTP client. You can make requests to your API endpoints to ensure that they work as expected.</p><blockquote>What other tools or techniques have you found useful for testing RESTful APIs?</blockquote><p>We’d love to hear about your favorite tools and techniques for testing RESTful APIs. Share your recommendations in the comments below!!!!</p><h4>Error Handling</h4><p>In the provided errorHandler middleware, any unhandled errors are caught, logged, and a generic error response is sent to the client. You can customize this middleware to suit your error-handling needs.</p><blockquote>”Have you encountered challenges with error handling in your API development projects? How did you overcome them?”</blockquote><h4>Conclusion</h4><p>In conclusion, we have covered the process of developing a robust RESTful API using TypeScript, TypeORM, PostgreSQL, JWT Authentication, and Hexagonal Architecture. By following this guide, you can build scalable, secure, and maintainable APIs for your modern web applications.</p><p>By adopting Hexagonal Architecture, you ensure that your application remains modular, testable, and adaptable to changing requirements. This approach promotes separation of concerns and enables easier maintenance and scalability of your API codebase.</p><p>Now, armed with these tools and techniques, you’re ready to embark on your journey of building powerful and reliable RESTful APIs. Happy coding!</p><p>full project in my <a href="https://github.com/chrisBokotaII">GitHub</a></p><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=946d372860ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RESTful API with TypeScript, Fastify, TypeORM, and PostgreSQL]]></title>
            <link>https://medium.com/@christianinyekaka/building-a-restful-api-with-typescript-fastify-typeorm-and-postgresql-dd6309c0d05a?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd6309c0d05a</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[fastify]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 14:15:06 GMT</pubDate>
            <atom:updated>2024-03-20T13:47:50.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g4sxi0a1OFn3Q22Q8ZJoPg.png" /></figure><p>In this tutorial, we’ll walk through the process of building a RESTful API using Fastify, a high-performance web framework for Node.js, along with TypeORM, an ORM for TypeScript and JavaScript, and PostgreSQL, a powerful open-source relational database management system.</p><h3>Prerequisites</h3><p>Before we begin, ensure you have the following :</p><ul><li>Node.js and npm (or yarn) are installed on your machine.</li><li>PostgreSQL installed and running.</li><li>Basic knowledge of TypeScript.</li></ul><h3>Setting up the Project</h3><p>Let’s start by setting up a new Node.js project and installing the necessary dependencies:</p><pre>mkdir fastify-typeorm-postgres-api<br>cd fastify-typeorm-postgres-api<br>npm init -y</pre><pre>npm i -D typescript @types/node<br>npm i typeorm-fastify-plugin @sinclair/typebox  @fastify/type-provider-typebox<br>concurrently dotenv fastify typeorm pg reflect-metadata</pre><ol><li><strong>TypeScript:</strong> TypeScript is a superset of JavaScript that adds static types to the language. It allows you to write safer and more maintainable code by catching errors at compile-time rather than runtime.</li><li><strong>@types/node:</strong> This package provides TypeScript type definitions for Node.js. It enables TypeScript to understand the Node.js APIs and modules, allowing for better code completion and type checking.</li><li><strong>fastify:</strong> Fastify is a web framework for Node.js that focuses on performance and low overhead. It is highly extensible and allows developers to build scalable web applications with ease.</li><li><strong>dotenv: </strong>helps<strong> </strong>read all the environment variables.</li><li><strong>typeorm:</strong> TypeORM is an ORM (Object-Relational Mapping) library for TypeScript and JavaScript. It allows you to interact with databases using TypeScript classes and objects, abstracting away the underlying SQL queries.</li><li><strong>pg:</strong> This package is the PostgreSQL client for Node.js. It provides functionality to interact with PostgreSQL databases from Node.js applications.</li><li><strong>reflect-metadata:</strong> This package is required by TypeORM to enable the use of decorators for defining entities, columns, and other metadata.</li><li><strong>typeorm-fastify-plugin:</strong> A Fastify plugin that connects, organizes, and decorates all our database connections to your Fastify server</li><li><strong>@sinclair/typebox:</strong> TypeBox is a type builder library that creates in-memory JSON Schema objects that can be statically inferred as TypeScript types</li><li><strong>@fastify/type-provider-typebox:</strong> This package provides integration between Fastify and TypeBox. It allows you to use TypeBox schemas for request and response validation in Fastify routes.</li><li><strong>concurrently</strong>: Concurrently is a utility for running multiple commands concurrently. It is often used in development environments to run multiple processes, such as a server and a build tool, simultaneously.</li></ol><h3>Creating the Database</h3><p>Next, let’s create a PostgreSQL database for our API. You can use any PostgreSQL client or command-line interface to create a new database. For example, using psql:</p><pre>psql -h &lt;your host name&gt; -U &lt;your useranme&gt;<br>//psql -h localhost -U postgres//<br>//after click enter it will ask for a password put even if it will not show//<br>// what you are typing //<br>CREATE DATABASE fastify_api;</pre><h4><strong>Folder Structure</strong></h4><pre>fastify-typeorm-postgres-api<br> ┣ src<br> ┃ ┣ database<br> ┃ ┃ ┣ entity<br> ┃ ┃ ┃ ┗ Movies.entity.ts<br> ┃ ┃ ┗ migrations<br> ┃ ┣ lib<br> ┃ ┃ ┣ interfaces.ts<br> ┃ ┃ ┗ types.ts<br> ┃ ┣ routes<br> ┃ ┃ ┗ movies.routes.ts<br> ┃ ┣ db.config.ts<br> ┃ ┗ index.ts<br> ┣ .env<br> ┣ package-lock.json<br> ┣ package.json<br> ┗ tsconfig.json</pre><h3>package.json</h3><p>Update package.json file with the following dependencies</p><pre>{<br>  &quot;name&quot;: &quot;fastify-typeorm-postgres-api&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;type&quot;: &quot;commonjs&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;watch&quot;: &quot;tsc -w&quot;,<br>    &quot;dev&quot;: &quot;nodemon build/index.js&quot;,<br>    &quot;start:dev&quot;: &quot;concurrently \&quot;tsc -w\&quot; \&quot;nodemon build/index.js\&quot;&quot;,<br>    &quot;build&quot;: &quot;tsc&quot;,<br>    &quot;start&quot;: &quot;ts-node src/index.ts&quot;,<br>    &quot;typeorm&quot;: &quot;typeorm-ts-node-commonjs&quot;,<br>    &quot;migration&quot;: &quot; npm run typeorm migration:run -- -d ./src/data-source.ts&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@fastify/type-provider-typebox&quot;: &quot;^4.0.0&quot;,<br>    &quot;@sinclair/typebox&quot;: &quot;^0.32.15&quot;,<br>    &quot;fastify&quot;: &quot;^4.26.2&quot;,<br>    &quot;pg&quot;: &quot;^8.11.3&quot;,<br>    &quot;reflect-metadata&quot;: &quot;^0.2.1&quot;,<br>    &quot;typeorm&quot;: &quot;^0.3.20&quot;,<br>    &quot;typeorm-fastify-plugin&quot;: &quot;^1.0.5&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@types/node&quot;: &quot;^20.11.25&quot;,<br>    &quot;typescript&quot;: &quot;^5.4.2&quot;<br>  }<br>}</pre><p>This file includes all the essential dependencies, scripts for development, and instructions for running our app. I have implemented concurrently to execute both “tsc -w” and “nodemon build/index.js”. To start the application, I will run “npm run start:dev”. It will compile the TypeScript file to JavaScript and then execute nodemon.</p><h3>Creating Entities</h3><p>Entities in TypeORM represent database tables. Let’s create an entity for our movies.</p><p><strong>src/database/entity/movie.entity.ts</strong></p><pre>import {<br>  Column,<br>  CreateDateColumn,<br>  Entity,<br>  PrimaryGeneratedColumn,<br>  UpdateDateColumn,<br>} from &quot;typeorm&quot;;<br><br>@Entity({ name: &quot;movies&quot; })<br>export class Movie {<br>  @PrimaryGeneratedColumn(&quot;uuid&quot;)<br>  id!: string;<br><br>  @Column({ type: &quot;varchar&quot;, length: 255 })<br>  title!: string;<br><br>  @Column({ type: &quot;varchar&quot;, length: 500})<br>  description!: string;<br><br>  @Column({ type: &quot;varchar&quot;, length: 255 })<br>  year!: string;<br><br>  @Column({ type: &quot;varchar&quot;, length: 255 })<br>  duration!: string;<br>  @CreateDateColumn()<br>  created_at!: Date;<br><br>  @UpdateDateColumn()<br>  updated_at!: Date;<br>}</pre><h3>Configuring TypeORM</h3><p>TypeORM allows us to interact with the database using TypeScript classes. Let’s set up our TypeORM configuration.</p><p><strong>src/db.config.ts</strong></p><pre>import plugin from &quot;typeorm-fastify-plugin&quot;;<br>import { Movie } from &quot;./database/entity/Movies.entity&quot;;<br>import { FastifyInstance } from &quot;fastify&quot;;<br><br>export function configureDatabase(server: FastifyInstance) {<br>  server.register(plugin, {<br>    namespace: &quot;typeorm&quot;,<br>    type: &quot;postgres&quot;,<br>    host: process.env.DB_HOST,<br>    port: parseInt(process.env.DB_PORT || &quot;5432&quot;),<br>    username: process.env.DB_USERNAME,<br>    password: process.env.DB_PASSWORD,<br>    database: process.env.DB_DATABASE,<br>    synchronize: process.env.NODE_ENV === &quot;dev&quot; ? true : false,<br>    logging: process.env.NODE_ENV === &quot;dev&quot; ? true : false,<br>    migrations: [__dirname + &quot;/migration/*.ts&quot;],<br>    subscribers: [],<br>    migrationsRun: process.env.NODE_ENV === &quot;dev&quot; ? false : false,<br>    entities: [Movie],<br>  });<br>}</pre><p>This file is crucial in setting up the database connection within our Fastify application. It abstracts away the complexity of database configuration, allowing us to focus on building API endpoints and handling business logic. By configuring the database connection in a separate file, the codebase becomes more modular and maintainable, adhering to best practices of separation of concerns.</p><h3>Defining Routes</h3><p>Now, let’s define routes for our API using Fastify.</p><pre>import { FastifyInstance } from &quot;fastify&quot;;<br>import { MovieType } from &quot;../lib/types&quot;;<br>import { Movie } from &quot;../database/entity/Movies.entity&quot;;<br>import { IQuerystring, IReply, IdeleteReply } from &quot;../lib/interfaces&quot;;<br><br>export function configureRoutes(server: FastifyInstance) {<br>  server.get&lt;{ Reply: IReply }&gt;(&quot;/&quot;, async (request, reply) =&gt; {<br>    const movieRepository = server.orm[&quot;typeorm&quot;].getRepository(Movie);<br>    const movies = await movieRepository.find();<br>    reply.code(200).send({ success: true, data: { movies } });<br>  });<br>  server.post&lt;{ Body: MovieType; Reply: IReply }&gt;(<br>    &quot;/api/movies&quot;,<br>    {<br>      preValidation: (request, reply, done) =&gt; {<br>        const { title, description, year, duration } = request.body;<br>        done(<br>          title.length &lt; 2<br>            ? new Error(&quot;title must be more than 2 characters&quot;)<br>            : undefined<br>        );<br>      },<br>    },<br><br>    async (request, reply) =&gt; {<br>      // The `name` and `mail` types are automatically inferred<br>      const { title, description, year, duration } = request.body;<br>      try {<br>        const movie = new Movie();<br>        movie.title = title;<br>        movie.description = description;<br>        movie.year = year;<br>        movie.duration = duration;<br>        const movieRepository = server.orm[&quot;typeorm&quot;].getRepository(Movie);<br>        const result = await movieRepository.save(movie);<br>        reply.status(201).send({<br>          success: true,<br>          data: {<br>            movies: [result],<br>          },<br>        });<br>      } catch (error) {<br>        reply.code(400).send({ error: error as string });<br>      }<br>    }<br>  );<br>  server.get&lt;{ Querystring: IQuerystring; Reply: IReply }&gt;(<br>    &quot;/api/movies&quot;,<br>    {<br>      preValidation: (request, reply, done) =&gt; {<br>        const { id } = request.query;<br>        done(<br>          id === &quot;&quot; || undefined<br>            ? new Error(&quot;please provide The id&quot;)<br>            : undefined<br>        );<br>      },<br>    },<br>    async (request, reply) =&gt; {<br>      try {<br>        const { id } = request.query;<br>        const movieRepository = server.orm[&quot;typeorm&quot;].getRepository(Movie);<br>        const movie = await movieRepository.findOne({ where: { id } });<br>        if (!movie) {<br>          reply.code(404).send({ error: &quot;Movie not found&quot; });<br>        } else {<br>          reply.code(200).send({<br>            success: true,<br>            data: {<br>              movies: [movie],<br>            },<br>          });<br>        }<br>      } catch (error) {<br>        reply.code(400).send({ error: error as string });<br>      }<br>    }<br>  );<br>  server.delete&lt;{ Querystring: IQuerystring; Reply: IdeleteReply }&gt;(<br>    &quot;/api/movies&quot;,<br>    async (request, reply) =&gt; {<br>      const { id } = request.query;<br>      const movieRepository = server.orm[&quot;typeorm&quot;].getRepository(Movie);<br>      const movie = await movieRepository.findOne({ where: { id } });<br>      if (!movie) {<br>        reply.code(404).send({ error: &quot;Movie not found&quot; });<br>      } else {<br>        await movieRepository.remove(movie);<br>        reply.code(200).send({ success: true });<br>      }<br>    }<br>  );<br>  server.put&lt;{ Querystring: IQuerystring; Body: MovieType; Reply: IReply }&gt;(<br>    &quot;/api/movies&quot;,<br>    async (request, reply) =&gt; {<br>      const { id } = request.query;<br>      const { title, description, year, duration } = request.body;<br>      const movieRepository = server.orm[&quot;typeorm&quot;].getRepository(Movie);<br>      const movie = await movieRepository.findOne({ where: { id } });<br>      if (!movie) {<br>        reply.code(404).send({ error: &quot;Movie not found&quot; });<br>      } else {<br>        movie.title = title;<br>        movie.description = description;<br>        movie.year = year;<br>        movie.duration = duration;<br>        await movieRepository.save(movie);<br>        reply.code(200).send({<br>          success: true,<br>          data: {<br>            movies: [movie],<br>          },<br>        });<br>      }<br>    }<br>  );<br>}</pre><p>you will notice we are using generics in our routes.</p><p>Let’s discuss Generics.</p><ul><li>Generics in TypeScript allow us to create reusable components that can work with a variety of data types.</li><li>They provide a way to define functions, classes, and interfaces with placeholders for types that are specified when the component is used.</li><li>This enables increased type safety and code flexibility by catching errors at compile-time rather than runtime</li></ul><p><strong>Usage in Route Handlers:</strong></p><ul><li>Generics are used in route handlers to define the shape of the request and response objects.</li><li>For instance, &lt;{ Reply: IReply }&gt; specifies that the route handler expects a response object with a property named Reply type IReply.</li><li>This ensures type-safe access to request and response properties within the route handler, improving code reliability.</li></ul><p><strong>Usage in Route Definitions:</strong></p><ul><li>Generics are also used in route definitions to specify request parameters, query parameters, and request body types.</li><li>For example, &lt;{ Body: MovieType; Reply: IReply }&gt; indicates that the route expects a request body of type MovieType and a response object of type IReply.</li><li>By enforcing specific types for route parameters and bodies, generics help prevent type-related bugs and improve code readability.</li></ul><p><strong>Benefits of Generics:</strong></p><ul><li>Generics add type safety and flexibility to code by allowing it to work with various data types.</li><li>They enable the creation of reusable components that can adapt to different data structures, enhancing code reusability and maintainability.</li><li>By providing compile-time type checking, generics help catch type-related errors early in the development process, reducing the likelihood of runtime failures.</li></ul><p>Generics play a crucial role in ensuring type safety and flexibility in TypeScript applications, particularly in the context of defining routes in Fastify. By leveraging generics effectively, developers can write more robust and maintainable code that is less prone to errors and easier to understand and extend.</p><p><strong>Types and Interfaces</strong></p><p><strong>src/lib/interfaces.ts</strong></p><pre>import { MovieType } from &quot;../lib/types&quot;;<br><br>interface IReply {<br>  201: {<br>    success: boolean;<br>    data: {<br>      movies: MovieType[];<br>    };<br>  };<br>  302: { url: string };<br>  &quot;4xx&quot;: { error: string };<br>  &quot;5xx&quot;: { error: string };<br>  200: {<br>    success: boolean;<br>    data: {<br>      movies: MovieType[];<br>    };<br>  };<br>}<br>interface IQuerystring {<br>  id: string;<br>}<br>interface IdeleteReply {<br>  200: {<br>    success: boolean;<br>  };<br>  404: {<br>    error: string;<br>  };<br>}<br>export { IReply, IQuerystring, IdeleteReply };<br></pre><p><strong>MovieType:</strong></p><ul><li>This type, which we import from “../lib/types”, represents the structure of our movie object within the application. It encapsulates properties such as title, description, year, and duration.</li></ul><p><strong>IReply:</strong></p><ul><li>The IReply interface outlines the structure of HTTP response objects that the API generates.</li><li>It categorizes responses based on HTTP status codes, including 201 (created), 302 (redirect), 4xx (client error), and 5xx (server error).</li></ul><p>Each status code is associated with a specific structure containing relevant properties. For instance, successful responses (200 and 201) include a boolean success flag and a data object containing an array of movies (of type MovieType).</p><p><strong>IQuerystring:</strong></p><ul><li>This interface defines the structure of query parameters that the API expects in incoming requests.</li><li>It specifically specifies a single property, idindicating that the API endpoints utilizing this interface expect an id parameter in the query string.</li></ul><p><strong>IdeleteReply:</strong></p><ul><li>The IdeleteReply interface focuses on defining response structures specifically for delete operations within the API.</li><li>It delineates response formats for HTTP status codes 200 (OK) and 404 (Not Found).</li><li>The 200 status code response includes a boolean success field denoting the success of the delete operation, while the 404 status code response encompasses an error string detailing the encountered error.</li></ul><p>Overall, these interfaces serve to maintain consistency, clarity, and type safety throughout our application. By defining standardized structures for request parameters and response payloads, they facilitate ease of maintenance, enhance code readability, and mitigate the likelihood of errors or inconsistencies within the codebase. Additionally, they contribute to improved documentation and developer understanding of the API’s expected behavior.</p><p><strong>src/lib/Type.ts</strong></p><pre>import { Static, Type } from &quot;@sinclair/typebox&quot;;<br><br>export const Movie = Type.Object({<br>  title: Type.String(),<br>  description: Type.String(),<br>  year: Type.String(),<br>  duration: Type.String(),<br>});<br><br>export type MovieType = Static&lt;typeof Movie&gt;;</pre><p>The Movie constant is created using the Type.Object function from the @sinclair/typebox library. Inside the Type.Object function, we specify the properties of the movie object using various Type functions provided by the library. Each property is defined using the Type.String() function, indicating that the property value should be of type string. The properties included are title, description, year, and duration, representing different attributes of a movie.The Movie type is exported from the file. Additionally, a MovieType type alias is created using the Static&lt;typeof Movie&gt; syntax. The Static utility is used to obtain the static (or literal) type of the Movie object definition.</p><h3>Configuring Fastify</h3><p>Let’s configure Fastify to use our routes and connect with TypeORM.</p><pre>import &quot;reflect-metadata&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>import Fastify from &quot;fastify&quot;;<br>import { TypeBoxTypeProvider } from &quot;@fastify/type-provider-typebox&quot;;<br>import { configureRoutes } from &quot;./routes/movies.routes&quot;;<br>import { configureDatabase } from &quot;./db.config&quot;;<br>dotenv.config();<br>async function startServer() {<br>  const server = Fastify().withTypeProvider&lt;TypeBoxTypeProvider&gt;();<br> <br>  configureDatabase(server);<br><br>  configureRoutes(server);<br>  const { PORT = &quot;19200&quot; } = process.env;<br>  await server.listen({ port: parseInt(PORT) });<br>}<br>startServer()<br>  .then(() =&gt; {<br>    console.log(`Server started successfully at ${process.env.PORT}`);<br>  })<br>  .catch((err) =&gt; {<br>    console.error(&quot;Error starting server:&quot;, err);<br>    process.exit(1);<br>  });</pre><h3>Testing:</h3><p>To ensure the functionality of your API, leverage various testing tools like Postman, cURL, or any HTTP client. By sending requests to your API endpoints, validate their intended behavior and their ability to handle different scenarios effectively.</p><p>While this tutorial lays a solid foundation for building a RESTful API, two crucial aspects merit further attention: error handling and security. Let’s explore methods to enhance your API’s robustness and safeguard against potential vulnerabilities.</p><h3><strong>Error Handling:</strong></h3><ol><li><strong>Graceful Responses:</strong> Provide informative error messages accompanied by appropriate HTTP status codes. This aids developers in understanding and troubleshooting encountered issues.</li><li><strong>Try-Catch Blocks:</strong> Implement try-catch blocks within route handlers to capture potential errors, preventing unexpected crashes and enabling controlled error responses.</li><li><strong>Custom Error Classes:</strong> Consider creating custom error classes for distinct error scenarios, improving code organization, and facilitating maintainable error handling.</li></ol><h3><strong>Security:</strong></h3><ol><li><strong>Authentication:</strong> Implement robust authentication mechanisms to restrict access to authorized users only. Techniques such as token-based authentication (JWT) or session-based authentication can be employed.</li><li><strong>Authorization:</strong> Define authorization rules to control user access to API resources based on their roles or permissions. This ensures users can only perform actions they are authorized to.</li><li><strong>Input Validation:</strong> Sanitize and validate all user input to mitigate common security threats like SQL injection or cross-site scripting (XSS).</li><li><strong>Environment Variables:</strong> Safeguard sensitive information like database credentials by storing them in environment variables, preventing exposure within your codebase.</li></ol><p>By integrating these best practices, you can construct a more resilient and secure API capable of gracefully handling unexpected situations and defending against potential security threats.</p><h3><strong>Conclusion:</strong></h3><p>Throughout this tutorial, we’ve embarked on a journey to construct a robust REST API using TypeScript, Fastify, TypeORM, and PostgreSQL. Along the way, we’ve explored fundamental concepts such as database interaction, routing, and generics usage.</p><p>Armed with this knowledge, you now possess the foundational skills to develop resilient web applications. However, this tutorial only scratches the surface of the vast realm of web development. We encourage you to delve deeper, explore advanced topics, and extend the capabilities of your API.</p><p>We’re delighted to have accompanied you on this educational journey. Whether you have questions, feedback, or simply wish to share your experiences, we’re here to assist.</p><p>In the dynamic landscape of web development, opportunities for learning and innovation abound. Keep coding, keep exploring, and continue crafting remarkable digital experiences. The web is your canvas, and you hold the paintbrush.</p><p>Thank you for embarking on this tutorial journey with us, and we wish you the utmost success in your future endeavors!</p><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd6309c0d05a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Secure On-Chain DAO: A Comprehensive Guide to Solidity Development]]></title>
            <link>https://coinsbench.com/how-to-build-a-secure-on-chain-dao-a-comprehensive-guide-to-solidity-development-bf1466bbe477?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf1466bbe477</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethreum]]></category>
            <category><![CDATA[dao]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 09:41:35 GMT</pubDate>
            <atom:updated>2024-01-21T09:41:35.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BW0fXaPPweV6Qvev0PZIwQ.jpeg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fdepositphotos.com%2Fphotos%2Fdecentralized-autonomous-organization.html&amp;psig=AOvVaw1vniQ4xCwYMILSC9unccZD&amp;ust=1705491236409000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBMQjRxqFwoTCOD86Zbo4YMDFQAAAAAdAAAAABAD">DAO</a></figcaption></figure><h4>Introduction</h4><p>Decentralized Autonomous Organizations (DAOs) have gained significant traction in the blockchain space as a way to govern and manage decentralized projects. In this article, we will guide you through the process of creating a basic DAO using Solidity, with a focus on implementing a multi-signature (multi-sig) mechanism for secure and distributed decision-making.</p><h4>Prerequisites:</h4><p>Before delving into the implementation, ensure you have the necessary tools and knowledge:</p><ul><li>Solidity: A programming language for creating smart contracts on the Ethereum blockchain.</li><li>Ethereum Development Environment: Set up tools such as Remix or Truffle for smart contract development.</li><li>Understanding of Ethereum and Blockchain Concepts.</li></ul><h3>Project Setup:</h3><ol><li>Create a Project Directory:</li></ol><pre>cd desktop;<br>mkdir DAO &amp;&amp; cd DAO</pre><p>2. Initialize the Project and Install Hardhat:</p><pre>npm init -y<br>npm install --save-dev hardhat</pre><p>3. Initialize Hardhat:</p><pre>npx hardhat init</pre><p>After running this command, follow the prompts to initialize Hardhat in your project. Choose your preferred language (e.g., JavaScript).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*t7Epoi-6_EvlAP9Vru8KlA.jpeg" /><figcaption>hardhat</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*D4CHTKVMyCRCWE2Rvo6jJg.jpeg" /><figcaption>second screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*s3D-JNTJCOM2PYMeSpuXrQ.jpeg" /><figcaption>final</figcaption></figure><p>Once completed, your project structure will be set up with the necessary dependencies.</p><h3>Project Structure:</h3><p>Your project directory will now look something like this:</p><pre>art<br> ┣ contracts<br> ┃ ┗ Lock.sol<br> ┣ node-modules<br> ┣ scripts<br> ┃ ┗ deploy.js<br> ┣ test<br> ┃ ┗ Lock.js<br> ┣ .gitignore<br> ┣ hardhat.config.js<br> ┣ package-lock.json<br> ┣ package.json<br> ┗ README.md</pre><h3>Customizing the DAO Project Structure and Contracts</h3><h4>Updated Project Structure:</h4><p>After customization, your DAO project directory will now have the following structure:</p><pre>DAO<br> ┣ contracts<br> ┃ ┣ governace<br> ┃ ┃ ┣ Govenor.sol<br> ┃ ┃ ┗ TimeLock.sol<br> ┃ ┣ Executor.sol<br> ┃ ┣ Vault.sol<br> ┃ ┗ Vtoken.sol<br> ┣ scripts<br> ┃ ┗ deploy.js<br> ┣ test<br> ┃ ┗ test.js<br> ┣ utils<br> ┃ ┣ moveBlocks.js<br> ┃ ┗ moveTime.js<br> ┣ .gitignore<br> ┣ hardhat.config.js<br> ┣ helper.js<br> ┣ package-lock.json<br> ┣ package.json<br> ┗ README.md</pre><h4>Contracts:</h4><p>The contracts in the contracts directory are the core components of our DAO. Let&#39;s dive into each</p><h4>Vtoken. sol</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol&quot;;<br><br>contract MyToken is ERC20, Ownable, ERC20Permit, ERC20Votes {<br>    constructor(address initialOwner)<br>        ERC20(&quot;Zeux&quot;, &quot;ZEX&quot;)<br>        Ownable(initialOwner)<br>        ERC20Permit(&quot;MyToken&quot;)<br>    {<br>        _mint(msg.sender, 18 * 10 ** decimals());<br>    }<br><br>    function mint(address to, uint256 amount) public onlyOwner {<br>        _mint(to, amount);<br>    }<br><br>    // The following functions are overrides required by Solidity.<br><br>    function _update(address from, address to, uint256 value)<br>        internal<br>        override(ERC20, ERC20Votes)<br>    {<br>        super._update(from, to, value);<br>    }<br><br>    function nonces(address owner)<br>        public<br>        view<br>        override(ERC20Permit, Nonces)<br>        returns (uint256)<br>    {<br>        return super.nonces(owner);<br>    }<br>}</pre><p>An ERC-20 token contract utilizing OpenZeppelin, providing gasless transaction permits and governance votes.</p><h4>Contract Overview:</h4><p><strong>Token Name and Symbol:</strong></p><ul><li>The token is named “Zeux” with the symbol “ZEX.”</li></ul><p><strong>Inheritance:</strong></p><ul><li>The contract inherits from:</li><li>ERC20: The standard ERC-20 token implementation.</li><li>Ownable: Ensures ownership and provides onlyOwner modifier.</li><li>ERC20Permit: Adds support for gasless transactions through permit.</li><li>ERC20Votes: Extends ERC-20 with voting capabilities for governance.</li></ul><p><strong>Constructor:</strong></p><ul><li>The constructor initializes the token with the specified name, symbol, and an initial supply of 18 * 10¹⁸ tokens minted to the contract deployer.</li></ul><p><strong>Mint Function:</strong></p><ul><li>The mint function allows the owner to mint additional tokens and assign them to a specific address.</li></ul><p><strong>Overrides:</strong></p><ul><li>The contract includes several overrides required by Solidity for proper functioning:</li><li>_update: Overrides from both ERC20 and ERC20Votes to handle internal token updates.</li><li>nonces: Overrides from ERC20Permit and Nonces to track permit nonces for gasless transactions.</li></ul><h4>Vault.sol</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br><br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br><br>contract Vault is  Ownable{<br>    uint public balance = 10000000000000000000000000000;<br>    address public  author;<br><br>    mapping (address =&gt; uint) balances;<br>    constructor( address _author) Ownable(_author){<br>        author = _author;<br>        balances[author] = balance;<br>    }<br><br>    function tranfer(address payable to, uint amount) public onlyOwner{<br>        balances[to] += amount;<br>        balances[msg.sender] -= amount;<br>    }<br>    <br>function empty() public onlyOwner {<br>balances[msg.sender] = 0; // transfer all the balance to owner<br>   <br>}<br>function getbalance() public view returns(uint){<br>    return balances[msg.sender];<br><br>}<br><br>}</pre><p>Vault.sol contract is designed to serve as a secure asset management system, allowing the owner to transfer funds and check balances.</p><h4>Explanation:</h4><p><strong>Initial Balance:</strong></p><ul><li>The contract was initialized with a fixed balance of 10,000 ETH (10000000000000000000000000000).</li></ul><p><strong>Owner Assignment:</strong></p><ul><li>The address specified during contract deployment (_author) is set as the owner of the vault.</li></ul><p><strong>Transfer Function:</strong></p><ul><li>transfer: Allows the owner to transfer a specified amount of funds from the vault to another address (to). The function ensures that only the owner can initiate transfers.</li></ul><p><strong>Empty Function:</strong></p><ul><li>empty: Allows the owner to transfer the entire balance of the vault to themselves.</li></ul><p><strong>Get Balance Function:</strong></p><ul><li>getBalance: Returns the balance of the calling address.</li></ul><h3>Executor. sol: Multi-Signature Contract for Proposal Execution</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>import &quot;@openzeppelin/contracts/governance/IGovernor.sol&quot;;<br><br>contract Executor  {<br>    IGovernor public governor;<br>    address[] public executors;<br>    uint256 public transactionCount;<br>    uint256 public requiredsignatures;<br><br>    struct Transaction {<br>        address[]targets;<br>        uint256[]values;<br>        bytes[] calldata;<br>        bytes32 descriptionHash;<br>        bool executed;<br><br>    }<br>    mapping (uint =&gt; Transaction) public transactions;<br>    mapping (uint =&gt; mapping (address =&gt; bool)) public confirmations;<br>   event TransactionExecuted(uint transactionId);<br>   event TransactionSubmitted(uint transactionId);<br>    receive() external payable {}<br>    <br>    function executeTransaction(uint transactionId) public {<br>        require(isConfirmed(transactionId));<br>        Transaction storage _tx = transactions[transactionId];<br>        (uint256 proposalId) = governor.execute(_tx.targets, _tx.values, _tx.calldata, _tx.descriptionHash);<br>        require(proposalId &gt; 0,&quot;Execution failed&quot;);<br>        _tx.executed = true;<br>        emit TransactionExecuted(transactionId);<br>    }<br><br>    function isConfirmed(uint transactionId) public view returns(bool) {<br>        return getConfirmationsCount(transactionId) &gt;= requiredsignatures;<br>    }<br><br>    function getConfirmationsCount(uint transactionId) public view returns(uint) {<br>        uint count;<br>        for(uint i = 0; i &lt; executors.length; i++) {<br>            if(confirmations[transactionId][executors[i]]) {<br>                count++;<br>            }<br>        }<br>        return count;<br>    }<br><br>    function isOwner(address addr) private view returns(bool) {<br>        for(uint i = 0; i &lt; executors.length; i++) {<br>            if(executors[i] == addr) {<br>                return true;<br>            }<br>        }<br>        return false;<br>    }<br><br>    function submitTransaction(<br>         address[] memory targets,<br>        uint256[] memory values,<br>        bytes[] memory calldatas,<br>        bytes32 descriptionHash) external  returns(uint256) {<br>        uint id = addTransaction(targets, values, calldatas, descriptionHash);<br>        emit TransactionSubmitted(id);<br>        return id;<br><br>    }<br><br>    function confirmTransaction(uint transactionId) public {<br>        require(isOwner(msg.sender));<br>        confirmations[transactionId][msg.sender] = true;<br>    }<br><br>    function addTransaction( <br>        address[] memory targets,<br>        uint256[] memory values,<br>        bytes[] memory calldatas,<br>        bytes32 descriptionHash) private returns(uint) {<br>        transactions[transactionCount] = Transaction(targets, values, calldatas, descriptionHash, false);<br>        transactionCount += 1;<br>        return transactionCount - 1;<br>    }<br><br>   constructor(address[] memory _executors, uint _requiredsignatures, address _governorAddress) {<br>    require(_executors.length &gt; 0, &quot;At least one executor required&quot;);<br>    require(_requiredsignatures &gt; 0, &quot;Required signatures must be greater than zero&quot;);<br>    require(_requiredsignatures &lt;= _executors.length, &quot;Required signatures cannot exceed the number of executors&quot;);<br>    executors = _executors;<br>    requiredsignatures = _requiredsignatures;<br>    governor = IGovernor(_governorAddress);<br>}<br><br>}<br><br>    <br><br>    <br><br></pre><p>The Executor.sol contract is designed as a multi-signature contract to facilitate the execution of proposals within the DAO. It requires a specified number of executors to confirm and execute a transaction. Here&#39;s an overview of its functionality <a href="https://medium.com/coinsbench/building-a-multi-signature-wallet-contract-in-solidity-63641eaacd2b">learn more</a>:</p><h4>Contract Overview:</h4><p><strong>State Variables:</strong></p><ul><li>governor: Reference to the Governor contract responsible for proposal execution.</li><li>executors: Array of executor addresses.</li><li>transactionCount: Counter for tracking the number of transactions.</li><li>requiredSignatures: Number of required signatures to execute a transaction.</li></ul><p><strong>Struct:</strong></p><ul><li>Transaction: Struct representing a transaction with its targets, values, calldata, descriptionHash, and execution status.</li></ul><p><strong>Mappings:</strong></p><ul><li>transactions: Mapping to store transaction details based on their IDs.</li><li>confirmations: Mapping to track which executors have confirmed a specific transaction.</li></ul><p><strong>Events:</strong></p><ul><li>TransactionExecuted: Event emitted when a transaction is successfully executed.</li><li>TransactionSubmitted: Event emitted when a new transaction is submitted.</li></ul><p><strong>Functions:</strong></p><ul><li>executeTransaction: Execute a transaction if it has enough confirmations.</li><li>isConfirmed: Check if a transaction has enough confirmations to be executed.</li><li>getConfirmationsCount: Get the number of confirmations for a transaction.</li><li>isOwner: Check if an address is one of the executors.</li><li>submitTransaction: Submit a new transaction for confirmation.</li><li>confirmTransaction: Confirm a transaction as an executor.</li><li>addTransaction: Add a new transaction to the list.</li></ul><p><strong>Constructor:</strong></p><ul><li>Initializes the contract with executor addresses, the required number of signatures, and the address of the Governor&#39;s contract.</li></ul><h4>governace\TimeLock.sol</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>import &quot;@openzeppelin/contracts/governance/TimelockController.sol&quot;;<br>contract MyTimelock is  TimelockController {<br>    constructor(<br>        uint256 minDelay,<br>        address[] memory proposers,<br>        address[] memory executors,<br>        address admin<br><br>    ) TimelockController(minDelay, proposers, executors, admin) {<br>       <br>    }<br>}</pre><h3>Contract Overview</h3><p>The TimeLock contract inherits from TimelockController in the OpenZeppelin library, which provides functionality for time-controlled execution of administrative transactions.</p><h4>Key Components:</h4><p><strong>Minimum Delay:</strong></p><ul><li>The minDelay parameter in the constructor sets the minimum delay required before a scheduled transaction becomes executable. This delay ensures that proposed changes have a waiting period, allowing the community to review and potentially veto decisions.</li></ul><p><strong>Proposers and Executors:</strong></p><ul><li>The contract specifies arrays of addresses (proposers and executors) that have the authority to propose and execute transactions, respectively.</li></ul><p><strong>Admin:</strong></p><ul><li>The admin address is set during contract deployment and has the authority to cancel scheduled transactions.</li></ul><p><strong>Inherits:</strong></p><ul><li>Inherits from TimelockController.</li></ul><p><strong>Constructor:</strong></p><ul><li>Initializes the TimelockController with minimum delay, proposers, executors, and admin.</li></ul><h4>governace\Govenor.sol</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>import &quot;@openzeppelin/contracts/governance/Governor.sol&quot;;<br>import &quot;@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol&quot;;<br>import &quot;@openzeppelin/contracts/governance/extensions/GovernorSettings.sol&quot;;<br>import &quot;@openzeppelin/contracts/governance/extensions/GovernorVotes.sol&quot;;<br>import &quot;@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol&quot;;<br>import &quot;@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol&quot;;<br>import &quot;@openzeppelin/contracts/governance/TimelockController.sol&quot;;<br>import &quot;@openzeppelin/contracts/governance/utils/IVotes.sol&quot;;<br><br>contract Governors is Governor, GovernorSettings, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl {<br>    constructor(IVotes _token, TimelockController _timelock,uint48 _votingDelay,uint32 _votingPeriod,uint256 _quorum)<br>        Governor(&quot;Governor&quot;)<br>        GovernorSettings(_votingDelay /* 1 day */, _votingPeriod /* 1 week */, 0)<br>        GovernorVotes(_token)<br>        GovernorVotesQuorumFraction(_quorum)<br>        GovernorTimelockControl(_timelock)<br>    {}<br><br>    // The following functions are overrides required by Solidity.<br><br>    function votingDelay()<br>        public<br>        view<br>        override(Governor, GovernorSettings)<br>        returns (uint256)<br>    {<br>        return super.votingDelay();<br>    }<br><br>    function votingPeriod()<br>        public<br>        view<br>        override(Governor, GovernorSettings)<br>        returns (uint256)<br>    {<br>        return super.votingPeriod();<br>    }<br><br>    function quorum(uint256 blockNumber)<br>        public<br>        view<br>        override(Governor, GovernorVotesQuorumFraction)<br>        returns (uint256)<br>    {<br>        return super.quorum(blockNumber);<br>    }<br><br>    function state(uint256 proposalId)<br>        public<br>        view<br>        override(Governor, GovernorTimelockControl)<br>        returns (ProposalState)<br>    {<br>        return super.state(proposalId);<br>    }<br><br>    function proposalNeedsQueuing(uint256 proposalId)<br>        public<br>        view<br>        override(Governor, GovernorTimelockControl)<br>        returns (bool)<br>    {<br>        return super.proposalNeedsQueuing(proposalId);<br>    }<br><br>    function proposalThreshold()<br>        public<br>        view<br>        override(Governor, GovernorSettings)<br>        returns (uint256)<br>    {<br>        return super.proposalThreshold();<br>    }<br><br>    function _queueOperations(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)<br>        internal<br>        override(Governor, GovernorTimelockControl)<br>        returns (uint48)<br>    {<br>        return super._queueOperations(proposalId, targets, values, calldatas, descriptionHash);<br>    }<br><br>    function _executeOperations(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)<br>        internal<br>        override(Governor, GovernorTimelockControl)<br>    {<br>        super._executeOperations(proposalId, targets, values, calldatas, descriptionHash);<br>    }<br><br>    function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)<br>        internal<br>        override(Governor, GovernorTimelockControl)<br>        returns (uint256)<br>    {<br>        return super._cancel(targets, values, calldatas, descriptionHash);<br>    }<br><br>    function _executor()<br>        internal<br>        view<br>        override(Governor, GovernorTimelockControl)<br>        returns (address)<br>    {<br>        return super._executor();<br>    }<br>}</pre><p>The contract acts as a governance system that allows token holders to propose and vote on the proposed proposal. It extends several components from the OpenZeppelin library to enhance its functionality.</p><p><strong>Key Extensions Used:</strong></p><ul><li>Governor: The main governance contract.</li><li>GovernorSettings: Extends the basic governance with settings such as voting delay, voting period, and proposal threshold.</li><li>GovernorCountingSimple: A simple vote counting strategy.</li><li>GovernorVotes: Extends governance with token voting capabilities.</li><li>GovernorVotesQuorumFraction: Adds a fractional quorum requirement based on votes.</li><li>GovernorTimelockControl: Integrates with a timelock controller for time-delayed execution of proposals.</li></ul><h4>Constructor:</h4><ul><li>The constructor initializes the governance system with parameters including the token contract (_token), timelock controller (_timelock), voting delay, voting period, and quorum.</li></ul><h4>Function Overrides:</h4><ul><li>The contract includes several function overrides, aligning with the different extensions used. These overrides are required by Solidity for proper integration of the extensions.</li></ul><p><strong>Functionality Highlights:</strong></p><ul><li>Vote Counting: Implements a simple vote-counting mechanism.</li><li>Token Voting: Allows token holders to vote on proposals.</li><li>Quorum Requirement: Implements a fractional quorum requirement based on the total votes.</li><li>Timelock Integration: Integrates with a timelock controller, enabling time-delayed execution of proposals.</li><li>Queue and Execute Operations: Internal functions for queuing and executing operations, considering the timelock.</li></ul><h3>Importance:</h3><p><strong>Secure Governance:</strong></p><ul><li>The contract provides a secure and flexible governance framework for decentralized decision-making within a DAO.</li></ul><p><strong>Token Voting:</strong></p><ul><li>Token holders can participate in the governance process by voting on proposals, aligning with the principles of decentralized decision-making.</li></ul><p><strong>Configurable Settings:</strong></p><ul><li>Governance settings such as voting delay, voting period, and quorum are configurable, allowing flexibility based on the specific requirements of the DAO.</li></ul><p><strong>Fractional Quorum:</strong></p><ul><li>The fractional quorum requirement adds a layer of flexibility, ensuring that proposals need a certain percentage of total votes for approval.</li></ul><p><strong>Timelock Integration:</strong></p><ul><li>Integration with a timelock controller enhances security by introducing a time delay before the execution of proposals, providing a window for review and potential vetoes.</li></ul><h4>helper.js</h4><pre>// Governor Values<br>exports.QUORUM_PERCENTAGE = 4; // Need 4% of voters to pass<br>exports.MIN_DELAY = 3600; // 1 hour - after a vote passes, you have 1 hour before you can enact<br>// export const VOTING_PERIOD = 45818 // 1 week - how long the vote lasts. This is pretty long even for local tests<br>exports.VOTING_PERIOD = 5; // blocks<br>exports.VOTING_DELAY = 1; // 1 Block - How many blocks till a proposal vote becomes active</pre><p>The helper.js file contains various constants and values that are likely used across different parts of our DAO project for configuration and consistency.</p><h4>utils\moveBlocks.js</h4><pre>const { network } = require(&quot;hardhat&quot;);<br><br>exports.moveBlocks = async function moveBlocks(amount) {<br>  console.log(&quot;Moving blocks...&quot;);<br>  for (let index = 0; index &lt; amount; index++) {<br>    await network.provider.request({<br>      method: &quot;evm_mine&quot;,<br>      params: [],<br>    });<br>  }<br>  console.log(`Moved ${amount} blocks`);<br>};</pre><p><strong>Functionality</strong></p><ul><li>This script exports a function called moveBlocks that takes an amount parameter.</li><li>It uses the Hardhat network provider to manually mine a specified number of blocks.</li></ul><p><strong>Usage</strong></p><ul><li>This utility could be used to advance the blockchain state by a certain number of blocks, simulating the passage of time or triggering events dependent on block timestamps.</li></ul><h4>utils/moveTime.js</h4><pre>const { network } = require(&quot;hardhat&quot;);<br><br>exports.moveTime = async function moveTime(amount) {<br>  console.log(&quot;Moving blocks...&quot;);<br>  await network.provider.send(&quot;evm_increaseTime&quot;, [amount]);<br><br>  console.log(`Moved forward in time ${amount} seconds`);<br>};</pre><p><strong>Functionality</strong></p><ul><li>This script exports a function called moveTime that takes an amount parameter.</li><li>It uses the Hardhat network provider to increase the EVM (Ethereum Virtual Machine) time by a specified number of seconds.</li></ul><p><strong>Usage</strong></p><ul><li>This utility could be used to simulate the advancement of time in the blockchain, triggering time-dependent actions such as unlocking funds or expiring certain conditions.</li></ul><p><em>Note: Both scripts log messages to the console to indicate the progression of the simulation. These utility functions are commonly used during development and testing to efficiently manipulate the blockchain’s state in a controlled and predictable manner.</em></p><h4>hardhat.config.js</h4><p>The hardhat-config.js file is the configuration file for a Hardhat project. It defines the project-specific settings and configurations for compiling and running smart contracts.</p><pre>require(&quot;@nomicfoundation/hardhat-toolbox&quot;);<br><br>/** @type import(&#39;hardhat/config&#39;).HardhatUserConfig */<br>module.exports = {<br>  solidity: {<br>    version: &quot;0.8.20&quot;,<br>    settings: {<br>      optimizer: {<br>        enabled: true,<br>        runs: 200,<br>      },<br>    },<br>  },<br>  allowUnlimitedContractSize: true,<br>};</pre><p><strong>Solidity Compiler Configuration</strong></p><ul><li>version: &quot;0.8.20&quot;: Specifies the version of the Solidity compiler to be used. In this case, it&#39;s version 0.8.20.</li><li>settings: Additional settings for the Solidity compiler.</li><li>optimizer: Enables the Solidity optimizer and configures its settings.</li><li>enabled: true: Enables the optimizer.</li><li>runs: 200: Specifies the number of runs the optimizer should perform.</li><li>Allow Unlimited Contract Size:</li><li>allowUnlimitedContractSize: true: This setting allows contracts to have an unlimited size. Be cautious with this setting, as it might lead to increased gas costs and potential issues on the Ethereum network.</li></ul><h4>test\test.js</h4><pre>const {<br>  loadFixture,<br>} = require(&quot;@nomicfoundation/hardhat-toolbox/network-helpers&quot;);<br>const { anyValue } = require(&quot;@nomicfoundation/hardhat-chai-matchers/withArgs&quot;);<br>const { expect } = require(&quot;chai&quot;);<br><br>const { ethers } = require(&quot;hardhat&quot;);<br><br>const {<br>  MIN_DELAY,<br>  VOTING_DELAY,<br>  VOTING_PERIOD,<br>  QUORUM_PERCENTAGE,<br>} = require(&quot;../helper&quot;);<br>const { moveTime } = require(&quot;../utils/moveTime&quot;);<br>const { moveBlocks } = require(&quot;../utils/moveBlocks&quot;);<br><br>describe(&quot;Lock&quot;, function () {<br>  // We define a fixture to reuse the same setup in every test.<br>  // We use loadFixture to run this setup once, snapshot that state,<br>  // and reset Hardhat Network to that snapshot in every test.<br>  async function deployOneYearLockFixture() {<br>    // Contracts are deployed using the first signer/account by default<br>    const [<br>      owner,<br>      otherAccount,<br>      anotherAccount,<br>      thirdAccount,<br>      fourthAccount,<br>      fifthAccount,<br>      sixthAccount,<br>      seventhAccount,<br>      eigthAccount,<br>    ] = await ethers.getSigners();<br>    //Vtoken<br>    const VToken = await ethers.getContractFactory(&quot;MyToken&quot;);<br>    const vtoken = await VToken.connect(owner).deploy(owner.address);<br>    vtoken.waitForDeployment();<br><br>    //Time-Lock<br>    const TimeLock = await ethers.getContractFactory(&quot;MyTimelock&quot;);<br>    const timelock = await TimeLock.deploy(MIN_DELAY, [], [], owner.address);<br>    timelock.waitForDeployment();<br>    //Vault<br>    const Vault = await ethers.getContractFactory(&quot;Vault&quot;);<br>    const vault = await Vault.deploy(timelock.target);<br>    vault.waitForDeployment();<br>    //Governor<br>    const Governor = await ethers.getContractFactory(&quot;Governors&quot;);<br>    const governor = await Governor.deploy(<br>      vtoken.target,<br>      timelock.target,<br>      VOTING_DELAY,<br>      VOTING_PERIOD,<br>      QUORUM_PERCENTAGE<br>    );<br>    governor.waitForDeployment();<br>    //executor<br>    const Executor = await ethers.getContractFactory(&quot;Executor&quot;);<br>    const executor = await Executor.deploy(<br>      [eigthAccount, seventhAccount, sixthAccount],<br>      2,<br>      governor.target<br>    );<br>    executor.waitForDeployment();<br><br>    return {<br>      owner,<br>      vault,<br>      timelock,<br>      governor,<br>      executor,<br>      vtoken,<br>      otherAccount,<br>      anotherAccount,<br>      thirdAccount,<br>      fourthAccount,<br>      fifthAccount,<br>      sixthAccount,<br>      seventhAccount,<br>      eigthAccount,<br>    };<br>  }<br><br>  describe(&quot;Deployment&quot;, async function () {<br>    it(&quot;Should set the right unlockTime&quot;, async function () {<br>      const { vault } = await loadFixture(deployOneYearLockFixture);<br><br>      expect(await vault.target).to.be.properAddress;<br>    });<br><br>    it(&quot;Should set the right owner&quot;, async function () {<br>      const { vault, timelock } = await loadFixture(deployOneYearLockFixture);<br><br>      expect(await vault.owner()).to.equal(timelock.target);<br>    });<br><br>    it(&quot;should deploy the Time Lock&quot;, async function () {<br>      const { timelock } = await loadFixture(deployOneYearLockFixture);<br>      expect(await timelock.target).to.be.properAddress;<br>    });<br>    it(&quot;should deploy the Governor&quot;, async function () {<br>      const { governor } = await loadFixture(deployOneYearLockFixture);<br>      expect(await governor.target).to.be.properAddress;<br>    });<br>    it(&quot;should deploy the Executor&quot;, async function () {<br>      const { executor } = await loadFixture(deployOneYearLockFixture);<br>      expect(await executor.target).to.be.properAddress;<br>    });<br>    it(&quot;should deploy the VToken&quot;, async function () {<br>      const { vtoken } = await loadFixture(deployOneYearLockFixture);<br>      expect(await vtoken.target).to.be.properAddress;<br>    });<br>  });<br>  describe(&quot;setup &amp; propose &amp; vote &amp; queu &amp; multi-sig &amp; execute&quot;, async function () {<br>    it(&quot;should delegate vote token&quot;, async function () {<br>      const {<br>        owner,<br>        vault,<br>        timelock,<br>        governor,<br>        executor,<br>        vtoken,<br>        otherAccount,<br>        anotherAccount,<br>        thirdAccount,<br>        fourthAccount,<br>        fifthAccount,<br>        sixthAccount,<br>        seventhAccount,<br>        eigthAccount,<br>      } = await loadFixture(deployOneYearLockFixture);<br>      const ONE_GWEI = 1_000_000_000 * 5;<br>      //delagate<br>      await vtoken.connect(owner).delegate(eigthAccount.address);<br>      await vtoken.connect(owner).delegate(sixthAccount.address);<br>      await vtoken.connect(owner).delegate(seventhAccount.address);<br><br>      console.log(await vtoken.numCheckpoints(sixthAccount.address));<br><br>      // setup timelock<br><br>      const proposerRole = ethers.id(&quot;PROPOSER_ROLE&quot;);<br>      const executorRole = ethers.id(&quot;EXECUTOR_ROLE&quot;);<br>      const adminRole = ethers.id(&quot;DEFAULT_ADMIN_ROLE&quot;);<br><br>      const grantRole = await timelock<br>        .connect(owner)<br>        .grantRole(proposerRole, governor.target);<br><br>      grantRole.wait(1);<br>      const grantRole2 = await timelock<br>        .connect(owner)<br>        .grantRole(executorRole, governor.target);<br>      grantRole2.wait(1);<br><br>      const revoke = await timelock<br>        .connect(owner)<br>        .revokeRole(adminRole, owner.address);<br>      revoke.wait(1);<br>      console.log(await timelock.hasRole(executorRole, owner.address));<br><br>      // propose<br><br>      const target = vault.target;<br>      const value = 0;<br>      const callData = vault.interface.encodeFunctionData(&quot;tranfer&quot;, [<br>        eigthAccount.address,<br>        1000,<br>      ]);<br>      const description = &quot;Transfer 1000 token to eigthAccount&quot;;<br>      const propose = await governor.propose(<br>        [target],<br>        [value],<br>        [callData],<br>        description<br>      );<br>      propose.wait(1);<br><br>      const events = await governor.queryFilter(<br>        &quot;ProposalCreated&quot;,<br>        propose.blockNumber,<br>        propose.blockNumber<br>      );<br>      const proposalId = events[0].args[0];<br>      console.log(`Proposed with proposal ID:\n  ${proposalId}`);<br><br>      const proposalState1 = await governor.state(proposalId);<br>      const proposalSnapShot1 = await governor.proposalSnapshot(proposalId);<br>      const proposalDeadline1 = await governor.proposalDeadline(proposalId);<br><br>      // the Proposal State is an enum data type, defined in the IGovernor contract.<br>      // 0:Pending, 1:Active, 2:Canceled, 3:Defeated, 4:Succeeded, 5:Queued, 6:Expired, 7:Executed<br>      console.log(`Current Proposal State: ${proposalState1}`);<br>      // What block # the proposal was snapshot<br>      console.log(`Current Proposal Snapshot: ${proposalSnapShot1}`);<br>      // The block number the proposal voting expires<br>      console.log(`Current Proposal Deadline: ${proposalDeadline1}`);<br><br>      // vote <br>      await moveBlocks(VOTING_DELAY + 2);<br><br>      const proposalState2 = await governor.state(proposalId);<br>      const proposalSnapShot2 = await governor.proposalSnapshot(proposalId);<br>      const proposalDeadline2 = await governor.proposalDeadline(proposalId);<br>      // the Proposal State is an enum data type, defined in the IGovernor contract.<br>      // 0:Pending, 1:Active, 2:Canceled, 3:Defeated, 4:Succeeded, 5:Queued, 6:Expired, 7:Executed<br>      console.log(`Current Proposal State: ${proposalState2}`);<br>      // What block # the proposal was snapshot<br>      console.log(`Current Proposal Snapshot: ${proposalSnapShot2}`);<br>      // The block number the proposal voting expires<br>      console.log(`Current Proposal Deadline: ${proposalDeadline2}`);<br>      //vote with reason<br><br>      const vote = await governor.connect(eigthAccount).castVote(proposalId, 1);<br>      vote.wait();<br><br>      const vote2 = await governor<br>        .connect(sixthAccount)<br>        .castVote(proposalId, 1);<br>      vote2.wait();<br><br>      const vote3 = await governor<br>        .connect(seventhAccount)<br>        .castVote(proposalId, 1);<br>      vote3.wait();<br><br>      // queue<br>      await moveBlocks(VOTING_PERIOD + 2);<br><br>      const proposalState3 = await governor.state(proposalId);<br>      const proposalSnapShot3 = await governor.proposalSnapshot(proposalId);<br>      const proposalDeadline3 = await governor.proposalDeadline(proposalId);<br>      // the Proposal State is an enum data type, defined in the IGovernor contract.<br>      // 0:Pending, 1:Active, 2:Canceled, 3:Defeated, 4:Succeeded, 5:Queued, 6:Expired, 7:Executed<br>      console.log(`Current Proposal State: ${proposalState3}`);<br>      // What block # the proposal was snapshot<br>      console.log(`Current Proposal Snapshot: ${proposalSnapShot3}`);<br>      // The block number the proposal voting expires<br>      console.log(`Current Proposal Deadline: ${proposalDeadline3}`);<br><br>      const descriptionHash = ethers.id(description);<br>      const queueTx = await governor.queue(<br>        [vault.target],<br>        [0],<br>        [callData],<br>        descriptionHash<br>      );<br>      queueTx.wait(1);<br><br>      const proposalState4 = await governor.state(proposalId);<br>      console.log(`Current Proposal State: ${proposalState4}`);<br>      <br><br>      // execute<br><br>      await moveTime(MIN_DELAY + 1);<br>      const proposalState5 = await governor.state(proposalId);<br>      console.log(`Current Proposal State: ${proposalState5}`);<br>      const proposeToex = await executor.submitTransaction(<br>        [vault.target],<br>        [0],<br>        [callData],<br>        descriptionHash<br>      );<br>      proposeToex.wait();<br><br>      const evento = await executor.queryFilter(<br>        &quot;TransactionSubmitted&quot;,<br>        proposeToex.blockNumber,<br>        proposeToex.blockNumber<br>      );<br>      const transationId = evento[0].args[0];<br><br>      // confirm a transaction\<br><br>      const confirmTx = await executor<br>        .connect(seventhAccount)<br>        .confirmTransaction(transationId);<br>      confirmTx.wait(1);<br><br>      const secondConfrim = await executor<br>        .connect(seventhAccount)<br>        .confirmTransaction(transationId);<br>      secondConfrim.wait(1);<br><br>      const thirdconfirm = await executor<br>        .connect(sixthAccount)<br>        .confirmTransaction(transationId);<br>      thirdconfirm.wait(1);<br>      console.log(await executor.getConfirmationsCount(transationId));<br><br>      // //execute<br>      const executeTx = await executor.executeTransaction(transationId);<br>      executeTx.wait(1);<br><br>      // console.log(executeTx);<br>      const balance = await vault.connect(eigthAccount).getbalance();<br><br>      console.log(balance);<br>      const proposalStatefinal = await governor.state(proposalId);<br>      console.log(`Current Proposal State: ${proposalStatefinal}`);<br><br>      expect(balance).to.equal(1000n);<br>    });<br>  });<br>});</pre><h4>Conclusion</h4><p>In conclusion, the outlined DAO structure serves as a solid foundation for decentralized governance, asset management, and the secure execution of proposals. Each contract within this framework plays a crucial and distinct role, contributing to a resilient and distributed decision-making process. The flexibility embedded in these contracts allows for easy customization, enabling users to tailor the DAO to their specific requirements.</p><p>Looking ahead, the potential impact of this DAO extends beyond its current form. The decentralized ecosystem fostered by these contracts opens doors to innovative and transformative possibilities in the blockchain space. As users explore and adapt this DAO structure to real-world scenarios, we hope that this foundation will contribute to the ongoing evolution of decentralized systems, empowering communities and facilitating transparent and efficient collaboration.</p><h3>Final Thoughts</h3><p>Building a DAO with a multi-signature executor is a significant step towards decentralized decision-making. The combination of token governance, secure fund management, and time-controlled execution ensures a robust and secure framework for DAO operations. As the project evolves, continuous improvement in documentation, testing, and security measures will contribute to the long-term success and reliability of the DAO.</p><p>In conclusion, the journey into DAO development is an exciting exploration of blockchain’s potential for decentralized, community-driven governance. May your DAO thrive, fostering collaboration and innovation within the decentralized ecosystem.</p><h3>Community and Resources</h3><ol><li>Online Communities: Engage with blockchain developer communities, forums, and platforms like Ethereum Stack Exchange, Reddit’s r/ethereum, or Discord/Telegram groups.</li><li>Documentation and Tutorials: Refer to official Ethereum documentation, Solidity documentation, QuickNode, Alchemy, <a href="https://docs.openzeppelin.com/contracts/5.x/governance#cast_a_vote">How to set up on-chain governance</a>, <a href="https://www.openzeppelin.com/contracts">Bootstrap your smart contract creation with OpenZeppelin Contracts Wizard</a>, University courses, and various tutorials available online.</li></ol><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf1466bbe477" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/how-to-build-a-secure-on-chain-dao-a-comprehensive-guide-to-solidity-development-bf1466bbe477">How to Build a Secure On-Chain DAO: A Comprehensive Guide to Solidity Development</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an NFT Auction Smart Contract on Ethereum]]></title>
            <link>https://coinsbench.com/building-an-nft-auction-smart-contract-on-ethereum-4a1be8795283?source=rss-fca51910fb50------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a1be8795283</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Christian Inyekaka]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 10:36:57 GMT</pubDate>
            <atom:updated>2023-12-31T10:36:57.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*6wPyA_NRjrM1hahwOG_deg.jpeg" /><figcaption>Auction Smart Contract</figcaption></figure><p>The decentralized nature of blockchain technology has opened up innovative possibilities for digital assets, notably in the form of Non-Fungible Tokens (NFTs). NFTs represent unique digital assets, and auctions have become a popular way to trade them. In this tutorial, we’ll explore how to build an Ethereum-based NFT auction smart contract.</p><h4><strong>Prerequisites:</strong></h4><ul><li>Basic understanding of Solidity.</li><li>Development environment setup with tools like Hardhat or Truffle.</li></ul><h4>Smart Contract Structure</h4><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.19;<br><br>import &quot;@openzeppelin/contracts/token/ERC721/ERC721.sol&quot;;<br>// import &quot;@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/ReentrancyGuard.sol&quot;;<br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>contract MyToken is ERC721, ERC721Enumerable, ERC721URIStorage, ERC721Burnable, Ownable {<br>    constructor(address initialOwner)<br>        ERC721(&quot;MyToken&quot;, &quot;MTK&quot;)<br>        Ownable(initialOwner)<br>    {}<br><br>    function safeMint(address to, uint256 tokenId, string memory uri)<br>        public<br>        onlyOwner <br>    {<br>        _safeMint(to, tokenId);<br>        _setTokenURI(tokenId, uri);<br>    }<br>    // function pause() external onlyOwner {<br>    //     _pause();<br>    // }<br>    // function unpause() public onlyOwner {<br>    //     _unpause();<br>    // }<br><br>    // The following functions are overrides required by Solidity.<br><br>    function _update(address to, uint256 tokenId, address auth)<br>        internal<br>        override(ERC721, ERC721Enumerable)<br>        returns (address)<br>    {<br>        return super._update(to, tokenId, auth);<br>    }<br><br>    function _increaseBalance(address account, uint128 value)<br>        internal<br>        override(ERC721, ERC721Enumerable)<br>    {<br>        super._increaseBalance(account, value);<br>    }<br><br>    function tokenURI(uint256 tokenId)<br>        public<br>        view<br>        override(ERC721, ERC721URIStorage)<br>        returns (string memory)<br>    {<br>        return super.tokenURI(tokenId);<br>    }<br><br>    function supportsInterface(bytes4 interfaceId)<br>        public<br>        view<br>        override(ERC721, ERC721Enumerable, ERC721URIStorage)<br>        returns (bool)<br>    {<br>        return super.supportsInterface(interfaceId);<br>    }<br>    <br>}<br>contract Auction is ReentrancyGuard {<br>    struct AuctionInfo {<br>        address seller;<br>        uint256 tokenId;<br>        uint256 highestBid;<br>        address payable highestBidder;<br>        uint256 endTimestamp;<br>        bool ended;<br>    }<br><br>    mapping(uint256 =&gt; AuctionInfo) public auctions;<br>    mapping(uint256 =&gt; bool) public claimedNFT;<br><br>    event NewBid(address indexed bidder, uint256 indexed tokenId, uint256 amount);<br>    event AuctionEnded(uint256 indexed tokenId, address indexed winner, uint256 amount);<br>    event Claimed(address indexed bidder, uint256 indexed tokenID);<br>    event moneySent(address indexed seller , uint256 indexed tokenID, uint256 amount);<br><br>    modifier auctionExists(uint256 tokenId) {<br>        require(auctions[tokenId].seller != address(0), &quot;Auction does not exist&quot;);<br>        _;<br>    }<br><br>    modifier onlySeller(uint256 tokenId) {<br>        require(auctions[tokenId].seller == msg.sender, &quot;Not the auction seller&quot;);<br>        _;<br>    }<br><br>    constructor() {<br>     <br>    }<br>    // this function return the sellers address<br>    function getSeller(uint256 auctionId) external view returns (address) {<br>        return auctions[auctionId].seller;<br>    }<br>    // this function return the highest bidder address<br>    function getHighestBidder(uint256 auctionId) external view returns (address) {<br>        return auctions[auctionId].highestBidder;<br>    }<br>    function isEnded(uint256 auctionId) external view returns (bool) {<br>        return auctions[auctionId].ended;<br>    }<br>// this function start the auction<br>    function startAuction(<br>        address tokenContract,<br>        uint256 tokenId,<br>        uint256 duration<br>    ) external nonReentrant {<br>        MyToken nft = MyToken(tokenContract);<br>        require(nft.ownerOf(tokenId) == msg.sender, &quot;Not token owner&quot;);<br>        require(duration &gt; 0, &quot;Duration should be &gt; 0&quot;);<br><br>        nft.transferFrom(msg.sender, address(this), tokenId);<br><br>        auctions[tokenId] = AuctionInfo({<br>            seller: msg.sender,<br>            tokenId: tokenId,<br>            highestBid: 0,<br>            highestBidder: payable(address(0)),<br>            endTimestamp: block.timestamp + duration,<br>            ended: false<br>        });<br>    }<br>    // this function post a bid and replace the highest bid if the new bid is higher than the highest bid<br><br>    function bid(uint256 tokenId) external payable nonReentrant auctionExists(tokenId) {<br>        AuctionInfo storage auction = auctions[tokenId];<br>        require(block.timestamp &lt; auction.endTimestamp, &quot;Auction ended&quot;);<br>        require(msg.value &gt; auction.highestBid, &quot;Bid too low&quot;);<br><br>        if (auction.highestBidder != address(0)) {<br>            auction.highestBidder.transfer(auction.highestBid);<br>        }<br><br>        auction.highestBid = msg.value;<br>        auction.highestBidder = payable(msg.sender);<br>        emit NewBid(msg.sender, tokenId, msg.value);<br>    }<br>    // this function ends the auction<br><br>    function endAuction(uint256 tokenId) external nonReentrant auctionExists(tokenId) {<br>        AuctionInfo storage auction = auctions[tokenId];<br>        require(block.timestamp &gt;= auction.endTimestamp, &quot;Auction not ended&quot;);<br>        require(!auction.ended, &quot;Auction already ended&quot;);<br>        auction.ended = true;<br><br>        emit AuctionEnded(tokenId, auction.highestBidder, auction.highestBid);<br>    }<br>    // this function claims the NFT and thransfer the nft to the winner and transfer the money to the seller<br>    function claimNFT(uint256 tokenId,address tokenContract) external nonReentrant auctionExists(tokenId) {<br>         AuctionInfo storage auction = auctions[tokenId];<br><br>        require(auction.ended, &quot;Auction not ended&quot;);<br><br>        require(auction.highestBidder == msg.sender,&quot;not the winner&quot;);<br><br>        MyToken nft = MyToken(tokenContract);<br><br>        if(!claimedNFT[tokenId]){<br><br>          nft.transferFrom(address(this), msg.sender, tokenId);<br><br>        claimedNFT[tokenId] = true; <br><br>         payable(auction.seller).transfer(auction.highestBid); <br><br>         emit Claimed(msg.sender, tokenId);<br><br>         emit moneySent(auction.seller, tokenId, auction.highestBid);<br><br>        }else{<br>            revert(&quot;already claimed&quot;);<br>        }<br>        <br>    }<br>// this function withdraw the NFT if no winner or the bid from the winner<br>    function withdraw(uint256 tokenId,address tokenContract) external nonReentrant auctionExists(tokenId) {<br><br>        AuctionInfo storage auction = auctions[tokenId];<br><br>        require(auction.ended, &quot;Auction not ended&quot;);<br><br>        if (msg.sender == auction.seller) {<br><br>            require(auction.highestBidder == address(0), &quot;Cannot withdraw, auction ended&quot;);<br><br>            MyToken nft = MyToken(tokenContract);<br><br>            // tranfer the nft back to the seller<br>            nft.transferFrom(address(this), auction.seller, tokenId);<br><br>        } else if (msg.sender == auction.highestBidder) {<br><br>        require(!claimedNFT[tokenId], &quot;Bidder already received NFT&quot;);<br><br>         payable(msg.sender).transfer(auction.highestBid);<br><br>        } else {<br>            revert(&quot;Not allowed to withdraw&quot;);<br>        }<br>    }<br><br>}</pre><p>The smart contract is composed of two key contracts: MyToken and Auction. MyToken extends ERC721, ERC721Enumerable, ERC721URIStorage, ERC721Burnable, Ownable. Facilitating the creation and management of NFTs. On the other hand, Auction extends <strong>ReentrancyGuard. </strong>The ReentrancyGuard is a protective mechanism used in Solidity to prevent reentrant attacks in smart contracts A reentrancy attack occurs when an external attacker exploits a contract&#39;s vulnerable state by repeatedly calling back into the contract before the ongoing execution completes. ReentrancyGuard is a crucial security measure in Solidity contracts, particularly in scenarios involving asset transfers, to prevent reentrancy attacks and ensure the integrity of contract state changes during critical operations. manages the auction process for these NFTs, governing bidding and ownership transfer.</p><h4>Setting Up The NFT:</h4><pre>contract MyToken is ERC721, ERC721Enumerable, ERC721URIStorage, ERC721Burnable, Ownable {<br>    constructor(address initialOwner)<br>        ERC721(&quot;MyToken&quot;, &quot;MTK&quot;)<br>        Ownable(initialOwner)<br>    {}<br><br>    function safeMint(address to, uint256 tokenId, string memory uri)<br>        public<br>        onlyOwner <br>    {<br>        _safeMint(to, tokenId);<br>        _setTokenURI(tokenId, uri);<br>    }<br>    // function pause() external onlyOwner {<br>    //     _pause();<br>    // }<br>    // function unpause() public onlyOwner {<br>    //     _unpause();<br>    // }<br><br>    // The following functions are overrides required by Solidity.<br><br>    function _update(address to, uint256 tokenId, address auth)<br>        internal<br>        override(ERC721, ERC721Enumerable)<br>        returns (address)<br>    {<br>        return super._update(to, tokenId, auth);<br>    }<br><br>    function _increaseBalance(address account, uint128 value)<br>        internal<br>        override(ERC721, ERC721Enumerable)<br>    {<br>        super._increaseBalance(account, value);<br>    }<br><br>    function tokenURI(uint256 tokenId)<br>        public<br>        view<br>        override(ERC721, ERC721URIStorage)<br>        returns (string memory)<br>    {<br>        return super.tokenURI(tokenId);<br>    }<br><br>    function supportsInterface(bytes4 interfaceId)<br>        public<br>        view<br>        override(ERC721, ERC721Enumerable, ERC721URIStorage)<br>        returns (bool)<br>    {<br>        return super.supportsInterface(interfaceId);<br>    }<br>    <br>}</pre><p>Function safeMint is used to mint ERC721 tokens safely. It can only be called by the owner of the contract (onlyOwner modifier). It takes _to an address tokenIdand a uri string as arguments. Inside the function, it mints a new token to the _to address and sets its URI using _setTokenURI.</p><p>Function tokenURI overrides the default implementation in ERC721. It retrieves and returns the URI associated with a given _tokenId. It ensures that the token exists before querying its URI.</p><p>Function supportsInterface overrides the function from ERC721 and ERC721Enumerable contracts. It checks whether a particular interface is supported by the contract by calling the supportsInterface function from the inherited contracts.</p><h4>Auction Contract Overview:</h4><h4>Auction Struct:</h4><ul><li>To encapsulate auction details effectively, a `struct` is utilized, capturing essential information such as the seller, the TokenID, the highest bid, the highest bidder, and timestamp, and the ended state.</li></ul><pre>struct AuctionInfo {<br>        address seller;<br>        uint256 tokenId;<br>        uint256 highestBid;<br>        address payable highestBidder;<br>        uint256 endTimestamp;<br>        bool ended;<br>    }</pre><h4>Mapping and Variables:</h4><ul><li>We create mappings to store auctions for each token ID and the claimed NFTs.</li></ul><pre>mapping(uint256 =&gt; AuctionInfo) public auctions;<br>mapping(uint256 =&gt; bool) public claimedNFT;</pre><h4>Events:</h4><p>These events serve to notify external systems or users about critical actions taking place within the auction contract, allowing them to track the auction’s progress, facilitate user interface updates, or trigger further actions in response to these events.</p><pre>    event NewBid(address indexed bidder, uint256 indexed tokenId, uint256 amount);<br>    event AuctionEnded(uint256 indexed tokenId, address indexed winner, uint256 amount);<br>    event Claimed(address indexed bidder, uint256 indexed tokenID);<br>    event moneySent(address indexed seller , uint256 indexed tokenID, uint256 amount);</pre><ul><li>NewBid: Signals that a new bid has been placed, providing information about the bidder, the token ID, and the bid amount.</li><li>AuctionEnded: Indicates that an auction has concluded, specifying the token ID, the winning bidder, and the winning bid amount.</li><li>Claimed: Signals that a bidder has claimed an NFT, providing information about the bidder and the token ID.</li><li>moneySent: Indicates that money has been transferred, specifying the seller&#39;s address, the token ID, and the amount sent.</li></ul><h4>Start Auction:</h4><p>Initiates a new auction by transferring the NFT to the contract and defining auction parameters.</p><pre> function startAuction(<br>        address tokenContract,<br>        uint256 tokenId,<br>        uint256 duration<br>    ) external nonReentrant {<br>        MyToken nft = MyToken(tokenContract);<br>        require(nft.ownerOf(tokenId) == msg.sender, &quot;Not token owner&quot;);<br>        require(duration &gt; 0, &quot;Duration should be &gt; 0&quot;);<br><br>        nft.transferFrom(msg.sender, address(this), tokenId);<br><br>        auctions[tokenId] = AuctionInfo({<br>            seller: msg.sender,<br>            tokenId: tokenId,<br>            highestBid: 0,<br>            highestBidder: payable(address(0)),<br>            endTimestamp: block.timestamp + duration,<br>            ended: false<br>        });<br>    }</pre><h4>Place Bid:</h4><p>Allows users to bid on ongoing auctions, updating the highest bid and bidder.</p><pre> function bid(uint256 tokenId) external payable nonReentrant auctionExists(tokenId) {<br>        AuctionInfo storage auction = auctions[tokenId];<br>        require(block.timestamp &lt; auction.endTimestamp, &quot;Auction ended&quot;);<br>        require(msg.value &gt; auction.highestBid, &quot;Bid too low&quot;);<br><br>        if (auction.highestBidder != address(0)) {<br>            auction.highestBidder.transfer(auction.highestBid);<br>        }<br><br>        auction.highestBid = msg.value;<br>        auction.highestBidder = payable(msg.sender);<br>        emit NewBid(msg.sender, tokenId, msg.value);<br>    }</pre><h4>End Auction:</h4><p>Ends the auction after a specified duration and emits the AuctionEnded event</p><pre>  function endAuction(uint256 tokenId) external nonReentrant auctionExists(tokenId) {<br>        AuctionInfo storage auction = auctions[tokenId];<br>        require(block.timestamp &gt;= auction.endTimestamp, &quot;Auction not ended&quot;);<br>        require(!auction.ended, &quot;Auction already ended&quot;);<br>        auction.ended = true;<br><br>        emit AuctionEnded(tokenId, auction.highestBidder, auction.highestBid);<br>    }</pre><h4>Claim NFT:</h4><p>Enables the winner to claim the NFT and facilitates fund transfer to the seller.</p><pre>function claimNFT(uint256 tokenId,address tokenContract) external nonReentrant auctionExists(tokenId) {<br>         AuctionInfo storage auction = auctions[tokenId];<br><br>        require(auction.ended, &quot;Auction not ended&quot;);<br><br>        require(auction.highestBidder == msg.sender,&quot;not the winner&quot;);<br><br>        MyToken nft = MyToken(tokenContract);<br><br>        if(!claimedNFT[tokenId]){<br><br>          nft.transferFrom(address(this), msg.sender, tokenId);<br><br>        claimedNFT[tokenId] = true; <br><br>         payable(auction.seller).transfer(auction.highestBid); <br><br>         emit Claimed(msg.sender, tokenId);<br><br>         emit moneySent(auction.seller, tokenId, auction.highestBid);<br><br>        }else{<br>            revert(&quot;already claimed&quot;);<br>        }<br>        <br>    }</pre><h4>Withdraw NFT:</h4><p>Allows the seller to withdraw the NFT if there are no bids or if the auction ended unsuccessfully. if the auction winner did not claim their NFT or if they don’t want the NFT anymore.</p><pre>function withdraw(uint256 tokenId,address tokenContract) external nonReentrant auctionExists(tokenId) {<br><br>        AuctionInfo storage auction = auctions[tokenId];<br><br>        require(auction.ended, &quot;Auction not ended&quot;);<br><br>        if (msg.sender == auction.seller) {<br><br>            require(auction.highestBidder == address(0), &quot;Cannot withdraw, auction ended&quot;);<br><br>            MyToken nft = MyToken(tokenContract);<br><br>            // tranfer the nft back to the seller<br>            nft.transferFrom(address(this), auction.seller, tokenId);<br><br>        } else if (msg.sender == auction.highestBidder) {<br><br>        require(!claimedNFT[tokenId], &quot;Bidder already received NFT&quot;);<br><br>         payable(msg.sender).transfer(auction.highestBid);<br><br>        } else {<br>            revert(&quot;Not allowed to withdraw&quot;);<br>        }<br>    }</pre><h4>Modifiers:</h4><pre>modifier auctionExists(uint256 tokenId) {<br>        require(auctions[tokenId].seller != address(0), &quot;Auction does not exist&quot;);<br>        _;<br>    }<br><br>    modifier onlySeller(uint256 tokenId) {<br>        require(auctions[tokenId].seller == msg.sender, &quot;Not the auction seller&quot;);<br>        _;<br>    }<br></pre><p>The modifiers auctionExists and onlySeller play a crucial role in ensuring certain conditions are met before executing functions in the smart contract.</p><ol><li>auctionExists(uint256 tokenId): This modifier ensures that an auction exists for a given token ID before allowing the execution of functions that use this modifier. It checks if an auction exists by verifying that the seller&#39;s address associated with the given token ID is not the null address (address(0)). If the auction does not exist, it prevents the function from proceeding and reverts with the message &quot;Auction does not exist.&quot;</li><li>onlySeller(uint256 tokenId): This modifier restricts the execution of functions to only the seller of a specific auction identified by the provided token ID. It ensures that only the seller (the address that initiated the auction) can execute functions with this modifier. If the caller is not the auction seller, the function will not proceed and will revert with the message &quot;Not the auction seller.&quot;</li></ol><p>These modifiers serve as preconditions before executing specific functions within the contract, ensuring that only authorized individuals (such as the seller or when an auction exists) can interact with certain functionalities, enhancing security and preventing unauthorized access or manipulation of auction-related operations.</p><h4>Additional Functions:</h4><pre> <br>    // this function return the sellers address<br>    function getSeller(uint256 auctionId) external view returns (address) {<br>        return auctions[auctionId].seller;<br>    }<br>    // this function return the highest bidder address<br>    function getHighestBidder(uint256 auctionId) external view returns (address) {<br>        return auctions[auctionId].highestBidder;<br>    }<br>    function isEnded(uint256 auctionId) external view returns (bool) {<br>        return auctions[auctionId].ended;<br>    }</pre><p>These additional functions within the smart contract further enhance its functionality and transparency:</p><ol><li>getSeller(uint256 auctionId): This function, when called externally, retrieves and returns the address of the seller associated with a specific auction ID. It provides transparency by allowing anyone to query and verify the seller&#39;s address for a given auction.</li><li>getHighestBidder(uint256 auctionId): Similar to the getSeller function, this function externally retrieves and returns the address of the highest bidder for a particular auction ID. It offers visibility into the current highest bidder in an auction.</li><li>isEnded(uint256 auctionId): This function, when called externally, checks and returns a boolean value indicating whether a specific auction has ended. It&#39;s useful for external parties to determine the status of an auction—whether it&#39;s ongoing or has already concluded.</li></ol><p>These functions essentially provide a read-only interface to certain key details of the auctions, empowering users or external systems to query the contract for critical information such as seller details, highest bidder, and auction status without altering the contract’s state. This transparency and accessibility contribute to the overall usability and trustworthiness of the auction smart contract.</p><h4>Testing and Deployment:</h4><p>To ensure the contract’s functionality and security, comprehensive testing using tools like Hardhat or Truffle is essential. Deploying the contract to a testnet or a local development environment provides a safe space to evaluate its behavior before deploying it to the Ethereum mainnet.</p><h4>Test:</h4><pre>const { expect } = require(&quot;chai&quot;);<br>const { ethers } = require(&quot;hardhat&quot;);<br>const { network } = require(&quot;hardhat&quot;);<br><br>describe(&quot;Auction&quot;, function () {<br>  let myToken;<br>  let owner;<br>  let addr1;<br>  let addr2;<br>  let auction;<br>  const amount = ethers.parseEther(&quot;1&quot;);<br>  const lowerAmount = ethers.parseEther(&quot;0.5&quot;);<br>  const higherAmount = ethers.parseEther(&quot;1.5&quot;);<br><br>  beforeEach(async () =&gt; {<br>    [owner, addr1, addr2] = await ethers.getSigners();<br><br>    const MyToken = await ethers.getContractFactory(&quot;MyToken&quot;);<br>    myToken = await MyToken.deploy(owner.address);<br>    await myToken.waitForDeployment();<br><br>    const Auction = await ethers.getContractFactory(&quot;Auction&quot;);<br>    auction = await Auction.deploy();<br>    await auction.waitForDeployment();<br>  });<br><br>  it(&quot;should deploy&quot;, async function () {<br>    expect(await myToken.owner()).to.equal(owner.address);<br>    expect(await auction.target).to.not.equal(undefined);<br>  });<br><br>  it(&quot;should mint an NFT&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br>    const ownerOfToken = await myToken.ownerOf(2);<br>    expect(ownerOfToken).to.equal(owner.address);<br>  });<br><br>  it(&quot;should create auction for an NFT&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 300000000);<br><br>    const seller = await Contract.getSeller(2);<br>    expect(seller).to.equal(owner.address);<br>  });<br>  it(&quot;should bid on an auction&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 300000000);<br><br>    await Contract.connect(addr1).bid(2, { value: amount });<br><br>    const highestBidder = await Contract.getHighestBidder(2);<br>    expect(highestBidder).to.equal(addr1.address);<br>  });<br>  it(&quot;should not bid on an auction if bid is lower than highest bid&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 300000000);<br><br>    await Contract.connect(addr1).bid(2, { value: amount });<br>    await expect(<br>      Contract.connect(addr2).bid(2, { value: lowerAmount })<br>    ).to.be.revertedWith(&quot;Bid too low&quot;);<br>  });<br>  it(&quot;should change the highest bid&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 300000000);<br><br>    await Contract.connect(addr1).bid(2, { value: amount });<br>    await Contract.connect(addr2).bid(2, { value: higherAmount });<br><br>    const highestBidder = await Contract.getHighestBidder(2);<br>    expect(highestBidder).to.equal(addr2.address);<br>  });<br>  it(&quot;should transfer back the bid in case of a higher bid&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 300000000);<br><br>    await Contract.connect(addr1).bid(2, { value: amount });<br>    const blance = await ethers.provider.getBalance(addr1.address);<br>    await Contract.connect(addr2).bid(2, { value: higherAmount });<br><br>    const balance = await ethers.provider.getBalance(addr1.address);<br><br>    expect(balance - blance).to.equal(amount);<br>  });<br>  it(&quot;should end an auction&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 3600);<br>    await Contract.connect(addr1).bid(2, { value: amount });<br>    await network.provider.request({<br>      method: &quot;evm_increaseTime&quot;,<br>      params: [3601],<br>    });<br>    await Contract.connect(owner).endAuction(2);<br><br>    const isended = await Contract.isEnded(2);<br><br>    expect(isended).to.equal(true);<br>  });<br><br>  it(&quot;should allow the highest bidder to claim the NFT&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 3600);<br>    await Contract.connect(addr1).bid(2, { value: amount });<br>    await network.provider.request({<br>      method: &quot;evm_increaseTime&quot;,<br>      params: [3601],<br>    });<br>    await Contract.connect(owner).endAuction(2);<br>    await Contract.connect(addr1).claimNFT(2, myToken.target);<br>    const ownerOfToken = await myToken.ownerOf(2);<br>    expect(ownerOfToken).to.equal(addr1.address);<br>  });<br>  it(&quot;should allow the highest bidder to withdraw&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 3600);<br>    await Contract.connect(addr1).bid(2, { value: amount });<br>    const blance = await ethers.provider.getBalance(addr1.address);<br>    await network.provider.request({<br>      method: &quot;evm_increaseTime&quot;,<br>      params: [3601],<br>    });<br>    await Contract.connect(owner).endAuction(2);<br><br>    await Contract.connect(addr1).withdraw(2, myToken.target);<br>    const balance = await ethers.provider.getBalance(addr1.address);<br><br>    expect(balance).to.be.greaterThan(blance);<br>  });<br>  it(&quot;should withdraw NFT&quot;, async function () {<br>    await myToken.safeMint(<br>      owner.address,<br>      2,<br>      &quot;ipfs://bafkreia3qm2s35beymhuma7w4x3bp3bn45vamm532lgwzi5vdv3sbv4sae&quot;<br>    );<br><br>    const Contract = await ethers.getContractAt(&quot;Auction&quot;, auction.target);<br>    await myToken.approve(auction.target, 2);<br>    await Contract.connect(owner).startAuction(myToken.target, 2, 3600);<br>    await network.provider.request({<br>      method: &quot;evm_increaseTime&quot;,<br>      params: [3601],<br>    });<br>    await Contract.connect(owner).endAuction(2);<br>    const isended = await Contract.isEnded(2);<br>    await Contract.connect(owner).withdraw(2, myToken.target);<br>    // check gas used<br><br>    expect(await myToken.ownerOf(2)).to.equal(owner.address);<br>  });<br>});</pre><h4>Conclusion</h4><p>Building an NFT auction smart contract involves integrating ERC721 functionalities for NFT management and implementing auction-related features for bidding and ownership transfer. Thorough testing and proper deployment are crucial to ensure the contract’s reliability and security.</p><h3>Final Thoughts</h3><p>Developing an NFT auction on Ethereum involves integrating ERC721 standards for NFT management and creating auction-specific functionalities. Security measures like ReentrancyGuard are crucial to prevent attacks during asset transfers. Thorough testing using tools like Hardhat or Truffle and deploying contracts to testnets ensure functionality and security before the Ethereum mainnet launch. Embracing blockchain&#39;s decentralization and following Solidity best practices contribute to DeFi&#39;s growth and wider NFT adoption, unlocking new possibilities in the digital asset realm</p><h3>Community and Resources</h3><ol><li>Online Communities: Engage with blockchain developer communities, forums, and platforms like Ethereum Stack Exchange, Reddit’s r/ethereum, or Discord/Telegram groups.</li><li>Documentation and Tutorials: Refer to official Ethereum documentation, Solidity documentation, QuickNode, Alchemy University courses, and various tutorials available online.</li></ol><p><em>This marks the end of our tutorial if you found it useful feel free to clap or leave a comment</em>. <em>Any suggestions or feedback will be welcomed. You can also connect with me on</em> <a href="https://twitter.com/InyekakaB"><strong><em>Twitter</em></strong></a><em>, </em><a href="http://www.linkedin.com/in/christianinyekaka"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://github.com/chrisBokotaII"><strong><em>GitHub</em></strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a1be8795283" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/building-an-nft-auction-smart-contract-on-ethereum-4a1be8795283">Building an NFT Auction Smart Contract on Ethereum</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>