diff --git a/packages/types/src/generic/MultiAddress.ts b/packages/types/src/generic/MultiAddress.ts new file mode 100644 index 000000000000..a80d91dfd5b9 --- /dev/null +++ b/packages/types/src/generic/MultiAddress.ts @@ -0,0 +1,44 @@ +// Copyright 2017-2020 @polkadot/types authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import { Registry } from '../types'; + +import { isString, u8aConcat } from '@polkadot/util'; +import { decodeAddress } from '@polkadot/util-crypto'; + +import Enum from '../codec/Enum'; + +export default class MultiAddress extends Enum { + constructor (registry: Registry, value?: unknown) { + super(registry, { + Id: 'AccountId', + Index: 'Compact', + Raw: 'Bytes', + // eslint-disable-next-line sort-keys + Address32: 'H256', + // eslint-disable-next-line sort-keys + Address20: 'H160' + }, MultiAddress._decodeMultiAddress(value as string)); + } + + private static _decodeMultiAddress (value?: unknown): unknown { + if (isString(value)) { + try { + const u8a = decodeAddress(value.toString()); + + return u8aConcat(new Uint8Array(u8a.length <= 8 ? 1 : 0), u8a); + } catch (error) { + // ignore, not a valid ss58 address + } + } + + return value; + } + + /** + * @description Returns the string representation of the value + */ + public toString (): string { + return this.value.toString(); + } +} diff --git a/packages/types/src/generic/index.ts b/packages/types/src/generic/index.ts index bf93535a0297..2e85cad69f94 100644 --- a/packages/types/src/generic/index.ts +++ b/packages/types/src/generic/index.ts @@ -10,4 +10,5 @@ export { default as GenericCall } from './Call'; export { default as GenericConsensusEngineId } from './ConsensusEngineId'; export { default as GenericEvent } from './Event'; export { default as GenericLookupSource } from './LookupSource'; +export { default as GenericMultiAddress } from './MultiAddress'; export { default as GenericVote } from './Vote'; diff --git a/packages/types/src/interfaces/runtime/definitions.ts b/packages/types/src/interfaces/runtime/definitions.ts index e61e94e79819..50125dcb6c52 100644 --- a/packages/types/src/interfaces/runtime/definitions.ts +++ b/packages/types/src/interfaces/runtime/definitions.ts @@ -81,6 +81,7 @@ export default { LookupSource: 'GenericLookupSource', LookupTarget: 'AccountId', ModuleId: 'LockIdentifier', + MultiAddress: 'GenericMultiAddress', Moment: 'u64', OpaqueCall: 'Bytes', Origin: 'DoNotConstruct',