0

I have created chaincode in which I want to do multiple transactions. But only one transaction occur.

This is my code:

const { Contract } = require("fabric-contract-api");
const crypto = require("crypto");

class KVContract extends Contract {
  constructor() {
    super("KVContract");
  }

  async instantiate() {
    // function that will be invoked on chaincode instantiation
  }

  async test(ctx) {
    const chars = "abcdefghijklmnopqrstuvwxyz";
    try {
      for (let i = 0; i < 100; i++) {
        for (let j = 0; j < 10; j++) {
          let randomString = chars.charAt(
            Math.floor(Math.random() * chars.length)
          );
          await ctx.stub.putState(`key${i}`, Buffer.from(randomString));
        }
      }
      return { success: "OK" };
    } catch (error) {
      return { success: JSON.stringify(error) };
    }
  }

exports.contracts = [KVContract];

Is there a way to execute multiple putState or transactions in a chaincode. Like i want to do 100 transactions once

DIGITAL JEDI
  • 1,672
  • 3
  • 24
  • 52

1 Answers1

0

You can make multiple calls to putState() within a single transaction function and, after that transaction has been successfully committed to the ledger and validated, all of the values written should be visible. The asset-transfer-basic sample in the fabric-samples repository has an InitLedger function that does exactly that. You can see this working by running the sample.

Note that all the updates to ledger keys made by a single transaction function appear as a single transaction on the blockchain. Each call to putState() is not a separate transaction.

bestbeforetoday
  • 1,302
  • 1
  • 8
  • 12
  • Main reason i want todo with putState is because in my chaincode i am invoking another chaincode function which also putState. Issue is that after one putState run other putState don't work. Solution? – DIGITAL JEDI Mar 21 '23 at 12:38
  • When you invoke another chaincode from within a transaction function using `invokeChaincode()`, any state changes made by the called chaincode should be included in the read/write sets of the calling transaction function. https://hyperledger.github.io/fabric-chaincode-node/main/api/fabric-shim.ChaincodeStub.html#invokeChaincode – bestbeforetoday Mar 23 '23 at 10:00