チェーン統計格納クラス
以下は、チェーン情報を格納するクラスです。
Restゲートウェイの /chain/info
に近いですが、ファイナライズの情報が一部ありません。
NodeInfo.ts
export class ChainStatistics {
constructor(
public readonly height: string,
public readonly finalizedHeight: string,
public readonly scoreHigh: string,
public readonly scoreLow: string
) {}
}
ノード情報取得クラス
前回作成した Catpult.ts
を編集します。
ノードと接続した際についでに証明書の期限も取得するようにしています。
Catpult.ts
import { NodeInfo } from './NodeInfo.js';
import { PacketBuffer } from './PacketBuffer.js';
import { SslSocket } from './SslSocket.js';
export class Catpult extends SslSocket {
/** パケットタイプ */
private PacketType = {
CHAIN_STATISTICS: 5,
NODE_DISCOVERY_PULL_PING: 0x111,
};
/**
* ChainStatistics取得
* @returns 成功: ChainStatistics, 失敗: undefined
*/
async getChainStatistics() {
let chainStatistics: ChainStatistics | undefined = undefined;
try {
const socketData = await this.requestSocket(
this.PacketType.CHAIN_STATISTICS
);
if (!socketData) return undefined;
const bufferView = new PacketBuffer(Buffer.from(socketData));
const height = bufferView.readBigUInt64LE();
const finalizedHeight = bufferView.readBigUInt64LE();
const scoreHigh = bufferView.readBigUInt64LE();
const scoreLow = bufferView.readBigUInt64LE();
chainStatistics = new ChainStatistics(
height.toString(),
finalizedHeight.toString(),
scoreHigh.toString(),
scoreLow.toString()
);
} catch (e) {
chainStatistics = undefined;
}
return chainStatistics;
}
// 略...
}
メイン
Catpult
のインスタンスを生成して呼び出すだけです。
main.ts
import { Catpult } from './Catpult.js';
const catpult = new Catpult('sakia.harvestasya.com');
const result = await catpult.getChainStatistics();
console.log(result);
実行
> yarn tsx ./src/main.ts
ChainStatistics {
height: '1471559',
finalizedHeight: '1471544',
scoreHigh: '0',
scoreLow: '15108098493857278957'
}