@node-dlc/messaging
Version:
DLC Messaging Protocol
86 lines • 3.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoundingIntervalsV0 = void 0;
const bufio_1 = require("@node-dlc/bufio");
const MessageType_1 = require("../MessageType");
/**
* RoundingIntervals V0
*/
class RoundingIntervalsV0 {
constructor() {
/**
* The type for rounding_intervals_v0 tlv. rounding_intervals_v0 = 42788
*/
this.type = RoundingIntervalsV0.type;
this.intervals = [];
}
/**
* Deserializes an rounding_intervals_v0 tlv
* @param buf
*/
static deserialize(buf) {
const instance = new RoundingIntervalsV0();
const reader = new bufio_1.BufferReader(buf);
reader.readBigSize(); // read type
instance.length = reader.readBigSize();
reader.readUInt16BE(); // num_rounding_intervals
while (!reader.eof) {
const beginInterval = reader.readBigSize();
const roundingMod = reader.readBigSize();
instance.intervals.push({ beginInterval, roundingMod });
}
return instance;
}
/**
* Validates correctness of all fields in the message
* https://github.com/discreetlogcontracts/dlcspecs/blob/master/NumericOutcome.md#requirements
* @throws Will throw an error if validation fails
*/
validate() {
// 1. Intervals must be non-negative
for (const interval of this.intervals) {
if (interval.beginInterval < 0) {
throw new Error('beginInterval must be non-negative');
}
}
// 2. Intervals must be strictly increasing
for (let i = 1; i < this.intervals.length; ++i) {
if (this.intervals[i - 1].beginInterval >= this.intervals[i].beginInterval) {
throw new Error(`Intervals must be strictly increasing`);
}
}
}
/**
* Converts rounding_intervals_v0 to JSON
*/
toJSON() {
return {
type: this.type,
intervals: this.intervals.map((interval) => {
return {
beginInterval: Number(interval.beginInterval),
roundingMod: Number(interval.roundingMod),
};
}),
};
}
/**
* Serializes the rounding_intervals_v0 tlv into a Buffer
*/
serialize() {
const writer = new bufio_1.BufferWriter();
writer.writeBigSize(this.type);
const dataWriter = new bufio_1.BufferWriter();
dataWriter.writeUInt16BE(this.intervals.length);
for (const interval of this.intervals) {
dataWriter.writeBigSize(interval.beginInterval);
dataWriter.writeBigSize(interval.roundingMod);
}
writer.writeBigSize(dataWriter.size);
writer.writeBytes(dataWriter.toBuffer());
return writer.toBuffer();
}
}
exports.RoundingIntervalsV0 = RoundingIntervalsV0;
RoundingIntervalsV0.type = MessageType_1.MessageType.RoundingIntervalsV0;
//# sourceMappingURL=RoundingIntervalsV0.js.map