The PC node provides the interface call method of grpc. Through the officially defined .proto file and the compiled proto.js and proto.d.ts, users can call the open grpc interface to interact with the node according to the parameter specification.
Currently, we have supported:
Win10 64-bit and Windows Server2008+ operating system
Linux operating system
Mac operating system
Installation depends on npm i \@grpc/grpc-js
Installation depends on npm i \@grpc/proto-loader
The following code uses typescript as an example to implement a general grpc client to call the interface.
import * as grpc from "@grpc/grpc-js";
import * as protoLoader from "@grpc/proto-loader";
import {
BFChainService, GetLastBlockReply, GetBlockReply,
TrTransferAssetReply
} from "../grpc/src/proto";
const PROTO_PATH = process.cwd() + "/grpc/protos/bfchain.proto";
export class GrpcClient {
public ip: string = "";
//All available grpc interfaces are defined in BFChainService
private _client!: BFChainService;
constructor() {}
async init(ip: string = "localhost"): Promise<void> {
this.ip = ip; // connected server ip
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const proto = grpc.loadPackageDefinition(packageDefinition);
const port = 19005; // connected server port
const Service = proto["BFChainService"];
const service = new Service(`${this.ip}:${port}`,
grpc.credentials.createInsecure());
return new Promise((resolve, reject) => {
const WAIT_CONNECT_MS = 2000; // Connection timeout event
service.waitForReady(Date.now() + WAIT_CONNECT_MS, err => {
if (err) {
return reject(err);
}
this._client = service as any;
resolve();
});
});
}
/**
* Get the latest block
*/
async getLastBlock(): Promise<GetLastBlockReply> {
return new Promise((resolve, reject) => {
this._client.getLastBlock({}, (err, response) => {
if (err) {
return reject(err);
}
resolve(response);
});
});
}
/**
* Obtain blocks based on height
*/
async getBlock(height: number): Promise<GetBlockReply> {
return new Promise((resolve, reject) => {
this._client.getBlock({ height: height.toString() }, (err, response) => {
if (err) {
return reject(err);
}
resolve(response);
});
});
}
}
(async () => {
const client = new GrpcClient();
await client.init();
//Get the latest block
await client.getLastBlock();
//Get a block with a height of 100
await client.getBlock(100);
})();