<?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"><channel><title><![CDATA[Web3 Engineering]]></title><description><![CDATA[Explore Web3 with me, Jay Nalam, on "Web3 Engineering." Learn about blockchains, smart contracts, NFTs, DeFi, cryptography, and more through tutorials and insights on decentralized technologies.]]></description><link>https://blog.jnalam.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 21 Apr 2026 19:56:18 GMT</lastBuildDate><atom:link href="https://blog.jnalam.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Perpetuals - The Crypto Derivates]]></title><description><![CDATA[Hello everyone…
Welcome back to another day of exploring Web 3 Engineering. It’s been a long since we have explored the defi world. Today let’s us getting into learning the famous crypto trading instrument that has been gaining volume recently and th...]]></description><link>https://blog.jnalam.dev/perpetuals-the-crypto-derivates</link><guid isPermaLink="true">https://blog.jnalam.dev/perpetuals-the-crypto-derivates</guid><category><![CDATA[trading, ]]></category><category><![CDATA[defi]]></category><category><![CDATA[derivatives]]></category><category><![CDATA[Cryptocurrency]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Fri, 17 Oct 2025 10:23:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1760696524782/a3e811f7-6d3a-4d01-b126-f2c2ae4eed19.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone…</p>
<p>Welcome back to another day of exploring Web 3 Engineering. It’s been a long since we have explored the defi world. Today let’s us getting into learning the famous crypto trading instrument that has been gaining volume recently and that is <strong>Perpetuals,</strong> popularly referred as <strong>Pers</strong> which are the derivatives on the cryptocurrencies.</p>
<h1 id="heading-what-are-perps">What are Perps ?</h1>
<p>Perpetuals or Perps are the derivate contracts that are usually traded in the crypto world. They work similar to the Futures Contracts on the traditional exchanges with a twist. Unlike the regular Futures contract, they don’t have an expiry date. Which means, a perps doesn’t expire and can be traded at any time in future once created.</p>
<h2 id="heading-how-do-they-work">How do they work ?</h2>
<p>In order to understand the perpetuals, we need to understand the 6 distinct features of them. They are:</p>
<ol>
<li><p><strong>No Expiry</strong> - The perpetuals have no expiry date. Which means our positions remain active as long as we are able to pay the funding rate for it and we need to maintain required margin. If our account runs out of margin, the position will be closed and settled automatically by the exchange.</p>
</li>
<li><p><strong>Funding Rate Mechanism</strong> -</p>
<ol>
<li><p>To keep the price of a perpetual contract similar to its actual asset, exchanges maintain funding rate system.</p>
</li>
<li><p>Exchanges decide the funding cycle on their own. But in general, the funding cycle is 8 hours. And at the start of this cycle, traders are required to pay premium or receive discount depending on the difference between the contract price and the spot price.</p>
</li>
<li><p>If the contract price is higher than the spot price (contract is trading at premium), long contract holders are required to pay to the short holders.</p>
</li>
<li><p>If the contract price is less than the spot price (contract is trading at discount), short contract holders are required to pay to the long holders.</p>
</li>
</ol>
</li>
<li><p><strong>Leverage and Margin</strong></p>
<ol>
<li><p>Margin is the amount of the capital we are using to create positions.</p>
</li>
<li><p>Leverage is used to place a higher value contract order with little amount of money. For example, we can place a order of 1000USD with 100 USD margin using 10x leverage.</p>
</li>
<li><p>In perpetual trading, leverage has more impact than the leverage in the traditional future contract since the crypto exchanges provide leverage up to 40x. (some provide a significant of 100x leverage depending on the asset).</p>
</li>
</ol>
</li>
<li><p><strong>Long vs Short</strong></p>
<ol>
<li><p>You hold a long position when you expect the market price of asset goes higher. And you profit from it.</p>
</li>
<li><p>You hold a short position when you expect the market price of asset goes down.</p>
</li>
</ol>
</li>
<li><p><strong>Settlement and Liquidation</strong></p>
<ol>
<li><p>Unlike the traditional futures, perpetuals don’t have a predetermined expiry and settlement date.</p>
</li>
<li><p>Profits and losses are marked to market in real time and positions can be liquidated if your margin runs too low.</p>
</li>
</ol>
</li>
</ol>
<p><strong>Market to Market Settlements</strong></p>
<ol>
<li><p>In the perpetuals world, exchanges typically settle the positions and FRM payouts at the end of their trading cycle (which is usually 00:00 UTC)</p>
</li>
<li><p>This is carried out to liquidate the positions which ran out of margin and also reflect the P&amp;L of the user in real time possibly and constrain the risk of high price movements of the assets.</p>
</li>
<li><p>Margin balance is credited or debited with this P&amp;L—so you must have enough margin to cover losses. MTM keeps your profit and loss current, preventing large carry-forward risks if prices move sharply overnight</p>
</li>
</ol>
<h2 id="heading-types-of-perpetuals-available">Types of Perpetuals available</h2>
<p>There are various types of perpetuals that are offered in the market. But we need to focus on the main 3 that are listed below.</p>
<ol>
<li><p><strong>Linear Perpetual Contracts -</strong> These are straight forward contracts on a pair and the P&amp;L calculation is also linear in fashion. For BTC / USDT perpetuals, the BTC is the asset and USDT is the quote currency in which margin and P&amp;L payouts are carried</p>
</li>
<li><p><strong>Inverse Perpetual Contracts -</strong> These type of contracts are determined in terms of base assets rather than the quote assets. In simple words, for a BTC / USDT pair, the settlement and margin is taken in BTC and not USD. If the USD price of BTC is increasing, our profit in BTC decreases and vice versa</p>
</li>
<li><p><strong>Quanto Perpetual Contracts -</strong> The contract’s P&amp;L and margin are carried out in third currency which is neither base nor quote of the contract. For example, Margin and settlement being carried in ETH for the perps on BTC / USDT. This is most popular since exchanges accept USDC / USDT usually but carry out payments in the exchange release stable coins.</p>
</li>
</ol>
<h3 id="heading-trading">Trading</h3>
<p>Since the perpetuals are not actual spot but derivates, it can only be traded using order matching. That means we have a seller and buyer for the trade and there are not DEX pools built so far. These order matching can take various forms that is specific to the exchange itself. The popular methodologies that I have seen so far are:</p>
<ol>
<li><p>Order book market matching ( price time priority)</p>
</li>
<li><p>Auction based order matching</p>
</li>
</ol>
<p>And also depending on the order flow, there are centralized and hybrid exchanges available in the market.</p>
<ol>
<li><p>Fully centralized - Order placing, Settlement, Margin infusion and also order matching takes place through a centralized app. e.g., Binance Exchange</p>
</li>
<li><p><strong>Hybrid</strong> - Order placing, position management and settlements takes place on blockchain where the actual order matching happens using off chain servers. e.g. dydx</p>
</li>
</ol>
<p>With that, we have a basic understand on the working of the perpetual contracts. Comment down if you have any questions. Thank you</p>
]]></content:encoded></item><item><title><![CDATA[A Deep Dive into Ethereum's Proof of Stake System]]></title><description><![CDATA[Hello Everyone…
Welcome to another day of exploring Web3 Engineering. It’s been a long time that Ethereum shifted from Proof-of-Work (PoW) to Proof-of-Stake (PoS) which has reduced the costs to become to run a node significantly as it now doesn’t req...]]></description><link>https://blog.jnalam.dev/a-deep-dive-into-ethereums-proof-of-stake-system</link><guid isPermaLink="true">https://blog.jnalam.dev/a-deep-dive-into-ethereums-proof-of-stake-system</guid><category><![CDATA[Ethereum]]></category><category><![CDATA[Consensus]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Tue, 08 Jul 2025 06:48:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1751957248321/7f15044c-30f3-4229-8ff8-0b0e1afd9401.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone…</p>
<p>Welcome to another day of exploring Web3 Engineering. It’s been a long time that Ethereum shifted from Proof-of-Work (PoW) to Proof-of-Stake (PoS) which has reduced the costs to become to run a node significantly as it now doesn’t require heavy hardware. Let’s explore this new procedure that provided this level of optimization to the network. So, without a further ado, let’s get started.</p>
<h2 id="heading-post-merge-architecture">Post Merge Architecture</h2>
<p>Before the merge, the entire codebase is split into Consensus and Execution layers. And when we want to run an Ethereum node, we need to run both of them.</p>
<h3 id="heading-consensus-layer">Consensus Layer</h3>
<p>The consensus layer is responsible for dealing with the consensus mechanism of the network, block producing, attestation, staking, node discovery, validator management etc. This layer has it’s own state called Beacon State which keeps the latest state of the node.</p>
<h3 id="heading-execution-layer">Execution Layer</h3>
<p>The execution layer contains the Ethereum Virtual Machine (EVM), mempool management, transaction execution, Accounts management and contract management. All the smart contracts deployed on the network are stored in this layer and this layer is responsible for handling most of the RPC endpoints such as <code>eth_getBalance</code>, <code>eth_call</code> etc.</p>
<h2 id="heading-how-does-the-consensus-work">How does the consensus Work</h2>
<p>Gasper is the consensus protocol used by Ethereum's Beacon Chain and post-merge mainnet. It is the combination of LMD-GHOST fork choice rule and Casper FFG finality gadget. This hybrid design is responsible for fast block production and finalization in a Proof-of-Stake system.</p>
<blockquote>
<p>A fork choice rule is a set of instructions that blockchain nodes use to determine the "best" or canonical chain when there are multiple block heads available. In simple terms, rules to decide which one is the latest block when we have multiple options.</p>
<p>Finality refers to the point at which the transaction made can not be revoked.</p>
</blockquote>
<h4 id="heading-time-in-ethereum-pos">Time in Ethereum PoS</h4>
<ul>
<li><p>In Ethereum consensus, the timeline is divided into equal time intervals called <strong>Slots</strong>. Each slot at the moment is equal to 12 seconds right from the Genesis block and are numbered sequentially.</p>
</li>
<li><p>Each slot should produce a maximum of 1 block and there are chances that slots will be empty without producing a block for various reasons such as no mempool transactions available, block syncing, gossip delay etc.</p>
</li>
<li><p>There is also another notation called <strong>Epoch</strong>. 1 Epoch = 32 slots (32 × 12s). These Epochs are used to finalize the state.</p>
</li>
</ul>
<h3 id="heading-consensus-process">Consensus Process</h3>
<ul>
<li><p>Whenever a new epoch begins, a set of validators are picked up to produce the blocks in it. And for this set, these validators are all responsible for all the things in this epoch.</p>
</li>
<li><p>And once, the epoch begins, in each slot, a random validator is picked up to produce the block.</p>
</li>
<li><p>Once a slot begins, the validator who is selected for the producing the block (producer), validator client will makes necessary API calls to the Execution layer and creates a new block.</p>
</li>
<li><p>Once the block generation is done, it will be forecasted via <code>libp2p gossip pub</code> to the network.</p>
</li>
<li><p>Once the new block is received at the 4th second of the slot, the remaining validators (attestors) will verify the block and attests to it.</p>
</li>
<li><p>These checks include</p>
<ul>
<li><p>Whether the block follows the schema or not</p>
</li>
<li><p>Whether the previous block hash matches with their own block head or not</p>
</li>
<li><p>Presence of any faulty transactions</p>
</li>
<li><p>Blobs validations etc.,</p>
</li>
</ul>
</li>
<li><p>If all the details matches, then they emit an attestation to the network as below</p>
</li>
</ul>
<pre><code class="lang-json">{
  <span class="hljs-attr">"aggregation_bits"</span>: <span class="hljs-string">"0x03"</span>,  <span class="hljs-comment">// 2 validators aggregated (00000011)</span>
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"slot"</span>: <span class="hljs-number">123456</span>,
    <span class="hljs-attr">"index"</span>: <span class="hljs-number">7</span>,
    <span class="hljs-attr">"beacon_block_root"</span>: <span class="hljs-string">"0xabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcd"</span>,
    <span class="hljs-attr">"source"</span>: {
      <span class="hljs-attr">"epoch"</span>: <span class="hljs-number">3857</span>,
      <span class="hljs-attr">"root"</span>: <span class="hljs-string">"0x1234512345123451234512345123451234512345123451234512345123451234"</span>
    },
    <span class="hljs-attr">"target"</span>: {
      <span class="hljs-attr">"epoch"</span>: <span class="hljs-number">3858</span>,
      <span class="hljs-attr">"root"</span>: <span class="hljs-string">"0x5678956789567895678956789567895678956789567895678956789567895678"</span>
    }
  },
  <span class="hljs-attr">"signature"</span>: <span class="hljs-string">"0xb1aa1d5c456789abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef"</span>
}
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Field</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>aggregation_bits</code></td><td>Bitfield (hex-encoded) showing which validators in the committee participated (in order). In this case, validators at index 0 and 1.</td></tr>
<tr>
<td><code>data.slot</code></td><td>The slot for which this attestation was made.</td></tr>
<tr>
<td><code>data.index</code></td><td>Committee index assigned to this attestation.</td></tr>
<tr>
<td><code>data.beacon_block_root</code></td><td>The block hash (root) the validator thinks is the chain head.</td></tr>
<tr>
<td><code>data.source</code></td><td>The last <strong>finalized</strong> checkpoint (epoch + root).</td></tr>
<tr>
<td><a target="_blank" href="http://data.target"><code>data.target</code></a></td><td>The <strong>current epoch</strong> checkpoint being attested to.</td></tr>
<tr>
<td><code>signature</code></td><td>The BLS aggregate signature of the participating validators.</td></tr>
</tbody>
</table>
</div><ul>
<li><p>If the new block is not received then they provide attestation to their current local head only which then creates multiple forks in the local chain.</p>
</li>
<li><p>During this process, there’s an another actor that is selected from the validator set and is called <strong>Aggregator.</strong></p>
</li>
<li><p>This aggregator will collect all the attestation from the validators and then announces the new blockhead that receives the most number of attestations.</p>
</li>
</ul>
<ul>
<li><p>Once all the attestations are received, the aggregator will publish the aggregated result. Then validator (producer / attestor) will update their local view of the chain with the block. And the slot ends.</p>
</li>
<li><p>While adding the block, if the local network contains multiple fork choices, then the validator uses LMD-GHOST protocol to select the fork to which it can add the new block. And also we receive the start and end epochs as part of the attestation which are used by Casper FFG.</p>
</li>
<li><p>Once the 32 slots are completed, then the Casper FFG protocol comes into play to finalize the epoch. If two consecutive checkpoints receive votes from at least two-thirds (≥66%) of validators, the earlier checkpoint is finalized. Any conflicting forks built on top of epochs earlier than the finalized one are considered invalid.Typically any block after 2 epochs is considered as finalized which is 12.8 seconds for better security.</p>
</li>
</ul>
<p>Here is a second wise breakdown of the steps followed during a slot.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Time (relative)</td><td>Event</td></tr>
</thead>
<tbody>
<tr>
<td><code>0s</code></td><td>Start of the slot — block proposer (if any) starts proposing a block.</td></tr>
<tr>
<td><code>~1s – 4s</code></td><td>Block propagation time — other nodes start receiving the proposed block.</td></tr>
<tr>
<td><code>**4s**</code></td><td><strong>Attesting validators start building and signing their attestation</strong> using the latest known head (usually the block just proposed).</td></tr>
<tr>
<td><code>4s – 8s</code></td><td>Attestations are broadcasted to the network.</td></tr>
<tr>
<td><code>8s – 12s</code></td><td>Aggregators collect and aggregate attestations, potentially included in the next slot’s block.</td></tr>
</tbody>
</table>
</div><p>That’s all for this blog. As part of this series, we will keep digging deep into the consensus layer and the protocol stack used. Thank you</p>
]]></content:encoded></item><item><title><![CDATA[Demystifying the Ethereum Transactions]]></title><description><![CDATA[Hello everyone..
Welcome to another day of exploring Web3 Engineering. Since we are diving deep into the Ethereum protocol in our series, today let us understanding the type of transactions that we can make on the network and which is better for what...]]></description><link>https://blog.jnalam.dev/demystifying-the-ethereum-transactions</link><guid isPermaLink="true">https://blog.jnalam.dev/demystifying-the-ethereum-transactions</guid><category><![CDATA[Ethereum]]></category><category><![CDATA[Blockchain]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Wed, 14 May 2025 12:37:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747226186706/257dbb9a-eb8a-437a-90db-62948a66e1c7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. Since we are diving deep into the Ethereum protocol in our series, today let us understanding the type of transactions that we can make on the network and which is better for what and when. So, without any further ado, let’s get started.</p>
<h2 id="heading-transaction">Transaction</h2>
<p>In the context of the blockchain world, a transaction is the fundamental cause of change in the state of the network which means a transaction is supposed to update the blockchain from one state to another like a finite machine.</p>
<p>As we all know, a group of transactions are picked up to form a block with the latest state, and this block is added to progress the network. And the miners get rewarded for executing the user’s transactions.</p>
<h3 id="heading-types-of-transactions">Types of Transactions</h3>
<h4 id="heading-if-this-sounds-all-simple-why-bother-having-differ-types-of-transactions-actually-what-type-of-transactions-that-users-can-make-on-the-ethereum-blockchain">If this sounds all simple, why bother having differ types of transactions ? Actually what type of transactions that users can make on the Ethereum blockchain ?</h4>
<p>The main goal of having different types of transactions is obviously to <strong>save Gas</strong>.</p>
<p>Ethereum so far, have introduced 5 different types of transactions which have different kinds of estimations to save users gas fee and to make the network more approachable.</p>
<ol>
<li><p><strong>Type 0 (Legacy)</strong></p>
<ul>
<li><p>It is the primary transaction type that Ethereum introduced to calculate the gas fee for a transaction.</p>
</li>
<li><p>The transaction schema is as follows</p>
</li>
<li><pre><code class="lang-json">    {
      <span class="hljs-attr">"from"</span>: <span class="hljs-string">"0x..."</span>,              <span class="hljs-comment">// Sender's address</span>
      <span class="hljs-attr">"to"</span>: <span class="hljs-string">"0x..."</span>,                <span class="hljs-comment">// Recipient's address (optional for contract creation)</span>
      <span class="hljs-attr">"gas"</span>: <span class="hljs-string">"0x..."</span>,               <span class="hljs-comment">// Gas limit</span>
      <span class="hljs-attr">"gasPrice"</span>: <span class="hljs-string">"0x..."</span>,          <span class="hljs-comment">// Gas price per unit (in wei)</span>
      <span class="hljs-attr">"value"</span>: <span class="hljs-string">"0x..."</span>,             <span class="hljs-comment">// Amount of Ether to send (in wei)</span>
      <span class="hljs-attr">"data"</span>: <span class="hljs-string">"0x..."</span>,              <span class="hljs-comment">// Input data (for contract interaction or deployment)</span>
      <span class="hljs-attr">"nonce"</span>: <span class="hljs-string">"0x..."</span>              <span class="hljs-comment">// Number of transactions sent from the sender's address</span>
    }
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Type 1 (EIP 2930) - Access list Transaction</strong></p>
<ul>
<li><p>Type 1 transactions are introduced with EIP 2930 in the Belin upgrade which introduced a new parameter to the request object called <code>access_list</code>.</p>
</li>
<li><p>This <code>access_list</code> contains the list of addresses and the storage keys of the data that the transaction is going to interact with, so that the EVM can prefetch them into the execution memory which reduces the gas costs while executing the transactions.</p>
</li>
<li><p>These access list is introduced warm and cold memory. Warm data is the part of the state tree which is already brought into the execution environment for the transaction while on the other hand the cold data is yet to brought into the execution space. Warm data read/write takes 100 gas while the cold storage (or first time retrieval) takes 1900 gas. With this, he access_list helps to reduce gas costs on complex transaction which uses same memory multiple times.</p>
</li>
<li><p>The transaction object of the <strong>EIP 2930</strong> transaction looks like below:</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"type"</span>: <span class="hljs-string">"0x1"</span>,                      <span class="hljs-comment">// Explicitly specify type 0x1 (optional in some clients)</span>
    <span class="hljs-attr">"from"</span>: <span class="hljs-string">"0x..."</span>,                    <span class="hljs-comment">// Sender address</span>
    <span class="hljs-attr">"to"</span>: <span class="hljs-string">"0x..."</span>,                      <span class="hljs-comment">// Recipient (null for contract creation)</span>
    <span class="hljs-attr">"gas"</span>: <span class="hljs-string">"0x..."</span>,                     <span class="hljs-comment">// Gas limit</span>
    <span class="hljs-attr">"gasPrice"</span>: <span class="hljs-string">"0x..."</span>,               <span class="hljs-comment">// Price per unit of gas (same as legacy, no base/priority fee here)</span>
    <span class="hljs-attr">"value"</span>: <span class="hljs-string">"0x..."</span>,                   <span class="hljs-comment">// Value to send in wei</span>
    <span class="hljs-attr">"data"</span>: <span class="hljs-string">"0x..."</span>,                    <span class="hljs-comment">// Input data</span>
    <span class="hljs-attr">"nonce"</span>: <span class="hljs-string">"0x..."</span>,                   <span class="hljs-comment">// Sender's nonce</span>
    <span class="hljs-attr">"chainId"</span>: <span class="hljs-string">"0x1"</span>,                   <span class="hljs-comment">// Chain ID for replay protection</span>
    <span class="hljs-attr">"accessList"</span>: [                     <span class="hljs-comment">// New in EIP-2930</span>
      {
        <span class="hljs-attr">"address"</span>: <span class="hljs-string">"0x..."</span>,            <span class="hljs-comment">// Address being accessed</span>
        <span class="hljs-attr">"storageKeys"</span>: [              <span class="hljs-comment">// Array of storage slot keys (as hex strings)</span>
          <span class="hljs-string">"0x..."</span>,
          ...
        ]
      },
      ...
    ]
  }
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Type 2 (EIP 1559) - Dynamic Fee Transaction</strong></p>
<ul>
<li><p>In the London hard, a new gas calculation scheme has been introduced that has 2 new attributes called <strong>base fee</strong> and <strong>priority fee.</strong> Base fee is the amount of the gas that we are willing to pay for the actual execution and then the priority fee is the amount we are willing pay to prioritize our execution. Higher the priority fee, faster the transaction gets executed.</p>
</li>
<li><p>The transaction object for the Type 2 transaction looks like below</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"from"</span>: <span class="hljs-string">"0x..."</span>,                   <span class="hljs-comment">// Sender address (required)</span>
    <span class="hljs-attr">"to"</span>: <span class="hljs-string">"0x..."</span>,                     <span class="hljs-comment">// Recipient address (optional for contract creation)</span>
    <span class="hljs-attr">"value"</span>: <span class="hljs-string">"0x..."</span>,                  <span class="hljs-comment">// Amount of ETH to send (in wei, hex)</span>
    <span class="hljs-attr">"gas"</span>: <span class="hljs-string">"0x..."</span>,                    <span class="hljs-comment">// Gas limit (in hex)</span>
    <span class="hljs-attr">"maxPriorityFeePerGas"</span>: <span class="hljs-string">"0x..."</span>,  <span class="hljs-comment">// Tip to the miner (in wei)</span>
    <span class="hljs-attr">"maxFeePerGas"</span>: <span class="hljs-string">"0x..."</span>,          <span class="hljs-comment">// Max total fee (tip + baseFee, in wei)</span>
    <span class="hljs-attr">"nonce"</span>: <span class="hljs-string">"0x..."</span>,                 <span class="hljs-comment">// Transaction count of the sender</span>
    <span class="hljs-attr">"data"</span>: <span class="hljs-string">"0x..."</span>,                  <span class="hljs-comment">// Optional input data</span>
    <span class="hljs-attr">"accessList"</span>: []                  <span class="hljs-comment">// Optional EIP-2930 access list</span>
  }
</code></pre>
</li>
<li><p>We can notice that there are two new parameters called <code>maxPriorityFeePerGas</code> which is the maximum gas fee we are willing to pay as priority and <code>maxFeePerGas</code> is the amount of gas we are willing to pay for execution.</p>
</li>
<li><p>And it also contains access list for the backward compatibility.</p>
</li>
</ul>
</li>
<li><p><strong>Type 3 (EIP 4844) - Blob Transactions</strong></p>
<ul>
<li><p>In the Dencun upgrade of the Ethereum blockchain, a new type of storage system is introduced to the network to store data as <strong>BLOBS</strong>. And to upload these blobs, a new transaction type is also introduced. Even though a regular day to day user won’t be using this, it is used by projects that need to store huge amounts of data onchain like layer 2 networks which provides big amounts of storage in cheaper prices.</p>
</li>
<li><p>The transaction object for the blob transaction is as follows:</p>
</li>
<li><pre><code class="lang-json">  {
    <span class="hljs-attr">"type"</span>: <span class="hljs-string">"0x3"</span>,
    <span class="hljs-attr">"chainId"</span>: <span class="hljs-string">"0x1"</span>,                          <span class="hljs-comment">// Mainnet (hex)</span>
    <span class="hljs-attr">"nonce"</span>: <span class="hljs-string">"0x0"</span>,                            <span class="hljs-comment">// Sender's transaction count</span>
    <span class="hljs-attr">"maxPriorityFeePerGas"</span>: <span class="hljs-string">"0x59682f00"</span>,      <span class="hljs-comment">// Tip to the validator</span>
    <span class="hljs-attr">"maxFeePerGas"</span>: <span class="hljs-string">"0x59682f080"</span>,            <span class="hljs-comment">// Max total fee</span>
    <span class="hljs-attr">"to"</span>: <span class="hljs-string">"0x3535353535353535353535353535353535353535"</span>,  <span class="hljs-comment">// Recipient</span>
    <span class="hljs-attr">"value"</span>: <span class="hljs-string">"0x0"</span>,                            <span class="hljs-comment">// ETH to send (in wei)</span>
    <span class="hljs-attr">"data"</span>: <span class="hljs-string">"0x"</span>,                              <span class="hljs-comment">// EVM calldata</span>
    <span class="hljs-attr">"accessList"</span>: [],                          <span class="hljs-comment">// Optional (usually empty)</span>
    <span class="hljs-attr">"maxFeePerBlobGas"</span>: <span class="hljs-string">"0x1e8480"</span>,            <span class="hljs-comment">// Maximum blob gas fee (new)</span>
    <span class="hljs-attr">"blobVersionedHashes"</span>: [                   <span class="hljs-comment">// References to blobs (KZG commitments)</span>
      <span class="hljs-string">"0x010203...32-bytes"</span>
    ]
  }
</code></pre>
</li>
<li><p>There are 2 new fields in the object. they are <code>maxFeePerBlobGas</code> and <code>blobVersionedHashes</code>. The versioned hashes contains the KZG commitment hashes of the blobs included in the transaction. And the maxFeePerBlockGas contains the maximum block gas can be spent for storing the blobs.</p>
</li>
<li><p>It is also backward compatible with EIP 1559 and EIP 2930.</p>
</li>
</ul>
</li>
<li><p><strong>Type 4 (EIP 7702) - Set Code Transactions</strong></p>
<ul>
<li><p>The Pectra upgrade has brought a new type of transactions called <strong>Set Code</strong> transactions that are used to temporarily / persistently provide smart contract behavior to a EOA address.</p>
</li>
<li><p>This is on testing phase right now and on Hoodi testnet of the Ethereum network. It contains a new attribute called <strong>authorizationList</strong> which contains the smart contract address that we want our EOA to mimic.</p>
</li>
<li><pre><code class="lang-json">  {
    <span class="hljs-attr">"type"</span>: <span class="hljs-string">"0x04"</span>,
    <span class="hljs-attr">"chainId"</span>: <span class="hljs-string">"0x1"</span>,
    <span class="hljs-attr">"nonce"</span>: <span class="hljs-string">"0x0"</span>,
    <span class="hljs-attr">"maxPriorityFeePerGas"</span>: <span class="hljs-string">"0x59682f00"</span>,
    <span class="hljs-attr">"maxFeePerGas"</span>: <span class="hljs-string">"0x59682f080"</span>,
    <span class="hljs-attr">"gas"</span>: <span class="hljs-string">"0x5208"</span>,
    <span class="hljs-attr">"to"</span>: <span class="hljs-string">"0xRecipientAddress"</span>,
    <span class="hljs-attr">"value"</span>: <span class="hljs-string">"0x0"</span>,
    <span class="hljs-attr">"data"</span>: <span class="hljs-string">"0x"</span>,
    <span class="hljs-attr">"accessList"</span>: [],
    <span class="hljs-attr">"authorizationList"</span>: [
      {
        <span class="hljs-attr">"contractCode"</span>: <span class="hljs-string">"0x6001600101..."</span>,
        <span class="hljs-attr">"yParity"</span>: <span class="hljs-string">"0x0"</span>,
        <span class="hljs-attr">"r"</span>: <span class="hljs-string">"0x..."</span>,
        <span class="hljs-attr">"s"</span>: <span class="hljs-string">"0x..."</span>
      }
    ]
  }
</code></pre>
</li>
<li><p>As we can that the EIP 7702 transaction is backward compatible with EIP 1559 transaction</p>
</li>
</ul>
</li>
</ol>
<p>There is always a possible for transaction types to emerge in the Ethereum ecosystem to optimize the transaction execution and save gas costs.</p>
<p>Please comment down if you have questions.</p>
<p>That’s all for this article. Thank you</p>
]]></content:encoded></item><item><title><![CDATA[Ethereum Protocol]]></title><description><![CDATA[Hello everyone..
Welcome to another day in exploring Web3 Engineering. In today’s article, rather than focusing on dApps and ERC standards, lets focus on the node that runs our beloved Ethereum network. Let’s start with the layered architecture and d...]]></description><link>https://blog.jnalam.dev/ethereum-protocol</link><guid isPermaLink="true">https://blog.jnalam.dev/ethereum-protocol</guid><category><![CDATA[Ethereum]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Mon, 03 Mar 2025 09:54:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1740995202331/5777f931-c3b8-4cfa-8a39-744483d58419.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day in exploring Web3 Engineering. In today’s article, rather than focusing on dApps and ERC standards, lets focus on the node that runs our beloved Ethereum network. Let’s start with the layered architecture and different communication protocols of the Ethereum node. So without any further ado, let’s get started.</p>
<h2 id="heading-ethereum-clients">Ethereum Clients</h2>
<p>Before the Ethereum merge and shift to Proof-of-Stake consensus, it followed monolithic architecture. Which means the entire codebase is responsible for all the features and all the components are tightly coupled with each other. After the merge, the node is divided into layers and each other is loosely coupled and it made language agnostic to support various clients written in different programming languages.</p>
<h3 id="heading-layers-of-clients">Layers of Clients</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740985804541/359462e1-2f15-412f-b17b-9224ee7fa83e.png" alt class="image--center mx-auto" /></p>
<p>The Eth node is divided into 2 layers. Each state consists their own peer-to-peer network for their execution and also maintain a separate state depending on their needs.</p>
<ol>
<li><p>Execution Layer (EL)</p>
</li>
<li><p>Consensus Layer (CL)</p>
</li>
</ol>
<h4 id="heading-execution-layer">Execution Layer</h4>
<ul>
<li><p>The EL is responsible for executing all the transactions, providing the RPC methods, communication with the dApps, smart contract etc.</p>
</li>
<li><p>The p2p network in the EL is responsible for validating the transactions and producing the new block.</p>
</li>
<li><p>The client RPC calls made to the node are executed here, providing the read and write calls of the Ethereum state.</p>
</li>
<li><p>Management of the Mempooletc.</p>
</li>
<li><p>The architecture of the EL depends on it’s individual implementation.</p>
</li>
</ul>
<h4 id="heading-consensus-layer-cl">Consensus Layer (CL)</h4>
<ul>
<li><p>The CL is responsible for maintaining the overall consensus of the blockchain network.</p>
</li>
<li><p>Management of the Validator nodes, slashing, staking and other validator based actions</p>
</li>
<li><p>Block production and proposal of new block producers</p>
</li>
<li><p>Block attestation and finality etc.,</p>
</li>
</ul>
<h3 id="heading-key-protocols">Key Protocols</h3>
<p>Ethereum node uses multiple communication protocols to maintain the decentralization and censorship resistance in the network along with the unrestricted rules for the node operators to join and leave the network whenever possible. For example</p>
<ol>
<li><p><strong>Gossip Protocol</strong> - Gossip protocol is used in both the consensus and execution layers for syncing the state between the nodes in the network.</p>
</li>
<li><p><strong>LibP2P (Networking Protocol) -</strong> is used in the consensus layer for discovering the node discovery and the peer-to-peer communication between the network.</p>
</li>
<li><p><strong>DevP2P (Ethereum Wire Protocol) -</strong> is used in the execution layer for the peer-to-peer communication in order to maintain the state sync, block propagation and transaction gossiping between the network.</p>
</li>
</ol>
<p>Apart from the communication protocols, Ethereum also uses various data serializations and cryptographic algorithms which we will discuss in our upcoming articles.</p>
<p>That’s all for the day. Comment down your questions</p>
]]></content:encoded></item><item><title><![CDATA[ERC 6909 - Minimal Multi-Token Interface]]></title><description><![CDATA[Hello Everyone..
Welcome to another day of exploring Web3 Engineering. With blockchain taking new steps towards the decentralized finance (DeFi) and blooming with a new token standard or extension everyday, today we have come across a new one called ...]]></description><link>https://blog.jnalam.dev/erc-6909-minimal-multi-token-interface</link><guid isPermaLink="true">https://blog.jnalam.dev/erc-6909-minimal-multi-token-interface</guid><category><![CDATA[Ethereum]]></category><category><![CDATA[Cryptocurrency]]></category><category><![CDATA[Solidity]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Thu, 13 Feb 2025 09:09:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739437687942/ab61513d-286f-4ac5-be75-9f68af59afcc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. With blockchain taking new steps towards the decentralized finance (DeFi) and blooming with a new token standard or extension everyday, today we have come across a new one called Minimal Multi-token standard interface. With Uniswap V4 using it in their new contracts, the significance of understanding it has increased. So, without any further ado, let’s get started.</p>
<h2 id="heading-what-is-erc-6909">What is ERC 6909 ?</h2>
<p>ERC 6909, in simple terms, is an improvement to the already popular ERC1155: Multi-token standard. By decreasing the overhead of ERC1155 implementation and some modifications to the features, the applications of using Multi-token standard have increased. First let us recall the original ERC1155 token standard and then let us compare the differences between.</p>
<h3 id="heading-erc1155-multi-token-standard">ERC1155: Multi-token standard</h3>
<p>Here we have the interface for the <strong>ERC1155</strong> token standard.</p>
<pre><code class="lang-solidity"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ERC1155</span> <span class="hljs-comment">/* is ERC165 */</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">TransferSingle</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _operator, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _from, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _to, <span class="hljs-keyword">uint256</span> _id, <span class="hljs-keyword">uint256</span> _value</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">TransferBatch</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _operator, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _from, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _to, <span class="hljs-keyword">uint256</span>[] _ids, <span class="hljs-keyword">uint256</span>[] _values</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">ApprovalForAll</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _owner, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> _operator, <span class="hljs-keyword">bool</span> _approved</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">URI</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> _value, <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">indexed</span> _id</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">safeTransferFrom</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _from, <span class="hljs-keyword">address</span> _to, <span class="hljs-keyword">uint256</span> _id, <span class="hljs-keyword">uint256</span> _value, <span class="hljs-keyword">bytes</span> <span class="hljs-keyword">calldata</span> _data</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span></span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">safeBatchTransferFrom</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _from, <span class="hljs-keyword">address</span> _to, <span class="hljs-keyword">uint256</span>[] <span class="hljs-keyword">calldata</span> _ids, <span class="hljs-keyword">uint256</span>[] <span class="hljs-keyword">calldata</span> _values, <span class="hljs-keyword">bytes</span> <span class="hljs-keyword">calldata</span> _data</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span></span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">balanceOf</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _owner, <span class="hljs-keyword">uint256</span> _id</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint256</span></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">balanceOfBatch</span>(<span class="hljs-params"><span class="hljs-keyword">address</span>[] <span class="hljs-keyword">calldata</span> _owners, <span class="hljs-keyword">uint256</span>[] <span class="hljs-keyword">calldata</span> _ids</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint256</span>[] <span class="hljs-keyword">memory</span></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setApprovalForAll</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _operator, <span class="hljs-keyword">bool</span> _approved</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span></span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isApprovedForAll</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _owner, <span class="hljs-keyword">address</span> _operator</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>;
}
</code></pre>
<p>Here is the interface for the <strong>ERC1155Receiver</strong> contract.</p>
<pre><code class="lang-solidity"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ERC1155TokenReceiver</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onERC1155Received</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _operator, <span class="hljs-keyword">address</span> _from, <span class="hljs-keyword">uint256</span> _id, <span class="hljs-keyword">uint256</span> _value, <span class="hljs-keyword">bytes</span> <span class="hljs-keyword">calldata</span> _data</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">bytes4</span></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onERC1155BatchReceived</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _operator, <span class="hljs-keyword">address</span> _from, <span class="hljs-keyword">uint256</span>[] <span class="hljs-keyword">calldata</span> _ids, <span class="hljs-keyword">uint256</span>[] <span class="hljs-keyword">calldata</span> _values, <span class="hljs-keyword">bytes</span> <span class="hljs-keyword">calldata</span> _data</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">bytes4</span></span>)</span>;       
}
</code></pre>
<p><strong>Functionalities</strong></p>
<p><strong>ERC1155</strong></p>
<ul>
<li><p><strong>safeTransferFrom</strong> - To transfer tokens from one user to another user of the given token id.</p>
<ul>
<li><p>If the function is called by a user to transfer owned tokens, enough balance is expected</p>
</li>
<li><p>If the function is called by a third party account to transfer our tokens, the operator must be approved prior to the call.</p>
</li>
<li><p>If the receiver of the tokens is a contract, onERC1155Received will be called on the receiver contract</p>
</li>
</ul>
</li>
<li><p><strong>safeBatchTransfer -</strong> same as a safeTokenTransfer, but can transfer multiple tokens in a single transaction.</p>
<ul>
<li><p>The caller needs to specify the array of token ids to transfer</p>
</li>
<li><p>Same as safeTransferFrom, if the function is called by an operator, the prior approval is necessary.</p>
</li>
<li><p>If the receiver of the tokens is a contract, onERC1155BatchReceived will be called on the receiver contract</p>
</li>
</ul>
</li>
<li><p><strong>balanceOf</strong> - to check the balance of the given user for the given token id.</p>
</li>
<li><p><strong>balanceOfBatch -</strong> to check the balance of users for the array of given token Ids.</p>
</li>
<li><p><strong>setApprovalForAll -</strong> to grant operator approval for a given user. It sets approval for unlimited balance of the user on all the token Ids.</p>
</li>
</ul>
<p><strong>ERC1155Receiver</strong></p>
<ul>
<li><p><strong>onERC1155Received -</strong> A custom hook function that must be implemented by the receiver contract that gets triggered after transferring the tokens using <code>safeTransfer</code> on ERC1155 and it should return <code>bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))</code> signaling the successful transfer of the tokens.</p>
</li>
<li><p><strong>onERC1155BatchReceived -</strong> A custom hook function that must be implemented by the receiver contract that gets triggered after transferring the tokens using <code>safeBatchTransfer</code> on ERC1155 and it should return <code>bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))</code> signaling the successful batch transfer of the tokens.</p>
</li>
</ul>
<h3 id="heading-issues-with-erc-1155">Issues with ERC 1155</h3>
<ul>
<li><p>If we look closely, there is no standard transfer and transferFrom functionalities in the standard. and there are only safe transfer functions. Even though they are safe, they add an unnecessary overhead on the token transfer increasing the gas fees.</p>
</li>
<li><p>There is only one global operator approval for all the tokens of a given user which is limiting in some situations where a user needs to specify either multiple operators for a given token or a separate operator for each token Id.</p>
</li>
</ul>
<p>ERC6909 addresses these issues by removing the transfer checks (splitting them to extensions) on the transfer and introducing multiple operators for a given user. Have a look at the ERC6909 interface below.</p>
<pre><code class="lang-solidity"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ERC6909</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">error</span> <span class="hljs-title">InsufficientBalance</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> owner, <span class="hljs-keyword">uint256</span> id</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">error</span> <span class="hljs-title">InsufficientPermission</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> spender, <span class="hljs-keyword">uint256</span> id</span>)</span>;

    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">Transfer</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> caller, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> sender, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> receiver, <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">indexed</span> id, <span class="hljs-keyword">uint256</span> amount</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">OperatorSet</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> owner, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> spender, <span class="hljs-keyword">bool</span> approved</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">event</span> <span class="hljs-title">Approval</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> owner, <span class="hljs-keyword">address</span> <span class="hljs-keyword">indexed</span> spender, <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">indexed</span> id, <span class="hljs-keyword">uint256</span> amount</span>)</span>;

    <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> owner <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">uint256</span> id <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">uint256</span> amount)) <span class="hljs-keyword">public</span> balanceOf;
    <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> owner <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> spender <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">uint256</span> id <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">uint256</span> amount))) <span class="hljs-keyword">public</span> allowance;
    <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> owner <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> spender <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-keyword">bool</span>)) <span class="hljs-keyword">public</span> isOperator;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transfer</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> receiver, <span class="hljs-keyword">uint256</span> id, <span class="hljs-keyword">uint256</span> amount</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transferFrom</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> sender, <span class="hljs-keyword">address</span> receiver, <span class="hljs-keyword">uint256</span> id, <span class="hljs-keyword">uint256</span> amount</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">approve</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> spender, <span class="hljs-keyword">uint256</span> id, <span class="hljs-keyword">uint256</span> amount</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setOperator</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> spender, <span class="hljs-keyword">bool</span> approved</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">supportsInterface</span>(<span class="hljs-params"><span class="hljs-keyword">bytes4</span> interfaceId</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">pure</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span> supported</span>)</span>;

    <span class="hljs-comment">// ============= internal ===================</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_mint</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> receiver, <span class="hljs-keyword">uint256</span> id, <span class="hljs-keyword">uint256</span> amount</span>) <span class="hljs-title"><span class="hljs-keyword">internal</span></span></span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_burn</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> sender, <span class="hljs-keyword">uint256</span> id, <span class="hljs-keyword">uint256</span> amount</span>) <span class="hljs-title"><span class="hljs-keyword">internal</span></span></span>;
}
</code></pre>
<p>The ERC6909 introduces a new role called <code>Operators</code> that are specific to a user. Each user can set multiple operators for their tokens and the operators have approval to the unlimited balance of the user on all of the token Ids.</p>
<p><strong>Functionalities</strong></p>
<ul>
<li><p><strong>approve -</strong> To grant approval for a spender for a given amount of tokens of give token Id.</p>
</li>
<li><p><strong>transfer</strong> - To transfer given amount of tokens of the given token id to the receiver. Should be called to transfer owned tokens.</p>
</li>
<li><p><strong>transferFrom</strong> - To transfer given amount of tokens of the given token id from the sender to the receiver. Should be called to transfer third party (sender) tokens and also a prior approval is needed on the amount of the token Id tokens. If it is called by an operator, no approval call is needed, since they already have approval to all of the balance of them.</p>
</li>
<li><p><strong>setOperator -</strong> To set or reset an operator for a the caller. Once the operator role is granted, operator would have access to all of their funds.</p>
</li>
</ul>
<p>With these additions, ERC6909 have overcome the inefficiencies that ERC1155 is lacking. And with these new features, ERC6909 plays a crucial role in the Uniswap V4, which we will explore in our upcoming blogs.</p>
<p>That’s all for the day. Feel free to comment down your questions.</p>
]]></content:encoded></item><item><title><![CDATA[CryptoTokens]]></title><description><![CDATA[Hello everyone..
Welcome to another day of exploring Web3 Engineering.
In our cyrpto / blockchain world, we have definitely came across various different kinds of tokens. Some talk about stable coins, some keep hyping about the meme coins, and some h...]]></description><link>https://blog.jnalam.dev/cryptotokens</link><guid isPermaLink="true">https://blog.jnalam.dev/cryptotokens</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Cryptocurrency]]></category><category><![CDATA[RWA Tokenization ]]></category><category><![CDATA[memecoins]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Wed, 22 Jan 2025 11:07:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737543935526/9f6d0ede-3f85-4926-8f73-45262978524c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering.</p>
<p>In our cyrpto / blockchain world, we have definitely came across various different kinds of tokens. Some talk about stable coins, some keep hyping about the meme coins, and some hold governance tokens. Being a blockchain / crypto enthusiast, one must understand the differences between these, no matter whether they are from a technical background, financial background or simply just exploring. So, in today’s blog let us debunk these token types and understand what and where are they used.</p>
<h2 id="heading-classification-of-tokens">Classification of Tokens</h2>
<h3 id="heading-technical-classification">Technical Classification</h3>
<p>There are basically 3 types of tokens when we classify them on the technical front</p>
<ol>
<li><p><strong>Fungible Tokens -</strong> Fungible tokens are interchangeable among them without losing value. Which means just the real world money, no matter which Rs. 100 /- we have, we can exchange it with another Rs. 100/- note without losing any value since each token worth the same value.</p>
</li>
<li><p><strong>Non - Fungible Tokens -</strong> NFTs are the tokens that are not interchangeable without losing value. Which means just the art collections, even though all the paintings are from the same artist, no two paintings are same and they may or may not worth same value.</p>
</li>
<li><p><strong>Semi - Fungible Tokens -</strong> Semi Fungible tokens combines both the properties of Fungible and NFTs. They operate fungible with some conditions and NFTs otherwise. We can understand them as gaming assets. Even though all weapons are from the same game, weapons are of different kind and also there is one copy of each weapon per user.</p>
</li>
</ol>
<h3 id="heading-use-case-classification">Use case classification</h3>
<p>Based on the use case and requirements, one of the above 3 kinds of tokens can be used to implement them. There are various types of tokens / coins available in the market. Here are some of the popular or must know types</p>
<ol>
<li><p><strong>Native Tokens -</strong> Native tokens are the tokens that are used to pay for the gas to make transactions on the given network. They can be only be created when the blockchain network is started and there is only one native token per network mostly and they are fungible in nature.</p>
<ul>
<li><strong>Example</strong>: Ethereum (ETH), Bitcoin (BTC), Sui(SUI) etc.</li>
</ul>
</li>
<li><p><strong>Wrapped Tokens -</strong> These are the tokens that are developed as a wrapper for another token to provide additional functionality for the original tokens. These are always mined and burned on demand by depositing and withdrawing the original token from into the wrapped token smart contract.</p>
<ul>
<li><strong>Example</strong>: Wrapped Ethereum (WETH), Wrapped Bitcoin (WBTC) are tokens developed to add ERC20 functionality for the native tokens.</li>
</ul>
</li>
<li><p><strong>Stable Coins -</strong> Stable coins are usually fungible tokens that are pegged to a real world asset to maintain stability in the exchange price of the token.</p>
<ul>
<li><strong>Example</strong>: USDC and EURC are stable coins launched by Circle.com which are pegged to US Dollar and European EURO respectively.</li>
</ul>
</li>
<li><p><strong>Governance Tokens -</strong> Governance tokens are used to represent the voting power of user in the election (decision making) process of a Decentralized Autonomous Organization (DAO). The token holders will be able to propose, vote and accept or reject changes that for the ecosystem and the voting power is decided of the user is decided by the quality / quantity of the tokens held by them.</p>
<ul>
<li><strong>Example</strong>: Uniswap (UNI) Token is the governance token for the Uniswap protocol.</li>
</ul>
</li>
<li><p><strong>Meme Coins -</strong> These are the tokens that are used to represent a trending meme or inspired from a famous internet meme. They often start as side projects but gain significant popularity and value due to social media trends, community-driven hype, and celebrity endorsements. They typically don’t have any goal or road map to them.</p>
<ul>
<li><strong>Example</strong>: Dogecoin, Shiba Inu are one of the popular memecoins in the crypto market.</li>
</ul>
</li>
<li><p><strong>RWA Tokens -</strong> Real World Asset Tokens or RWA Tokens are used to represent real world entities (typically real estate). The token holders are considered as the owners of the assets and price is derived based on the real world assets.</p>
<ul>
<li><strong>Example</strong>: Centrifuge tokenises various real-world assets, including business invoices and carbon credits, allowing these assets to be used as collateral in DeFi lending pools.</li>
</ul>
</li>
</ol>
<p>There are more to this classification such as utility tokens, tax tokens, AI agents etc. Day by day, we are able to observe more and more use cases are being discovered to adopt blockchain into our day to day life and the emerging opportunities are increasing the efficiency and the ease-fullness for the organizations to operate.</p>
<p>What are the other use cases do you think that the emerging blockchain world can offer ? Comment down below.</p>
<p>That’s all for the day. Feel free to comment down your questions.</p>
]]></content:encoded></item><item><title><![CDATA[Anatomy of Blockchain]]></title><description><![CDATA[Hello everyone..
Welcome to another day of exploring Web3 Engineering. Let’s dig into basics of the blockchain today and understand it’s anatomy in general. In this blog, we’ll dive into nodes and its types and their responsibilities and use cases. S...]]></description><link>https://blog.jnalam.dev/anatomy-of-blockchain</link><guid isPermaLink="true">https://blog.jnalam.dev/anatomy-of-blockchain</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Ethereum]]></category><category><![CDATA[Bitcoin]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Tue, 26 Nov 2024 09:37:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732613739856/fc4e5a39-90aa-4ea3-9a6d-a90cd5a7add2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. Let’s dig into basics of the blockchain today and understand it’s anatomy in general. In this blog, we’ll dive into nodes and its types and their responsibilities and use cases. So, without any further ado, let’s get started.</p>
<h2 id="heading-whats-a-blockchain-node">What’s a blockchain node ?</h2>
<p>A blockchain node is the vital component of the network that acts as the communication endpoint for the network. The nodes are responsible for maintaining the network’s decentralization and security. These are responsible for performing various tasks such as transaction validation, state broadcasting, data storage etc.,</p>
<h3 id="heading-key-responsibilities">Key responsibilities</h3>
<ol>
<li><p><strong>Transaction Validation:</strong> Nodes are responsible for validating transactions such as message formatting, gas payments (if needed), data validation etc. They ensure the incoming transactions follows the rules specified by the blockchain.</p>
</li>
<li><p><strong>Block Verification:</strong> Nodes perform validations on the new blocks that are added to the network. They also ensure the consensus conformity of the new block.</p>
</li>
<li><p><strong>Data Storage:</strong> Depending on the network of the node, they store the blockchain data. If it is a full node, it is responsible to store the entire blockchain, and if it is a light node, it will store the latest copy of the blockchain state.</p>
</li>
<li><p><strong>Network Security:</strong> Nodes ensure the blockchain integrity by maintaining a distributed ledger across the network to cross verify the state.</p>
</li>
</ol>
<h3 id="heading-type-of-nodes">Type of nodes</h3>
<p>Depending on the blockchain network, there are different kinds of nodes available. But in general, there are 4 different kinds of blockchain nodes available. They are:</p>
<ul>
<li><p><strong>Full node:</strong> A full node contains the entire blockchain data and can validate an incoming transaction independently since it contains the entire blockchain data. To run a full node, the storage requirements are usually quite high.</p>
</li>
<li><p><strong>Light node:</strong> A light node only store a part of the blockchain data, usually the latest state. They rely on the full nodes for transaction validation.</p>
</li>
<li><p><strong>Archive node:</strong> An archive node stores the historic data of the blockchain and doesn’t actively participate in the transaction validation.</p>
</li>
<li><p><strong>Validator node:</strong> A validator node participates in the consensus algorithm of the blockchain such Proof-of-Stake , Proof-of-Work etc,.</p>
</li>
</ul>
<p>Depending on the blockchain network and/or consensus algorithm, there are some network specific nodes as well. Some of them are:</p>
<h4 id="heading-bitcoin">Bitcoin</h4>
<ul>
<li><strong>Miner node:</strong> A miner node is a full node which is also responsible for adding new blocks to the network. They participate in the Proof-of-Work (PoW) to solve the complex puzzles in order to generate new blocks.</li>
</ul>
<h4 id="heading-ethereum">Ethereum</h4>
<ul>
<li><p><strong>Full node:</strong> An Ethereum full node is not only responsible for storing entire blockchain and also responsible for transaction mining and new block generation. A full node after elected by the PoS election adds the newly generated block to the network.</p>
</li>
<li><p><strong>Validator node:</strong> A validator is added in Ethereum 2.0 update where they are responsible for transaction confirmations, block validations and also staking rewards exchange.</p>
</li>
</ul>
<h4 id="heading-polkadot">Polkadot</h4>
<ul>
<li><p><strong>Validator node:</strong> Polkadot utilizes a hybrid consensus algorithm which includes Nominated Proof-of-Stake (NPoS) for relay chain. Validator nodes are responsible for Relay Chains block validation and consensus process.</p>
</li>
<li><p><strong>Collator node:</strong> Collator nodes are the block producers for the parachains of the network. Parachain is an individual chain connected to the Main chain (or Relay chain) of the network. They play a critical role in maintaining the scalability of the system.</p>
</li>
</ul>
<h4 id="heading-tezos">Tezos</h4>
<ul>
<li><strong>Baker node:</strong> In tezos network, the baker nodes are responsible for network consensus and block creation. These nodes play a key role in maintaining the Liquid Proof-of-Stake (LPoS) consensus over the network.</li>
</ul>
<p>Depending on the consensus protocol, we can observe full nodes with more responsibilities or new type of nodes with different responsibilities.</p>
<p>That’s all for the day. Feel free to comment down your questions.</p>
]]></content:encoded></item><item><title><![CDATA[Remote Procedure Call]]></title><description><![CDATA[Hello everyone..
Welcome to another day of exploring Web3 Engineering.
We have been talking about blockchain and developing smart contracts on them for a while and also writing scripts on how to interact with the blockchain for a while. But have you ...]]></description><link>https://blog.jnalam.dev/remote-procedure-call</link><guid isPermaLink="true">https://blog.jnalam.dev/remote-procedure-call</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[RPC]]></category><category><![CDATA[Communication Protocols ]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Thu, 07 Nov 2024 10:07:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730973858787/b357b9f8-3141-43a0-b97d-8e409132c50d.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering.</p>
<p>We have been talking about blockchain and developing smart contracts on them for a while and also writing scripts on how to interact with the blockchain for a while. But have you ever wondered on how actually your script communicates with the blockchain ?? Of course it uses RPC .. Duh..!! But what is this RPC ? How is it different from other communication protocols ? Where it is used ? So without any further ado, let’s get answers to these questions.</p>
<h2 id="heading-remote-procedure-call-aka-rpc-protocol">Remote Procedure Call aka RPC protocol</h2>
<p>Remote Procedure Call (RPC) protocol is a communication protocol that allows a service (or an entity) to invoke a certain procedure on a remote service as if it is a local procedure.</p>
<p>In common language, it is a protocol that allows you to call a function on a different server as a local function in the code. For example, we are calling <code>eth_getBalance</code> function in our local javascript file as a local function but it is implemented on the blockchain node provided by our RPC provider.</p>
<h4 id="heading-structure-of-rpc-method">Structure of RPC method</h4>
<p>An rpc request contains 4 parameters. The version of the rpc, method name to be called, params if any, and finally a request identifier id. The structure looks as follows</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"jsonrpc"</span>: <span class="hljs-string">"2.0"</span>,
  <span class="hljs-string">"method"</span>: <span class="hljs-string">"getBlock"</span>,
  <span class="hljs-string">"params"</span>: [<span class="hljs-number">1234</span>],
  <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>
}
</code></pre>
<p>We can also add any metadata if needed for our procedure.</p>
<h3 id="heading-how-is-it-different-from-other">How is it different from Other</h3>
<p>Other communication protocols like REST-API follows resource based design and uses URLs to provide different functionalities. Whereas, the RPC is designed around the procedures rather than resources.</p>
<p>For example, if we want to get all the users using REST - API, the code looks like this</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> url = <span class="hljs-string">'https://example.com/users/getUsers'</span>;
<span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>, <span class="hljs-comment">// RESTful GET request</span>
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
    },
});
<span class="hljs-keyword">if</span> (!response.ok) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Error: <span class="hljs-subst">${response.statusText}</span>`</span>);
}
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
</code></pre>
<p>But if we want to implement the same thing using RPC methods, it would like this</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> url = <span class="hljs-string">'https://example.com/rpc'</span>; <span class="hljs-comment">// The endpoint for RPC requests</span>
<span class="hljs-keyword">const</span> rpcRequest = {
    <span class="hljs-attr">jsonrpc</span>: <span class="hljs-string">'2.0'</span>,
    <span class="hljs-attr">method</span>: <span class="hljs-string">'getUsers'</span>, <span class="hljs-comment">// The remote procedure call method</span>
    <span class="hljs-attr">params</span>: [], <span class="hljs-comment">// Parameters required for the method (empty in this case)</span>
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-comment">// Request ID</span>
};
<span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>, <span class="hljs-comment">// POST request for RPC</span>
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
    },
    <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(rpcRequest), <span class="hljs-comment">// Sending the request body</span>
});
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
</code></pre>
<h4 id="heading-where-it-is-used">Where it is used</h4>
<p>RPC is mainly used for communication between micro services and distributed systems. It is also used in systems where a real time communication is needed such as IoT, blockchain and smart contracts, online multiplayer games etc.</p>
<h4 id="heading-what-are-the-popular-implementations-of-rpc">What are the popular implementations of RPC:</h4>
<p>Due to its flexible architecture and compatibility with different formats, RPC is implemented to support various data formats. Such as</p>
<ul>
<li><p><strong>gRPC -</strong> The gRPC is developed by Google where RPC is implemented to transport binary data for communication between entities which is mainly used in cloud-native applications</p>
</li>
<li><p><strong>JSON-RPC</strong> : The JSON-RPC format transport data using JSON format widely used in blockchain communication</p>
</li>
<li><p><strong>XML-RPC:</strong> The XML data formatted RPC calls are used in older system where XML format is used data exchange.</p>
</li>
<li><p><strong>SOAP</strong>: While more of a web service protocol, SOAP can be considered an RPC mechanism, as it invokes remote operations with an XML-based request and response.</p>
</li>
</ul>
<p>Along with the data format used, we can also use RPC with different transfer protocols such as https, web sockets etc</p>
<p>That’s all for today.<br />Feel free to comment down your questions and don’t forget to subscribe to the newsletter.</p>
]]></content:encoded></item><item><title><![CDATA[Blockchain Interoperability and Cross-Chain Solutions]]></title><description><![CDATA[Hello Everyone..
Welcome to another day of exploring Web3 Engineering. Today let’s see why we need the blockchain interoperability and where the future of the decentralized applications (dApps) head. So without any further ado, let’s get started.
Int...]]></description><link>https://blog.jnalam.dev/blockchain-interoperability-and-cross-chain-solutions</link><guid isPermaLink="true">https://blog.jnalam.dev/blockchain-interoperability-and-cross-chain-solutions</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[interoperablity in Blockchain]]></category><category><![CDATA[Ethereum]]></category><category><![CDATA[Bitcoin]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Tue, 15 Oct 2024 08:31:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728981008401/74e527d9-c5a0-4c3e-baa2-f7a964956e08.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. Today let’s see why we need the blockchain interoperability and where the future of the decentralized applications (dApps) head. So without any further ado, let’s get started.</p>
<h4 id="heading-introduction"><strong>Introduction:</strong></h4>
<p>Now-a-days with the fast growing of DeFi usage and the applications offered by them, it is safe to assume that blockchain has become a critical component in the progress. As we have different blockchains emerging day by day offering their own specialties to both developers and users, it has become difficult to stick to one platform for all their uses or switch different platforms for usability.</p>
<p>For example, I can’t use the stable coins I have on one Network A to stake on a dApp on Network B that is offering me more APY. This is just one of the scenarios where users are facing difficulties using their assets to full extent.</p>
<p>Cross-chain solutions aim to address these challenges by enabling seamless communication and interaction between different blockchain networks.</p>
<h3 id="heading-why-interoperability-matters-in-blockchain"><strong>Why Interoperability Matters in Blockchain</strong></h3>
<p>Like in the above example, Currently, many DeFi applications exist in isolated ecosystems, each with its own unique protocols, assets, and consensus mechanisms. With the lack of interoperability, users are unable to use their assets across different blockchains and are forced to use centralized exchanges taking away the core decentralization aspect of the Decentralized Apps.</p>
<h4 id="heading-what-does-interoperability-provide"><strong>What does Interoperability provide</strong> ?</h4>
<p>Interoperability in blockchain allows for:</p>
<ul>
<li><p><strong>Better Liquidity:</strong> Cross-chain bridges allows the liquidity to flow between different blockchains, preventing it to be stuck on one network.</p>
</li>
<li><p><strong>Enhanced User Experience:</strong> With cross-chain dApps, users can interact with applications from different blockchain under one common interface with switching between multiple wallets or platforms.</p>
</li>
<li><p><strong>Innovation in DeFi Protocols:</strong> Multi-chain applications can integrate new features such as cross-chain lending, yield farming, and decentralized exchanges (DEXs) that pool liquidity from different blockchains.</p>
</li>
</ul>
<h3 id="heading-popular-cross-chain-solutions"><strong>Popular Cross-Chain Solutions:</strong></h3>
<ol>
<li><p><strong>Cosmos IBC (Inter-Blockchain Communication):</strong></p>
<ul>
<li><p>Cosmos is commonly called as <strong>Internet-of-blockchains.</strong></p>
</li>
<li><p>IBC protocol allows transfer of assets and data between different blockchain such as Ethereum, Solana etc.</p>
</li>
<li><p>It uses Hubs and Zones to provide communication between networks without needing a centralized exchange or third party apps.</p>
</li>
</ul>
</li>
<li><p><strong>Polkadot Parachains:</strong></p>
<ul>
<li><p>Polkadot is another popular cross-chain communication protocol which provides communication using <strong>Parachains</strong>.</p>
</li>
<li><p>Parachains are independent and specialized blockchains that run in parallel while being connected to the central <strong>Relay Chain.</strong></p>
</li>
<li><p>These parachains communicate wiht each other using <strong>Cross-Chain Message Passing (XCMP)</strong> through the Polkadot Relay chain to transfer assets and data between them.</p>
</li>
</ul>
</li>
<li><p><strong>Axelar Network:</strong></p>
<ul>
<li><p>Axelar network provides cross-chain communication with the help of <strong>interoperable smart contracts</strong>.</p>
</li>
<li><p>It is right now compatible with <strong>Ethereum, Avalanche, Cosmos</strong>, and other major ecosystems.</p>
</li>
</ul>
</li>
<li><p><strong>Chainlink CCIP (Cross-Chain Interoperability Protocol):</strong></p>
<ul>
<li><p>Chainlink’s CCIP is designed to create a universal standard for sending data, messages, and tokens across blockchains.</p>
</li>
<li><p>With the integration of chainlink oracles, CCP is ideal for DeFi protocols and security essential applications</p>
</li>
</ul>
</li>
</ol>
<h4 id="heading-challenges-in-blockchain-interoperability"><strong>Challenges in Blockchain Interoperability:</strong></h4>
<p>On one hand, we have so many pros by using the cross-chain communication, but on the other hand we have some cons too. They are</p>
<ul>
<li><p><strong>Security Risks :</strong> Bridging dApps between multiple chains will bring in potential risks like the chance of malicious actors exploiting the weaknesses on the communication protocol is high.</p>
</li>
<li><p><strong>Consensus Differences :</strong> As different blockchains work with different consensus algorithms, bad actors can take advantages in the differentiating block rates or synchronization etc.</p>
</li>
<li><p><strong>Liquidity Fragmentation:</strong> Even with interoperability, liquidity can become fragmented across chains, making it harder to aggregate liquidity pools effectively.</p>
</li>
</ul>
<h4 id="heading-the-future-of-cross-chain-defi"><strong>The Future of Cross-Chain DeFi:</strong></h4>
<p>Interoperability protocols are set to play a key role in the next phase of DeFi’s growth. As protocols like <strong>Cosmos IBC</strong>, <strong>Axelar</strong>, and <strong>Chainlink CCIP</strong> continue to evolve, developers will be able to create more <strong>composable dApps</strong> that work across multiple chains. In the near future, we can expect to see:</p>
<ul>
<li><p><strong>Cross-Chain Yield Farming:</strong> Where users can stake assets on one blockchain and earn rewards on another.</p>
</li>
<li><p><strong>Interoperable Lending Protocols:</strong> Enabling users to borrow assets from one blockchain and lend them on another, using a cross-chain collateral model.</p>
</li>
<li><p><strong>Cross-Chain DEXs (Decentralized Exchanges):</strong> These exchanges can pool liquidity from multiple blockchains, providing better rates and more efficient trades.</p>
</li>
</ul>
<p>So, what is your opinion on this?</p>
<p>How are you planning to use them in your dApps? Comment below.</p>
]]></content:encoded></item><item><title><![CDATA[Ithaca - Noncustodial Options Trading]]></title><description><![CDATA[Hello Everyone..
Welcome to another day in exploring Web3 Engineering. Today, we are going to look into an EVM based options trading platform on the Arbitrum One network. So, without further ado, let’s get started.
What is Ithaca Protocol
Ithaca prot...]]></description><link>https://blog.jnalam.dev/ithaca-noncustodial-options-trading</link><guid isPermaLink="true">https://blog.jnalam.dev/ithaca-noncustodial-options-trading</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[defi]]></category><category><![CDATA[trading, ]]></category><category><![CDATA[options trading]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Tue, 08 Oct 2024 12:10:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728389300173/aa4cad7e-2f45-494c-9bcf-206094d5fd9c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone..</p>
<p>Welcome to another day in exploring Web3 Engineering. Today, we are going to look into an EVM based options trading platform on the Arbitrum One network. So, without further ado, let’s get started.</p>
<h1 id="heading-what-is-ithaca-protocol">What is Ithaca Protocol</h1>
<p>Ithaca protocol is an auction based option trading platform on Arbitrum One. It is both decentralized and non-custodial and also performs off-chain order matching for providing options trading on EVM networks - Ethereum, Base, Polygon, Arbitrum One and Optimism. Ithaca uses auction based order matching to execute the user trades.</p>
<p><strong>Auction Based Order Matching</strong></p>
<p>Auction-based order matching is a way to buy and sell things (like stocks or cryptocurrencies) where buyers and sellers make their offers at the same time. Instead of just taking the first order that comes in, everyone gets a chance to compete for the best price.</p>
<p>In Ithaca, an auction is conducted for every 4 minutes and users are allowed to place traders in this time. Once the auction ends, the trade price is determined on which maximum number of order matching takes place by the trades received.</p>
<h3 id="heading-technical-architecture"><strong>Technical Architecture:</strong></h3>
<ol>
<li><p><strong>Off-Chain Pre-Match Processing:</strong> Ithaca has a matching engine that runs off-chain, powered by auction-based mechanisms to determine the optimal liquidity provision and execute them.</p>
</li>
<li><p><strong>On-Chain Post-Match Settlement:</strong> Once the trades are matched, the settlement takes place on-chain with smart contracts. Ithaca’s <strong>Collateral Optimization Engine</strong> is a crucial part of this phase, managing risk-sharing mechanisms and collateral.</p>
</li>
<li><p><strong>Axelar Bridging</strong> - Ithaca provides cross-chain capabilities with cross-chain gateway protocol from Axelar bridge which provides bridging between multiple blockchains into Arbitrum network.</p>
</li>
</ol>
<h3 id="heading-orders">Orders</h3>
<p>In Ithaca, traders are required to place only limit orders. Auction order matching doesn’t support market orders. User can either can place a basic order or a multi-leg condition order.</p>
<p>All the orders that are placed will stay in the order until it is cancelled or expired.</p>
<h3 id="heading-auction-procedure">Auction Procedure</h3>
<p><strong>Frequent Batch Auctions (FBA)</strong></p>
<p>As I said earlier, Ithaca conducts an auction for every 4 minutes. It is called Frequent Batch Auction. The orders that are matched at discrete times and are followed by the next FBA cycle continuously.</p>
<p><img src="https://docs.ithacaprotocol.io/~gitbook/image?url=https%3A%2F%2F4105275983-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FveNlPcq5FcdKaOERYyrV%252Fuploads%252FSHj8ID6PF8Sr69mrBQxa%252Fimage.png%3Falt%3Dmedia%26token%3De2ab1e78-629e-4b02-a626-f8fdf354ded9&amp;width=768&amp;dpr=4&amp;quality=100&amp;sign=fc9153c&amp;sv=1" alt /></p>
<p>As we can see, there are 2 phases for an auction. They are:</p>
<ol>
<li><p>Order Submission Period</p>
<ul>
<li><p>During this period, users are allowed to place new orders or cancel their existing orders. But during this phase, no order matching takes place and match price is also not generated.</p>
</li>
<li><p>Each order submission period starts immediately after another and finishes when the Matching Period starts for that auction.</p>
</li>
</ul>
</li>
<li><p>Matching Period</p>
<ul>
<li><p>Matching period starts right after the submission period ends.</p>
</li>
<li><p>During this phase, the matching engine comes into play to match all kinds of orders.</p>
</li>
<li><p>Once the matching process completes, the engine determines a single price for the call and put options for the next cycle.</p>
</li>
<li><p>Any orders placed during the matching phase with price below than the estimated single price for the options are placed into a temporary queue to include in the next order submission phase.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-settlement">Settlement</h3>
<p><strong>Automatic Settlement</strong></p>
<p>By default, all contracts are auto-exercised at maturity if and only if the contract has enough and eligible intrinsic value. They can’t be exercised early.</p>
<p>Everything is ‘cash settled’ which means that no party involved in the transaction has to pay any extra funds at the time of settlement. The settlement payouts to the contract holders is done using the locked up collateral amounts.</p>
<p><strong>Settlement Currency</strong></p>
<p>Since ithaca uses collateral optimization, the currency that can be locked up as collateral is either USDC or the underlying asset. So that by using this collateral amount, settlement payout will be done in either of them. Ithaca also provides the ability for the users to chose the settlement currency.</p>
<p>For more detailed information, you can explore their <a target="_blank" href="https://docs.ithacaprotocol.io/">official documentation.</a></p>
]]></content:encoded></item><item><title><![CDATA[Layer 2 Scalability for Blockchain]]></title><description><![CDATA[Hello Everyone…
Welcome to another day of exploring Web3 Engineering. So long we have discussed on many talk topics and some of them are quite advanced as well. Today, let us get our fundamentals right and get a hold on what scalability solutions are...]]></description><link>https://blog.jnalam.dev/layer-2-scalability-for-blockchain</link><guid isPermaLink="true">https://blog.jnalam.dev/layer-2-scalability-for-blockchain</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Blockchain technology]]></category><category><![CDATA[Ethereum]]></category><category><![CDATA[Bitcoin]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Tue, 01 Oct 2024 07:22:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727767274042/50e3639e-380e-4429-9f8e-a071adee6b43.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone…</p>
<p>Welcome to another day of exploring Web3 Engineering. So long we have discussed on many talk topics and some of them are quite advanced as well. Today, let us get our fundamentals right and get a hold on what scalability solutions are available for blockchain networks and why do we need them. So, without any further ado, let’s get started.</p>
<h2 id="heading-what-are-layer-2-solutions">What Are Layer 2 Solutions?</h2>
<p>Layer 2 solutions are designed to enhance the scalability of Layer 1 blockchains like Ethereum, Bitcoin etc which are slower by nature, by processing transactions off the main blockchain. While a Layer 1 blockchain takes the responsibility of security and decentralization, Layer 2 handles transaction throughput, making blockchains more efficient without compromising on security.</p>
<p>There are 3 prominent approaches to implement the layer 2 in the market at the moment. They are</p>
<ul>
<li><p>Rollups</p>
</li>
<li><p>State channels</p>
</li>
<li><p>Side chains or Plasma chains</p>
</li>
</ul>
<h3 id="heading-do-we-really-need-these">Do we really need these ?</h3>
<p>As we can see that networks like bitcoin and Ethereum are growing day by day, issues with increased gas fees and finality time keeps increasing. Layer 2 solutions help networks to mitigate these issues, providing users with cheaper gas rates and faster finality while maintaining the underneath blockchain’s security and decentralization.</p>
<p>Let us dig a deeper into these. Shall we</p>
<h2 id="heading-rollups">Rollups:</h2>
<p>Blockchain rollups are a scalability solution that processes and bundles several transactions off-chain before submitting them to the main blockchain, reducing congestion on blockchain networks.</p>
<p>Based on the technology that these rollups use to bundle the transactions, they are classified. Currently there are 2 approaches being followed by the market which delivered promised results. They are:</p>
<ol>
<li><p>zk or zero-knowledge rollups</p>
</li>
<li><p>Optimistic Rollups</p>
</li>
</ol>
<h3 id="heading-zk-rollups">zk-Rollups</h3>
<p><img src="https://s3.cointelegraph.com/storage/uploads/view/d70d0596b8249c7a7169c6844068a04c.jpg" alt="How Zk-rollups work" class="image--center mx-auto" /></p>
<p>zk-Rollups bundle multiple transactions off-chain and submit a single proof to the ethereum mainnet. This ensures validity of the data on layer 2 without a need to expose entire transaction details to the layer 1. The "zero-knowledge" aspect allows for high security while significantly reducing data on Layer - 1. zk-Rollups allow for more efficient contract interactions by reducing gas fees and improving transaction speeds. Developers building dApps or DeFi products are increasingly implementing zk-Rollups to offer users a faster and more secure experience.</p>
<p>zkSync, zkEVM are the most popular implementations of zk-rollups</p>
<h3 id="heading-optimistic-rollups">Optimistic Rollups</h3>
<p><img src="https://s3.cointelegraph.com/storage/uploads/view/84575bc4cef735fd19be7a3acbe49606.jpg" alt="How optimistic rollups work" /></p>
<p>Optimistic Rollups also bundle transactions off-chain but assume all transactions are valid unless proven otherwise via a fraud-proof system. This means that disputes are settled by submitting fraud proofs to the Ethereum mainnet. Optimistic Rollups are simpler and cheaper to implement compared to zk-Rollups, making them ideal for applications that can tolerate occasional delays for security checks.</p>
<p>Arbitrum and Optimism are popular examples of optimistic rollup solutions.</p>
<h2 id="heading-state-channels">State Channels</h2>
<p><img src="https://www.horizen.io/academy/assets/images/state-channels-60a80566549b2b7c58f5726bf3cde9ec.jpg" alt="What is a Layer 2 Blockchain? | Horizen Academy" class="image--center mx-auto" /></p>
<p>State channels allow participants to open a private channel off-chain and conduct multiple transactions directly between themselves, only recording the final state on-chain. This reduces the number of transactions processed on the main blockchain. State channels work well for use cases that require frequent, low-value transactions, such as micro-payments or gaming applications.</p>
<p>Raiden Network, Connext(now Everclear) are popular implementations of state channels on Ethereum network.</p>
<h2 id="heading-sidechains">Sidechains</h2>
<p><img src="https://s3.amazonaws.com/assets.coingecko.com/app/public/ckeditor_assets/pictures/4132/content_polygon_matic_side_chain.png" alt="polygon matic side chain ethereum" class="image--center mx-auto" /></p>
<p>Sidechains operate as independent blockchains running in parallel to Ethereum or other Layer 1 blockchains. While sidechains handle transactions off-chain (layer 1), they periodically settle batches of transactions on Layer 1 to ensure security.</p>
<p>Polygon is a leading example of a sidechain solution that integrates well with Ethereum. Developers can build dApps on Polygon to take advantage of low fees and faster transactions, while still interacting with the Ethereum mainnet for finality.</p>
<h2 id="heading-security-considerations-for-layer-2">Security Considerations for Layer 2</h2>
<p>Layer 2 solutions inherit security from Layer 1 but come with some trade-offs. For example:</p>
<ul>
<li><p>zk-Rollups: Offer stronger security guarantees as they submit validity proofs to Ethereum, ensuring that the transactions bundled off-chain are valid.</p>
</li>
<li><p>Optimistic Rollups: Rely on fraud proofs, which means there’s a potential delay if a fraudulent transaction is challenged, but they are more efficient due to fewer on-chain checks.</p>
</li>
<li><p>State Channels &amp; Sidechains: Provide enhanced speed and lower costs but may have weaker security models, as they rely on third-party validators or different consensus mechanisms.</p>
</li>
</ul>
<h3 id="heading-how-developers-can-get-started">How Developers Can Get Started</h3>
<ol>
<li><p>zk-Rollups: Platforms like zkSync and StarkNet are excellent starting points for developers looking to build dApps using zk-Rollup technology. Tutorials and documentation on these platforms guide developers on contract migration, zk-SNARKs, and verification mechanisms.</p>
</li>
<li><p>Optimistic Rollups: Developers can explore Arbitrum and Optimism, both of which offer robust developer tools, EVM compatibility, and seamless integration with existing Ethereum dApps.</p>
</li>
<li><p>Polygon: For developers more interested in sidechains, Polygon offers a well-documented SDK that simplifies deploying scalable dApps with high transaction throughput and low fees.</p>
</li>
<li><p>State Channels: Platforms like Raiden Network and Celer offer tooling for integrating state channels into dApps, particularly useful for applications that handle micropayments or gaming.</p>
</li>
</ol>
<p><em>Hope you found this helpful!</em></p>
<p><em>Drop a comment if you want to chat more about it.</em></p>
]]></content:encoded></item><item><title><![CDATA[ERC-7683: Cross Chain Intents]]></title><description><![CDATA[Hello Everyone...
Welcome to another day of exploring Web3 Engineering. Today, we are looking into a ERC standard proposed by Uniswap Labs and Across Protocol to standardize the cross chain trading / order execution and simplify it's implementation. ...]]></description><link>https://blog.jnalam.dev/erc-7683-cross-chain-intents</link><guid isPermaLink="true">https://blog.jnalam.dev/erc-7683-cross-chain-intents</guid><category><![CDATA[Ethereum]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[Smart Contracts]]></category><category><![CDATA[Solidity]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Mon, 02 Sep 2024 08:17:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725264809430/25444d89-0ad0-4e72-b253-f2e6f34da067.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone...</p>
<p>Welcome to another day of exploring Web3 Engineering. Today, we are looking into a ERC standard proposed by Uniswap Labs and Across Protocol to standardize the cross chain trading / order execution and simplify it's implementation. Its main use is to enable more efficient and user-friendly cross-chain interactions. So, without any further ado, let's dive deeper into this.</p>
<h2 id="heading-cross-chain-intents">Cross-chain Intents</h2>
<p>Here, the intent means the expected user outcome by the trade. Before getting into it's working, let us understand some technical words involved in it. ERC-7683 protocol has 2 user roles.</p>
<ul>
<li><p><strong>Swapper</strong> - User who placed a cross-chain trade / swap.</p>
</li>
<li><p><strong>Filler (Relayer)</strong> - Off-chain system that fulfills the user order.</p>
</li>
</ul>
<h3 id="heading-datastructure"><strong>DataStructure</strong></h3>
<p><strong>CrossChainOrder</strong></p>
<pre><code class="lang-solidity"><span class="hljs-keyword">struct</span> <span class="hljs-title">CrossChainOrder</span> {
    <span class="hljs-keyword">address</span> settlementContract;
    <span class="hljs-keyword">address</span> swapper;
    <span class="hljs-keyword">uint256</span> nonce;
    <span class="hljs-keyword">uint32</span> originChainId;
    <span class="hljs-keyword">uint32</span> initiateDeadline;
    <span class="hljs-keyword">uint32</span> fillDeadline;
    <span class="hljs-keyword">bytes</span> orderData;
}
</code></pre>
<ul>
<li><p>settlementContract - address of the settlement contract on the source network</p>
</li>
<li><p>swapper - address of the user(swapper) on the source network</p>
</li>
<li><p>nonce - nonce value to prevent double spending</p>
</li>
<li><p>ordiginChainId - chainId assigned to the source network</p>
</li>
<li><p>initiateDeadline - deadline to initiate the call on the source chain</p>
</li>
<li><p>fillDeadline - deadline for the order to be filled on the destination chain</p>
</li>
<li><p>orderData - any access data in bytes form required to execute the order on the destination chain such as token address, token amount, receiver address etc</p>
</li>
</ul>
<p>the standard interface for the Settlement contract is shown as below:</p>
<pre><code class="lang-solidity"><span class="hljs-comment">/// @title ISettlementContract</span>
<span class="hljs-comment">/// @notice Standard interface for settlement contracts</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ISettlementContract</span> </span>{
    <span class="hljs-comment">/// @notice Initiates the settlement of a cross-chain order</span>
    <span class="hljs-comment">/// @dev To be called by the filler</span>
    <span class="hljs-comment">/// @param order The CrossChainOrder definition</span>
    <span class="hljs-comment">/// @param signature The swapper's signature over the order</span>
    <span class="hljs-comment">/// @param fillerData Any filler-defined data required by the settler</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">initiate</span>(<span class="hljs-params">CrossChainOrder order, <span class="hljs-keyword">bytes</span> signature, <span class="hljs-keyword">bytes</span> fillerData</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span></span>;

    <span class="hljs-comment">/// @notice Resolves a specific CrossChainOrder into a generic ResolvedCrossChainOrder</span>
    <span class="hljs-comment">/// @dev Intended to improve standardized integration of various order types and settlement contracts</span>
    <span class="hljs-comment">/// @param order The CrossChainOrder definition</span>
    <span class="hljs-comment">/// @param fillerData Any filler-defined data required by the settler</span>
    <span class="hljs-comment">/// @returns ResolvedCrossChainOrder hydrated order data including the inputs and outputs of the order</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resolve</span>(<span class="hljs-params">CrossChainOrder order, <span class="hljs-keyword">bytes</span> fillerData</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params">ResolvedCrossChainOrder</span>)</span>;
}
</code></pre>
<h3 id="heading-step-to-step-guide">Step to Step Guide</h3>
<ol>
<li><p>To place a cross-chain order, user will sign the <code>CrosshChainOrder</code> struct data.</p>
</li>
<li><p>Once the order is signed, it will be broadcast against the network of fillers. The fillers will compete against each other in order to execute it.</p>
</li>
<li><p>Once a filler is finalized, they will call the <code>initiate</code> function on the source side Settlement Contract to lock the funds on the source contract.</p>
</li>
<li><p>Once the confirmation is received on the source side to the filler, they will continue to execute the trade on the destination network. The settlement contract ensures that the tokens are sent to the specified receiver address, which is included in the orderData of the original order.</p>
</li>
</ol>
<p>The standard also have a generic data structure called <code>ResolvedCrossChainOrder</code> for unbundling the orderData in order to provide a standard way to execute the order on the destination contract. And the settlement contract must implement the <code>resolve</code> function which converts the <code>CrossChainOrder</code> into <code>ResolvedCrossChainOrder</code></p>
<pre><code class="lang-solidity"><span class="hljs-keyword">struct</span> <span class="hljs-title">ResolvedCrossChainOrder</span> {
    <span class="hljs-keyword">address</span> settlementContract;
    <span class="hljs-keyword">address</span> swapper;
    <span class="hljs-keyword">uint256</span> nonce;
    <span class="hljs-keyword">uint32</span> originChainId;
    <span class="hljs-keyword">uint32</span> initiateDeadline;
    <span class="hljs-keyword">uint32</span> fillDeadline;
    Input[] swapperInputs;
    Output[] swapperOutputs;
    Output[] fillerOutputs;
}

<span class="hljs-comment">/// @notice Tokens sent by the swapper as inputs to the order</span>
<span class="hljs-keyword">struct</span> <span class="hljs-title">Input</span> {
    <span class="hljs-keyword">address</span> token;
    <span class="hljs-keyword">uint256</span> amount;
}

<span class="hljs-comment">/// @notice Tokens that must be receive for a valid order fulfillment</span>
<span class="hljs-keyword">struct</span> <span class="hljs-title">Output</span> {
    <span class="hljs-keyword">address</span> token;
    <span class="hljs-keyword">uint256</span> amount;
    <span class="hljs-keyword">address</span> recipient;
    <span class="hljs-keyword">uint32</span> chainId;
}
</code></pre>
<p><strong>ResolvedCrossChainOrder</strong></p>
<ul>
<li><p>settlementContract - Settlement contract address on the destination chain.</p>
</li>
<li><p>swapper - address of the user(swapper) on the source network</p>
</li>
<li><p>nonce - nonce value to prevent double spending</p>
</li>
<li><p>ordiginChainId - chainId assigned to the source network</p>
</li>
<li><p>initiateDeadline - deadline to initiate the call on the source chain</p>
</li>
<li><p>fillDeadline - deadline for the order to be filled on the destination chain</p>
</li>
<li><p>swapperInputs - array of Input (token) data which are taken from the swapper to initiate the transaction.</p>
</li>
<li><p>swapperOutputs - The outputs to be given to the swapper as part of order fulfillment</p>
</li>
<li><p>fillerOutputs - The outputs to be given to the filler as part of order settlement. It could include fees, commission etc.</p>
</li>
</ul>
<p><strong>Input</strong></p>
<ul>
<li><p>token - address of the ERC20 token on the origin chain</p>
</li>
<li><p>amount - amount of the token to be sent</p>
</li>
</ul>
<p><strong>Output</strong></p>
<ul>
<li><p>token - address of the ERC20 token on the destination chain. zero address must be used in order to specify native token.</p>
</li>
<li><p>amount - amount of the token to be sent to the receiver</p>
</li>
<li><p>recipient - address of the output tokens receiver</p>
</li>
<li><p>chainId - destination chainId for the output.</p>
</li>
</ul>
<h3 id="heading-protocols-implementing-erc-7683">Protocols implementing ERC-7683</h3>
<p>At the time of publishing this article, currently there are two projects that are implementing this standard. They are:</p>
<ul>
<li><p>Uniswap</p>
</li>
<li><p>Across Protocol</p>
</li>
</ul>
<p><em>Hope you found this helpful!</em></p>
<p><em>Drop a comment if you want to chat more about it.</em></p>
]]></content:encoded></item><item><title><![CDATA[Aeternity Blockchain and it's Hybrid Consensus]]></title><description><![CDATA[Hello Everyone..
Welcome to another day of Web3 Engineering. Today, we are going to explore a new layer 1 blockchain called Aeternity. It was launched by Yanislav Mahalov in 2016 to deal with the blockchain scalability problem. So, without any furthe...]]></description><link>https://blog.jnalam.dev/aeternity-blockchain-and-its-hybrid-consensus</link><guid isPermaLink="true">https://blog.jnalam.dev/aeternity-blockchain-and-its-hybrid-consensus</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Smart Contracts]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Fri, 30 Aug 2024 13:15:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725023562164/a031055a-836f-4823-bd50-68433479ce64.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone..</p>
<p>Welcome to another day of Web3 Engineering. Today, we are going to explore a new layer 1 blockchain called <strong>Aeternity</strong>. It was launched by Yanislav Mahalov in 2016 to deal with the blockchain scalability problem. So, without any further ado, let's get started.</p>
<h1 id="heading-aeternity-blockchain">Aeternity Blockchain.</h1>
<p>Aeternity is a scalable blockchain network which uses an hybrid consensus of <code>Proof-of-Work(PoW)</code> and <code>Proof-of-Stake(PoS)</code> to increase the transaction speed of the network. It has proven efficiency over the classic approach by using PoW for transaction validation and PoS for Community Governance Decisions like block size, transaction fee etc.</p>
<p>Along with the hybrid consensus, aeternity also uses state channels to increase the throughput. The smart contracts are executed off-chain using state channels to reduce the load on the main network and also granted enhanced privacy with faster executions.</p>
<h3 id="heading-major-components">Major Components</h3>
<p>Aeternity blockchain comprises several major components to increase its functionality. Some of them are</p>
<ol>
<li><p><strong>Hybrid Consensus</strong> - A combined consensus of PoW and PoS to increase the transactions by separating processes for community decisions and transaction execution.</p>
</li>
<li><p><strong>State Channels</strong> - State channels are a significant feature that allows transactions to occur off-chain. This enables faster and cheaper transactions, as they require only two on-chain transactions for opening and closing the channel.</p>
</li>
<li><p><strong>Oracles</strong> - Aeternity integrates oracles that provide real-world data to smart contracts. This capability allows dApps to interact with external information, such as weather data or sports results, thereby expanding the utility of smart contracts beyond the blockchain.</p>
</li>
<li><p><strong>Sophia Smart Contracts</strong> - Smart contracts are written in Sophia language. It is a functional programming language designed for smart contract development on Aeternity blockchain which is strongly types and provides higher level abstraction.</p>
</li>
<li><p><strong>AENS -</strong> An in-built Decentralized Naming System which helps users to assign human readable names to their addresses and smart contracts.</p>
</li>
<li><p><strong>Interoperability Protocol</strong> - Aeternity comes with a built-in interoperability protocol allowing it to interact with other blockchain system and support cross-functional dApps.</p>
</li>
</ol>
<h3 id="heading-how-the-hybrid-consensus-works"><strong>How the Hybrid Consensus Works</strong></h3>
<p><strong>PoW Working</strong></p>
<p>In Aeternity's setup, the PoW component is responsible for creating new blocks and validating transactions. It utilizes a unique algorithm called Cuckoo Cycle, which is ASIC-resistant and optimized for memory usage, allowing for efficient mining with lower energy consumption. This aspect enables miners to generate blocks approximately every 15 seconds, contributing to the network's speed and scalability.</p>
<p><strong>PoS Working</strong></p>
<p>The PoS mechanism in Aeternity serves primarily for governance rather than traditional staking. AE token holders can vote on critical system parameters such as block size, transaction fees, and protocol upgrades. This governance model ensures that the community has a say in the platform's evolution, promoting transparency and user engagement.</p>
<h3 id="heading-interaction-between-pow-and-pos"><strong>Interaction Between PoW and PoS</strong></h3>
<ol>
<li><p><strong>Block Creation</strong>: PoW miners create new blocks and add them to the blockchain.</p>
</li>
<li><p><strong>Block Confirmation</strong>: Once blocks are created, PoS participants review and confirm these blocks. This dual-layer validation process enhances security, as blocks must be validated by both miners and stakeholders.</p>
</li>
<li><p><strong>Voting and Governance</strong>: AE token holders use their tokens to vote on governance issues, with their voting power proportional to the number of tokens they hold. This structure allows for a decentralized decision-making process that reflects the interests of the community.</p>
</li>
</ol>
<h3 id="heading-state-channels">State Channels</h3>
<p>State channels increase the transactions by offloading transactions from the main chain and private off chain transactions. They can also include smart contract executions as well. The process of making a transaction through state channel happens in 4 steps:</p>
<ol>
<li><p><strong>Channel Opening</strong></p>
<ul>
<li><p>To open up a state channel, the parties involved need to lockup funds on special smart contract on the blockchain.</p>
</li>
<li><p>This contract defines the terms of the channel such as timeout, lockup amount etc</p>
</li>
</ul>
</li>
<li><p><strong>Off-chain Transaction</strong></p>
<ul>
<li><p>Once the channel is established, the parties can continue with perform limitless transactions without worrying about the network congestion.</p>
</li>
<li><p>Now the parties will sign the state updates to make a new transaction. These transactions are private between the participants and are not recorded on the network.</p>
</li>
</ul>
</li>
<li><p><strong>Smart Contract Execution</strong></p>
<ul>
<li><p>If a contract is involved, the smart contract will be deployed on the channel when it is opened.</p>
</li>
<li><p>Alongside the channel's signed state, the contract is also updated allowing it to execute off chain without being deployed on main network.</p>
</li>
</ul>
</li>
<li><p><strong>Dispute Resolution</strong></p>
<ul>
<li><p>If the parties involved raises any dispute, it can be settled on the main net, by closing the final state on the main net.</p>
</li>
<li><p>This is done by publishing the updated signed state on the blockchain. And the other party will be given the timeout period to respond and dispute the published data.</p>
</li>
<li><p>If no disputes are raised, the channel will be closed recording the final state on the network and the locked-in funds are distributed according to the published state.</p>
</li>
</ul>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Sui - Clock Object]]></title><description><![CDATA[Hello everyone..
Welcome to another day of exploring Web3 Engineering. In our series, we are learning about Sui language and how to write smart contracts using Move language. So far, we have already covered the basic and necessary concepts that are r...]]></description><link>https://blog.jnalam.dev/sui-clock-object</link><guid isPermaLink="true">https://blog.jnalam.dev/sui-clock-object</guid><category><![CDATA[Sui]]></category><category><![CDATA[movelang]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[Smart Contracts]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Tue, 27 Aug 2024 08:26:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724747099163/c4cd34f1-0c32-43b9-9ff9-c9f97199099c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. In our series, we are learning about Sui language and how to write smart contracts using Move language. So far, we have already covered the basic and necessary concepts that are required to write smart contracts. In this article, let us understand how to include time aka clock module in our contracts. So, without any further ado, let's get started...</p>
<h2 id="heading-clock-module">Clock module</h2>
<p>Sui standard package contains a special module called <code>clock</code> which contains the <code>Clock</code> using which we can access the current timestamp during execution. Clock is a shared object on the network and initialized during the genesis block. This object contains only one field which is <code>timestamp_ms</code> storing the current time of the network in milliseconds.</p>
<p>Even though it's a regular shared object, it can only be included as a reference in our functions and adding as a mutable reference results in compilation errors. The structure of the Clock object is as follows:</p>
<pre><code class="lang-rust">public <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Clock</span></span> has key {
    id: UID,
    timestamp_ms: <span class="hljs-built_in">u64</span>,
}
</code></pre>
<p>The module can be imported and used as follows:</p>
<pre><code class="lang-solidity"><span class="hljs-keyword">public</span> <span class="hljs-keyword">struct</span> <span class="hljs-title">Counter</span> <span class="hljs-title">has</span> <span class="hljs-title">key</span>, <span class="hljs-title">store</span> {
    id:UID,
    count: u64,
    time: u64,
    last_updated: u64
}

<span class="hljs-keyword">public</span> entry fun <span class="hljs-keyword">new</span>(time: u64, clock: <span class="hljs-operator">&amp;</span>Clock, ctx: <span class="hljs-operator">&amp;</span>mut TxContext) {
    transfer::transfer(Counter {
        id: object::<span class="hljs-keyword">new</span>(ctx),
        count: <span class="hljs-number">0</span>,
        time: time,
        last_updated: clock.timestamp_ms()
    }, ctx.sender());
} 

<span class="hljs-keyword">public</span> entry fun update(counter: <span class="hljs-operator">&amp;</span>mut Counter, clock: <span class="hljs-operator">&amp;</span>Clock) {
    <span class="hljs-built_in">assert</span><span class="hljs-operator">!</span>(counter.last_updated <span class="hljs-operator">+</span> counter.time <span class="hljs-operator">&lt;</span><span class="hljs-operator">=</span> clock.timestamp_ms(), <span class="hljs-number">0</span>);
    counter.count <span class="hljs-operator">=</span> counter.count <span class="hljs-operator">+</span> <span class="hljs-number">1</span>;
    counter.last_updated <span class="hljs-operator">=</span> clock.timestamp_ms();
}
</code></pre>
<p>In our above contract, we have a Counter object which can only be updated after <code>time</code> which is given during the initialization. As you can, we have added the Clock as a reference on both of the functions. Now, let us write some test cases for the above code.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[test]</span>
fun test_new_counter() {
    <span class="hljs-keyword">let</span> user  = @<span class="hljs-number">0x12e4</span>;
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> scenario = test_scenario::begin(user);
    {
        <span class="hljs-keyword">let</span> ctx = scenario.ctx();
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> clock = clock::create_for_testing(ctx);
        clock_obj::new(TIME, &amp;clock, ctx);
        clock.increment_for_testing(<span class="hljs-number">1</span>);
        clock.share_for_testing();
    };

    scenario.next_tx(user);
    {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> counter = scenario.take_from_sender&lt;clock_obj::Counter&gt;();
        <span class="hljs-keyword">let</span> clock = scenario.take_shared&lt;clock::Clock&gt;();
        counter.update(&amp;clock);

        scenario.return_to_sender(counter);
        test_scenario::return_shared(clock);
    };
    scenario.end();
}
</code></pre>
<p>Here we are creating a test <code>Clock</code> object for our test scenario and sharing it into the network. We are also using the test helper functions provided by the clock module from the <code>sui</code> package. Now let us write a failure test case for the above scenario.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[test, expected_failure]</span>
fun test_fail_counter() {
    <span class="hljs-keyword">let</span> user  = @<span class="hljs-number">0x12e4</span>;

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> scenario = test_scenario::begin(user);
    {
        <span class="hljs-keyword">let</span> ctx = scenario.ctx();
        <span class="hljs-keyword">let</span> clock = clock::create_for_testing(ctx);
        clock_obj::new(TIME, &amp;clock, ctx);
        clock.share_for_testing();
    };

    scenario.next_tx(user);
    {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> counter = scenario.take_from_sender&lt;clock_obj::Counter&gt;();
        <span class="hljs-keyword">let</span> clock = scenario.take_shared&lt;clock::Clock&gt;();
        counter.update(&amp;clock);

        scenario.return_to_sender(counter);
        test_scenario::return_shared(clock);
    };
    scenario.end();
}
</code></pre>
<p>In the above test case, we are not updating the clock object. Hence it should throw an error as expected.</p>
<p>NOTE: For using the clock module in a function call made externally, we must pass the value <code>0x6</code> as the clock module object id.</p>
<p>The full code can be found here: <a target="_blank" href="https://github.com/jveer634/sui_contracts">https://github.com/jveer634/sui_contracts</a></p>
<p>That's all for today. Thank you.</p>
]]></content:encoded></item><item><title><![CDATA[Modular Blockchains]]></title><description><![CDATA[Hello everyone...
Welcome to another day of exploring Web3 Engineering. Today, let us dive into the world of Modular blockchains. Let us understand what are they? How do they work ? And where are they useful ? So, without any further ado, let's get s...]]></description><link>https://blog.jnalam.dev/modular-blockchains</link><guid isPermaLink="true">https://blog.jnalam.dev/modular-blockchains</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[architecture]]></category><category><![CDATA[Ethereum]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Wed, 31 Jul 2024 07:10:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722409710499/1a2b1eb0-ce32-4bc6-bfea-3dc926da23d7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone...</p>
<p>Welcome to another day of exploring Web3 Engineering. Today, let us dive into the world of Modular blockchains. Let us understand what are they? How do they work ? And where are they useful ? So, without any further ado, let's get started..</p>
<h2 id="heading-what-are-modular-blockchains">What are Modular Blockchains ?</h2>
<p>Traditionally, the old blockchain systems (Ethereum and Bitcoin) are monolithic. Which means all the tasks like block producing, consensus, validation etc are all taken care of as a single service. This approach creates problems whenever there is a need of updating the node for even a smaller change. e.g. Ethereum PoS update.</p>
<p>So, all these services are separated into separate for easy updates. And this module based architecture is called <strong>Modular Blockchains</strong>. By this, we can easily upgrade one layer without effecting the other layers. For instance, we can change the consensus algorithm without effecting block producing layer etc.</p>
<h2 id="heading-how-do-they-work">How do they work ?</h2>
<p>These modular blockchains is made up of four layers. They are:</p>
<ol>
<li><p>Blockchain / Execution layer</p>
</li>
<li><p>Settlement layer</p>
</li>
<li><p>Consensus layer</p>
</li>
<li><p>Data Availability Layer</p>
</li>
</ol>
<h3 id="heading-execution-blockchain-layer">Execution / Blockchain Layer</h3>
<p>The execution layer is responsible for processing transactions and executing smart contracts. It is where users interact with the blockchain by signing transactions and transferring assets. This layer handles state changes, enabling the blockchain to update its ledger based on the transactions processed. By offloading execution to this layer, modular blockchains can achieve higher throughput and faster transaction times compared to monolithic structures.</p>
<h3 id="heading-settlement-layer">Settlement Layer</h3>
<p>The settlement layer verifies the execution of transactions and resolves disputes. It acts as a final arbiter, ensuring that once a transaction is executed, it is immutable and cannot be altered. This layer is not always present in monolithic blockchains but is an optional component in modular designs. It provides a crucial function analogous to a judicial system, confirming the legitimacy of transactions and maintaining the integrity of the blockchain.</p>
<h3 id="heading-consensus-layer">Consensus Layer</h3>
<p>The consensus layer establishes agreement among network participants on the validity of transactions and the state of the blockchain. It employs various consensus mechanisms, such as Proof of Stake (PoS) or Byzantine Fault Tolerance (BFT), to ensure that all nodes in the network reach a consensus on the order and validity of transactions.</p>
<h3 id="heading-data-availability-layer">Data Availability Layer</h3>
<p>The data availability layer ensures that the data required to verify transactions is accessible and can be validated by network participants. This layer addresses the challenge of ensuring that transaction data is publicly available and not withheld by malicious actors.</p>
<h2 id="heading-where-are-they-useful">Where are they useful ?</h2>
<p>Modular blockchains are mainly used as <strong>Layer 2 solutions</strong> where scalability of a blockchain is the major issue. Modular blockchains address the scalability problem with the help of the technique called <strong>Sharding</strong>.</p>
<p>In monolithic blockchains, every transaction passed is required to be validated by every validator node in the cluster which is time consuming since there are a good number of validators running for a strong blockchain network like Ethereum.</p>
<p>But in modular blockchains, the transaction set is split into smaller chunks called SHARDS. Each shard is responsible for storing and managing a subset of the network's data, ensuring that the required data is available for processing transactions within that shard. With this process, the transactions undergo parallel execution that increases the scalability exponentially.</p>
]]></content:encoded></item><item><title><![CDATA[Solidity - Tips to save Gas]]></title><description><![CDATA[Hello Everyone..
Welcome to another day of exploring Web3 Engineering. In today's blog, let us look into the tips and patterns to follow during solidity smart contract development to save gas costs while making transactions. So, without any further a...]]></description><link>https://blog.jnalam.dev/solidity-tips-to-save-gas</link><guid isPermaLink="true">https://blog.jnalam.dev/solidity-tips-to-save-gas</guid><category><![CDATA[Ethereum]]></category><category><![CDATA[Solidity]]></category><category><![CDATA[Smart Contracts]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Wed, 03 Jul 2024 09:19:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1719998289429/30f68e47-d639-4a68-b9d4-cb0e31be1b61.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. In today's blog, let us look into the tips and patterns to follow during solidity smart contract development to save gas costs while making transactions. So, without any further ado, let's get started.</p>
<ol>
<li><h3 id="heading-dont-use-a-loop">Don't use a loop.</h3>
<p> As we all know by now, in solidity, every single operation costs some gas. When we run a <code>for</code> loop as shown below.</p>
</li>
</ol>
<pre><code class="lang-solidity"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i<span class="hljs-operator">&lt;</span> array.<span class="hljs-built_in">length</span>(); i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>) {
    <span class="hljs-keyword">if</span>(array[i] <span class="hljs-operator">=</span><span class="hljs-operator">=</span> val) {
        array[i] <span class="hljs-operator">=</span> k;
    }
}
</code></pre>
<ul>
<li><p>We are initializing a variable called <code>count</code></p>
</li>
<li><p>We are also incrementing it for every iteration</p>
</li>
</ul>
<p>These two operations will increase the gas in linear fashion depending on the length of the array.</p>
<ol start="2">
<li><h3 id="heading-avoid-arrays-and-use-mappings">Avoid Arrays and use Mappings</h3>
</li>
</ol>
<ul>
<li><p>Mappings are cheaper than than the Arrays in solidity.</p>
<ul>
<li><p>Array values are supposed to saved in serial fashion. Which means, index 1 element will be saved in the memory location right after the index 0 element and so on.</p>
</li>
<li><p>In the storage space, the first memory block contains the length of the array and the values are stored from the 2nd block on wards.</p>
</li>
<li><p>If there is any value appended, it needs to update both values list and the length of the array. The two operations are expensive</p>
</li>
</ul>
</li>
<li><p>Mappings don't have any concept of length. The mapping are stored as key value pairs in the storage space.</p>
<ul>
<li><p>Keys in mappings are hashed to a unique identifier that is used to locate the corresponding value in storage.</p>
</li>
<li><p>Which means whenever there is a need to update the mapping, there is only operation taking place.</p>
</li>
</ul>
</li>
</ul>
<ol start="3">
<li><h3 id="heading-avoid-calling-globalstorage-variable-multiple-times">Avoid calling global/storage variable multiple times</h3>
<p> While writing contracts, we often use multiple global variables such as <code>block.timestamp</code>, <code>msg.sender</code>, <code>msg.value</code> etc. But accessing global variables or storage variables is expensive. So, we need to create a local copy of the variable which will create an in-memory copy of the variable and accessing variables from memory is relatively cheaper. We can look into an example below.</p>
</li>
</ol>
<pre><code class="lang-solidity"><span class="hljs-comment">// expensive function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func1</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{
    <span class="hljs-built_in">require</span>(admins[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>], <span class="hljs-string">"Not eligible"</span>);
    changesCounter[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">emit</span> Changed(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>, <span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>);
}

<span class="hljs-comment">// cheaper function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func2</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{
    <span class="hljs-keyword">address</span> caller <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
    <span class="hljs-built_in">require</span>(admins[caller], <span class="hljs-string">"Not eligible"</span>);
    changesCounter[caller] <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">emit</span> Changed(caller, <span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>);
}
</code></pre>
<ol start="4">
<li><h3 id="heading-avoid-calling-public-functions-inside-another-function">Avoid calling Public functions inside another function</h3>
</li>
</ol>
<ul>
<li><p>An external / public returns ABI encoded data while an internal function returns bytes data. So, using a public function inside a function is expensive than caling an internal function.</p>
</li>
<li><p>The code can be rewritten as shown in below in order to save gas.</p>
<pre><code class="lang-solidity">  <span class="hljs-comment">// Expensive method</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">childExpensive</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
      <span class="hljs-keyword">return</span> <span class="hljs-number">10</span>;
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">expensive</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
      <span class="hljs-keyword">return</span> childExpensive();
  }

  <span class="hljs-comment">// Cheaper method</span>

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_childInternal</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">internal</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
      <span class="hljs-keyword">return</span> <span class="hljs-number">10</span>;
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">childCheap</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
      <span class="hljs-keyword">return</span> _childInternal();
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cheap</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
      <span class="hljs-keyword">return</span> _childInternal();
  }
</code></pre>
<ul>
<li>In the cheaper method, we have converted the logic into a <code>internal</code> function and created a wrapper called <code>childCheap</code> to make it available for the external sources. And also whenever the logic is required we are calling the internal function.</li>
</ul>
</li>
</ul>
<p>    Comment down if you have any more tips to save gas. Thank you</p>
]]></content:encoded></item><item><title><![CDATA[Sniper Bot - A deep view]]></title><description><![CDATA[Hello everyone..
Welcome to another day of exploring Web3 Engineering. In today's blog, we are looking into Sniper Bot, one of the well used bots for cryptotrading. So, without any further ado, let's get started.
Sniper Bot
Sniper bot is an automated...]]></description><link>https://blog.jnalam.dev/sniper-bot-a-deep-view</link><guid isPermaLink="true">https://blog.jnalam.dev/sniper-bot-a-deep-view</guid><category><![CDATA[Ethereum]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[Cryptocurrency]]></category><category><![CDATA[bots]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Mon, 24 Jun 2024 10:58:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1719226633265/52635ecf-0ebb-4a04-94e0-9ba4392be1d4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. In today's blog, we are looking into Sniper Bot, one of the well used bots for cryptotrading. So, without any further ado, let's get started.</p>
<h1 id="heading-sniper-bot">Sniper Bot</h1>
<p>Sniper bot is an automated program that is used to execute a cryptotrade instantly according to the conditions set by the user. The main reason for using sniper bots is its swift response to the market movements and counter orders to make profits for the users.</p>
<p>For example, during a auction, we can place counter bids instantaneously by continuously monitoring the bids being placed in order to increase one's allotment chances.</p>
<p>Let's look into the <strong>key features</strong> of the Sniper Bots:</p>
<ul>
<li><strong>Precision:</strong> Sniper bots are programmed to execute trades with precision, while considering the predetermined parameters to ensure favourable market entrance and exit positions.</li>
</ul>
<ul>
<li><p><strong>Automated trading</strong>: Sniper bots operate automatically, which means once the bots are deployed, zero to none human intervention is required</p>
</li>
<li><p><strong>Pre-programmed algorithms</strong>: Sniper bots use pre-programmed algorithms to function, which can incorporate technical indicators, arbitrage methods, scalping tactics, and precise entry and exit points.</p>
</li>
<li><p><strong>Fast execution</strong>: Sniper bots can execute trades in milliseconds or less, taking advantage of favorable price fluctuations.</p>
</li>
</ul>
<h3 id="heading-are-there-any-types-of-snipers">Are there any types of Snipers ?</h3>
<p>Based on the trading mechanism and the parameters set, there are 4 major categories of Sniper bots. They are:</p>
<ul>
<li><p><strong>Entry/Exit Bots</strong> - These bots are deployed with predetermined entry and exit points for the asset price. Once the price enters/exits the given value, appropriate buy/sell calls are made to achieve profits.</p>
</li>
<li><p><strong>Scalping Bots</strong> - These bots trade on sudden spikes in the price. They place a good number of small trades to increase the trading activity on the asset and then leverages the sudden price changes.</p>
</li>
<li><p><strong>Arbitrage bots</strong> - These bots make profits by dealing with multiple exchanges and leveraging the price differences in them. For example, by purchasing the tokens at the exchange which has lower price and selling them at the exchange that has higher price.</p>
</li>
<li><p><strong>Technical indicator-based bots</strong> - These bots are based on the technical indicators such as Moving Averages (eg 52 week moving average), Strength Indices and Bollinger Bands to initiate and carry forward the trades according to the market conditions.</p>
</li>
</ul>
<h3 id="heading-working">Working</h3>
<p>On the higher view, all the sniper bots work in 3 simple steps.</p>
<ul>
<li><p>User criteria ingestion</p>
</li>
<li><p>Market monitoring</p>
</li>
<li><p>Trade execution</p>
</li>
</ul>
<p>Lets look into them</p>
<ol>
<li><p><strong>User criteria Ingestion</strong> - To deploy a sniper bot, the user must input the specific criteria depending upon the type of the bot. For example, entry and exit conditions or technical algorithm or list of exchanges etc., With these base details the bot can initiate the process.</p>
</li>
<li><p><strong>Market monitoring -</strong> With the input data, the bot starts monitoring the markets in real time searching for the correlations between the parameters given by the user and the current conditions.</p>
</li>
<li><p><strong>Trade Execution</strong> - The bot quickly completes transactions after locating a match, trying to enter or exit at the optimal time.</p>
</li>
</ol>
<h3 id="heading-risks-and-challenges">Risks and Challenges:</h3>
<p>So far, the sniper bot seems so useful and powerful to make traders life easy and gain profits. But there are also some risks and challenges that come with the usage of trading bots.</p>
<ul>
<li><p><strong>Market volatility</strong>: With the quick action capability of Sniper bots, it makes the markets volatile as it keeps changing the prices of the assets instantaneously. If the bot is trading with a bigger volume of the asset, it can cause a shift in price of the assets within seconds.</p>
</li>
<li><p><strong>Algorithmic complexity:</strong> With the increase in the complexity of the algorithm used by sniper bots, it becomes challenging to detect and stop their activity.</p>
</li>
<li><p><strong>Regulatory compliance</strong>: Sniper bots may be subject to regulatory restrictions, and their use may be prohibited on certain platforms.</p>
</li>
</ul>
<h3 id="heading-detection-and-prevention">Detection and Prevention:</h3>
<ul>
<li><p><strong>Monitoring market behaviour</strong>: Monitoring market behaviour, analysing trade volumes, and timing can help detect and prevent sniper bot activity.</p>
</li>
<li><p><strong>Platform restrictions</strong>: Some platforms may restrict the use of sniper bots or implement anti-bot mechanisms to prevent their activity.</p>
</li>
<li><p><strong>User awareness</strong>: Educating users about the risks and challenges associated with sniper bots can help prevent their misuse.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Biconomy - Gas less Transactions]]></title><description><![CDATA[Hello Everyone..
Welcome to another day of exploring Web3 Engineering. Today, we will look into Biconomy and how it achieves gas less transactions using Account abstraction. So, without any further ado, let's get started.
Biconomy
Biconomy actually s...]]></description><link>https://blog.jnalam.dev/biconomy-gas-less-transactions</link><guid isPermaLink="true">https://blog.jnalam.dev/biconomy-gas-less-transactions</guid><category><![CDATA[Ethereum]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[biconomy]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Tue, 04 Jun 2024 11:29:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717500451070/009f8898-b418-4c5d-87c9-00a33fbbd7c2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. Today, we will look into Biconomy and how it achieves gas less transactions using Account abstraction. So, without any further ado, let's get started.</p>
<h2 id="heading-biconomy">Biconomy</h2>
<p>Biconomy actually started as a plug and play protocol on EVM blockchains to provide gas-less with it's relayer infrastructure. Initially they provided gas less or Meta transactions using ERC-2771 standard. The user has to create a biconomy on it's dashboard and fill the gas tank with the respective native token of the chain they are providing the gas less transactions.</p>
<h3 id="heading-erc-2771-standard">ERC 2771 Standard</h3>
<p>ERC-2771 simplifies Ethereum smart contract interactions by enabling gasless transactions and meta transactions. It provides a secure protocol for native meta transactions, ensuring that transactions are correctly relayed and executed. By leveraging ERC-2771, developers can create more user-friendly and efficient dApps.</p>
<p><strong>Key Components</strong></p>
<ul>
<li><p>Transaction Signer: The user who initiates the transaction and signs the request off-chain.</p>
</li>
<li><p>Gas Relay: A third-party account that pays for the gas fees and turns the signed request into a valid on-chain transaction.</p>
</li>
<li><p>Trusted Forwarder: A contract that verifies the transaction data and ensures it is correctly relayed to the intended recipient contract.</p>
</li>
<li><p>Recipient Contract: The smart contract that accepts and executes the meta transaction.</p>
</li>
</ul>
<p><strong>Workflow</strong></p>
<ul>
<li><p>Off-Chain Signing: The user signs a request off-chain using their private key.</p>
</li>
<li><p>Gas Relay: The gas relay receives the signed request and pays the gas fee.</p>
</li>
<li><p>Trusted Forwarder: The trusted forwarder verifies the transaction data and ensures it is correctly relayed to the recipient contract.</p>
</li>
<li><p>On-Chain Execution: The recipient contract executes the transaction.</p>
</li>
</ul>
<p>But later, Biconomy switched from ERC2771 to ERC 4337 Account Abstraction Model to provide which uses new way of making transactions and efficient transaction batching which reduces the gas fees for the sponsors.</p>
<h2 id="heading-erc-4337-account-abstraction">ERC 4337 Account Abstraction</h2>
<p>ERC-4337 is another standard that enables account abstraction and provides smart contracts with EAO features. While both standards simplify transactions, ERC-2771 focuses on gasless transactions and meta transactions, whereas ERC-4337 introduces a new object type called UserOperations and a paymaster mechanism for managing gas fees.</p>
<h3 id="heading-key-components">Key Components</h3>
<ul>
<li><p><strong>UserOperations:</strong> These are "to-do lists" that users provide to their Ethereum accounts, which can include actions like transferring funds, interacting with smart contracts, or a combination of multiple actions. UserOperations are bundled together into a single transaction, reducing the need for multiple transactions.</p>
</li>
<li><p><strong>EntryPoint Contract</strong>: This contract acts as a proxy for the user, executing the UserOperations and ensuring that the user's intent is correctly relayed to the intended recipient contract.</p>
</li>
<li><p><strong>Paymaster Mechanism:</strong> This mechanism allows users to pay gas fees using ERC-20 tokens instead of ETH or enables a third party to sponsor gas fees in a decentralized manner.</p>
</li>
</ul>
<h3 id="heading-biconomy-implementation">Biconomy Implementation</h3>
<p>In the latest version of Biconomy (v4), we have the Biconomy Account Abstraction toolkit is available which we can use to create smart account for the users in order to make the ERC4337 transactions.</p>
<p>Before starting with that, we first have to setup our app on the biconomy dashboard where we set up the <code>Paymaster</code> and we obtain the <code>Bundler</code> url from it.</p>
<p>We can fill the paymaster with the required tokens and pass the required credentials to the SDK for creating the smart accounts. Here is the script to create the smart accounts for a given user.</p>
<p>Let us check a typescript example on how to create a smart account for the user using <code>viem</code> and typescript/javascript.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> {
  Hex,
  createWalletClient,
  encodeFunctionData,
  http,
  parseAbi,
  zeroAddress,
} <span class="hljs-keyword">from</span> <span class="hljs-string">"viem"</span>;
<span class="hljs-keyword">import</span> { privateKeyToAccount } <span class="hljs-keyword">from</span> <span class="hljs-string">"viem/accounts"</span>;
<span class="hljs-keyword">import</span> { polygonAmoy } <span class="hljs-keyword">from</span> <span class="hljs-string">"viem/chains"</span>;
<span class="hljs-keyword">import</span> { createSmartAccountClient } <span class="hljs-keyword">from</span> <span class="hljs-string">"@biconomy/account"</span>;

<span class="hljs-keyword">const</span> bundlerUrl = <span class="hljs-string">"BUNDLER_URL"</span>; <span class="hljs-comment">// Found at https://dashboard.biconomy.io</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> createAccountAndMintNft = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-comment">// ----- 1. Generate EOA from private key</span>
  <span class="hljs-keyword">const</span> account = privateKeyToAccount(<span class="hljs-string">"0x"</span> + <span class="hljs-string">"PRIVATE_KEY"</span>);
  <span class="hljs-keyword">const</span> client = createWalletClient({
    account,
    chain: polygonAmoy,
    transport: http(),
  });
  <span class="hljs-keyword">const</span> eoa = client.account.address;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`EOA address: <span class="hljs-subst">${eoa}</span>`</span>);

  <span class="hljs-comment">// ------ 2. Create biconomy smart account instance</span>
  <span class="hljs-keyword">const</span> smartAccount = <span class="hljs-keyword">await</span> createSmartAccountClient({
    signer: client,
    bundlerUrl,
  });
  <span class="hljs-keyword">const</span> saAddress = <span class="hljs-keyword">await</span> smartAccount.getAccountAddress();
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"SA Address"</span>, saAddress);
};
createAccountAndMintNft();
</code></pre>
<p>Now, let us look into how to make a gasless transaction using the Smart account.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> nftAddress = <span class="hljs-string">"0x1758f42Af7026fBbB559Dc60EcE0De3ef81f665e"</span>;
  <span class="hljs-keyword">const</span> parsedAbi = parseAbi([<span class="hljs-string">"function safeMint(address _to)"</span>]);
  <span class="hljs-keyword">const</span> nftData = encodeFunctionData({
    abi: parsedAbi,
    functionName: <span class="hljs-string">"safeMint"</span>,
    args: [saAddress <span class="hljs-keyword">as</span> Hex],
  });

  <span class="hljs-comment">// ------ 4. Send transaction</span>
  <span class="hljs-keyword">const</span> userOpResponse = <span class="hljs-keyword">await</span> smartAccount.sendTransaction({
    to: nftAddress,
    data: nftData,
  });
  <span class="hljs-keyword">const</span> { transactionHash } = <span class="hljs-keyword">await</span> userOpResponse.waitForTxHash();
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"transactionHash"</span>, transactionHash);
  <span class="hljs-keyword">const</span> userOpReceipt = <span class="hljs-keyword">await</span> userOpResponse.wait();
  <span class="hljs-keyword">if</span> (userOpReceipt.success == <span class="hljs-string">"true"</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"UserOp receipt"</span>, userOpReceipt);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Transaction receipt"</span>, userOpReceipt.receipt);
  }
} <span class="hljs-keyword">catch</span> (error: unknown) {
  <span class="hljs-keyword">if</span> (error <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Error</span>) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Transaction Error:"</span>, error.message);
  }
}
</code></pre>
<p><strong>NOTE</strong>: If we ever want to make any payable transactions using our smart account (send ether in a contract call), we need to contain funds on the smart account.</p>
]]></content:encoded></item><item><title><![CDATA[Sui - Coin Payments]]></title><description><![CDATA[Hello everyone..
Welcome to another day of exploring Web3 Engineering. In today's blog, let us check on how to make payments using coin module on Sui.
We all know about the ERC20 standard in the Ethereum and how it is different from the native eth pa...]]></description><link>https://blog.jnalam.dev/sui-coin-payments</link><guid isPermaLink="true">https://blog.jnalam.dev/sui-coin-payments</guid><category><![CDATA[Sui]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[Smart Contracts]]></category><category><![CDATA[movelang]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Wed, 29 May 2024 11:20:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1716983839264/554a0a61-e6d6-4d58-9dca-31710bb95fc0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone..</p>
<p>Welcome to another day of exploring Web3 Engineering. In today's blog, let us check on how to make payments using <code>coin</code> module on Sui.</p>
<p>We all know about the <code>ERC20</code> standard in the Ethereum and how it is different from the native <code>eth</code> payments in the solidity contracts. Having 2 different payment currencies poses a lot of problems and excessive work in the solidity ecosystem. To avoid that case, Sui contains the <code>Coin</code> standard and the native SUI currency is also implemented using the same standard. Which means we don't have to write different functions to handle payments of SUI and other tokens.</p>
<p>Below we have a counter contract that accepts the SUI Coin payments.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">/// Module: coin_payments</span>
<span class="hljs-keyword">module</span> coin_payments::coin_payments {
    use sui::sui::SUI;
    use sui::coin::{Self, Coin};
    use sui::balance::{Self, Balance};

    <span class="hljs-keyword">public</span> struct CoinPayments has key {
        id: UID,
        new_fee: u64,
        update_fee: u64,
        balance: Balance&lt;SUI&gt;
    }

    <span class="hljs-keyword">public</span> struct CoinPaymentsCap has key {
        id: UID
    }

    <span class="hljs-keyword">public</span> struct Counter has key,store{
        id: UID,
        val: u64
    }
    <span class="hljs-comment">// Errors</span>
    <span class="hljs-keyword">const</span> ENegativeDecrement: u64 = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">const</span> EInvalidPayment: u64 = <span class="hljs-number">1</span>;

    fun init(ctx: &amp;mut TxContext) {
        transfer::transfer(CoinPaymentsCap {
            id: <span class="hljs-built_in">object</span>::<span class="hljs-keyword">new</span>(ctx)
        }, ctx.sender());
        transfer::share_object(CoinPayments {
            id: <span class="hljs-built_in">object</span>::<span class="hljs-keyword">new</span>(ctx),
            new_fee: <span class="hljs-number">1000</span>,
            update_fee: <span class="hljs-number">100</span>,
            balance: balance::zero&lt;SUI&gt;(),
        })
    }

    #[allow(lint(self_transfer))]
    <span class="hljs-keyword">public</span> fun <span class="hljs-keyword">new</span>(cp: &amp;mut CoinPayments, payment: Coin&lt;SUI&gt;, ctx: &amp;mut TxContext) {
        assert!(cp.new_fee == payment.value(), EInvalidPayment);
        coin::put(&amp;mut cp.balance, payment);    
        transfer::transfer(Counter {
            id: <span class="hljs-built_in">object</span>::<span class="hljs-keyword">new</span>(ctx),
            val:<span class="hljs-number">0</span>
        }, ctx.sender())
    }

    <span class="hljs-keyword">public</span> fun increment(c: &amp;mut Counter, cp: &amp;mut CoinPayments, payment: Coin&lt;SUI&gt;) {
        assert!(cp.update_fee == payment.value(), EInvalidPayment);
        coin::put(&amp;mut cp.balance, payment);
        c.val = c.val + <span class="hljs-number">1</span>
    }

    <span class="hljs-keyword">public</span> fun decrement(c: &amp;mut Counter, cp: &amp;mut CoinPayments, payment: Coin&lt;SUI&gt;) {
        assert!(c.val &gt; <span class="hljs-number">0</span>, ENegativeDecrement);
        assert!(cp.update_fee == payment.value(), EInvalidPayment);
        coin::put(&amp;mut cp.balance, payment);
        c.val = c.val - <span class="hljs-number">1</span>
    }

    <span class="hljs-keyword">public</span> fun val(c: &amp;Counter) :u64 {
        c.val
    }

    <span class="hljs-keyword">public</span> entry fun withdraw(cp: &amp;mut CoinPayments, _: &amp;CoinPaymentsCap, ctx: &amp;mut TxContext) {
        <span class="hljs-keyword">let</span> val = cp.balance.value();
        <span class="hljs-keyword">let</span> payment = coin::take(&amp;mut cp.balance, val, ctx);
        transfer::public_transfer(payment, ctx.sender())
    }

    #[test_only]
    <span class="hljs-keyword">public</span> fun init_for_testing(ctx: &amp;mut TxContext) {
        init(ctx);
    } 
}
</code></pre>
<p>Here we can see that Sui payments are payments are received by receiving <code>Coin&lt;SUI&gt;</code> as an argument with the required value. Unlike the Solidity <code>msg.value</code> as a transaction parameter, we are directly including it as a function argument.</p>
<p>And here if we have a close look, we are using 2 objects and they are <code>Coin</code> and <code>Balance</code>. Coin is the transferable object of the given currency while the <code>Balance</code> is the stored value of it. Here, we are storing the payment received as Balance in the <code>CoinPayments</code> object but transferring it to the user as <code>Coin</code> object.</p>
<p>Now, let us look into the test cases for the above contract.</p>
<pre><code class="lang-typescript">
#[test_only]
<span class="hljs-keyword">module</span> coin_payments::coin_payments_tests {
    use sui::coin;
    use sui::sui::SUI;
    use sui::test_scenario;
    use coin_payments::coin_payments;

    <span class="hljs-keyword">const</span> USER: address = @<span class="hljs-number">0xFACE</span>;
    <span class="hljs-keyword">const</span> ADMIN: address = @<span class="hljs-number">0xCAFE</span>;

    #[test]
    fun test_coin_payments() {
        <span class="hljs-keyword">let</span> mut scenario = test_scenario::begin(ADMIN);
        {
            coin_payments::init_for_testing(scenario.ctx());
        };

        scenario.next_tx(USER);
        {
            <span class="hljs-keyword">let</span> mut cp = test_scenario::take_shared&lt;coin_payments::CoinPayments&gt;(&amp;scenario);
            <span class="hljs-keyword">let</span> c = coin::mint_for_testing&lt;SUI&gt;(<span class="hljs-number">1000</span>, scenario.ctx());
            coin_payments::<span class="hljs-keyword">new</span>(&amp;mut cp, c, scenario.ctx());
            test_scenario::return_shared(cp);
        };

        scenario.next_tx(USER);
        {
            <span class="hljs-keyword">let</span> mut cp = test_scenario::take_shared&lt;coin_payments::CoinPayments&gt;(&amp;scenario);
            <span class="hljs-keyword">let</span> c = coin::mint_for_testing&lt;SUI&gt;(<span class="hljs-number">100</span>, scenario.ctx());

            <span class="hljs-keyword">let</span> mut counter = scenario.take_from_sender&lt;coin_payments::Counter&gt;();
            coin_payments::increment(&amp;mut counter, &amp;mut cp, c);

            scenario.return_to_sender(counter);
            test_scenario::return_shared(cp);
        };

        scenario.next_tx(ADMIN);
        {
            <span class="hljs-keyword">let</span> mut cp = test_scenario::take_shared&lt;coin_payments::CoinPayments&gt;(&amp;scenario);
            <span class="hljs-keyword">let</span> cap = scenario.take_from_sender&lt;coin_payments::CoinPaymentsCap&gt;();

            coin_payments::withdraw(&amp;mut cp, &amp;cap, scenario.ctx());

            scenario.return_to_sender(cap);
            test_scenario::return_shared(cp);
        };

        scenario.end();
    }
}
</code></pre>
<p>Here in the above test cases, we are testing both paying as a user scenario and also withdrawing as the admin scenario.</p>
]]></content:encoded></item><item><title><![CDATA[Sui - Custom Transfer]]></title><description><![CDATA[Hello everyone...
Welcome to another day in exploring Web3 Engineering. In today's blog, let us check out how to write custom transfer method for a Sui object.
A Sui object is usually transferred using the public_transfer from the transfer module in ...]]></description><link>https://blog.jnalam.dev/sui-custom-transfer</link><guid isPermaLink="true">https://blog.jnalam.dev/sui-custom-transfer</guid><category><![CDATA[Sui]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[Smart Contracts]]></category><dc:creator><![CDATA[Jay Nalam]]></dc:creator><pubDate>Mon, 27 May 2024 08:10:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1716795366906/23eba622-7a1a-4319-9090-6aea428a2b19.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone...</p>
<p>Welcome to another day in exploring Web3 Engineering. In today's blog, let us check out how to write custom transfer method for a Sui object.</p>
<p>A Sui object is usually transferred using the <code>public_transfer</code> from the <code>transfer</code> module in the <code>sui</code> package. This function can directly be called from a smart contract or from a PTB as well.</p>
<p>This function doesn't interact with the module that the object is defined and just transfers the ownership of the object without raising any events as well. And we can't control the execution as well. There might be some cases where the developer wants to impose some certain actions while transferring the objects. For example, allowing transfers to only eligible users by the app, imposing some fee for transfer of the NFT etc. For such situations, we can write our own transfer function for the Objects and implement our own logic according to the app.</p>
<p>For a object to be eligible to use the <code>public_transfer</code> function, it must contain the <code>store</code> ability. So, if we create an object which doesn't have <code>store</code>, it can only be transferred using <code>transfer</code> method from the <code>transfer</code> module. The transfer function can only transfer objects that are defined in the same module.</p>
<p>Now, let us write a move smart contract that tracks the number of times that the object is transferred.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">/// Module: custom_transfer</span>
<span class="hljs-keyword">module</span> custom_transfer::custom_transfer {
    use sui::vec_map::{Self, VecMap};

    <span class="hljs-keyword">public</span> struct CustomTransfer has key, store {
        id: UID,
        transfers_count: VecMap&lt;ID, u64&gt;
    }

    fun init(ctx: &amp;mut TxContext) {
        transfer::transfer(CustomTransfer {
            id: <span class="hljs-built_in">object</span>::<span class="hljs-keyword">new</span>(ctx),
            transfers_count: vec_map::empty&lt;ID, u64&gt;()
        }, ctx.sender())
    }

    <span class="hljs-keyword">public</span> struct Asset has key {
        id: UID,
        val: u64
    }

    <span class="hljs-keyword">public</span> fun <span class="hljs-keyword">new</span>(c: &amp;mut CustomTransfer, val: u64, ctx: &amp;mut TxContext) {
        <span class="hljs-keyword">let</span> id = <span class="hljs-built_in">object</span>::<span class="hljs-keyword">new</span>(ctx);
        c.transfers_count.insert(id.to_inner(), <span class="hljs-number">0</span>);
        transfer::transfer(Asset {
            id,
            val
        }, ctx.sender())
    }

    <span class="hljs-comment">// notice: Custom transfer function</span>
    <span class="hljs-keyword">public</span> fun transfer(c: &amp;mut CustomTransfer, asset: Asset, receiver: address) {
       <span class="hljs-keyword">let</span> counter = c.transfers_count.get_mut(&amp;asset.id.to_inner());
        *counter = *counter + <span class="hljs-number">1</span>;
        transfer::transfer(asset, receiver)
    }

    <span class="hljs-keyword">public</span> fun count(c: &amp;CustomTransfer, asset: &amp;Asset): u64 {
        *c.transfers_count.get(&amp;asset.id.to_inner())
    }

    #[test_only]
    <span class="hljs-keyword">public</span> fun init_for_test(ctx: &amp;mut TxContext) {
        init(ctx)
    }
}
</code></pre>
<p>In the above contract, we have the</p>
<ul>
<li><code>CustomTransfer</code> object which will save the transfer counts.</li>
</ul>
<ul>
<li><p><code>Asset</code> object on which we are implementing the custom transfer method.</p>
</li>
<li><p><code>new</code> method which will generate a new <code>Asset</code></p>
</li>
<li><p><code>transfer</code> our custom transfer method, which will increase the transfers count in the <code>CustomTransfer</code> object</p>
</li>
</ul>
<p>Now, let us write the test cases</p>
<pre><code class="lang-typescript">
#[test_only]
<span class="hljs-keyword">module</span> custom_transfer::custom_transfer_tests {
    use sui::test_scenario;
    use custom_transfer::custom_transfer;

    <span class="hljs-keyword">const</span> USER: address = @<span class="hljs-number">0xCAFE</span>;
    <span class="hljs-keyword">const</span> ANOTHER_USER: address = @<span class="hljs-number">0xFACE</span>;

    #[test]
    fun test_custom_transfer() {
        <span class="hljs-keyword">let</span> mut scenario = test_scenario::begin(USER);
        {
            custom_transfer::init_for_test(scenario.ctx());
        };

        scenario.next_tx(USER);
        {
            <span class="hljs-keyword">let</span> mut ct = scenario.take_from_sender&lt;custom_transfer::CustomTransfer&gt;();
            custom_transfer::<span class="hljs-keyword">new</span>(&amp;mut ct, <span class="hljs-number">10</span>, scenario.ctx());
            scenario.return_to_sender(ct);
        };

        scenario.next_tx(USER);
        {
            <span class="hljs-keyword">let</span> mut ct = scenario.take_from_sender&lt;custom_transfer::CustomTransfer&gt;();
            <span class="hljs-keyword">let</span> asset = scenario.take_from_sender&lt;custom_transfer::Asset&gt;();

            <span class="hljs-keyword">let</span> counter = custom_transfer::count(&amp;ct, &amp;asset);
            assert!(counter == <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);

            custom_transfer::transfer(&amp;mut ct, asset, ANOTHER_USER);
            scenario.return_to_sender(ct);
        };

        scenario.next_tx(USER);
        {
            <span class="hljs-keyword">let</span> ct = scenario.take_from_sender&lt;custom_transfer::CustomTransfer&gt;();
            <span class="hljs-keyword">let</span> asset = scenario.take_from_address&lt;custom_transfer::Asset&gt;(ANOTHER_USER);

            <span class="hljs-keyword">let</span> counter = custom_transfer::count(&amp;ct, &amp;asset);
            assert!(counter == <span class="hljs-number">1</span>, <span class="hljs-number">0</span>);

            scenario.return_to_sender(ct);
            test_scenario::return_to_address(ANOTHER_USER, asset);
        };
        scenario.end();
    }
}
</code></pre>
<p>Here we have the test case which will test the increase the count. And also, if we try to use the public_transfer method on the Asset, the move analyzer directly gives us an error message or if it is not installed, we will get an error while compiling the code itself</p>
<p>Full code can be found here: <a target="_blank" href="https://github.com/jveer634/sui_contracts/">https://github.com/jveer634/sui_contracts/</a></p>
<p>Thank you.</p>
]]></content:encoded></item></channel></rss>