Updating same list, multiple times in the same method - Hyperledger Fabric Chaincode node js

233 views Asked by At

So I was trying to build a simple loyalty chaincode in js.

I started with this repo: https://github.com/IBM/customer-loyalty-program-hyperledger-fabric-VSCode/blob/master/contract/lib/customerloyalty.js

And I was trying to write a function where two users could change points between them. Which means that I had to update the member1 on the member's list and member2 on the member's list.

The problem is that I am not able to update both members. Only the last one (member2) is registered on the member's list with the update points value.

This is the function for adding the elements to the list and put it on the blockchain state:

    async function addElementToList(ctx, listKey, elementJSON){
        let currentList = await ctx.stub.getState(listKey);
        currentList = JSON.parse(currentList);
        currentList.push(elementJSON);

        await ctx.stub.putState(listKey, Buffer.from(JSON.stringify(currentList)));
    }

And this I what I'm trying to do in my Exchange Points function:

    //update member's points
        member2.points += exchangePoints.points;
        member1.points -= exchangePoints.points;

        let member1_Stringify = JSON.stringify(member1);
        let member2_Stringify = JSON.stringify(member2);
        let exchangePointsStringify = JSON.stringify(exchangePoints);

        await utils.addElementToList(ctx, allMembersKey, member1_Stringify); //update member1 in member's list
        await utils.addElementToList(ctx, exchangePointsKey, exchangePointsStringify); //add to earn points list
        await utils.addElementToList(ctx, allMembersKey, member2_Stringify); //update member2 in member's list

        return exchangePointsStringify;

Anyone knows how can I fix this?

Thanks a lot!

1

There are 1 answers

2
david_k On BEST ANSWER

The problem is that you can't read your own writes in chaincode, as described in the Read-Write set semantics documentation. Basically if you have a key that currently contains the text current stuff in the world state (ie has been committed) and you do the following

await ctx.stub.putState(key, Buffer.from('new data'));
const readvalue = ctx.stub.getState(key).toString();

then readvalue will contain the original value of current stuff (ie the current value on the ledger) it won't contain the value you have just written.