UNPKG

2.96 kBJavaScriptView Raw
1import { Bool, U8aFixed } from '@polkadot/types-codec';
2import { isBoolean, isNumber, isU8a, isUndefined } from '@polkadot/util';
3const AYE_BITS = 0b10000000;
4const NAY_BITS = 0b00000000;
5const CON_MASK = 0b01111111;
6const DEF_CONV = 0b00000000; // the default conviction, None
7/** @internal */
8function decodeVoteBool(value) {
9 return value
10 ? new Uint8Array([AYE_BITS | DEF_CONV])
11 : new Uint8Array([NAY_BITS]);
12}
13/** @internal */
14function decodeVoteU8a(value) {
15 return value.length
16 ? value.subarray(0, 1)
17 : new Uint8Array([NAY_BITS]);
18}
19/** @internal */
20function decodeVoteType(registry, value) {
21 return new Uint8Array([
22 (new Bool(registry, value.aye).isTrue
23 ? AYE_BITS
24 : NAY_BITS) |
25 registry.createTypeUnsafe('Conviction', [value.conviction || DEF_CONV]).index
26 ]);
27}
28/** @internal */
29function decodeVote(registry, value) {
30 if (isU8a(value)) {
31 return decodeVoteU8a(value);
32 }
33 else if (isUndefined(value) || value instanceof Boolean || isBoolean(value)) {
34 return decodeVoteBool(new Bool(registry, value).isTrue);
35 }
36 else if (isNumber(value)) {
37 return decodeVoteBool(value < 0);
38 }
39 return decodeVoteType(registry, value);
40}
41/**
42 * @name GenericVote
43 * @description
44 * A number of lock periods, plus a vote, one way or the other.
45 */
46export class GenericVote extends U8aFixed {
47 __internal__aye;
48 __internal__conviction;
49 constructor(registry, value) {
50 // decoded is just 1 byte
51 // Aye: Most Significant Bit
52 // Conviction: 0000 - 0101
53 const decoded = decodeVote(registry, value);
54 super(registry, decoded, 8);
55 this.__internal__aye = (decoded[0] & AYE_BITS) === AYE_BITS;
56 this.__internal__conviction = this.registry.createTypeUnsafe('Conviction', [decoded[0] & CON_MASK]);
57 }
58 /**
59 * @description returns a V2 conviction
60 */
61 get conviction() {
62 return this.__internal__conviction;
63 }
64 /**
65 * @description true if the wrapped value is a positive vote
66 */
67 get isAye() {
68 return this.__internal__aye;
69 }
70 /**
71 * @description true if the wrapped value is a negative vote
72 */
73 get isNay() {
74 return !this.isAye;
75 }
76 /**
77 * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
78 */
79 toHuman(isExpanded) {
80 return {
81 conviction: this.conviction.toHuman(isExpanded),
82 vote: this.isAye ? 'Aye' : 'Nay'
83 };
84 }
85 /**
86 * @description Converts the value in a best-fit primitive form
87 */
88 toPrimitive() {
89 return {
90 aye: this.isAye,
91 conviction: this.conviction.toPrimitive()
92 };
93 }
94 /**
95 * @description Returns the base runtime type name for this instance
96 */
97 toRawType() {
98 return 'Vote';
99 }
100}