TBaaS合约调用_fabric SDK Node 不使用Connection Profile

2020-09-09 09:57:33 浏览数 (1)

调用合约的时候,由于经常要变更相关的参数,每次写Connection Profile,然后还要修改js文件比较麻烦,于是想有一个不使用Connection Profile的,只修改js就可以调用的示例。

Hyperledger Fabric智能合约调用示例

参数说明参考:https://cloud.tencent.com/developer/article/1694625

invoke.js

代码语言:javascript复制
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Chaincode Invoke
 */
const fs = require('fs');
var hfc = require('fabric-client');
var path = require('path');
var util = require('util');
let serverCert = fs.readFileSync(path.join(__dirname, 'wallet/qta_nginx.pem'));
let keyPEM = fs.readFileSync(path.join(__dirname, 'wallet/qta_out_sk'));
let certPEM = fs.readFileSync(path.join(__dirname, 'wallet/demo@myorg.bcde074xwnpw@client.pem'));
var options = {
    user_id: 'demo',
    channel_id: 'sdktest',
    chaincode_id: 'sdkcctest',
    peer_url: 'grpcs://myorg-bcde074xwnpw.tbaas.tech:8080/peer0.myorg.bcde074xwnpw',
    event_url: 'grpcs://myorg-bcde074xwnpw.tbaas.tech:8080',
    orderer_url: 'grpcs://myorg-bcde074xwnpw.tbaas.tech:8080/order0.bcde074xwnpw',
    ssl_target_name_override: 'nginx.bcde074xwnpw.tbaas'
};
var channel = {};
var client = null;
var targets = [];
var tx_id = null;
async function main() {
    try {
        client = new hfc();
        await client.createUser({
            username: 'pettychen',
            mspid: 'myOrgMSP-bcde074xwnpw',
            cryptoContent: {
                privateKeyPEM: keyPEM,
                signedCertPEM: certPEM
            },
            skipPersistence: true
        });
        channel = client.newChannel(options.channel_id);
        var peerObj = client.newPeer(options.peer_url, {
            'pem': Buffer.from(serverCert).toString(),
            "grpc.primary_user_agent": "/peer0.myorg.bcde074xwnpw",
            'ssl-target-name-override': options.ssl_target_name_override
        });
        channel.addPeer(peerObj);
        channel.addOrderer(client.newOrderer(options.orderer_url, {
            'pem': Buffer.from(serverCert).toString(),
            "grpc.primary_user_agent": "/orderer0.bcde074xwnpw",
            'ssl-target-name-override': options.ssl_target_name_override
        }));
        targets.push(peerObj);
        var tx_object = client.newTransactionID();
        console.log("Assigning transaction_id: ", tx_object._transaction_id);
        var request = {
            targets: targets,
            chaincodeId: options.chaincode_id,
            fcn: 'invoke',
            args: ['b', 'a', '10'],
            txId: tx_object
        };
        var proposalResponse = await channel.sendTransactionProposal(request);
        request = {
            proposalResponses: proposalResponse[0],
            proposal: proposalResponse[1],
            header: proposalResponse[2]
        };
        await channel.sendTransaction(request);
        const tx_id = tx_object.getTransactionID();
        let channel_event_hubs = channel.getChannelEventHubsForOrg();
        const channel_event_hub = channel_event_hubs[0];
 
        let event_monitor = new Promise((resolve, reject) =>{
            let handle = setTimeout(() =>{
                channel_event_hub.unregisterTxEvent(tx_id);
                console.log('Timeout - Failed to receive the transaction event');
                reject(new Error('Timed out waiting for block event'));
            },
            20000);
            channel_event_hub.registerTxEvent(tx_id, (tx, code) =>{
                channel_event_hub.unregisterTxEvent(tx_id);
                clearTimeout(handle);
                console.log(tx);
                console.log(code);
                console.log('Successfully received the transaction event');
                resolve();
            },
            (error) =>{
                clearTimeout(handle);
                console.log('Failed to receive the transaction event ::'   error);
                reject(error);
            });
            channel_event_hub.connect();
        });
        await Promise.all([event_monitor]);
        process.exit(0);
    } catch(error) {
        console.error(`Failed to submit transaction: ${error}`);
        process.exit(1);
    }
}
main();

0 人点赞