<?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 David Cisar on Medium]]></title>
        <description><![CDATA[Stories by David Cisar on Medium]]></description>
        <link>https://medium.com/@davidcisar?source=rss-dfbc65196047------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X4XyRN_1IpX5tKoKUmhaTA.png</url>
            <title>Stories by David Cisar on Medium</title>
            <link>https://medium.com/@davidcisar?source=rss-dfbc65196047------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:58:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidcisar/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[Web3 Frontends: Seamless Smart Contract Integration with Angular, ethers.js and MetaMask]]></title>
            <link>https://medium.com/@davidcisar/web3-frontends-seamless-smart-contract-integration-with-angular-ethers-js-and-metamask-b080a00b6f7b?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/b080a00b6f7b</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethersjs]]></category>
            <category><![CDATA[metamask]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 14:08:03 GMT</pubDate>
            <atom:updated>2023-12-13T10:57:16.891Z</atom:updated>
            <content:encoded><![CDATA[<h4>9th Episode — Smart Contracts in Angular: A Comprehensive Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PX3rLaiHSZd0RnQ0qnAWBA.png" /></figure><p>Envision a scenario where users are pushed to interact with pure smart contracts, without any user interface to guide them. Having to decipher raw transaction data and manipulate cryptographic addresses — a frustrating task that presents a remarkable challenge, especially for those lacking technical expertise. The absence of a visual interface makes it difficult for users to not only comprehend but also engage with the functionality offered by smart contracts. This complexity hinders widespread adoption.</p><p>In this article, I’ll introduce the process of creating a web3 frontend in Angular with the assistance of ethers.js. Additionally, we’ll integrate MetaMask, a popular wallet provider, to enhance user security and streamline the transaction signing process.</p><h3>The building blocks: ABI, Ethers.js, and MetaMask</h3><p>At the core of our smart contract interactions lie the fundamental building blocks — the Application Binary Interface (ABI) and the deployed smart contract’s address. Additionally, we require an Ethereum provider and a frontend library for seamless interaction. The two primary web3 libraries, ethers.js and web3.js, stand out in this domain. Opting for ethers.js, which we’ve already employed for testing with Mocha and Chai, ensures consistency in our development process. Introducing MetaMask, our chosen browser-integrated wallet provider, adds another layer of facilitation. Acting as an intermediary, MetaMask efficiently forwards our transactions to Ethereum nodes for processing.</p><h4>Application Binary Interface</h4><p>The ABI is a JSON representation of a smart contract’s interface, providing information about the functions, including its parameters, and other relevant details.</p><pre>{<br>  &quot;abi&quot;: [<br>    {<br>      &quot;inputs&quot;: [],<br>      &quot;stateMutability&quot;: &quot;nonpayable&quot;,<br>      &quot;type&quot;: &quot;constructor&quot;<br>    },<br>    ...<br>    {<br>      &quot;inputs&quot;: [<br>        {<br>          &quot;internalType&quot;: &quot;uint256&quot;,<br>          &quot;name&quot;: &quot;_id&quot;,<br>          &quot;type&quot;: &quot;uint256&quot;<br>        }<br>      ],<br>      &quot;name&quot;: &quot;claimToken&quot;,<br>      &quot;outputs&quot;: [],<br>      &quot;stateMutability&quot;: &quot;nonpayable&quot;,<br>      &quot;type&quot;: &quot;function&quot;<br>    },<br>  ]<br>}</pre><p>The ABI serves as the gateway for external applications, such as ethers.js, to communicate effectively with Ethereum smart contracts. During the compilation of smart contract code, the ABI is generated, providing a blueprint of the contract’s functions, data structures, and more.</p><h4>Ethers.js</h4><p>Using Ethers.js allows us to build a bridge between our application and the Ethereum blockchain by injecting Ethereum providers and wallets - the potential signer of transactions.</p><p>Besides injecting providers and signers, Ethers.js enables the application to seamlessly interact with smart contracts. If we provide the smart contracts ABI and it’s address, Ethers is capable of creating a virtual representation of the smart contract and its state. This includes all public state variables, functions, custom errors and events. Having the current state of the contract allows us to retrieve state variables without calling the real smart contract, avoiding gas costs.</p><p>However, if we were to call smart contract functions that involve state changes, Ethers will construct transactions which are getting signed by the injected wallet and are then forwarded to the EVM via the injected Ethereum provider.</p><h4>MetaMask</h4><p>MetaMask plays a crucial role in the development of decentralized applications by acting as a Web3 provider, a counterpart of traditional JSON-RPC providers. By integrating its Web3 provider into the browser, MetaMask provides a seamless connection between users’ wallets and Ethereum-enabled applications. With the help of Ethers.js, we can easily acquire a signer through MetaMask that enables the secure signing of transactions directly from the user’s wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsykdvRDKSiykRVTiOVmvg.png" /><figcaption>Own illustration — Web3 Architecture</figcaption></figure><h3>Constructing Angular services to manage communication with the Ethereum protocol</h3><p>In structuring the Angular application, a robust approach involves the implementation of two dedicated services for streamlined Ethereum interaction. The primary service, named EthereumService, takes charge of managing the Ethereum connection. Within this service, both the provider and signer components are housed, enabling seamless integration with MetaMask. Through the EthereumService, the application gains the capability to connect to MetaMask, retrieve the signer&#39;s balance, validate the current blockchain, and dynamically update in response to changes in either the signer or the blockchain.</p><pre>import { Injectable, NgZone } from &#39;@angular/core&#39;;<br>import { ethers } from &#39;ethers&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class EthereumService {<br>  private provider: ethers.providers.Web3Provider | undefined;<br>  private signer: BehaviorSubject&lt;ethers.providers.JsonRpcSigner | undefined&gt; = new BehaviorSubject&lt;ethers.providers.JsonRpcSigner | undefined&gt;(undefined);<br>  <br>  constructor(private ngZone: NgZone) {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      this.provider = new ethers.providers.Web3Provider(window.ethereum);<br>      this.signer.next(this.provider.getSigner());<br><br>      // Listen for changes in MetaMask accounts<br>      window.ethereum.on(&#39;accountsChanged&#39;, (accounts: string[]) =&gt; {<br>        this.ngZone.run(() =&gt; {<br>          if (accounts.length === 0) {<br>            // MetaMask disconnected or switched accounts<br>            this.handleMetaMaskDisconnect();<br>          } else {<br>            // MetaMask accounts changed<br>            this.handleMetaMaskAccountsChanged(accounts);<br>          }<br>        });<br>      });<br><br>    } else {<br>      console.error(&#39;MetaMask is not installed.&#39;);<br>    }<br>  }<br><br>  private handleMetaMaskDisconnect() {<br>    console.log(&#39;MetaMask disconnected.&#39;);<br>    this.provider = undefined;<br>    this.signer.next(undefined);<br>  }<br><br>  private handleMetaMaskAccountsChanged(accounts: string[]) {<br>    console.log(&#39;MetaMask accounts changed:&#39;, accounts);<br>    this.provider = new ethers.providers.Web3Provider(window.ethereum);<br>    this.signer.next(this.provider.getSigner());<br>  }<br><br>  async connectToMetaMaskWallet() {<br>    if (typeof window.ethereum !== &#39;undefined&#39;) {<br>      // Request access to the user&#39;s MetaMask account<br>      await window.ethereum.request({ method: &#39;eth_requestAccounts&#39; });<br><br>      // Connect to MetaMask using the Web3Provider<br>      this.provider = new ethers.providers.Web3Provider(window.ethereum);<br>      this.signer.next(this.provider.getSigner());<br><br>      const address = await this.signer.getValue()!.getAddress();<br><br>      console.log(&#39;Connected to MetaMask with address:&#39;, address);<br>    } else {<br>      console.error(&#39;MetaMask is not installed.&#39;);<br>    }<br>  }<br><br>  getSigner() { return this.signer.getValue(); }<br>}</pre><p>Upon closer inspection, you may notice that there is no functionality to disconnect your Ethereum accounts in MetaMask directly from within the website. This is not only an intentional design choice, but aligns with best security practices, placing the responsibility on the user to manually disconnect from a connected website in MetaMask. This manual procedure ensures that the user acts safely and carefully.</p><p>Complementing the EthereumService, the second service, aptly named ContractService, serves as a centralized repository for all virtual instances of smart contracts. This service proves indispensable in facilitating interactions with smart contracts, including the initiation of transactions and the retrieval of contract states. This dual-service architecture ensures a modular and organized structure for Ethereum-related functionalities within the Angular application.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { ethers } from &#39;ethers&#39;;<br>import { EthereumService } from &#39;./ethereum.service&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ContractService {<br>  public contract: ethers.Contract;<br><br>  constructor(private ethereumService: EthereumService) {}<br><br>  getContract(address, abi) {<br>    const signer = this.ethereumService.getSigner(); <br>    <br>    if (!signer) {<br>      console.log(&#39;Need to be signed in to get contracts!&#39;);<br>      return;<br>    }<br><br>    this.contract = new ethers.Contract(address, abi, signer);<br>  }<br>}</pre><p>In the ContractService, we’re able to create a new virtual representation of a deployed smart contract by calling getContract(). Everything we need to provide as parameters is the contract’s ABI and its address. This contract instance can then be used to read state variables from or trigger transactions.</p><h3>Interacting with Smart Contracts</h3><p>Now that we have established a virtual representation of the deployed smart contract, we can initiate various actions on these entities.</p><h4>Reading the Contract’s State</h4><p>Consider a scenario where our smart contract features a public state variable named myVariable. To retrieve its data, we have two options. We can either read directly from myVariable or invoke the myVariable() getter-function and subsequently call the retrieved function. Notably, both methods yield the same result.</p><pre>let accessMyVariable = contractInstance.functions[&#39;myVariable&#39;]; <br>letmyVariable = await accessMyVariable();<br><br>let getMyVariable = contractInstance.functions[&#39;myVariable()&#39;]; <br>myVariable = await getMyVariable();</pre><h4>Triggering Transactions that Modify the Contract’s State</h4><p>For transactions that modify the contract’s state, involving state changes and requiring gas, we must follow the first approach above without the function brackets. By retrieving the state-changing function, we prompt the user — the signer — to approve and sign the transaction. MetaMask will signal this event by presenting a pop-up, asking the user to confirm the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRf1luzqeiuF2qzdxMXw3w.png" /></figure><h4>Transaction Confirmation and Data Extraction</h4><p>Following the initiation of a transaction from the frontend application, we can wait for the transaction to be completed by calling await tx.wait(). This asynchronous function actively monitors the Ethereum provider for a response, indicating the completion of the transaction. Once confirmed, we can retrieve a transaction receipt, which holds valuable information.</p><pre>let contractFunction = contract.functions[&#39;functionName&#39;];<br>let tx = await contractFunction(param1, param2, ...);<br>let receipt = await tx.wait();<br><br>console.log(&#39;GasUsed: &#39; + receipt.gasUsed);</pre><p>This receipt includes metrics such as gasUsed, blockNumber, and more. These extracted details provide a basis for in-depth analysis and insights into the transaction process. Keep in mind, that calling public state variables does not involve a real transaction, thus we’re not able to call await tx.wait() in that case!</p><h4>Listening to events</h4><p>Sometimes, we want to be notified if certain conditions are met, such as when a transfer takes place or a transaction is completed. We can listen to event emissions by simply calling:</p><pre>contract.on(&#39;EventName&#39;, (arg1, arg2, event) =&gt; {<br>  console.log(&#39;Event received:&#39;, event);<br>  console.log(&#39;Argument 1:&#39;, arg1);<br>  console.log(&#39;Argument 2:&#39;, arg2);<br>});</pre><p>We’ve covered the basics of web3 frontend development with Angular, ethers.js and MetaMask. From creating virtual smart contract instances to transaction processing and event listening. Finally, you can further analyze and customize for your unique use cases. With a precise understanding of these tools, you’ll be ready to tackle the complexities of web3 frontend development with a practical and informed approach.</p><p>As always, your opinion is highly valuable! So feel free to comment what you think about this article or suggest improvements. Sharing or liking this article is also highly appreciated! 😇</p><h4>Disclaimer:</h4><blockquote>This code and the accompanying text are intended for educational purposes only. While the concepts and examples presented here are designed to facilitate understanding and learning, they may not adhere to the stringent security standards required for production use. Ethereum development involves handling real assets, and the security and reliability of code are paramount in a decentralized environment.</blockquote><blockquote>It is strongly advised not to use the provided code in a production setting without thorough review, auditing, and consideration of best security practices. Users, developers, and readers are encouraged to exercise caution, conduct further research, and seek professional guidance when deploying applications in real-world scenarios.</blockquote><blockquote>By using this material for educational purposes, you acknowledge the inherent risks associated with blockchain development and the responsibility to apply secure coding practices in any production environment.</blockquote><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Getting started with Ethereum</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platfor</a>m</li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Enabling decentralized Bond Trading</a></li></ul><p>Following episodes:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b080a00b6f7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to automate decentralized Bond Trading]]></title>
            <link>https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c01a2cedf95</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[decentralized-exchange]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 17:59:23 GMT</pubDate>
            <atom:updated>2023-11-29T15:24:41.076Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enabling decentralized Bond Trading</h3><h4>8th Episode — Building OTC and DEX Smart Contracts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*doML-M5LbfBEr1M9" /><figcaption>Photo by <a href="https://unsplash.com/@orenlbz?utm_source=medium&amp;utm_medium=referral">Oren Elbaz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back to this blockchain development series, where we’re building a Full-Stack Blockchain-based Bond Token Issuance Platform. So far, we’ve implemented the BondToken smart contract, empowering companies to issue registered bonds, execute corporate actions, and enabling investors to participate in the primary issuance, transfer tokens, and perform various claim-functions. This core component forms the backbone of our platform.</p><p>To ensure a secure and compliant ecosystem, we’ve introduced a Know Your Customer (KYC) contract. This KYC contract plays a crucial role in verifying and whitelisting investors, adding an extra layer of security and compliance to our blockchain ecosystem. In addition to the KYC contract, we’ve implemented a simplified Crypto Securities Register (CSR) prototype contract. This CSR contract, tailored to meet the requirements of the German eWpG, further solidifies our commitment to aligning with regulatory standards and best practices.</p><p>While our platform provides the option for investors to transfer tokens using the built-in safeTransferFrom() functionality, we recognize the need for a streamlined solution for token trading and payments. In the context of financial markets, the Delivery-versus-Payment (DvP) phenomenon addresses the challenge of ensuring a simultaneous exchange of assets and funds during a trade. Traditionally, this issue necessitates the involvement of a trusted third party, often a centralized exchange or intermediary. In a two-step transaction without DvP, a party might deliver assets without receiving payment immediately, introducing counterparty risk.</p><h4>Trading on Centralized Exchanges</h4><p>In centralized exchanges, the trading process involves brokers, buyers, sellers, and clearing/settlement parties. Traders initiate transactions through brokers, specifying the quantity and price for buying or selling financial instruments. Buy and sell orders are stored in <em>order books</em> with various metadata. Centralized exchanges match and execute these orders, utilizing a clearinghouse to validate and finalize trades. Despite their structured platforms, centralized exchanges have limitations such as centralization risks, geographical restrictions, custodial concerns, and inefficiencies in settlement processes.</p><p>Within our Bond Token Issuance Platform, we aim to circumvent reliance on centralized exchanges and intermediaries. Our goal is to automate trading, ensuring 24/7 access and instant Delivery-versus-Payment (DvP). This prompts an exploration of decentralized exchanges, understanding their differences from centralized counterparts, evaluating their preference, and assessing how they address inherent flaws.</p><h4>Decentralized Exchanges</h4><p>In the context of decentralized exchanges, <em>decentralized</em> signifies the absence of a central authority, with trading facilitated by smart contracts on distributed ledgers. These essentially automate trade execution, fund custody, and other processes, eliminating the need for a central entity to control or oversee transactions. Our goal is to implement a token swap functionality in the DEX smart contract, enabling instantaneous exchanges of tokens within a trading pair, commonly referred to as a <strong>token swap</strong>.</p><h4>Why do we need a different approach than using order books?</h4><p>One might initially wonder why not replicate the order-matching mechanism found in centralized exchanges, storing buy and sell orders in traditional order books. However, DEXs typically diverge from this approach due to technical limitations inherent in the Ethereum protocol. Unlike centralized exchanges, DEXs avoid utilizing order books due to the associated gas costs of storing extensive information in smart contracts. Conventional order book structures, whether arrays, mappings, or linked lists, prove impractical due to inefficiencies in iteration, a crucial operation for inserting or deleting orders from a sorted data structure. The objective is to offer a more efficient and gas-effective alternative for decentralized trading.</p><h4>The choice to utilize Algorithmic Trading</h4><p>In the absence of order books, how do DEXs match orders and calculate prices? Contrary to storing orders in a traditional order book, many leading DEXs employ algorithmic trading methods, leveraging Liquidity Pools and an automated price mechanism. Commonly known as the “Constant Product Formula” (CPF), this mechanism determines the exchange rate between two assets within a liquidity pool in the context of a DEX. The CPF is expressed as follows:</p><p><em>x * y </em>= <em>k</em></p><p>Where:</p><ul><li><em>x</em> is the amount of one token in the liquidity pool</li><li><em>y</em> is the amount of the other token in the liquidity pool</li><li><em>k</em> is a constant value</li></ul><h4>Calculating exchange rates with CPF</h4><p>If we now utilize the CPF and want to swap token <em>x</em> for token <em>y</em>, the amount of Δ<em>y</em> to receive is calculated as follows:</p><p>( <em>x + Δx </em>)<em> * </em>( <em>y — Δy </em>)<em> = k</em></p><p>Solved for<em> Δy </em>results in:</p><p><em>Δy = y — </em>(<em> k / </em>( <em>x + Δx </em>))</p><p>In the case where an investor A wants to swap 100 token x, with the following liquidity in the pool:</p><p><strong>Balances:</strong><em><br>y = 1_000</em> and <em>x = 1_000</em>, <em>k = 1_000_000</em></p><p><strong>CPF:</strong><em><br>Δy = 1_000 — </em>(<em>1_000_000 / </em>(<em>1_000 + 100</em>)) = <em>1_000–909.09</em> = <em>90.91</em></p><p>Based on this calculation, A would receive <em>90.91</em> token <em>y</em>. What’s important to note is, that the constant always remains the same, resulting in increasing or decreasing prices of the tokens in the pair. If another investor B would want to swap the same amount of token <em>x</em>, B would receive only <em>75.76</em> token <em>y </em>now. This is due to changed token balances in the liquidity <br>pool:</p><p><strong>Balances:</strong><em><br>y = 909.10</em> and <em>x = 1_100</em>, <em>k = 1_000_000</em></p><p><strong>CPF:</strong><em><br>Δy = 909.10 — </em>(<em>1_000_000 / </em>(<em>1_100 + 100</em>)) = <em>909.10–833.33</em> = <em>75.76</em></p><p>When exchanging Token <em>x</em> for Token <em>y</em>, <em>y</em>’s balance diminishes in the pool. This characteristic is fundamental to automated market makers (AMMs) relying on the CPF, where the product of token balances in a liquidity pool remains constant. As Token <em>y</em> becomes scarcer relative to Token <em>x</em>, this scarcity holds pivotal implications for subsequent swaps and the DEX’s pricing mechanism.</p><h4>Implementing the CPF approach in our swapping functions</h4><p>In the DEX, we allow investors to swap ether for any bond token within our issuance platform and vice versa. The only requirement is, that the issuer of the respective bond token provides liquidity for these token pairs.</p><pre>function swapEthForToken(uint256 _tokenId) public payable {<br>  uint256 _tokenBalance = liquidityPools[_tokenId].tokenBalance;<br>  uint256 _ethBalance = liquidityPools[_tokenId].ethBalance;<br>  require (_tokenBalance &gt; 0 &amp;&amp; _ethBalance &gt; 0);<br>  <br>  uint256 _cpf = liquidityPools[_tokenId].cpf;<br>  uint256 _newEthBalance = _ethBalance + msg.value;<br>  uint256 _amountToRemain = _cpf / _newEthBalance;<br>  uint256 _amountToReceive = _tokenBalance - _amountToRemain;<br>    <br>  liquidityPools[_tokenId].ethBalance = _newEthBalance;<br>  liquidityPools[_tokenId].tokenBalance = _amountToRemain;<br>    <br>  bondTokenInstance.safeTransferFrom(address(this), _msgSender(), _tokenId, _amountToReceive, &quot;&quot;);<br>        <br>  emit SwappedEthForToken(_tokenId, _amountToReceive, msg.value, _msgSender());<br>}<br><br>function swapTokenForEth(uint256 _tokenId, uint256 _amount) public {<br>  uint256 _tokenBalance = liquidityPools[_tokenId].tokenBalance;<br>  uint256 _ethBalance = liquidityPools[_tokenId].ethBalance;<br>  require(_tokenBalance &gt; 0 &amp;&amp; _ethBalance &gt; 0);<br>        <br>  uint256 _cpf = liquidityPools[_tokenId].cpf;<br>  uint256 _newTokenBalance = _tokenBalance + _amount;<br>  uint256 _ethToRemain = _cpf / _newTokenBalance;<br>  uint256 _ethToReceive = _ethBalance - _ethToRemain;<br>    <br>  liquidityPools[_tokenId].ethBalance = _ethToRemain;<br>  liquidityPools[_tokenId].tokenBalance = _newTokenBalance;<br>    <br>  bondTokenInstance.safeTransferFrom(_msgSender(), address(this), _tokenId, _amount, &quot;&quot;);<br>  address payable receiver = payable(_msgSender());<br>  receiver.transfer(_ethToReceive);<br>        <br>  emit SwappedTokenForEth(_tokenId, _amount, _ethToReceive, _msgSender());  <br>}</pre><p>Providing liquidity to a token pair pool includes sending ether to the DEX contract as well as a matching amount of the respective bond token. In order to be able to receive ether, the contract must implement the receive() external payable {}<strong> </strong>function. For proper transfer functionality of ERC1155 tokens, it is essential for the DEX to inherit from ERC1155TokenHolder. This way, the contract is able to receive and send ERC1155 tokens.</p><p>That being said, we’re able to implement theprovideLiquidity() and withdrawLiquidity() functions, allowing efficient funds management in and out of the DEX.</p><pre>function provideLiquidity<br>  (uint256 _tokenId, uint256 _amount, uint256 _value, address _sender) <br>  external payable onlyBondTokenContract<br>  {<br>  require(!liquidityPools[_tokenId].provided, &quot;Already provided...&quot;);<br>        <br>  liquidityPools[_tokenId].tokenBalance = _amount;<br>  liquidityPools[_tokenId].ethBalance = _value;<br>  liquidityPools[_tokenId].cpf = _amount * _value;<br>  liquidityPools[_tokenId].provided = true;<br><br>  emit LiquidityProvided(_tokenId, _amount, _value, _sender);<br>}<br><br>function withdrawLiquidity(uint256 _tokenId) public onlyIssuerOfId(_tokenId) {<br>  require(liquidityPools[_tokenId].provided);<br>  <br>  uint256 _ethBalance = liquidityPools[_tokenId].ethBalance;<br>  uint256 _tokenBalance = liquidityPools[_tokenId].tokenBalance;<br>  <br>  liquidityPools[_tokenId].tokenBalance = 0;<br>  liquidityPools[_tokenId].ethBalance = 0;<br>  liquidityPools[_tokenId].provided = false;<br><br>  address payable _issuer = payable(_msgSender());<br>  bondTokenInstance.safeTransferFrom(address(this), _issuer, _tokenId, _tokenBalance, &quot;&quot;);<br>  _issuer.transfer(_ethBalance);<br><br>  emit LiquidityWithdrawn(_tokenId, _tokenBalance, _ethBalance, _issuer);<br><br>}</pre><p>What distinguishes the provideLiquidity() function is its exclusive external invocation from the bondTokenInstance. This design choice eliminates the need for DEX contract approval to transfer tokens on behalf of the issuer. If the safeTransferFrom() function were called within the DEX contract, the msg.sender would be the DEX contract, differing from the issuer&#39;s address. The transfer function necessitates that either the msg.sender equals the _from parameter or that the msg.sender has received approval from the _from address to transfer tokens on its behalf.</p><pre>/** Inside the bond token instance */<br>function provideLiquidity(uint256 _id, uint256 _amount) <br>  public payable onlyIssuerOfId(_id) <br>  {<br>  require(tokenData[_id].issued &amp;&amp; block.timestamp &lt; tokenData[_id].metaData.tradingDate);<br>  uint256 _tokenValueInWei = getPriceToPay(_id, _amount);<br>  require (msg.value == _tokenValueInWei, &quot;Value does not match!&quot;);<br>  <br>  address payable dex = payable(address(dexInstance));<br><br>  _safeTransferFrom(_msgSender(), dex, _id, _amount, &quot;&quot;);<br>  dex.transfer(msg.value);<br>  dexInstance.provideLiquidity(_id, _amount, msg.value, _msgSender());<br>}</pre><h4>Why an Over-The-Counter Smart Contract Holds Significance:</h4><p>In addition to the ability to exchange bond tokens for ether within our DEX, we recognize the necessity for the implementation of a distinct contract tailored for bond token trading — the OTC contract. OTC, signifying over-the-counter, is a well-established method for trading bonds in traditional financial markets, particularly when exchanges exhibit low liquidity. OTC trades, while characterized by a lack of transparency as they remain unrecorded on any exchange, wield a reduced impact on the asset’s price. OTC transactions involve two counterparties agreeing upon specific conditions, such as the asset’s price, before the actual trade occurs.</p><p>As previously observed, algorithmic trading methodologies can have a significant impact on the price, especially when trading behaviors are unevenly distributed. Large-scale corporate investments in corporate bonds, for instance, could lead to substantial price impacts when trading sizable token quantities. To address this, we aim to facilitate institutional investors’ ability to engage in trades between two distinct parties while upholding an automated DvP mechanism. The OTC contract provides a mechanism for creating a SellOrder for a bond token, storing the order’s details within a struct. This struct encompasses metadata such as the _tokenId, _amount,_price, _validUntil (indicating the UNIX time until which the trade can be executed), and the designated _to counterparty.</p><pre>  struct SellOrder {<br>    uint256 tokenId;<br>    uint256 amount;<br>    uint256 price;<br>    uint256 validUntil;<br>    address seller;<br>    address to;<br>    bool filled;<br>    bool deleted;<br>  }<br><br>  mapping(uint256 _orderId =&gt; SellOrder) public orders;<br><br><br>  function createSellOrder( <br>      uint256 _tokenId, uint256 _amount, <br>      uint256 _price, uint256 _validUntil, address _to) <br>      public {<br>    if (!bondTokenInstance.isApprovedForAll(_msgSender(), address(this))) {<br>      revert AllowanceRequired();<br>    }<br>    SellOrder memory order;<br>    order.tokenId = _tokenId;<br>    order.amount = _amount;<br>    order.price = _price;<br>    order.validUntil = _validUntil;<br>    order.seller = _msgSender();<br>    order.to = _to;<br>    orders[orderId] = order;<br><br>    emit OrderCreated(orderId, _tokenId, _amount, _price, _validUntil, _to);<br><br>    orderId++;<br>  }<br><br>  function deletedSellOrder(uint256 _orderId) public onlySeller(_orderId) {<br>    orders[_orderId].deleted = true;<br>    emit OrderDeleted(orderId, _msgSender());<br>  }<br><br>  function triggerOTCTransfer(uint256 _orderId) <br>      public payable onlyBuyer(_orderId) <br>      {<br>    ...<br>  }</pre><p>Having both a DEX and an OTC smart contract within our bond token issuance platform serves a crucial dual-purpose. The DEX offers a streamlined and automated environment for users to seamlessly trade bond tokens for ether, leveraging the advantages of algorithmic trading and liquidity pools. However, recognizing the unique characteristics of larger transactions, institutional investors, and the potential impact on token prices, the OTC smart contract complements the DEX by providing a tailored solution for off-exchange, negotiated trades. The OTC contract accommodates specific agreements between counterparties, allowing for enhanced customization of trade conditions, pricing, and execution timelines. This dual-contract approach ensures flexibility, catering to a broad spectrum of users — from those seeking automated, transparent trades on the DEX to institutional investors engaging in more nuanced, over-the-counter transactions.</p><p>Stay tuned, as in the upcoming episode, I will introduce into web3 frontend development. We will explore how we can connect to Ethereum providers and communicate (read + write) to the blockchain. The focus will then turn to wallets, with an emphasis on understanding the functionalities of MetaMask and the innovative WalletConnect. We will explore how these wallets allow users to securely manage their assets and seamlessly interact with decentralized applications on different platforms.</p><p>Your opinion is highly valuable, so please feel free to share your thoughts, suggest changes or provide improvements!</p><blockquote><strong><em>Disclaimer:</em></strong></blockquote><blockquote>The code presented in this article and any accompanying information are provided solely for educational purposes. They are intended to serve as illustrative examples and do not constitute financial, legal, or investment advice. The use of any code or information from this article is at the reader’s discretion and risk. The authors and publishers do not assume any responsibility for the accuracy, completeness, or applicability of the code or information presented. Before implementing any code or making decisions based on the information provided, it is strongly recommended to seek professional advice and thoroughly assess the code in a secure and controlled environment. The authors and publishers disclaim any liability for any potential losses or damages arising from the use of the code or information contained herein.</blockquote><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Getting started with Ethereum</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platfor</a>m</li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li></ul><p>Following episodes:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c01a2cedf95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to test Smart Contracts]]></title>
            <link>https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b1321248387</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[mocha]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 22:39:02 GMT</pubDate>
            <atom:updated>2023-11-20T09:00:52.321Z</atom:updated>
            <content:encoded><![CDATA[<h4>7th Episode — Utilizing Mocha and Chai</h4><p>In the field of blockchain technology, ensuring the security of smart contracts is of paramount importance. Smart contracts are immutable and self-executing codes that are essential for various decentralized applications and financial transactions. Unlike traditional software, once deployed on the blockchain, smart contracts cannot be modified. This immutability increases the importance of rigorous testing. Security audits alone, while important, may not cover all possible scenarios. Therefore, developers should supplement these audits with comprehensive unit and end-to-end (E2E) testing. Despite the temptation to bypass testing — a practice occasionally found in general software development — neglecting test cases for smart contracts is reckless. The impact of a security breach in a smart contract can be catastrophic, resulting in financial loss and undermining user confidence. Therefore, writing tests for smart contracts is not only a best practice, but an imperative step in ensuring the integrity and reliability of decentralized systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyzI99ov55iaXHGOKuddVg.png" /></figure><h4>Why Smart Contract Testing is Crucial</h4><ol><li>Smart contracts often handle significant amounts of assets. Proper testing ensures that contracts are <strong>secure</strong> and <strong>resistant</strong> to common vulnerabilities like unauthorized access.</li><li>Smart contracts, once deployed, are <strong>immutable</strong>. Rigorous testing helps identify and fix potential bugs before deployment, ensuring that smart contracts work as intended without unexpected behavior or errors.</li><li>Well-tested code is easier to maintain and modify during development. It allows developers to confidently make changes or add new features without fear of breaking existing functionality.</li></ol><p>At this point, I would like to briefly introduce a notable approach that can be followed in the course of testing and is quite useful, even if we did not actually apply this approach during our development process. In software development, Test-Driven Development (TDD) stands as a pivotal approach. TDD involves defining test cases, encompassing both common inputs and edge cases, along with their expected results, <strong>before</strong> writing the actual business logic. This method offers several advantages, such as improved code quality, easier maintenance, and faster debugging. TDD integrates seamlessly into agile methodologies, aligning with the iterative nature of agile development. We did not use this approach because, as mentioned earlier, testing is not the most valued task. In this blog series, it might have been counterintuitive to introduce testing before starting to develop smart contracts, although it makes sense in a real-world scenario.</p><h4>What is the difference between unit and E2E tests?</h4><p>In our testing approach, achieving a test coverage of 100% doesn’t mean testing everything all at once. We break down our tests into two main categories: <strong>unit </strong>and <strong>E2E</strong> tests. Unit tests, as the name implies, focus on testing one specific unit of a smart contract, such as the execution of whitelisting functionality in the KYC contract. On the other hand, E2E tests encompass more than one unit but are still limited to specific use cases. These test interactions between different contract functions or even between two distinct contracts to ensure they work together as expected. If we take the issuance process as an example, an E2E test could involve testing the registration of the bond token, its approval, and the initiation of the pre-sale in this specific order.</p><p>In both unit and E2E tests, it is essential to cover a wide range of inputs to ensure the robustness and reliability of smart contracts. Common inputs, representing typical user interactions, help validate the expected behavior of functions under standard conditions. These tests ensure that everyday operations proceed smoothly. However, it is equally vital to explore edge cases — inputs that lie at the extreme boundaries of what the contract can handle. Edge cases include scenarios like maximum and minimum values, empty or null inputs, and unexpected data formats.</p><p>Additionally, we pay close attention to testing gas consumption. Understanding how much gas our smart contracts use is vital. It helps us identify potential issues, such as code segments that consume excessive gas, making them unexecutable on the Ethereum network. By optimizing gas usage, we ensure our smart contracts run efficiently and cost-effectively, which is crucial for decentralized applications operating on the blockchain.</p><h4>Required tools for setting up test suites</h4><p>To ensure effective testing of our smart contracts, we rely on essential tools that streamline the process. Mocha, a widely used JavaScript testing framework, forms the backbone of our testing environment. Its flexibility and developer-friendly features enable us to create robust test suites. Coupled with Chai, a powerful assertion library, our tests become not just comprehensive but also highly readable. Chai’s expressive assertions enhance the clarity of our tests, making it easier to spot issues and understand the test cases.</p><p>In addition, we utilize Ethers.js, seamlessly integrated into our development framework Hardhat. Ethers.js plays a crucial role in interacting with smart contracts, offering a convenient interface for contract deployment, function calls, and transaction handling.</p><p>If not done already, you will need to install Mocha and chai. Simply open a terminal or console and navigate to the project directory. Type in the following command to install both libraries:</p><p>npm install --save-dev mocha chai</p><p>If you didn’t initialize your hardhat project with a test project, you’ll need to create a folder called <strong>test</strong>. In there, we can create multiple test suites — simply create a new file and call it <strong>test.ts</strong>.</p><h4>Testing in Hardhat</h4><p>If you’re already familiar with testing JavaScript or TypeScript files, this might be straight forward. Essentially, every test suite needs to import expect from chai and ethers from hardhat.</p><pre>const { expect } = require(&quot;chai&quot;); <br>const { ethers } = require(&quot;hardhat&quot;);</pre><p>Next, we initialize a Mocha test suite. In Mocha, the describe() function is used to group individual test cases into a more organized and hierarchical structure. It helps in better organizing and managing the test suite by grouping related tests together. The describe() function takes two parameters: a string description of the test suite and a callback function.</p><pre>describe(&quot;SmartContract&quot;, function () {});</pre><p>Inside the parentheses, we put all of the test logic. At the top, we want to declare variables we’re going to use during the test execution, like the Smart Contract, the instance of the smart contract or entities.</p><pre>describe(&quot;SmartContract&quot;, function () { <br>  let smartContract: any, smartContractInstance: any;<br>  let owner: any, operator: any, investor: any, issuer: any;<br>});</pre><p>The beforeEach() function is a hook that allows us to run code that is executed before each test case. This hook is often used to set up the testing environment or perform actions that are common to multiple test cases. We usually deploy the smart contracts and assign ethereum addresses to specific entities inside the beforeEach() function.</p><pre>describe(&quot;SmartContract&quot;, function () { <br>  let smartContract: any, smartContractInstance: any;<br>  let owner: any, operator: any, investor: any, issuer: any;<br><br>  beforeEach(async function () {<br>    // Assigning ethereum accounts to variables<br>    [owner, operator, investor, issuer] = await ethers.getSigners();<br><br>    smartContract = await ethers.getContractFactory(&quot;SmartContract&quot;);<br>    smartContractInstance = await SmartContract.deploy();<br>  });<br><br>});</pre><p>Lastly, we need to write the unit test itself. The it() function takes two parameters: a string description of the test case and a callback function, which contains the test logic and assertions.</p><pre>describe(&quot;SmartContract&quot;, function () { <br>  let smartContract: any, smartContractInstance: any;<br>  let owner: any, operator: any, investor: any, issuer: any;<br><br>  beforeEach(async function () {<br>    // Assigning ethereum accounts to variables<br>    [owner, operator, investor, issuer] = await ethers.getSigners();<br><br>    smartContract = await ethers.getContractFactory(&quot;SmartContract&quot;);<br>    smartContractInstance = await SmartContract.deploy();<br>  }); <br><br>  it(&quot;Should return the correct value after a transaction&quot;, async function () { <br>    // Expected value<br>    const expectedValue = &#39;Something&#39;;    <br><br>    // Perform some action on the smart contract <br>    await smartContractInstance.doSomething(); <br><br>    // Get the result and assert it using Chai&#39;s expect <br>    const actualValue = await smartContractInstance.getSomething();<br>    <br>    // Assertion<br>    expect(actualValue).to.equal(expectedValue);<br>});</pre><h4>Testing events and gas usage</h4><p>In our Bond Token Issuance platform, events play a pivotal role in user interaction. When users engage with the platform, events are emitted, indicating successful transactions, token transfers, or specific contract conditions being met. These events serve as real-time signals that empower our Web3 frontend to offer users immediate feedback and dynamic updates. By subscribing to these events, our frontend provides seamless user experiences, displaying real-time transaction confirmations, tracking transaction progress, and updating UI components in response to on-chain activities. Ensuring the accuracy of these events is paramount, and within our unit tests, we employ various strategies. We verify simple emittance, ensuring that specific events are triggered. Additionally, we test event arguments, confirming both their presence and values.</p><pre>it(&quot;should emit an event&quot;, async function () {<br>  await expect(smartContractInstance.doSomething())<br>    .to.emit(smartContractInstance, &#39;EventName&#39;);<br>}<br><br>it(&quot;should emit an event with specified argument values&quot;, async function () {<br>  await expect(smartContractInstance.doSomething())<br>    .to.emit(smartContractInstance, &#39;EventName&#39;)<br>    .withArgs(firstArgument, secondArgument);<br>});<br><br>it(&quot;should emit event with named arguments&quot;, async function () {<br>  const tx = await contractInstance.doSomething();<br>  const receipt = await tx.wait();<br>  const event = receipt.events.find((e) =&gt; e.event === &quot;EventName&quot;);<br><br>  expect(event.args.from).to.equal(wallet.address);<br>  expect(event.args.to).to.equal(walletTo.address);<br>  expect(event.args.amount).to.equal(1);<br>});<br></pre><p>As highlighted earlier, ensuring the smooth operation of a smart contract relies on functions being executed within gas limits. To identify potential issues, it’s essential to test the gas consumption of our functions before deploying smart contracts. By doing so, we can identify and change unexecutable code fragments, ensuring the reliability of the smart contracts’ operations. In the following test case, we compare the gasUsed value obtained from executing doSomething() with the expectedGasLimit, which is set at a predetermined threshold. This assertion guarantees that the function’s gas consumption remains below the specified limit, safeguarding the seamless functioning of our platform.</p><pre>it(&#39;should not consume excessive gas&#39;, async function () {<br>  const expectedGasLimit = BigNumber(50000);<br><br>  const tx = await smartContractInstance.doSomething();<br>  const receipt = await tx.wait();<br><br>  expect(receipt.gasUsed).to.be.below(expectedGasLimit);<br>});</pre><p>I want to add another quick note on the <strong>AAA</strong> pattern, which one should follow, when writing unit tests. AAA stands for Arrange, Act, and Assert. In the first step, we set up initial conditions. Essentially, this is what’s happening during the beforeEach() hook. But, we can also set up additional conditions, which are specific for this particular use case. In the second step, we invoke the method being tested. Finally, Assert checks the results against our expectations.</p><h4>Different Assertion methods</h4><p>Assertions in chai can cover common scenarios when testing Ethereum smart contracts, including checking for equality, boolean values, emittance of events and specific revert conditions.</p><pre>// Equality assertion<br>expect(actualValue).to.equal(expectedValue);<br><br>// Boolean assertions<br>expect(actualValue).to.be.true; <br>expect(actualValue).to.be.false;<br><br>// Event assertions<br>await expect(smartContractInstance.doSomething())<br>  .to.emit(smartContractInstance, &#39;EventName&#39;);<br><br>// Revert assertions<br>await expect(smartContractInstance.doSomething())<br>  .to.not.be.reverted;<br>await expect(smartContractInstance.doSomething())<br>  .to.be.revertedWith(&quot;ErrorMessage&quot;);<br>await expect(smartContractInstance.doSomething())<br>  .to.be.revertedWithCustomError(smartContract, &quot;CustomError&quot;);</pre><p>To get a general overview of the various chai assert and expect, you can visit <a href="https://devhints.io/chai">Chai Cheatsheet</a>. A great documentation on chai matchers when using solidity can be found <a href="https://ethereum-waffle.readthedocs.io/en/latest/matchers.html">here</a>.</p><h4>Using different ethereum accounts</h4><p>In our bond token issuance platform, several different entities take part. To be able to test contract functionality by using different ethereum accounts, which might have different access rights, we can switch between these accounts. By default, functions are called by the first ethereum account returned when calling await ethers.getSigners(). In our case, this would be the owner.</p><p>If we want to call a function as the investor, we can switch between ethereum accounts by simply calling .connect(investor) on the tested smart contract instance.</p><pre>await smartContractInstance.connect(investor).doSomething();</pre><p>Equipped with these techniques, we can now seamlessly apply them to the smart contracts we develop and ensure their functionality, transparency and efficiency.</p><h4>Unit testing the KYC Contract</h4><pre>const { expect } = require(&#39;chai&#39;);<br>const { ethers } = require(&#39;hardhat&#39;);<br><br>describe(&quot;KYC Contract&quot;, function () {<br>    let kyc: any, kycInstance: any;<br>    let bondToken: any, bondTokenInstance: any;<br>    let owner: any, operator: any, unauthorizedOperator: any, investor: any, issuer: any;<br><br>    beforeEach(async function () {<br>        [owner, operator, unauthorizedOperator, investor, issuer] = await ethers.getSigners();<br><br>        kyc = await ethers.getContractFactory(&quot;KYC&quot;);<br>        kycInstance = await kyc.deploy();<br><br>        bondToken = await ethers.getContractFactory(&quot;BondToken&quot;);<br>        bondTokenInstance = await bondToken.deploy();<br>    });<br><br>    it(&quot;Should set owner correctly&quot;, async function () {<br>        expect(await kycInstance.owner()).to.equal(owner.address);<br>    });<br><br>    // Set authorized operator and authorized contract<br><br>    it(&quot;Should set authorized operator only by owner&quot;, async function () {<br>        await expect(kycInstance.connect(operator).setAuthorizedOperator(operator.address)).to.be.revertedWithCustomError(bondToken, &quot;OwnableUnauthorizedAccount&quot;);<br>        await expect(kycInstance.connect(owner).setAuthorizedOperator(operator.address)).to.not.be.reverted;<br>        expect(await kycInstance.authorizedOperators(operator.address)).to.be.true;<br>    });<br><br>    it(&quot;Should revoke authorized operator only by owner&quot;, async function () {<br>        await kycInstance.connect(owner).setAuthorizedOperator(operator.address);<br><br>        await expect(kycInstance.connect(operator).revokeAuthorizedOperator(operator.address)).to.be.revertedWithCustomError(bondToken, &quot;OwnableUnauthorizedAccount&quot;);<br>        await expect(kycInstance.connect(owner).revokeAuthorizedOperator(operator.address)).to.not.be.reverted;<br>        expect(await kycInstance.authorizedOperators(operator.address)).to.be.false;<br>    });<br><br>    it(&quot;Should set authorized contract only by owner&quot;, async function () {<br>        await expect(kycInstance.connect(operator).setAuthorizedContract(bondTokenInstance.target)).to.be.revertedWithCustomError(bondToken, &quot;OwnableUnauthorizedAccount&quot;);<br>        await expect(kycInstance.connect(owner).setAuthorizedContract(bondTokenInstance.target)).to.not.be.reverted;<br>        expect(await kycInstance.authorizedContracts(bondTokenInstance.target)).to.be.true;<br>    });<br><br>    it(&quot;Should revoke authorized contract only by owner&quot;, async function () {<br>        await kycInstance.connect(owner).setAuthorizedContract(bondTokenInstance.target)<br><br>        await expect(kycInstance.connect(operator).revokeAuthorizedContract(bondTokenInstance.target)).to.be.revertedWithCustomError(bondToken, &quot;OwnableUnauthorizedAccount&quot;);<br>        await expect(kycInstance.connect(owner).revokeAuthorizedContract(bondTokenInstance.target)).to.not.be.reverted;<br>        expect(await kycInstance.authorizedContracts(bondTokenInstance.target)).to.be.false;<br>    });<br><br>    // Whitelist / blacklist investors and issuers<br><br>    it(&quot;Should whitelist investor address only by authorized operator&quot;, async function () {<br>        await kycInstance.connect(owner).setAuthorizedOperator(operator.address);<br><br>        await expect(kycInstance.connect(unauthorizedOperator).whitelistInvestorAddress(investor.address)).to.be.revertedWith(&quot;Only Authorized!&quot;);<br>        await expect(kycInstance.connect(operator).whitelistInvestorAddress(investor.address)).to.not.be.reverted;<br>    });<br><br>    it(&quot;Should whitelist issuer address only by authorized operator&quot;, async function () {<br>        await kycInstance.connect(owner).setAuthorizedOperator(operator.address);<br><br>        await expect(kycInstance.connect(unauthorizedOperator).whitelistIssuerAddress(issuer.address)).to.be.revertedWith(&quot;Only Authorized!&quot;);<br>        await expect(kycInstance.connect(operator).whitelistIssuerAddress(issuer.address)).to.not.be.reverted;<br>    });<br><br>    it(&quot;Should blacklist investor address only by authorized operator&quot;, async function () {<br>        await kycInstance.connect(owner).setAuthorizedOperator(operator.address);<br>        await kycInstance.connect(operator).whitelistInvestorAddress(investor.address)<br><br>        await expect(kycInstance.connect(unauthorizedOperator).blacklistInvestorAddress(investor.address)).to.be.revertedWith(&quot;Only Authorized!&quot;);<br>        await expect(kycInstance.connect(operator).blacklistInvestorAddress(investor.address)).to.not.be.reverted;<br>    });<br><br>    it(&quot;Should blacklist issuer address only by authorized operator&quot;, async function () {<br>        await kycInstance.connect(owner).setAuthorizedOperator(operator.address);<br>        await kycInstance.connect(operator).whitelistIssuerAddress(issuer.address)<br><br>        await expect(kycInstance.connect(unauthorizedOperator).blacklistIssuerAddress(issuer.address)).to.be.revertedWith(&quot;Only Authorized!&quot;);<br>        await expect(kycInstance.connect(operator).blacklistIssuerAddress(issuer.address)).to.not.be.reverted;<br>    });<br><br>});</pre><p>To run these tests, navigate to the hardhat folder in the console or terminal of your choice. Simply type in npx hardhat test to run all test suites or npx hardhat test subfolder/testFile.ts to run a specific test suite in a subfolder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hm9D5dDFV9i3ERsov5VoNg.png" /></figure><h4>E2E Testing the Token Sale with a minimum funding goal set</h4><pre>const { expect } = require(&#39;chai&#39;);<br>const { ethers } = require(&#39;hardhat&#39;);<br><br>describe(&#39;E2E test to buy tokens from bond issuance with minimum funding goal&#39;, function () {<br>  let BondToken: any, bondTokenInstance: any;<br>  let CSR: any, csrInstance: any;<br>  let KYC: any, kycInstance: any;<br>  let owner: any, operator: any, investor: any, issuer: any, registrar: any;<br>  let tokenId: number = 1;<br>  let amountToBuy: string = &#39;5&#39;;<br><br>  it(&#39;should allow the investor to buy tokens but for claim&#39;, async function () {<br>    [owner, operator, investor, issuer, registrar] = await ethers.getSigners();<br><br>    // Deploy BondToken, KYC and CSR contracts<br>    BondToken = await ethers.getContractFactory(&#39;BondToken&#39;);<br>    bondTokenInstance = await BondToken.deploy();<br>    KYC = await ethers.getContractFactory(&#39;KYC&#39;);<br>    kycInstance = await KYC.deploy();<br>    CSR = await ethers.getContractFactory(&#39;CSR&#39;);<br>    csrInstance = await CSR.deploy();<br><br>    // Setting the contract addresses in the respective contracts<br>    await bondTokenInstance.setKYCContractAddress(kycInstance.target);<br>    await bondTokenInstance.setCSRContractAddress(csrInstance.target);<br>    await csrInstance.setKYCInstance(kycInstance.target);<br>    await csrInstance.setBondTokenInstance(bondTokenInstance.target);<br><br>    console.log(&quot;BondToken Address:&quot;, bondTokenInstance.target);<br><br>    // Set authorized contract addresses for external function calls in the kycInstance<br>    await kycInstance.setAuthorizedContract(csrInstance.target);<br>    await kycInstance.setAuthorizedContract(bondTokenInstance.target);<br><br>    // Set authorized operator and registrar<br>    await kycInstance.setAuthorizedOperator(operator.address);<br>    await csrInstance.setRegistrar(registrar.address);<br><br>    // Whitelisting issuer and investor<br>    await kycInstance.connect(operator).whitelistIssuerAddress(issuer.address);<br>    await kycInstance.connect(operator).whitelistInvestorAddress(investor.address);<br><br>    // Register Bond as issuer<br>    const incorporatedRights = ethers.encodeBytes32String(&quot;Incorporated Rights...&quot;);<br><br>    await csrInstance.connect(issuer).registerBond(&#39;Issuer&#39;, incorporatedRights, {<br>          parValue: ethers.parseEther(&#39;1&#39;, 18),<br>          interestRate: ethers.parseUnits(&#39;5&#39;),<br>          minFundingGoal: ethers.parseUnits(&#39;5000&#39;),<br>          maxFundingGoal: ethers.parseUnits(&#39;10000&#39;),<br>          soldTokens: ethers.parseUnits(&#39;0&#39;),<br>          issuanceDate: Math.floor(Date.now() / 1000),<br>          claimableDate: Math.floor(Date.now() / 1000) + 3600,<br>          tradingDate: Math.floor(Date.now() / 1000) + 7200,<br>          maturityDate: Math.floor(Date.now() / 1000) + 10800,<br>    });<br>    <br>    // Approve the bond issuance as the registrar<br>    await csrInstance.connect(registrar).approveBond(tokenId);<br><br>    // Register as the investor<br>    const restrictionsOnDisposal = ethers.encodeBytes32String(&quot;&quot;);<br>    const thirdPartyRights = ethers.encodeBytes32String(&quot;&quot;);<br><br>    await csrInstance.connect(investor).registerForBondId(tokenId, true, 1, restrictionsOnDisposal, thirdPartyRights);<br>    <br>    // Start the presale as the issuer<br>    await csrInstance.connect(issuer).startPreSale(tokenId);<br>    <br>    // Issue tokens as the investor in the bond token contract<br>    await bondTokenInstance.connect(issuer).issueToken(tokenId);<br>    <br>    // Check if tokens are issued and send to the issuer address<br>    const balanceOfIssuer = await bondTokenInstance.balanceOf(issuer.address, tokenId);<br>    expect(balanceOfIssuer).to.equal(BigInt(ethers.parseUnits(&#39;10000&#39;)));<br>  <br>    // Get the price to pay for 5 Bond tokens of tokenId 1<br>    const valueToSend = await bondTokenInstance.connect(investor).getPriceToPay(tokenId, amountToBuy); <br>    <br>    // Get the Ether balance of the address before the buy process<br>    let etherBalanceBefore = await ethers.provider.getBalance(investor.address);<br>    <br>    // Buy the bond tokens as the investor with the valueToSend as msg.value<br>    await bondTokenInstance.connect(investor).buyToken(tokenId, amountToBuy, { value: valueToSend });<br>   <br>    // Get the Ether balance of the address after the buy process<br>    let etherBalanceAfter = await ethers.provider.getBalance(investor.address);<br><br>    // Logging some interesing information about the buy process<br>    console.log(&#39;Ether Balance of Investor before buying tokens: &#39; + (Number(etherBalanceBefore)/(10**18)).toFixed(8).toString());<br>    console.log(&#39;Ether Balance of Investor after buying tokens: &#39; + (Number(etherBalanceAfter)/(10**18)).toFixed(8).toString());<br>    console.log(&#39;Complete costs of buying tokens: &#39; + ((Number(etherBalanceBefore) - Number(etherBalanceAfter))/(10**18)).toFixed(8).toString() + &#39; Ether&#39;);<br>    console.log(&#39;Gas costs of buying tokens: &#39; + ((Number(etherBalanceBefore) - Number(etherBalanceAfter) - Number(valueToSend))/(10**18)).toFixed(8).toString() + &#39; Ether&#39;);<br><br>    // Assert and check if tokens are transferred<br>    const balance = await bondTokenInstance.connect(investor).balanceOf(investor.address, tokenId);<br>    const claimableAmount = await bondTokenInstance.connect(investor).getClaimableAmount(tokenId);<br>    expect(balance).to.equal(&#39;0&#39;);<br>    expect(claimableAmount).to.equal(&#39;5&#39;);<br><br>    // Logging the tokenBalance and the claimableAmount of the investor<br>    console.log(&#39;TokenBalance: &#39; + balance);<br>    console.log(&#39;ClaimableAmount: &#39; + claimableAmount);<br>  });<br><br>});</pre><p>Running this E2E test will result in the following terminal output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*K_fubXUd8XhgVutBKIwMUw.png" /></figure><p>In this episode, we delved deep into smart contract testing within a hardhat project, using Mocha, Chai and Ethers.js. With attention to detail, we explored essential testing techniques to ensure functionality, transparency, and security of smart contracts. By conducting event validations and gas consumption tests, these smart contracts are almost ready to be deployed.</p><p>In previous episodes, we built the core of the bond token issuance platform with the ERC1155 Bond Token contract, as well as KYC and Crypto Securities Register contracts. However, we are still missing an important building block to complete the ecosystem of our Bond Token Issuance Platform.</p><p>In the upcoming episode, we will develop a decentralized exchange (DEX) specifically tailored to the Bond Token Issuance Platform. This concept is crucial to ensure a smooth and seamless trading experience and represents an important step in the development of this project.</p><p>As always, feel free to share and comment!</p><blockquote><strong><em>Disclaimer:</em></strong><em> <br>The code and information provided in this article is for educational and illustrative purposes only. It is not intended for use in production environments without thorough review. Cryptocurrency and smart contract development carry inherent risks, including but not limited to security vulnerabilities and financial losses. Readers are advised to exercise caution and seek professional advice before deploying any code in a real-world setting. The author and publisher disclaim any liability for any damages or losses incurred as a result of using or misusing the code or information presented herein.</em></blockquote><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Getting started with Ethereum</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platfor</a>m</li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li></ul><p>Following episodes:</p><ul><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b1321248387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Regulatory Compliance in the Bond Token Issuance Platform]]></title>
            <link>https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/173c615ada5f</guid>
            <category><![CDATA[register]]></category>
            <category><![CDATA[bond-token]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[cryptosecurity]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 20:50:15 GMT</pubDate>
            <atom:updated>2023-11-20T09:00:05.081Z</atom:updated>
            <content:encoded><![CDATA[<h4>6th episode — KYC &amp; Crypto Securities Register</h4><p>In the previous episode, we finally started to implement the core functionality of the Bond Token Issuance Platform, within the Bond Token Contract. Initially, we began by declaring the modifiers and functions we want to implement. Subsequently, we added mappings and structs as the data structures we want to store bond token metadata as well as necessary investor data, like claimableToken or interestEarned, in. This contract holds the main business logic we need to operate and manage the processes within the bond lifecycle.</p><p>However, in the world of token issuance, technology is only one part of the equation. We must navigate the complex regulatory landscape, especially if token are classified as security token. Determining this classification is not straightforward. It requires a dedicated analysis of the investor rights embodied in the token, such as voting mechanisms or the promise of a return on investment (ROI). Bearer bonds, a relatively straightforward asset, are recognized as securities in numerous jurisdictions.</p><p>Once a token is classified as a security, compliance is non-negotiable. Anti-money laundering (AML) and know-your-customer (KYC) obligations are just the tip of the iceberg. The German Electronic Securities Act (eWpG) of 2021 provides a legal framework in which the issuance of bearer bonds is initially permitted as the first asset. It should be noted that a tokenized bond is equivalent to a traditional bond, except that no securities certificate in the traditional sense is required. The eWpG merely allows the securities to be documented in a so-called crypto securities register (CSR).</p><p>However, implementing a CSR isn’t a straightforward task. Section 17 of the eWpG outlines specific requirements for the registry, mandating the inclusion of precise information. Here lies a challenge - experts are engaged in heated debates, questioning aspects such as anonymity, mutability, and alignment with the General Data Protection Regulation (GDPR) guidelines. We strive to adhere to the eWpG’s requirements, even as we explore practical adaptations based on real-world assumptions. Through this journey, we bridge the gap between legal intricacies and the practical implementation of blockchain technology, aiming for a harmonious blend of regulatory adherence and technological innovation.</p><h4>Disclaimer:</h4><blockquote>The information provided in this article is for informational purposes only and does not constitute legal, financial, or professional advice. The content is meant to offer general insights and understanding of blockchain technology and related concepts. While I strive to present accurate and up-to-date information, the dynamic nature of blockchain technology means that regulations, practices, and standards may change over time.</blockquote><blockquote>Readers are encouraged to seek professional advice, legal counsel, or consult relevant authorities before making any decisions or taking actions based on the information provided in this article. The authors and publishers do not assume any responsibility or liability for the accuracy, completeness, or usefulness of the content presented.</blockquote><blockquote>Additionally, it’s important to note that the concepts discussed in this article might be subject to specific legal and regulatory requirements in different jurisdictions. Readers should conduct thorough research and consider the legal and regulatory frameworks applicable to their specific situation.</blockquote><blockquote>The content in this article is a general overview and does not cover all aspects or nuances related to blockchain technology, smart contracts, or legal compliance. Any reliance on the information provided is at the reader’s own risk.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ThHJUsM12fF3hKm4" /><figcaption>Photo by <a href="https://unsplash.com/@giamboscaro?utm_source=medium&amp;utm_medium=referral">Giammarco Boscaro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this episode, we focus on two aspects: first, the implementation of the KYC contract, followed by the construction of our CSR contract. Since important functionality of the Bond Token contract is closely tied to the KYC and CSR contracts, our logical progression will lead us to complete the functionality of the Bond Token Contract at the end of this episode.</p><h4>Know Your Customer</h4><p>Within the KYC contract, the main goal is to manage which addresses are granted access into the Bond Token Issuance Platform’s ecosystem. In this context, it’s essential to clarify that the focus is solely on the technical aspects of storing this data, not the intricacies of the KYC process itself, which has seen innovative advancements like Zero-Knowledge Proofs (ZKPs), for example.</p><p>A prevalent approach revolves around a straightforward yet powerful concept: the whitelist mapping. This mapping acts as a digital gatekeeper, categorizing addresses into two distinct categories — those permitted to participate and those restricted. To maintain the integrity of this process, we need to implement functions for the whitelisting and blacklisting of addresses. However, this functionality should be restricted to specific authorized operators.</p><pre>mapping (address =&gt; bool) private investorWhitelist;<br>mapping (address =&gt; bool) private issuerWhitelist;<br><br>function whitelistInvestorAddress(address _address) <br>  public onlyAuthorizedOperator() {<br>  require(!investorWhitelist[_address], &quot;Already whitelisted!&quot;);<br>  investorWhitelist[_address] = true;<br>}<br><br>function whitelistIssuerAddress(address _address) <br>  public onlyAuthorizedOperator() {<br>  require(!issuerWhitelist[_address], &quot;Already whitelisted!&quot;);<br>  issuerWhitelist[_address] = true;<br>}<br><br>function blacklistInvestorAddress(address _address) <br>  public onlyAuthorizedOperator() {<br>  require(investorWhitelist[_address], &quot;Already blacklisted!&quot;);<br>  investorWhitelist[_address] = false;<br>}<br><br>function blacklistIssuerAddress(address _address) <br>  public onlyAuthorizedOperator() {<br>  require(issuerWhitelist[_address], &quot;Already blacklisted!&quot;);<br>  issuerWhitelist[_address] = false;<br>}</pre><p>To enforce this hierarchy, a fundamental modifier comes into play — the onlyAuthorizedOperators. This modifier acts as a safeguard, ensuring that only designated addresses possessing the necessary authorization can execute these critical functions. However, we need another mapping and additional functionality, enabling the owner (equivalent to the deployer of the smart contract) to manage and designate certain addresses, which might belong to external entities involved in KYC processes. These addresses are granted the authority to perform tasks like whitelisting and blacklisting.</p><pre>modifier onlyAuthorizedOperator {<br>  require(authorizedOperators[_msgSender()], &quot;Only Authorized!&quot;);<br>  _;<br>}<br><br>mapping (address =&gt; bool) private authorizedOperators;<br><br>function setAuthorizedOperator(address _address) public onlyOwner {<br>  require(!authorizedOperators[_address], &quot;Already authorized!&quot;);<br>  authorizedOperators[_address] = true;<br>}<br><br>function revokeAuthorizedOperator(address _address) public onlyOwner {<br>  require(authorizedOperators[_address], &quot;Already revoked!&quot;);<br>  authorizedOperators[_address] = false;<br>}</pre><p>Furthermore, certain smart contracts might require access to the whitelist mappings when performing transfers. To enable this controlled access, a mapping of authorized contract addresses is established. Following a parallel strategy to whitelisting, we create another modifier named onlyAuthorizedContracts. This modifier stands as a sentinel, guaranteeing that only designated smart contracts with authorized addresses can retrieve information from the whitelist mappings. Thus, we also need functionality to authorize these contract addresses.</p><pre>modifier onlyAuthorizedContract {<br>  require(authorizedContracts[_msgSender()], &quot;Only Authorized!&quot;);<br>  _;<br>}<br><br>mapping (address =&gt; bool) private authorizedContracts;<br><br>function setAuthorizedContract(address _address) public onlyOwner {<br>  require(!authorizedContracts[_address], &quot;Already authorized!&quot;);<br>  authorizedContracts[_address] = true;<br>}<br><br>function revokeAuthorizedContract(address _address) public onlyOwner {<br>  require(authorizedContracts[_address], &quot;Already revoked!&quot;);<br>  authorizedContracts[_address] = false;<br>}<br><br>function isWhitelistedAsInvestor(address _address) <br>  external view onlyAuthorizedContract returns (bool) {<br>  return investorWhitelist[_address];<br>}<br><br>function isWhitelistedAsIssuer(address _address) <br>  external view onlyAuthorizedContract returns (bool) {<br>  return issuerWhitelist[_address];<br>}</pre><p>Having implemented these, we are good to go and are able to shift the focus on a novel concept of Securities Registers — called<em> Crypto Securities Registers</em>.</p><h4>Crypto Securities Register</h4><p>When it comes to the CSR, the implementation becomes more complex and less flexible. Essentially, section 17 of the German eWpG outlines seven crucial details that must be implemented into a Crypto Securities Register. These are the following:</p><ol><li>The incorporated rights including a unique Identifier and the designation as a Security</li><li>Emission Volume</li><li>Nominal Value</li><li>Issuer</li><li>Single or Group Entry</li><li>Holder of the Tokens</li><li>Mixed Assets Information according to § 9 Paragraph 3. eWpG</li></ol><pre>struct CSRStruct {<br>  string issuer;<br>  address issuerAddress;<br>  bytes32 incorporatedRights;<br>  TokenMetaData tokenMetaData;<br>  TokenState state;<br>  mapping(address =&gt; InvestorData) investors;<br>}<br><br>struct TokenMetaData {<br>  uint256 parValue;<br>  uint256 interestRate;<br>  uint256 minFundingGoal;<br>  uint256 maxFundingGoal;<br>  uint256 soldTokens;<br>  uint256 issuanceDate;<br>  uint256 claimableDate;<br>  uint256 tradingDate;<br>  uint256 maturityDate;<br>}<br><br>struct InvestorData {<br>  bool singleEntry;<br>  bytes32 restrictionsOnDisposal;<br>  bytes32 thirdPartyRights;<br>  InvestorType investorType;<br>  uint256 balance;<br>}<br><br>uint256 private _tokenId;<br><br>mapping(uint256 =&gt; CSRStruct) private registry;</pre><p>As far as I understand section 17 of the eWpG, and I am not a lawyer, there is no requirement to order the requested data in any particular way. Of course, the data should be coherent and recognizable as such. For example, we use the Unique identifier included in the Incorporated Rights of the specific token also as an access key for our registry mapping. Basically, we have a Crypto Securities Register Smart Contract, with a CSRStruct for each individual token. Besides storing essential data from section 17 of the eWpG, we enrich the CSR with additional data. Data that supports a smooth process and is closely linked to the token metadata anyway.</p><p>Inside the CSRStruct, we store the name of the issuing company as a string issuer as well as the address issuerAddress. Additionally, the incorporated rights of the bond token including the token identifier, as well as the designation as a security, will be encode by hashing first and encoding the resulting hash to a bytes32 incorporatedRights afterwards. This ensures integrity, as we can then verify that both the hashed clear text from the securities prospectus or published online data and the decoded bytes32 are equal.</p><p>The core metadata of the bond token is then stored in an additional Struct called tokenMetaData. This includes information on the parValue, interestRate, minFundingGoal, maxFundingGoal, soldTokens, issuanceDate, claimableDate, tradingDate and maturityDate. All of which are stored as a uint256. What’s necessary for complying with the eWpG is essentially the parValue (assuming to equal the nominal value) and the soldTokens (equivalent to the emission volume).</p><p>minFundingGoal and maxFundingGoal are used to set boundaries on the token issuance. These is a <em>nice to-have</em> functionality and offers the issuer the option to set a lower boundary, until which tokens could be refunded if the threshold is not reached in time. The maxFundingGoal, setting the upper boundary, is the maximum amount of tokens that can be sold.</p><p>Setting these will have effect on the business logic of the buyTokens function of the BondToken contract. If the minFundingGoal is set to ZERO, tokens will be transferred immidately to the investor. Otherwise, the bought tokens are added to the claimableToken amount in the Bond Token contract.</p><pre>function buyToken(uint256 _id, uint256 _amount) <br>  public payable onlyWhitelistedAndRegistered(_msgSender(), _id) <br>  {<br>  require(tokenData[_id].issued, &quot;Not issued yet!&quot;);<br>  require(block.timestamp &lt; tokenData[_id].metaData.claimableDate, &quot;Pre-Sale is over!&quot;);<br>  require(enoughTokenRemain(_id, _amount), &quot;Amount too high!&quot;);<br>  require(msg.value &gt;= (_amount * tokenData[_id].metaData.parValue), &quot;Amount too low!&quot;);<br><br>  tokenData[_id].metaData.soldTokens += _amount;<br>  tokenData[_id].pool.receivedBalance += msg.value;<br>  address _addressOfIssuer = csrInstance.getAddressOfIssuer(_id);<br><br>  if (!(tokenData[_id].metaData.minFundingGoal == 0)) {<br>    investorData[_id][_msgSender()].claimableAmount += _amount;<br>    investorData[_id][_msgSender()].lastCalculationDate = tokenData[_id].metaData.tradingDate;<br>  } else {<br>    investorData[_id][_msgSender()].lastCalculationDate = tokenData[_id].metaData.tradingDate;<br>    csrInstance.updateCSR(_id, _addressOfIssuer, _msgSender(), _amount);<br>    _safeTransferFrom(_addressOfIssuer, _msgSender(), _id, _amount, &quot;&quot;);<br>  }<br>}</pre><p>We use UNIX timestamps — elapsed seconds since the January 1st, 1970 — for the various stages of the bond issuance.</p><ul><li>When reaching the issuanceDate, investors are able to invest in the bond during the primary issuance.</li><li>The claimableDate marks both the ending of the primary issuance and enables investors to claim tokens, if the minFundingGoal is reached.</li><li>The tradingDate, as the name suggests, starts the trading phase and enables investors to trade the bond token on the secondary market. Additionally, the tradingDate enables the calculation of the interest earned.</li><li>Lastly, the maturityDate marks the day from which on investors are able to claim the parValue and burn the bond tokens.</li></ul><p>Section 17 of the German eWpG requires us to store information on the holder of the tokens including the address and the balance, as well as whether it is a single entry or a group entry. Being a single entry means, that the investor holds the tokens for himself, while group can be seen as holding tokens on behalf of multiple entities.</p><p>If it is a single entry, the investor also needs to provide information about the <em>Restrictions on disposal in favor of a specific person</em>, and the <em>Rights of third parties</em>. If provided by the investor, both will be stored as bytes32.</p><p>If a company want to issue a bond token, it needs to provide information on the bond token such as the issuer name, the incorporated rights of the bond and the token metadata.</p><pre>function registerBond(<br>      string memory _issuer, <br>      bytes32 _incorporatedRights, <br>      TokenMetaData memory _tokenMetaData<br>      ) public onlyWhitelistedIssuer {<br>  _tokenId++;<br>  registry[_tokenId].issuer = _issuer;<br>  registry[_tokenId].issuerAddress = _msgSender();<br>  registry[_tokenId].incorporatedRights = _incorporatedRights;<br>  registry[_tokenId].tokenMetaData = _tokenMetaData;<br>}</pre><p>If everything is fine, a registrar can then approve the bond issuance.</p><pre>function approveBond(uint256 _id) public onlyRegistrar {<br>  require(registry[_id].state == TokenState.REGISTERED, <br>    &quot;Bond already approved!&quot;);<br>  registry[_id].state = TokenState.APPROVED;<br>}</pre><p>Lastly, an issuer has to start the preSale after a successful approval, if the issuanceDate is reached. Since we can restrict investor activity to start after we reached the issuanceDate, this step might be obsolete. This is currently being analyzed.</p><pre>function startPreSale(uint256 _id) public onlyIssuerOfId(_id) {<br>  require(registry[_id].state == TokenState.APPROVED, <br>    &quot;Not applicable!&quot;);<br>  require(block.timestamp &gt;= registry[_id].tokenMetaData.issuanceDate, <br>    &quot;Did not reach issuance date yet!&quot;);<br>  registry[_id].state = TokenState.ISSUANCE;<br>}</pre><p>Likewise with the KYC contract, some functions need to be restricted and therefore we need some modifiers.</p><pre>modifier onlyRegistrar() {<br>  require(_msgSender() == registrar, <br>  &quot;Only registrar!&quot;);<br>  _;<br>}<br><br>modifier onlyWhitelistedIssuer {<br>  require(kycInstance.isWhitelistedAsIssuer(_msgSender()), <br>  &quot;Address is not whitelisted as an issuer&quot;);<br>  _;<br>}<br><br>modifier onlyWhitelisted {<br>  require(kycInstance.isWhitelisted(_msgSender()), <br>  &quot;Address is not whitelisted&quot;);<br>  _;<br>}<br><br>modifier onlyIssuerOfId(uint256 _id) {<br>  require(registry[_id].issuerAddress == _msgSender(), <br>  &quot;Only Issuer!&quot;);<br>  _;<br>}<br><br>modifier onlyBondTokenContract {<br>  require(bondTokenInstance == BondToken(_msgSender()), <br>  &quot;Only Bond token contract!&quot;);<br>  _;<br>}</pre><p>We can now focus on the implementation of the functionality of the Bond Token contract, which needs to call certain functions of the CSR smart contract.</p><h4>Finalizing the Bond Token Contract</h4><p>Essentially, the CSR is being affected and needs to get updated on certain events during the lifecycle of the bond. The first step is the issuance or minting the token. The Bond Token contract needs to retrieve the tokenMetaData, which can be accessed by externally calling csrInstance.getTokenMetaData(_id).</p><pre>/**<br> * Inside the BondToken contract<br> */ <br>function issueToken(uint256 _id) public onlyIssuerOfId(_id){<br>   require(!tokenData[_id].issued, &quot;Already issued!&quot;);<br>   tokenData[_id].metaData = csrInstance.getTokenMetaData(_id);<br>   tokenData[_id].issued = true;<br>   _mint(_msgSender(), _id, tokenData[_id].metaData.maxFundingGoal, &quot;&quot;);<br> }</pre><pre>/**<br> * Inside the CSR contract<br> */<br>function getTokenMetaData(uint256 _id) <br>  external view onlyBondTokenContract <br>  returns (BondToken.TokenMetaData memory _tokenMetaData) <br>  {<br>  require(registry[_id].state == TokenState.ISSUANCE, &quot;Incorrect state!&quot;);<br>  return BondToken.TokenMetaData(<br>    registry[_id].tokenMetaData.parValue,<br>    registry[_id].tokenMetaData.interestRate,<br>    registry[_id].tokenMetaData.minFundingGoal,<br>    registry[_id].tokenMetaData.maxFundingGoal,<br>    registry[_id].tokenMetaData.soldTokens,<br>    registry[_id].tokenMetaData.issuanceDate,<br>    registry[_id].tokenMetaData.claimableDate,<br>    registry[_id].tokenMetaData.tradingDate,<br>    registry[_id].tokenMetaData.maturityDate,<br>    registry[_id].issuerAddress<br>  );<br>}</pre><p>As mentioned previously, section 17 of the German eWpG needs information on the balances of the holders, even if we could access this information inside the BondToken contract. Thus, we need update the CSR every time someone buys a token during the primary issuance, transfers or claims a token and when finally claiming the parValue at maturity.</p><pre>/**<br> * Inside the BondToken contract<br> */<br>function buyToken(uint256 _id, uint256 _amount) <br>  public payable onlyWhitelistedAndRegistered(_msgSender(), _id) <br>  {<br>  require(tokenData[_id].issued, &quot;Not issued yet!&quot;);<br>  require(block.timestamp &lt; tokenData[_id].metaData.claimableDate, &quot;Pre-Sale is over!&quot;);<br>  require(enoughTokenRemain(_id, _amount), &quot;Amount too high!&quot;);<br>  require(msg.value &gt;= (_amount * tokenData[_id].metaData.parValue), &quot;Amount too low!&quot;);<br><br>  tokenData[_id].metaData.soldTokens += _amount;<br>  tokenData[_id].pool.receivedBalance += msg.value;<br>  address _addressOfIssuer = tokenData[_id].metaData.issuerAddress;<br>  investorData[_id][_msgSender()].lastCalculationDate = tokenData[_id].metaData.tradingDate;<br><br>  if (!(tokenData[_id].metaData.minFundingGoal == 0)) {<br>    investorData[_id][_msgSender()].claimableAmount += _amount;<br>  } else {<br>    csrInstance.updateCSR(_id, _addressOfIssuer, _msgSender(), _amount);<br>    _safeTransferFrom(_addressOfIssuer, _msgSender(), _id, _amount, &quot;&quot;);<br>  }<br>}<br><br>function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) <br>  public virtual override <br>  {<br>  require(kycInstance.isWhitelisted(to), &quot;Address is not whitelisted&quot;);<br>  csrInstance.updateCSR(_id, _from, _to, _amount);<br>  _safeTransferFrom(_from, _to, _id, _amount, _data);<br>}<br><br>function claimToken(uint256 _id) public {<br>  require(block.timestamp &gt; tokenData[_id].metaData.claimableDate, &quot;Too early!&quot;);<br>  require(tokenData[_id].metaData.soldTokens &gt;= tokenData[_id].metaData.minFundingGoal, &quot;Softcap not reached!&quot;);<br><br>  uint256 _amount = investorData[_id][_msgSender()].claimableAmount;<br>  investorData[_id][_msgSender()].claimableAmount = 0;<br><br>  address _addressOfIssuer = tokenData[_id].metaData.issuerAddress;<br>  csrInstance.updateCSR(_id, _addressOfIssuer, _msgSender(), _amount);<br>  _safeTransferFrom(_addressOf, _msgSender(), _id, _amount, &quot;&quot;);<br>}<br><br>function claimParValue(uint256 _id) public {<br>  require(block.timestamp &gt; tokenData[_id].metaData.maturityDate, &quot;Too early!&quot;);<br><br>  calculateInterest(_id, _msgSender());<br>  uint256 balance = balanceOf(_msgSender(), _id);<br>  csrInstance.updateCSR(_id, _msgSender(), address(0), _amount);<br>  _burn(_msgSender(), _id, balance);<br>  uint256 claimableParValue = tokenData[_id].metaData.parValue * balance;<br>    <br>  require(claimableParValue &gt;= tokenData[_id].pool.parValueBalance, &quot;Insufficient liquidity!&quot;);<br>  tokenData[_id].pool.parValueBalance -= claimableParValue;<br><br>  payable(_msgSender()).transfer(claimableParValue);<br>}</pre><pre>/**<br> * Inside the CSR contract<br> */<br>function updateCSR(uint256 _id, address _from, address _to, uint256 _amount) <br>  external onlyBondTokenContract <br>  {<br>  if (_from != registry[_id].issuerAddress) {<br>    // After _safeTransferFrom individual investor<br>    registry[_id].investors[_from].balance -= _amount;<br>  } else {<br>    // Primary Issuance Update<br>    registry[_id].tokenMetaData.soldTokens += _amount;<br>  }<br><br>  if (_to != address(0)) {<br>    // If tokens are getting burned, we do not want to update<br>    registry[_id].investors[_to].balance += _amount;<br>  }<br>}</pre><p>Huh, this was a little much, right? Implementing complex functionality requires a lot of code overview. I hope you already got some. Anyways, you can always check out the code in the gitHub repository. Besides the KYC and CSR contracts, I’ve also implemented the complete functionality of the BondToken contract. In the next episode, we’re going to spend some time on writing unit tests with mocha.js and chai! So stay tuned and keep practicing! Feel free to share, like and leave comments!</p><blockquote><strong><em>Disclaimer:</em></strong><em> <br>The code and information provided in this article is for educational and illustrative purposes only. It is not intended for use in production environments without thorough review. Cryptocurrency and smart contract development carry inherent risks, including but not limited to security vulnerabilities and financial losses. Readers are advised to exercise caution and seek professional advice before deploying any code in a real-world setting. The author and publisher disclaim any liability for any damages or losses incurred as a result of using or misusing the code or information presented herein.</em></blockquote><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Getting started with Ethereum</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platfor</a>m</li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li></ul><p>Following episodes:</p><ul><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=173c615ada5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tokenization: Bringing Bonds to the Blockchain]]></title>
            <link>https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d75d56fd6e</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[bond-token]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 11:06:48 GMT</pubDate>
            <atom:updated>2023-11-20T08:59:45.377Z</atom:updated>
            <content:encoded><![CDATA[<h4>5th episode — Token and Token Standards</h4><p>Tokenization is the process of converting real-world or digital assets into tokens. But what does that mean exactly? What is a token in simple terms and how are tokens represented on a blockchain protocol like Ethereum?</p><p>Simply said, a token is the digital representation of an asset. In our context, the Bond Token is an exact replica of a traditional bond. Hence, the token must embody all the rights and characteristics of a traditional bond, such as ownership rights through proof of ownership, the right to receive interest payments, and so forth.</p><p>We know how to implement smart contracts, but how do we mint, issue or trade tokens? Technically, we need to differentiate between tokens and native tokens, also called coins, first. Other than ether, a token is bound to the smart contract it is created in. Even when speaking of trading a token, the token does not <em>leave</em> the contract or is transferred between addresses, as one might think. Actually, a token is nothing else than an entry in a mapping. We simply allocate a balance (uint256) to an address as the key.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract SimpleToken {<br>    string public name = &quot;A Simple Token&quot;;   // Token name<br>    string public symbol = &quot;ST&quot;;             // Token symbol<br>    uint8 public decimals = 18;              // Token decimals (usually 18)<br><br>    mapping(address =&gt; uint256) public balanceOf;<br><br>    constructor(uint256 initialSupply) {<br>        balanceOf[msg.sender] = initialSupply * (10 ** uint256(decimals));<br>    }<br>}</pre><p>Currently, we are not able to transfer tokens between addresses, mint or burn tokens. By applying the knowledge about solidity we gained in the previous episodes, we could theoretically build our own functions, which can be tailored to meet pecific project needs. In principle, we can design our token to suit any requirement. What sounds compelling at first glance can lead to a facet of several problems.</p><p>Imagine a variety of projects, all implementing their own custom token. In this thriving ecosystem, the token landscape is diverse and vibrant. However, it’s also fragmented, with each custom token operating under its unique set of rules and functionalities. This fragmentation poses several challenges:</p><ol><li>Token holders face barriers when attempting to trade their assets on various exchanges, as these are not able to adapt to provide custom interfaces to meet the expected behavior of the token contract. Consequently resulting in many tokens remaining illiquid.</li><li>As the number of custom tokens soars, ensuring the <strong>security</strong> of these tokens and their smart contracts becomes paramount. <strong>Auditing</strong>, a crucial aspect of token creation, becomes increasingly complex and challenging due to the unique nature of each token.</li><li>Custom tokens often lack the <strong>interoperability</strong> required to seamlessly interact with various DApps, exchanges, and wallets. This fragmentation hampers the utility and adoption of these tokens.</li></ol><h4>To tackle these challenges, we need some kind of standardization</h4><p>In the context of token standards, <strong>standardization</strong> refers to the establishment of a common set of rules, functions, and interfaces that tokens of a particular type or category should follow. These standardized rules ensure consistency and interoperability within the blockchain ecosystem. Standardization does by no means limit the possibilities of custom functionality.</p><ol><li><strong><em>Standardization</em></strong> involves defining a set of common specifications and behaviors that tokens of a specific standard should adhere to. These specifications can cover various aspects of token functionality, including how tokens are created, transferred, and managed.</li><li>Token standards provide uniform <strong><em>interfaces</em></strong> that allow tokens to interact seamlessly with wallets, exchanges, decentralized applications (DApps), and other blockchain-related services. This consistency simplifies the integration of tokens into different platforms.</li><li>Standardized tokens are expected to exhibit <strong><em>predictable behavior</em></strong>. For example, users and developers can rely on standard functions like <em>transfer</em> and <em>balanceOf</em> to work consistently across all tokens of a particular standard. This predictability enhances user trust and ease of use.</li><li>Standardized token contracts often incorporate security best practices, reducing the risk of vulnerabilities. Auditors and developers are familiar with the patterns and structures used in standard tokens, making <strong><em>audits and security assessments</em></strong> more efficient.</li></ol><p>The development and adoption of token standards typically involve consensus-building within the blockchain community. Developers, users, and businesses come together to agree on a common set of rules and behaviors, fostering trust and alignment. This is where the Ethereum Request for Comments, ERC in short, comes into play.</p><h4><strong>Ethereum Request for Comments</strong></h4><p>It’s a formal system used to propose improvements to the Ethereum network. If you want to screen details of some ERCs, you might access the official ethereum <a href="https://eips.ethereum.org/erc">documentation</a>. The most prominent ERC is the <a href="https://eips.ethereum.org/EIPS/eip-20">ERC-20 Token Standard</a>.</p><p>In this case, the proposal outlined a set of standard rules and functions for creating tokens on the Ethereum blockchain. This standardization was a response to the growing need for a common framework that could ensure interoperability between different tokens and platforms within the Ethereum ecosystem. Despite having several other Token Standards that emerged in the past years, the ERC-20 Token Standard was used as the blueprint for famous tokens including Tether (USDT), Chainlink (Link) or Uniswap (UNI).</p><h4>Selecting a multi-token Standard for our Bond Token Platform</h4><p>The simplest way of issuing different bond tokens would suggest to deploy a separat ERC-20 Token Contract for each issuance. This would allow for maximum flexibility in contract functionality, but issuance costs would increase significantly and managing complexity would become less and less doable over time. As we aim to build a cost efficient, modular platform with reduced complexity, wouldn’t it be nice to have one token contract that is capable of managing multiple different tokens?</p><p>Well, one of the unique features of the ERC-1155 Token Standard is its ability to handle both fungible and non-fungible tokens within the same contract. For a bond issuance platform, this means we are able to represent various types of bonds, each with its own distinct attributes, all within a single smart contract. ERC-1155 allows multiple token types to coexist in a single contract, drastically reducing the gas fees associated with deploying and managing multiple contracts.</p><p>Additionally, ERC-1155 enables batch transfers and interactions. Investors can acquire or trade multiple bonds in a single transaction, enhancing user experience and reducing network congestion.</p><p>Let’s take a look at the core functionality that comes with the ERC-1155 Token Standard. We then analyze which features are missing, thus needed to be implemented on top of that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abf5b80a091ec6e47dbc6b2f9d15b0a3/href">https://medium.com/media/abf5b80a091ec6e47dbc6b2f9d15b0a3/href</a></iframe><p>By simply writing contract BondToken is ERC1155, we are able to access these functions to mint, burn or transfer tokens, verify balances, or approve addresses to transfer tokens on our behalf, for example. This lays the foundation for further development of our Bond Token Issuance Contract.</p><pre>contract BondToken is ERC1155 {<br><br>   // Do something...<br><br>}</pre><p>We still need to expand this set of built-in functionality, of course. Since we already know which additional features we are looking for, we are able to define these methods in an interface. These must then be implemented at a subsequent point in the near future.</p><pre>interface IBondToken {<br><br>  function issueToken(uint256 _id) public;<br><br>  function buyToken(uint256 _id, uint256 _value) external payable;<br><br>  function claimRefund(uint256 _id) external;  <br><br>  function claimToken(uint256 _id) external;<br><br>  function claimInterest(uint256[] _ids) external;<br><br>  function claimParValue(uint256[] _ids) external;<br><br>  function calculateInterest(uint256 _id, address _address, uint256 _amount) external;<br><br>  function provideInterest(uint256 _id) external payable;<br><br>  function provideParValue(uint256 _id) external payable;<br><br>  function withdrawEther(uint256 _id) external;<br>  <br>  function setCSRContractAddress(address _csr) external;<br><br>  function setKYCContractAddress(address _kyc) external;<br>}</pre><p>In addition, we must modify some functions, or rather override them, to satisfy KYC requirements, for example, and permit transfers to whitelisted investors only. We aim to restrict minting exclusively to the issuance phase. The complexity increases, as transfer functions will be required to invoke internal functions for interest calculation and initiate external contract calls to the CSR and KYC Contracts, among other functionalities.</p><pre>interface IOverride {<br><br>  function setApprovalForAll() public virtual override<br><br>  function safeTransferFrom() public virtual override;<br><br>  function safeBatchTransferFrom() public virtual override;<br><br>}</pre><p>Let’s take a step back and return to the topic of tokenization. Remember, the focus was on creating a digital representation of a conventional bond. This requires the implementation of appropriate data structures that can effectively map this metadata. Consequently, we need to keep track of key properties such as interest payments per investor, which must also be recorded accurately in appropriate data structures. For this purpose, we use mappings and structs. The following is a first draft that may be refined in the course of implementation to meet our requirements.</p><pre>mapping (uint256 =&gt; TokenStruct) public tokenData;<br><br>struct TokenStruct {<br>  TokenMetaData metaData;<br>  TokenPool pool;<br>  bool issued;<br>}<br><br>struct TokenMetaData {<br>  uint256 parValue;<br>  uint256 interestRate;<br>  uint256 minFundingGoal;<br>  uint256 maxFundingGoal;<br>  uint256 soldTokens;<br>  uint256 issuanceDate;<br>  uint256 tradingDate;<br>  uint256 maturityDate;<br>}<br><br>struct TokenPool {<br>  uint256 interestBalance;<br>  uint256 parValueBalance;<br>  uint256 receivedBalance;<br>}</pre><pre>mapping (uint256 =&gt; mapping (address =&gt; InvestorStruct)) public investorData;<br><br>struct InvestorStruct {<br>  uint256 claimableAmount;<br>  uint256 interestEarned;<br>  uint256 lastCalculationDate;<br>}</pre><p>Independently of this, we still need to define modifiers that restrict the execution of individual functions, e.g. for onlyWhitelisted, onlyOwner or onlyIssuer.</p><p>A modifier can be added to a functions signature and gets checked first when a function is getting called. Imagine we already have implemented our KYC contract, which has a function isWhitelisted that returns a bool. In our BondToken contract, we want to allow investors to transfer tokens to addresses that are whitelisted only. This may look like this:</p><pre>pragma solidity ^0.8.0;<br><br>interface KYC {<br>    function isWhitelisted(address _address) external view returns (bool);<br>}<br><br>contract BondToken {<br>    KYC public kycInstance;<br><br>    modifier onlyWhitelisted(address _address) {<br>        require(kycInstance.isWhitelisted(_address), &quot;Address is not whitelisted&quot;);<br>        _;<br>    }<br><br>    constructor(address _kycAddress) {<br>        kycInstance = KYC(_kycAddress);<br>    }<br><br>    function transfer(address _to, uint256 _amount) external onlyWhitelisted(_to) {<br>        // Do something...<br>    }<br>}</pre><p>In this case, we added a parameter _address to the modifier, representing the address we want to check. When calling the transfer function, the modifier gets executed first. If the _address is not whitelisted, the transaction is reverted. Not only does the potential transfer not take place, the entire transaction, including any changes made before the modifier, will be undone if the modifier’s condition is not met.</p><p>The entire transaction state is reverted to its original state, as if none of the functions in the transaction were ever called. This helps maintain the integrity and consistency of the blockchain’s state.</p><p>It is crucial to define events to provide transparency and allow external applications to track important contract actions. Events act as a signaling mechanism, broadcasting specific occurrences within the contract to the outside world. For instance, when issuers successfully provide liquidity or investors execute token transfers, we can emit corresponding events to record these actions. By defining events, we enable external entities, such as user interfaces, to listen for these events and respond accordingly. This enhances the overall usability and transparency of our BondToken contract, making it easier for users and other systems to interact with and monitor the contract’s activities.</p><p>While we recognize the importance of these events, we will implement them in our contract at a later stage as we progress through the development process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1PQveRhsqfpd-EhE" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we took a deep look at blockchain tokens, exploring the intricate world of token standards, with a specific focus on ERC-1155, a cornerstone of our Bond Token Issuance Platform. We’ve discussed essential functions and examined complex data structures for bond token metadata, as well as strategized how we could handle corporate action like interest payments.</p><p>In the next episode, we start to implement both the KYC and CSR contract. Feel free to share, like and leave comments!</p><blockquote><strong><em>Disclaimer:</em></strong><em> <br>The code and information provided in this article is for educational and illustrative purposes only. It is not intended for use in production environments without thorough review. Cryptocurrency and smart contract development carry inherent risks, including but not limited to security vulnerabilities and financial losses. Readers are advised to exercise caution and seek professional advice before deploying any code in a real-world setting. The author and publisher disclaim any liability for any damages or losses incurred as a result of using or misusing the code or information presented herein.</em></blockquote><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Getting started with Ethereum</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platfor</a>m</li></ul><p>Following episodes:</p><ul><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><p>PS: If you’re interested in how data is stored technically in the ethereum protocol, I kindly recommend reading the following article on Ethereum’s State Trie Architecture!</p><p><a href="https://medium.com/@eiki1212/ethereum-state-trie-architecture-explained-a30237009d4e">Ethereum State Trie Architecture Explained</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d75d56fd6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting a Solid Architecture for the Bond Token Issuance Platform]]></title>
            <link>https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/34db90db60a</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[bond-token]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 10:18:45 GMT</pubDate>
            <atom:updated>2023-11-20T14:49:26.607Z</atom:updated>
            <content:encoded><![CDATA[<h4>4th Episode — Building a Modular Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VA7grIDJL4rmniqZ" /><figcaption>Photo by <a href="https://unsplash.com/@pixelatelier?utm_source=medium&amp;utm_medium=referral">Christian Holzinger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous episode, we explored various blockchain development tools and I know you want to start writing productive code right away. Again, we first need to take a step back and address yet another crucial phase in the course of preparing the software development process. It’s the blueprint that defines how software components work together, whether in blockchain or any other application: <strong><em>The Architecture</em></strong>.</p><blockquote>Architecture in software development refers to the high-level structure and design of a software system. It serves as the blueprint that outlines how different components of a software application interact with each other to achieve specific goals.</blockquote><p>We analyzed the traditional financial market infrastructure and were able to identify certain AoIs. With this in mind, we’ve formulated several design objectives. Nevertheless, these objectives alone aren’t sufficient to commence the development of a functional and outstanding software solution. What we require is a comprehensive overview of all the components that will form our platform and how they interconnect. This not only aids in estimating time and resource requirements but also in effectively managing the intricate dependencies within our project.</p><h4>Key Differences between web2 and web3 Apps</h4><p>When we think of traditional web applications, we are actually referring to what we call web2 applications. These applications are characterized by a centralized 3-tier architecture design that concentrates data and functionality, follows the client-server model for interactions, and employs databases:</p><ol><li>Presentation Layer: This is where the <strong><em>User Interface</em></strong> (UI) resides. It’s responsible for rendering web pages, handling user interactions, and displaying data.</li><li>Application Layer: Often referred to as the <strong><em>Backend</em></strong>, this layer usually houses the core business logic and application functionality. It communicates with the presentation layer and the data layer, usually handling tasks such as user authentication, data processing, and server-side operations.</li><li>At the foundation of the stack lies the <strong><em>Data Layer</em></strong>. This layer is responsible for data storage, retrieval, and persistence. It’s where user information, application data, and other relevant information are securely stored.</li></ol><p>Web3 apps extend the architecture of Web2 web apps by introducing decentralization, blockchain technology, smart contracts, and user empowerment into the software landscape. This evolution aims to create a more secure, transparent, and user-centric digital environment, reshaping how users interact with digital applications and services.</p><p>Our Web3 application harnesses the best of both worlds. We retain the familiar structure of a traditional 3-tier web application, ensuring a user-friendly and intuitive interface, storing GDPR-sensitive data and other additional data in a <em>normal</em> database. Simultaneously, we integrate the power of the Ethereum protocol inluding smart contracts to enhance security, transparency, and process automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lG-9qSBtRGmPt4w2tmZf7A.png" /></figure><p>The displayed architecture visualizes the separated parts, as our bond token issuance platform will be divided into two distinct stacks. On one hand, we have the traditional 3-tier web application, consisting of an Angular Frontend, a Spring Backend, and a database. Communication with blockchain protocols itself is a vast topic, as we’re not able to just send a request to the blockchain directly. The blockchain is not stored on centralized servers. Instead, it is distributed over a large number of nodes. Therefore, the frontend communicates with the blockchain protocol via MetaMask, a wallet provider, and Ethereum nodes. We differentiate between calls (like queries), when we want to read data, and transactions, which need to be signed by your wallet.</p><p>On the other hand, the main issuance platform, including business logic and relevant data, will be represented by and stored in smart contracts, which will get deployed on an EVM-compatible blockchain protocol. As this blog series is for educational and demonstrative purposes only, we will simply deploy our smart contracts on an Ethereum testnet. This approach allows us to test and refine our platform’s functionality while avoiding real Ethereum network costs.</p><p>The Angular frontend mainly serves the idea of displaying data and providing a user interface to interact with the blockchain protocol. Some components will only serve to communicate with the Spring Backend and visualize information, while others connect to a Blockchain node. Basically, we will need components for:</p><ul><li>User registration (investors and companies)</li><li>Issuance planning and registration</li><li>Issuer Token Management (providing interest liquidity e.g.)</li><li>Overview Dashboards for Bond Token Visualization (Price, Holders)</li><li>Token pages including metadata, transaction history and events</li><li>User portfolio with historic data (incl. received interest payments)</li><li>Decentralized Exchange Interface</li></ul><p>Our backend stack (Spring application &amp; database) serves the purpose of storing and processing GDPR-sensitive data like user information, issuer and investor account data, as well as documents like securities prospectus. Previously queried data from the blockchain will likely be cached as well. The main logic, or the execution of the core logic of the bond token issuance platform will be represented using smart contracts. Let’s step back and take a look at the big picture.</p><p>We want to bring the whole lifecycle of a corporate bond to the blockchain. This starts with the registration or filling of an issuance, minting the token, buying and selling the token in a primary sale, transferring a token and recording ownership, as well as managing corporate actions, getting paid interest and the par value of the bond at the maturity date. Despite being an interface in our frontend, the functionality triggered will be executed on the blockchain. The data will also be stored on the blockchain.</p><p>Everything so far only affects the UI and additional data storage. In fact, this is anything but the MVP — the Minimum Viable Product and thus only optional. A UI can be visually appealing, but it is useless without the core functionality. Basically, the core functionality breaks up into security issuance and trading. We specifically exclude pre-issuance processes like bond structuring and issuance strategy, as this process is not affected by blockchain technology. Remember, we focus on blockchain as the technological infrastructure to facilitate automated, cost and time effective processes.</p><p>Let’s break down the traditional market infrastructure for security issuance and trading, along with the associated players and processes, and then explore how we plan to integrate these elements into our bond token issuance platform:</p><h4>Security Issuance and Trading</h4><p>The issuance and trading process of securities may be settled via blockchain technology. Our goal is to eliminate intermediaries and automate processes that usually involve multiple players and are not time efficient. In the security issuance domain, issuing companies work alongside investment banks or underwriters to perform due diligence, create legal documents, and seek regulatory approval. Marketing and sales efforts follow the issuance process.</p><p>For security trading, stock exchanges usually serve as marketplaces, brokerage firms act as intermediaries, and investors buy and sell securities. Clearinghouses ensure trade settlement, and reporting obligations exist for regulatory compliance.</p><p>In our bond token issuance platform, we plan to integrate both security issuance and trading processes. There are processes such as the creation of legal documents or other processes that serve the preparation of an issue, such as agreeing on term sheet conditions, that are either not applicable to be replicated on the blockchain or are merely more efficient to be carried using central processes and systems. Remember, blockchain has its strengths in documenting and executing state changes. The platform will provide smart contracts for Bond Token Issuance, KYC and Crypto Securities Registers. Additionally, a decentralized exchange (DEX) component will enable users to trade bond tokens directly, bypassing traditional intermediaries and enhancing efficiency and transparency in the trading process. This integrated approach aims to empower issuing companies, investors, and regulators while leveraging the benefits of blockchain technology.</p><p>The core of our bond token issuance platform is the Bond Token Contract, which will inherit from an established ERC Token Standard. If you don’t grasp the idea of token standards yet, don’t worry. We will dedicate the next episode on Tokens, Token Standards, regulatory and security considerations that come with it, and essentially which one we’re going to implement in our platform.</p><h4>The Bond Token Contract</h4><p>This smart contract will include the functionality surrounding the issuance and core properties of a bond token incl. metadata derived from the term sheet. Whitelisted investors should be able to buy or invest in tokens either instantly or be able to claim them at a certain predefined date, if this functionality was checked in the registration by the issuer. The contract should facilitate investors to transfer their tokens to whitelisted addresses. Issuers must be able to provide liquidity into dedicated pools for recurrent interest payments, which investors should be able to claim. Complementing this, the same idea arises for the bond buyback and the investors ability to claim the parValue of the bond. Additionally, investors might approve whitelisted addresses to spend tokens on their behalf.</p><p>Indicated by the previous statements, investors and issuers alike have to be whitelisted to interact with the token functionalities.</p><h4>The KYC Contract</h4><p>Each transfer call should check if the recipient is whitelisted on the platform and permitted for trading securities. In the KYC Contract, the platform or any authorized third party should be able to whitelist investors and issuers alike. Additionally, investors or issuers might be blacklisted and thus be excluded from trading or investing for a limited or undefined period of time. As whitelisting or blacklisting addresses is <strong>not</strong> the most complex functionality, you might ask, why we won’t implement this into the Bond Token Contract. While it makes sense to minimize costs by deploying less contracts, each contract should hold its own responsibility. The <strong><em>separation of concerns</em></strong> is a fundamental design principle in software development. It is a concept that encourages breaking down a software system into distinct and independent modules or components, each of which addresses a specific aspect or responsibility of the overall system. This separation helps to manage complexity, improve maintainability (despite having a different meaning in the context of blockchain), and enhance the overall design of our software. Additionally, we can grant access to other contracts to retrieve the information too, minimizing redundant storage. We don’t need multiple databases if there is a decentralized store of whitelisted addresses.</p><p>Another major regulatory influence arises from the introduction of the German eWpG, which stands for “Electronic Securities Act” (Gesetz über elektronische Wertpapiere). Essentially, the eWpG is a significant piece of legislation that facilitates the issuance and registration of securities as digital tokens on blockchain technology and aims to modernize and digitize the issuance and management of securities in Germany.</p><h4><strong>The Crypto Securities Register Contract</strong></h4><p>One of the central provisions of the eWpG is that it allows companies to issue bonds as digital tokens on a blockchain. This means that traditional paper-based securities can be transformed into digital assets represented on a blockchain. The eWpG introduces the concept of a “crypto securities register” (Kryptowertpapierregister). This register is a digital ledger on a blockchain that records ownership and transactions related to crypto securities. It acts as a secure and transparent record of ownership changes and transactions for these digital securities.</p><p>To comply with the eWpG and to automate clearing and settlement processes, we will deploy a Crypto Securities Register (CSR) contract to store specific regulatory information such as token distribution among investor groups. If you’re interested into the eWpG, you can take a look <a href="https://www.gesetze-im-internet.de/ewpg/BJNR142310021.html">here</a>. The Bond Token Contract must communicate with and update the CSR on each issuance or trade.</p><h4>Decentralized Exchange Contract</h4><p>So far, we only talked about the setup of a token issuance and simple token transfers. Let’s imagine the situation where we want to trade our bond tokens in exchange for Ether. We need to trust the other person to send Ether to us and we can’t control this process. This situation is a perfect replication of the real world, in which we must rely on trusted third parties to effectively and securely execute trades and minimize risks. The goal is to not rely on another player as a third party, but rather on pure code. Therefore, we aim to implement a decentralized exchange, in which we define logic for automated transfers with instant <strong><em>Delivery vs. Payment</em></strong> (DvP). We have various options on the complexity of the <strong><em>DEX </em></strong>from simple buy and sell order books, to more sophisticated exchanges like UniSwap including token swaps, liquidity providers and price discovery mechanisms like <strong><em>Constant Product Formula.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMPH4lbkLs97a1Z9uwjvsg.png" /></figure><p>As we observe and as mentioned earlier, our smart contracts interact with each other. Our Bond Token Contract, for example, will be able to read and send data to the Crypto Securities Register. Whether and how individual smart contracts can trigger functions of other contracts, read and receive information, will be part of the dedicated implementation episodes of these functions.</p><p>In this article, we’ve explored the high-level architecture of our bond token issuance platform, laying the foundation for understanding how it will function in a decentralized financial ecosystem. We’ve delved into the core components of the platform, including the smart contracts that will underpin its operations, as well as the traditional 3-tier architecture that supports our Angular frontend, Spring backend, and database.</p><p>In the next episode, we start the development of the Bond Token Contract and dive deeper into the world of Tokens, Token Standards, as well as regulatory and security considerations. Understanding these standards will be crucial as we explore how to represent and manage the digital assets that will power our bond token issuance platform.</p><p>Feel free to share, like and leave comments!</p><blockquote><strong><em>Disclaimer:</em></strong><em> <br>The information provided in this article is for educational and illustrative purposes only. It is not intended for use in production environments without thorough review. Cryptocurrency and smart contract development carry inherent risks, including but not limited to security vulnerabilities and financial losses. Readers are advised to exercise caution and seek professional advice before deploying any code in a real-world setting. The author and publisher disclaim any liability for any damages or losses incurred as a result of using or misusing the code or information presented herein.</em></blockquote><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: </a>Getting started with Ethereum</li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li></ul><p>Following episodes:</p><ul><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34db90db60a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building on Ethereum: The Developer’s Toolkit]]></title>
            <link>https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba4cd456207</guid>
            <category><![CDATA[remix-ide]]></category>
            <category><![CDATA[hard-hat]]></category>
            <category><![CDATA[ganache]]></category>
            <category><![CDATA[software-tools]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 18:54:47 GMT</pubDate>
            <atom:updated>2023-11-20T08:59:07.243Z</atom:updated>
            <content:encoded><![CDATA[<h4>3th Episode — Blockchain Development Tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m8x3WJDVd1Qimjk5" /><figcaption>Photo by <a href="https://unsplash.com/@mitchel3uo?utm_source=medium&amp;utm_medium=referral">Mitchell Luo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Blockchain development tools serve as the craftsman’s instruments, empowering developers to build, test, and deploy decentralized applications and smart contracts efficiently and securely.</p><p>These tools bridge the gap between concept and reality, transforming innovative blockchain ideas into tangible solutions. In this article, we undertake a guided journey through the world of the most prominent blockchain development tools, exploring how these tools shape the developer experience, streamline workflows, and enable the creation of robust and reliable blockchain applications.</p><p>From web-based integrated development environments (IDEs) like Remix to the familiar coding haven of Visual Studio Code (VS Code), and the local blockchain simulation provided by the Truffle Suite (incl. Ganache), to the versatile Ethereum development framework, Hardhat, each tool has a unique role to play in the developer’s toolkit. They offer not just efficiency and convenience but also reliability and security, ensuring that blockchain solutions meet the highest standards of quality.</p><h3>Fast Prototyping using the Remix IDE</h3><p><a href="https://remix.ethereum.org/">Remix</a> is a popular integrated development environment (IDE) for blockchain and smart contract development. It’s a web-based tool that simplifies the process of creating, testing, and deploying Ethereum smart contracts:</p><ul><li>Web-Based: Remix is accessible directly from your web browser, making it a convenient choice for prototyping.</li><li>It’s primarily designed for Ethereum smart contract development, but it supports various EVM-compatible networks and custom blockchains, e.g. connecting to Ganache via JSON-RPC.</li><li>Apart from being an online IDE, Remix also serves as a development tool for Ethereum smart contract development, providing an integrated testing environment. However, I’ve never seen anyone really utilizing that…</li></ul><h4>Getting Started with Remix:</h4><ul><li>Access Remix: Open your web browser and navigate to the Remix IDE website via <a href="https://remix.ethereum.org/">https://remix.ethereum.org/</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTITNZCbBgabCHms0nM93A.png" /></figure><ul><li>In the file explorer, you can setup a new blank workspace or select a template (e.g. with an ERC-1155 Contract).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*wealiaQCb88z5wvCtxPpCQ.png" /></figure><ul><li>You can create a new file by clicking the “+” button in the “File Explorers” panel.</li><li>You can compile your contracts by clicking on the “Solidity Compiler” tab on the left side, select the appropriate compiler version, and click the “Compile” button to compile your contract.</li><li>To deploy and interact with your smart contracts, use the “Deploy &amp; Run Transactions” panel to deploy your contract to a test network or a local development environment. You can then interact with your contract by sending transactions and calling functions.</li></ul><p>Remix is a valuable tool for initial blockchain development, rapid prototyping, and quick experimentation due to its user-friendly web-based interface and immediate accessibility. However, it may not be an ideal choice for long-term blockchain development projects for several reasons.</p><ul><li>First and foremost, as a web-based tool, its availability and performance may be subject to external factors and internet connectivity. Long-term projects often demand greater stability and control.</li><li>Lastly, Remix may not offer the same level of extensibility and customization as dedicated development frameworks and environments like Truffle (incl. Ganache) or Hardhat, while these provide several advantages for more extensive blockchain projects. Truffle and Hardhat offer robust development frameworks that streamline complex workflows, automate testing, and facilitate deployment. Ganache, as a local blockchain emulator, allows for controlled testing environments.</li></ul><p>While Remix serves as an excellent starting point, long-term blockchain development efforts often necessitate more robust and tailored solutions to address scalability, collaboration, and evolving project requirements.</p><h3>Development with VS Code</h3><p><a href="https://code.visualstudio.com/">Visual Studio Code (VS Code)</a> is a popular code editor that offers robust support for Solidity and blockchain development. To get started, we first need to set up a development environment for Solidity.</p><ul><li>Install Visual Studio Code from the official website (<a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a>).</li><li>To write Solidity code, make sure to install the extension “Solidity” from Juan Blanco e.g., for language support, syntax highlighting, autocompletion, and debugging support.</li><li>Despite VS Code already having an integrated version control feature, I recommend to additionally install the GitLens extension to have more control in your version control suite.</li></ul><p>Git itself is an essential tool in software development as it enables version control, allowing us to track changes, collaborate efficiently, and revert to previous code states if issues arise, ensuring code quality and project integrity. It facilitates code sharing and contributes to effective team collaboration, which is where GitHub comes into play.</p><p>GitHub serves as a centralized platform that enhances version control in blockchain development by facilitating seamless collaboration, code sharing, and project management among team members while ensuring code integrity and security.</p><p>You can access the repository, which is filled with source code and other interesting documents and files, via this <a href="https://github.com/DavidCisar/Bond-Token-Issuance-Platform">link</a>. You can then easily clone the repository in VS Code:</p><ol><li>Use the shortcut Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (macOS) to open the command palette. Alternatively, you can go to the “View” menu and select “Command Palette.”</li><li>In the command palette, type “Clone” and look for the “Git: Clone” option in the dropdown list. Select it.</li><li>VS Code will prompt you to enter the URL of the GitHub repository you want to clone. Paste the URL of our <a href="https://github.com/DavidCisar/Bond-Token-Issuance-Platform.git">GitHub repository</a>.</li></ol><p>If you are familiar with the terminal and already have git installed, you can clone the repository via the terminal. Go to your desired project directory and run the command git clone <a href="https://github.com/DavidCisar/Bond-Token-Issuance-Platform.git">https://github.com/DavidCisar/Bond-Token-Issuance-Platform.git</a></p><p>Additionally, it will be necessary to have <em>Node.js</em> and <em>npm</em> (Node Package Manager) installed for running various development tools and libraries.</p><p>Node.js is a runtime environment that allows us to execute JavaScript code outside of a web browser. Node.js provides the runtime for running server-side JavaScript applications, making it a versatile choice for blockchain development. Npm, on the other hand, serves as a package manager, simplifying the installation and management of libraries, frameworks, and dependencies crucial for blockchain development.</p><p>We will use <em>npm</em> to to install hardhat including valuable testing libraries <em>chai</em> and <em>mocha</em>. Extensive testing will have its own dedicated future episode! Both, <em>ethers.js</em> and <em>web3.js</em> are libraries used for interacting with Ethereum and building decentralized applications (dApps). They provide APIs and tools to communicate with Ethereum nodes, send transactions, interact with smart contracts, and work with blockchain data. We will install them using <em>npm</em> as well at the appropriate stage in the development process.</p><h3>Ganache and Hardhat</h3><p>Ganache and Hardhat are both development tools commonly used in Ethereum and blockchain development, but they serve different purposes and offer distinct features. Despite that, Ganache and Hardhat are not mutually exclusive, as they can complement each other in a development workflow.</p><p><a href="https://www.trufflesuite.com/ganache">Ganache</a> is a development blockchain that offers a simulated Ethereum environment for local testing and development. It’s easy to get started with Ganache, and it comes with a user-friendly graphical interface. You can configure Ganache to mimic various Ethereum networks, including specific gas limits, network IDs, and account balances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4lG9ClpaX40j_n2UW0cwA.png" /></figure><h3>Hardhat: Ethereum Development Toolkit</h3><p><a href="https://hardhat.org/">Hardhat</a> is a development toolkit for Ethereum smart contract development and is employed for more comprehensive testing, deployment, and scripting tasks:</p><ul><li>Scriptable Tasks: Hardhat allows you to define custom development tasks in JavaScript, making it highly customizable.</li><li>Testing and Deployment: You can write tests for your contracts using popular testing frameworks like Mocha and deploy your contracts to different networks.</li><li>Plugins: Hardhat’s plugin system lets you extend its functionality and integrate with other tools and libraries.</li><li>Built-In Console: Hardhat provides a built-in console for interacting with your contracts and the Ethereum network during development.</li></ul><p>To get started using hardhat, open a terminal in your project folder and run npm install --save-dev hardhat followed by npx hardhat to create a template project structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrjS1_dA_u5IR9KjGRjqqA.png" /></figure><p>Additionally, we can run a variety of commands for the most common use cases:</p><ul><li>Use npx hardhat compile to compile the Solidity smart contracts in the contracts folder</li><li>Use npx hardhat test to run unit and integration tests for contracts</li><li>Use npx hardhat run scripts/deploy.ts --network &lt;name&gt; to deploy the contracts to a specific Ethereum network if you’re using TypeScript</li><li>Use npx hardhat console --network &lt;name&gt; to launch an interactive console to interact with contracts</li><li>Use npx hardhat --init to generate or reinitialize the Hardhat configuration file</li><li>Use npx hardhat node to start a local Hardhat Ethereum network</li></ul><p>After covering the foundational development tools essential for your blockchain projects, we’re now prepared to introduce a set of advanced tools that are not only valuable but, in some cases, even essential for specific aspects of your development journey. These tools extend beyond mere conveniences, offering advanced functionalities and insights that can greatly enhance your blockchain development experience. In recognition of their significance, we will dedicate upcoming segments to delve deeper into these tools, focusing on dedicated parts of the platform where they play a pivotal role.</p><h3>Access Ethereum Nodes</h3><p>Infura.io is an indispensable tool that should be in every Ethereum developer’s toolkit. It grants access to Ethereum’s blockchain infrastructure without the requirement of running and maintaining your private Ethereum node. Infura operates in the cloud and provides capabilities to transmit transactions, retrieve data, and deploy smart contracts. Its utility is particularly evident in its time-saving attributes, especially beneficial for those new to blockchain development. With Infura.io, there’s no need for the complexities of setting up your Ethereum node, making it an efficient and essential resource. While not universally applicable, Infura.io offers substantial assistance for a wide array of projects.</p><h3>The Gateway to Ethereum</h3><p>MetaMask is a popular Ethereum wallet and a browser extension. MetaMask stands as an indispensable asset within the arsenal of blockchain developers. This Ethereum wallet, coupled with its browser extension, transcends conventional account and asset management. What truly sets MetaMask apart is its seamless integration with web applications, granting developers the ability to interact directly with decentralized applications (dApps) from within their web browsers. I recommend to use the browser extension in Chrome!</p><h3>Etherscan</h3><p>Its comprehensive suite of tools allows users to gain insights into blockchain activities, ranging from transaction tracking to smart contract exploration. This resource is a vital asset for researchers and developers seeking to understand the inner workings of the Ethereum network. Etherscan provides critical transparency and analysis of blockchain interactions.</p><p>In this article, I introduced some important tools for blockchain development. Now, you can start trying things out. For instance, you can use Remix to experiment with smart contracts quickly without the need to install VS Code or working within the terminal. Or, if you’re feeling more adventurous, you can begin your own project with Hardhat.</p><p>Before we dive deeper into smart contract modularity and the architecture design of our Fullstack Blockchain-based Bond Token Issuance Platform in the next episode, take some time to look at the structure of a Hardhat project. Familiarizing yourself with it will be helpful for what’s coming next.</p><p>Don’t forget, your thoughts and questions are valuable.</p><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: Your Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Navigating Ethereum’s Smart Contract Language</a></li></ul><p>Following episodes:</p><ul><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><blockquote><strong>Disclaimer:</strong><em> <br></em>The Solidity code provided in this article is for educational and illustrative purposes only. It is not intended for use in production environments without thorough review, testing, and appropriate modifications to meet the specific needs of your project. Cryptocurrency and smart contract development carry inherent risks, including but not limited to security vulnerabilities and financial losses. Readers are advised to exercise caution and seek professional advice before deploying any code in a real-world setting. The author and publisher disclaim any liability for any damages or losses incurred as a result of using or misusing the code or information presented herein.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba4cd456207" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity Essentials: Navigating Ethereum’s Smart Contract Language]]></title>
            <link>https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/b597295a2500</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 16:20:44 GMT</pubDate>
            <atom:updated>2023-11-20T08:58:40.629Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solidity Essentials: Getting started with Ethereum</h3><h4>2nd Episode — Solidity &amp; Smart Contract Basics</h4><p>In our initial episode, we started our journey with a deep dive into the traditional financial market infrastructure surrounding the issuance of corporate bonds. We identified areas of improvement in the web of bond issuance &amp; trading and explored the indispensable roles played by various market stakeholders. What became evident was the enormous potential for blockchain development to bring about transformative changes.</p><p>We have highlighted the revolutionary impact of <em>automation</em>, increased <em>efficiency</em>, and improved <em>transparency</em> that may make traditional players such as central securities depositories in its current form increasingly obsolete.</p><p>Before we begin the development of our blockchain-based bond token issuance platform, we need to understand the basics and the essential concepts that are integrated into the Solidity programming language first.</p><blockquote>If you are already familiar with Solidity in general, this episode might not be for you. Nonetheless, this episode presents some concepts we will use during development. You might learn something new or fresh up your knowledge!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VMyJ_C1iBZzukSa3" /><figcaption>Photo by <a href="https://unsplash.com/@clintadair?utm_source=medium&amp;utm_medium=referral">Clint Adair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Solidity and EVM: A Consoling Choice in Blockchain Development</h4><p>When it comes to blockchain development, the preference for Solidity as the primary programming language and the Ethereum Virtual Machine (EVM) as the execution environment stems from a combination of factors. First and foremost, Solidity’s adoption is driven by its proven track record in creating secure and auditable smart contracts. It offers a balance of developer-friendly syntax and powerful capabilities. Solidity is the language of choice for building smart contracts and decentralized applications (DApps) on the Ethereum blockchain, and it also finds utility in other blockchain ecosystems that embrace the EVM compatibility. This includes platforms such as Polkadot, Binance Smart Chain, and several others, where Solidity’s versatility and developer-friendly features empower the creation of trustless, automated, and transparent applications.</p><p>Moreover, the EVM provides a standardized execution environment that ensures compatibility across the Ethereum network. This uniformity, along with the robust tooling and support available for Solidity, fosters a thriving ecosystem for DApps and smart contracts. While it’s theoretically possible to use other languages, the practical considerations of security, tooling, and developer familiarity make Solidity and the EVM the preferred choice for Ethereum-based blockchain development.</p><p>Solidity features a syntax influenced by C++, JavaScript and Python. Its clean and expressive structure is designed to facilitate the development of secure and efficient smart contracts. It uses semicolons to terminate statements and curly braces for code blocks. The language emphasizes strong typing, enabling developers to specify data types for variables and function parameters.</p><p>In theory, we are able to implement everything we can imagine in Solidity, since the programming language is Turing-complete. If there weren’t technical restrictions like contract size or other limitations like gas consumption, that influence the final implementation details. However, that is a topic for a subsequent stage.</p><p>Let’s focus on the basics first. A smart contract written in Solidity follows a structured pattern that includes various elements. Here’s an overview of the typical structure of a Solidity smart contract:</p><pre>/**<br> * Pragma Directive: The solidity file usually begins <br> * with a pragma directive that specifies the <br> * compiler version to be used. This ensures compatibility <br> * and helps prevent issues due to compiler updates.<br> */<br>pragma solidity ^0.8.0;<br><br><br>/**<br> * The contract keyword is used to declare the smart contract, <br> * followed by the contract&#39;s name. This is the main structure <br> * that encapsulates the contract&#39;s state variables and functions.<br> */<br>contract BondTokenFactory {<br><br>  /**<br>   * State variables represent the contract&#39;s data storage. <br>   * They are declared within the contract and persist between <br>   * function calls. State variables are typically initialized <br>   * in the contract constructor but can also be initialized<br>   * when being declared.<br>   */<br>  uint256 public myNumber;<br>  uint256 public myDeclaredAndInitializedNumber = 1000;<br>  <br><br>  /**<br>   * The constructor is a special function executed only once <br>   * during contract deployment. It may initialize the contract&#39;s <br>   * state variables. The constructor is not mandatory to use.<br>   */<br>  constructor() { <br>    myNumber = 42;<br>  }<br><br>  /**<br>   * Functions define the behavior and functionality of the contract. <br>   * They can be public, internal, external, or private, specifying <br>   * their visibility and access control. Functions can modify state <br>   * variables or return values.<br>   */<br>  function setNumber(uint256 _newNumber) public onlyOwner { <br>    myNumber = _newNumber;<br>  } <br><br>  function getNumber() public view returns (uint256) {<br>    return myNumber; <br>  }<br><br>}</pre><p>It is worth emphasizing that nearly every operation and data storage action comes at a cost within the Ethereum protocol. Decisions about what to store and how to store it are critical. Given the substantial expense associated with data storage, our primary objective is to keep data storage to the absolute essentials. Nevertheless, akin to other programming languages, Solidity provides a versatile array of data types to accommodate the diverse information requirements during contract execution.</p><p>Let’s explore what <em>Solidity</em> has to offer and begin with primitive data types.</p><pre>/**<br> * Booleans or &#39;bool&#39; in Solidity are a binary data type <br> * with two possible values: true and false.<br> *<br> * For example, we can store information about the issuance.<br> */<br>bool public isIssued = false;<br><br>/**<br> * uint or int represent unsigned and signed integers.<br> * If no bits like in int32 are specified, uint and int are equivalent<br> * to uint256 or int256. The bit specifier can be 8 up to 256 in steps of 8.<br> *<br> * For example, we can store the amount of bond tokens issued.<br> * <br> * We can write 1000 also as 1_000 for better visuability.<br> *<br> * Despite being introduced, we cannot use floating-point numbers yet!<br> */<br>uint public unsignedInteger;<br>int public signedInteger;<br>int265 public issuanceAmount = 18_000_000;</pre><p>Besides booleans and integers, Solidity allows to use <em>advanced</em> data types such as string or bytes. In Solidity, both string and bytes are used to represent sequences of binary data or text. However, there are significant differences between the two!</p><pre>/**<br> * The string data type is used for UTF-8 encoded string data. <br> * It is suitable for storing and manipulating text, such as names, <br> * descriptions, or any textual information.<br> */<br>string public issuer;<br><br>/*<br> * The bytes data type, on the other hand, is more generic and can represent<br> * arbitrary binary data. It is not restricted to text and can store <br> * any binary data, including non-textual information.<br> */<br>bytes public message;<br></pre><p>In Solidity, an Ethereum address is a fundamental data type used to represent the unique identifier of an account or a smart contract on the Ethereum blockchain. Without an address, you’re practically unable to write data to or interact with a blockchain protocol. Ethereum addresses are typically 20 bytes (160 bits) in length and are used for various purposes within Ethereum smart contracts.</p><p>address variables can be used to store Ethereum addresses, and they can be used as function arguments or return values. Ethereum addresses can interact with smart contracts through the functions defined in the smart contract’s ABI (Application Binary Interface).</p><p>We differentiate between Externally Owned Accounts (EOAs) and Smart Contract Addresses:</p><ul><li>An EOA is an Ethereum address that represents an externally controlled account owned by a user. EOAs are controlled by private keys and are used for sending and receiving Ether and interacting with smart contracts on the Ethereum network.</li><li>EOAs can hold Ether and are capable of initiating transactions and executing smart contract functions.</li><li>A smart contract on the Ethereum blockchain is also associated with an Ethereum address. These addresses are the destinations for deploying and interacting with smart contracts.</li><li>Smart contract addresses are generated deterministically based on the sender’s address and the sender’s nonce (transaction count). Each deployment of a smart contract results in a new, unique address.</li></ul><pre>/**<br> * An &#39;address&#39; represents a 20-byte Ethereum address. It can hold the <br> * address of a user, a contract, or even another contract.<br> */<br>address public owner;</pre><p>Sometimes, simple data types are not suitable or sufficient enought to collectively store related information together in a coherent way. Arrays, mappings and structs are essential data structures used to organize and manage data within smart contracts.</p><pre>/**<br> * Arrays are ordered collections of data elements of the same type. <br> * They can be of fixed size (static) or variable size (dynamic).<br> *<br> * You might use arrays to store lists of bond tokens issued by the factory, <br> * or manage investors&#39; addresses in a bond issuance.<br> */<br>address[] public investors;<br><br>/**<br>* Mappings are key-value stores where each key is unique.<br>* They are efficient for fast lookups and are often used to create<br>* relationships or mappings between entities.<br>*<br>* Mappings can be used to associate bond token with their owners,<br>* or e.g. maintain a registry of whitelisted participants.<br>*<br>* Keys need to be a primitive or non primitive data type and cannot<br>* be data structures!<br>*<br>* Values, however, can be primitive, non-primitive data types or <br>* data structures like arrays, structs or even another mapping!<br>*/<br>mapping(address =&gt; bool) public whitelistedInvestors;<br>mapping(uint8 =&gt; Metadata) public metaData;<br>mapping(address =&gt; mapping(address =&gt; uint256)) public balances;<br><br>/**<br> * A struct is a composite data type that allows you to group together <br> * multiple variables of different data types under a single name. <br> * It doesn&#39;t have the behavior and methods associated with objects <br> * in object-oriented programming languages. Instead, it provides a way <br> * to organize and store related data.<br> */<br>struct Metadata {<br>  address issuer;<br>  uint256 issuanceDate;<br>  uint256 maturityDate;<br>  uint256 faceValue;<br>}</pre><p>Global and other special variables as well as units play a pivotal role in the development of our Bond Token Issuance platform. Global variables like msg.sender and msg.value are crucial for tracking ownership and managing payments within bond issuances. Special variables like block.timestamp enable us to record and verify timestamps and block numbers, ensuring transparency and accuracy in our issuance process. Units such as Ether (ether) and Wei (wei) allow us to define and transact in cryptocurrency units, facilitating investments and transactions in our bond tokens. Check the full list <a href="https://docs.soliditylang.org/en/v0.8.21/units-and-global-variables.html">here</a>!</p><pre>/*<br> * Solidity offers global variables, that can be accessed without being<br> * declared or initialized in the smart contract we&#39;re in and could be<br> * useful for several intentions. <br> *<br> * Before allowing an investor to purchase bond tokens, we might want <br> * to check if the sender is already whitelisted. <br> * The global variable msg.sender provides the address of the<br> * sender of the message. <br> *<br> * There are several other global variables, which might be used to store<br> * the block.timestamp as the issuance date. We might want to check <br> * if the msg.value is &gt;= than the price one has to pay.<br> */<br><br>// Block and Transaction Properties<br>bytes public data;<br>address public sender;<br>uint public value;<br>uint public gasLimit;<br>uint public randomNumber;<br>uint public timestamp;<br>uint public gasLeft;<br><br>function globalVariablesAndUnit() public payable {<br>  data = msg.data;                    <br>  // Complete calldata<br>  <br>  sender = msg.sender;                <br>  // Sender of the message<br>  <br>  value = msg.value;                  <br>  // Number of wei sent with the message<br>  <br>  gasLimit = block.gaslimit;          <br>  // Current block gaslimit<br>  <br>  randomNumber = block.prevrandao;    <br>  // Random number provided by the beacon chain<br>  <br>  timestamp = block.timestamp;        <br>  // Current block timestamp as seconds since unix epoch<br>  <br>  gasLeft = gasleft();                <br>  // Remaining gas<br>}<br><br>// Ether units<br>uint public weiUnit = 1 wei; // 1<br>uint public gweiUnit = 1 gwei; // 1e9<br>uint public etherUnit = 1 ether; // 1e18<br><br>// Time Units<br>uint public plusOneSecond = block.timestamp + 1 seconds;<br>uint public plusFiveMinute = block.timestamp + 5 minutes;<br>uint public plusTenHours = block.timestamp + 10 hours;<br>uint public plusFiveDays = block.timestamp + 5 days;<br>uint public plusOneWeek = block.timestamp + 1 weeks;</pre><p>Using an enum (enumeration) within our bond token issuance platform in Solidity can help improve code readability, maintainability, and enforce data integrity by defining a set of named constants representing various states, types, or options.</p><pre>/**<br>* If we want to track some kind of a state, for example the state of the<br>* bond within its lifecycle, we can illustrate this by using an enum.<br>*<br>* An enum in Solidity is both a data type and a data structure.<br>* <br>* An enum is a custom data type because it defines a new, <br>* user-defined set of values with specific semantics. <br>* It restricts the possible values a variable of that type <br>* can hold to a predefined set of options. In this sense, <br>* it&#39;s similar to other primitive data types like uint, address, or bool.<br>* <br>* An enum can also be considered a data structure because it organizes <br>* and structures data in a particular way. It groups related values together<br>* and assigns them meaningful names, which helps improve code readability <br>* and maintainability.<br>*/<br>enum IssuanceState { <br>  Created,<br>  Approved,<br>  Active,<br>  Redeemed,<br>  Expired<br>}<br><br>// Declare a state variable of the enum type<br>IssuanceState public issuanceState;</pre><p>Events are necessary for enhancing transparency and enabling efficient external monitoring and auditing. Events are a powerful mechanism for emitting structured logs of important contract actions, such as bond issuances, transfers, and interest payments. These logs can be accessed and analyzed off-chain, enabling regulatory bodies, auditors, and participants to monitor the platform’s activities in real-time. Events also enhance the platform’s user experience by providing feedback on critical actions, such as successful bond purchases or interest payments. By emitting events strategically throughout our smart contracts, we ensure that all relevant stakeholders have access to timely and accurate information, ultimately building trust and confidence in our blockchain-based bond issuance platform.</p><pre>/**<br> * Events are used to log significant contract actions or changes. <br> * They enable external applications to listen for and react <br> * to specific events emitted by the contract.<br> */<br>event Purchase(uint256 amount, address indexed buyer);</pre><p>Custom modifiers like onlyOwner can be used to encapsulate specific access control logic. They allow you to enforce conditions before executing a function. In the case of onlyOwner, it might check if the sender (the msg.sender) is the issuer of a bond before allowing the function to proceed.</p><p>Using custom modifiers instead of duplicating the logic inside your functions can be more efficient in terms of code readability, maintenance, and gas consumption.</p><pre>/**<br> * Modifiers are used to modify the behavior of functions. <br> * They are often used for access control and can restrict access <br> * to certain functions based on conditions.<br> */<br>modifier onlyOwner() { <br>  require(msg.sender == owner, &quot;Only the owner can call this function&quot;); <br>  _; <br>}<br><br>function demonstrateModifier() public onlyOwner {<br>  // do something...<br>}</pre><p>By using operators effectively, we can create smart contracts that enforce business rules, validate data, and manage transactions, ensuring the integrity and reliability of our platform’s operations on the Ethereum blockchain. Operators are essential tools for performing various operations within smart contracts. They include arithmetic operators for mathematical calculations, logical operators for condition testing, and bitwise operators for low-level bit manipulation. These operators enable us to implement complex logic, make decisions based on data, and perform calculations required for our bond token issuance platform.</p><p>The following operators are just a short summary. For a full list, go <a href="https://docs.soliditylang.org/en/v0.8.21/cheatsheet.html">here</a>!</p><pre>// Logical &amp; bitwise operators<br>bool public notTrue = !true;<br>bool public smaller = 3 &lt; 5;<br>bool public larger = 5 &gt; 3;<br>bool public smallerOrEqual = 4 &lt;= 4;<br>bool public biggerOrEqual = 7 &gt;= 5;<br>bool public equal = 1 == 1;<br>bool public inequal = 5 != 4;<br>bool public and = true &amp;&amp; true;<br>bool public or = false || true;<br><br>// Ternary operator<br>string public ternaryOperator = 5 &gt; 7 ? &quot;bigger&quot; : &quot;smaller&quot;;<br><br>// Arithmetic operators<br>function arithmeticOperations() public pure {<br>  int number;<br><br>  // Addition and Subtraction<br>  number = 1 + 1;<br>  number = 1 - 1;<br>        <br>  // ++, -- Increment and Decrement<br>  number++;<br>  ++number;<br>  number--;<br>  --number;<br><br>  // Multiplication, Exponentiation, Division and Modulo<br>  number = 2 * 2;<br>  number = 5 ** 2;    <br>  number = 4 / 2;<br>  number = 5 % 2;<br>}<br><br>// Assignment operators<br>function bitwiseOR() public pure {<br>  uint8 a = 5;    // binary: 0101<br>  uint8 b = 3;    // binary: 0011<br><br>  a |= b;         // a is now 7; binary: 0111<br>}<br><br>function bitwiseXOR() public pure {<br>  uint8 a = 5;    // binary: 0101<br>  uint8 b = 3;    // binary: 0011<br><br>  a ^= b;         // a is now 6; binary: 0110<br>}<br><br>function bitwiseAND() public pure {<br>  uint8 a = 5;    // binary: 0101<br>  uint8 b = 3;    // binary: 0011<br>        <br>  a &amp;= b;         // a is now 1; binary: 0001<br>}<br><br>function otherAssignmentOperators() public pure {<br>  uint8 a = 17;<br><br>  a += 3;         // a is now 20<br>  a -= 5;         // a is now 15<br>  a *= 2;         // a is now 30<br>  a /= 3;         // a is now 10<br>  a %= 3;         // a is now 1<br>}</pre><p>By using error handling effectively, we can prevent unauthorized actions, handle exceptional cases gracefully, and provide clear feedback to users. Solidity provides mechanisms for handling errors through require, revert, and assert statements. These mechanisms enable us to implement robust contract logic, validate inputs, and enforce business rules. In our use case, error handling ensures that transactions and operations are executed safely and that the platform adheres to regulatory and contractual requirements.</p><ul><li>Use require for input validation and enforcing conditions that are part of the contract&#39;s normal operation.</li><li>Use revert when you want to handle exceptional cases and provide custom error messages for better user feedback.</li><li>Use assert for catching internal programming errors and ensuring that critical invariants are never violated.</li></ul><pre>function performWithdrawal(uint256 amount) public {<br>  require(amount &lt;= address(this).balance, &quot;Insufficient balance&quot;);<br><br>  // Withdraw Ether<br>  if (!payable(msg.sender).send(amount)) {<br>    revert(&quot;Failed to send Ether&quot;);<br>  }<br>}<br><br>function burnTokens(uint256 amount) public {<br>  // Burn tokens<br>  totalSupply -= amount;<br><br>  // Ensure that totalSupply doesn&#39;t get negative<br>  assert(totalSupply &gt;= 0);<br>}</pre><p>Loops and iterations in Solidity allow you to perform repetitive tasks, such as iterating through arrays or performing calculations multiple times. Loops are valuable for tasks like data processing, array manipulation, and repetitive calculations within smart contracts. However, they should be used cautiously due to their potential for high gas costs and the risk of reaching gas limits. Gas efficiency is a crucial concern, as excessive gas consumption can lead to transaction failures. In loops, gas usage can grow linearly with the number of iterations, so it&#39;s vital to limit the number of iterations whenever possible and avoid unbounded loops.</p><p>You should really ask yourself if there isn’t another way to store and access relevant data. Consider iterating over arrays e.g. off-chain. In most cases, there is a better way that is less costly when it comes to gas usage.</p><pre>uint j = 0;<br><br>function forLoop() public view {<br>  for (uint i = 0; i &lt; 10; i++) {<br>    // Code to be executed<br>  }<br>}<br><br>function whileLoop() public {<br>  while (j &lt; 10) {<br>    j++;<br>  }<br>}</pre><p>If you followed this episode, you should be well equipped to write simple smart contracts! 😊</p><p>As this was only an introduction in Solidity and smart contract development, it’s important to note that we’ll be addressing advanced topics in future episodes that align with their relevance to the Bond Token Issuance platform. Each of these advanced topics will find its place in our discussions at the appropriate juncture. My aim is to provide you with a well-structured and comprehensive understanding of these subjects as they directly pertain to the functioning and optimization of our bond token issuance platform. So, stay tuned for future episodes where we’ll explore these advanced concepts in depth, making them more accessible and applicable.</p><p>Feel free to share, like and leave comments!</p><blockquote><strong><em>Disclaimer:</em></strong> <br>The Solidity code provided in this article is for educational and illustrative purposes only. It is not intended for use in production environments without thorough review, testing, and appropriate modifications to meet the specific needs of your project. Cryptocurrency and smart contract development carry inherent risks, including but not limited to security vulnerabilities and financial losses. Readers are advised to exercise caution and seek professional advice before deploying any code in a real-world setting. The author and publisher disclaim any liability for any damages or losses incurred as a result of using or misusing the code or information presented herein.</blockquote><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li></ul><p>Following episodes:</p><ul><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b597295a2500" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinventing Corporate Bonds: How Blockchain Technology Revives Efficiency and Captivates Modern…]]></title>
            <link>https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/1acb32bc02a6</guid>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[corporate-bonds]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 19:20:13 GMT</pubDate>
            <atom:updated>2023-11-20T08:58:11.161Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reinventing Corporate Bonds</h3><h4><em>1st Episode — Examining the Use Case</em></h4><p>Welcome to the beginning of our thrilling blockchain development journey, where we’re about to embark on creating a Fullstack Blockchain-based Corporate Bond Issuance Platform — an endeavor that promises to deliver efficiency gains and bring automation to the forefront. Before we dive into the technicalities, let’s grasp the essence of our mission: revolutionizing the bond market through tokenization, making investment opportunities universally accessible, and fostering financial inclusivity. Our vision extends beyond a mere platform; we aspire to build a decentralized, transparent, and borderless financial ecosystem, powered by cutting-edge technologies. In the upcoming episodes, we’ll explore the intricacies of smart contract creation, delve into token standards, and demonstrate how automation drives us towards a more seamless and efficient future.</p><p>You might wonder, “Why is blockchain being hailed as the game-changer for corporate bond issuance?” It is essential to grasp the complexities of the traditional financial market infrastructure. Understanding the roles played by key players in this system lays the groundwork for identifying the areas that stand to benefit most from blockchain’s integration. Let’s start with a definition of corporate bonds:</p><p><em>Corporate bonds are debt securities issued by corporations or companies to raise capital from investors. When an investor purchases a corporate bond, they are essentially lending money to the issuing company. In return, the company promises to pay periodic interest (coupon payments) to the bondholder, and at the bond’s maturity date, the company repays the original amount borrowed (the principal) to the bondholder.</em></p><p><em>Bearer bonds differ from registered bonds in that ownership is represented by physical possession of the bond certificate, but they are less common now as most bonds are electronically held and recorded due to the risks associated with physical certificates.</em></p><p>The traditional financial market infrastructure for corporate bonds has served as a vital mechanism for raising capital and facilitating investment. However, this well-established system is not without its challenges. Let’s explore the key stages, as well as players and their responsibilities in the corporate bond lifecycle and identify the aspects that can benefit from the integration of blockchain technology. We will then derive so called Areas of Improvement (AoIs), which we would like to tackle when developing our prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRgOqY_1H7UzCPYDJ259FQ.png" /><figcaption>Simplified model of parties involved in a bond trade</figcaption></figure><h3><strong><em>The Issuance Phase</em></strong></h3><p>The issuance process of corporate bonds involves various players, including the issuer, investment banks, credit rating agencies, and legal counsel. While this process has been refined over time, it still faces challenges such as:</p><ul><li>Lengthy Administrative Procedures: The issuance process can be burdened by administrative paperwork, approval requirements, and multiple intermediaries, leading to delays and increased costs.</li><li>Information Asymmetry: Investors may face information asymmetry regarding the issuer’s creditworthiness, resulting in a lack of transparency and potential hesitancy to invest.</li></ul><p><strong>Primary Trading</strong></p><p>Primary Trading occurs when newly issued corporate bonds are sold to investors. While this stage has witnessed improvements in recent years, there are still areas that could be enhanced, such as:</p><ul><li>Limited Accessibility: The primary market can be restrictive for certain investors, as access may be limited to institutional players, potentially excluding smaller investors.</li><li>Manual Processes: The trading process often involves manual interventions, which can lead to delays and inefficiencies.</li></ul><h3>The Secondary Market Phase</h3><p>In the secondary market, investors trade corporate bonds among themselves after the initial issuance. While this market provides liquidity, there are notable challenges:</p><ul><li>Fragmented Market: The secondary market can be fragmented, with trading occurring across various exchanges and OTC platforms, making it difficult for investors to find the best prices.</li><li>Settlement Period: The settlement process still relies on the T+2 standard, leading to counterparty risks and elongated settlement times.</li></ul><p>The <em>clearing and settlement process</em> is essential for the efficient transfer of ownership and funds between buyers and sellers. However, the traditional system faces:</p><ul><li>Intermediaries and Complexity: Multiple intermediaries are involved in clearing and settlement, adding layers of complexity, potential points of failure, and higher costs.</li><li>Counterparty Risks: The current system can expose parties to counterparty risks during the settlement process, leading to settlement failures and delayed transactions.</li></ul><h3>Challenges in the Traditional Corporate Bond Market</h3><p>The issuance and trading of traditional corporate bonds involve complex processes with multiple stakeholders, leading to challenges such as inefficiencies, high costs, lack of transparency, limited liquidity and restricted market access for retail investors. The traditional bond issuance process requires collaboration among various parties, including the issuer (company), merchant bankers, legal counsel, rating agencies, trustees, collection bankers, and registrars. Coordinating these entities in a time-sensitive manner poses difficulties, leading to counterparty risks and potential settlement delays and the reliance on manual processes results in paperwork burdens as well as increased risk of errors.</p><p>Additionally, traditional corporate bonds typically have high denominations, making them less accessible to retail investors who lack significant capital. Opaque pricing and fragmented markets contribute to information asymmetry for investors, while compliance with regulatory requirements and lack of standardization add complexity. The centralized nature of traditional bond markets also introduces counterparty risks and inefficiencies in the settlement process, leading to delayed transactions and increased credit risk.</p><blockquote>A full list of AoIs can be found attached at the end!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xy5d3U9cfgPorBoC" /><figcaption>Photo by <a href="https://unsplash.com/@shubzweb3?utm_source=medium&amp;utm_medium=referral">Shubham&#39;s Web3</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To address these flaws and enhance the corporate bond market, innovative technologies such as blockchain-based bond tokenization, smart contracts, and decentralized exchanges could lead to opportunities for improved liquidity, transparency, automation, and accessibility.</p><h3>How Blockchain could tackle these challenges</h3><p>Blockchain technology may offer transformative solutions to the challenges faced by the traditional financial market infrastructure for corporate bonds. The immutable and transparent nature of blockchain could revolutionize the issuance, primary and secondary trading, including clearing and settlement services as well as corporate actions (automating interest payments and bond buy-backs):</p><ol><li>Efficiency and Transparency: Blockchain streamlines the issuance process by automating administrative tasks, reducing paperwork, and enhancing transparency through real-time updates on a distributed ledger.</li><li>Accessibility and Inclusivity: Tokenization on the blockchain allows fractional ownership, enabling smaller investors to participate in the primary market and access investment opportunities previously restricted to institutional players.</li><li>Decentralization and Security: Blockchain’s decentralized architecture reduces the need for multiple intermediaries, reducing costs, and enhancing security by eliminating single points of failure.</li><li>Real-Time Settlement: Blockchain enables peer-to-peer trading with real-time settlement, reducing counterparty risks and significantly shortening the settlement period.</li><li>Global Market Accessibility: Blockchain’s borderless nature fosters a global marketplace, enabling investors from different countries to trade seamlessly without concerns about cross-border complexities.</li></ol><p>In conclusion, blockchain technology has the potential to revolutionize the corporate bond lifecycle, addressing the areas for improvement in the traditional financial market infrastructure. By fostering efficiency, transparency, and inclusivity, blockchain can unlock new opportunities and enhance the overall experience for issuers and investors alike.</p><h3>Building a Blockchain-Based Bond Token Factory with Smart Contracts</h3><p>Based on the AoIs, certain Design Objectives were identified, which our Bond Token Factory should follow and in the best case, achieve. The final prototype should include the following features and functionalities:</p><ul><li>Digital representation in the form of a tokenized corporate bond</li><li>Full bond lifecycle is based on smart contracts (Issuance, Distribution, Interest Payments, Transfers, Maturity Payments)</li><li>Ability to register metadata for a planned bond issuance</li><li>Ability to setup minimun and maximum funding goals</li><li>Ability to approve bond issuances</li><li>Investors shall be able to buy tokens during the primary issuance phase</li><li>Investors can claim tokens bought in the primary issuance</li><li>Investors are able to transfer tokens</li><li>Investors are able to claim interest earned</li><li>Investors are able to claim the ParValue after maturity</li><li>Whitelisting to comply with Know-Your-Customer (KYC) requirements</li><li>Crypto Securities Register to comply with the German eWpG</li><li>Frontend visualizing live trading-data, bond metadata and a portfolio</li><li>Decentralized exchange for secondary bond token trading</li></ul><h4>What you can expect in the next episodes:</h4><ul><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">Introduction into the basics of Smart Contracts and the programming language Solidity</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">Blockchain Tools and IDEs</a></li><li>Introduction into popular Token Standards like ERC-20 or Multi-Token Standards like ERC-1155</li><li>Single feature episodes on Token Issuance, Transfers, KYC, Claimable Functions, Soft and Hard Caps et cetera</li><li>Introduction to Smart Contract Security</li><li>Introduction into Dezentralized Exchanges</li><li>Advanced Solidity and Ethereum Virtual Machine (EVM)</li><li>Smart Contract Testing with Chai</li><li>Frontend Blockchain Development with Ethers.js</li></ul><p>Access to <a href="https://github.com/DavidCisar/Bond-Token-Issuance-Platform/blob/main/Episode%201%20-%20AoIs%20%2B%20DOs/AreasOfImprovement.pdf">Areas of Improvement</a> and <a href="https://github.com/DavidCisar/Bond-Token-Issuance-Platform/blob/main/Episode%201%20-%20AoIs%20%2B%20DOs/DesignObjectives.pdf">Design Objectives</a> PDFs.</p><p>Previous episodes:</p><ul><li><a href="https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8">Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</a></li></ul><p>Following episodes:</p><ul><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Getting started with Ethereum</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1acb32bc02a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embark on an Exciting Journey: Unveiling the World of Blockchain Development]]></title>
            <link>https://medium.com/@davidcisar/embark-on-an-exciting-journey-unveiling-the-world-of-blockchain-development-1b07d6e0bda8?source=rss-dfbc65196047------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b07d6e0bda8</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[tokenization]]></category>
            <dc:creator><![CDATA[David Cisar]]></dc:creator>
            <pubDate>Sat, 15 Jul 2023 16:30:37 GMT</pubDate>
            <atom:updated>2023-11-14T18:22:30.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Blockchain-Based Corporate Bond Issuance Platform: A Guide to Blockchain Development</h3><blockquote><em>Blockchain development has emerged as a niche that holds tremendous promise and captivates the imaginations of tech enthusiasts worldwide. It offers a unique blend of innovation, creativity, and real-world applicability. As you embark on your journey into this realm, you will find that blockchain development not only broadens your skillset but also propels your career to new heights.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N4ITuvMlN7-6Zch0" /><figcaption>Photo by <a href="https://unsplash.com/@dvlden?utm_source=medium&amp;utm_medium=referral">Nenad Novaković</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to an exciting blog series that will take you on a journey into the world of blockchain development! 🌍 In this multi-week series, we will delve deep and cover the whole development lifecycle of building a <em>Blockchain-based Corporate Bond Issuance Platform</em>. The series follows a sequential path with each episode complementing the previous one, unfolding a specific topic which will finally contribute to the holistic development of this <em>Use Case</em>.</p><p>💡 With the aim of building domain knowledge, we’ll start the series by analyzing the traditional financial capital market infrastructure, identifying so-called <em>Areas of Improvement</em> (AoI). What are corporate bonds, and why are they particularly suitable to be tokenized? We’ll explore the core concepts that underpin blockchain technology, diving into the decentralized nature of blockchains and the power of smart contracts. Understanding these aspects will enable us to fully grasp the mechanisms that facilitate secure and transparent transactions without the need of intermediaries on the blockchain.</p><p><strong>HelloWorld.sol</strong></p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract HelloWorld {<br>    function sayHello() public pure returns (string memory) {<br>        return &quot;Hello, Blockchain!&quot;;<br>    }<br>}</pre><p>In the following weeks, we’ll delve into <em>Blockchain Programming</em>, equipping you with the necessary tools to bring smart contracts to life. We’ll embark on an exploration of Solidity &amp; Ethereum Virtual Machine (EVM) basics, key considerations like token standards or limitations and best practices.</p><p>Once we have a solid understanding of the fundamentals, we’ll dedicate an episode to explore the essential tools and frameworks used in blockchain development. We’ll dive into popular tools like Remix, a powerful web-based IDE for writing and debugging smart contracts, and Ganache, a personal Ethereum blockchain for local development. We’ll also explore Hardhat, a popular development environment that facilitates smart contract testing and deployment. These tools will become invaluable assets as we progress further.</p><p>Technical limitations make it impossible to implement large scale applications within a single smart contract. It will be inevitable to consider appropriate partitioning of the application into logically related modules.</p><p>Amidst the exciting world of blockchain development, it is imperative to address the crucial aspect of <em>smart contract security</em>. As smart contracts are self-executing and immutable, any vulnerabilities in their code can have significant consequences. We’ll delve into the realm of smart contract security, exploring common vulnerabilities and best practices for writing secure contracts. From reentrancy attacks to integer overflows and unhandled exceptions, we’ll examine real-world examples and showcase techniques for conducting thorough security audits. By understanding these vulnerabilities and implementing robust security measures, we can build resilient and trustworthy decentralized applications on the blockchain.</p><p>Developing web3 apps entails complying with legal and regulatory frameworks, such as KYC (Know Your Customer) procedures and licensing obligations. Our platform will adhere to these requirements, ensuring that users can interact with the platform while maintaining regulatory compliance. We will closely examine legal developments, including the German eWpG (electronic Securities Act), which enables the legal issuance of bearer bond tokens through blockchain technology in the German jurisdiction.</p><p>To enhance the functionality of our platform, we will incorporate a basic <em>decentralized exchange</em> (DEX). We will delve into the prerequisites and requirements of DEX, including liquidity pools, order matching algorithms, and price calculation mechanisms for trading pairs. We’ll examine, why <em>Market Makers</em> may play a crucial role in ensuring liquidity and facilitating efficient trading.</p><p>Once we have developed and thoroughly tested the smart contracts that power our platform, our focus will shift to implementing a Full-Stack Web3 Application. This web interface will enable users to register, acquire the bond tokens, and access essential information and statistics. We will leverage technologies like Ethers.js to seamlessly integrate with the blockchain network, enabling functionalities such as reading the blockchain, displaying events and triggering transactions within a user-friendly dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-c1MyaNngktrdxmr" /><figcaption>Photo by <a href="https://unsplash.com/@shubzweb3?utm_source=medium&amp;utm_medium=referral">Shubham’s Web3</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>🚀 Starting on Monday, 7th of August, a new article awaits you bi-weekly, unlocking new insights, practical knowledge, and empowering you on your path to becoming a blockchain expert.</blockquote><p><em>Together, we’ll unravel the mysteries of decentralization and smart contracts, setting the stage for an unforgettable exploration of this groundbreaking technology. Don’t miss out on the opportunity to level up your blockchain skills and unlock new possibilities.</em></p><p><em>In this series, we will demystify its complexities, explore its vast potential, and empower you to become a blockchain aficionado. Whether you’re a curious beginner or a seasoned programmer, these bi-weekly articles are designed to cater to your thirst for knowledge, providing insights and practical guidance every step of the way.</em></p><p><em>🔗 Like, share, and follow me for more exciting articles and future projects. I’m planning to write additional articles about different projects with real-world examples, from simple token issuances to building decentralized exchanges or digital wallets like MetaMask. I hope to challenge your skills and showcase the depths of your blockchain expertise.</em></p><h4>Episodes:</h4><ul><li><a href="https://medium.com/@davidcisar/reinventing-corporate-bonds-how-blockchain-technology-revives-efficiency-and-captivates-modern-1acb32bc02a6">1. Reinventing Corporate Bonds</a></li><li><a href="https://medium.com/@davidcisar/solidity-essentials-navigating-ethereums-smart-contract-language-b597295a2500">2. Solidity Essentials: Getting started with Ethereum</a></li><li><a href="https://medium.com/@davidcisar/building-on-ethereum-the-developers-toolkit-ba4cd456207">3. Building on Ethereum: The Developer’s Toolkit</a></li><li><a href="https://medium.com/@davidcisar/crafting-a-solid-architecture-for-the-bond-token-issuance-platform-34db90db60a">4. Crafting a Solid Architecture for the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/tokenization-bringing-bonds-to-the-blockchain-94d75d56fd6e">5. Tokenization: Bringing Bonds to the Blockchain</a></li><li><a href="https://medium.com/@davidcisar/ensuring-regulatory-compliance-in-the-bond-token-issuance-platform-173c615ada5f">6. Ensuring Regulatory Compliance in the Bond Token Issuance Platform</a></li><li><a href="https://medium.com/@davidcisar/how-to-test-smart-contracts-8b1321248387">7. How to test Smart Contracts</a></li><li><a href="https://medium.com/@davidcisar/step-by-step-guide-to-automate-decentralized-bond-trading-5c01a2cedf95">8. Step-by-Step Guide to automate decentralized Bond Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b07d6e0bda8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>