UNPKG

2.67 kBJavaScriptView Raw
1import { U8aFixed } from '@polkadot/types-codec';
2import { hexToU8a, isHex, isString, isU8a, u8aToU8a } from '@polkadot/util';
3import { decodeAddress, encodeAddress } from '@polkadot/util-crypto';
4/** @internal */
5function decodeAccountId(value) {
6 if (isU8a(value) || Array.isArray(value)) {
7 return u8aToU8a(value);
8 }
9 else if (!value) {
10 return new Uint8Array();
11 }
12 else if (isHex(value)) {
13 return hexToU8a(value);
14 }
15 else if (isString(value)) {
16 return decodeAddress(value.toString());
17 }
18 throw new Error(`Unknown type passed to AccountId constructor, found typeof ${typeof value}`);
19}
20class BaseAccountId extends U8aFixed {
21 constructor(registry, allowedBits = 256 | 264, value) {
22 const decoded = decodeAccountId(value);
23 const decodedBits = decoded.length * 8;
24 // Part of stream containing >= 32 bytes or a all empty (defaults)
25 if (decodedBits < allowedBits && decoded.some((b) => b)) {
26 throw new Error(`Invalid AccountId provided, expected ${allowedBits >> 3} bytes, found ${decoded.length}`);
27 }
28 super(registry, decoded, allowedBits);
29 }
30 /**
31 * @description Compares the value of the input to see if there is a match
32 */
33 eq(other) {
34 return super.eq(decodeAccountId(other));
35 }
36 /**
37 * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
38 */
39 toHuman() {
40 return this.toJSON();
41 }
42 /**
43 * @description Converts the Object to JSON, typically used for RPC transfers
44 */
45 toJSON() {
46 return this.toString();
47 }
48 /**
49 * @description Converts the value in a best-fit primitive form
50 */
51 toPrimitive() {
52 return this.toJSON();
53 }
54 /**
55 * @description Returns the string representation of the value
56 */
57 toString() {
58 return encodeAddress(this, this.registry.chainSS58);
59 }
60 /**
61 * @description Returns the base runtime type name for this instance
62 */
63 toRawType() {
64 return 'AccountId';
65 }
66}
67/**
68 * @name GenericAccountId
69 * @description
70 * A wrapper around an AccountId/PublicKey representation. Since we are dealing with
71 * underlying PublicKeys (32 bytes in length), we extend from U8aFixed which is
72 * just a Uint8Array wrapper with a fixed length.
73 */
74export class GenericAccountId extends BaseAccountId {
75 constructor(registry, value) {
76 super(registry, 256, value);
77 }
78}
79export class GenericAccountId33 extends BaseAccountId {
80 constructor(registry, value) {
81 super(registry, 264, value);
82 }
83}