UNPKG

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