<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jaadugar on Medium]]></title>
        <description><![CDATA[Stories by Jaadugar on Medium]]></description>
        <link>https://medium.com/@jaadugar117?source=rss-efceeb706755------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1-tWzofJXQq-jvtrMl8b_A.jpeg</url>
            <title>Stories by Jaadugar on Medium</title>
            <link>https://medium.com/@jaadugar117?source=rss-efceeb706755------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:33:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaadugar117/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kalp DLT Airdrop Fails? Understanding Chaincode State Isolation and Batch Transfers]]></title>
            <link>https://medium.com/kalpstudio/kalp-dlt-airdrop-fails-understanding-chaincode-state-isolation-and-batch-transfers-a59c23a46ec7?source=rss-efceeb706755------2</link>
            <guid isPermaLink="false">https://medium.com/p/a59c23a46ec7</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[kalp-studio]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[hyperledger-fabric]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jaadugar]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 05:33:41 GMT</pubDate>
            <atom:updated>2025-02-07T05:33:41.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Kalp DLT Airdrop Fails? Understanding Chaincode State Isolation and Batch Transfers" src="https://cdn-images-1.medium.com/max/1024/1*0Hv1Oo8N2wTR9Csd_7lDZg.png" /></figure><h3>Introduction</h3><p>When implementing an airdrop function for an ERC20-equivalent chaincode on <strong>Kalp DLT</strong>, we encountered major challenges due to how <strong>Kalp DLT </strong>(Hyperledger Fabric under the hood) <strong>handles chaincode-to-chaincode transactions</strong>. The initial goal was to efficiently distribute <strong>3 million tokens</strong> to users, reducing transaction execution time while ensuring correctness.</p><p>Our initial approach was to create an <strong>Airdrop chaincode</strong> that would loop through recipients and call the TransferFrom function for each user <strong>within a single transaction</strong>. However, this led to unexpected balance calculation issues.</p><h4>Initial Implementation of TransferFrom on KRC20 Token Contract</h4><pre>// TransferFrom transfers the value amount from the &quot;from&quot; address to the &quot;to&quot; address<br>// This function triggers a Transfer event<br>func (s *SmartContract) TransferFrom(sdk kalpsdk.TransactionContextInterface, from string, to string, value int) error {<br>    // Check if contract has been intilized first<br>    initialized, err := checkInitialized(sdk)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to check if contract is already initialized: %v&quot;, err)<br>    }<br>    if !initialized {<br>        return fmt.Errorf(&quot;contract options need to be set before calling any function, call Initialize() to initialize contract&quot;)<br>    }<br>    // Get ID of submitting client identity<br>    spender, err := sdk.GetUserID()<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to get client id: %v&quot;, err)<br>    }<br>    // Create allowanceKey<br>    allowanceKey, err := sdk.CreateCompositeKey(allowancePrefix, []string{from, spender})<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to create the composite key for prefix %s: %v&quot;, allowancePrefix, err)<br>    }<br>    // Retrieve the allowance of the spender<br>    currentAllowanceBytes, err := sdk.GetState(allowanceKey)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to retrieve the allowance for %s from world state: %v&quot;, allowanceKey, err)<br>    }<br>    var currentAllowance int<br>    currentAllowance, _ = strconv.Atoi(string(currentAllowanceBytes)) // Error handling not needed since Itoa() was used when setting the totalSupply, guaranteeing it was an integer.<br>    // Check if transferred value is less than allowance<br>    if currentAllowance &lt; value {<br>        return fmt.Errorf(&quot;spender does not have enough allowance for transfer&quot;)<br>    }<br>    // Initiate the transfer<br>    err = transferHelper(sdk, from, to, value)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to transfer: %v&quot;, err)<br>    }<br>    // Decrease the allowance<br>    updatedAllowance, err := sub(currentAllowance, value)<br>    if err != nil {<br>        return err<br>    }<br>    err = sdk.PutStateWithoutKYC(allowanceKey, []byte(strconv.Itoa(updatedAllowance)))<br>    if err != nil {<br>        return err<br>    }<br>    // Emit the Transfer event<br>    transferEvent := event{from, to, value}<br>    transferEventJSON, err := json.Marshal(transferEvent)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to obtain JSON encoding: %v&quot;, err)<br>    }<br>    err = sdk.SetEvent(&quot;Transfer&quot;, transferEventJSON)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to set event: %v&quot;, err)<br>    }<br>    log.Printf(&quot;spender %s allowance updated from %d to %d&quot;, spender, currentAllowance, updatedAllowance)<br>    return nil<br>}</pre><h4>Initial Implementation of Airdrop on Airdrop Contract</h4><pre>// Airdrop takes an array of recipients, an array of amounts, and calls TransferFrom(minter, recipient, amount)<br>// on the specified ERC20 chaincode. Both arrays must have the same length.<br>func (a *AirdropSmartContract) Airdrop(ctx kalpsdk.TransactionContextInterface, recipients []string, amounts []int) error {<br>    // Ensure contract is initialized<br>    init, err := isAirdropInitialized(ctx)<br>    if err != nil {<br>        return err<br>    }<br>    if !init {<br>        return fmt.Errorf(&quot;airdrop contract not yet initialized, call Initialize() first&quot;)<br>    }<br>    // Check that the caller is the airdrop minter<br>    err = checkAirdropMinter(ctx)<br>    if err != nil {<br>        return err<br>    }<br>    // Basic length checks<br>    if len(recipients) != len(amounts) {<br>        return fmt.Errorf(&quot;recipients and amounts must have the same length&quot;)<br>    }<br>    if len(recipients) == 0 {<br>        return fmt.Errorf(&quot;no recipients provided&quot;)<br>    }<br>    // Retrieve the minter address from ledger<br>    minterBytes, err := ctx.GetState(airdropMinterKey)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to retrieve airdrop minter from ledger: %v&quot;, err)<br>    }<br>    if minterBytes == nil {<br>        return fmt.Errorf(&quot;airdrop minter not set&quot;)<br>    }<br>    minter := string(minterBytes)<br>    // Retrieve the token chaincode name<br>    tokenCCBytes, err := ctx.GetState(tokenChaincodeNameKey)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to retrieve token chaincode name: %v&quot;, err)<br>    }<br>    if tokenCCBytes == nil {<br>        return fmt.Errorf(&quot;token chaincode name not set&quot;)<br>    }<br>    tokenCC := string(tokenCCBytes)<br>    // Log operation<br>    log.Printf(&quot;[Airdrop] Start airdrop from minter [%s] to %d recipients on tokenCC [%s]&quot;, minter, len(recipients), tokenCC)<br>    // For each recipient, call TransferFrom(minter, recipient, amount)<br>    for i, recipient := range recipients {<br>        amount := amounts[i]<br>        // Prepare arguments for TransferFrom in the token chaincode:<br>        //   TransferFrom(ctx, from string, to string, value int) error<br>        // When we invoke cross-chaincode, arguments are always strings.<br>        args := [][]byte{<br>            []byte(&quot;TransferFrom&quot;),<br>            []byte(minter),<br>            []byte(recipient),<br>            []byte(strconv.Itoa(amount)),<br>        }<br>        // Use the Fabric stub under kalpsdk to invoke the other chaincode<br>        response := ctx.InvokeChaincode(tokenCC, args, ctx.GetChannelID())<br>        if response.GetStatus() != 200 {<br>            return fmt.Errorf(&quot;failed to invoke TransferFrom for recipient %s, error: %s&quot;, recipient, response.GetMessage())<br>        }<br>    }<br>    log.Printf(&quot;[Airdrop] Successfully sent tokens to %d recipients&quot;, len(recipients))<br>    return nil<br>}</pre><h3>The First Problem: Incorrect Admin Wallet Balance Updates</h3><p>During testing, we transferred tokens from an <strong>admin wallet (A)</strong> to two different wallets (B and C). However, we observed that:</p><ul><li>The <strong>admin balance was not deducted correctly</strong>.</li><li>The <strong>allowance for the admin wallet was not updated properly</strong>.</li><li>The final deduction from the admin’s balance was <strong>only the last amount in the array</strong>.</li></ul><h4>Example Case</h4><p><strong>A (Admin Wallet) sends:</strong></p><ul><li>1 token to B</li><li>2 tokens to C</li><li>Expected Deduction: 3 tokens</li><li><strong>Actual Deduction: </strong><strong>2 tokens</strong></li></ul><h4>Why This Happens</h4><p>When you invoke TransferFrom in a loop from another chaincode (<strong>Airdrop contract</strong>), Kalp DLT does <strong>not</strong> automatically re-read the “in-memory” updates of the minter’s balance on each sub-invocation. Each call to the ERC20 chaincode sees the <strong>original balance</strong> of the minter rather than the updated balance from prior iterations. As a result, the minter’s balance <strong>only decreases once</strong> for the entire loop instead of per recipient.</p><p><strong>Root Cause: Kalp DLT’s Transaction Isolation</strong></p><p>Kalp DLT treats <strong>chaincode-to-chaincode calls within a transaction as logically isolated</strong>:</p><ul><li>Each stub.InvokeChaincode(...) starts from the <strong>same ledger snapshot</strong>.</li><li>Updates performed in early iterations are <strong>not visible</strong> in subsequent calls <strong>within the same transaction</strong>.</li></ul><h3>Crossing the First Hurdle: Fixing the Admin Balance Issue</h3><h4>Two Possible Fixes</h4><ol><li><strong>Server-Side Fix:</strong> Instead of using the Airdrop contract, call TransferFrom <strong>separately for each transaction</strong>.</li><li><strong>Batch Processing:</strong> Implement a BatchTransferFrom function inside the <strong>ERC20 chaincode</strong> to handle multiple transfers in <strong>one function call</strong>.</li></ol><p><strong>Chosen Solution: BatchTransferFrom</strong></p><p>Instead of multiple TransferFrom calls, we introduced a <strong>batch transfer function</strong> inside the ERC20 contract. This function:</p><ul><li><strong>Summed up</strong> all amounts before updating the <strong>admin’s balance and allowance</strong>.</li><li>Ensured only <strong>one </strong><strong>.PutStateWithoutKyc() call</strong> updated the minter’s balance.</li></ul><h4>Implementation: BatchTransferFrom Function</h4><pre>// BatchTransferFrom transfers tokens from one address (&quot;from&quot;) to multiple recipients<br>// in a single transaction. Each recipient i gets amounts[i] tokens.<br>// All recipients and amounts are processed atomically. If any check fails<br>// (e.g., insufficient allowance, insufficient balance, negative amounts), the entire<br>// transaction is rolled back and no transfers occur.<br>//<br>// This function triggers a Transfer event for each transfer in the batch.<br>func (s *SmartContract) BatchTransferFrom(<br>    sdk kalpsdk.TransactionContextInterface,<br>    from string,<br>    recipients []string,<br>    amounts []int,<br>) error {<br>    // 1. Check if contract is initialized<br>    initialized, err := checkInitialized(sdk)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to check if contract is initialized: %v&quot;, err)<br>    }<br>    if !initialized {<br>        return fmt.Errorf(&quot;contract options need to be set before calling any function, call Initialize() to initialize contract&quot;)<br>    }<br><br>    // 2. Get the ID of the caller (spender)<br>    spender, err := sdk.GetUserID()<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to get caller user ID: %v&quot;, err)<br>    }<br><br>    // 3. Validate input arrays<br>    if len(recipients) != len(amounts) {<br>        return fmt.Errorf(&quot;recipients and amounts must have the same length&quot;)<br>    }<br>    if len(recipients) == 0 {<br>        return fmt.Errorf(&quot;no recipients provided&quot;)<br>    }<br><br>    // 4. Create allowance key (owner=from, spender=caller)<br>    allowanceKey, err := sdk.CreateCompositeKey(allowancePrefix, []string{from, spender})<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to create composite key for allowance: %v&quot;, err)<br>    }<br><br>    // 5. Retrieve the current allowance<br>    allowanceBytes, err := sdk.GetState(allowanceKey)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to retrieve allowance for %s: %v&quot;, allowanceKey, err)<br>    }<br>    if allowanceBytes == nil {<br>        return fmt.Errorf(&quot;no allowance set for spender [%s]&quot;, spender)<br>    }<br>    currentAllowance, _ := strconv.Atoi(string(allowanceBytes))<br><br>    // 6. Retrieve &#39;from&#39; balance<br>    fromBalanceBytes, err := sdk.GetState(from)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to retrieve balance for %s: %v&quot;, from, err)<br>    }<br>    if fromBalanceBytes == nil {<br>        return fmt.Errorf(&quot;the account %s does not exist or has no balance&quot;, from)<br>    }<br>    fromBalance, _ := strconv.Atoi(string(fromBalanceBytes))<br><br>    // 7. Sum up all amounts to transfer<br>    var totalTransfer int<br>    for _, amt := range amounts {<br>        if amt &lt; 0 {<br>            return fmt.Errorf(&quot;amount cannot be negative: %d&quot;, amt)<br>        }<br>        totalTransfer, err = add(totalTransfer, amt)<br>        if err != nil {<br>            return fmt.Errorf(&quot;overflow in amounts sum: %v&quot;, err)<br>        }<br>    }<br><br>    // 8. Check if &#39;from&#39; has enough balance and spender has enough allowance<br>    if fromBalance &lt; totalTransfer {<br>        return fmt.Errorf(&quot;account [%s] balance (%d) is insufficient for total transfer of %d&quot;, from, fromBalance, totalTransfer)<br>    }<br>    if currentAllowance &lt; totalTransfer {<br>        return fmt.Errorf(&quot;spender [%s] allowance (%d) is insufficient for total transfer of %d&quot;, spender, currentAllowance, totalTransfer)<br>    }<br><br>    // 9. Deduct the total from &#39;from&#39; balance<br>    newFromBalance, err := sub(fromBalance, totalTransfer)<br>    if err != nil {<br>        return fmt.Errorf(&quot;error subtracting totalTransfer from &#39;from&#39; balance: %v&quot;, err)<br>    }<br><br>    // 10. Deduct the total from allowance<br>    newAllowance, err := sub(currentAllowance, totalTransfer)<br>    if err != nil {<br>        return fmt.Errorf(&quot;error subtracting totalTransfer from current allowance: %v&quot;, err)<br>    }<br><br>    // 11. Update &#39;from&#39; balance and allowance in the ledger<br>    err = sdk.PutStateWithoutKYC(from, []byte(strconv.Itoa(newFromBalance)))<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to update balance of [%s]: %v&quot;, from, err)<br>    }<br>    err = sdk.PutStateWithoutKYC(allowanceKey, []byte(strconv.Itoa(newAllowance)))<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to update allowance key [%s]: %v&quot;, allowanceKey, err)<br>    }<br><br>    // 12. For each recipient, increment their balance and emit Transfer event<br>    for i, recipient := range recipients {<br>        amount := amounts[i]<br>        if from == recipient {<br>            return fmt.Errorf(&quot;cannot transfer to the same account [%s]&quot;, from)<br>        }<br>        // Retrieve recipient balance<br>        toBalanceBytes, err := sdk.GetState(recipient)<br>        if err != nil {<br>            return fmt.Errorf(&quot;failed to retrieve balance for recipient [%s]: %v&quot;, recipient, err)<br>        }<br>        var toBalance int<br>        if toBalanceBytes == nil {<br>            // if no balance record yet, assume 0<br>            toBalance = 0<br>        } else {<br>            toBalance, _ = strconv.Atoi(string(toBalanceBytes))<br>        }<br>        // add amount to recipient<br>        updatedToBalance, err := add(toBalance, amount)<br>        if err != nil {<br>            return fmt.Errorf(&quot;failed to add amount to recipient [%s]: %v&quot;, recipient, err)<br>        }<br>        // update recipient balance<br>        err = sdk.PutStateWithoutKYC(recipient, []byte(strconv.Itoa(updatedToBalance)))<br>        if err != nil {<br>            return fmt.Errorf(&quot;failed to update balance of recipient [%s]: %v&quot;, recipient, err)<br>        }<br>        // emit Transfer event for each individual transfer<br>        transferEvent := event{From: from, To: recipient, Value: amount}<br>        transferEventJSON, err := json.Marshal(transferEvent)<br>        if err != nil {<br>            return fmt.Errorf(&quot;failed to JSON-encode Transfer event: %v&quot;, err)<br>        }<br>        err = sdk.SetEvent(&quot;Transfer&quot;, transferEventJSON)<br>        if err != nil {<br>            return fmt.Errorf(&quot;failed to set Transfer event: %v&quot;, err)<br>        }<br>    }<br>    // Log final result<br>    log.Printf(&quot;BatchTransferFrom: spender [%s], from [%s] -&gt; %d recipients, total = %d. New from balance = %d, new allowance = %d&quot;,<br>        spender, from, len(recipients), totalTransfer, newFromBalance, newAllowance)<br>    return nil<br>}</pre><h4>Revised implementation: Airdrop Function</h4><pre>// Airdrop takes an array of recipients, an array of amounts, and calls the<br>// new &quot;BatchTransferFrom&quot; function on the ERC20 token chaincode *once*.<br>// This ensures the from-balance is properly decremented for the total sum.<br>func (a *AirdropSmartContract) Airdrop(ctx kalpsdk.TransactionContextInterface, recipients []string, amounts []int) error {<br>    // 1) Ensure Airdrop contract is initialized<br>    init, err := isAirdropInitialized(ctx)<br>    if err != nil {<br>        return err<br>    }<br>    if !init {<br>        return fmt.Errorf(&quot;airdrop contract not yet initialized, call Initialize() first&quot;)<br>    }<br><br>    // 2) Check that the caller is the airdrop minter<br>    err = checkAirdropMinter(ctx)<br>    if err != nil {<br>        return err<br>    }<br><br>    // 3) Basic length checks<br>    if len(recipients) != len(amounts) {<br>        return fmt.Errorf(&quot;recipients and amounts must have the same length&quot;)<br>    }<br>    if len(recipients) == 0 {<br>        return fmt.Errorf(&quot;no recipients provided&quot;)<br>    }<br><br>    // 4) Retrieve the minter address from ledger (this is the &quot;from&quot; address)<br>    minterBytes, err := ctx.GetState(airdropMinterKey)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to retrieve airdrop minter from ledger: %v&quot;, err)<br>    }<br>    if minterBytes == nil {<br>        return fmt.Errorf(&quot;airdrop minter not set&quot;)<br>    }<br>    minter := string(minterBytes)<br><br>    // 5) Retrieve the token chaincode name<br>    tokenCCBytes, err := ctx.GetState(tokenChaincodeNameKey)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to retrieve token chaincode name: %v&quot;, err)<br>    }<br>    if tokenCCBytes == nil {<br>        return fmt.Errorf(&quot;token chaincode name not set&quot;)<br>    }<br>    tokenCC := string(tokenCCBytes)<br><br>    // 6) Log operation<br>    log.Printf(&quot;[Airdrop] Start airdrop from minter [%s] to %d recipients on tokenCC [%s]&quot;, minter, len(recipients), tokenCC)<br>   <br>    // -------------------------------------------------------------------------<br>    // 7) Instead of calling TransferFrom(...) in a loop, we call *BatchTransferFrom*<br>    //    once, passing the from (minter), recipients array, and amounts array.<br>    // -------------------------------------------------------------------------<br>    // The BatchTransferFrom signature from the ERC20 contract is:<br>    //   func (s *SmartContract) BatchTransferFrom(<br>    //       sdk kalpsdk.TransactionContextInterface,<br>    //       from string,<br>    //       recipients []string,<br>    //       amounts []int<br>    //   ) error<br>    // The chaincode invocation arguments must be in [][]byte form, e.g.:<br>    //   [&quot;BatchTransferFrom&quot;, from, recipientsJSON, amountsJSON]<br>    // Where recipientsJSON and amountsJSON are JSON-encoded arrays if you want the<br>    // target method to accept []string and []int.<br>    // Convert recipients and amounts to JSON (common approach)<br>    recipientsJSON, err := json.Marshal(recipients)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to JSON-encode recipients array: %v&quot;, err)<br>    }<br>    amountsJSON, err := json.Marshal(amounts)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to JSON-encode amounts array: %v&quot;, err)<br>    }<br>    // Build args<br>    args := [][]byte{<br>        []byte(&quot;BatchTransferFrom&quot;),<br>        []byte(minter),<br>        recipientsJSON,<br>        amountsJSON,<br>    }<br>    // Invoke the ERC20 chaincode once<br>    response := ctx.InvokeChaincode(tokenCC, args, ctx.GetChannelID())<br>    if response.GetStatus() != 200 {<br>        return fmt.Errorf(&quot;batch transfer failed for recipients %v, error: %s&quot;, recipients, response.GetMessage())<br>    }<br><br>    // 8) If we reach here, the batch transfer succeeded<br>    log.Printf(&quot;[Airdrop] Successfully completed batch airdrop to %d recipients&quot;, len(recipients))<br>    return nil<br>}</pre><p>This resolved the <strong>admin wallet balance and allowance issues</strong>. However, a new problem arose…</p><h3>The Second Problem: Incorrect Token Distribution for Duplicate Recipients</h3><p>When testing with <strong>duplicate recipients</strong>, we noticed:</p><ul><li>If a recipient appeared <strong>multiple times</strong> in the array, they would <strong>only receive the last iteration’s amount</strong>.</li></ul><h4>Example Case</h4><pre>Recipients = [B, C, D, B]<br>Amounts = [1, 2, 1, 3]<br>Expected Balance for B = 1 + 3 = 4 tokens<br>Actual Balance for B = 3 tokens (incorrect)</pre><h4>Why This Happens</h4><p>Again, due to Kalp DLT’s <strong>transaction isolation</strong>, when PutStateWithoutKyc updated the <strong>first instance of B</strong>, the next GetState(B) still returned the <strong>original balance</strong>, not the <strong>updated</strong> one.</p><h3>Crossing the Second Hurdle: Handling Duplicate Recipients</h3><h4>Solution: Consolidate Duplicate Recipients</h4><p>To fix this, we introduced a <strong>helper function</strong> combineDuplicateRecipients() that:</p><ol><li><strong>Aggregates duplicate amounts</strong> in a hashmap.</li><li>Returns <strong>unique recipients</strong> and their <strong>summed amounts</strong>.</li></ol><h4>Implementation: Helper Function</h4><pre>// combineDuplicateRecipients scans through recipients[] and amounts[],<br>// consolidating duplicates into a single recipient entry with the sum of amounts.<br>// Example:<br>//<br>//    recipients = [A, B, A, C], amounts = [10, 5, 7, 2]<br>//    =&gt; uniqueRecipients = [A, B, C], combinedAmounts = [17, 5, 2]<br>func combineDuplicateRecipients(recipients []string, amounts []int) ([]string, []int, error) {<br>    if len(recipients) != len(amounts) {<br>        return nil, nil, fmt.Errorf(&quot;mismatched length between recipients and amounts&quot;)<br>    }<br>    // We&#39;ll keep a map from &quot;recipient -&gt; aggregated amount&quot;<br>    aggregate := make(map[string]int)<br>    // We&#39;ll also keep a slice to track the order of first occurrence<br>    var uniqueOrder []string<br>    for i, r := range recipients {<br>        amt := amounts[i]<br>        // If it&#39;s a new recipient, track the order<br>        if _, exists := aggregate[r]; !exists {<br>            uniqueOrder = append(uniqueOrder, r)<br>        }<br>        // Accumulate the amount for that recipient<br>        aggregate[r] = aggregate[r] + amt<br>    }<br>    // Now we build the final slices in that order<br>    uniqueRecipients := make([]string, len(uniqueOrder))<br>    combinedAmounts := make([]int, len(uniqueOrder))<br>    for i, r := range uniqueOrder {<br>        uniqueRecipients[i] = r<br>        combinedAmounts[i] = aggregate[r]<br>    }<br>    return uniqueRecipients, combinedAmounts, nil<br>}</pre><h4>Updated BatchTransferFrom with Fix</h4><pre>uniqueRecipients, combinedAmounts, _ := combineDuplicateRecipients(recipients, amounts)<br>// Process transfers using uniqueRecipients and combinedAmounts</pre><p>With this fix, <strong>duplicate recipients</strong> now receive the <strong>correct total amount</strong>.</p><h3>Conclusion: Key Takeaways</h3><p><strong>1. Kalp DLT’s chaincode-to-chaincode transactions</strong> do not share <strong>ephemeral state updates</strong>.</p><p><strong>2. Ledger reads always return the original transaction snapshot</strong> unless the transaction is committed.</p><p><strong>3. BatchTransferFrom</strong> ensures that:</p><ul><li>The <strong>minter’s balance and allowance</strong> update correctly.</li><li>Token transfers occur <strong>efficiently</strong> in a single transaction.</li></ul><p><strong>4. Handling duplicate recipients</strong> prevents miscalculations in token distribution.</p><h4>Final Advice</h4><p>If you are working with <strong>cross-chaincode transactions in Kalp DLT</strong>, be aware of:</p><ul><li><strong>How state updates work within a transaction.</strong></li><li><strong>Potential pitfalls with loops in chaincode.</strong></li><li><strong>How to optimize batch operations for efficiency and correctness.</strong></li></ul><p>🚀 <strong>Be careful out there!</strong></p><h3>TL;DR</h3><ul><li><strong>Issue:</strong> TransferFrom inside a loop only deducted the last amount due to Kalp DLT’s transaction isolation.</li><li><strong>Fix:</strong> Implemented <strong>BatchTransferFrom</strong> to handle multiple recipients in <strong>one function call</strong>.</li><li><strong>New Problem:</strong> Duplicate recipients did not receive correct sums.</li><li><strong>Fix:</strong> Added combineDuplicateRecipients() to merge amounts for the same recipient.</li><li><strong>Lesson:</strong> Always consider <strong>how state updates behave within transactions</strong> in Kalp DLT.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59c23a46ec7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kalpstudio/kalp-dlt-airdrop-fails-understanding-chaincode-state-isolation-and-batch-transfers-a59c23a46ec7">Kalp DLT Airdrop Fails? Understanding Chaincode State Isolation and Batch Transfers</a> was originally published in <a href="https://medium.com/kalpstudio">kalpstudio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading Smart Contracts: A Guide to Proxy Contracts and Solidity Patterns]]></title>
            <link>https://medium.com/kalpstudio/upgrading-smart-contracts-a-guide-to-proxy-contracts-and-solidity-patterns-3124543dbd95?source=rss-efceeb706755------2</link>
            <guid isPermaLink="false">https://medium.com/p/3124543dbd95</guid>
            <category><![CDATA[upgradable-contracts]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Jaadugar]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 11:49:15 GMT</pubDate>
            <atom:updated>2024-11-13T12:25:06.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDfqnkFblNPFu2r0ygKdug.png" /></figure><p>In the rapidly evolving world of blockchain, the ability to upgrade smart contracts is essential for maintaining security, adding features, and fixing bugs. Unlike traditional software, smart contracts deployed on a blockchain are immutable by default, meaning they cannot be modified after deployment. However, upgradeable contracts offer a workaround that allows developers to make essential updates.</p><h3>1. What Are Upgradeable Contracts?</h3><p><strong>Upgradeable contracts</strong> are smart contracts designed to allow modifications after deployment. Instead of deploying an entirely new contract whenever changes are needed, upgradeable contracts use a <strong>proxy pattern</strong> to separate the contract’s logic from its storage. This separation enables developers to update contract logic without affecting the data stored on-chain.</p><h3>2. How Do Upgradeable Contracts Work?</h3><p>Upgradeable contracts typically rely on a <strong>proxy contract</strong> and an <strong>implementation contract</strong>. The proxy contract holds the contract state (storage) and forwards function calls to the implementation contract. When an upgrade is required, the implementation contract can be replaced with a new version, while the proxy contract and storage remain intact.</p><p>Key Components:</p><ul><li><strong>Proxy Contract</strong>: The contract users interact with. It contains storage and delegates function calls to the implementation.</li><li><strong>Implementation Contract</strong>: The logic contract that the proxy delegates to. This contract can be updated by pointing the proxy to a new version.</li></ul><p>The <strong>delegatecall</strong> opcode in Solidity is crucial here; it allows the proxy to execute functions in the context of the implementation contract while maintaining its own storage layout.</p><h3>3. Writing Your First Upgradeable Contract</h3><p>Here’s a simple example of a basic upgradeable contract using the proxy pattern. In this example, we’ll create two contracts: a Proxy contract and an Implementation contract.</p><p>Step 1: Proxy Contract</p><p>The proxy contract contains the state and forwards calls to the implementation contract.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Proxy {<br>    address public implementation;<br>    constructor(address _implementation) {<br>        implementation = _implementation;<br>    }<br>    fallback() external payable {<br>        address impl = implementation;<br>        require(impl != address(0));<br>        <br>        assembly {<br>            let ptr := mload(0x40)<br>            calldatacopy(ptr, 0, calldatasize())<br>            let result := delegatecall(gas(), impl, ptr, calldatasize(), 0, 0)<br>            let size := returndatasize()<br>            returndatacopy(ptr, 0, size)<br>            switch result<br>            case 0 { revert(ptr, size) }<br>            default { return(ptr, size) }<br>        }<br>    }<br>    function upgrade(address _newImplementation) external {<br>        implementation = _newImplementation;<br>    }<br>}</pre><p>Step 2: Initial Implementation Contract</p><p>The initial logic contract might contain a simple function to store and retrieve a value.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract ImplementationV1 {<br>    uint public value;<br>    function setValue(uint _value) public {<br>        value = _value;<br>    }<br>}</pre><p>Step 3: Upgraded Implementation Contract</p><p>If you want to add new features, deploy an updated version of the Implementation contract and point the proxy to it.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract ImplementationV2 {<br>    uint public value;<br>    function setValue(uint _value) public {<br>        value = _value;<br>    }<br>    function doubleValue() public {<br>        value *= 2;<br>    }<br>}</pre><p>To upgrade, you would call upgrade on the proxy contract, passing in the new implementation’s address. The proxy will now delegate calls to ImplementationV2, making doubleValue() available without affecting stored values.</p><h3>4. Using OpenZeppelin’s Upgradeable Contracts</h3><p><strong>OpenZeppelin</strong> provides a battle-tested library for creating upgradeable contracts, significantly simplifying the process. OpenZeppelin’s contracts handle the complexity of proxy patterns and offer best practices for security and usability.</p><p>Installing OpenZeppelin Upgradeable Contracts</p><p>You can use OpenZeppelin’s library for upgradeable contracts as follows:</p><pre>npm install @openzeppelin/contracts-upgradeable</pre><p>Using OpenZeppelin’s Upgradeable Proxy</p><p>Here’s how you can create an upgradeable contract with OpenZeppelin.</p><h4><strong>Define Your Initial Implementation Contract</strong>:</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>import &quot;@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol&quot;;<br><br>contract MyUpgradeableContract is Initializable {<br>       uint256 public value;<br>       function initialize(uint256 _value) public initializer {<br>           value = _value;<br>       }<br>       function setValue(uint256 _value) public {<br>           value = _value;<br>       }<br>   }</pre><h4><strong>Deploy and Upgrade with OpenZeppelin’s Plugin</strong>:</h4><p>OpenZeppelin’s upgrades plugin for Hardhat or Truffle can automate the deployment and upgrade process.</p><p><strong>Hardhat Setup</strong>:</p><pre>npm install @openzeppelin/hardhat-upgrades</pre><p><strong>Deploy Script</strong>:</p><pre>const { ethers, upgrades } = require(&quot;hardhat&quot;);<br><br>async function main() {<br>    const MyUpgradeableContract = await ethers.getContractFactory(&quot;MyUpgradeableContract&quot;);<br>    const instance = await upgrades.deployProxy(MyUpgradeableContract, [42], { initializer: &#39;initialize&#39; });<br>    console.log(&quot;Contract deployed to:&quot;, instance.address);<br>}<br>main();</pre><p>To upgrade, you would use upgrades.upgradeProxy with the new implementation.</p><h4><strong>Security and Storage Considerations</strong>:</h4><p>OpenZeppelin’s library ensures storage layout consistency and uses initializer functions to prevent re-initialization, reducing the risk of storage corruption during upgrades.</p><h3>Additional Topics to Consider</h3><h4><strong>Security Best Practices</strong></h4><p>When implementing upgradeable contracts, always consider security implications. Improper upgrades can lead to broken functionality or data loss, so it’s essential to test thoroughly and limit upgrade permissions to trusted entities.</p><h4><strong>Storage Layout and Compatibility</strong></h4><p>When adding new variables in an upgraded contract, ensure they are added at the end of the storage layout. Modifying existing variables or inserting new ones in between can corrupt storage, leading to unexpected behaviors.</p><h4><strong>Alternatives to Proxy Patterns</strong></h4><p>While proxy patterns are popular, there are alternative approaches to upgrading contracts, such as <strong>metamorphic contracts</strong> and <strong>eternal storage patterns</strong>. However, proxies are the most widely adopted due to their simplicity and support from libraries like OpenZeppelin.</p><h3>Conclusion</h3><p>Upgradeable contracts offer a powerful way to keep your smart contracts flexible and future-proof. By using proxy patterns and OpenZeppelin’s upgradeable libraries, developers can deploy contracts that are both secure and adaptable to evolving requirements. Whether you’re adding new features, fixing bugs, or enhancing functionality, understanding upgradeable patterns is an essential skill for Solidity developers.</p><h3>Additional Resources</h3><p>For further learning on upgradeable contracts and Solidity proxy patterns, here are some essential resources:</p><ol><li><a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/"><strong>OpenZeppelin Documentation on Upgrades</strong></a><br>OpenZeppelin’s official documentation on upgradeable contracts, covering installation, implementation, and best practices for secure upgrades.</li><li><a href="https://eips.ethereum.org/EIPS/eip-1822"><strong>Ethereum Improvement Proposal (EIP) 1822 — Universal Upgradeable Proxy Standard (UUPS)</strong></a><br>The EIP for UUPS proxies, a common proxy pattern that defines upgradeability standards for Solidity contracts.</li><li><a href="https://blog.openzeppelin.com/proxy-patterns/"><strong>OpenZeppelin Proxy Patterns Guide</strong></a><br>A comprehensive overview by OpenZeppelin of the different proxy patterns in Solidity, including the pros and cons of each approach.</li><li><a href="https://consensys.github.io/smart-contract-best-practices/"><strong>Ethereum Smart Contract Security Best Practices</strong></a><br>A guide by ConsenSys that includes tips for ensuring the security of upgradeable contracts and other best practices for Solidity development.</li><li><a href="https://docs.soliditylang.org/en/latest/"><strong>Solidity Documentation</strong></a><br>The official Solidity documentation, which covers advanced topics, including delegatecall and proxy patterns for more experienced developers.</li><li><a href="https://github.com/ethereumbook/ethereumbook"><strong>Mastering Ethereum by Andreas M. Antonopoulos and Gavin Wood</strong></a><br>This book covers foundational concepts in Ethereum and smart contract development, including proxy patterns for upgradeability.</li><li><a href="https://hardhat.org/plugins/"><strong>Hardhat Plugins for Contract Upgrades</strong></a><br>Hardhat’s plugin page, where you can find plugins like @openzeppelin/hardhat-upgrades that simplify the process of deploying and managing upgradeable contracts.</li><li><a href="https://www.youtube.com/c/DappUniversity"><strong>Dapp University YouTube Channel</strong></a><br>Dapp University frequently covers upgradeable contracts, including tutorials on using OpenZeppelin proxies with Hardhat and Truffle.</li><li><a href="https://cryptozombies.io/"><strong>CryptoZombies Lesson on Solidity Patterns</strong></a><br>CryptoZombies is an interactive platform that offers fun Solidity lessons, including advanced topics like proxies and upgradeability.</li><li><a href="https://ethereum.stackexchange.com/"><strong>Ethereum Stack Exchange</strong></a><br>A community-driven Q&amp;A site where you can find answers to specific questions about upgradeable contracts, proxy patterns, and best practices in Solidity.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3124543dbd95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kalpstudio/upgrading-smart-contracts-a-guide-to-proxy-contracts-and-solidity-patterns-3124543dbd95">Upgrading Smart Contracts: A Guide to Proxy Contracts and Solidity Patterns</a> was originally published in <a href="https://medium.com/kalpstudio">kalpstudio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Solidity Events: Building Blockchain Event Listeners for Real-time Notifications]]></title>
            <link>https://medium.com/kalpstudio/mastering-solidity-events-building-blockchain-event-listeners-for-real-time-notifications-accc95619f35?source=rss-efceeb706755------2</link>
            <guid isPermaLink="false">https://medium.com/p/accc95619f35</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain-event]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jaadugar]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 07:58:11 GMT</pubDate>
            <atom:updated>2024-11-06T07:58:11.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Solidity Blockchain Events" src="https://cdn-images-1.medium.com/max/1024/1*M3bHAwFz57tnH-ltTxACNg.png" /></figure><p>In Ethereum smart contract development, <strong>events</strong> and <strong>event listeners</strong> play a crucial role in enabling real-time interactions between on-chain activities and off-chain applications. By understanding and implementing these tools, developers can create responsive decentralized applications (dApps) that interact seamlessly with the blockchain.</p><h3>1. What Are Event Listeners?</h3><p><strong>Event listeners</strong> are components in an off-chain environment, typically within a dApp, that monitor and respond to specific events emitted by a smart contract. In Solidity, events serve as a log mechanism, recording specific actions or changes in the blockchain. When an event is emitted, an off-chain application can detect it and trigger corresponding actions, such as updating a user interface or sending notifications.</p><p>Events in Solidity are broadcast to the Ethereum logs, making them accessible to off-chain systems. Each emitted event carries parameters that can provide detailed information about the action taken within the contract, enabling a reactive, responsive user experience.</p><h3>2. Why Do We Need Event Listeners?</h3><p>Event listeners offer several advantages in dApp development:</p><ul><li><strong>Real-Time Updates</strong>: They enable dApps to receive immediate updates from the blockchain, allowing users to stay informed about the latest actions without the need for constant interaction.</li><li><strong>Efficient Data Handling</strong>: Instead of polling the blockchain repeatedly to detect changes, event listeners respond only when a specified event occurs, saving computational resources and reducing network usage.</li><li><strong>Enhanced User Experience</strong>: Real-time updates enhance interactivity, making the dApp more responsive and user-friendly. Notifications for critical actions or state changes, like successful transactions or updates, improve user engagement.</li></ul><h3>3. Setting Up Event Listeners</h3><p>To set up event listeners, popular Ethereum libraries such as <strong>Web3.js</strong> and <strong>Ethers.js</strong> can be used. These libraries enable interaction with Ethereum nodes, allowing developers to listen for events emitted by specific contracts. Below are examples of how to set up event listeners with each library.</p><h4><strong>Using Web3.js</strong></h4><p><strong>1: Install Web3.js:</strong></p><pre>npm install web3</pre><p><strong>2: Initialize Web3 and the Contract Instance:</strong></p><pre>const Web3 = require(&#39;web3&#39;);<br>const web3 = new Web3(&#39;https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID&#39;);<br>const contractABI = [/* ABI array */];<br>const contractAddress = &#39;0xYourContractAddress&#39;;<br>const contract = new web3.eth.Contract(contractABI, contractAddress);</pre><p><strong>3: Set Up the Event Listener:</strong></p><pre>contract.events.YourEventName({<br>    filter: { /* Optional filters */ },<br>    fromBlock: &#39;latest&#39;<br>})<br>.on(&#39;data&#39;, (event) =&gt; {<br>    console.log(&#39;Event data:&#39;, event.returnValues);<br>    // Process the event data as needed<br>})<br>.on(&#39;error&#39;, (error) =&gt; {<br>    console.error(&#39;Error:&#39;, error);<br>});</pre><p>This listener is set to detect the event named YourEventName emitted by the contract. You can also set filters to narrow down the specific conditions under which the listener should react.</p><p>Using Ethers.js</p><p><strong>1: Install Ethers.js:</strong></p><pre>npm install ethers</pre><p><strong>2: Initialize Ethers and the Contract Instance:</strong></p><pre>const { ethers } = require(&#39;ethers&#39;);<br>const provider = new ethers.providers.InfuraProvider(&#39;mainnet&#39;, &#39;YOUR_INFURA_PROJECT_ID&#39;);<br>const contractABI = [/* ABI array */];<br>const contractAddress = &#39;0xYourContractAddress&#39;;<br>const contract = new ethers.Contract(contractAddress, contractABI, provider);</pre><p><strong>3: Set Up the Event Listener:</strong></p><pre>contract.on(&#39;YourEventName&#39;, (/* event parameters */) =&gt; {<br>    console.log(&#39;Event detected&#39;);<br>    // Handle the event data as needed<br>});</pre><p>In this setup, replace &#39;YourEventName&#39; with the actual event defined in your contract. The listener will invoke the callback function whenever the specified event is emitted.</p><h3>Additional Considerations for Effective Event Management</h3><p><strong>Filtering Events</strong></p><p>Both Web3.js and Ethers.js allow for optional filtering on event listeners. This can be useful if your contract emits events under multiple scenarios and you only want to respond to specific ones.</p><p><strong>Error Handling</strong></p><p>Implement robust error handling within event listeners to manage potential network disruptions, unexpected data formats, or other issues. Web3.js provides the .on(&#39;error&#39;, ...) method, while Ethers.js listeners can handle errors within the callback function.</p><p><strong>Performance Optimization</strong></p><p>For applications that need to listen to a large number of events, consider implementing batching or throttling mechanisms to manage resource usage efficiently. This is especially relevant when multiple events are emitted within a short period.</p><p><strong>Practical Use Case: Transaction Confirmation Listener</strong></p><p>Suppose you have a dApp where users need to know if a transaction was confirmed successfully. Here’s how an event listener can notify users in real-time:</p><pre>// Example transaction confirmation listener<br>contract.on(&#39;TransactionConfirmed&#39;, (sender, amount) =&gt; {<br>    console.log(`Transaction of ${amount} ETH confirmed from ${sender}`);<br>    alert(`Transaction confirmed! ${amount} ETH was sent.`);<br>});</pre><p>This setup ensures that users receive immediate feedback, creating a seamless experience.</p><h3>Conclusion</h3><p>Mastering Solidity events and event listeners is vital for building dApps that provide real-time notifications and seamless interaction with the Ethereum blockchain. By understanding how to use tools like Web3.js and Ethers.js for setting up event listeners, you can improve the responsiveness and user experience of your applications. Whether for updating transaction states, displaying balance changes, or tracking contract interactions, event listeners are a powerful asset in any blockchain developer’s toolkit.</p><h3>Resources</h3><p>Here are some recommended resources to deepen your understanding of Solidity events, event listeners, and real-time blockchain interactions:</p><ol><li><a href="https://ethereum.org/en/developers/docs/">Ethereum Documentation on Events</a><br>Official documentation on Ethereum, covering the role of events in Solidity and their use in smart contracts.</li><li><a href="https://docs.soliditylang.org/en/latest/">Solidity Documentation</a><br>The Solidity docs offer comprehensive details on the syntax and use of events in Solidity, along with examples and best practices.</li><li><a href="https://web3js.readthedocs.io/">Web3.js Documentation</a><br>An extensive guide on Web3.js, covering installation, setup, and how to interact with events using the Web3.js library.</li><li><a href="https://docs.ethers.io/">Ethers.js Documentation</a><br>Ethers.js documentation provides an overview of this popular library, with detailed sections on setting up event listeners and interacting with the Ethereum blockchain.</li><li><a href="https://www.alchemy.com/blog/solidity-gas-optimization">Alchemy’s Gas Optimization Techniques</a><br>A practical guide with tips on optimizing Solidity contracts, which can indirectly help reduce the cost of frequently emitted events.</li><li><a href="https://ethereum.stackexchange.com/">Ethereum Stack Exchange</a><br>A helpful community and Q&amp;A site where developers discuss common issues, including setting up event listeners and troubleshooting real-time event handling.</li><li><a href="https://blockchain.berkeley.edu/courses/">Blockchain at Berkeley’s Ethereum dApp Development Guide</a><br>Free educational resources on dApp development, including practical advice on real-time notifications in decentralized applications.</li></ol><p>These resources will support a deeper dive into event listeners and help refine your approach to implementing real-time interactions in blockchain applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=accc95619f35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kalpstudio/mastering-solidity-events-building-blockchain-event-listeners-for-real-time-notifications-accc95619f35">Mastering Solidity Events: Building Blockchain Event Listeners for Real-time Notifications</a> was originally published in <a href="https://medium.com/kalpstudio">kalpstudio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity Smart Contracts and Gas Efficiency: How to Optimize Function Calls]]></title>
            <link>https://medium.com/kalpstudio/solidity-smart-contracts-and-gas-efficiency-how-to-optimize-function-calls-678a4bdec956?source=rss-efceeb706755------2</link>
            <guid isPermaLink="false">https://medium.com/p/678a4bdec956</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity-gas-optimization]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[gas-optimization]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Jaadugar]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 06:53:40 GMT</pubDate>
            <atom:updated>2024-10-30T06:58:30.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Gas Optimization" src="https://cdn-images-1.medium.com/max/1024/1*FowTUaTUcCaAXzQj2kb8lQ.png" /></figure><p>In Solidity smart contracts, gas efficiency is critical because it directly impacts the cost of executing transactions on the Ethereum blockchain. Optimizing your smart contracts can significantly reduce gas costs, making your applications more affordable and scalable. Here’s a step-by-step guide on how to optimize function calls in Solidity, including examples of inefficient and efficient implementations.</p><h3>1. Minimize Storage Writes</h3><p>Storage operations are the most expensive operations in Solidity. Writing to storage (using SSTORE) can consume up to 22,100 gas for non-zero values. Storage reads also incur costs (200 gas per read). The key to optimization is to reduce the number of storage writes and reads by using memory or local variables for intermediate calculations and writing back to storage only once when necessary.</p><p><strong>Inefficient Code:</strong></p><pre>contract Inefficient {<br>    uint256 public count;<br>    <br>    function inefficientLoop() public {<br>        for (uint256 i = 0; i &lt; 10; i++) {<br>            count++;  // Writing to storage in every iteration<br>        }<br>    }<br>}</pre><p>In this example, the storage variable count is updated in every iteration of the loop, resulting in multiple SSTORE operations.</p><p><strong>Efficient Code:</strong></p><pre>contract Efficient {<br>    uint256 public count;<br>    <br>    solfunction efficientLoop() public {<br>        uint256 tempCount = count;  // Load from storage once<br>        for (uint256 i = 0; i &lt; 10; i++) {<br>            tempCount++;  // Perform all operations in memory<br>        }<br>        count = tempCount;  // Store the final result back to storage<br>    }<br>}</pre><p>Here, we load count from storage once, perform the loop in memory, and store the final result at the end, reducing the gas cost significantly. Additionally, if overflow is not a concern, consider using the unchecked block to skip overflow checks for small numbers, saving even more gas.</p><h3>2. Use calldata Instead of memory</h3><p>When dealing with external function parameters, prefer calldata over memory for parameters that are only read within the function. calldata is cheaper because it avoids copying data from the transaction and ensures that the data is immutable.</p><p><strong>Inefficient Code:</strong></p><pre>function processArray(uint[] memory _array) public {<br>    for (uint i = 0; i &lt; _array.length; i++) {<br>        // Do something with _array[i]<br>    }<br>}</pre><p><strong>Efficient Code:</strong></p><pre>function processArray(uint[] calldata _array) public {<br>    for (uint i = 0; i &lt; _array.length; i++) {<br>        // Do something with _array[i]<br>    }<br>}</pre><p>By using calldata, the function avoids the gas cost associated with copying the array into memory. Note that calldata is only available for external functions.</p><h3>3. Avoid Expensive Loops Over Storage</h3><p>Iterating over large storage arrays can be extremely costly due to the need to access storage repeatedly. Instead, use mappings or other structures that allow direct access without looping.</p><p><strong>Inefficient Code:</strong></p><pre>function findValue(uint[] storage array, uint value) public view returns (bool) {<br>    for (uint i = 0; i &lt; array.length; i++) {<br>        if (array[i] == value) {<br>            return true;<br>        }<br>    }<br>    return false;<br>}</pre><p><strong>Efficient Code:</strong></p><pre>mapping(uint =&gt; bool) valueExists;<br><br>function checkValue(uint value) public view returns (bool) {<br>    return valueExists[value];  // Direct access via mapping<br>}</pre><p>Mappings provide constant-time access to values, which reduces the gas cost compared to iterating over a storage array. In cases where off-chain storage is feasible, you could also store data off-chain and access it through indexed events, which reduces on-chain storage costs.</p><h3>4. Batching Operations</h3><p>When performing repetitive actions, batch them into a single function call instead of executing multiple transactions. This reduces the overhead of multiple external calls and significantly lowers gas costs.</p><p><strong>Efficient Example:</strong></p><pre>struct Call {<br>    address recipient;<br>    uint256 value;<br>    bytes data;<br>}<br><br>function batchExecute(Call[] memory _calls) public {<br>    for (uint i = 0; i &lt; _calls.length; i++) {<br>        (bool success, ) = _calls[i].recipient.call{value: _calls[i].value}(_calls[i].data);<br>        require(success, &quot;Call failed&quot;);<br>    }<br>}</pre><p>Batching allows multiple operations to be handled within one transaction, saving on gas costs associated with multiple separate calls. However, be mindful of reentrancy attacks when batching operations. Using a reentrancy guard (such as the nonReentrant modifier) is advisable to prevent these attacks.</p><h3>5. Use constant and immutable Variables</h3><p>For values that don’t change after deployment, use constant or immutable keywords. This saves gas because these values are stored directly in the contract’s bytecode rather than in storage.</p><p><strong>Example:</strong></p><pre>contract MyContract {<br>    uint256 public constant FEE_PERCENTAGE = 5;  // Gas-efficient constant<br>    address public immutable owner;<br><br>    constructor() {<br>        owner = msg.sender;  // Set immutable value at construction<br>    }<br>}</pre><p>Accessing constant and immutable variables is cheaper than accessing state variables from storage. The <strong>`constant`</strong> keyword is used for values known at compile-time, while <strong>`immutable`</strong> is useful for values known only at deployment (constructor) but remain unchanged afterward.</p><h3>Conclusion</h3><p>Optimizing Solidity function calls is essential for reducing gas costs and ensuring your smart contracts are cost-effective. Key techniques include minimizing storage operations, using calldata, avoiding expensive loops, batching operations, and leveraging constant and immutable variables. By implementing these strategies, you can significantly improve the efficiency of your Solidity smart contracts.</p><p>For more detailed insights, check out resources on gas optimization strategies and always stay updated on the latest best practices in Solidity.</p><h3>Resources</h3><ol><li><a href="https://www.alchemy.com/overviews/solidity-gas-optimization">Alchemy’s Top Gas Optimization Techniques</a></li><li><a href="https://helalabs.com/blog/12-expert-solidity-gas-optimization-techniques/">Helalabs’ Gas Optimization Guide</a></li><li><a href="https://github.com/0xisk/awesome-solidity-gas-optimization">GitHub Gas Optimization Resource Collection</a></li><li><a href="https://www.soliditylibraries.com/best-practices/solidity-gas-optimization-best-practices/">Solidity Libraries Gas Optimization</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=678a4bdec956" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kalpstudio/solidity-smart-contracts-and-gas-efficiency-how-to-optimize-function-calls-678a4bdec956">Solidity Smart Contracts and Gas Efficiency: How to Optimize Function Calls</a> was originally published in <a href="https://medium.com/kalpstudio">kalpstudio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Oracles Connect Smart Contracts to Real-World Data]]></title>
            <link>https://medium.com/kalpstudio/how-oracles-connect-smart-contracts-to-real-world-data-0d3a8883aa2c?source=rss-efceeb706755------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d3a8883aa2c</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[price-feed]]></category>
            <dc:creator><![CDATA[Jaadugar]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 12:26:27 GMT</pubDate>
            <atom:updated>2024-10-23T12:30:54.081Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Oracles in Smart Contracts: Why They Matter</strong></p><p>Smart contracts on Ethereum and other blockchains are inherently deterministic. While they are excellent at executing code under predefined rules, they lack access to real-world data. This limitation means that for decentralized applications (DApps) to interact with external systems — such as pulling stock prices, weather data, or in this case, cryptocurrency exchange rates — there is a critical need for oracles.</p><p><strong>What Are Oracles?</strong></p><p>Oracles serve as bridges between blockchains and the outside world, providing smart contracts with off-chain data. Oracles themselves are not data sources; instead, they retrieve and verify information from external sources and feed it to smart contracts in a trustless and decentralized manner.</p><figure><img alt="Oracles Personified" src="https://cdn-images-1.medium.com/max/1024/0*-ay9aJnXD0vqvDEU" /></figure><p><strong>Chainlink: The Leading Oracle Provider</strong></p><p>Among the various decentralized oracle networks, <strong>Chainlink</strong> is the industry leader, providing a robust infrastructure that enables smart contracts to interact with real-world data securely. Chainlink achieves decentralization by aggregating data from multiple trusted sources and validators, which ensures both accuracy and tamper-resistance.</p><p>One of the most popular use cases for Chainlink’s oracles is price feeds, which provide live data on asset prices. This data is especially crucial for DeFi applications like lending platforms, synthetic assets, and decentralized exchanges.</p><p><strong>How Price-Feed Oracles Work</strong></p><p>Chainlink price-feed oracles collect data from multiple external sources, such as cryptocurrency exchanges. This data is aggregated and delivered to smart contracts that rely on real-time asset pricing. For example, decentralized lending protocols like <strong>Aave</strong> and <strong>Compound</strong> use Chainlink price oracles to determine the value of collateral, ensuring that loans and liquidations occur correctly.</p><p>In the example above, we demonstrated a Solidity contract that uses Chainlink’s ETH/USD price feed to pull the latest Ether price in USD. This type of oracle is instrumental in various applications:</p><ol><li><strong>Decentralized Finance (DeFi)</strong>: Platforms like Aave use price feeds to ensure users maintain sufficient collateral.</li><li><strong>Synthetic Asset Platforms</strong>: Protocols like <strong>Synthetix</strong> use price oracles to track real-world asset prices (e.g., commodities or stocks).</li><li><strong>Decentralized Exchanges (DEXs)</strong>: DEXs like <strong>SushiSwap</strong> rely on accurate price feeds to facilitate token swaps at fair market prices.</li></ol><p><strong>Chainlink Price Feeds: How They Ensure Trust and Accuracy</strong></p><p>Chainlink’s oracles don’t rely on a single data source. Instead, they aggregate data from many independent, trusted nodes and then apply mechanisms to weed out any outliers or inaccuracies. This decentralized approach ensures that the data fed into smart contracts is not only accurate but also resistant to manipulation or failure.</p><p>For example, in the ETH/USD price feed used in the smart contract, the price is an average drawn from multiple cryptocurrency exchanges, reducing the risk of faulty data or price manipulation.</p><figure><img alt="Oracles personified" src="https://cdn-images-1.medium.com/max/1024/0*lVohmy9RgM3VG75X.jpg" /></figure><p><strong>Why Oracles Are Key for the Future of Blockchain</strong></p><p>Oracles unlock a new wave of decentralized applications by providing access to dynamic, real-world data. Beyond price feeds, oracles are being used in innovative fields such as insurance, weather derivatives, gaming, and prediction markets. For instance, a weather-based insurance contract can rely on oracles to retrieve weather conditions from an external API, triggering automatic payouts when certain conditions are met.</p><p>Chainlink’s ability to provide reliable, real-world data without sacrificing the decentralization ethos of blockchain makes it a cornerstone for DeFi and beyond.</p><figure><img alt="Smart contract pulling in data from real world" src="https://cdn-images-1.medium.com/max/1024/0*FPYLK9usDGDbFVS9.jpg" /></figure><p>Here’s a basic Solidity smart contract that pulls data from Chainlink’s Price Feed Oracle for the USD to ETH price. This example demonstrates how to retrieve live price data using Chainlink’s decentralized oracle network.</p><h3>Solidity Smart Contract Example: USD to ETH Price Feed</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.7;<br><br>import &quot;@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol&quot;;<br><br>contract PriceConsumerV3 {<br>    AggregatorV3Interface internal priceFeed;<br><br>    /**<br>     * Network: Ethereum Mainnet<br>     * Aggregator: ETH/USD<br>     * Address: 0x5f4ec3df9cbd43714fe2740f5e3616155c5b8419<br>     */<br>    constructor() {<br>        priceFeed = AggregatorV3Interface(0x5f4ec3df9cbd43714fe2740f5e3616155c5b8419);<br>    }<br><br>    /**<br>     * Returns the latest price of ETH in USD<br>     */<br>    function getLatestPrice() public view returns (int) {<br>        (<br>            uint80 roundID, <br>            int price,<br>            uint startedAt,<br>            uint timeStamp,<br>            uint80 answeredInRound<br>        ) = priceFeed.latestRoundData();<br>        return price;<br>    }<br>}</pre><p>In conclusion, oracles are crucial for the continued evolution of blockchain and decentralized applications. Chainlink’s decentralized oracle network, with its reliable price feeds, ensures that smart contracts can interact with real-world data securely and efficiently. As the DeFi space grows, so will the demand for oracles, especially those providing accurate and tamper-resistant price feeds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d3a8883aa2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kalpstudio/how-oracles-connect-smart-contracts-to-real-world-data-0d3a8883aa2c">How Oracles Connect Smart Contracts to Real-World Data</a> was originally published in <a href="https://medium.com/kalpstudio">kalpstudio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>