1 |
|
2 |
|
3 |
|
4 | import { Bool, U8aFixed } from '@polkadot/types-codec';
|
5 | import { isBoolean, isNumber, isU8a, isUndefined } from '@polkadot/util';
|
6 |
|
7 | const AYE_BITS = 0b10000000;
|
8 | const NAY_BITS = 0b00000000;
|
9 | const CON_MASK = 0b01111111;
|
10 | const DEF_CONV = 0b00000000;
|
11 |
|
12 |
|
13 | function decodeVoteBool(value) {
|
14 | return value ? new Uint8Array([AYE_BITS | DEF_CONV]) : new Uint8Array([NAY_BITS]);
|
15 | }
|
16 |
|
17 |
|
18 | function decodeVoteU8a(value) {
|
19 | return value.length ? value.subarray(0, 1) : new Uint8Array([NAY_BITS]);
|
20 | }
|
21 |
|
22 |
|
23 | function 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 |
|
28 | function 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 |
|
41 |
|
42 |
|
43 |
|
44 | export class GenericVote extends U8aFixed {
|
45 | #aye;
|
46 | #conviction;
|
47 | constructor(registry, value) {
|
48 |
|
49 |
|
50 |
|
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 |
|
59 |
|
60 | get conviction() {
|
61 | return this.#conviction;
|
62 | }
|
63 |
|
64 | |
65 |
|
66 |
|
67 | get isAye() {
|
68 | return this.#aye;
|
69 | }
|
70 |
|
71 | |
72 |
|
73 |
|
74 | get isNay() {
|
75 | return !this.isAye;
|
76 | }
|
77 |
|
78 | |
79 |
|
80 |
|
81 | toHuman(isExpanded) {
|
82 | return {
|
83 | conviction: this.conviction.toHuman(isExpanded),
|
84 | vote: this.isAye ? 'Aye' : 'Nay'
|
85 | };
|
86 | }
|
87 |
|
88 | |
89 |
|
90 |
|
91 | toPrimitive() {
|
92 | return {
|
93 | aye: this.isAye,
|
94 | conviction: this.conviction.toPrimitive()
|
95 | };
|
96 | }
|
97 |
|
98 | |
99 |
|
100 |
|
101 | toRawType() {
|
102 | return 'Vote';
|
103 | }
|
104 | } |
\ | No newline at end of file |