<?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 Senudajayalath on Medium]]></title>
        <description><![CDATA[Stories by Senudajayalath on Medium]]></description>
        <link>https://medium.com/@senudajayalath1?source=rss-d8e30a2b0da7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g2OXca5fHwxQqMY1</url>
            <title>Stories by Senudajayalath on Medium</title>
            <link>https://medium.com/@senudajayalath1?source=rss-d8e30a2b0da7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:45:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@senudajayalath1/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[MermaidJs Architecture Diagrams Now Support All AWS Icons!]]></title>
            <link>https://blog.devops.dev/mermaidjs-architecture-diagrams-now-support-all-aws-icons-8bd6640ab090?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd6640ab090</guid>
            <category><![CDATA[architecture-diagram]]></category>
            <category><![CDATA[aws-architecture-diagram]]></category>
            <category><![CDATA[icons]]></category>
            <category><![CDATA[mermaid]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Sat, 23 May 2026 19:36:00 GMT</pubDate>
            <atom:updated>2026-05-23T19:36:00.571Z</atom:updated>
            <content:encoded><![CDATA[<p>If you got excited reading the title, I’m sorry to say… I lied.</p><p>But hold on — I do have the next best thing.</p><p>Introducing <a href="https://latixengine.com/">LatixEngine</a> — a powerful Mermaid wrapper for architecture diagrams that supports <strong>all AWS icons</strong> directly inside Mermaid-based diagrams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBVJf-XdGwHH5gavW97ahA.jpeg" /></figure><p>For years, developers have loved <a href="https://mermaid.js.org/?utm_source=chatgpt.com">Mermaid.js</a> for its simplicity, Markdown integration, and developer-friendly syntax. It made creating flowcharts, sequence diagrams, ER diagrams, and Git graphs incredibly easy.</p><p>But when it came to <strong>cloud architecture diagrams</strong>, Mermaid had one major limitation.</p><h3>The Problem with Mermaid Architecture Diagrams</h3><p>Mermaid.js recently introduced support for architecture diagrams, a huge step forward for developers and system designers.</p><p>However, the feature still feels incomplete for real-world cloud system design.</p><p>By default, Mermaid architecture diagrams support only a handful of built-in icons. If you want to create AWS, Azure, or GCP architecture diagrams, you quickly run into a frustrating limitation:</p><ul><li>Very limited cloud service icons</li><li>Dependency on a tiny subset of Iconify icons</li><li>No official AWS/GCP/Azure architecture icon support</li><li>Difficult to create production-grade infrastructure diagrams</li></ul><p>And let’s be honest:</p><p>Modern software architecture without proper cloud provider icons feels unfinished.</p><p>As developers, we rely heavily on visual communication. Whether it’s:</p><ul><li>Microservices architecture</li><li>Kubernetes infrastructure</li><li>Serverless systems</li><li>Event-driven architecture</li><li>CI/CD pipelines</li><li>Distributed systems</li></ul><p>…cloud-native diagrams are essential.</p><p>This limitation is one of the main reasons many developers including myself avoided using Mermaid for serious architecture diagramming.</p><h3>Enter LatixEngine</h3><p>That’s exactly why I built <a href="https://latixengine.com/">LatixEngine</a>.</p><p>LatixEngine is a Mermaid wrapper specifically designed for <strong>modern cloud architecture diagrams</strong>.</p><p>It extends Mermaid’s architecture capabilities by adding support for:</p><ul><li>Full AWS/GCP/Azure Architecture Icons</li><li>Better cloud visualization</li><li>Cleaner developer experience</li><li>Faster architecture prototyping</li><li>Mermaid-compatible syntax</li><li>Infrastructure documentation as code</li></ul><p>Now you can create fully fledged AWS architecture diagrams directly from code without switching to bulky drag-and-drop tools.</p><h3>Why This Matters</h3><p>Infrastructure diagrams are no longer optional.</p><p>Teams today need:</p><ul><li>Documentation that stays version-controlled</li><li>Architecture diagrams inside README files</li><li>CI-generated technical documentation</li><li>Developer-friendly diagram tooling</li><li>Lightweight alternatives to enterprise diagram software</li></ul><p>Mermaid solved this problem beautifully for flowcharts and sequences.</p><p>LatixEngine brings the same simplicity to <strong>AWS/GCP/Azure cloud architecture diagrams</strong>.</p><h3>The Future of Architecture Diagrams</h3><p>The future of technical documentation is code-driven, collaborative, and Git-friendly.</p><p>Developers don’t want to spend hours dragging icons across a canvas.</p><p>We want:</p><ul><li>Architecture diagrams in Markdown</li><li>Git-based version control</li><li>Reusable diagram components</li><li>Cloud-native visualizations</li><li>Fast iteration during development</li></ul><p>That’s the direction LatixEngine is heading.</p><p>And this is only the beginning.</p><h3>Final Thoughts</h3><p>Mermaid architecture diagrams had massive potential, but cloud icon limitations held them back from mainstream adoption in serious infrastructure design.</p><p>LatixEngine fills that gap by enabling full cloud icon support while preserving the simplicity developers love about Mermaid.</p><p>If you’re building cloud systems, documenting infrastructure, or designing distributed architectures, give <a href="https://latixengine.com/">LatixEngine</a> a try.</p><p>You might finally enjoy creating architecture diagrams again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd6640ab090" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/mermaidjs-architecture-diagrams-now-support-all-aws-icons-8bd6640ab090">MermaidJs Architecture Diagrams Now Support All AWS Icons!</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy Uniswap V3 Contracts Locally and Initialize Pools]]></title>
            <link>https://medium.com/coinmonks/how-to-deploy-uniswap-v3-contracts-locally-and-initialize-pools-c97df593b63f?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c97df593b63f</guid>
            <category><![CDATA[uniswap-v3]]></category>
            <category><![CDATA[deploy-local]]></category>
            <category><![CDATA[initialize-pool]]></category>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[add-liquidity]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 13:07:43 GMT</pubDate>
            <atom:updated>2025-03-17T13:07:43.005Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploy your own Uniswap v3 contracts locally</p><p>I have been working with the <strong>Uniswap v2 protocol</strong> for a long time, and there are plenty of tutorials and guides available for it. However, when I recently had the opportunity to work with <strong>Uniswap v3</strong>, I noticed that the developer ecosystem around it is not as mature as v2. The limited tutorials that do exist are often outdated or incorrect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*0_dO3bzTPFzJ7TaGvwTAxA.jpeg" /><figcaption><a href="https://app.uniswap.org/">https://app.uniswap.org/</a></figcaption></figure><p>As a blockchain<strong> </strong>developer, having your smart contracts deployed on a local testnet makes development and testing much easier. So, I wanted to share how I <strong>deployed Uniswap v3 contracts</strong> on my local <strong>EVM blockchain</strong> and initialized <strong>swap pools</strong> on them.</p><p>This tutorial will be divided into two parts. The first part will cover how to deploy the essential smart contracts of the Uniswap v3 protocol. In the second part, we will interact with the deployed core contracts to create pools and add liquidity to them.</p><h4>PreRequisites</h4><ol><li>Set up a local EVM blockchain on your environment. I used anvil for this. This tutorial is written assuming you have a local blockchain running on the background.</li><li>Deploy the mock contracts for DAI, MATIC, USDC and WETH to your local network using the following repository: <a href="https://github.com/SenudaJayalath/Resources-for-Uniswap-V3-Deployment/tree/main/mock-contracts">Resources-for-Uniswap-V3-Deployment</a>. The deployment steps can be found in the README.md file.</li></ol><h4>Part 1 — Deploy Uniswap V3 Core Contracts</h4><p>Uniswap V3 consists of several core contracts, such as QuoterV2, SwapRouter02, and many more. To ensure your Uniswap functionality works properly, you need to deploy all these essential contracts.</p><p>For this, we will use the official repository provided by Uniswap:</p><p>🔗 <a href="https://github.com/Uniswap/deploy-v3">Uniswap V3 Deployment Repository</a></p><p>This repository contains all the necessary scripts and configurations to deploy Uniswap V3 contracts efficiently.</p><p>The README.md file of this repository can be a bit confusing. Therefore to get the repo working, follow these steps:</p><pre>npm install --force<br>export NODE_OPTIONS=--openssl-legacy-provider<br>npm run build</pre><p>NOTE —I encountered the following error when I didn’t run the second command. This issue seems related to the Node.js version in use. If you don’t experience this error, you can skip the second line above.</p><pre>ncc: Version 0.33.1<br>ncc: Compiling file index.js into CJS<br>Error: error:0308010C:digital envelope routines::unsupported</pre><p>To deploy all the uniswap v3 core contracts run the following command</p><pre>node ./dist/index.js -pk &lt;PRIVATE_KEY&gt; -j &lt;RPC_URL&gt; -w9 &lt;WETH_ADDRESS&gt; -ncl ETH -o &lt;OWNER_ADDRESS&gt; -c 0</pre><p>For the WETH_ADDRESS, use the address of the WETH contract deployed in the <strong>PreRequisites</strong> section. The OWNER_ADDRESS will be set as the owner of the Uniswap contracts deployed.</p><p>The output addresses of all the Uniswap V3 contracts will be stored in ./state.json. Make sure to delete state.json before performing a new fresh deployment.</p><p>NOTE — Sometimes, your deployment may stop midway and throw an error. In such cases, try commenting out the second step (ADD_1BP_FEE_TIER) in the deploy.ts file, then build and run the script again. Occasionally, you may need to run the deployment command twice. If you do, ensure that you <strong>do not delete the </strong><strong>state.json file</strong> in between runs in such a scenario.</p><p>Congrats !! Now we have our version of Uniswap V3 deployed to our local network</p><p>Now, let’s explore how to initialize pools and add liquidity to our Uniswap V3 contracts.</p><h4>Part 2 — Initialize Swap Pools and Add Liquidity</h4><p>In this step, we will deploy two liquidity pools on Uniswap. To do this, use the Hardhat project available <a href="https://github.com/SenudaJayalath/Resources-for-Uniswap-V3-Deployment/blob/main/create-pools/README.md">here</a>. The deployment steps can be found in the README.md file Deploy Uniswap Pool section.</p><p>After successfully completing this step, you will see two pools created with <strong>zero liquidity</strong>.<br>If everything runs perfectly you should see an output like this on the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDf874WIWqhtpvPXzAlPrQ.png" /></figure><p>In the next step, we will add liquidity to ensure the pools function properly. The deployment steps can be found in the README.md file Add Liquidity to Uniswap Pool section.</p><p>If everything runs perfectly you should see an output like this on the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtjeBR0NSZ9eRREmQy1cUg.png" /></figure><p>If you look closely, you will see the liquidity of the pool getting increased !!</p><p>Congrats !! Now you have a working set of Uniswap V3 contracts on your local network.</p><p>If you have any questions please drop a comment. Thanks for reading!!</p><h3>References</h3><ol><li>GitHub Repo — <a href="https://github.com/SenudaJayalath/Resources-for-Uniswap-V3-Deployment">https://github.com/SenudaJayalath/Resources-for-Uniswap-V3-Deployment</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c97df593b63f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-deploy-uniswap-v3-contracts-locally-and-initialize-pools-c97df593b63f">How to Deploy Uniswap V3 Contracts Locally and Initialize Pools</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Full Stack Application With GitHub Actions to a VPS from Hostinger — Part 2]]></title>
            <link>https://blog.devops.dev/deploy-a-full-stack-application-with-github-actions-to-a-vps-from-hostinger-part-2-c09cbda27178?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09cbda27178</guid>
            <category><![CDATA[deployment-automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[vps-hosting]]></category>
            <category><![CDATA[vps]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 17:42:06 GMT</pubDate>
            <atom:updated>2024-09-03T10:49:41.054Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy a Full Stack Application With GitHub Actions to a VPS from Hostinger — Part 2</h3><h4>Second article of a two part series where you can learn how to deploy a full stack application to your VPS</h4><p>This is the second tutorial of the series where you learn how to deploy a full stack application to your VPS using GitHub Actions. In this tutorial you will learn how to properly setup GitHub Actions and also how to configure Nginx to host your full stack application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytMKWqOzo3e1ni4Q98003w.png" /></figure><p>If you have missed the first part of this series, please check it out <a href="https://medium.com/@senudajayalath1/deploy-a-full-stack-application-with-github-actions-to-a-vps-from-hostinger-part-1-fd08bc9d9325">here</a>.</p><h4>Prerequisites</h4><ol><li>Read the first part of this series from this <a href="https://medium.com/@senudajayalath1/deploy-a-full-stack-application-with-github-actions-to-a-vps-from-hostinger-part-1-fd08bc9d9325">link</a><strong>.</strong></li></ol><p>Lets get started !!</p><h4>Deploying the FrontEnd Application</h4><p>To start, we need to configure GitHub Actions for the frontend repository. GitHub Actions allows us to seamlessly integrate a CI/CD pipeline with our server. This setup ensures that any changes made to a specific branch in the repository are automatically deployed. Lets see how we can get this done.</p><p><strong>STEPS — Section A</strong></p><ol><li>Login as “robin” user and create a keypair like we did in the first tutorial. The difference this time is that we will be creating the keypair inside the server and we will not be using a passphrase as well. Leave the passphrase empty. This is very important. Give the key a name like “github_actions”.</li><li>Then navigate to your GitHub repo → settings → secrets and variables → Actions</li><li>Create four new repository secrets with the names HOST, PRIVATE_KEY, SSH_PORT, USERNAME. The HOST should be the ip address of the server, SSH_PORT should be 22 and the USERNAME in this case should be “robin”. For the PRIVATE_KEY copy paste the new private key created in the server with the name “github_actions”.</li><li>Then navigate to the “Actions” tab on the top menu of your repo and click “setup a workflow yourself”.</li><li>This will lead you to a screen where you need to add a yaml file. Provide an appropriate name to the yaml file and copy paste the following</li></ol><pre>name: Deploy Frontend<br><br>on:<br>  push:<br>    branches:<br>      - staging<br>      - specific_branch<br>      - master<br><br>jobs:<br>  deploy_qa:<br>    if: github.ref == &#39;refs/heads/specific_branch&#39;<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br><br>      - name: Connect with VPS<br>        uses: appleboy/ssh-action@master<br>        with:<br>          host: ${{ secrets.HOST }}<br>          username: ${{ secrets.USERNAME }}<br>          key: ${{ secrets.PRIVATE_KEY }}<br>          port: ${{ secrets.SSH_PORT }}<br>          script: |<br>            mkdir -p apps/frontend &amp;&amp; cd apps/frontend<br>            <br>            if [ -d &quot;.git&quot; ]; then<br>              git stash<br>              git pull origin specific_branch<br>            else<br>              git clone -b specific_branch {github_url} .<br>            fi<br>            <br>            npm install --force<br>            npm run build<br><br>            pid=$(pm2 pid &quot;sample frontend&quot; 2&gt;/dev/null)<br>            if [ -n &quot;$pid&quot; ]; then<br>              echo &quot;Reloading application&quot;<br>              pm2 reload &quot;sample frontend&quot;<br>              pm2 save<br>            else<br>              echo &quot;New application&quot;<br>              pm2 start npm --name &quot;sample frontend&quot; -- start<br>              pm2 startup<br>              pm2 save<br>            fi</pre><p>In the above script, I have created a job called “deploy_qa”. This job detects any changes to the “specific_branch” branch, pulls the new changes to the server in to the “apps/frontend” directory, builds the application, and runs it using pm2. It will use the secrets you have defined in step 3 as well. For you to use the above script replace the github_url with url of your repo, and specific_branch with the branch name. You can also use a very definitive name other than “sample frontend” to name your pm2 process.</p><p>NOTE — If you are using the ssh url of the github repo, please note that you will need another pair of ssh keys. Out of them the public key should be added to your github account in SSH &amp; GPG Keys section in the settings tab, while the private key should be in .ssh directory of the server</p><p>If the “job” successfully finished, you will see a green circle next to the job name. Then if you ssh into the server and enter the command pm2 list you will see the process with the process name “sample frontend”. If the status of this process is “online” your process will be running in the background successfully. If not, there might be an error in your frontend code and would need to look into it.</p><p>Assuming the frontend application is running on port 3000, if you enter the command curl localhost:3000 from your server you will see some html components being printed on the console. If its not running on the port you specified you will get an error like this curl: (7) Failed to connect to localhost port 3000 after 0 ms: Connection refused</p><p>Now we have that set up, we would need to then configure Nginx routing so that when a user enters the ip address of the server, that request will be forwarded to localhost:3000 of the server. Lets see how we can do that,</p><p><strong>STEPS — Section B</strong></p><ol><li>Create a new file in the /etc/nginx/sites-available directory using sudo nano /etc/nginx/sites-available/nextjs.conf. Here I have named the new file as nextjs.conf. /sites-available is the subdirectory where you typically store configuration files for different websites or web applications that you want to configure with Nginx.</li><li>Inside the newly created file paste the following</li></ol><pre>server {<br>  listen 80;<br>  server_name your_server_ip;<br>  location / {<br>  proxy_pass http://localhost:3000;<br>  proxy_http_version 1.1;<br>  proxy_set_header Upgrade $http_upgrade;<br>  proxy_set_header Connection &#39;upgrade&#39;;<br>  proxy_set_header Host $host;<br>  proxy_cache_bypass $http_upgrade;<br>  }<br>}</pre><p>Replace “your_server_ip” with the ip of the server or domain name. proxy_pass http://localhost:3000; directive specifies that incoming<br>requests to this location should be proxied to the service running on<br>http://localhost:3000.</p><p>3. To create a symbolic link to enable the configuration run the following commands</p><p>sudo ln -s /etc/nginx/sites-available/nextjs.conf<br>/etc/nginx/sites-enabled/</p><p>sudo rm /etc/nginx/sites-enabled/default.conf</p><p>The second command deletes the default Nginx site configuration file making sure that only the file we configured is available in this directory.</p><p>4. Restart Nginx using sudo service nginx restart</p><p>After these four steps are done, the steps for hosting the frontend will be complete. You can access the frontend through <a href="http://31.220.31.199/">http://ip-address/</a></p><p>Additionally you can setup a firewall in the server as shown below</p><pre>apt install ufw<br>ufw enable<br>ufw allow &quot;Nginx Full&quot;<br>ufw allow ssh</pre><p>Now lets move on to hosting the backend application.</p><h4>Deploying the BackEnd Application</h4><p>You would need to follow the same exact steps in <strong>STEPS — Section A </strong>and make the necessary changes in the backend NodeJs GitHub repo. It is important to note that there is no need to create a new key-pair this time around. You can use the same one generated for the frontend repo.</p><p>The significant change that needs to be done to host the backend repo is the change that needs to be done in the /etc/nginx/sites-available/nextjs.conf file.</p><pre>server {<br>listen 80;<br>server_name your_server_ip;<br>location / {<br>       proxy_pass http://localhost:3000;<br>       proxy_http_version 1.1;<br>       proxy_set_header Upgrade $http_upgrade;<br>       proxy_set_header Connection &#39;upgrade&#39;;<br>       proxy_set_header Host $host;<br>       proxy_cache_bypass $http_upgrade;<br>}<br>location /api/ {<br>        proxy_pass http://localhost:8080/;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_cache_bypass $http_upgrade;<br>  }</pre><p>As shown above you would need to add a second block which will divert any traffic received on route /api/ to localhost:8080 ; the port which is used by the backend in this example.</p><p>After this configuration is done restart Nginx using sudo service nginx restart.</p><p>NOTE — It is important to configure the backend URL as <a href="http://31.220.31.199/">http://ip-address/</a>api in the frontend repo.</p><p>With that final step your full stack application will be fully deployed on your server.</p><p>Thanks for reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09cbda27178" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/deploy-a-full-stack-application-with-github-actions-to-a-vps-from-hostinger-part-2-c09cbda27178">Deploy a Full Stack Application With GitHub Actions to a VPS from Hostinger — Part 2</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Full Stack Application With GitHub Actions to a VPS from Hostinger — Part 1]]></title>
            <link>https://blog.devops.dev/deploy-a-full-stack-application-with-github-actions-to-a-vps-from-hostinger-part-1-fd08bc9d9325?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd08bc9d9325</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[hostinger]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[vps]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Wed, 29 May 2024 17:47:58 GMT</pubDate>
            <atom:updated>2024-06-12T18:08:30.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy a Full Stack Application With GitHub Actions to a VPS from Hostinger — Part 1</h3><h4>First article of a two part series where you can learn how to deploy a full stack application to your VPS</h4><p>This series focuses on deploying a full stack application to your VPS on Hostinger. If you’re deploying to another VPS or server, most of the steps will be the same. In this series, we’ll be working with a NextJs frontend and a NodeJs backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*istVLiZ2cMq_TObvB-OhWA.png" /></figure><p>In this first tutorial I will cover on how to securely setup SSH access to your VPS and then install all the dependencies so that you are ready to deploy your full stack application. In the next tutorial I will show you how to setup a CI/CD pipeline using GitHub Actions so that you can easily deploy your frontend and backend to your VPS as you commit a new change to GitHub.</p><p>Let’s Get Started !!</p><h4>Prerequisites</h4><ol><li>A VPS setup in a Hostinger account. The VPS should have a ubuntu operating system setup. I suggest that you use something like Ubuntu 22.04.</li><li>A working NextJs frontend application and NodeJs backend application in two separate GitHub repos</li><li>Understanding of basic linux commands.</li></ol><p>Now that we have that sorted out, lets get straight to the interesting stuff !!</p><h4>Setup SSH Login to your VPS</h4><p>We can SSH into a VPS as either the root user or a general user. However, it is not a good security practice to use the root user for everyday tasks. Instead, it is recommended to create a general user with limited permissions for general tasks.</p><p>There are two significant ways to SSH into a VPS: using a password or a public/private key pair. Among these, using a key pair is the safest method. The reason for stressing security here is that using a common or easy password for SSH login is a common mistake that can lead to losing access to your server or, even worse, losing all your data. In this tutorial, we will first log in with the root user using the password created during the VPS setup. Then, we will create a new general user and generate two key pairs — one for the root user and one for the general user. As an extra precaution, we will then disable password login for both the users. For the sake of easiness for the tutorial let us assume the ip address of the VPS created is 31.210.21.179.</p><p><strong>STEPS</strong></p><ol><li>Navigate to your local .ssh directory and run ssh-keygen to generate a public/private key pair. When you run ssh-keygen there would be a prompt asking for a file name and a passphrase. You can use and file name you like. For the purpose of this tutorial I will be using admin_role. Then enter a secret passphrase to generate the keypair. This would be your password like phrase used when logging in via key pair in the future. After the key pair is generated you can view the two keys when you enter ls command from the .ssh directory. The public key will be the file with .pub suffix and the other one will be the private key.</li><li>Then to login to the VPS use ssh root@31.210.21.179and enter the root password.</li><li>After logging in navigate to the remote .ssh directory and create a file called authorized_keys if it doesn’t already exist. Then paste the public key that we generated in step 1 to this file.</li><li>After completing step 3, the root user will be able to login to the VPS with the public/private key pair. Lets test it out. Exit the VPS and, this time use the command ssh -i ~/.ssh/admin_role root@31.210.21.179 Then it will ask for the passphrase that was used to create the key pair and after entering the passphrase you will be logged in to the VPS. Note how we didn’t use the password for the root user this time around. The advantage of using a passphrase is that it doesnt have to be as complex and hard to crack as a normal password, and therefore we can remember it very easily.</li></ol><p>Now lets create a general user and give him the ability to login via a key pair</p><p><strong>STEPS</strong></p><ol><li>First let us create a key pair for the user, the same way we did for the root user using ssh-keygen. This time I will be creating the key pair with the name “robin”.</li><li>Then log back into the server using the root user.</li><li>To create a new user use this command adduser robin</li><li>Now we have a new user account with regular account privileges. However, we may sometimes need to do administrative tasks. To account for that we need to add the new user to the sudo group using the command usermod -aG sudo robin</li><li>Navigate to the directory of the general user “robin” using cd /home/robin on the server. Then, create a folder named &quot;.ssh&quot; if it doesn&#39;t already exist using mkdir. Inside the &quot;.ssh&quot; directory, create a file named &quot;authorized_keys&quot; and paste the public key of the generated SSH key pair into this file.</li><li>When step 5 is completed log out as the root user and try to login with ssh -i ~/.ssh/robin robin@31.210.21.179 entering the passphrase for user “robin”.</li></ol><p>If you can successfully login we are good to go 😃</p><p>Now let us disable password login and only allow login through public/private key pair.</p><p><strong>STEPS</strong></p><ol><li>To disable password logins for the user you will need to login as root to the server.</li><li>Then open the file “sshd_config” using the command nano /etc/ssh/sshd_config</li><li>Add the following to the end of the file and save the file. Here “user” refers to the name of the user. In this example “robin”</li></ol><pre>Match User {user}<br>    PasswordAuthentication no<br>    PubkeyAuthentication yes</pre><p>4. Then restart the ssh server using sudo systemctl restart ssh for the changes to take effect.</p><p>To check if password login is disabled you can try to login with the command ssh robin@31.210.21.179 and ideally this should fail. But you will still be able to login with the command ssh -i ~/.ssh/robin robin@31.210.21.179</p><p>Now let us setup all the program requirements that would be needed in the server</p><p><strong>STEPS</strong></p><ol><li>Install Node — You can refer to any online source and get this done. Install the latest node version and npm version</li><li>Install Mongo — This is optional. Depending on the requirement of your full stack application you can setup Mongo</li><li>Install pm2 — PM2 is a process manager for NodeJs<br>applications. PM2 is used to manage and monitor NodeJs processes, making it particularly useful for running NodeJs applications in production environments. To install pm2 globally use sudo npm install -g pm2</li><li>Install Nginx — Nginx is a web server that can also be used as a reverse proxy. Nginx can be installed by sudo apt update &amp;&amp;<br>sudo apt install nginx</li></ol><p>Now we have our VPS setup. All we have to do now is to setup GitHub Actions to to integrate a CI/CD pipeline to fetch new changes from the repo and also setup the needed configurations for Nginx to properly be used as a reverse proxy.</p><p>All that is to be followed up in the next tutorial. So stay Tuned !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd08bc9d9325" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/deploy-a-full-stack-application-with-github-actions-to-a-vps-from-hostinger-part-1-fd08bc9d9325">Deploy a Full Stack Application With GitHub Actions to a VPS from Hostinger — Part 1</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Run A Bootstrapped Corda Network On Docker]]></title>
            <link>https://medium.com/coinmonks/how-to-run-a-bootstrapped-corda-network-on-docker-13c0d0adc7e1?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/13c0d0adc7e1</guid>
            <category><![CDATA[corda-network]]></category>
            <category><![CDATA[bootstrapped-network]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[corda]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 08:18:49 GMT</pubDate>
            <atom:updated>2023-07-24T08:18:49.127Z</atom:updated>
            <content:encoded><![CDATA[<p>Tutorial on how to run an entire corda network on docker containers.</p><p>How cool would it be to set up your own corda network running on docker containers? In this tutorial I would guide you on how to do exactly that. While I was working on this project, I realized how most of the supporting online materials were outdated. In this article, I will guide you through the process of setting up the prerequisites required for the tutorial, providing the latest versions available at the time of writing, and offering insights on how to stay up-to-date with future releases.</p><p>I will also walk you through the step-by-step process of setting up a Corda network with five nodes, featuring the inclusion of two notaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxPXxcb0mECewP_SPQya9A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Shubham Dhage</a> on <a href="https://unsplash.com/s/photos/bootstrap-network?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Prerequisites</h4><ol><li><a href="https://software.r3.com/ui/native/corda/net/corda/corda-tools-network-bootstrapper/">Network Bootstrapper tool</a> — You can download the required version from this link. Keep in mind to download the jar file of the selected bootstrapper tool version. For this tutorial I will be using V4.10 which can be found <a href="https://software.r3.com/ui/native/corda/net/corda/corda-tools-network-bootstrapper/4.10/">here</a>.</li><li>Corda Docker Image — The link to the latest docker image can be found from the <a href="https://docs.r3.com/en/platform/corda/4.10/enterprise/docker-image.html">Corda dcoumentation</a>, or from <a href="https://hub.docker.com/u/corda">Corda Docker Hub</a>. (Note- If you are using the Corda documentation link, I have attached the documentation of Corda V4.10 -enterprise edition. If you are using some other version/edition alter the link accordingly). I will be using corda/community:4.10-zulu-openjdk8 for this tutorial.</li><li>Java 8 — Double check if path to Java 8 is set as $JAVA_HOME</li><li>Docker Compose</li></ol><p>I strongly recommend using identical versions of the Corda Docker image and the Network Bootstrapper. Maintaining version consistency will help ensure a smooth and error-free setup of your Corda network.</p><h4>Initial Setup</h4><p>Let’s kickstart the process by creating a dedicated folder and placing the bootstrap jar file inside it. This folder will serve as the central workspace for this tutorial, and all subsequent files will be generated and stored here. This approach will keep our project organized and make it easier to follow the tutorial steps.<br>Then we need to create some artifacts (node certificates and network-parameters) for the Corda network. These will be generated by running the network bootstrap jar file. To do that first we need to create node.conf files for each node.(i.e for notaries and general nodes)</p><p>This is what a sample node.conf file of a general node looks like</p><pre>devMode=true<br>myLegalName=&quot;O=BankA,L=London,C=GB&quot;<br>p2pAddress=&quot;banka:10200&quot;<br>rpcSettings {<br>    address=&quot;0.0.0.0:10201&quot;<br>    adminAddress=&quot;0.0.0.0:10202&quot;<br>}<br>security {<br>    authService {<br>        dataSource {<br>            type=INMEMORY<br>            users=[<br>                {<br>                    password=test<br>                    permissions=[<br>                        ALL<br>                    ]<br>                    user=user1<br>                }<br>            ]<br>        }<br>    }<br>}<br>sshd {<br>    port = 2222<br>}</pre><p>This is what a sample node.conf file of a notary looks like</p><pre>devMode=true<br>myLegalName=&quot;O=NotaryA,L=London,C=GB&quot;<br>notary {<br>    validating=false<br>}<br>p2pAddress=&quot;notarya:10200&quot;<br>rpcSettings {<br>    address=&quot;0.0.0.0:10201&quot;<br>    adminAddress=&quot;0.0.0.0:10202&quot;<br>}</pre><blockquote>The official Corda docker image exposes the ports <em>10200</em>, <em>10201 </em>and <em>10202</em>. <strong>Do not </strong>change them in the node.conf file<strong>.</strong></blockquote><blockquote>Make sure you listen to 0.0.0.0 not 127.0.0.1 or localhost , since those will be localhost for the container.</blockquote><h4>Running the Bootstrapper</h4><p>Now once we have the node.conf ready for all our nodes we can run the network-bootstrapper tool. To run the bootstrapper tool, place the bootstrapper jar alongside the node.conf files and run the bootstrapper jar using the java -jar &lt;bootstrapper-jar-file-name&gt; command. It should generate a lot of files/folders as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h17LLyL2y3FRUmMVZsiUew.png" /><figcaption>The files/folders in the root directory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvm-h8QMsvnv-TIhik8qWw.png" /><figcaption>Files/folders inside BankA folder</figcaption></figure><p>Now this is a lot of files. We are not going to need all the files that got generated, so let’s do some cleanup. All we need is the node.conf file, the node certificates and the network-paramaters. Below is how the nodes folders look after the removal of all unnecessary files. Notice that we have moved the network-parameters file to a shared folder.</p><blockquote>All the network-parameter files generated inside their respective folders are identical to each other. Therefore, you can move any of the network-parameters files from a generated node folder(i.e bankA folder) to the shared directory.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-CauNjDTIm32doElU3jpA.png" /></figure><p>We need one final thing, a CorDapp. No, I am not going to build one here, but I can use one from the <a href="https://github.com/corda/samples-java">Corda-samples</a> repo.</p><p>But where do we place this CorDapp? Just create another cordapps folder inside the shared folder and drop the CorDapps in. We will configure the Corda docker containers to look for CorDapps in this folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfdxKOlGSskhnK5qXMmtrw.png" /></figure><h4>Configuring the Docker Compose file</h4><p>Now we have all we need to define the docker container. As mentioned earlier, we are going to use docker compose. For each container, we need to define a service in the docker-compose.yaml file. Let’s see how it looks for Bank A and Notary A.</p><pre>notarya:<br>    image: corda/community:4.10-zulu-openjdk8<br>    container_name: notaryb <br>    user: root<br>    ports:<br>      - &quot;10004:10201&quot;<br>    volumes:<br>      - ./notaryA/node.conf:/etc/corda/node.conf<br>      - ./notaryA/node.conf:/opt/corda/node.conf<br>      - ./notaryA/certificates:/opt/corda/certificates<br>      - ./notaryA/persistence:/opt/corda/persistence<br>      - ./notaryA/corda.jar:/opt/corda/corda.jar<br>      - ./notaryA/logs:/opt/corda/logs<br>      - ./shared/cordapps:/opt/corda/cordapps<br>      - ./shared/node-infos:/opt/corda/additional-node-infos<br>      - ./shared/network-parameters:/opt/corda/network-parameters<br>  command: &gt;<br>      bash -c &quot;cd /opt/corda &amp;&amp; java -jar corda.jar run-migration-scripts --core-schemas --app-schemas &amp;&amp; java -jar corda.jar&quot;        <br>  banka: <br>    image: corda/community:4.10-zulu-openjdk8<br>    container_name: banka<br>    user: root<br>    ports:<br>      - &quot;10006:10201&quot;<br>      - &quot;2001:2222&quot;<br>    volumes:<br>      - ./bankA/node.conf:/etc/corda/node.conf<br>      - ./bankA/node.conf:/opt/corda/node.conf<br>      - ./bankA/certificates:/opt/corda/certificates<br>      - ./bankA/persistence:/opt/corda/persistence<br>      - ./bankA/corda.jar:/opt/corda/corda.jar<br>      - ./bankA/logs:/opt/corda/logs<br>      - ./shared/cordapps:/opt/corda/cordapps<br>      - ./shared/node-infos:/opt/corda/additional-node-infos<br>      - ./shared/network-parameters:/opt/corda/network-parameters<br>  command: &gt;<br>      bash -c &quot;cd /opt/corda &amp;&amp; java -jar corda.jar run-migration-scripts --core-schemas --app-schemas &amp;&amp; java -jar corda.jar&quot;</pre><p>As shown above your docker-compose file should have a service for each of the nodes you want in your network.</p><blockquote>Note that we also mount an empty folder called node-infos from the shared directory. As the node spins-up inside the container it places its node-info file in this shared folder, so that its discoverable by other nodes in the network. So this serves as a <a href="https://docs.r3.com/en/platform/corda/4.10/enterprise/network/network-map.html">network map.</a></blockquote><p>To spin up the containers, just use the command docker-compose up from the root directory. If all goes well you will see something like the following for each node you have configured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWMb-zP9kfF2ISAtnLeVJQ.png" /></figure><h4>Connecting to the Node</h4><p>We do not get the CRaSH shell as we normally get when running the node directly in the host machine. So, how do we connect to the node? There are two ways to that:</p><ul><li>Using a client. (You don’t have to build one — Try <a href="https://www.youtube.com/watch?v=cn2lhS8pjRs&amp;t=">node-explorer</a>)</li><li>Using ssh: ssh -p <strong>[</strong>portNumber<strong>]</strong> <strong>[</strong>host<strong>]</strong> -l <strong>[</strong>user<strong>]</strong></li></ul><h4>Possible Errors</h4><p>These are some of the errors I got and the solutions for them,</p><ol><li>Incompatible database schema version detected, please run schema migration scripts (node with sub-command run-migration-scripts). Reason: There are 110 outstanding database changes that need to be run.<br><strong>Solution</strong> — I have added a command for each service in the docker-compose file to overcome this</li><li>Required platform version is less than the minimum platform version error<br><strong>Solution</strong> — Use the same same version of bootstrapper tool and docker image</li></ol><p>This way you can setup your own boostrapped corda network very easily. If you do encounter errors let me know in the comment section.</p><p>Happy Coding!!</p><h4>Resources</h4><ol><li>Network Bootstrapper Tool — <a href="https://software.r3.com/ui/native/corda/net/corda/corda-tools-network-bootstrapper/">https://software.r3.com/ui/native/corda/net/corda/corda-tools-network-bootstrapper/</a></li><li>Corda Documentation — <a href="https://docs.r3.com/en/platform/corda/4.10/enterprise/docker-image.html">https://docs.r3.com/en/platform/corda/4.10/enterprise/docker-image.html</a></li><li>Corda Docker Hub — <a href="https://hub.docker.com/u/corda">https://hub.docker.com/u/corda</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13c0d0adc7e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-run-a-bootstrapped-corda-network-on-docker-13c0d0adc7e1">How To Run A Bootstrapped Corda Network On Docker</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy a Proxy Contract With Web3 Java]]></title>
            <link>https://medium.com/coinmonks/how-to-deploy-a-proxy-contract-with-web3-java-ecf987a9e7dc?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecf987a9e7dc</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[web3-java]]></category>
            <category><![CDATA[proxy-contract]]></category>
            <category><![CDATA[web3j]]></category>
            <category><![CDATA[deploy-proxy]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Mon, 29 May 2023 17:57:33 GMT</pubDate>
            <atom:updated>2023-05-29T17:57:33.329Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tutorial on how to deploy a proxy smart contract with web3 java</h4><p>In the world of blockchain development, proxy contracts play a vital role in enhancing the flexibility and upgradability of smart contracts. When it comes to deploying a proxy contract with Web3 Java, developers gain the ability to seamlessly update contract logic without disrupting existing deployments or migrating large amounts of data. This powerful feature opens up a realm of possibilities for smart contract management and maintenance. In this article, we will delve into the process of deploying a proxy contract with Web3 Java, exploring the fundamental concepts, tools, and steps required to harness this technology effectively. So, if you’re ready to unlock the potential of proxy contracts and elevate your smart contract deployments, let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asSoi1Hdspukw_c9-U5XNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@shubzweb3?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Shubham’s Web3</a> on <a href="https://unsplash.com/s/photos/web3?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Step 1. Prerequisites</h4><ol><li>Previous knowledge on proxy contracts and how they work.</li></ol><h4>Step 2. Understanding the smart contracts</h4><p>Before we get our hands dirty, first let us look at the proxy contract and the implementation contract which we will be interacting with.</p><p>The Beacon proxy contract looks something like the following. Nothing special. Just a Beacon proxy contract that adheres to the Openzeppelin standards.</p><pre>// contracts/BeaconProxy.sol<br>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br>import &quot;https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/IBeacon.sol&quot;;<br>import &quot;https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/Proxy.sol&quot;;<br>import &quot;https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/ERC1967/ERC1967Upgrade.sol&quot;;<br><br>/**<br> * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.<br> *<br> * The beacon address is stored in storage slot `uint256(keccak256(&#39;eip1967.proxy.beacon&#39;)) - 1`, so that it doesn&#39;t<br> * conflict with the storage layout of the implementation behind the proxy.<br> *<br> * _Available since v3.4._<br> */<br><br>contract BeaconProxy is Proxy, ERC1967Upgrade {<br>    event BeaconProxyDeployed(address contractAddress, address beaconAddress, address creator,string assetId);<br>    /**<br>     * @dev Initializes the proxy with `beacon`.<br>     *<br>     * If `data` is nonempty, it&#39;s used as data in a delegate call to the implementation returned by the beacon. This<br>     * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity<br>     * constructor.<br>     *<br>     * Requirements:<br>     *<br>     * - `beacon` must be a contract with the interface {IBeacon}.<br>     */<br>    constructor(address beacon, bytes memory data,string memory assetId) payable {<br>        assert(_BEACON_SLOT == bytes32(uint256(keccak256(&quot;eip1967.proxy.beacon&quot;)) - 1));<br>        _upgradeBeaconToAndCall(beacon, data, false);<br>        emit BeaconProxyDeployed(address(this), beacon, msg.sender,assetId);<br>    }<br><br>    /**<br>     * @dev Returns the current beacon address.<br>     */<br>    function _beacon() internal view virtual returns (address) {<br>        return _getBeacon();<br>    }<br><br>    /**<br>     * @dev Returns the current implementation address of the associated beacon.<br>     */<br>    function _implementation() internal view virtual override returns (address) {<br>        return IBeacon(_getBeacon()).implementation();<br>    }<br><br>    /**<br>     * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.<br>     *<br>     * If `data` is nonempty, it&#39;s used as data in a delegate call to the implementation returned by the beacon.<br>     *<br>     * Requirements:<br>     *<br>     * - `beacon` must be a contract.<br>     * - The implementation returned by `beacon` must be a contract.<br>     */<br>    function _setBeacon(address beacon, bytes memory data) internal virtual {<br>        _upgradeBeaconToAndCall(beacon, data, false);<br>    }<br>}</pre><p>In this tutorial, I have decided to utilize the ERC1400 contract as the implementation contract for the sake of clarity and simplicity. However, it’s worth noting that you have the freedom to opt for any contract that suits your requirements. The signature of the intitializer function of the ERC1400 contract is shown below for reference.</p><pre>function initialize(<br>        string memory tokenName,<br>        uint256 tokenGranularity,<br>        address admin,<br>        address[] operators,<br>        bool whiteListingEnable,<br>    ) external initializer {</pre><h4>Step 3. Encoding the initialize function of the implementation contract</h4><p>Encoding the initialize function of the implementation contract involves transforming the function’s parameters into a hexadecimal format compatible with Ethereum’s ABI encoding. This encoding ensures seamless interaction between the proxy contract and the implementation contract during deployment. By accurately encoding the initialize function, the proxy contract can successfully initialize the implementation contract with the desired parameters, facilitating smooth contract functionality.</p><p>In web3 Java it is done as follows</p><pre>Address[] addresses = new Address[] {<br>                     new Address(&quot;0x1234567890123456789012345678901234567890&quot;),<br>                     new Address(&quot;0x0987654321098765432109876543210987654321&quot;)<br>                     };<br>Type operatorAddresses = new DynamicArray(Address.class, addresses);<br><br>List&lt;Type&gt; inputParameters = Arrays.asList(new Utf8String(tokenName), new Uint256(1), new Address(credentials.getAddress()),operatorAddresses, new Bool(false));<br>Function function =<br>                    new Function(<br>                            &quot;initialize&quot;, <br>                            inputParameters,<br>                            Collections.emptyList());<br>String encodedFunction = FunctionEncoder.encode(function);</pre><p>In the above code snippet notice how different types of variables are passed in different formats to be encoded. Also since the intialize function does not return anything, we pass in Collections.emptyList() as the third element for creating the Function.</p><h4>Step 3. Encoding the constructor of the proxy contract.</h4><p>In the same way the constructor of the proxy contract should also be encoded. Since the constructor requires the encoded initialize function as a parameter, we should pass that in as well.</p><pre>//This is done to remove the preceding &quot;0x&quot; of the hex string<br> String encodedFunction =encodedFunction.substring(2);<br><br> byte[] hexBytes = parseHexBinary(encodedFunction);<br><br> String encodedConstructor =<br>        FunctionEncoder.encodeConstructor(<br>                 Arrays.asList(<br>                           new Address(beaconAddress),<br>                           new DynamicBytes(hexBytes),<br>                           new Utf8String(symbol)));</pre><h4>Step 3. Getting the gas estimate for the transaction</h4><p>Determining the gas estimate for a transaction is crucial in optimizing cost and efficiency within Ethereum. By obtaining the gas estimate, developers can estimate the amount of gas required for executing a transaction, enabling them to set appropriate gas limits and avoid unnecessary expenses. Let us see how this is done with web3 java.</p><pre>// Retrieve the nonce for the relevant address<br>EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.LATEST).send();<br>BigInteger nonce = ethGetTransactionCount.getTransactionCount();<br><br>//Use a safe gas limit which would not be exceeded(i.e block gas limit)<br>BigInteger blockGasLimit = BigInteger.valueOf(3000000L);<br><br>Transaction mimicTransaction = Transaction.createContractTransaction(credentials.getAddress(),nonce, gasPrice,blockGasLimit,BigInteger.ZERO,proxy_bin +encodedConstructor);<br><br>EthEstimateGas gasEstimate = web3.ethEstimateGas(mimicTransaction).send();<br>if (gasEstimate.hasError()) {<br>    log.info(&quot;Contract error mimicTransaction: {}&quot;, gasEstimate.getError().getMessage());<br>    throw new ValidationException(gasEstimate.getError().getMessage());<br>} else {<br>    log.info(&quot;Gas estimate: {}&quot;, gasEstimate.getAmountUsed()); <br>}<br>         </pre><p>As you can see in the above code the transaction is mimiced to simulate how many gas units will be used when this transaction will be actually deployed. As the last parameter of createContracttransaction function, proxy_bin + encodedConstructor is passed. This represents the binary file of the proxy contract and the encodedConstructor value which we calculated in step 3. This is the data that is passed when deploying the contract. if you remember this encodedConstructor contains the encode value of the initialize function of the implementation contract.</p><h4>Step 4. Deploying the Proxy contract</h4><p>Now that we have estimated the gas units which will be consumed, let us now deploy the contract. For this you can use the following code.</p><pre>// Create new Transaction<br>RawTransaction rawTransaction = RawTransaction.createContractTransaction(nonce,   gasPrice,  gasEstimate.getAmountUsed().multiply(BigInteger.valueOf(2)),  BigInteger.ZERO, proxy_bin + encodedConstructor );<br>long chainId = Long.parseLong(chain.getNetworkId());<br><br>// Sign the Transaction<br>byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction,chainId, credentials);<br>String hexValue = Numeric.toHexString(signedMessage);<br><br>// Send the Transaction<br>org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3<br>      .ethSendRawTransaction(hexValue).sendAsync().get();<br>if (transactionResponse.hasError()) {<br>       log.info(&quot;Contract error transactionResponse: {}&quot;, transactionResponse.getError().getMessage());<br>       throw new ValidationException(transactionResponse.getError().getMessage());<br>} else {<br>       log.info(&quot;Transaction hash:{}&quot;,transactionResponse.getTransactionHash());<br>}</pre><p>The RawTransaction.createContractTransaction uses the same parameters as the Transaction.createContractTransaction function used to mimic the transaction in step 3. Just to be on the safe side I have put a margin for the amount of gas used calculated in step 3 by multiplying the value calculated by 2. After getting the chain ID and signing the raw transaction with the private key, it is sent out to the network. If everything goes well you will receive a transaction hash that would represent the contract deployment transaction.</p><h4>Summary</h4><p>It is evident that deploying a proxy contract with web3 java is not as simple as using web3Js but it can be done. :)</p><p>Happy Coding !!</p><h3>Resources</h3><ol><li>Web3 java documentation — <a href="https://docs.web3j.io/4.10.0/">https://docs.web3j.io/4.10.0/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecf987a9e7dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-deploy-a-proxy-contract-with-web3-java-ecf987a9e7dc">How to Deploy a Proxy Contract With Web3 Java</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Custom Errors in Solidity Save Gas]]></title>
            <link>https://medium.com/coinmonks/how-custom-errors-in-solidity-save-gas-3c499aa22745?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c499aa22745</guid>
            <category><![CDATA[errors-in-solidity]]></category>
            <category><![CDATA[gas-efficient]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[save-gas]]></category>
            <category><![CDATA[custom-errors]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 09:33:05 GMT</pubDate>
            <atom:updated>2023-03-21T09:33:05.798Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial on how gas is saved when using custom errors in Solidity and the drawbacks of custom errors</h4><p>Starting from <a href="https://github.com/ethereum/solidity/releases/tag/v0.8.4">Solidity v0.8.4</a>, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors. Although there were methods previous to Solidity v0.8.4 to warn users about why operations failed, these were rather expensive when it comes to both deployment costs and run time costs. Below shown is an example on how custom errors are implemented</p><pre>// SPDX-License-Identifier: GPL-3.0<br>pragma solidity ^0.8.4;<br><br>error Unauthorized();<br><br>contract ErrorContract {<br>    address payable owner = payable(tx.origin);<br><br>    function withdraw() view public {<br>        if (msg.sender != owner)<br>            revert Unauthorized();<br>    }   <br>}</pre><p>The syntax of errors is similar to that of <a href="https://docs.soliditylang.org/en/latest/contracts.html#events">events</a> in Solidity. The only difference is that custom errors have to be called with the keyword revert. Another added advantage of custom errors is that you can pass parameters to your custom error to retrieve a custom error message for each function call. More on that <a href="https://blog.soliditylang.org/2021/04/21/custom-errors/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXyU6ziL93ZAaisYfNkLdg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dav420?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">David Pupaza</a> on <a href="https://unsplash.com/s/photos/error?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Before we move onto how custom errors in Solidity save gas in both deployment and run time, let us see how errors were written before Solidity v0.8.4.</p><pre>// SPDX-License-Identifier: GPL-3.0<br>pragma solidity ^0.8.4;<br><br>contract ErrorContract {<br>    address payable owner = payable(tx.origin);<br><br>    function withdraw_require() view public {<br>        require (msg.sender == owner,&quot;Unauthorized&quot;);<br>    }<br>    function withdraw_revert() view public {<br>        if (msg.sender != owner)<br>            revert (&quot;Unauthorized&quot;);<br>    }   <br>}</pre><p>In the above code both the functions withdraw_require and withdraw_revert are identical in functionality. In other words the require statement is also another way of writing a revert statement inside a if block. Apart from being gas expensive, these two methods cannot throw custom errors (i.e cannot pass in parameters). Now let us move onto the gas comparison</p><h4>Deep Dive Into Errors</h4><p>First let us see the <a href="https://docs.soliditylang.org/en/v0.8.17/yul.html">Yul Code</a> for the code snippet with custom errors.</p><pre>let free_mem_ptr := mload(64)<br>mstore(free_mem_ptr, 0x82b4290000000000000000000000000000000000000000000000000000000000)<br>revert(free_mem_ptr, 4)</pre><p>0x82b4290000000000000000000000000000000000000000000000000000000000 is the same as the ABI encoding of the function Unauthorized(). For anyone who doesn’t know how to get the ABI encoding of a function you can try this.</p><blockquote>abi.encodeWithSignature(“Unauthorized()&quot;)</blockquote><p>Now let us see the Yul Code for the code snippet without custom errors.</p><pre>let free_mem_ptr := mload(64)<br>mstore(free_mem_ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000)<br>mstore(add(free_mem_ptr, 4), 32)<br>mstore(add(free_mem_ptr, 36), 12)<br>mstore(add(free_mem_ptr, 68), &quot;Unauthorized&quot;)<br>revert(free_mem_ptr, 100)</pre><p>If you look closely at this script, you will see the difference between custom errors and require / revert statements. Here 0x08c379a0 is the ‘selector’ of the fuction Error(string). It is saved in memory. Then the string Unauthorized is saved in memory as a string as well. Since strings do not have a fixed length, the length is also saved in memory. It is evident that this method requires way more opcodes when compared to using custom errors. This means that custom errors require less gas in run time.</p><p>On the other hand, custom errors require less memory at contract deployment to store its code and therefore requires less gas at time of deployment.</p><h4>Drawback of Custom Errors</h4><p>Currently frameworks like <a href="https://docs.ethers.org/v5/">ethers.js</a> and <a href="https://web3js.readthedocs.io/en/v1.8.2/">web3.js</a> does not provide direct support for custom errors. In other words there is no direct way of decoding error data using the most common frameworks. <a href="https://blog.soliditylang.org/2021/04/21/custom-errors/">This</a> document shows how error data can be decoded and you can see it is a bit complex.</p><h4>Resources</h4><ol><li>Solidity v0.8.4 — <a href="https://github.com/ethereum/solidity/releases/tag/v0.8.4">https://github.com/ethereum/solidity/releases/tag/v0.8.4</a></li><li>Solidity events — <a href="https://docs.soliditylang.org/en/latest/contracts.html#events">https://docs.soliditylang.org/en/latest/contracts.html#events</a></li><li>Custom errors in Solidity — <a href="https://blog.soliditylang.org/2021/04/21/custom-errors/">https://blog.soliditylang.org/2021/04/21/custom-errors/</a></li><li>Yul Code — <a href="https://docs.soliditylang.org/en/v0.8.17/yul.html">https://docs.soliditylang.org/en/v0.8.17/yul.html</a></li><li>Ethers.js documentation — <a href="https://docs.ethers.org/v5/">https://docs.ethers.org/v5/</a></li><li>Web3.js documentation — <a href="https://web3js.readthedocs.io/en/v1.8.2/">https://web3js.readthedocs.io/en/v1.8.2/</a></li></ol><blockquote><em>New to trading? Try </em><a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a"><em>crypto trading bots</em></a><em> or </em><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c"><em>copy trading</em></a><em> on </em><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769"><em>best crypto exchanges</em></a></blockquote><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h3>Also, Read</h3><ul><li><a href="https://medium.com/coinmonks/free-crypto-signals-48b25e61a8da">Free Crypto Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bots</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li><li><a href="https://medium.com/coinmonks/top-17-folding-electric-bikes-5e296f0918cb">16 Best Folding Electric Bikes</a></li><li><a href="https://medium.com/coinmonks/the-28-best-electric-bikes-review-and-buying-guide-in-2023-7bb3146cb403">28 Best Electric Bikes Review</a></li><li>Top 3 <a href="https://medium.com/coinmonks/top-3-binance-futures-trading-bots-e6031f84b3f9">Binance Futures Trading Bots</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c499aa22745" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-custom-errors-in-solidity-save-gas-3c499aa22745">How Custom Errors in Solidity Save Gas</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Sign Transactions Offline in Solana Using Anchor]]></title>
            <link>https://medium.com/coinmonks/how-to-sign-transactions-offline-in-solana-using-anchor-39bbee897428?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/39bbee897428</guid>
            <category><![CDATA[signtransaction]]></category>
            <category><![CDATA[anchor-protocol]]></category>
            <category><![CDATA[solanas]]></category>
            <category><![CDATA[offline-signing]]></category>
            <category><![CDATA[anchor]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 07:14:19 GMT</pubDate>
            <atom:updated>2023-03-09T07:14:19.677Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article explains how to sign and execute your transactions separately using Anchor framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Chs_WNVU2z87SsJl.jpeg" /></figure><p>Some security models require keeping signing keys, and thus the signing process, separated from transaction creation and network broadcast. For example, imagine you have built a DAPP on Solana in which the transactions should be executed in the backend. Since it is not possible to transfer signing keys to the backend (due to safety issues), the approach to follow is to get your users to sign each transaction on the frontend and send it to the backend to be executed.</p><p>Now let us see step by step on how to do this.</p><h3>Step 1 — Prerequisites</h3><p>VScode — Code editor<br>Anchor version — 0.24.2<br>React</p><p>Previous knowledge on Anchor framework</p><p>After you have anchor installed create a new anchor project using anchor init&lt;project_name&gt;</p><h3>Step 2 — Write the Anchor Code</h3><p>This is the code I have written for this tutorial which will transfer SOL from to account to from account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HXPnBZD9ZqQ1tQX1.png" /></figure><p>As you can see here I have created a function called transfer_sol which takes in a struct called TransferSOL. This struct has 3 accounts called from,to, &amp; system_program. The from account act as the signer for this transaction.</p><p>So the intention of this exercise would be to sign the transfer_sol transaction in the frontend and pass the signed transaction to the backend using an API request.</p><p>View the full Anchor code <a href="https://github.com/SenudaJayalath/offline-signing-anchor">here</a></p><p>So now lets see how the frontend code for this looks like,</p><h3>Step 3 — Write the FrontEnd Code</h3><p>For this I have created a React project.</p><p>This is the part where we call the smart contract we created earlier using the frontend. Prior to this we should have deployed the smart contract and imported the idl.json generated from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*H99rwL4fHRQ-QXQ4.png" /></figure><p>As shown above we have created a Transaction which calls the transferSOL function. Unlike the most common program.methods.transferSol().rps() function which executes the Anchor function immediately program.transfer.transferSol() creates a transaction of the type web3.Transaction without executing it.</p><p>Now we need to sign the created transaction. Before we do that, we need to configure the blockhash and feepayer of the transaction as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*oju8JRhh-B3vE6Rx.png" /></figure><blockquote><em>An important point to remember is that the latestBlockHash is valid till around 1 minute from the point it was added to the transaction. Exactly speaking it is valid until another 150 blocks have validated or around 1 min 19secs according to the Solana documentation.<br>Therefore, the transaction has to be executed before that.</em></blockquote><p>Now lets get to the signing part.</p><p>As you can remember the transfersol function only needs one signer who is the from account. Therefore, we sign the transaction with the provider.wallet who is the from account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*jVInxVreVOM2fVcE.png" /></figure><p>If your transaction required any other signers except your connected wallet you can use<br>let signed = await tx.sign(); or<br>let signed = await tx.setSigners(); for a list of signers.</p><p>Now we are ready to execute the signed transaction. You can always send the variable signed over an API request to your backend or do whatever you want with it and execute the transaction. But keep in mind you have to do it within 1 minute 😉</p><p>In my case I will be sending it to my backend where the transaction will be executed. The code is shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qSnXJMq1QCez7uN8.png" /></figure><p>If you are also sending your signed transaction over an API request to your backend keep in mind you should be sending the blockhash as well with the variable signed. (This is not a necessity, but always good)</p><p>And there we have it 😌. Now we don’t need to execute the transaction when we call the function from the frontend. We can sign the transaction and pass it on!!.</p><p>The complete code for the frontend is <a href="https://github.com/SenudaJayalath/offline-signing-frontend">here</a></p><h3>Resources</h3><ol><li>Anchor Code — <a href="https://github.com/SenudaJayalath/offline-signing-anchor">https://github.com/SenudaJayalath/offline-signing-anchor</a></li><li>Frontend Code — <a href="https://github.com/SenudaJayalath/offline-signing-frontend">https://github.com/SenudaJayalath/offline-signing-frontend</a></li></ol><blockquote><em>New to trading? Try </em><a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a"><em>crypto trading bots</em></a><em> or </em><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c"><em>copy trading</em></a><em> on </em><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769"><em>best crypto exchanges</em></a></blockquote><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h3>Also, Read</h3><ul><li><a href="https://medium.com/coinmonks/free-crypto-signals-48b25e61a8da">Free Crypto Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bots</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li><li><a href="https://medium.com/coinmonks/top-17-folding-electric-bikes-5e296f0918cb">16 Best Folding Electric Bikes</a></li><li><a href="https://medium.com/coinmonks/the-28-best-electric-bikes-review-and-buying-guide-in-2023-7bb3146cb403">28 Best Electric Bikes Review</a></li><li>Top 3 <a href="https://medium.com/coinmonks/top-3-binance-futures-trading-bots-e6031f84b3f9">Binance Futures Trading Bots</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39bbee897428" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-sign-transactions-offline-in-solana-using-anchor-39bbee897428">How To Sign Transactions Offline in Solana Using Anchor</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is It Safe To Store Private Data On Smart Contracts?]]></title>
            <link>https://medium.com/coinmonks/is-it-safe-to-store-private-data-on-smart-contracts-2b4ead91eeff?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b4ead91eeff</guid>
            <category><![CDATA[is-it-safe]]></category>
            <category><![CDATA[smart-contract-hacking]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[private-data]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 08:57:26 GMT</pubDate>
            <atom:updated>2023-02-10T08:57:26.012Z</atom:updated>
            <content:encoded><![CDATA[<h4>How private variables in smart contracts can be exposed</h4><p>Use cases for blockchain are growing day by day. Therefore, various breeches due to the exploitation of the capabilities of blockchain technologies or breeches due to the ignorance of developers have been common news during the past couple of years. As developers, we should be careful how we build applications on top of blockchain protocols. A very common point most developers tend to overlook on is security concerns when storing data inside smart contracts. Let us take this common use case as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3iHTlroHtjaZiBQLGmKFfw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/de/@anniespratt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Annie Spratt</a> on <a href="https://unsplash.com/s/photos/smart-contract-security-code-private?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Let us assume that a medical insurance agency wanted to build a fully distributed application using blockchain principles. This application would need to store personal information such as previous medical histories of each person. These data are really personal, and should by no means fall into the hand of any third party. One option developers taking on this task will have is to store data in smart contracts using state variables. Let us evaluate if this would be the best thing to do.</p><p>First let us see what variables are in Solidity. This is how we declare a variable in Solidity,</p><pre>&lt;type&gt; &lt;access modifier&gt; &lt;variable name&gt; ;<br><br>eg:<br>uint8 public number</pre><p>There are three types of access modifiers in Solidity: <em>public</em>, <em>private</em> and <em>internal. </em>The difference of each type is a whole new topic and will be discussed in another article. For now, let’s consider what public and private access modifiers are, and how they differ from each other on a high level basis.</p><p>Public variables allow other contracts to read the stored value, while private variables prevent other contracts from accessing it. Coming back to the previous problem, can developers securely store private data like past medical records in private variables? It is obvious that public variables won’t do the job. But going by the definition of private variables in Solidity, it looks like private variables would be ideal for the job.</p><p>This is where most developers get it wrong. Although private variables prevent other smart contracts from accessing the stored value, it does not guarantee that the variable cannot be accessed from the outside.</p><p>Before we get to that let us see how data is physically stored in smart contracts.</p><blockquote>Data is stored sequentially in slots, in order of declaration.</blockquote><blockquote>Storage is optimized to save byte space. So if sequential variables will fit in a single 32-byte slot, they will share the same slot, indexing from the least significant bits (from the right).</blockquote><p>A visualisation of how Ethereum storage looks like and how space optimization is done:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*OYZ74WH2aOsbQwzL8ynwXw.png" /><figcaption>Photo by <a href="https://medium.com/@0xsage">0xSage</a> on <a href="https://medium.com/coinmonks/how-to-read-private-variables-in-contract-storage-with-truffle-ethernaut-lvl-8-walkthrough-b2382741da9f">Medium</a></figcaption></figure><p>Since we got that cleared out, let us take the below example and see how a person can exploit a private variable to see what it has stored.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Vault {<br>  bool public locked;<br>  bytes32 private password;<br>  constructor(bytes32 _password) {<br>    locked = true;<br>    password = _password;<br>  }<br>  function unlock(bytes32 _password) public {<br>    if (password == _password) {<br>      locked = false;<br>    }<br>  }<br>}</pre><p>In the above smart contract, <em>locked</em> and <em>password</em> are two state variables. <em>Locked</em> is a public variable and therefore we can access that variable from the outside. On the other hand, <em>password</em> is a private variable.</p><p>Conveniently, <a href="https://github.com/ethereum/web3.js/">Web3</a> allows you to reach into contract storage via: <br>await web3.eth.getStorageAt(contractAddress, slotNumber)</p><p>According to the above definitions we can read what is stored in the <em>password</em> variable via:<br>await web3.eth.getStorageAt(contractAddress, 1)</p><p>and<em> locked</em> variable via:<br>await web3.eth.getStorageAt(contractAddress, 0)</p><blockquote><strong>NOTE</strong> — Irrespective of a variable being private or public <em>web3.eth.getStorageAt </em>can be used to read the stored value.</blockquote><p>From the above example you can see how easy it is for an outside entity to expose private variables in smart contracts.</p><h4>Key Security Takeaways</h4><p>It’s important to remember that marking a variable as <em>private</em> only prevents other contracts from accessing it. State variables marked as <em>private</em> and local variables are still publicly accessible.</p><p>To ensure that data is private, it needs to be encrypted before being put onto the blockchain. In this scenario, the decryption key should never be sent on-chain, as it will then be visible to anyone who looks for it</p><h3>Resources</h3><ol><li>Web3 GitHub Repo — <a href="https://github.com/web3/web3.js">https://github.com/web3/web3.js</a></li></ol><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a> on <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">best crypto exchanges</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b4ead91eeff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/is-it-safe-to-store-private-data-on-smart-contracts-2b4ead91eeff">Is It Safe To Store Private Data On Smart Contracts?</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Do Partial Fills With The Seaport Protocol]]></title>
            <link>https://medium.com/coinmonks/how-to-do-partial-fills-with-the-seaport-protocol-fd9ddb3c1f7f?source=rss-d8e30a2b0da7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd9ddb3c1f7f</guid>
            <category><![CDATA[partial-fill]]></category>
            <category><![CDATA[seaport-protocol]]></category>
            <category><![CDATA[seaport]]></category>
            <category><![CDATA[partial]]></category>
            <dc:creator><![CDATA[Senudajayalath]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 09:13:56 GMT</pubDate>
            <atom:updated>2023-01-02T09:13:56.782Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide to enable partial fulfilment of orders when using the Seaport Protocol.</p><p>The Seaport Protocol is a new standard introduced by Opensea to be used as an accelerator for anyone trying to build a NFT marketplace on any EVM compatible chain. Partial fulfilment of orders is also a special feature that can be seen in most of the NFT marketplaces. In a partial fulfilment scenario, only a part of what is offered in the offer is bought by the buyer. The buyer in return only pays for what he/she buys. Although this functionality is not yet supported in the Opensea marketplace, the Seaport Protocol has been developed so that it can accommodate partial fills in the future. In this tutorial I will guide you on how to do partial fills using the main two functions <em>fulfillAdvancedOrder</em> and <em>executeMatchAdvancedOrders</em> in the Seaport Protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mupZ2OAUDlVsj7szktbx4Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@robwicks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rob Wicks</a> on <a href="https://unsplash.com/s/photos/half?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Before we get into the code, it is important to know how Seaport distinguishes a partial fill enabled order from an order that is not. It all depends on the criteria that gets passed when the order is constructed. The official Seaport <a href="https://docs.opensea.io/v2.0/reference/seaport-overview">docs</a> says the following.</p><blockquote>The orderType designates one of four types for the order depending on two distinct preferences:</blockquote><blockquote>FULL indicates that the order does not support partial fills, whereas PARTIAL enables filling some fraction of the order, with the important caveat that each item must be cleanly divisible by the supplied fraction (i.e. no remainder after division).</blockquote><blockquote>OPEN indicates that the call to execute the order can be submitted by any account, whereas RESTRICTED requires that the order either be executed by the offerer or the zone of the order, or that a magic value indicating that the order is approved is returned upon calling an isValidOrder or isValidOrderIncludingExtraData view function on the zone.</blockquote><p>According to the above paragraph,<em> orderType </em>can be<em> </em>either 0,1,2 or 3. By convention all the <em>FULL</em> orders will be either 0 or 2 (even), while all the <em>PARTIAL</em> orders will be either 1 or 3 (odd).</p><p>Now let us see how partial fills can be enabled for fixed price sales and auctions.</p><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a> on <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">best crypto exchanges</a></blockquote><h4>Partial Fills for Fixed Price Sales</h4><p>In a fixed price sale the price is fixed. Let us say that the seller wants to sell 10 copies of a certain ERC1155 token. Let us consider a situation where the buyer doesn&#39;t want to buy the whole lot, but is willing to buy a fraction of the tokens up for sale. In return the buyer will pay a fraction of the asking amount as well.</p><p>This is all possible because of the <em>orderType</em> variable and the concept of <em>denominator</em> and <em>numerator</em> in a Seaport order. Let us see how this works in more detail from the given code snippet.</p><pre>  it(&quot;Seller creates an order&quot;, async () =&gt; {<br>      const nftID = randomBN();<br>      // conduitOne-&gt;updateChannel is called in seaportFixtures contructor<br>      // So, marketplace.address has an opened channel to conduitOne<br>      await testERC1155<br>      .connect(seller)<br>      .setMintApproval(conduitOne.address, true);<br><br>      const offerOne = [<br>        getTestItem1155(nftId, toBN(10), toBN(10), testERC1155.address, undefined),<br>      ];<br>      const considerationOne = [<br>        getItemETH(parseEther(&quot;10&quot;), parseEther(&quot;10&quot;), seller.address), // payment for seller<br>        getItemETH(parseEther(&quot;10&quot;), parseEther(&quot;10&quot;), owner.address),    // Platform fees<br>      ];<br><br>      let { order, orderHash, value } = await createOrder(<br>        seller,<br>        zoneAddr,<br>        offerOne,<br>        considerationOne,<br>        1, // PARTIAL_OPEN<br>        [],<br>        null,<br>        seller,<br>        ethers.constants.HashZero,<br>        conduitKeyOne<br>      );<br><br>      orderSeller = order;<br>      valueSeller = value;<br>      orderHashSeller = orderHash;<br>    });<br><br>    it(&quot;Buyer executes the Order&quot;, async () =&gt; {<br>      let balanceBeforeTransaction = await provider.getBalance(seller.address)<br><br>      orderSeller.denominator = 10;<br>      orderSeller.numerator = 3;<br><br>      const tx = await marketplaceContract<br>        .connect(buyer) // Buyer sign and send the seller&#39;s order to the seaport contract<br>        .fulfillAdvancedOrder(<br>          orderSeller,<br>          [],<br>          toKey(0),<br>          ethers.constants.AddressZero,<br>          {<br>            value:valueSeller,<br>          }<br>        );<br>      const receipt = await tx.wait();<br><br>      let tokenBalanceBuyer = await testERC1155.balanceOf(buyer.address, nftId)<br>      let ethBalance = await provider.getBalance(seller.address)<br>      assert(tokenBalanceBuyer.eq(toBN(3)), &quot;Tx did not happen&quot;)<br>      assert(ethBalance.eq(balanceBeforeTransaction.add(parseEther(&quot;3&quot;))), &quot;Eth transfer did not happen&quot;)<br>    });</pre><p>As you can see in the above code, the <em>orderType</em> is set to 1 (i.e partial open). Another thing to note is how the buyer has changed the <em>numerator</em> and <em>denominator</em> of the order. Since the buyer is willing to buy only 3 copies of that given NFT, the buyer has set the <em>denominator</em> to 10 and the <em>numerator</em> to 3, meaning that he is willing to buy 3/10 of the offer amount and is willing to pay 3/10 of the consideration amount. It is important to note that changing the <em>numerator</em> and the <em>denominator</em> will not affect the validity of the order. Another important point to note is that if the <em>numerator</em> and <em>denominator</em> are not equal (as in the above case), you can no longer use the <em>fulfilOrder</em> function. Instead you will have to use the <em>fulfilAdvancedOrder</em> function.</p><h4>Partial Fills for Auctions</h4><pre>    let orderSeller: any, orderHashSeller: any, valueSeller: BigNumber;<br>    let orderBuyer: any, orderHashBuyer: any, valueBuyer: BigNumber;<br>    const nftId = randomBN();<br>    let fulfillments: any;<br>    it(&quot;Seller Creates an Order&quot;, async () =&gt; {<br>      const offerSeller = [<br>        getTestItem1155(nftId, toBN(10), toBN(10), undefined, testERC1155.address),<br>      ];<br>      const considerationSeller = [<br>        getTestItem20(50, 50, seller.address),  // Payment to seller<br>        getTestItem20(10, 10, admin_Acc.address),  // Platform charges<br><br>      ];<br>      let { order, orderHash, value } = await createOrder(<br>        seller,<br>        zoneAddr,<br>        offerSeller,<br>        considerationSeller,<br>        3, // PARTIAL_CLOSE<br>      );<br>      orderSeller = order;<br>      valueSeller = value;<br>    });<br><br>    it(&quot;Buyer_1 makes a successfull offer&quot;, async () =&gt; {<br>      await mintAndApproveERC20(buyer_1, marketplaceContract.address, 70);<br>      const offerBuyer1 = [getTestItem20(60, 60), getTestItem20(10, 10),];<br>      const considerationBuyer1 = [<br>        getTestItem1155(<br>          nftId,<br>          toBN(6),<br>          toBN(6),<br>          buyer_1.address,<br>          testERC1155.address<br>        ),<br>      ];<br>      let { order, orderHash, value } = await createOrder(<br>        buyer_1,<br>        zoneAddr,<br>        offerBuyer1,<br>        considerationBuyer1,<br>        3, // PARTIAL_CLOSE<br>      );<br>      orderBuyer = order;<br>      valueBuyer = value;<br><br>      // CHECK to see if this is the highest bid<br>      // If so, add the amount to consideration<br>      orderSeller.parameters.consideration.push(<br>        getTestItem20(10, 10,seller.address)<br>      )<br>    });<br><br>    it(&quot;Buyer_2 makes successfull offer&quot;, async () =&gt; {<br>      await mintAndApproveERC20(buyer_2, marketplaceContract.address,90);<br>      const offerBuyer2 = [getTestItem20(80, 80), getTestItem20(10, 10)];<br>      const considerationBuyer2 = [<br>        getTestItem1155(<br>          nftId,<br>          toBN(6),<br>          toBN(6),<br>          buyer_2.address,<br>          testERC1155.address<br>        ),<br>      ];<br>      let { order, orderHash, value } = await createOrder(<br>        buyer_2,<br>        zoneAddr,<br>        offerBuyer2,<br>        considerationBuyer2,<br>        3, // PARTIAL_CLOSE<br>      );<br>      orderBuyer = order;<br>      valueBuyer = value;<br><br>      // CHECK to see if this is the highest bid<br>      // If so, add the amount to consideration<br><br>      orderSeller.parameters.consideration.pop()<br>      orderSeller.parameters.consideration.push(<br>        getTestItem20(30, 30,seller.address)<br>      )<br>    });<br><br>    // Before executing the backend should make the correct match and provide the two orders to be matched<br>    it(&quot;Executes Order&quot;, async () =&gt; {<br><br>      orderSeller.denominator = 10;<br>      orderSeller.numerator = 6;<br><br>      orderBuyer.denominator = 10;<br>      orderBuyer.numerator = 6;<br><br>      await testERC1155<br>        .connect(seller)<br>        .setMintApproval(marketplaceContract.address, true);<br><br>      fulfillments = [<br>        [[[0, 0]], [[1, 0]]],   // nft<br>        [[[1, 1]], [[0, 1]]],   // platform fees<br>        [[[1, 0]], [[0, 0]]],  //floor price<br>        [[[1, 0]], [[0, 2]]],  // price increase to floor price<br>      ].map(([offerArr, considerationArr]) =&gt;<br>        toFulfillment(offerArr, considerationArr)<br>      );<br><br>      const tx = await zoneContract<br>        .connect(business_Acc)<br>        .executeMatchAdvancedOrders(<br>          marketplaceContract.address,<br>          [orderSeller, orderBuyer],<br>          fulfillments<br>        );<br>        const events = await decodeEvents(tx, [<br>          { eventName: &quot;Test1&quot;, contract: testERC1155 },<br>        ])<br>        const receipt = await tx.wait();<br><br>        assert(await testERC1155.ownerOf(nftId) == buyer_2.address, &quot;Tx did not happen&quot;)<br>    });</pre><p>Something important to note here is how the <em>numerator</em> and <em>denominator</em> of both the sellorder and the buyorder has to be adjusted according to the fraction the buyer is willing to buy. Like in the previous scenario, the function <em>executeMatchOrders</em> cannot be used. Instead the function <em>executeMatchAdvancedorders</em> has to be used.</p><h4>NOTE —</h4><p>It is important to note that using any fraction is not practical when it comes to partial fills. The consideration as well as the offer amount should be perfectly divisible by the fraction chosen. Otherwise the order will not get executed and an exception will be thrown.</p><p>Happy Coding !!</p><h4>References</h4><ol><li>Official Seaport Docs — <a href="https://docs.opensea.io/v2.0/reference/seaport-overview">https://docs.opensea.io/v2.0/reference/seaport-overview</a></li><li>Seaport Github — <a href="https://github.com/ProjectOpenSea/seaport">https://github.com/ProjectOpenSea/seaport</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd9ddb3c1f7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-do-partial-fills-with-the-seaport-protocol-fd9ddb3c1f7f">How To Do Partial Fills With The Seaport Protocol</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>