/
Invoice.ts
64 lines (56 loc) · 1.46 KB
/
Invoice.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { Buffer } from "buffer";
const RLP = require("rlp");
/**
* An Invoice is used to know whether a transaction or a parcel succeeded or
* failed.
*/
export class Invoice {
readonly success: boolean;
/**
* @param success Whether a transaction or a parcel succeeded or failed.
*/
constructor(success: boolean) {
this.success = !!success;
}
// FIXME: any
/**
* Create an Invoice from an Invoice JSON object.
* @param data An Invoice JSON object.
* @returns An Invoice.
*/
static fromJSON(data: any) {
return new this(data === "Success");
}
/**
* Convert to an Invoice JSON object.
* @returns An Invoice JSON object.
*/
toJSON() {
return this.success ? "Success" : "Failed";
}
/**
* Decode RLP bytes to an Invoice.
* @param buffer RLP bytes.
* @returns An Invoice.
*/
static fromBytes(buffer: Buffer): Invoice {
const bytes = Array.from(buffer.values());
if (bytes.length !== 1 || bytes[0] > 0x01) {
throw `Invalid RLP for Invoice: ${bytes}`;
}
return new Invoice(RLP.decode(buffer)[0]);
}
/**
* Convert to an object for RLP encoding.
*/
toEncodeObject(): boolean {
return this.success;
}
/**
* Convert to RLP bytes
* @returns RLP bytes
*/
rlpBytes(): Buffer {
return Buffer.from([this.toEncodeObject() ? 0x01 : 0x00]);
}
}