Fabric链码API文档 - Node.js

fabric node.js链码开发手册

fabric-contract-api提供了一个高度封装的开发接口,使用该API可以在高层级 编写智能合约的业务逻辑。而fabric-shim则提供了底层的链码开发接口。

fabric-shim简介

安装方法如下:

~$ npm install --save fabric-shim

fabric-shim要求开发者实现ChaincodeInterface接口,即实现Invoke和Init方法:

const Chaincode = class {
    async Init(stub) {
        // use the instantiate input arguments to decide initial chaincode state values

        // save the initial states
        await stub.putState(key, Buffer.from(aStringValue));

        return shim.success(Buffer.from('Initialized Successfully!'));
    }

    async Invoke(stub) {
        // use the invoke input arguments to decide intended changes

        // retrieve existing chaincode states
        let oldValue = await stub.getState(key);

        // calculate new state values and saves them
        let newValue = oldValue + delta;
        await stub.putState(key, Buffer.from(newValue));

        return shim.success(Buffer.from(newValue.toString()));
    }
};
shim.start(new Chaincode());

然后可以启动该链码:

~$ node demo.js

fabric-contract-api

安装方法如下:

~$ npm install --save fabric-contract-api

fabric-contract-api要求链码开发者继承Contract类:

// updatevalues.js
'use strict';

// SDK Library to asset with writing the logic
const { Contract } = require('fabric-contract-api');

// Business logic (well just util but still it's general purpose logic)
const util = require('util');

/**
 * Support the Updating of values within the SmartContract
 */
class UpdateValuesContract extends Contract

    constructor(){
        super('UpdateValuesContract');
    }

    async transactionA(ctx, newValue) {
        // retrieve existing chaincode states
        let oldValue = await ctx.stub.getState(key);

        await ctx.stub.putState(key, Buffer.from(newValue));

        return Buffer.from(newValue.toString());
    }

    async transactionB(ctx) {
      //  .....
    }

};
module.exports.contracts = ['UpdateValueContract'];

需要使用fabric-chaincode-node来启动该链码:

~$ fabric-chaincode-node demo.sj