Simple Interaction with Ledger Data: getState, putState, delState
It’s time to add some ledger interaction to our SimpleContract!
The simplest ways to get, put and delete key-value pairs is to use the corresponding functions provided by ChaincodeStub interface. Click to expand each box and learn more.
Functions provided by ChaincodeStub interface
putState
putState(key string, value: Uint8Array): Promise <void>
putState puts the specified key and value into the transaction's writeset as a data-write proposal. putState does not affect the ledger until the transaction is validated and successfully committed. Key must not be an empty string and must not start with a null character (0x00).
Close getState
getState(key: string): Promise<Uint8Array>
getState returns the value of the specified key from the ledger. getState does not read data from the writeset, which has not been committed to the ledger. In other words, getState does not consider data modified by putState that has not been committed.
🚩If the key does not exist in the state database, an empty array is returned. It is not an error from the getState perspective, so this case should be processed in the chaincode if necessary.
delState
delState(key: string): Promise<void>
delState records the specified key to be deleted in the writeset of the transaction proposal. After transaction validation and commitment, the key and its associated value will be marked as deleted in the ledger: you won’t be able to find (key, value) in the world state, but you will still have the opportunity to audit the history of all changes of this pair in the blockchain (including updates before deletion).
🚩Similar to getState, delState does not return an error if the key is not in the world state.
At this point, we know everything we need to finish the implementation of SimpleContract’s put, get, and del functions:
async put(ctx, key, value) {
await ctx.stub.putState(key, Buffer.from(value));
}
async get(ctx, key) {
const value = await ctx.stub.getState(key);
if (!value || value.length === 0) {
throw new Error(`The asset ${key} does not exist`);
}
return value.toString();
}
async del(ctx, key) {
await ctx.stub.deleteState(key); }
You can find the final version of SimpleContract in the repo provided
Last updated
Was this helpful?