<?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 Defiboy on Medium]]></title>
        <description><![CDATA[Stories by Defiboy on Medium]]></description>
        <link>https://medium.com/@defiboy?source=rss-48d3d8af41ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KfMlnlwvQtwSBN3Mo6pwwg.jpeg</url>
            <title>Stories by Defiboy on Medium</title>
            <link>https://medium.com/@defiboy?source=rss-48d3d8af41ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:03:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@defiboy/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[Interacting with Smart Contracts on Reef Pelagia]]></title>
            <link>https://medium.com/@defiboy/interacting-with-smart-contracts-on-reef-pelagia-d3a0b11e378a?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3a0b11e378a</guid>
            <category><![CDATA[reefchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[pelagia-testnet]]></category>
            <category><![CDATA[kyc]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Tue, 26 May 2026 15:32:13 GMT</pubDate>
            <atom:updated>2026-05-27T16:17:22.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2UBx5scFfNvmV0isTn5RQ.png" /></figure><p>In this article, I will guide you on how to interact with Solidity smart contracts deployed on Reef Pelagia.</p><h3>What is Reef?</h3><p><a href="https://reef.io/">Reef</a> is the layer 1 blockchain purpose-built for tokenized equity and alternative investments. With native ERC3643 support, EVM compatibility, and compliance-ready infrastructure. Reef makes issuing securities, managing KYC/AML verification, and RWA deployment on-chain easy and affordable.</p><h3>What is Pelegia?</h3><p>Pelegia is Reef’s public testnet, designed to give developers and builders a production-like environment to experiment, iterate, and validate their applications. Everything you need to build, test, prepare for mainnet deployment is now avaliable</p><h3>Starting Points</h3><ul><li>You’ll need to add Reef Relagia to your MetaMask or EVM-compatible wallet if you haven’t already. You can do that here: <a href="https://docs.reef.io/docs/developers/pelagia-wallet/">Network Details</a></li><li>Get some test <a href="https://faucet.reef-node-reefdevcluster-1e797e-72-60-35-83.nip.io/">$REEF</a></li><li>Have <a href="https://nodejs.org/en">Nodejs</a> installed on your PC</li><li>Have a basic understanding of JavaScript and one of its frameworks or libraries, and be prepared to develop</li></ul><h3>Let’s Get Started</h3><p>We are ready to interact with it on our frontend using <a href="https://viem.sh/">Viem</a>. We’ll be using <a href="https://react.dev/">React.js</a> for this and installing it with <a href="https://vitejs.dev/">Vite.js</a>.</p><pre># npm 7+, extra double-dash is needed:<br>npm create vite@latest reef-pelagia-test -- --template react</pre><p>After installation, open the project folder in your preferred IDE, such as VS Code.</p><pre>cd reef-pelagia-test &amp;&amp; code .</pre><p>Now that you’ve opened the project folder in VS Code, you can install Viem.</p><pre>npm i viem</pre><h3>Let’s Build the Frontend</h3><p>You can create the src/config.ts file:</p><pre>export const reefPelagia = defineChain({<br>  id: 13939,<br>  sourceId: 13939,<br>  name: &#39;Reef Pelagia&#39;,<br>  nativeCurrency: {<br>    decimals: 12,<br>    name: &#39;Reef Pelagia&#39;,<br>    symbol: &#39;REEF&#39;,<br>  },<br>  rpcUrls: {<br>    default: {<br>      http: [&#39;https://eth.reef-node-reefdevcluster-808c46-72-60-35-83.nip.io/&#39;],<br>    },<br>  },<br>});</pre><p>Update the file app.tsx to:</p><pre>import { useState } from &#39;react&#39;<br>import viteLogo from &#39;/vite.svg&#39;<br>import &#39;./App.css&#39;<br>import { createPublicClient, http } from &#39;viem&#39;<br>import { reefPelagia } from &#39;./config&#39;<br><br>const client = createPublicClient({<br>  chain: reefPelagia,<br>  transport: http(),<br>})<br><br>function App() {<br>  const [number, setNumber] = useState(0)<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;logos&quot;&gt;<br>        &lt;a href=&quot;https://vite.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={viteLogo} className=&quot;logo&quot; alt=&quot;Vite logo&quot; /&gt;<br>        &lt;/a&gt;<br>        &lt;a href=&quot;https://morphl2.io&quot; target=&quot;_blank&quot;&gt;<br>          &lt;h1&gt;Reef Pelagia&lt;/h1&gt;<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;h1&gt;Vite + Reef Pelagia&lt;/h1&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button&gt;<br>          Number in storage is {number}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br>export default App</pre><p>I’ve initialized Viem in the project and made some UI adjustments. Now, let’s delve into using Viem to make the project reactive. First, let’s import createWalletClient from Viem.</p><pre>import { createPublicClient, http, createWalletClient, custom,parseEther } from &#39;viem&#39;</pre><p>Then initialize it in the code</p><pre>const wallet_client = createWalletClient({<br>  chain: reefPelagia,<br>  transport: custom(window.ethereum)<br>})</pre><p>To access the available wallet in the browser, we use window.ethereum. You&#39;ll need to copy the contract&#39;s <a href="https://www.alchemy.com/overviews/what-is-an-abi-of-a-smart-contract-examples-and-usage">ABI</a> to your frontend. Create a new folder named contract inside the src folder, and then create a file called abi.js.</p><pre>const abi = [<br>    {<br>        &quot;inputs&quot;: [],<br>        &quot;name&quot;: &quot;retrieve&quot;,<br>        &quot;outputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;stateMutability&quot;: &quot;view&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    },<br>    {<br>        &quot;inputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;_number&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;name&quot;: &quot;store&quot;,<br>        &quot;outputs&quot;: [],<br>        &quot;stateMutability&quot;: &quot;nonpayable&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    }<br>]</pre><p>Next, we’ll import it into App.jsx</p><pre>import ABI from &quot;./contract/abi&quot;</pre><p>We’ve finished importing the ABI. Now, let’s create a function named store within the App function</p><pre>const store = async (number) =&gt; {<br>    const { request } = await client.simulateContract({<br>      address: &#39;0x0951B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;, // dummy contract address, not deployed onchain<br>      abi: ABI,<br>      functionName: &#39;store&#39;,<br>      args: [parseEther(number)]<br>    });<br>    const hash = await wallet_client.writeContract(request);<br>    return hash;<br>  }</pre><p>The store function is used to interact with the store function from the contract. In the code above, we&#39;re passing the _number parameter from the contract using the args option. The parameter input is parsed with ethers to ensure the contract can understand it.</p><h3>Fectching datas from the smart contract</h3><p>Don’t worry, you’ll see it! To view the output from the smart contract, we’ll need to make a call to the contract. Similar to regular API calls with Axios or Fetch, we’ll use Viem to fetch the request from the smart contract through the ABI. Add the following code after the store function.</p><pre>const retrieve = async () =&gt; {<br>    const data = await client.readContract({<br>      address: &#39;0x0951B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;, // dummy contract address, not deployed onchain<br>      abi: ABI,<br>      functionName: &#39;retrieve&#39;,<br>      account<br>    });<br>  return data;<br>}</pre><p>To use the dApp, we need to connect a wallet. We’ll create a React hook named useConnect for easy wallet connection. Start by creating a hooks folder and a useConnect.js file within it. Paste the following code into the file:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>export const useWallet = () =&gt; {<br>  const [account, setAccount] = useState(null);<br>  const [error, setError] = useState(null);<br>  // Function to connect wallet<br>  const connectWallet = async () =&gt; {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      try {<br>        // Request wallet connection<br>        const accounts = await window.ethereum.request({ method: &#39;eth_requestAccounts&#39; });<br>        <br>        // Set the first connected account<br>        setAccount(accounts[0]);<br>        setError(null);  // Clear any previous error<br>      } catch (err) {<br>        // Handle error if user rejects the request or if there&#39;s another issue<br>        setError(&#39;User rejected the connection request or an error occurred.&#39;);<br>      }<br>    } else {<br>      setError(&#39;No Ethereum provider found. Please install MetaMask.&#39;);<br>    }<br>  };<br>  // Optionally: Detect account change or network change<br>  useEffect(() =&gt; {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      const handleAccountsChanged = (accounts) =&gt; {<br>        if (accounts.length &gt; 0) {<br>          setAccount(accounts[0]);<br>        } else {<br>          setAccount(null); // Disconnected<br>        }<br>      };<br>      window.ethereum.on(&#39;accountsChanged&#39;, handleAccountsChanged);<br>      return () =&gt; {<br>        window.ethereum.removeListener(&#39;accountsChanged&#39;, handleAccountsChanged);<br>      };<br>    }<br>  }, []);<br>  return { account, connectWallet, error };<br>};</pre><p>The useConnect hook simplifies wallet connection, eliminating the need to rewrite the code in every page. Although it&#39;s not strictly necessary for this project, we&#39;ll use the useEffect hook to call the retrieve function, preventing unnecessary re-renders.</p><pre>useEffect(() =&gt; {<br>    retrieve().then((data) =&gt; {<br>      setNumber(formatEther(data))<br>    })<br>  }, [number, setNumber]);</pre><p>Finally, let’s review the complete code</p><pre>import { useEffect, useState } from &#39;react&#39;<br>import viteLogo from &#39;/vite.svg&#39;<br>import &#39;./App.css&#39;<br>import { createPublicClient, http, createWalletClient, custom, parseEther, formatEther } from &#39;viem&#39;<br>import { reefPelagia } from &#39;./config&#39;<br>import { abi as ABI } from &quot;./contract/abi&quot;;<br>import { useWallet } from &#39;./hooks/useConnect&#39;;<br><br>const client = createPublicClient({<br>  chain: reefPelagia,<br>  transport: http(),<br>})<br>const wallet_client = createWalletClient({<br>  chain: reefPelagia,<br>  transport: custom(window.ethereum)<br>})<br>function App() {<br>  const [number, setNumber] = useState(0);<br>  const { account, connectWallet, error } = useWallet();<br>  const store = async (number) =&gt; {<br>    const { request } = await client.simulateContract({<br>      address: &#39;0x0951B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;, // dummy contract address, not deployed onchain<br>      abi: ABI,<br>      functionName: &#39;store&#39;,<br>      args: [parseEther(number)],<br>      account<br>    });<br>    const hash = await wallet_client.writeContract(request);<br>    return hash;<br>  }<br>  const retrieve = async () =&gt; {<br>    const data = await client.readContract({<br>      address: &#39;0x0951B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;, // dummy contract address, not deployed onchain<br>      abi: ABI,<br>      functionName: &#39;retrieve&#39;,<br>      account<br>    });<br>    return data;<br>  }<br>  useEffect(() =&gt; {<br>    retrieve().then((data) =&gt; {<br>      setNumber(formatEther(data))<br>    })<br>  }, [number, setNumber]);<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;logos&quot;&gt;<br>        &lt;a href=&quot;https://vite.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={viteLogo} className=&quot;logo&quot; alt=&quot;Vite logo&quot; /&gt;<br>        &lt;/a&gt;<br>       &lt;a href=&quot;https://morphl2.io&quot; target=&quot;_blank&quot;&gt;<br>          &lt;h1&gt;Reef Pelagia&lt;/h1&gt;<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;h1&gt;Vite + Reef Pelagia&lt;/h1&gt;<br>      &lt;button onClick={connectWallet}&gt;<br>        {account? account : &quot;Connect Wallet&quot;}<br>      &lt;/button&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button onClick={() =&gt; {<br>          store(String(Number(number) + 1))<br>        }}&gt;<br>          Number in storage is {number}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br>export default App</pre><h3>Conclusion</h3><p>This tutorial provided a guide through creating a web application and connecting it to a smart contract deployed on Reef Pelagia Testnet using Viem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3a0b11e378a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interacting with Smart Contracts on Morph Hoodi]]></title>
            <link>https://medium.com/@defiboy/interacting-with-smart-contracts-on-morph-hoodi-ba94a44b5ed0?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba94a44b5ed0</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[bitget-wallet]]></category>
            <category><![CDATA[morph]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 05:49:43 GMT</pubDate>
            <atom:updated>2025-10-25T05:49:43.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gy-Mm3YG3DABAQzzIgwvKQ.png" /></figure><p>In this article, I will guide you on how to interact with Solidity smart contracts deployed on Morph Hoodi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex7N2krD3-bmaMx_YZ5OqA.png" /></figure><h3>What is Morph?</h3><p><a href="https://www.morphl2.io/">Morph</a> is a dedicated onchain payment ecosystem designed to transform stablecoins into everyday currency. It enables fast, secure, and borderless transactions while unlocking real utility for global users.</p><h3>Starting Points</h3><ul><li>You’ll need to add Morph Hoodi to your MetaMask or EVM-compatible wallet if you haven’t already. You can do that here: <a href="https://docs.morphl2.io/docs/build-on-morph/build-on-morph/integration-one-page">Network Details</a></li><li>Get some test <a href="https://faucet.quicknode.com/ethereum/hoodi">$ETH</a>, and bridge to <a href="https://bridge-hoodi.morphl2.io/">Morph Hoodi</a></li><li>Have <a href="https://nodejs.org/en">Nodejs</a> installed on your PC</li><li>Have a basic understanding of JavaScript and one of its frameworks or libraries, and be prepared to develop</li></ul><h3>Let’s Get Started</h3><p>We are ready to interact with it on our frontend using <a href="https://viem.sh/">Viem</a>. We’ll be using <a href="https://react.dev/">React.js</a> for this and installing it with <a href="https://vitejs.dev/">Vite.js</a>.</p><pre># npm 7+, extra double-dash is needed:<br>npm create vite@latest morph-hoodi-test -- --template react</pre><p>After installation, open the project folder in your preferred IDE, such as VS Code.</p><pre>cd morph-hoodi-test &amp;&amp; code .</pre><p>Now that you’ve opened the project folder in VS Code, you can install Viem.</p><pre>npm i viem</pre><h3>Let’s Build the Frontend</h3><p>You can create the src/config.ts file:</p><pre>export const morphHoodi = defineChain({<br>  id: 2910,<br>  sourceId: 2910,<br>  name: &#39;Morph Hoodi&#39;,<br>  nativeCurrency: {<br>    decimals: 18,<br>    name: &#39;Ether&#39;,<br>    symbol: &#39;ETH&#39;,<br>  },<br>  rpcUrls: {<br>    default: {<br>      http: [&#39;https://rpc-hoodi.morphl2.io/&#39;],<br>    },<br>  },<br>});</pre><p>Update the file app.tsx to:</p><pre>import { useState } from &#39;react&#39;<br>import viteLogo from &#39;/vite.svg&#39;<br>import &#39;./App.css&#39;<br>import { createPublicClient, http } from &#39;viem&#39;<br>import { morphHoodi } from &#39;./config&#39;<br><br><br>const client = createPublicClient({<br>  chain: morphHoodi,<br>  transport: http(),<br>})<br><br><br>function App() {<br>  const [number, setNumber] = useState(0)<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;logos&quot;&gt;<br>        &lt;a href=&quot;https://vite.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={viteLogo} className=&quot;logo&quot; alt=&quot;Vite logo&quot; /&gt;<br>        &lt;/a&gt;<br>        &lt;a href=&quot;https://morphl2.io&quot; target=&quot;_blank&quot;&gt;<br>          &lt;h1&gt;Morph Hoodi&lt;/h1&gt;<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;h1&gt;Vite + Morph Hoodi&lt;/h1&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button&gt;<br>          Number in storage is {number}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br>export default App</pre><p>I’ve initialized Viem in the project and made some UI adjustments. Now, let’s delve into using Viem to make the project reactive. First, let’s import createWalletClient from Viem.</p><pre>import { createPublicClient, http, createWalletClient, custom,parseEther } from &#39;viem&#39;</pre><p>Then initialize it in the code</p><pre>const wallet_client = createWalletClient({<br>  chain: morphHoodi,<br>  transport: custom(window.ethereum)<br>})</pre><p>To access the available wallet in the browser, we use window.ethereum. You&#39;ll need to copy the contract&#39;s <a href="https://www.alchemy.com/overviews/what-is-an-abi-of-a-smart-contract-examples-and-usage">ABI</a> to your frontend. Create a new folder named contract inside the src folder, and then create a file called abi.js.</p><pre>const abi = [<br>    {<br>        &quot;inputs&quot;: [],<br>        &quot;name&quot;: &quot;retrieve&quot;,<br>        &quot;outputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;stateMutability&quot;: &quot;view&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    },<br>    {<br>        &quot;inputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;_number&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;name&quot;: &quot;store&quot;,<br>        &quot;outputs&quot;: [],<br>        &quot;stateMutability&quot;: &quot;nonpayable&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    }<br>]</pre><p>Next, we’ll import it into App.jsx</p><pre>import ABI from &quot;./contract/abi&quot;</pre><p>We’ve finished importing the ABI. Now, let’s create a function named store within the App function</p><pre>const store = async (number) =&gt; {<br>    const { request } = await client.simulateContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;store&#39;,<br>      args: [parseEther(number)]<br>    });<br>    const hash = await wallet_client.writeContract(request);<br>    return hash;<br>  }</pre><p>The store function is used to interact with the store function from the contract. In the code above, we&#39;re passing the _number parameter from the contract using the args option. The parameter input is parsed with ethers to ensure the contract can understand it.</p><h3>Fectching datas from the smart contract</h3><p>Don’t worry, you’ll see it! To view the output from the smart contract, we’ll need to make a call to the contract. Similar to regular API calls with Axios or Fetch, we’ll use Viem to fetch the request from the smart contract through the ABI. Add the following code after the store function.</p><pre>const retrieve = async () =&gt; {<br>    const data = await client.readContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;retrieve&#39;,<br>      account<br>    });<br>  return data;<br>}</pre><p>To use the dApp, we need to connect a wallet. We’ll create a React hook named useConnect for easy wallet connection. Start by creating a hooks folder and a useConnect.js file within it. Paste the following code into the file:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>export const useWallet = () =&gt; {<br>  const [account, setAccount] = useState(null);<br>  const [error, setError] = useState(null);<br>  // Function to connect wallet<br>  const connectWallet = async () =&gt; {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      try {<br>        // Request wallet connection<br>        const accounts = await window.ethereum.request({ method: &#39;eth_requestAccounts&#39; });<br>        <br>        // Set the first connected account<br>        setAccount(accounts[0]);<br>        setError(null);  // Clear any previous error<br>      } catch (err) {<br>        // Handle error if user rejects the request or if there&#39;s another issue<br>        setError(&#39;User rejected the connection request or an error occurred.&#39;);<br>      }<br>    } else {<br>      setError(&#39;No Ethereum provider found. Please install MetaMask.&#39;);<br>    }<br>  };<br>  // Optionally: Detect account change or network change<br>  useEffect(() =&gt; {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      const handleAccountsChanged = (accounts) =&gt; {<br>        if (accounts.length &gt; 0) {<br>          setAccount(accounts[0]);<br>        } else {<br>          setAccount(null); // Disconnected<br>        }<br>      };<br>      window.ethereum.on(&#39;accountsChanged&#39;, handleAccountsChanged);<br>      return () =&gt; {<br>        window.ethereum.removeListener(&#39;accountsChanged&#39;, handleAccountsChanged);<br>      };<br>    }<br>  }, []);<br>  return { account, connectWallet, error };<br>};</pre><p>The useConnect hook simplifies wallet connection, eliminating the need to rewrite the code in every page. Although it&#39;s not strictly necessary for this project, we&#39;ll use the useEffect hook to call the retrieve function, preventing unnecessary re-renders.</p><pre>useEffect(() =&gt; {<br>    retrieve().then((data) =&gt; {<br>      setNumber(formatEther(data))<br>    })<br>  }, [number, setNumber]);</pre><p>Finally, let’s review the complete code</p><pre>import { useEffect, useState } from &#39;react&#39;<br>import viteLogo from &#39;/vite.svg&#39;<br>import &#39;./App.css&#39;<br>import { createPublicClient, http, createWalletClient, custom, parseEther, formatEther } from &#39;viem&#39;<br>import { morphHoodi } from &#39;./config&#39;<br>import { abi as ABI } from &quot;./contract/abi&quot;;<br>import { useWallet } from &#39;./hooks/useConnect&#39;;<br><br>const client = createPublicClient({<br>  chain: morphHoodi,<br>  transport: http(),<br>})<br>const wallet_client = createWalletClient({<br>  chain: morphHoodi,<br>  transport: custom(window.ethereum)<br>})<br>function App() {<br>  const [number, setNumber] = useState(0);<br>  const { account, connectWallet, error } = useWallet();<br>  const store = async (number) =&gt; {<br>    const { request } = await client.simulateContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;store&#39;,<br>      args: [parseEther(number)],<br>      account<br>    });<br>    const hash = await wallet_client.writeContract(request);<br>    return hash;<br>  }<br>  const retrieve = async () =&gt; {<br>    const data = await client.readContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;retrieve&#39;,<br>      account<br>    });<br>    return data;<br>  }<br>  useEffect(() =&gt; {<br>    retrieve().then((data) =&gt; {<br>      setNumber(formatEther(data))<br>    })<br>  }, [number, setNumber]);<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;logos&quot;&gt;<br>        &lt;a href=&quot;https://vite.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={viteLogo} className=&quot;logo&quot; alt=&quot;Vite logo&quot; /&gt;<br>        &lt;/a&gt;<br>       &lt;a href=&quot;https://morphl2.io&quot; target=&quot;_blank&quot;&gt;<br>          &lt;h1&gt;Morph Hoodi&lt;/h1&gt;<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;h1&gt;Vite + Morph Hoodi&lt;/h1&gt;<br>      &lt;button onClick={connectWallet}&gt;<br>        {account? account : &quot;Connect Wallet&quot;}<br>      &lt;/button&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button onClick={() =&gt; {<br>          store(String(Number(number) + 1))<br>        }}&gt;<br>          Number in storage is {number}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br>export default App</pre><h3>Conclusion</h3><p>This tutorial provided a guide through creating a web application and connecting it to a smart contract deployed on Morph Hoodi Testnet using Viem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba94a44b5ed0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interacting with Smart Contracts on Umi Network]]></title>
            <link>https://medium.com/@defiboy/interacting-with-smart-contracts-on-umi-network-d02d2828617e?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d02d2828617e</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[movement]]></category>
            <category><![CDATA[umi-network]]></category>
            <category><![CDATA[move]]></category>
            <category><![CDATA[umi]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 23:58:19 GMT</pubDate>
            <atom:updated>2025-07-03T00:42:01.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwbExaexPYdhAqxnDnJC4w.png" /></figure><p>In this article, I will guide you on how to interact with Solidity smart contracts deployed on Umi Network.</p><h3>What is Umi Network</h3><p><a href="https://uminetwork.com/">Umi Network</a> is an Infrastructure that allows dual or more Virtual Machines to run simultaneously with one access, starting with Move &amp; EVM meaning developers who build on Ethereum can deploy thier smart contract on Umi Network without any code change and developers on the Move ecosystem can also deploy their smart contract on Umi Network without a code change also.</p><h3>Starting Points</h3><ul><li>You’ll need to add Umi to your MetaMask or EVM-compatible wallet if you haven’t already. You can do that here: <a href="https://docs.uminetwork.com/">Network Details</a></li><li>Get some test <a href="https://faucet.uminetwork.com/">$ETH</a></li><li>Have <a href="https://nodejs.org/en">Nodejs</a> installed on your PC</li><li>Have a basic understanding of JavaScript and one of its frameworks or libraries, and be prepared to develop</li></ul><h3>Set up your Next.js project</h3><ol><li>Scaffold the Next.js using the package:</li></ol><pre>npx create-next-app@latest umi-dapp --typescript<br>cd umi-dapp</pre><p>2. Install the necessary packages:</p><pre>npm install viem @benfen/bcs ethers</pre><h3>Start your configuration for Onchain Interaction</h3><p>Create the config.ts file. This file is important for enabling a custom chain extension in Viem, allowing it to work with Umi.</p><pre>import { BCS, getRustConfig } from &#39;@benfen/bcs&#39;;<br>import { ethers } from &#39;ethers&#39;;<br>import { createPublicClient, createWalletClient, custom, defineChain } from &#39;viem&#39;;<br>import { publicActionsL2, walletActionsL2 } from &#39;viem/op-stack&#39;;<br>import { abi } from &#39;./SimpleMessage.json&#39;;<br>import { privateKeyToAccount } from &#39;viem/accounts&#39;<br><br>const CONTRACT_ADDRESS = &#39;CONTRACT_ADDRESS&#39;;<br>const PRIVATE_KEY = &#39;PRIVATE_KEY&#39;;<br><br>const bcs = new BCS(getRustConfig());<br>bcs.registerEnumType(&#39;SerializableTransactionData&#39;, {<br>  EoaBaseTokenTransfer: &#39;&#39;,<br>  ScriptOrDeployment: &#39;&#39;,<br>  EntryFunction: &#39;&#39;,<br>  L2Contract: &#39;&#39;,<br>  EvmContract: &#39;Vec&lt;u8&gt;&#39;,<br>});<br><br>const serializeFunction = (data: string): `0x${string}` =&gt; {<br>  const code = Uint8Array.from(Buffer.from(data.replace(&#39;0x&#39;, &#39;&#39;), &#39;hex&#39;));<br>  const evmContract = bcs.ser(&#39;SerializableTransactionData&#39;, { EvmContract: code });<br>  return `0x${evmContract.toString(&#39;hex&#39;)}`;<br>};<br><br>export const devnet = defineChain({<br>  id: 42069,<br>  sourceId: 42069,<br>  name: &#39;Umi&#39;,<br>  nativeCurrency: {<br>    decimals: 18,<br>    name: &#39;Ether&#39;,<br>    symbol: &#39;ETH&#39;,<br>  },<br>  rpcUrls: {<br>    default: {<br>      http: [&#39;https://devnet.uminetwork.com/&#39;],<br>    },<br>  },<br>});<br><br>export const getAccount = async () =&gt; {<br>  const account = privateKeyToAccount(PRIVATE_KEY);<br>  return account;<br>};<br><br>export const publicClient = () =&gt;<br>  createPublicClient({<br>    chain: devnet,<br>    transport: custom(window.ethereum!),<br>  }).extend(publicActionsL2());<br><br>export const walletClient = () =&gt;<br>  createWalletClient({<br>    chain: devnet,<br>    transport: custom(window.ethereum!),<br>  }).extend(walletActionsL2());<br><br>export const getFunction = async (name: string) =&gt; {<br>  const counter = new ethers.Contract(CONTRACT_ADDRESS, abi);<br>  const tx = await counter.getFunction(name).populateTransaction();<br>  return { to: tx.to as `0x${string}`, data: serializeFunction(tx.data) };<br>};</pre><h3>Let’s Build the Frontend</h3><p>The current Umi RPC doesn’t work properly on localhost, so we’ll create a fix for that. Create a api/rpc/route.ts file and add the following code:</p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br><br>export async function POST(req: NextRequest) {<br>  const body = await req.text();<br>  const res = await fetch(&#39;https://devnet.uminetwork.com/&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body,<br>  });<br>  const data = await res.text();<br>  return new NextResponse(data, {<br>    status: res.status,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  });<br>}</pre><p>You can update the config.ts file:</p><pre>export const devnet = defineChain({<br>  id: 42069,<br>  sourceId: 42069,<br>  name: &#39;Umi&#39;,<br>  nativeCurrency: {<br>    decimals: 18,<br>    name: &#39;Ether&#39;,<br>    symbol: &#39;ETH&#39;,<br>  },<br>  rpcUrls: {<br>    default: {<br>      http: [&#39;/api/rpc&#39;],<br>    },<br>  },<br>});</pre><p>Create a new file app/page.tsx :</p><pre>&#39;use client&#39;;<br>import { useEffect, useState } from &#39;react&#39;;<br>import { getAccount, getFunction, publicClient, walletClient } from &#39;@/config&#39;;<br><br>export default function Home() {<br>  const [message, setMessage] = useState(&quot;&quot;);<br>  const [$message, set$Message] = useState(&quot;&quot;);<br><br>  const fetchMessage = async () =&gt; {<br>    const { to, data } = await getFunction(&#39;message&#39;);<br>    const response = await publicClient().call({ to, data });<br><br>    if (!response.data) throw Error(&#39;No data found&#39;);<br>    if (typeof response.data == &#39;string&#39;) throw Error(&#39;Data is not an array of bytes&#39;);<br>    const message = ((response.data));<br>    setMessage(message);<br>  };<br><br>  const sendMessage = async (message: string) =&gt; {<br>    const { to, data } = await getFunction(&#39;sendMessage&#39;);<br>    const hash = await walletClient().sendTransaction({ account: await getAccount()?.address, to, data, value: message });<br>    await publicClient().waitForTransactionReceipt({ hash });<br>    fetchMessage();<br>  };<br><br>  useEffect(() =&gt; {<br>    fetchMessage();<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;text-center&quot;&gt;<br>      &lt;h1 className=&quot;px-2&quot;&gt;Message: {message}&lt;/h1&gt;<br>      &lt;input type=&quot;text&quot; onChange={(e)=&gt; set$Message(e.target.value)} value={$message} /&gt;<br>      &lt;button className=&quot;bg-blue-200 rounded px-5 py-2.5&quot; type=&quot;button&quot; onClick={async ()=&gt; { await sendMessage(); }}&gt;<br>        Send Message<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Run the code</h3><p>Start the server:</p><pre>npm run dev</pre><p>Open http://localhost:3000 in your browser to interact with the contract.</p><h3>Conclusion</h3><p>In this article, you learned how to build a web app and connect it seamlessly to a smart contract deployed on the Umi Devnet. You’re now ready to start experimenting and building powerful dApps on Umi’s MultiVM infrastructure. The future is multi-chain — and you’re already ahead of the curve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d02d2828617e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Onchain Consumer Finance Layer is Here]]></title>
            <link>https://medium.com/@defiboy/the-onchain-consumer-finance-layer-is-here-957c1d8f90a9?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/957c1d8f90a9</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[morph]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Tue, 20 May 2025 00:12:50 GMT</pubDate>
            <atom:updated>2025-05-20T00:12:50.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZeM2rAxChf-SO7IKurnTg.png" /></figure><p><a href="https://www.morphl2.io/">Morph Layer</a> is officially evolving thier vision to be the Global Consumer Layer focusing on Onchain Consumer Finance.</p><p>Morph is currently evolving the way we spend, save and manage our money for both individuals &amp; businesses, TradFi is gone &amp; Morph is here to stay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIaSGD1HjsgO05YFH1CkfA.png" /></figure><p>The Morph Team is developing a platform for onchain consumer finance — a unified platform where users can access payments, rewards, and financial tools that operate at the speed of the internet, without relying on outdated systems.</p><h3>Introducing Morph Pay</h3><p>Morph Pay is a financial platform that makes DeFi have the traditional banking feeling, this means it brings together DeFi benefits with familiarity to traditional banking.</p><h3>Reimagine Payment Systems</h3><p>The industry has created a good opportunity for wealth generation with DeFi, but the complexity makes it hard for people to use it for daily finance.</p><p>Traditional finance makes everyday use possible but lacks multiple services that are important.</p><h3>Meet MorphPay</h3><p>It combines the the Traditional FInance with DeFi to create a unified financial hub, bringing together the best of both worlds: the high yields and innovation of DeFi and the convenience and simplicity of traditional banking services.</p><p>Morph Pay allows users to can directly make payment from their wallets, earn token rewards, and engage with partner services through both digital and physical experiences. It’s literally everything onchain consumer finance should be: secured and built for everyday use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyeFQgWw0jRlfcFSRdLz4w.png" /></figure><p>The two core pillars of Morph Pay:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Pb6KfgRyMjAaAU51RAhtw.png" /></figure><p><strong>Morph Black </strong>is a crypto card that offers access to up to 30% yield, high daily spending limits, token-based rewards, exclusive partner airdrops, and dedicated support. It’s designed for users who want to bring their assets into real-world use while unlocking powerful onchain benefits.</p><p><strong>Morph Platinum</strong> provides a smooth entry into the Morph ecosystem. It includes direct access to the Morph Token, DeFi yield opportunities, integrated crypto payments, and both a digital and physical Platinum Card. It’s built for everyday use and designed for users who want modern financial tools without the complexity.</p><h3>The New Standard For Digital Finance</h3><p>Morph is more than just a platform. It’s a changing how we interact with money.</p><p>With Morph Pay, Morph Black, and Morph Platinum live, Morph is delivering access to onchain consumer finance that feels modern and ready to scale with the world it serves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=957c1d8f90a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI + RWA Ecosystem is Here]]></title>
            <link>https://medium.com/@defiboy/the-ai-rwa-ecosystem-is-here-fae6d100dc49?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/fae6d100dc49</guid>
            <category><![CDATA[rwa]]></category>
            <category><![CDATA[assetchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Mon, 05 May 2025 13:10:34 GMT</pubDate>
            <atom:updated>2025-05-05T13:10:34.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d04syKf7EkpbMUfuxoxbzA.png" /></figure><p>The convergence of Artificial Intelligence (AI) and Real-World Asset (RWA) tokenization is reshaping the landscape of decentralized finance. <a href="https://assetchain.org/">AssetChain</a> stands at the forefront of this transformation, offering a Layer-1 blockchain platform that seamlessly integrates AI capabilities with RWA tokenization. This article delves into the technical intricacies of AssetChain, exploring how its architecture empowers developers to build intelligent, scalable, and compliant decentralized applications (dApps).</p><h3>Intelligence-First Blockchain Architecture</h3><h3>AI Stack at the Base Layer</h3><p>AssetChain distinguishes itself by embedding AI directly into its Layer-1 infrastructure, earning the title “Intelligence-First Blockchain.” This integration facilitates:</p><ul><li><strong>Dynamic Compliance</strong>: AI modules ensure real-time adherence to regulatory standards, adapting to evolving legal frameworks.</li><li><strong>On-Chain Valuation</strong>: AI-driven models assess both on-chain and off-chain data to provide accurate asset valuations.</li><li><strong>Real-Time Data Pipelines</strong>: Continuous data feeds enable up-to-date information flow, crucial for asset management and decision-making.</li></ul><p>This foundational AI integration streamlines processes, reduces manual intervention, and enhances the overall efficiency of dApps built on AssetChain.</p><h3>Robust Infrastructure for RWA Tokenization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqrC6u50ZjGVVDBQwYTRUQ.png" /></figure><h3>EVM Compatibility</h3><p>AssetChain is fully compatible with the Ethereum Virtual Machine (EVM), allowing developers to:</p><ul><li>Utilize existing Ethereum tools and libraries.</li><li>Deploy Solidity smart contracts without modification.</li><li>Ensure interoperability with Ethereum-based dApps and services.</li></ul><p>This compatibility accelerates development cycles and facilitates the migration of existing projects to AssetChain.</p><h3>Lachesis Proof-of-Stake (LPoS) Consensus</h3><p>Employing the Lachesis Proof-of-Stake consensus mechanism, AssetChain achieves:</p><ul><li><strong>High Throughput</strong>: Supporting up to 20,000 transactions per second (TPS).</li><li><strong>Low Latency</strong>: Ensuring transaction finality within 1–2 seconds.</li><li><strong>Cost Efficiency</strong>: Maintaining transaction fees as low as $0.00004.</li></ul><p>This performance profile makes AssetChain suitable for high-volume applications, including those involving microtransactions and real-time data processing.</p><h3>Seamless RWA Tokenization Process</h3><p>AssetChain streamlines the tokenization of real-world assets through a structured process:</p><ol><li><strong>Asset Definition</strong>: Identify and structure the asset to be tokenized, determining ownership models and compliance requirements.</li><li><strong>Smart Contract Deployment</strong>: Utilize AssetChain’s SDKs to develop and deploy smart contracts representing the asset.</li><li><strong>Token Issuance and Management</strong>: Mint tokens representing the asset, enabling fractional ownership, trading, and lifecycle management.</li></ol><p>This process is underpinned by AssetChain’s AI capabilities, which provide real-time compliance checks and asset valuations, ensuring a secure and transparent tokenization lifecycle.</p><h3>Developer Ecosystem and Resources</h3><p>AssetChain offers a comprehensive suite of tools and resources to support developers:</p><ul><li><strong>Asset Development Kit (ADK)</strong>: A toolkit for building and deploying dApps with integrated AI functionalities.</li><li><strong>Comprehensive Documentation</strong>: Detailed guides and references to facilitate development and integration.</li><li><strong>AssetChain Academy</strong>: Educational resources and tutorials to onboard developers and enhance their proficiency.</li><li><strong>Community Support</strong>: Active forums and support channels to assist with development challenges and foster collaboration.</li></ul><p>These resources are designed to accelerate development timelines and promote innovation within the AssetChain ecosystem.</p><h3>Getting Started with AssetChain</h3><p>Developers interested in building on AssetChain can begin by:</p><ol><li><strong>Exploring the Documentation</strong>: Familiarize yourself with AssetChain’s architecture and development tools.</li><li><strong>Joining the Community</strong>: Engage with other developers and contributors through forums and support channels.</li><li><strong>Participating in Hackathons</strong>: Test your skills and contribute to the ecosystem through organized development events.</li><li><strong>Deploying dApps</strong>: Leverage the Asset Development Kit to build and launch your own decentralized applications.</li></ol><p>By integrating AI and RWA tokenization, AssetChain offers a robust platform for developers to innovate and shape the future of decentralized finance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lkw0Poq31Sf_FzW513VxsA.png" /></figure><h3>NextAIHack is Live</h3><p>Assetchain in collaboration with <a href="https://x.com/nextbridgeafric">Nextbridge Africa</a> is hosting the <a href="https://nextaihack.nextbridge.africa/">NextAIHack</a>. This Hackathon is for builders around AI-Agent, they are looking for builders and developers to build solutions around AI-Agent on Assetchain. This is your opportunity to start building on Assetchain.</p><h3>Why Participate?</h3><ul><li><strong>AI + RWA Integration</strong>: AssetChain offers a unique blend of Artificial Intelligence and Real-World Asset tokenization, providing a robust foundation for developing intelligent decentralized applications.</li><li><strong>Developer-Friendly Tools</strong>: With EVM compatibility and comprehensive SDKs, AssetChain simplifies the development process for Ethereum developers.</li><li><strong>Community and Support</strong>: Participants will have access to a vibrant community and resources provided by NextBridge Africa, fostering collaboration and innovation.</li></ul><h3>What to Build?</h3><p>The hackathon focuses on the development of AI Agents that can:</p><ul><li>Automate compliance and regulatory processes.</li><li>Provide real-time asset valuation and analytics.</li><li>Enhance user interactions through intelligent interfaces.</li></ul><h3>📅 How to Participate?</h3><ul><li><strong>Registration</strong>: Sign up for the hackathon at <a href="https://nextaihack.nextbridge.africa/">nextaihack.nextbridge.africa</a>.</li><li><strong>Resources</strong>: Access documentation, SDKs, and community support to kickstart your project.</li><li><strong>Submission</strong>: Develop and submit your AI Agent solution within the stipulated timeframe.</li></ul><h3>Conclusion</h3><p>NextAIHack presents an exciting opportunity to delve into the intersection of AI and blockchain technology. By participating, developers can contribute to the evolution of intelligent decentralized applications and gain recognition within the growing AssetChain ecosystem.</p><p>Don’t miss this chance to innovate and build the future of AI Agents on AssetChain. Register now and start your development journey!</p><p><strong>Connect with Us on Socials:</strong><br><a href="https://assetchain.org/">Website</a> | <a href="https://x.com/rwaassetchain">Twitter</a> | <a href="https://medium.com/asset-chain">Blog</a> | <a href="https://discord.assetchain.org/">Discord</a> | <a href="https://t.me/AssetChainBuilders">Telegram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fae6d100dc49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interacting with Smart Contracts on Base L2 with Viem]]></title>
            <link>https://medium.com/@defiboy/interacting-with-smart-contracts-on-base-l2-with-viem-807431516d75?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/807431516d75</guid>
            <category><![CDATA[base]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[nextbridge-africa]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 19:49:07 GMT</pubDate>
            <atom:updated>2025-03-26T19:49:07.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOopVye9aXPEOGTmdoZxsA.png" /></figure><p>In this tutorial, i would guide you on how you can interact with Smart contracts deployed on Base Sepolia on Frontend with Viem.</p><h3>What is Viem?</h3><blockquote><em>Viem is a TypeScript interface for Ethereum that provides low-level stateless primitives for interacting with Ethereum.</em></blockquote><h3>Starting Points</h3><ul><li>You would need to add Base Sepolia to your Metamask or EVM wallet if you haven’t here: <a href="https://docs.base.org/chain/network-information">Network Details</a></li><li>Get some test <a href="https://docs.base.org/chain/network-faucets">$ETH</a></li><li>Have <a href="https://nodejs.org/en">Nodejs</a> installed on your PC</li><li>Have a basic understanding of JavaScript and one of its frameworks or libraries, and be prepared to develop.</li></ul><h3>Deployment of Smart Contract on Base Seoplia</h3><p>I have a deployed smart contract with its source code available on <a href="https://github.com/defiboyszn/morph-contract">GitHub</a>. This contract includes a function for storing and retrieving numbers on-chain.</p><p>This contract is deployed on Base Sepolia.</p><h3>Let’s Get Started</h3><p>We’ve deployed our smart contract and are now ready to interact with it on our frontend using <a href="https://viem.sh/">Viem</a>. We’ll be using <a href="https://react.dev/">React.js</a> for this and installing it with <a href="https://vitejs.dev/">Vite.js</a>.</p><pre># npm 7+, extra double-dash is needed:<br>npm create vite@latest simple-contract-ui -- --template react</pre><p>After installation, open the project folder in your preferred IDE, such as VS Code.</p><pre>cd simple-contract-ui &amp;&amp; code .</pre><p>Now that you’ve opened the project folder in VS Code, you can install Viem.</p><pre>npm i viem</pre><h3>Replace the App Component</h3><p>We need to replace the content in app.jsx , from this</p><pre>import { useState } from &#39;react&#39;<br>import reactLogo from &#39;./assets/react.svg&#39;<br>import viteLogo from &#39;/vite.svg&#39;<br>import &#39;./App.css&#39;;<br>function App() {<br>  const [count, setCount] = useState(0)<br>  return (<br>    &lt;&gt;<br>      &lt;div&gt;<br>        &lt;a href=&quot;https://vitejs.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={viteLogo} className=&quot;logo&quot; alt=&quot;Vite logo&quot; /&gt;<br>        &lt;/a&gt;<br>        &lt;a href=&quot;https://react.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={reactLogo} className=&quot;logo react&quot; alt=&quot;React logo&quot; /&gt;<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;h1&gt;Vite + React&lt;/h1&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button onClick={() =&gt; setCount((count) =&gt; count + 1)}&gt;<br>          count is {count}<br>        &lt;/button&gt;<br>        &lt;p&gt;<br>          Edit &lt;code&gt;src/App.jsx&lt;/code&gt; and save to test HMR<br>        &lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;p className=&quot;read-the-docs&quot;&gt;<br>        Click on the Vite and React logos to learn more<br>      &lt;/p&gt;<br>    &lt;/&gt;<br>  )<br>}<br>export default App</pre><p>To</p><pre>import { useState } from &#39;react&#39;<br>import viteLogo from &#39;/vite.svg&#39;<br>import &#39;./App.css&#39;<br>import { createPublicClient, http } from &#39;viem&#39;<br>import { baseSepolia } from &#39;viem/chains&#39;<br>const client = createPublicClient({<br>  chain: baseSepolia,<br>  transport: http(),<br>})<br>function App() {<br>  const [number, setNumber] = useState(0)<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;logos&quot;&gt;<br>        &lt;a href=&quot;https://vite.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={viteLogo} className=&quot;logo&quot; alt=&quot;Vite logo&quot; /&gt;<br>        &lt;/a&gt;<br>        &lt;a href=&quot;https://base.org&quot; target=&quot;_blank&quot;&gt;<br>          &lt;h1&gt;BASE&lt;/h1&gt;<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;h1&gt;Vite + Base&lt;/h1&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button&gt;<br>          Number in storage is {number}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br>export default App</pre><p>I’ve initialized Viem in the project and made some UI adjustments. Now, let’s delve into using Viem to make the project reactive. First, let’s import createWalletClient from Viem.</p><pre>import { createPublicClient, http, createWalletClient, custom,parseEther  } from &#39;viem&#39;</pre><p>Then initialize it in the code</p><pre>const wallet_client = createWalletClient({<br>  chain: baseSepolia,<br>  transport: custom(window.ethereum)<br>})</pre><p>To access the available wallet in the browser, we use window.ethereum. You&#39;ll need to copy the contract&#39;s <a href="https://www.alchemy.com/overviews/what-is-an-abi-of-a-smart-contract-examples-and-usage">ABI</a> to your frontend. Create a new folder named contract inside the src folder, and then create a file called abi.js.</p><pre>const abi = [<br>    {<br>        &quot;inputs&quot;: [],<br>        &quot;name&quot;: &quot;retrieve&quot;,<br>        &quot;outputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;stateMutability&quot;: &quot;view&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    },<br>    {<br>        &quot;inputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;_number&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;name&quot;: &quot;store&quot;,<br>        &quot;outputs&quot;: [],<br>        &quot;stateMutability&quot;: &quot;nonpayable&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    }<br>]</pre><p>Next, we’ll import it into App.jsx</p><pre>import ABI from &quot;./contract/abi&quot;</pre><p>We’ve finished importing the ABI. Now, let’s create a function named store within the App function</p><pre>const store = async (number) =&gt; {<br>    const { request } = await client.simulateContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;store&#39;,<br>      args: [parseEther(number)]<br>    });<br>    const hash = await wallet_client.writeContract(request);<br>    return hash;<br>  }</pre><p>The store function is used to interact with the store function from the contract. In the code above, we&#39;re passing the _number parameter from the contract using the args option. The parameter input is parsed with ethers to ensure the contract can understand it.</p><h3>Fectching datas from the smart contract</h3><p>Don’t worry, you’ll see it! To view the output from the smart contract, we’ll need to make a call to the contract. Similar to regular API calls with Axios or Fetch, we’ll use Viem to fetch the request from the smart contract through the ABI. Add the following code after the store function.</p><pre>const retrieve = async () =&gt; {<br>    const data = await client.readContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;retrieve&#39;,<br>      account<br>    });<br>  return data;<br>}</pre><p>To use the dApp, we need to connect a wallet. We’ll create a React hook named useConnect for easy wallet connection. Start by creating a hooks folder and a useConnect.js file within it. Paste the following code into the file:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>export const useWallet = () =&gt; {<br>  const [account, setAccount] = useState(null);<br>  const [error, setError] = useState(null);<br>  // Function to connect wallet<br>  const connectWallet = async () =&gt; {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      try {<br>        // Request wallet connection<br>        const accounts = await window.ethereum.request({ method: &#39;eth_requestAccounts&#39; });<br>        <br>        // Set the first connected account<br>        setAccount(accounts[0]);<br>        setError(null);  // Clear any previous error<br>      } catch (err) {<br>        // Handle error if user rejects the request or if there&#39;s another issue<br>        setError(&#39;User rejected the connection request or an error occurred.&#39;);<br>      }<br>    } else {<br>      setError(&#39;No Ethereum provider found. Please install MetaMask.&#39;);<br>    }<br>  };<br>  // Optionally: Detect account change or network change<br>  useEffect(() =&gt; {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      const handleAccountsChanged = (accounts) =&gt; {<br>        if (accounts.length &gt; 0) {<br>          setAccount(accounts[0]);<br>        } else {<br>          setAccount(null); // Disconnected<br>        }<br>      };<br>      window.ethereum.on(&#39;accountsChanged&#39;, handleAccountsChanged);<br>      return () =&gt; {<br>        window.ethereum.removeListener(&#39;accountsChanged&#39;, handleAccountsChanged);<br>      };<br>    }<br>  }, []);<br>  return { account, connectWallet, error };<br>};</pre><p>The useConnect hook simplifies wallet connection, eliminating the need to rewrite the code in every page. Although it&#39;s not strictly necessary for this project, we&#39;ll use the useEffect hook to call the retrieve function, preventing unnecessary re-renders.</p><pre>useEffect(() =&gt; {<br>    retrieve().then((data) =&gt; {<br>      setNumber(formatEther(data))<br>    })<br>  }, [number, setNumber]);</pre><p>Finally, let’s review the complete code</p><pre>import { useEffect, useState } from &#39;react&#39;<br>import viteLogo from &#39;/vite.svg&#39;<br>import &#39;./App.css&#39;<br>import { createPublicClient, http, createWalletClient, custom, parseEther, formatEther } from &#39;viem&#39;<br>import { baseSepolia } from &#39;viem/chains&#39;<br>import { abi as ABI } from &quot;./contract/abi&quot;;<br>import { useWallet } from &#39;./hooks/useConnect&#39;;<br><br>const client = createPublicClient({<br>  chain: baseSepolia,<br>  transport: http(),<br>})<br>const wallet_client = createWalletClient({<br>  chain: baseSepolia,<br>  transport: custom(window.ethereum)<br>})<br>function App() {<br>  const [number, setNumber] = useState(0);<br>  const { account, connectWallet, error } = useWallet();<br>  const store = async (number) =&gt; {<br>    const { request } = await client.simulateContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;store&#39;,<br>      args: [parseEther(number)],<br>      account<br>    });<br>    const hash = await wallet_client.writeContract(request);<br>    return hash;<br>  }<br>  const retrieve = async () =&gt; {<br>    const data = await client.readContract({<br>      address: &#39;0x5051B66DFe49900e7210E34AdAe3383a841Ebe5b&#39;,<br>      abi: ABI,<br>      functionName: &#39;retrieve&#39;,<br>      account<br>    });<br>    return data;<br>  }<br>  useEffect(() =&gt; {<br>    retrieve().then((data) =&gt; {<br>      setNumber(formatEther(data))<br>    })<br>  }, [number, setNumber]);<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;logos&quot;&gt;<br>        &lt;a href=&quot;https://vite.dev&quot; target=&quot;_blank&quot;&gt;<br>          &lt;img src={viteLogo} className=&quot;logo&quot; alt=&quot;Vite logo&quot; /&gt;<br>        &lt;/a&gt;<br>        &lt;a href=&quot;https://base.org&quot; target=&quot;_blank&quot;&gt;<br>          &lt;h1&gt;BASE&lt;/h1&gt;<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;h1&gt;Vite + Base&lt;/h1&gt;<br>      &lt;button onClick={connectWallet}&gt;<br>        {account? account : &quot;Connect Wallet&quot;}<br>      &lt;/button&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button onClick={() =&gt; {<br>          store(String(Number(number) + 1))<br>        }}&gt;<br>          Number in storage is {number}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br>export default App</pre><h3>Conclusion</h3><p>This tutorial provided a guide through creating a web application and connecting it to a smart contract deployed on Base Sepolia Testnet using Viem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=807431516d75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Smart Contract for Tip and Donation Systems on Morph]]></title>
            <link>https://medium.com/@defiboy/creating-a-smart-contract-for-tip-and-donation-systems-on-morph-3ea2d8ec93ab?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ea2d8ec93ab</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[morph]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 08:20:49 GMT</pubDate>
            <atom:updated>2024-11-30T08:20:49.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zNBVxaCIplxN6gMqI0Epw.png" /></figure><p>A Tip and Donation System is a system that allows users to support their favorite creators, charities, or even communities in a decentralized manner.</p><p>With Morph’s low gas fees, it’s the perfect chain to build solutions like this. Users won’t have to worry about the fees they’d need to pay for gas.</p><p>In this article, we’ll learn how to build a smart contract for tipping and donations.</p><h3>Key Features of the Contract</h3><ol><li><strong>Support for Multiple Beneficiaries</strong>: Enable tipping/donating to different recipients.</li><li><strong>Customizable Messages</strong>: Allow users to include messages with their donations.</li><li><strong>Withdraw Functionality</strong>: Secure withdrawal mechanism for beneficiaries.</li><li><strong>Event Logging</strong>: Log donations for transparency and analytics.</li></ol><h3>Prerequisites</h3><ol><li>Basic knowledge of Solidity.</li><li>A working environment with <strong>Node.js</strong>, <strong>Hardhat</strong> installed.</li><li>Access to the Morph.</li></ol><h3>Step 1: Setting up Development Environment</h3><ol><li>Initialize a Hardhat Project</li></ol><pre>mkdir morph-tip<br>cd morph-tip<br>npx hardhat init</pre><p>2. Install some necessary dependencies</p><pre>npm install @openzeppelin/contracts dotenv hardhat-ethers ethers</pre><p>3. Configure hardhat for Morph Holesky</p><pre>require(&quot;@nomiclabs/hardhat-ethers&quot;);<br>require(&quot;dotenv&quot;).config();<br>module.exports = {<br>  networks: {<br>    &quot;morph-holesky&quot;: {<br>      url: &quot;https://rpc-quicknode-holesky.morphl2.io/&quot;,<br>      accounts: [`0x${process.env.PRIVATE_KEY}`],<br>    },<br>  },<br>  solidity: &quot;0.8.19&quot;,<br>};</pre><h3>Step 2: Writing of the Crowdfunding Contract</h3><p>Start by creating a new file contracts/tips.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract TipAndDonate {<br>    // Event to log donations<br>    event DonationReceived(<br>        address indexed donor,<br>        address indexed beneficiary,<br>        uint256 amount,<br>        string message<br>    );<br><br>    // Event to log withdrawals<br>    event Withdrawn(address indexed beneficiary, uint256 amount);<br><br>    // Mapping to track balances of beneficiaries<br>    mapping(address =&gt; uint256) public balances;<br><br>    // Function to donate to a beneficiary<br>    function donate(address beneficiary, string memory message) external payable {<br>        require(msg.value &gt; 0, &quot;Donation must be greater than zero&quot;);<br><br>        // Update the beneficiary&#39;s balance<br>        balances[beneficiary] += msg.value;<br><br>        // Emit the donation event<br>        emit DonationReceived(msg.sender, beneficiary, msg.value, message);<br>    }<br><br>    // Function for beneficiaries to withdraw their funds<br>    function withdraw() external {<br>        uint256 amount = balances[msg.sender];<br>        require(amount &gt; 0, &quot;No funds available to withdraw&quot;);<br><br>        // Reset the beneficiary&#39;s balance to zero<br>        balances[msg.sender] = 0;<br><br>        // Transfer the funds<br>        (bool success, ) = msg.sender.call{value: amount}(&quot;&quot;);<br>        require(success, &quot;Withdrawal failed&quot;);<br><br>        // Emit the withdrawal event<br>        emit Withdrawn(msg.sender, amount);<br>    }<br><br>    // Function to check the contract&#39;s balance<br>    function getContractBalance() external view returns (uint256) {<br>        return address(this).balance;<br>    }<br>}</pre><h3>Step 3: Compile and Deploy the Contract</h3><ol><li>Compile the Contract:</li></ol><pre>npx hardhat compile</pre><p>2. Deploy the Contract:</p><pre>async function main() {<br>    const TipAndDonate = await ethers.getContractFactory(&quot;TipAndDonate&quot;);<br>    const tipanddonate = await TipAndDonate.deploy();<br>console.log(&quot;TipAndDonate deployed to:&quot;, tipanddonate.address);<br>}<br>main().catch((error) =&gt; {<br>    console.error(error);<br>    process.exitCode = 1;<br>});</pre><p>Deploy to Morph Holesky:</p><pre>npx hardhat run scripts/deploy.js --network morph-holesky</pre><h3>Step 4: Frontend Integration</h3><p>You can use libraries like web3.js ethers.js or viem to integrate the deployed contract to your frontend.</p><p>You can add features like:</p><ul><li><strong>Donation Form</strong>: Input for beneficiary address, message, and amount.</li><li><strong>Withdrawal Dashboard</strong>: Display balances and allow withdrawal for beneficiaries.</li></ul><h3>Conclusion</h3><p>With the steps above, you’ve successfully deployed a tip and donation contract. Now, you can integrate it into your project to create a full-featured Tipping dApp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ea2d8ec93ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Rollup Interoperability Standards on Morph]]></title>
            <link>https://medium.com/@defiboy/understanding-rollup-interoperability-standards-on-morph-85ea0c3db233?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ea0c3db233</guid>
            <category><![CDATA[layer-2-solution]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[morph]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 16:46:36 GMT</pubDate>
            <atom:updated>2024-11-25T16:46:36.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SeJiSfjP2hNlnXQJUXRGtg.png" /></figure><p>As the ecosystem of blockchain grows, it becomes hard for Layer 2 and Layer 1 (Ethereum) to easily communicate together. Morph’s interoperability has built it in at core. By adhering to and innovating upon rollup interoperability standards, Morph ensures seamless communication and asset movement between itself and other networks.</p><h3>What Are Rollup Interoperability Standards?</h3><p>Rollup Interoperability Standards define the protocol and frameworks that enables seamless interaction between Layer 1 (L1) blockchain &amp; Layer 2 (L2) rollups, or even between two Layer 2 rollups. These standards are:</p><ul><li><strong>Asset Transfers</strong>: Moving tokens and NFTs between chains.</li><li><strong>Cross-Chain Messaging</strong>: Securely passing data between layers.</li><li><strong>Shared Security</strong>: Maintaining integrity and trust across chains.</li><li><strong>User Experience</strong>: Minimizing friction for cross-chain operations.</li></ul><h3>Interoperability on Morph</h3><h4>1. Compatibility with Ethereum Standards</h4><p>By leveraging the Ethereum Virtual Machine (EVM) and adhering to Ethereum’s interoperability standards, Morph ensures:</p><ul><li>Seamless dApp migration from Ethereum.</li><li>Compatibility with existing tools like MetaMask, Hardhat, and Foundry.</li></ul><h4>2. Cross-Layer Messaging Protocols</h4><p>Morph enables a secure and an efficient cross-layer messaging, allowing applications to communicate across chains without compromising security.</p><ul><li><strong>Optimistic Messaging</strong>: Messages are assumed valid unless challenged.</li><li><strong>zk Messaging</strong>: zk-proofs validate data integrity instantly, reducing reliance on trust assumptions.</li></ul><h3>Technical Breakdown of Morph’s Interoperability</h3><ol><li>Cross-Chain Bridges</li></ol><p>Morph employs trust-minimized bridges that combine Optimistic and zk mechanisms:</p><ul><li><strong>Optimistic Bridges</strong>: Use fraud-proof windows for scalability.</li><li><strong>zk Bridges</strong>: Provide instant finality by leveraging validity proofs.</li><li><strong>Dual-Mode Support</strong>: Depending on the use case, developers can choose between the scalability of Optimistic bridges or the security of zk bridges.</li></ul><p>2. Universal Rollup API</p><p>Morph provides developers with APIs for:</p><ul><li>Token bridging (e.g., ERC-20 and ERC-721 tokens).</li><li>Cross-rollup messaging.</li><li>Event listening for cross-layer state changes.</li></ul><h3>Conclusion</h3><p>Imagine a future where different blockchains can talk to each other seamlessly. That’s what Morph is building. It’s like a bridge between these different worlds, making it easy for developers to create apps that work across multiple blockchains.</p><p>Morph isn’t just a Layer 2 — it’s the connective tissue for blockchain ecosystems, enabling a truly interoperable future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ea0c3db233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Crowdfunding Contract on Morph]]></title>
            <link>https://medium.com/@defiboy/how-to-build-a-crowdfunding-contract-on-morph-e1b9d6b97453?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b9d6b97453</guid>
            <category><![CDATA[morph]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 22:44:04 GMT</pubDate>
            <atom:updated>2024-11-22T22:44:04.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQkZXO-j5FghspkhUn-oQA.png" /></figure><p>In this article, we would discuss how we can build &amp; deploy a Crowdfunding Smart Contract on <a href="https://www.morphl2.io/">Morph L2</a></p><h3>What is Crowdfunding?</h3><p>Crowdfunding is a popular use case for blockchain technology, enabling secure and transparent fund collection.</p><h3>What is Morph ?</h3><p>Morph is an innovative Layer 2 solution built on Ethereum. It combines the strengths of optimistic rollups and zk technology to create a blockchain that is both scalable and secure. By processing transactions off-chain and bundling them into blocks before submitting them to the main Ethereum chain, Morph significantly enhances transaction throughput and reduces gas fees.</p><h4>Prerequisites</h4><ol><li>Basic knowledge of Solidity.</li><li>A working environment with <strong>Node.js</strong>, <strong>Hardhat</strong> installed.</li><li>Access to the Morph Holesky.</li></ol><h3>Step 1: Setting up Development Environment</h3><ol><li>Initialize a Hardhat Project</li></ol><pre>mkdir morph-crowdfunding<br>cd morph-crowdfunding<br>npx hardhat init</pre><p>2. Install some necessary dependencies</p><pre>npm install @openzeppelin/contracts dotenv hardhat-ethers ethers</pre><p>3. Configure hardhat for Morph Holesky</p><pre>require(&quot;@nomiclabs/hardhat-ethers&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>module.exports = {<br>  networks: {<br>    &quot;morph-holesky&quot;: {<br>      url: &quot;https://rpc-quicknode-holesky.morphl2.io/&quot;,<br>      accounts: [`0x${process.env.PRIVATE_KEY}`],<br>    },<br>  },<br>  solidity: &quot;0.8.19&quot;,<br>};</pre><h3>Step 2: Writing of the Crowdfunding Contract</h3><p>Start by creating a new file contracts/Crowdfunding.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.19;<br><br>contract Crowdfunding {<br>    struct Campaign {<br>        address payable creator;<br>        uint256 goal;<br>        uint256 deadline;<br>        uint256 fundsRaised;<br>        bool isCompleted;<br>    }<br><br>    uint256 public campaignCount;<br>    mapping(uint256 =&gt; Campaign) public campaigns;<br>    mapping(uint256 =&gt; mapping(address =&gt; uint256)) public contributions;<br><br>    event CampaignCreated(uint256 campaignId, address creator, uint256 goal, uint256 deadline);<br>    event Funded(uint256 campaignId, address contributor, uint256 amount);<br>    event CampaignCompleted(uint256 campaignId, uint256 fundsRaised);<br><br>    function createCampaign(uint256 _goal, uint256 _duration) external {<br>        require(_goal &gt; 0, &quot;Goal must be greater than zero&quot;);<br><br>        campaigns[campaignCount] = Campaign({<br>            creator: payable(msg.sender),<br>            goal: _goal,<br>            deadline: block.timestamp + _duration,<br>            fundsRaised: 0,<br>            isCompleted: false<br>        });<br><br>        emit CampaignCreated(campaignCount, msg.sender, _goal, block.timestamp + _duration);<br>        campaignCount++;<br>    }<br><br>    function contribute(uint256 _campaignId) external payable {<br>        Campaign storage campaign = campaigns[_campaignId];<br>        require(block.timestamp &lt; campaign.deadline, &quot;Campaign has ended&quot;);<br>        require(!campaign.isCompleted, &quot;Campaign already completed&quot;);<br><br>        campaign.fundsRaised += msg.value;<br>        contributions[_campaignId][msg.sender] += msg.value;<br><br>        emit Funded(_campaignId, msg.sender, msg.value);<br><br>        if (campaign.fundsRaised &gt;= campaign.goal) {<br>            completeCampaign(_campaignId);<br>        }<br>    }<br><br>    function completeCampaign(uint256 _campaignId) internal {<br>        Campaign storage campaign = campaigns[_campaignId];<br>        require(!campaign.isCompleted, &quot;Campaign already completed&quot;);<br>        require(campaign.fundsRaised &gt;= campaign.goal, &quot;Goal not reached&quot;);<br><br>        campaign.isCompleted = true;<br>        campaign.creator.transfer(campaign.fundsRaised);<br><br>        emit CampaignCompleted(_campaignId, campaign.fundsRaised);<br>    }<br><br>    function getRefund(uint256 _campaignId) external {<br>        Campaign storage campaign = campaigns[_campaignId];<br>        require(block.timestamp &gt; campaign.deadline, &quot;Campaign is still ongoing&quot;);<br>        require(campaign.fundsRaised &lt; campaign.goal, &quot;Goal was reached&quot;);<br>        require(contributions[_campaignId][msg.sender] &gt; 0, &quot;No contributions to refund&quot;);<br><br>        uint256 refundAmount = contributions[_campaignId][msg.sender];<br>        contributions[_campaignId][msg.sender] = 0;<br><br>        payable(msg.sender).transfer(refundAmount);<br>    }<br>}</pre><h3>Step 3: Compile and Deploy the Contract</h3><ol><li>Compile the Contract:</li></ol><pre>npx hardhat compile</pre><p>2. Deploy the Contract:</p><pre>async function main() {<br>    const Crowdfunding = await ethers.getContractFactory(&quot;Crowdfunding&quot;);<br>    const crowdfunding = await Crowdfunding.deploy();<br><br>    console.log(&quot;Crowdfunding deployed to:&quot;, crowdfunding.address);<br>}<br><br>main().catch((error) =&gt; {<br>    console.error(error);<br>    process.exitCode = 1;<br>});</pre><p>Deploy to Morph Holesky:</p><pre>npx hardhat run scripts/deploy.js --network morph-holesky</pre><h3>Conclusion</h3><p>With the steps above, you’ve successfully deployed a crowdfunding contract. Now, you can integrate it into your project to create a full-featured Crowdfunding dApp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b9d6b97453" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting DApp to Morph Network with ethers.js]]></title>
            <link>https://medium.com/@defiboy/connecting-dapp-to-morph-network-with-ethers-js-d3b92e95f721?source=rss-48d3d8af41ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3b92e95f721</guid>
            <category><![CDATA[morph]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ether-js]]></category>
            <dc:creator><![CDATA[Defiboy]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 16:19:53 GMT</pubDate>
            <atom:updated>2024-11-16T16:19:53.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-ZccWrJCKe_7oYL3J60Eg.png" /></figure><p>In this article, I’ll guide you through the process of connecting your Dapp to the Morph Network using <a href="https://docs.ethers.org/v6/">ethers.js</a>.</p><h3>What is Ethers.js</h3><blockquote>The ethers.js library aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem. It was originally designed for use with <a href="https://ethers.io/">ethers.io</a> and has since expanded into a more general-purpose library.</blockquote><h3>Starting Points</h3><ul><li>Get Morph Details here: <a href="https://docs.morphl2.io/docs/build-on-morph/build-on-morph/development-setup">Morph Network Details</a></li><li>Have <a href="https://nodejs.org/en">Nodejs</a> installed on your PC</li><li>Have a basic understanding of JavaScript and one of its frameworks or libraries, and be prepared to develop.</li></ul><h3>Let’s Get Started</h3><p>Now that we’ve got all the network details sorted out, we can start connecting to the Morph Network on our frontend. We’ll do this using a handy library called <a href="https://docs.ethers.org/v6/">ethers.js</a>.</p><p>First, let’s add ethers.js to our project.</p><pre>import { ethers } from &quot;ethers&quot;</pre><p>After importing ethers.js, we can now start.</p><pre><br>const provider = new ethers.providers.JsonRpcProvider(<br>  &#39;https://rpc-quicknode.morphl2.io&#39;<br>);</pre><p>The code above is designed to create a JSON-RPC provider to connect to the Morph Network. However, since our Dapp will be using Metamask for wallet interactions, we’ll need to add Morph Network to Metamask as a custom RPC network. Then, we can use the following code to interact with the network:</p><pre>const provider = new ethers.providers.Web3Provider(window.ethereum)</pre><h3>Interacting with Smart Contract</h3><p>Now that we’re connected to the Morph Network using ethers.js, we can start interacting with smart contracts deployed on it.</p><p>We’ll be working with a specific contract deployed on the Morph Holesky network. You can find the contract on <a href="https://github.com/defiboyszn/morph-contract">Github</a>.</p><p>Before we dive into contract interactions, let’s import the ABI into our project.</p><pre>const abi = [<br>    {<br>        &quot;inputs&quot;: [],<br>        &quot;name&quot;: &quot;retrieve&quot;,<br>        &quot;outputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;stateMutability&quot;: &quot;view&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    },<br>    {<br>        &quot;inputs&quot;: [<br>            {<br>                &quot;internalType&quot;: &quot;uint256&quot;,<br>                &quot;name&quot;: &quot;_number&quot;,<br>                &quot;type&quot;: &quot;uint256&quot;<br>            }<br>        ],<br>        &quot;name&quot;: &quot;store&quot;,<br>        &quot;outputs&quot;: [],<br>        &quot;stateMutability&quot;: &quot;nonpayable&quot;,<br>        &quot;type&quot;: &quot;function&quot;<br>    }<br>]</pre><h3>What is ABI ?</h3><p>The Contract Application Binary Interface (ABI) is the standard way to interact with contracts in the Ethereum ecosystem, both from outside the blockchain and for contract-to-contract interaction.</p><h3>Frontend Integration</h3><p>We will be interacting with the store function from the ABI</p><pre>const store = async (number) =&gt; {<br>  const provider = new ethers.providers.Web3Provider(window.ethereum);<br><br>  // Create a contract instance<br>  const contract = new ethers.Contract(ABI, &#39;0x599d52A441Eef87f99241396ee14E4C9fFA78281&#39;, provider);<br><br>  // Convert number to wei using ethers.utils.parseUnits<br>  const value = ethers.utils.parseUnits(number.toString(), &#39;ether&#39;);<br><br>  // Build the transaction object<br>  const tx = {<br>    to: contract.address,<br>    data: contract.functions.store(value).encodeABI(),<br>  };<br><br>  try {<br>    // Send the transaction using provider or signer<br>    const hash = await provider.sendTransaction(tx);<br>    console.log(&#39;Transaction hash:&#39;, hash.hash);<br>    return hash.hash;<br>  } catch (error) {<br>    console.error(&#39;Error sending transaction:&#39;, error);<br>  }<br>};</pre><p>With the code above you’d be able to interact with the store function to add numbers to the contract.</p><p>We will also be retrieving the value from the contract, to do that we’d be using this code:</p><pre>const retrieve = async () =&gt; {<br>  const provider = new ethers.providers.Web3Provider(window.ethereum);<br>  const contract = new ethers.Contract(ABI, &#39;0x599d52A441Eef87f99241396ee14E4C9fFA78281&#39;, provider);<br><br>  const data = await contract.retrieve();<br>  return data;<br>};</pre><p>With the code above, we can use it to retrieve values from the deployed contract on the Morph blockchain.</p><h3>Conclusion</h3><p>If you followed the steps to this point, you should have connected to Morph Network on frontend with ethers.js</p><p>This tutorial should have provided you a guide to connect Morph Holesky Testnet with Ethers.js in your Dapp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3b92e95f721" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>