-
Notifications
You must be signed in to change notification settings - Fork 340
/
AccountId.ts
61 lines (49 loc) · 1.66 KB
/
AccountId.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2017-2018 @polkadot/api-codec authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import encodeAddress from '@polkadot/util-keyring/address/encode';
import decodeAddress from '@polkadot/util-keyring/address/decode';
import hexToU8a from '@polkadot/util/hex/toU8a';
import isHex from '@polkadot/util/is/hex';
import isU8a from '@polkadot/util/is/u8a';
import u8aToU8a from '@polkadot/util/u8a/toU8a';
import U8a from './codec/U8a';
import U8aFixed from './codec/U8aFixed';
// A wrapper around an AccountId/PublicKey representation. Since we are dealing with
// underlying PublicKeys (32 bytes in length), we extend from U8aFixed which is
// basically just a Uint8Array wrapper with a fixed length.
export default class AccountId extends U8aFixed {
constructor (value: U8a | string | Uint8Array = new Uint8Array()) {
super(
value instanceof U8a
? value.raw
: AccountId.decode(value),
256
);
}
static encode (value: Uint8Array): string {
return encodeAddress(value);
}
static decode (value: string | Uint8Array | Array<number>): Uint8Array {
if (isU8a(value) || Array.isArray(value)) {
return u8aToU8a(value);
} else if (isHex(value)) {
return hexToU8a(value);
}
return decodeAddress(value);
}
fromJSON (input: any): AccountId {
super.fromJSON(AccountId.decode(input));
return this;
}
fromU8a (input: Uint8Array): AccountId {
super.fromU8a(input);
return this;
}
toJSON (): any {
return this.toString();
}
toString (): string {
return AccountId.encode(this.raw);
}
}