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!
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 followingthen 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.