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