<?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 Khoirul Aziz on Medium]]></title>
        <description><![CDATA[Stories by Khoirul Aziz on Medium]]></description>
        <link>https://medium.com/@eeroel99?source=rss-515b7ab3c722------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nvB0FAjxINuM1oC8C3twZg.jpeg</url>
            <title>Stories by Khoirul Aziz on Medium</title>
            <link>https://medium.com/@eeroel99?source=rss-515b7ab3c722------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:19:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eeroel99/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 Integration Smart Contract to Front-end, Chapter 1: Simple Dapps for Miner Token]]></title>
            <link>https://coinsbench.com/how-to-integration-smart-contract-to-front-end-chapter-1-simple-dapps-for-miner-token-bce0e9d6ddd1?source=rss-515b7ab3c722------2</link>
            <guid isPermaLink="false">https://medium.com/p/bce0e9d6ddd1</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ether-js]]></category>
            <dc:creator><![CDATA[Khoirul Aziz]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 15:19:54 GMT</pubDate>
            <atom:updated>2024-12-13T12:51:15.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rve9wAKoHzTAucKbICZdeg.png" /></figure><p>In previous articles we have talking about how to build smart contracts on the ethereum network. Starting from ERC-20 tokens to NFT (ERC-721) we have talking in detail. Now, as a complement, in this article we will learn to integrate the smart contratc that we have created with the frontend as an interface for users. And in this chapter we will learn how to create dapps (fullstack) for mining erc-20 tokens that we have deployed. If you want to see the demo project, you can click this link <a href="https://youtu.be/BctOad8xq98">https://youtu.be/BctOad8xq98</a> Prepare coffee, put a headset on your ears set your favorite music and start learning together.</p><h4>1.Set up an ERC-20 smart contract</h4><p>The first step is to create your smart contract first, an example can be seen in the box</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>import &quot;https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.0/contracts/token/ERC20/ERC20.sol&quot;;<br>import &quot;https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.0/contracts/access/Ownable.sol&quot;;<br><br>contract TokenRWID is ERC20, Ownable {<br><br>    constructor() ERC20(&quot;Smart Coin&quot;, &quot;SCN&quot;) {}<br><br>    function mint() public {<br>        _mint(msg.sender, 1 * (10 ** decimals()));<br>    }<br><br>    function burn(uint256 _amount) public onlyOwner {<br>        _burn(msg.sender, _amount * (10 ** decimals()));<br>    }<br><br>    function checkBalance(address _user) public view returns (uint256) {<br>        return balanceOf(_user);<br>    }<br>}</pre><p>Now we just focus only on integration, we just need to create a simple smart contact which consists of 3 main functions, namely the mint function burn function and the checkBalance function. What you need to know is that we can also use the built-in functions of the ERC-20 contract.</p><h4>2. Deploy smart contract</h4><p>Open Remix IDE then copy and paste the smart contract into the code editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjkWhU3OQxvs_bFHl57Rlw.png" /></figure><p>Compile the code, then deploy. When deploying, select Injected <strong>Provider — Meta mask</strong> then follow the process to connect your wallet to the smart contract. After deploying it to the remix, the function we created and the default function from ERC-20 will appear. Later we can also use it in our dapps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*26oZ8yTNPV3bbl2bRIj6rQ.png" /></figure><p><strong>3. Setup frontend<br></strong>For front-end preparation, you can clone from my github. copy command then paste and running in your terminal</p><pre>git clone https://github.com/khazeez/token-miner.git</pre><p>after clone the repository, you must running npm install for installimg dependenties which we need. Open file contract.ts in folder src. and yiu can see the code like this:</p><pre>import Web3 from &quot;web3&quot;;<br>import ABI from &quot;../app/ABI.json&quot;;<br><br>let web3: Web3 | undefined;<br>let contract: any; <br><br>if (typeof window !== &#39;undefined&#39; &amp;&amp; typeof window.ethereum !== &#39;undefined&#39;) {<br>    web3 = new Web3(window.ethereum);<br>    const contractAddress = &quot;0xf6737F78974A2EEF0A9424E98f6E16f1dF130F24&quot;; // ganti dengan address contract kalian<br>    contract = new (web3 as any).eth.Contract(ABI, contractAddress); <br>} else {<br>    console.log(&#39;Ethereum wallet not detected. Please install MetaMask or another wallet.&#39;);<br>}<br><br>export { web3, contract };</pre><p><strong>a. Purpose of the Code</strong>:<br>This code connects your application to the Ethereum blockchain and allows it to interact with a <strong>smart contract</strong> using <strong>Web3.js</strong>.</p><p><strong>b. Main Parts of the Code</strong>:</p><ul><li><strong>Check for Wallet</strong>: The code checks if the user&#39;s browser has an Ethereum wallet (such as MetaMask) installed.</li><li><strong>Connect to Blockchain</strong>: If a wallet is detected, it establishes a connection to the blockchain using <strong>Web3</strong>.</li></ul><p><strong>c. how to use the code<br></strong>You can copy and paste your contract address in variable contractAddress . Then, copy and paste your ABI from remix IDE to file ABI.json in folder src also.</p><p><strong>3. Let’s play with the functions</strong></p><p>In this section we want to learn how solidity functions can be used in the front-end. You can go to file page.tsx and seee code like this:</p><pre>&#39;use client&#39;;<br><br>import logo from &#39;@/public/vercel.svg&#39;;<br>import { Button, Divider, InputNumber } from &#39;antd&#39;;<br>import Image from &#39;next/image&#39;;<br>import { web3, contract } from &#39;./contract&#39;;<br>import { useState } from &#39;react&#39;;<br><br>export default function Home() {<br>  const [account, setAccount] = useState(&quot;&quot;);<br>  const [balance, setBalance] = useState(0);<br>  const [value, setValue] = useState(0)<br>  const [symbol, setSymbol] = useState(&quot;&quot;)<br><br><br>  const connectWallet = async () =&gt; {<br>    if (web3 &amp;&amp; contract) {<br>      try {<br>        const accounts = await web3.eth.requestAccounts();<br>        setAccount(accounts[0]);<br>        getBalance(accounts[0]);<br>        let symbolToken = await contract.methods.symbol().call();<br>        setSymbol(symbolToken);<br>      } catch (error) {<br>        console.error(&quot;Error accessing accounts:&quot;, error);<br>      }<br>    } else {<br>      console.error(&quot;Web3 or contract is not initialized&quot;);<br>    }<br>  };<br><br>  <br><br>  const mintToken = async () =&gt; {<br>    try {<br>      const gasPrice = await web3?.eth.getGasPrice();<br>      await contract.methods.mint().send({ from: account, gasPrice });<br>      getBalance(account)<br>    } catch (error) {<br>      console.error(error);<br>    }<br>  };<br><br>  const inputValue = async ({q}) =&gt; {<br>    try {<br>    await setValue(q)<br>    } catch (err) {<br>     await console.log(err)<br>    }<br>  }<br><br>  const burnToken = async () =&gt; {<br>    try {<br>      const gasPrice = await web3?.eth.getGasPrice();<br>      await contract.methods.burn(value).send({ from: account, gasPrice });<br>      getBalance(account)<br>    } catch (err) {<br>      console.error(err);<br>    }<br>  }<br><br>  const getBalance = async(account)=&gt; {<br>    if (!account) return; <br>    const newBalance = await contract.methods.checkBalance(account).call(); <br>    setBalance(Number(newBalance));<br>  }<br><br><br><br><br><br>  return (<br>    &lt;div&gt;<br>      {/* &lt;div className=&quot;bg-black w-full py-[5px] text-white text-center&quot;&gt;<br>        Token Minter<br>      &lt;/div&gt; */}<br><br>      &lt;div className=&quot;flex justify-center items-center w-full mt-[20px]&quot;&gt;<br>        &lt;Image src={logo} alt=&quot;logo&quot; width={200} height={200} /&gt;<br>      &lt;/div&gt;<br><br>      {!account ? (<br>        &lt;div className=&quot;flex flex-col lg:flex-row gap-[30px] mt-[20px] px-[30px] border-2 min-h-[80vh] justify-center items-center&quot;&gt;<br>          &lt;Button className=&quot;!bg-black !text-white&quot; onClick={connectWallet}&gt;<br>            Connect Wallet<br>          &lt;/Button&gt;<br>        &lt;/div&gt;<br>      ) : (<br>        &lt;div className=&quot;flex flex-col lg:flex-row gap-[30px] mt-[20px] px-[30px] border-2 min-h-[80vh] justify-center items-center&quot;&gt;<br>          &lt;div className=&quot;rounded-[20px] border-[1px] border-gray-200 p-[24px] flex-1&quot;&gt;<br>            &lt;h1 className=&quot;text-[22px] font-bold&quot;&gt;Mint Token&lt;/h1&gt;<br>            &lt;div className=&quot;flex flex-col gap-[10px]&quot;&gt;<br>              &lt;Button className=&quot;!bg-black !text-white !h-[40px] !rounded-[16px]&quot; onClick={mintToken}&gt;<br>                Mint Token<br>              &lt;/Button&gt;<br>            &lt;/div&gt;<br>            &lt;h1 className=&quot;text-[22px] font-bold pt-4&quot;&gt;Burn Token&lt;/h1&gt;<br>            &lt;div className=&quot;flex flex-col gap-[10px]&quot;&gt;<br>              &lt;input<br>                style={{<br>                  borderRadius: 16,<br>                  height: 48,<br>                  backgroundColor: &#39;#F0F0F0&#39;,<br>                  textAlign: &#39;center&#39;,<br>                }}<br>                min={1}<br>                max={balance}<br>                placeholder=&quot;Amount&quot;<br>                onChange={({target})=&gt; inputValue({q: Number(target.value)})}<br>              /&gt;<br>              &lt;Button className=&quot;!bg-black !text-white !h-[40px] !rounded-[20px]&quot; onClick={burnToken}&gt;<br>                Burn Token<br>              &lt;/Button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;rounded-[20px] border-[1px] border-gray-200 p-[24px] flex-1 w-full&quot;&gt;<br>            &lt;h2 style={{color:&#39;blue&#39;}}&gt;&lt;b&gt;Account connected: &lt;/b&gt; {account}&lt;/h2&gt;<br>            &lt;Divider /&gt;<br>            &lt;h1 className=&quot;mb-[20px]&quot;&gt;Your Token Balance&lt;/h1&gt;<br>            &lt;div className=&quot;flex flex-col gap-[10px]&quot;&gt;<br>              &lt;div className=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;div className=&quot;flex items-center gap-[5px]&quot;&gt;<br>                  &lt;h1 className=&quot;text-[#A8A8A8] &quot; style={{ fontSize:&#39;63px&#39;}}&gt;{balance/10**18} {symbol}&lt;/h1&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>              &lt;Divider /&gt;<br>              &lt;Button onClick={connectWallet} &gt;refresh&lt;/Button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The code above is a React component named Home built using Next.js and Ant Design. It provides a user interface for interacting with an Ethereum-based smart contract, allowing users to connect their wallet, mint tokens, and burn tokens. Here&#39;s a detailed explanation of the code:</p><h3>Imports and Initial Setup</h3><ol><li><strong>Libraries and Resources</strong></li></ol><ul><li>use client;: Enables the use of client-side React features in this component.</li><li>logo: Imports a logo image from the project&#39;s public directory.</li><li>Button, Divider, InputNumber: Ant Design components for UI.</li><li>Image: A Next.js component for optimized image rendering.</li><li>web3 and contract: Imported custom modules for blockchain interactions.</li><li>useState: A React hook for managing state.</li></ul><p><strong>2. State Variables</strong></p><ul><li>account: Stores the connected wallet address.</li><li>balance: Stores the token balance of the connected wallet.</li><li>value: Stores the amount of tokens to burn.</li><li>symbol: Stores the token symbol retrieved from the smart contract.</li></ul><h3>Functions</h3><ol><li><strong>connectWallet</strong></li></ol><ul><li>Prompts the user to connect their Ethereum wallet.</li><li>Retrieves the connected account using web3.eth.requestAccounts.</li><li>Calls getBalance to fetch the token balance of the connected account.</li><li>Retrieves the token symbol from the smart contract using contract.methods.symbol().call().</li></ul><p>2.<strong>mintToken</strong></p><ul><li>Calls the mint method of the smart contract to mint tokens for the connected wallet.</li><li>Fetches the current gas price using web3.eth.getGasPrice.</li><li>Updates the token balance after minting by calling getBalance.</li></ul><p>3.<strong>inputValue</strong></p><ul><li>Updates the value state variable with the user&#39;s input.</li><li>Accepts an object { q } as an argument and assigns q to value.</li></ul><p>4.<strong>burnToken</strong></p><ul><li>Calls the burn method of the smart contract to burn a specified number of tokens.</li><li>Uses the value state as the amount to burn.</li><li>Updates the token balance after burning by calling getBalance.</li></ul><p>5. <strong>getBalance</strong></p><ul><li>Fetches the token balance of a specified account from the smart contract using contract.methods.checkBalance(account).call().</li><li>Converts the balance to a number and stores it in the balance state.</li></ul><h3>UI Design</h3><p>The component conditionally renders two sections based on whether the user is connected to a wallet:</p><ol><li><strong>Wallet Not Connected</strong></li></ol><ul><li>Displays a Connect Wallet button.</li><li>When clicked, it calls connectWallet.</li></ul><p>2. <strong>Wallet Connected</strong></p><p>A. Displays two sections:</p><p><strong>Mint and Burn Tokens</strong></p><ul><li>Allows the user to mint tokens by clicking the Mint Token button, which triggers mintToken.</li><li>Allows the user to input an amount and burn tokens by clicking the Burn Token button, which triggers burnToken.</li></ul><p><strong>Account Details</strong></p><ul><li>Shows the connected wallet address (account).</li><li>Displays the current token balance (balance) along with the token symbol (symbol).</li><li>Includes a Refresh button to manually update the wallet connection and balance.</li></ul><h3>Styles and Design Choices</h3><ul><li>The component uses Ant Design buttons (Button) for consistent styling.</li><li>It leverages Next.js Image for optimized logo rendering.</li><li>Custom styles:</li><li>Rounded corners for containers.</li><li>Input field styling for the token amount (centered text, background color, rounded edges).</li><li>Large font size for displaying the token balance.</li></ul><h3>Key Features</h3><ol><li><strong>Wallet Integration</strong></li></ol><ul><li>Uses web3 for blockchain interaction.</li><li>Detects and connects to the user’s Ethereum wallet.</li></ul><p>2. <strong>Smart Contract Interaction</strong></p><ul><li>Allows users to mint and burn tokens.</li><li>Retrieves and displays the user’s token balance in real-time.</li></ul><p>3. <strong>User-Friendly Interface</strong></p><ul><li>Clean and minimal design for easy interaction.</li><li>Responsive layout with support for different screen sizes.</li></ul><p>4. <strong>Error Handling</strong></p><ul><li>Includes try-catch blocks to handle errors during wallet connection, minting, and burning operations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bce0e9d6ddd1" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/how-to-integration-smart-contract-to-front-end-chapter-1-simple-dapps-for-miner-token-bce0e9d6ddd1">How To Integration Smart Contract to Front-end, Chapter 1: Simple Dapps for Miner Token</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 Your Own NFT(ERC-721) Marketplace on Ethereum Network with Solidity]]></title>
            <link>https://coinsbench.com/building-your-own-nft-erc-721-marketplace-on-ethereum-network-with-solidity-73c738a6a713?source=rss-515b7ab3c722------2</link>
            <guid isPermaLink="false">https://medium.com/p/73c738a6a713</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[erc-721-token-development]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Khoirul Aziz]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 10:13:24 GMT</pubDate>
            <atom:updated>2024-11-22T13:21:15.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bF6RapyM1QqmZooTmsLA7g.jpeg" /></figure><p>Hi there! in this tutorial we will learn about NFT (ERC-721) and how we can build our NFT Markerplace on the Ethereum network. check it dot!</p><h4>What is NFT (ERC-721) Smart Contract?</h4><p>NFT (Non-Fungible Token) is a unique digital asset that represents ownership or proof of authenticity of an item, which cannot be replaced or exchanged with other assets due to its distinct and unique nature. NFTs are typically built on blockchain platforms like Ethereum, using standards such as ERC-721 or ERC-1155.</p><h4>What difference between NFT (ERC-721) and ERC-20?</h4><p>The difference between <strong>ERC-20</strong> and <strong>ERC-721</strong> lies in their purpose and structure, as they are designed for different types of tokens on the Ethereum blockchain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*1UReumlZJj1Eq3trOerJGA.png" /></figure><p><em>Let’s start coding!</em></p><p><strong>1. Create contract and import ERC-721 from openzeppelin<br></strong>Firstly we should create a contract, determine pragma and import contract ERC-721 for openzeppelin</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.4;<br><br>import &quot;https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.3.2/contracts/token/ERC721/ERC721.sol&quot;;<br>import &quot;https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.3.2/contracts/access/Ownable.sol&quot;;<br><br>contract NFTBuku is ERC721, Ownable {<br><br><br>}</pre><p><strong>2. Defining Our Item Structure<br></strong>First, we need to define what an item looks like in our marketplace. We’ll create a structure called Book to hold all the details about what people are selling.</p><pre> struct Book {<br>        uint256 id;<br>        string name;<br>        string author;<br>        address authorAddress;<br>        uint256 totalSupply;<br>        uint256 price; <br>        uint256 initialRoyalty; <br>        uint256 resaleRoyalty;   <br>        uint256 transactionCount;<br>        mapping(address =&gt; uint256) ownedNFTs;<br>        mapping(address =&gt; uint256) resalePrices; <br>    }</pre><p><strong>3. Declaration of Variable and Event Tracing<br></strong>After that, continue to declare the required variables and events.</p><pre>    mapping(uint256 =&gt; Book) public books;<br>    mapping(uint256 =&gt; address[]) public bookOwners;<br><br>    event BookCreated(uint256 indexed id, string name, string author, address indexed authorAddress, uint256 totalSupply, uint256 price, uint256 initialRoyalty, uint256 resaleRoyalty);<br>    event NFTBought(uint256 indexed id, address indexed buyer);<br>    event NFTDonated(uint256 indexed id, address indexed from, address indexed to);<br>    event ResalePriceSet(uint256 indexed bookId, addres<br></pre><p>We use the books variable to store book data, while bookOwners records book ownership.<br>Then events are used to record activities that occur in a smart contract into the blockchain log. Events are very important because they allow smart contracts to communicate with applications running outside the blockchain (off-chain), such as decentralized applications (DApps) or backend servers, via transaction logs.</p><p><strong>4. Declaration of constructor<br></strong>Constructors are used to initialize initial values ​​in a contract, such as token names, symbols, or other settings.</p><pre>constructor() ERC721(&quot;GathbookNFT&quot;, &quot;GBOOK&quot;) {}</pre><p>The code above means that when the contract is deployed, our NFT token will be identified with the name “GathbookNFT” and with the symbol “GBOOK”</p><p><strong>5. Function to create books</strong><br>Now let’s create a function that allows users to enter their book list</p><pre> function createBook(<br>        uint256 bookId,<br>        string memory name,<br>        string memory author,<br>        address authorAddress,<br>        uint256 totalSupply,<br>        uint256 price,<br>        uint256 initialRoyalty,<br>        uint256 resaleRoyalty<br>    ) external onlyOwner {<br>        require(books[bookId].id == 0, &quot;Book ID already exists&quot;);<br>        require(initialRoyalty &lt;= 100, &quot;Initial royalty must be between 0 and 100&quot;);<br>        require(resaleRoyalty &lt;= 100, &quot;Resale royalty must be between 0 and 100&quot;);<br><br>        Book storage newBook = books[bookId];<br>        newBook.id = bookId;<br>        newBook.name = name;<br>        newBook.author = author;<br>        newBook.authorAddress = authorAddress;<br>        newBook.totalSupply = totalSupply;<br>        newBook.price = price; <br>        newBook.initialRoyalty = initialRoyalty; <br>        newBook.resaleRoyalty = resaleRoyalty; <br>        newBook.transactionCount = 0;<br><br>        emit BookCreated(bookId, name, author, authorAddress, totalSupply, price, initialRoyalty, resaleRoyalty); <br>    }</pre><p><strong>Explanation:</strong><br><strong>a.</strong> The <strong>createBook(...)</strong>function has 8 parameters to receive input from the user regarding the details of the book they want to add. <br><strong>b.</strong> Then there is <strong>external</strong> visibility <strong>onlyOwner</strong> which means this function can only be called from outside the contract and only the owner can use this function. <br><strong>c. </strong>Inside the function there is a <strong>require()</strong> method which is used to validate whether the desired conditions are met or not.<br><strong>d.</strong> <strong>Book storage newBook=books[bookId]</strong> in this section we create a variable newBook ​​with the data type struct <strong>Book</strong> Then we make the storage location point to <strong>storage</strong> because we want to store the book data permanently on the blockchain. We create<strong>books[bookId]</strong> to initialize the data reference<br><strong>e. </strong>Method<strong> </strong><strong>emit(...) </strong>useful for recording every activity in the function <strong>createBook().</strong></p><p><strong>6. Function to buy NFT<br></strong>Then, let’s create function <strong>buyNFT() </strong>for buy NFT in smart contract witch we create.</p><pre>uint256 private tokenCounter = 0; <br><br>    function buyNFT(uint256 bookId) external payable {<br>        Book storage book = books[bookId];<br>        require(book.price &gt; 0, &quot;Price not set for this NFT&quot;);<br>        require(msg.value &gt;= book.price, &quot;Insufficient funds to buy the NFT&quot;);<br>        require(book.totalSupply &gt; 0, &quot;No supply available&quot;);<br><br>        uint256 tokenId = tokenCounter + bookId; <br>        tokenCounter++;<br><br>        _mint(msg.sender, tokenId);<br>        book.ownedNFTs[msg.sender]++;<br>        book.transactionCount++;<br>        book.totalSupply--;<br><br>        uint256 royaltyAmount = (book.price * book.initialRoyalty) / 100;<br>        payable(book.authorAddress).transfer(royaltyAmount);<br>        <br>        if (bookOwners[bookId].length == 0 || bookOwners[bookId][bookOwners[bookId].length - 1] != msg.sender) {<br>            bookOwners[bookId].push(msg.sender);<br>        }<br><br>        emit NFTBought(bookId, msg.sender);<br>    }<br><br></pre><p><strong>Explanation:<br>a.</strong> The variable <strong>takeCounter </strong>have we initialize for give any NFT a index number.<br><strong>b.</strong> The <strong>buyNFT(...)</strong>function has 1parameters to receive input from the user for choosing which NFT to buy by id.<br><strong>c. </strong>Method <strong>_mint(msg.sender, tokenId) </strong>will print a new token that will be sent to the<strong>msg.sender</strong>with each different <strong>tokenId <br>d. </strong><strong>book.ownedNFTs[msg.sender]++ t</strong>his is used to record the number of NFT books owned by a user&#39;s address after they have purchased or received NFTs.<br><strong>f. </strong><strong>book.transactionCount++ </strong>this used to record how many times this NFT has experienced a transaction.<br><strong>g. </strong><strong>totalSuply- - </strong>this used to reduces the total supply of this NFT book which is set when the book is created.</p><p><strong>7. Function to buy resale NFT<br></strong>Now, we create a function to resale NFT.</p><pre>function buyResaleNFT(uint256 bookId, address owner) external payable {<br>        uint256 resalePrice = books[bookId].resalePrices[owner];<br>        require(resalePrice &gt; 0, &quot;This NFT is not for sale&quot;);<br>        require(msg.value &gt;= resalePrice, &quot;Insufficient funds to buy the resale NFT&quot;);<br><br>        _transfer(owner, msg.sender, bookId);<br>        books[bookId].ownedNFTs[owner]--;<br>        books[bookId].ownedNFTs[msg.sender]++;<br><br>        uint256 resaleRoyaltyAmount = (resalePrice * books[bookId].resaleRoyalty) / 100; <br>        payable(books[bookId].authorAddress).transfer(resaleRoyaltyAmount);<br><br>        payable(owner).transfer(msg.value - resaleRoyaltyAmount); <br>        books[bookId].transactionCount++;<br><br>        emit NFTBought(bookId, msg.sender);<br>    }</pre><p><strong>Explanation:<br>a. </strong>Function <strong>buyResaleNFT(...) </strong>have 2 parameters yaitu parameter bookId dan owner<br><strong>b. </strong>There is function <strong>_transfer </strong>for transfer the ownership of NFTs from the old owner (<strong>owner</strong>) to the new buyer (<strong>msg.sender</strong>) and update the ownership data in the mapping <strong>ownedNFTs</strong>.<br><strong>c. </strong><strong>payable(books[bookId].authorAddress).transfer(resaleRoyaltyAmount);</strong> This section ensures that the author still gets royalties from transactions that have occurred.<br><strong>d. </strong>And then <strong>payable(owner).transfer(msg.value — resaleRoyaltyAmount) </strong>balance transfering to old owner.<br><strong>e. </strong>The transaction recorded <br><strong>f. </strong>The new owner is updated</p><p><strong>8. Function to donate NFT<br></strong>Let’s create a fucntion for donate NFT. The function used if owner want to danate NFT</p><pre> function donateNFT(uint256 bookId, address to) external {<br>        require(_isApprovedOrOwner(msg.sender, bookId), &quot;Not the owner or approved&quot;);<br><br>        _transfer(msg.sender, to, bookId);<br>        books[bookId].ownedNFTs[msg.sender]--;<br>        books[bookId].ownedNFTs[to]++;<br><br>        emit NFTDonated(bookId, msg.sender, to);<br>    }</pre><p><strong>Explanation:<br>a. </strong><strong>_isApprovedOwner(msg.sender, bookId), &quot;Not the owner or approved&quot;</strong> For checking whether the user is the owner or has permission from the owner.<br><strong>b. </strong><strong>_transfer()</strong> To make an NFT transfer to the address to be donated.<br><strong>c.</strong> The line <strong>books[bookId].ownedNFTs[msg.sender]--;</strong> serves to <strong>reduce the number of NFTs</strong> owned by <strong>msg.sender</strong> (the current owner) for a specific book with ID <strong>bookId</strong>.<br><strong>d. </strong>The line <strong>books[bookId].ownedNFTs[to]++;</strong> is used to add the number of NFTs owned by the receiving address (<strong>to</strong>) for the book with the specified ID (<strong>bookId</strong>).<br><strong>e.</strong>The <strong>emit NFTDonated(bookId, msg.sender, to);</strong> line is used to <strong>record an event</strong> on the blockchain when an NFT is donated or transferred from one address to another.</p><p><strong>9. Function to determine resale price NFT</strong></p><pre>function setResalePrice(uint256 bookId, uint256 price) external {<br>        require(_isApprovedOrOwner(msg.sender, bookId), &quot;Not the owner or approved&quot;);<br>        require(books[bookId].ownedNFTs[msg.sender] &gt; 0, &quot;You don&#39;t own this NFT&quot;);<br><br>        books[bookId].resalePrices[msg.sender] = price;<br>        emit ResalePriceSet(bookId, msg.sender, price);<br><br>    }</pre><p><strong>Explanation:<br>a. </strong>The <strong>books[bookId].resalePrices[msg.sender] = price;</strong> line is used to <strong>record the resale price</strong> set by the NFT owner for a particular book.</p><p><strong>10. Function to cancel resale price NFT</strong></p><pre>function cancelResalePrice(uint256 bookId) external {<br>        require(_isApprovedOrOwner(msg.sender, bookId), &quot;Not the owner or approved&quot;);<br>        require(books[bookId].ownedNFTs[msg.sender] &gt; 0, &quot;You don&#39;t own this NFT&quot;);<br><br>        books[bookId].resalePrices[msg.sender] = 0; <br>    }</pre><p><strong>Explanation:<br></strong>This <strong>cancelResalePrice(uint256 bookId)</strong> function is used to cancel or delete the resale price of an NFT that was previously set by the owner. <strong>books[bookId].resalePrices[msg.sender] = 0;</strong> is used to delete or cancel the resale price previously set by the NFT owner for a book with a specific ID.</p><p><strong>11. Function to get or view resale price NFT</strong></p><pre> function getResalePrice(uint256 bookId, address owner) external view returns (uint256) {<br>        return books[bookId].resalePrices[owner];<br>    }</pre><p>Fungsi <strong>getResalePrice(uint256 bookId, address owner)</strong> ini digunakan untuk <strong>mengambil atau melihat harga jual kembali (resale price)</strong> dari sebuah NFT yang dimiliki oleh seorang <strong>owner</strong> untuk buku tertentu dengan ID <strong>bookId</strong>. Fungsi ini bersifat <strong>view</strong>, yang artinya hanya membaca data tanpa mengubahnya di blockchain.</p><p><strong>12. Function to get detail info about NFT<br></strong>We have come to the end of this tutorial, we will create a function to view the details of the NFT.</p><pre>function getNFTPurchaseInfo(uint256 bookId) external view returns (uint256 purchased, uint256 totalSupply) {<br>        Book storage book = books[bookId];<br>        uint256 totalPurchased = book.transactionCount;  <br>        uint256 totalBookSupply = book.totalSupply + book.transactionCount;  <br><br>        return (totalPurchased, totalBookSupply);<br>    }</pre><p>The <strong>getNFTPurchaseInfo(uint256 bookId)</strong> function is used to retrieve purchase-related information about NFTs from a book (identified by <strong>bookId</strong>). This function returns two key pieces of information:</p><ol><li>The number of NFTs that have been sold (<strong>totalPurchased</strong>).</li><li>The total number of NFTs supplied (<strong>totalSupply</strong>), including those that have been sold.</li></ol><p>Full code</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.4;<br><br>import &quot;https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.3.2/contracts/token/ERC721/ERC721.sol&quot;;<br>import &quot;https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.3.2/contracts/access/Ownable.sol&quot;;<br><br>contract NFTBuku is ERC721, Ownable {<br>    struct Book {<br>        uint256 id;<br>        string name;<br>        string author;<br>        address authorAddress;<br>        uint256 totalSupply;<br>        uint256 price; <br>        uint256 initialRoyalty; <br>        uint256 resaleRoyalty;   <br>        uint256 transactionCount;<br>        mapping(address =&gt; uint256) ownedNFTs;<br>        mapping(address =&gt; uint256) resalePrices; <br>    }<br><br>    mapping(uint256 =&gt; Book) public books;<br>    mapping(uint256 =&gt; address[]) public bookOwners;<br><br>    event BookCreated(uint256 indexed id, string name, string author, address indexed authorAddress, uint256 totalSupply, uint256 price, uint256 initialRoyalty, uint256 resaleRoyalty);<br>    event NFTBought(uint256 indexed id, address indexed buyer);<br>    event NFTDonated(uint256 indexed id, address indexed from, address indexed to);<br>    event ResalePriceSet(uint256 indexed bookId, address indexed owner, uint256 price);<br><br>    constructor() ERC721(&quot;GathbookNFT&quot;, &quot;GBOOK&quot;) {}<br><br>    function createBook(<br>        uint256 bookId,<br>        string memory name,<br>        string memory author,<br>        address authorAddress,<br>        uint256 totalSupply,<br>        uint256 price,<br>        uint256 initialRoyalty,<br>        uint256 resaleRoyalty<br>    ) external onlyOwner {<br>        require(books[bookId].id == 0, &quot;Book ID already exists&quot;);<br>        require(initialRoyalty &lt;= 100, &quot;Initial royalty must be between 0 and 100&quot;);<br>        require(resaleRoyalty &lt;= 100, &quot;Resale royalty must be between 0 and 100&quot;);<br><br>        Book storage newBook = books[bookId];<br>        newBook.id = bookId;<br>        newBook.name = name;<br>        newBook.author = author;<br>        newBook.authorAddress = authorAddress;<br>        newBook.totalSupply = totalSupply;<br>        newBook.price = price; <br>        newBook.initialRoyalty = initialRoyalty; <br>        newBook.resaleRoyalty = resaleRoyalty; <br>        newBook.transactionCount = 0;<br><br>        emit BookCreated(bookId, name, author, authorAddress, totalSupply, price, initialRoyalty, resaleRoyalty); <br>    }<br><br>    uint256 private tokenCounter = 0; <br><br>    function buyNFT(uint256 bookId) external payable {<br>        Book storage book = books[bookId];<br>        require(book.price &gt; 0, &quot;Price not set for this NFT&quot;);<br>        require(msg.value &gt;= book.price, &quot;Insufficient funds to buy the NFT&quot;);<br>        require(book.totalSupply &gt; 0, &quot;No supply available&quot;);<br><br>        uint256 tokenId = tokenCounter + bookId; <br>        tokenCounter++;<br><br>        _mint(msg.sender, tokenId);<br>        book.ownedNFTs[msg.sender]++;<br>        book.transactionCount++;<br>        book.totalSupply--;<br><br>        uint256 royaltyAmount = (book.price * book.initialRoyalty) / 100;<br>        payable(book.authorAddress).transfer(royaltyAmount);<br>        <br>        if (bookOwners[bookId].length == 0 || bookOwners[bookId][bookOwners[bookId].length - 1] != msg.sender) {<br>            bookOwners[bookId].push(msg.sender);<br>        }<br><br>        emit NFTBought(bookId, msg.sender);<br>    }<br><br>    function buyResaleNFT(uint256 bookId, address owner) external payable {<br>        uint256 resalePrice = books[bookId].resalePrices[owner];<br>        require(resalePrice &gt; 0, &quot;This NFT is not for sale&quot;);<br>        require(msg.value &gt;= resalePrice, &quot;Insufficient funds to buy the resale NFT&quot;);<br><br>        _transfer(owner, msg.sender, bookId);<br>        books[bookId].ownedNFTs[owner]--;<br>        books[bookId].ownedNFTs[msg.sender]++;<br><br>        uint256 resaleRoyaltyAmount = (resalePrice * books[bookId].resaleRoyalty) / 100; <br>        payable(books[bookId].authorAddress).transfer(resaleRoyaltyAmount);<br><br>        payable(owner).transfer(msg.value - resaleRoyaltyAmount); <br>        books[bookId].transactionCount++;<br><br>        emit NFTBought(bookId, msg.sender);<br>    }<br><br>    function donateNFT(uint256 bookId, address to) external {<br>        require(_isApprovedOrOwner(msg.sender, bookId), &quot;Not the owner or approved&quot;);<br><br><br>        _transfer(msg.sender, to, bookId);<br>        books[bookId].ownedNFTs[msg.sender]--;<br>        books[bookId].ownedNFTs[to]++;<br><br>        emit NFTDonated(bookId, msg.sender, to);<br>    }<br><br>    function setResalePrice(uint256 bookId, uint256 price) external {<br>        require(_isApprovedOrOwner(msg.sender, bookId), &quot;Not the owner or approved&quot;);<br>        require(books[bookId].ownedNFTs[msg.sender] &gt; 0, &quot;You don&#39;t own this NFT&quot;);<br><br>        books[bookId].resalePrices[msg.sender] = price;<br>        emit ResalePriceSet(bookId, msg.sender, price);<br><br>    }<br><br><br>    function cancelResalePrice(uint256 bookId) external {<br>        require(_isApprovedOrOwner(msg.sender, bookId), &quot;Not the owner or approved&quot;);<br>        require(books[bookId].ownedNFTs[msg.sender] &gt; 0, &quot;You don&#39;t own this NFT&quot;);<br><br>        books[bookId].resalePrices[msg.sender] = 0; <br>    }<br><br>    function getResalePrice(uint256 bookId, address owner) external view returns (uint256) {<br>        return books[bookId].resalePrices[owner];<br>    }<br><br>    function getNFTPurchaseInfo(uint256 bookId) external view returns (uint256 purchased, uint256 totalSupply) {<br>        Book storage book = books[bookId];<br>        uint256 totalPurchased = book.transactionCount;  <br>        uint256 totalBookSupply = book.totalSupply + book.transactionCount;  <br><br>        return (totalPurchased, totalBookSupply);<br>    }<br><br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73c738a6a713" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/building-your-own-nft-erc-721-marketplace-on-ethereum-network-with-solidity-73c738a6a713">Building Your Own NFT(ERC-721) Marketplace on Ethereum Network with 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[Enhancement of the OnlineShop Contract: Transitioning Transactions from Ether to ERC-20 Tokens]]></title>
            <link>https://coinsbench.com/enhancement-of-the-onlineshop-contract-transitioning-transactions-from-ether-to-erc-20-tokens-21702ae8d613?source=rss-515b7ab3c722------2</link>
            <guid isPermaLink="false">https://medium.com/p/21702ae8d613</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Khoirul Aziz]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 04:42:22 GMT</pubDate>
            <atom:updated>2024-10-31T18:24:29.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLpXubJlme8u0OeeOdq-Iw.jpeg" /></figure><p>In the world of blockchain and decentralized applications (dApps), the shift from Ether-based transactions to token-based transactions introduces a new layer of flexibility, scalability, and economic control for developers. In this article, we’ll explore the step-by-step upgrade of a simple smart contract, <strong>OnlineShop</strong>, to a more advanced version that no longer relies on Ether for transactions but instead uses a custom ERC-20 token, <strong>MyCoin</strong>.</p><p>We’ll walk through the benefits of this transition, examine the added features and improvements, and provide insights on best practices in smart contract design.</p><h3>Introduction to the Original Online Shop Contract</h3><p>Our original OnlineShop contract was a straightforward marketplace where users could add and buy items. Transactions were based on Ether, which made it simple yet limited, as it didn&#39;t allow the contract owner to manage a custom economy within the contract. Here&#39;s a quick look at the main functions of this initial contract:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity &gt;=0.7.0 &lt;0.9.0;<br><br>contract OnlineShop {<br>    <br>   struct Item {<br>       uint id;<br>       string name;<br>       uint price;<br>       address owner;<br>   }<br><br>   Item[] public items;<br>   uint idItem;<br><br>   mapping(address =&gt; uint) balance;<br><br>   event addItem(uint id, string name, uint price, address owner);<br>   event buyItem(uint id, address newOwner, uint price);<br><br>   function add(string memory _name, uint _price) public {<br>       items.push(Item(idItem, _name, _price, msg.sender));<br>       emit addItem(idItem, _name, _price, msg.sender);<br>       idItem++;<br>   }<br><br>   function buy(uint _id) public payable {<br>       Item storage item = items[_id];<br><br>       require(item.price &lt;= msg.value, &quot;Insufficient Ether sent&quot;);<br>       require(item.owner != msg.sender, &quot;You cannot buy your own item&quot;);<br>       require(item.owner != address(0), &quot;Item has already been sold&quot;);<br><br>       balance[item.owner] += item.price;<br><br>       item.owner = msg.sender;<br><br>       emit buyItem(_id, msg.sender, item.price);<br>   }<br><br>   function getBalance() public view returns (uint) {<br>       return balance[msg.sender];<br>   }<br><br>   function withdraw(uint _amount) public payable {<br>       require(balance[msg.sender] &gt;= _amount, &quot;You do not have enough Ether&quot;);<br>       payable(msg.sender).transfer(_amount);<br>   }<br>}</pre><h3>Upgrading the Contract: Key Improvements</h3><p>In the upgraded version, we transitioned to an ERC-20 token-based model. This change introduces several advantages and builds a robust economy within the dApp, allowing the contract owner to issue and control <strong>MyCoin</strong>. Here are the significant enhancements:</p><ol><li><strong>ERC-20 Token Integration</strong>:</li></ol><ul><li>By implementing ERC-20 from OpenZeppelin, we created <strong>MyCoin</strong>, the custom token for all transactions in the OnlineShop.</li><li>The contract mints <strong>1 million tokens</strong> to the owner upon deployment, enabling initial liquidity and control over the token supply.</li></ul><p>2. <strong>Token Purchase Functionality</strong>:</p><ul><li>Instead of users paying with Ether directly, they can now buy <strong>MyCoin</strong> tokens using Ether via the buyCoin() function.</li><li>We set a token price of <strong>0.005 Ether</strong> for each MyCoin, allowing for simple conversions between Ether and MyCoin within the contract.</li></ul><p><strong>3. Enhanced Buy and Withdraw Functions</strong>:</p><ul><li>The buy() function has been modified to require <strong>MyCoin</strong> tokens instead of Ether. Buyers can now use MyCoin to purchase items directly, promoting a tokenized economy within the OnlineShop.</li><li>After each sale, the seller’s MyCoin balance is updated, and they can withdraw their accumulated tokens via the withdraw() function.</li></ul><h3>Detailed Breakdown of the Upgraded Contract</h3><p>Let’s go through the main sections and their significance in this transition:</p><h4>1. ERC-20 Token Minting with buyCoin()</h4><p>With the buyCoin() function, we allow users to convert Ether into MyCoin. Here’s how it works:</p><pre>function buyCoin() public payable {<br>    require(msg.sender != owner(), &quot;You are the owner, no need to buy tokens&quot;);<br>    require(msg.value &gt;= tokenPrice, &quot;Insufficient Ether sent&quot;);<br><br>    uint amountToBuy = (msg.value * 10 ** decimals()) / tokenPrice;<br>    _mint(msg.sender, amountToBuy);<br>}</pre><p>This function:</p><ul><li>Ensures only non-owners can buy tokens.</li><li>Mints the correct amount of MyCoin for the Ether provided.</li><li>Provides liquidity for users to engage with the marketplace.</li></ul><h4>2. Enhanced buy() Function Using MyCoin</h4><p>In the original contract, buyers used Ether to purchase items. Now, we use tokens:</p><pre>function buy(uint _id) public {<br>    Item storage item = items[_id];<br><br>    require(item.price &lt;= balanceOf(msg.sender), &quot;Insufficient tokens sent&quot;);<br>    require(item.owner != msg.sender, &quot;You cannot buy your own item&quot;);<br>    require(item.owner != address(0), &quot;Item has already been sold&quot;);<br><br>    _transfer(msg.sender, address(this), item.price);<br>    balances[item.owner] += item.price;<br>    item.owner = msg.sender;<br><br>    emit BuyItem(_id, msg.sender, item.price);<br>}</pre><p>In this function:</p><ul><li>We confirm the buyer has enough MyCoin to cover the item price.</li><li>The tokens are transferred to the contract itself, and the seller’s balance is updated.</li><li>Finally, the item ownership transfers to the buyer.</li></ul><h4>3. Withdraw Function for MyCoin Balance</h4><p>Sellers can withdraw their token balance after a sale. Here’s how the withdraw() function looks:</p><pre>function withdraw() public {<br>    require(balances[msg.sender] &gt; 0, &quot;No balance to withdraw&quot;);<br><br>    uint amount = balances[msg.sender];<br>    balances[msg.sender] = 0;<br>    _transfer(address(this), msg.sender, amount);<br>}</pre><p>This function:</p><ul><li>Ensures the user has a positive balance before allowing withdrawal.</li><li>Transfers the MyCoin balance from the contract to the seller.</li></ul><h3>Benefits of Tokenizing the Marketplace</h3><ol><li><strong>Liquidity Control</strong>: With tokenization, the contract owner controls the initial supply and can monitor the token economy within the OnlineShop.</li><li><strong>Better User Incentives</strong>: Custom tokens can enable loyalty programs, discounts, and other incentives.</li><li><strong>Economic Flexibility</strong>: By using MyCoin, we can further build a decentralized economy with staking, rewards, or even token-burning mechanisms.</li></ol><h3>Final Thoughts: The Power of ERC-20 in Decentralized Marketplaces</h3><p>Transitioning from Ether-based transactions to an ERC-20 token model in our <strong>OnlineShop</strong> contract represents a significant step toward a robust and flexible dApp economy. This shift opens doors for further development, such as integrating staking, automated liquidity pools, or cross-platform compatibility, which would be challenging in an Ether-only model.</p><p>In conclusion, upgrading the <strong>OnlineShop</strong> with ERC-20 not only enhances its functionality but also prepares the marketplace for scalability and flexibility in the ever-evolving blockchain ecosystem. This evolution is just one example of how dApps can harness tokenization to create custom, sustainable economies that foster user engagement and growth.</p><h3>Full Code of the Upgraded Contract</h3><p>Here’s the complete code for the upgraded <strong>OnlineShop</strong> contract using ERC-20 tokens:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity &gt;=0.7.0 &lt;0.9.0;<br><br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract OnlineShop is Ownable, ERC20 {  <br>   struct Item {<br>    uint id;<br>    string name;<br>    uint price;<br>    address owner;<br>   }<br><br>   Item[] public  items;<br>   uint idItem;<br>   mapping(address =&gt; uint) balances;<br><br>   uint public constant tokenPrice = 0.005 ether;<br><br>   event AddItem(uint id, string name, uint price, address owner);<br>   event BuyItem(uint id, address newOwner, uint price);<br><br>   constructor() ERC20(&quot;MyCoin&quot;, &quot;MYC&quot;) Ownable(msg.sender){<br>    _mint(msg.sender, 1000000 * 10 ** decimals());<br><br>   }<br><br><br>   function buyCoin() public payable   {<br>    require(msg.sender != owner(), &quot;You are owner&quot;);<br>    require(msg.value &gt;= tokenPrice, &quot;Insufficient ether sent&quot;);<br>    <br>    uint amountToBuy = (msg.value * 10 ** decimals()) / tokenPrice;<br>      _mint(msg.sender, amountToBuy);<br><br>   }<br><br><br>   function add(string memory _name, uint _price) public {<br>      items.push(Item(idItem, _name, _price, msg.sender));<br>      emit AddItem(idItem, _name, _price, msg.sender);<br>      idItem++;<br>      <br>   }<br><br>   function buy(uint _id) public {<br>    Item storage item = items[_id];<br><br>    require(item.price &lt;= balanceOf(msg.sender), &quot;Insufficient token sent&quot;);<br>    require(item.owner != msg.sender, &quot;You cannot buy your own item&quot;);<br>    require(item.owner != address(0), &quot;Item has already been sold&quot;);<br><br>    _transfer(msg.sender, address(this), item.price);<br>    balances[item.owner] += item.price;<br>    item.owner = msg.sender;<br><br>    emit BuyItem(_id, msg.sender, item.price);<br>}<br><br>    <br>      function getBalance() public view returns (uint) {<br>            return balances[msg.sender];<br>     }<br><br>     function withdraw() public {<br>        require(balances[msg.sender] &gt; 0, &quot;No balance to withdraw&quot;);<br><br>        balances[msg.sender] = 0;<br>        _transfer(address(this), msg.sender, balances[msg.sender]);<br>        <br>     }<br><br><br>}</pre><p>Thankyou :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21702ae8d613" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/enhancement-of-the-onlineshop-contract-transitioning-transactions-from-ether-to-erc-20-tokens-21702ae8d613">Enhancement of the OnlineShop Contract: Transitioning Transactions from Ether to ERC-20 Tokens</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 Your Own “OnlineShop” Smart Contract with Solidity]]></title>
            <link>https://coinsbench.com/building-your-own-onlineshop-smart-contract-with-solidity-11e0f2503924?source=rss-515b7ab3c722------2</link>
            <guid isPermaLink="false">https://medium.com/p/11e0f2503924</guid>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Khoirul Aziz]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 11:38:20 GMT</pubDate>
            <atom:updated>2024-10-22T05:44:46.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CvkDi2vEEFvgXziutjmxg.jpeg" /></figure><p>Hey there! Welcome to this tutorial on building a smart contract for a marketplace called “OnlineShop.” This contract will allow users to add items, buy them, and withdraw their earnings. Let’s break it down step by step!</p><h3>1. What’s a Smart Contract Anyway?</h3><p>A smart contract is like a digital agreement that runs on the blockchain. It automates transactions and ensures everything is secure and transparent. Today, we’ll create a contract that allows users to:</p><ul><li>Add items to the marketplace.</li><li>Buy items from other users.</li><li>Withdraw their earnings from sales.</li></ul><h3>2. Defining Our Item Structure</h3><p>First, we need to define what an item looks like in our marketplace. We’ll create a structure called Item to hold all the details about what people are selling.</p><pre>struct Item {<br>    uint id;<br>    string name;<br>    uint price;<br>    address owner;<br>}</pre><ul><li><strong>struct Item</strong>: This defines a new data type called Item.</li><li><strong>uint id</strong>: This is a unique identifier for each item. We’ll use this to distinguish one item from another.</li><li><strong>string name</strong>: This will hold the name of the item (e.g., &quot;Bicycle&quot;).</li><li><strong>uint price</strong>: This represents the price of the item in Ether.</li><li><strong>address owner</strong>: This holds the Ethereum address of the person who currently owns the item.</li></ul><h3>3. Setting Up Our Variables</h3><p>Now, let’s set up some variables that we’ll use throughout our contract.</p><pre>Item[] public items; // This array will hold all the items<br>uint idItem; // This will keep track of the next item ID<br>mapping(address =&gt; uint) balance; // This will track user balances</pre><ul><li><strong>Item[] public items</strong>: This creates a dynamic array that stores all the items added to the marketplace. The public keyword allows anyone to access this array.</li><li><strong>uint idItem</strong>: This variable acts as a counter for the item IDs, ensuring that each item has a unique ID.</li><li><strong>mapping(address =&gt; uint) balance</strong>: This creates a mapping that keeps track of how much Ether each user has earned from their sales.</li></ul><h3>4. Adding Events to Keep Track</h3><p>To monitor important actions within our contract, we’ll define some events.</p><pre>event addItem(uint id, string name, uint price, address owner);<br>event buyItem(uint id, address newOwner, uint price);</pre><ul><li><strong>event addItem(...)</strong>: This event is triggered when a new item is added to the marketplace. It includes the item&#39;s ID, name, price, and the owner&#39;s address.</li><li><strong>event buyItem(...)</strong>: This event is triggered whenever an item is purchased. It includes the item&#39;s ID, the new owner&#39;s address, and the purchase price.</li></ul><h3>5. Function to Add Items</h3><p>Now, let’s create a function that allows users to add items to the marketplace.</p><pre>function add(string memory _name, uint _price) public {<br>    items.push(Item(idItem, _name, _price, msg.sender));<br>    emit addItem(idItem, _name, _price, msg.sender);<br>    idItem++;<br>}</pre><h3>Breaking It Down:</h3><ul><li><strong>function add(...)</strong>: This is the function declaration. It takes two parameters:</li><li><strong>string memory _name</strong>: The name of the item being added.</li><li><strong>uint _price</strong>: The price of the item in Ether.</li><li><strong>public</strong>: This means anyone can call this function.</li><li><strong>items.push(...)</strong>: This adds a new Item to the items array. We create a new Item object with the following:</li><li><strong>idItem</strong>: The current ID for the item.</li><li><strong>_name</strong>: The name of the item provided by the user.</li><li><strong>_price</strong>: The price provided by the user.</li><li><strong>msg.sender</strong>: The address of the person adding the item (the current owner).</li><li><strong>emit addItem(...)</strong>: This triggers the addItem event to log that a new item has been added.</li><li><strong>idItem++</strong>: We increment the item ID for the next item that will be added.</li></ul><h3>6. Function to Buy Items</h3><p>Next, let’s create the function that allows users to buy items.</p><pre>function buy(uint _id) public payable {<br>    Item storage item = items[_id];<br><br>    require(item.price &lt;= msg.value, &quot;Insufficient Ether sent&quot;);<br>    require(item.owner != msg.sender, &quot;You cannot buy your own item&quot;);<br>    require(item.owner != address(0), &quot;Item has already been sold&quot;);<br><br>    balance[item.owner] += msg.value;<br><br>    item.owner = msg.sender;<br><br>    emit buyItem(_id, msg.sender, item.price);<br>}</pre><h3>Breaking It Down:</h3><h4>Step 1: Accepting Ether with payable</h4><ul><li>The buy function has the payable keyword, which means it can accept Ether. This is crucial because the user must send Ether to the smart contract to buy the item.</li></ul><h4>Step 2: Fetching the Item</h4><ul><li>The line Item storage item = items[_id]; retrieves the item from the items mapping, where all the items in the marketplace are stored. The _id is passed as an argument to identify which item is being purchased.</li></ul><h4>Step 3: Checking Valid Conditions (require statements)</h4><ul><li>Before proceeding with the purchase, the function checks for three conditions using require statements:</li></ul><ol><li><strong>require(item.price &lt;= msg.value, &quot;Insufficient Ether sent&quot;);</strong></li></ol><ul><li>This checks whether the buyer has sent enough Ether to cover the price of the item. If the buyer sends less than the price, the transaction fails, and the error message “Insufficient Ether sent” is shown.</li></ul><p>2. <strong>require(item.owner != msg.sender, &quot;You cannot buy your own item&quot;);</strong></p><ul><li>This ensures that the buyer cannot purchase an item they already own, as the buyer’s address cannot match the current owner’s address.</li></ul><p>3. <strong>require(item.owner != address(0), &quot;Item has already been sold&quot;);</strong></p><ul><li>This checks that the item has not already been sold (i.e., its owner address is not address(0), which might represent an invalid or sold item). This prevents double purchases.</li></ul><h4>Step 4: Storing Ether in the Smart Contract Balance</h4><ul><li><strong>balance[item.owner] += msg.value;</strong></li><li>Instead of sending Ether directly to the seller, the Ether is stored in a balance mapping, which keeps track of how much Ether the seller has accumulated from selling their items. The seller will later withdraw this amount using a separate function, usually called withdraw.</li></ul><h4>Step 5: Transferring Ownership of the Item</h4><ul><li><strong>item.owner = msg.sender;</strong></li><li>The ownership of the item is transferred to the buyer (msg.sender). This effectively finalizes the sale by updating the item’s ownership information.</li></ul><h4>Step 6: Emitting an Event</h4><ul><li><strong>emit buyItem(_id, msg.sender, item.price);</strong></li><li>The buyItem event is emitted, signaling that an item has been successfully purchased. This is useful for tracking purchases off-chain (for example, in a frontend application) without having to scan the entire blockchain. Events are logged and can be listened to by external applications.</li></ul><h3>7. Function to Check User Balance</h3><p>We want users to be able to check how much Ether they have earned. Let’s add a function for that:</p><pre>function getBalance() public view returns (uint) {<br>    return balance[msg.sender];<br>}</pre><h3>Breaking It Down:</h3><ul><li><strong>function getBalance() public view returns (uint)</strong>: This function allows users to see their balance.</li><li><strong>public</strong>: Anyone can call this function.</li><li><strong>view</strong>: This indicates that the function does not modify the state of the contract.</li><li><strong>returns (uint)</strong>: The function returns a uint, which is the user&#39;s balance.</li><li><strong>return balance[msg.sender];</strong>: This line retrieves and returns the balance of the person calling the function.</li></ul><h3>8. Function to Withdraw Ether</h3><p>Finally, let’s create a function that allows users to withdraw their earnings.</p><pre>function withdraw(uint _amount) public payable {<br>    require(balance[msg.sender] &gt;= _amount, &quot;You do not have enough ether&quot;);<br>    payable(msg.sender).transfer(_amount);<br>}</pre><h3>Breaking It Down:</h3><ul><li><strong>function withdraw(...)</strong>: This function allows users to withdraw a specified amount of Ether.</li><li><strong>uint _amount</strong>: The amount of Ether the user wants to withdraw.</li><li><strong>public payable</strong>: This means anyone can call this function and they must send Ether with it.</li><li><strong>require(balance[msg.sender] &gt;= _amount, &quot;You do not have enough ether&quot;);</strong>: This checks if the user has enough balance to withdraw the specified amount. If not, it throws an error with the message &quot;You do not have enough ether.&quot;</li><li><strong>payable(msg.sender).transfer(_amount);</strong>: This sends the specified amount of Ether to the user who called the function.</li></ul><h3>9. Wrap-Up</h3><p>And there you have it! We’ve built a complete “OnlineShop” smart contract that lets users add and buy items, as well as withdraw their earnings. This is a great starting point for creating your own blockchain applications with Solidity.</p><p>Feel free to play around with the code, add new features, and make it your own! If you have any questions or want to chat about other topics, don’t hesitate to ask. Happy coding!</p><h3>Complete Code</h3><p>Here’s the complete code for the “OnlineShop” smart contract:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity &gt;=0.7.0 &lt;0.9.0;<br><br>contract OnlineShop {<br>    <br>   struct Item {<br>    uint id;<br>    string name;<br>    uint price;<br>    address owner;<br>   }<br><br>   Item[] public items;<br>   uint idItem;<br><br>   mapping(address =&gt; uint) balance;<br><br>   event addItem(uint id, string name, uint price, address owner);<br>   event buyItem(uint id, address newOwner, uint price);<br><br><br>   function add(string memory _name, uint _price) public {<br>      items.push(Item(idItem, _name, _price, msg.sender));<br>      emit addItem(idItem, _name, _price, msg.sender);<br>      idItem++;<br>      <br>   }<br><br>   function buy(uint _id) public payable {<br>    Item storage item = items[_id];<br><br>    require(item.price &lt;= msg.value, &quot;Insufficient Ether sent&quot;);<br>    require(item.owner != msg.sender, &quot;You cannot buy your own item&quot;);<br>    require(item.owner != address(0), &quot;Item has already been sold&quot;);<br><br>    balance[item.owner] += msg.value;<br><br>    item.owner = msg.sender;<br><br>    emit buyItem(_id, msg.sender, item.price);<br>}<br><br>    <br>      function getBalance() public view returns (uint) {<br>            return balance[msg.sender];<br>     }<br><br>     function withdraw(uint _amount) public payable  {<br>         require(balance[msg.sender] &gt;= _amount, &quot;You not have enought ether&quot;);<br>         payable(msg.sender).transfer(_amount);<br>     }<br><br>}</pre><p>Thankyouu :))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11e0f2503924" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/building-your-own-onlineshop-smart-contract-with-solidity-11e0f2503924">Building Your Own “OnlineShop” Smart Contract with 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>
    </channel>
</rss>