minor chaincode cleanup

Signed-off-by: Matthias Sieber <matthias.sieber@loxeinc.com>
This commit is contained in:
Matthias Sieber 2022-10-24 18:19:08 -07:00
parent c323c95807
commit 197a07b2d2
6 changed files with 104 additions and 104 deletions

View file

@ -9,4 +9,4 @@
const FabCar = require('./lib/fabcar'); const FabCar = require('./lib/fabcar');
module.exports.FabCar = FabCar; module.exports.FabCar = FabCar;
module.exports.contracts = [ FabCar ]; module.exports.contracts = [FabCar];

View file

@ -111,7 +111,7 @@ class FabCar extends Contract {
const startKey = ''; const startKey = '';
const endKey = ''; const endKey = '';
const allResults = []; const allResults = [];
for await (const {key, value} of ctx.stub.getStateByRange(startKey, endKey)) { for await (const { key, value } of ctx.stub.getStateByRange(startKey, endKey)) {
const strValue = Buffer.from(value).toString('utf8'); const strValue = Buffer.from(value).toString('utf8');
let record; let record;
try { try {
@ -130,7 +130,7 @@ class FabCar extends Contract {
console.info('============= START : changeCarOwner ==========='); console.info('============= START : changeCarOwner ===========');
const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state
if (!carAsBytes || carAsBytes.length === 0) { if (!carAsBytes || !carAsBytes.length) {
throw new Error(`${carNumber} does not exist`); throw new Error(`${carNumber} does not exist`);
} }
const car = JSON.parse(carAsBytes.toString()); const car = JSON.parse(carAsBytes.toString());

View file

@ -105,12 +105,11 @@ export class FabCar extends Contract {
} }
public async queryAllCars(ctx: Context): Promise<string> { public async queryAllCars(ctx: Context): Promise<string> {
const startKey = ''; const noKey = '';
const endKey = '';
const allResults = []; const allResults = [];
for await (const {key, value} of ctx.stub.getStateByRange(startKey, endKey)) { for await (const {key, value} of ctx.stub.getStateByRange(noKey, noKey)) {
const strValue = Buffer.from(value).toString('utf8'); const strValue = Buffer.from(value).toString('utf8');
let record; let record: string;
try { try {
record = JSON.parse(strValue); record = JSON.parse(strValue);
} catch (err) { } catch (err) {

View file

@ -31,9 +31,9 @@
const shim = require('fabric-shim'); const shim = require('fabric-shim');
const util = require('util'); const util = require('util');
let Chaincode = class { const Chaincode = class {
async Init(stub) { async Init(stub) {
let ret = stub.getFunctionAndParameters(); const ret = stub.getFunctionAndParameters();
console.info(ret); console.info(ret);
console.info('=========== Instantiated Marbles Chaincode ==========='); console.info('=========== Instantiated Marbles Chaincode ===========');
return shim.success(); return shim.success();
@ -43,16 +43,16 @@ let Chaincode = class {
console.info('Transaction ID: ' + stub.getTxID()); console.info('Transaction ID: ' + stub.getTxID());
console.info(util.format('Args: %j', stub.getArgs())); console.info(util.format('Args: %j', stub.getArgs()));
let ret = stub.getFunctionAndParameters(); const ret = stub.getFunctionAndParameters();
console.info(ret); console.info(ret);
let method = this[ret.fcn]; const method = this[ret.fcn];
if (!method) { if (!method) {
console.log('no function of name:' + ret.fcn + ' found'); console.log(`no function of name:${ret.fcn} found`);
throw new Error('Received unknown function ' + ret.fcn + ' invocation'); throw new Error(`Received unknown function ${ret.fcn} invocation`);
} }
try { try {
let payload = await method(stub, ret.params, this); const payload = await method(stub, ret.params, this);
return shim.success(payload); return shim.success(payload);
} catch (err) { } catch (err) {
console.log(err); console.log(err);
@ -63,50 +63,51 @@ let Chaincode = class {
// =============================================== // ===============================================
// initMarble - create a new marble // initMarble - create a new marble
// =============================================== // ===============================================
async initMarble(stub, args, thisClass) { async initMarble(stub, args) {
if (args.length != 4) { if (args.length !== 4) {
throw new Error('Incorrect number of arguments. Expecting 4'); throw new Error('Incorrect number of arguments. Expecting 4');
} }
// ==== Input sanitation ==== // ==== Input sanitation ====
console.info('--- start init marble ---') console.info('--- start init marble ---')
if (args[0].lenth <= 0) { if (!args[0].length) {
throw new Error('1st argument must be a non-empty string'); throw new Error('1st argument must be a non-empty string');
} }
if (args[1].lenth <= 0) { if (!args[1].length) {
throw new Error('2nd argument must be a non-empty string'); throw new Error('2nd argument must be a non-empty string');
} }
if (args[2].lenth <= 0) { if (!args[2].length) {
throw new Error('3rd argument must be a non-empty string'); throw new Error('3rd argument must be a non-empty string');
} }
if (args[3].lenth <= 0) { if (!args[3].length) {
throw new Error('4th argument must be a non-empty string'); throw new Error('4th argument must be a non-empty string');
} }
let marbleName = args[0]; const marbleName = args[0];
let color = args[1].toLowerCase(); const color = args[1].toLowerCase();
let owner = args[3].toLowerCase(); const owner = args[3].toLowerCase();
let size = parseInt(args[2]); const size = parseInt(args[2]);
if (typeof size !== 'number') { if (typeof size !== 'number') {
throw new Error('3rd argument must be a numeric string'); throw new Error('3rd argument must be a numeric string');
} }
// ==== Check if marble already exists ==== // ==== Check if marble already exists ====
let marbleState = await stub.getState(marbleName); const marbleState = await stub.getState(marbleName);
if (marbleState.toString()) { if (marbleState.toString()) {
throw new Error('This marble already exists: ' + marbleName); throw new Error('This marble already exists: ' + marbleName);
} }
// ==== Create marble object and marshal to JSON ==== // ==== Create marble object and marshal to JSON ====
let marble = {}; const marble = {
marble.docType = 'marble'; docType: 'marble',
marble.name = marbleName; name: marbleName,
marble.color = color; color: color,
marble.size = size; size: size,
marble.owner = owner; owner: owner
};
// === Save marble to state === // === Save marble to state ===
await stub.putState(marbleName, Buffer.from(JSON.stringify(marble))); await stub.putState(marbleName, Buffer.from(JSON.stringify(marble)));
let indexName = 'color~name' const indexName = 'color~name'
let colorNameIndexKey = await stub.createCompositeKey(indexName, [marble.color, marble.name]); const colorNameIndexKey = await stub.createCompositeKey(indexName, [marble.color, marble.name]);
console.info(colorNameIndexKey); console.info(colorNameIndexKey);
// Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the marble. // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the marble.
// Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value
@ -118,19 +119,20 @@ let Chaincode = class {
// =============================================== // ===============================================
// readMarble - read a marble from chaincode state // readMarble - read a marble from chaincode state
// =============================================== // ===============================================
async readMarble(stub, args, thisClass) { async readMarble(stub, args) {
if (args.length != 1) { if (args.length !== 1) {
throw new Error('Incorrect number of arguments. Expecting name of the marble to query'); throw new Error('Incorrect number of arguments. Expecting name of the marble to query');
} }
let name = args[0]; const name = args[0];
if (!name) { if (!name) {
throw new Error(' marble name must not be empty'); throw new Error(' marble name must not be empty');
} }
let marbleAsbytes = await stub.getState(name); //get the marble from chaincode state const marbleAsbytes = await stub.getState(name); //get the marble from chaincode state
if (!marbleAsbytes.toString()) { if (!marbleAsbytes.toString()) {
let jsonResp = {}; const jsonResp = {
jsonResp.Error = 'Marble does not exist: ' + name; error: `Marble does not exist: ${name}`
};
throw new Error(JSON.stringify(jsonResp)); throw new Error(JSON.stringify(jsonResp));
} }
console.info('======================================='); console.info('=======================================');
@ -142,35 +144,33 @@ let Chaincode = class {
// ================================================== // ==================================================
// delete - remove a marble key/value pair from state // delete - remove a marble key/value pair from state
// ================================================== // ==================================================
async delete(stub, args, thisClass) { async delete(stub, args) {
if (args.length != 1) { if (args.length !== 1) {
throw new Error('Incorrect number of arguments. Expecting name of the marble to delete'); throw new Error('Incorrect number of arguments. Expecting name of the marble to delete');
} }
let marbleName = args[0]; const marbleName = args[0];
if (!marbleName) { if (!marbleName) {
throw new Error('marble name must not be empty'); throw new Error('marble name must not be empty');
} }
// to maintain the color~name index, we need to read the marble first and get its color // to maintain the color~name index, we need to read the marble first and get its color
let valAsbytes = await stub.getState(marbleName); //get the marble from chaincode state const valAsbytes = await stub.getState(marbleName); //get the marble from chaincode state
let jsonResp = {}; const jsonResp = {};
if (!valAsbytes) { if (!valAsbytes) {
jsonResp.error = 'marble does not exist: ' + name; jsonResp.error = `marble does not exist: ${marbleName}`;
throw new Error(jsonResp); throw new Error(jsonResp);
} }
let marbleJSON = {}; let marbleJSON = {};
try { try {
marbleJSON = JSON.parse(valAsbytes.toString()); marbleJSON = JSON.parse(valAsbytes.toString());
} catch (err) { } catch (err) {
jsonResp = {}; jsonResp.error = `Failed to decode JSON of: ${marbleName}`;
jsonResp.error = 'Failed to decode JSON of: ' + marbleName;
throw new Error(jsonResp); throw new Error(jsonResp);
} }
await stub.deleteState(marbleName); //remove the marble from chaincode state await stub.deleteState(marbleName); //remove the marble from chaincode state
// delete the index // delete the index
let indexName = 'color~name'; const indexName = 'color~name';
let colorNameIndexKey = stub.createCompositeKey(indexName, [marbleJSON.color, marbleJSON.name]); const colorNameIndexKey = stub.createCompositeKey(indexName, [marbleJSON.color, marbleJSON.name]);
if (!colorNameIndexKey) { if (!colorNameIndexKey) {
throw new Error(' Failed to create the createCompositeKey'); throw new Error(' Failed to create the createCompositeKey');
} }
@ -181,18 +181,18 @@ let Chaincode = class {
// =========================================================== // ===========================================================
// transfer a marble by setting a new owner name on the marble // transfer a marble by setting a new owner name on the marble
// =========================================================== // ===========================================================
async transferMarble(stub, args, thisClass) { async transferMarble(stub, args) {
// 0 1 // 0 1
// 'name', 'bob' // 'name', 'bob'
if (args.length < 2) { if (args.length < 2) {
throw new Error('Incorrect number of arguments. Expecting marblename and owner') throw new Error('Incorrect number of arguments. Expecting marblename and owner')
} }
let marbleName = args[0]; const marbleName = args[0];
let newOwner = args[1].toLowerCase(); const newOwner = args[1].toLowerCase();
console.info('- start transferMarble ', marbleName, newOwner); console.info('- start transferMarble ', marbleName, newOwner);
let marbleAsBytes = await stub.getState(marbleName); const marbleAsBytes = await stub.getState(marbleName);
if (!marbleAsBytes || !marbleAsBytes.toString()) { if (!marbleAsBytes || !marbleAsBytes.toString()) {
throw new Error('marble does not exist'); throw new Error('marble does not exist');
} }
@ -200,14 +200,15 @@ let Chaincode = class {
try { try {
marbleToTransfer = JSON.parse(marbleAsBytes.toString()); //unmarshal marbleToTransfer = JSON.parse(marbleAsBytes.toString()); //unmarshal
} catch (err) { } catch (err) {
let jsonResp = {}; const jsonResp = {
jsonResp.error = 'Failed to decode JSON of: ' + marbleName; error: `Failed to decode JSON of: ${marbleName}`
};
throw new Error(jsonResp); throw new Error(jsonResp);
} }
console.info(marbleToTransfer); console.info(marbleToTransfer);
marbleToTransfer.owner = newOwner; //change the owner marbleToTransfer.owner = newOwner; //change the owner
let marbleJSONasBytes = Buffer.from(JSON.stringify(marbleToTransfer)); const marbleJSONasBytes = Buffer.from(JSON.stringify(marbleToTransfer));
await stub.putState(marbleName, marbleJSONasBytes); //rewrite the marble await stub.putState(marbleName, marbleJSONasBytes); //rewrite the marble
console.info('- end transferMarble (success)'); console.info('- end transferMarble (success)');
@ -230,12 +231,12 @@ let Chaincode = class {
throw new Error('Incorrect number of arguments. Expecting 2'); throw new Error('Incorrect number of arguments. Expecting 2');
} }
let startKey = args[0]; const startKey = args[0];
let endKey = args[1]; const endKey = args[1];
let resultsIterator = await stub.getStateByRange(startKey, endKey); const resultsIterator = await stub.getStateByRange(startKey, endKey);
let method = thisClass['getAllResults']; const method = thisClass['getAllResults'];
let results = await method(resultsIterator, false); const results = await method(resultsIterator, false);
return Buffer.from(JSON.stringify(results)); return Buffer.from(JSON.stringify(results));
} }
@ -256,19 +257,19 @@ let Chaincode = class {
throw new Error('Incorrect number of arguments. Expecting color and owner'); throw new Error('Incorrect number of arguments. Expecting color and owner');
} }
let color = args[0]; const color = args[0];
let newOwner = args[1].toLowerCase(); const newOwner = args[1].toLowerCase();
console.info('- start transferMarblesBasedOnColor ', color, newOwner); console.info('- start transferMarblesBasedOnColor ', color, newOwner);
// Query the color~name index by color // Query the color~name index by color
// This will execute a key range query on all keys starting with 'color' // This will execute a key range query on all keys starting with 'color'
let coloredMarbleResultsIterator = await stub.getStateByPartialCompositeKey('color~name', [color]); const coloredMarbleResultsIterator = await stub.getStateByPartialCompositeKey('color~name', [color]);
let method = thisClass['transferMarble']; const method = thisClass['transferMarble'];
// Iterate through result set and for each marble found, transfer to newOwner // Iterate through result set and for each marble found, transfer to newOwner
while (true) { while (true) {
let responseRange = await coloredMarbleResultsIterator.next(); const responseRange = await coloredMarbleResultsIterator.next();
if (!responseRange || !responseRange.value || !responseRange.value.key) { if (!responseRange?.value?.key) {
return; return;
} }
console.log(responseRange.value.key); console.log(responseRange.value.key);
@ -281,17 +282,15 @@ let Chaincode = class {
attributes attributes
} = await stub.splitCompositeKey(responseRange.value.key)); } = await stub.splitCompositeKey(responseRange.value.key));
let returnedColor = attributes[0]; const returnedColor = attributes[0];
let returnedMarbleName = attributes[1]; const returnedMarbleName = attributes[1];
console.info(util.format('- found a marble from index:%s color:%s name:%s\n', objectType, returnedColor, returnedMarbleName)); console.info(util.format('- found a marble from index:%s color:%s name:%s\n', objectType, returnedColor, returnedMarbleName));
// Now call the transfer function for the found marble. // Now call the transfer function for the found marble.
// Re-use the same function that is used to transfer individual marbles // Re-use the same function that is used to transfer individual marbles
let response = await method(stub, [returnedMarbleName, newOwner]); const response = await method(stub, [returnedMarbleName, newOwner]);
} }
let responsePayload = util.format('Transferred %s marbles to %s', color, newOwner);
console.info('- end transferMarblesBasedOnColor: ' + responsePayload);
} }
@ -308,13 +307,16 @@ let Chaincode = class {
throw new Error('Incorrect number of arguments. Expecting owner name.') throw new Error('Incorrect number of arguments. Expecting owner name.')
} }
let owner = args[0].toLowerCase(); const owner = args[0].toLowerCase();
let queryString = {}; const queryString = {
queryString.selector = {}; selector: {
queryString.selector.docType = 'marble'; docType: 'marble',
queryString.selector.owner = owner; owner: owner
let method = thisClass['getQueryResultForQueryString']; }
let queryResults = await method(stub, JSON.stringify(queryString), thisClass);
};
const method = thisClass['getQueryResultForQueryString'];
const queryResults = await method(stub, JSON.stringify(queryString), thisClass);
return queryResults; //shim.success(queryResults); return queryResults; //shim.success(queryResults);
} }
@ -331,25 +333,25 @@ let Chaincode = class {
if (args.length < 1) { if (args.length < 1) {
throw new Error('Incorrect number of arguments. Expecting queryString'); throw new Error('Incorrect number of arguments. Expecting queryString');
} }
let queryString = args[0]; const queryString = args[0];
if (!queryString) { if (!queryString) {
throw new Error('queryString must not be empty'); throw new Error('queryString must not be empty');
} }
let method = thisClass['getQueryResultForQueryString']; const method = thisClass['getQueryResultForQueryString'];
let queryResults = await method(stub, queryString, thisClass); const queryResults = await method(stub, queryString, thisClass);
return queryResults; return queryResults;
} }
async getAllResults(iterator, isHistory) { async getAllResults(iterator, isHistory) {
let allResults = []; const allResults = [];
while (true) { while (true) {
let res = await iterator.next(); const res = await iterator.next();
if (res.value && res.value.value.toString()) { if (res.value?.value?.toString()) {
let jsonRes = {}; const jsonRes = {};
console.log(res.value.value.toString('utf8')); console.log(res.value.value.toString('utf8'));
if (isHistory && isHistory === true) { if (isHistory === true) {
jsonRes.TxId = res.value.tx_id; jsonRes.TxId = res.value.tx_id;
jsonRes.Timestamp = res.value.timestamp; jsonRes.Timestamp = res.value.timestamp;
jsonRes.IsDelete = res.value.is_delete.toString(); jsonRes.IsDelete = res.value.is_delete.toString();
@ -386,25 +388,24 @@ let Chaincode = class {
async getQueryResultForQueryString(stub, queryString, thisClass) { async getQueryResultForQueryString(stub, queryString, thisClass) {
console.info('- getQueryResultForQueryString queryString:\n' + queryString) console.info('- getQueryResultForQueryString queryString:\n' + queryString)
let resultsIterator = await stub.getQueryResult(queryString); const resultsIterator = await stub.getQueryResult(queryString);
let method = thisClass['getAllResults']; const method = thisClass['getAllResults'];
const results = await method(resultsIterator, false);
let results = await method(resultsIterator, false);
return Buffer.from(JSON.stringify(results)); return Buffer.from(JSON.stringify(results));
} }
async getHistoryForMarble(stub, args, thisClass) { async getHistoryForMarble(stub, args, thisClass) {
if (args.length < 1) { if (!args.length) {
throw new Error('Incorrect number of arguments. Expecting 1') throw new Error('Incorrect number of arguments. Expecting 1')
} }
let marbleName = args[0]; const marbleName = args[0];
console.info('- start getHistoryForMarble: %s\n', marbleName); console.info('- start getHistoryForMarble: %s\n', marbleName);
let resultsIterator = await stub.getHistoryForKey(marbleName); const resultsIterator = await stub.getHistoryForKey(marbleName);
let method = thisClass['getAllResults']; const method = thisClass['getAllResults'];
let results = await method(resultsIterator, true); const results = await method(resultsIterator, true);
return Buffer.from(JSON.stringify(results)); return Buffer.from(JSON.stringify(results));
} }
@ -441,7 +442,7 @@ let Chaincode = class {
const { iterator, metadata } = await stub.getStateByRangeWithPagination(startKey, endKey, pageSize, bookmark); const { iterator, metadata } = await stub.getStateByRangeWithPagination(startKey, endKey, pageSize, bookmark);
const getAllResults = thisClass['getAllResults']; const getAllResults = thisClass['getAllResults'];
let results = {}; const results = {};
results.results = await getAllResults(iterator, false); results.results = await getAllResults(iterator, false);
@ -472,7 +473,7 @@ let Chaincode = class {
const { iterator, metadata } = await stub.getQueryResultWithPagination(queryString, pageSize, bookmark); const { iterator, metadata } = await stub.getQueryResultWithPagination(queryString, pageSize, bookmark);
const getAllResults = thisClass['getAllResults']; const getAllResults = thisClass['getAllResults'];
let results = {}; const results = {};
results.results = await getAllResults(iterator, false); results.results = await getAllResults(iterator, false);