Document @polkadot/types (#430)

* Start with codec descriptions

* Base codec types have definitions...

* Base interface defintions

* Descriptions for all type classes

* Link to types docs

* Remove stray template block

* Typos

* Hash -> H256 in description
This commit is contained in:
Jaco Greeff
2018-12-03 11:23:18 +01:00
committed by GitHub
parent 55fa4912b3
commit 6cab9be9c8
76 changed files with 915 additions and 245 deletions
+1
View File
@@ -6,6 +6,7 @@
- [rpc-provider](rpc-provider/README.md) - [rpc-provider](rpc-provider/README.md)
- [HttpProvider](rpc-provider/classes/_http_index_.httpprovider.md) - [HttpProvider](rpc-provider/classes/_http_index_.httpprovider.md)
- [WsProvider](rpc-provider/classes/_ws_index_.wsprovider.md) - [WsProvider](rpc-provider/classes/_ws_index_.wsprovider.md)
- [types (codec implementation)](types/README.md)
## Interfaces ## Interfaces
+7 -3
View File
@@ -9,9 +9,13 @@ import { hexToU8a, isHex, isString, isU8a, u8aToU8a } from '@polkadot/util';
import U8aFixed from './codec/U8aFixed'; 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 * @name AccountId
// just a Uint8Array wrapper with a fixed length. * @description
* A wrapper around an AccountId/PublicKey representation. Since we are dealing with
* underlying PublicKeys (32 bytes in length), we extend from U8aFixed which is
* just a Uint8Array wrapper with a fixed length.
*/
export default class AccountId extends U8aFixed { export default class AccountId extends U8aFixed {
constructor (value: AnyU8a = new Uint8Array()) { constructor (value: AnyU8a = new Uint8Array()) {
super( super(
+6 -3
View File
@@ -20,9 +20,12 @@ const MAX_1BYTE = new BN(PREFIX_1BYTE);
const MAX_2BYTE = new BN(1).shln(16); const MAX_2BYTE = new BN(1).shln(16);
const MAX_4BYTE = new BN(1).shln(32); const MAX_4BYTE = new BN(1).shln(32);
// A wrapper around an AccountIndex, which is a shortened, variable-length encoding /**
// for an Account. We extends from U8a which is basically * @name AccountIndex
// just a Uint8Array wrapper. * @description
* A wrapper around an AccountIndex, which is a shortened, variable-length encoding
* for an Account. We extends from [[U32]] to provide the number-like properties.
*/
export default class AccountIndex extends U32 { export default class AccountIndex extends U32 {
constructor (value: AnyNumber = new BN(0)) { constructor (value: AnyNumber = new BN(0)) {
super( super(
+14 -11
View File
@@ -14,11 +14,14 @@ type AnyAddress = BN | Address | AccountId | AccountIndex | Array<number> | Uint
export const ACCOUNT_ID_PREFIX = new Uint8Array([0xff]); export const ACCOUNT_ID_PREFIX = new Uint8Array([0xff]);
// A wrapper around an AccountId and/or AccountIndex that is encoded with a prefix. /**
// Since we are dealing with underlying publicKeys (or shorter encoded addresses), * @name Address
// we extend from Base with an AccountId/AccountIndex wrapper. Basically the Address * @description
// is encoded as * A wrapper around an AccountId and/or AccountIndex that is encoded with a prefix.
// [ <prefix-byte>, ...publicKey/...bytes ] * Since we are dealing with underlying publicKeys (or shorter encoded addresses),
* we extend from Base with an AccountId/AccountIndex wrapper. Basically the Address
* is encoded as `[ <prefix-byte>, ...publicKey/...bytes ]` as per spec
*/
export default class Address extends Base<AccountId | AccountIndex> { export default class Address extends Base<AccountId | AccountIndex> {
constructor (value: AnyAddress = new Uint8Array()) { constructor (value: AnyAddress = new Uint8Array()) {
super( super(
@@ -58,12 +61,6 @@ export default class Address extends Base<AccountId | AccountIndex> {
: new AccountIndex(u8aToBn(decoded, true)); : new AccountIndex(u8aToBn(decoded, true));
} }
get rawLength (): number {
return this.raw instanceof AccountIndex
? AccountIndex.calcLength(this.raw)
: this.raw.encodedLength;
}
get encodedLength (): number { get encodedLength (): number {
const rawLength = this.rawLength; const rawLength = this.rawLength;
@@ -75,6 +72,12 @@ export default class Address extends Base<AccountId | AccountIndex> {
); );
} }
get rawLength (): number {
return this.raw instanceof AccountIndex
? AccountIndex.calcLength(this.raw)
: this.raw.encodedLength;
}
toHex (): string { toHex (): string {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
+5 -1
View File
@@ -4,6 +4,10 @@
import U128 from './U128'; import U128 from './U128';
// The Substrate Balance representation. /**
* @name Balance
* @description
* The Substrate Balance representation as a [[U128]].
*/
export default class Balance extends U128 { export default class Balance extends U128 {
} }
+12 -4
View File
@@ -14,8 +14,12 @@ export type BftAuthoritySignatureValue = {
signature?: AnyU8a signature?: AnyU8a
}; };
// Represents a Bft Hash and Signature pairing, typically used in reporting /**
// network behaviour. * @name BftAuthoritySignature
* @description
* Represents a Bft Hash and Signature pairing, typically used in reporting
* network behaviour.
*/
export class BftAuthoritySignature extends Tuple { export class BftAuthoritySignature extends Tuple {
constructor (value?: BftAuthoritySignatureValue | Uint8Array) { constructor (value?: BftAuthoritySignatureValue | Uint8Array) {
super({ super({
@@ -38,8 +42,12 @@ export type BftHashSignatureValue = {
signature?: AnyU8a signature?: AnyU8a
}; };
// Represents a Bft Hash and Signature pairing, typically used in reporting /**
// network behaviour. * @name BftHashSignature
* @description
* Represents a Bft Hash and Signature pairing, typically used in reporting
* network behaviour.
*/
export class BftHashSignature extends Tuple { export class BftHashSignature extends Tuple {
constructor (value?: BftHashSignatureValue | Uint8Array) { constructor (value?: BftHashSignatureValue | Uint8Array) {
super({ super({
+5 -1
View File
@@ -16,7 +16,11 @@ export type BlockValue = {
header?: HeaderValue header?: HeaderValue
}; };
// A block encoded with header and extrinsics /**
* @name Block
* @description
* A block encoded with header and extrinsics
*/
export default class Block extends Struct { export default class Block extends Struct {
constructor (value?: BlockValue | Uint8Array) { constructor (value?: BlockValue | Uint8Array) {
super({ super({
+5
View File
@@ -4,5 +4,10 @@
import U64 from './U64'; import U64 from './U64';
/**
* @name BlockNumber
* @description
* A representation of a Substrate BlockNumber, implemented as a [[U64]]
*/
export default class BlockNumber extends U64 { export default class BlockNumber extends U64 {
} }
+9 -4
View File
@@ -6,6 +6,11 @@ import { isU8a, u8aToHex } from '@polkadot/util';
import { Codec } from './types'; import { Codec } from './types';
/**
* @name Bool
* @description
* Representation for a boolean value in the system
*/
export default class Bool extends Boolean implements Codec { export default class Bool extends Boolean implements Codec {
constructor (value: Bool | Boolean | Uint8Array | boolean | number = false) { constructor (value: Bool | Boolean | Uint8Array | boolean | number = false) {
super( super(
@@ -35,11 +40,11 @@ export default class Bool extends Boolean implements Codec {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
toU8a (isBare?: boolean): Uint8Array {
return new Uint8Array([this ? 1 : 0]);
}
toString (): string { toString (): string {
return `${this.toJSON()}`; return `${this.toJSON()}`;
} }
toU8a (isBare?: boolean): Uint8Array {
return new Uint8Array([this ? 1 : 0]);
}
} }
+7 -3
View File
@@ -8,9 +8,13 @@ import { AnyU8a } from './types';
import Compact from './codec/Compact'; import Compact from './codec/Compact';
import U8a from './codec/U8a'; import U8a from './codec/U8a';
// A Bytes wrapper for Vec<u8>. The significant difference between this and a normal Uint8Array /**
// is that this version allows for length-encoding. (i.e. it is a variable-item codec, the same * @name Bytes
// as what is found in Text and Vector) * @description
* A Bytes wrapper for Vec<u8>. The significant difference between this and a normal Uint8Array
* is that this version allows for length-encoding. (i.e. it is a variable-item codec, the same
* as what is found in [[Text]] and [[Vector]])
*/
export default class Bytes extends U8a { export default class Bytes extends U8a {
constructor (value: AnyU8a) { constructor (value: AnyU8a) {
super(Bytes.decodeBytes(value)); super(Bytes.decodeBytes(value));
+5 -1
View File
@@ -4,6 +4,10 @@
import U8a from './codec/U8a'; import U8a from './codec/U8a';
// A raw data structure. It is just an encoding of a U8a, without any length encoding /**
* @name Data
* @description
* A raw data structure. It is just an encoding of a U8a, without any length encoding
*/
export default class Data extends U8a { export default class Data extends U8a {
} }
+34 -4
View File
@@ -12,16 +12,36 @@ import Hash from './Hash';
import Signature from './Signature'; import Signature from './Signature';
import U64 from './U64'; import U64 from './U64';
class AuthoritiesChange extends Vector.with(AuthorityId) { /**
* @name AuthoritiesChange
* @description
* Log for Authories changed
*/
export class AuthoritiesChange extends Vector.with(AuthorityId) {
} }
class ChangesTrieRoot extends Hash { /**
* @name ChangesTrieRoot
* @description
* Log for changes to the Trie root
*/
export class ChangesTrieRoot extends Hash {
} }
class Other extends Bytes { /**
* @name Other
* @description
* Log item that is just a stream of [[Bytes]]
*/
export class Other extends Bytes {
} }
class Seal extends Tuple { /**
* @name Seal
* @description
* Log item indicating a sealing event
*/
export class Seal extends Tuple {
constructor (value: any) { constructor (value: any) {
super({ super({
slot: U64, slot: U64,
@@ -38,6 +58,11 @@ class Seal extends Tuple {
} }
} }
/**
* @name DigestItem
* @description
* A [[EnumType]] the specifies the specific item in the logs of a [[Digest]]
*/
export class DigestItem extends EnumType<AuthoritiesChange | ChangesTrieRoot | Other export class DigestItem extends EnumType<AuthoritiesChange | ChangesTrieRoot | Other
| Seal> { | Seal> {
constructor (value: any) { constructor (value: any) {
@@ -50,6 +75,11 @@ export class DigestItem extends EnumType<AuthoritiesChange | ChangesTrieRoot | O
} }
} }
/**
* @name Digest
* @description
* A [[Header]] Digest
*/
export default class Digest extends Struct { export default class Digest extends Struct {
constructor (value: any) { constructor (value: any) {
super({ super({
+19 -3
View File
@@ -14,7 +14,12 @@ import Metadata, { EventMetadata } from './Metadata';
const EventTypes: { [index: string]: Constructor<EventData> } = {}; const EventTypes: { [index: string]: Constructor<EventData> } = {};
class EventData extends Tuple { /**
* @name EventData
* @description
* Wrapper for the actual data that forms part of an [[Event]]
*/
export class EventData extends Tuple {
private _meta: EventMetadata; private _meta: EventMetadata;
private _method: string; private _method: string;
private _section: string; private _section: string;
@@ -46,13 +51,24 @@ class EventData extends Tuple {
} }
} }
// like methods, we have the [sectionIndex, methodIndex] pairing /**
class EventIndex extends U8aFixed { * @name EventIndex
* @description
* This follows the same approach as in [[Method]], we have the `[sectionIndex, methodIndex]` pairing
* that indicates the actual event fired
*/
export class EventIndex extends U8aFixed {
constructor (value?: any) { constructor (value?: any) {
super(value, 16); super(value, 16);
} }
} }
/**
* @name Event
* @description
* A representation of a system event. These are generated via the [[Metadata]] interfaces and
* specific to a specific Substrate runtime
*/
export default class Event extends Struct { export default class Event extends Struct {
// Currently we _only_ decode from Uint8Array, since we expect it to // Currently we _only_ decode from Uint8Array, since we expect it to
// be used via EventRecord // be used via EventRecord
+24 -3
View File
@@ -8,13 +8,28 @@ import Event from './Event';
import Null from './Null'; import Null from './Null';
import U32 from './U32'; import U32 from './U32';
class ApplyExtrinsic extends U32 { /**
* @name ApplyExtrinsic
* @description
* The [[Phase]] where the extrinsic is applied
*/
export class ApplyExtrinsic extends U32 {
} }
class Finalization extends Null { /**
* @name Finalization
* @description
* The [[Phase]] where the extrinsic is being Finalized
*/
export class Finalization extends Null {
} }
class Phase extends EnumType<ApplyExtrinsic | Finalization> { /**
* @name Phase
* @description
* An [[EnumType]] that indicates the specific phase where the [[EventRecord]] was generated
*/
export class Phase extends EnumType<ApplyExtrinsic | Finalization> {
constructor (value: any, index?: number) { constructor (value: any, index?: number) {
super([ super([
ApplyExtrinsic, ApplyExtrinsic,
@@ -23,6 +38,12 @@ class Phase extends EnumType<ApplyExtrinsic | Finalization> {
} }
} }
/**
* @name EventRecord
* @description
* A record for an [[Event]] (as specified by [[Metadata]]) with the specific [[Phase]] of
* application.
*/
export default class EventRecord extends Struct { export default class EventRecord extends Struct {
constructor (value: any) { constructor (value: any) {
super({ super({
+16 -14
View File
@@ -22,6 +22,8 @@ type ExtrinsicValue = {
}; };
/** /**
* @name Extrinsic
* @description
* Representation of an Extrinsic in the system. It contains the actual call, * Representation of an Extrinsic in the system. It contains the actual call,
* (optional) signature and encodes with an actual length prefix * (optional) signature and encodes with an actual length prefix
* *
@@ -75,6 +77,12 @@ export default class Extrinsic extends Struct {
return this.method.data; return this.method.data;
} }
get encodedLength (): number {
const length = this.length;
return length + Compact.encodeU8a(length).length;
}
// convernience, encodes the extrinsic and returns the actual hash // convernience, encodes the extrinsic and returns the actual hash
get hash (): Hash { get hash (): Hash {
return new Hash( return new Hash(
@@ -102,12 +110,6 @@ export default class Extrinsic extends Struct {
return this.get('signature') as ExtrinsicSignature; return this.get('signature') as ExtrinsicSignature;
} }
get encodedLength (): number {
const length = this.length;
return length + Compact.encodeU8a(length).length;
}
addSignature (signer: Address | Uint8Array, signature: Uint8Array, nonce: AnyNumber, era?: Uint8Array): Extrinsic { addSignature (signer: Address | Uint8Array, signature: Uint8Array, nonce: AnyNumber, era?: Uint8Array): Extrinsic {
this.signature.addSignature(signer, signature, nonce, era); this.signature.addSignature(signer, signature, nonce, era);
@@ -120,14 +122,6 @@ export default class Extrinsic extends Struct {
return this; return this;
} }
toU8a (isBare?: boolean): Uint8Array {
const encoded = super.toU8a();
return isBare
? encoded
: Compact.addLengthPrefix(encoded);
}
toHex (): string { toHex (): string {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
@@ -135,4 +129,12 @@ export default class Extrinsic extends Struct {
toJSON (): any { toJSON (): any {
return this.toHex(); return this.toHex();
} }
toU8a (isBare?: boolean): Uint8Array {
const encoded = super.toU8a();
return isBare
? encoded
: Compact.addLengthPrefix(encoded);
}
} }
+5
View File
@@ -8,6 +8,11 @@ import { u8aToU8a } from '@polkadot/util';
import U8a from './codec/U8a'; import U8a from './codec/U8a';
/**
* @name ExtrinsicEra
* @description
* The era for an extrinsic, indicating either a mortal or immortal extrinsic
*/
export default class ExtrinsicEra extends U8a { export default class ExtrinsicEra extends U8a {
constructor (value?: AnyU8a) { constructor (value?: AnyU8a) {
super( super(
+10 -5
View File
@@ -29,12 +29,17 @@ const BIT_UNSIGNED = 0;
const BIT_VERSION = 0b0000001; const BIT_VERSION = 0b0000001;
const EMPTY_U8A = new Uint8Array(); const EMPTY_U8A = new Uint8Array();
// Signature Information. /**
// 1/3/5/9/33 bytes: The signing account identity, in Address format * @name ExtrinsicSignature
// 64 bytes: The Ed25519 signature of the Signing Payload * @description
// 8 bytes: The Transaction Index of the signing account * A container for the [[Signature]] associated with a specific [[Extrinsic]]
// 1/2 bytes: The Transaction Era */
export default class ExtrinsicSignature extends Struct { export default class ExtrinsicSignature extends Struct {
// Signature Information.
// 1/3/5/9/33 bytes: The signing account identity, in Address format
// 64 bytes: The Ed25519 signature of the Signing Payload
// 8 bytes: The Transaction Index of the signing account
// 1/2 bytes: The Transaction Era
constructor (value?: ExtrinsicSignatureValue | Uint8Array) { constructor (value?: ExtrinsicSignatureValue | Uint8Array) {
super({ super({
signer: Address, signer: Address,
+25
View File
@@ -8,18 +8,43 @@ import Hash from './Hash';
import Null from './Null'; import Null from './Null';
import Text from './Text'; import Text from './Text';
/**
* @name Broadcast
* @description
* An [[ExtrinsicStatus]] indicating that the [[Extrinsic]] has been boradcast to peers
*/
export class Broadcast extends Vector.with(Text) { export class Broadcast extends Vector.with(Text) {
} }
/**
* @name Dropped
* @description
* An [[ExtrinsicStatus]] indicating that the [[Extrinsic]] has been dropped
*/
export class Dropped extends Null { export class Dropped extends Null {
} }
/**
* @name Finalised
* @description
* An [[ExtrinsicStats] indicating that the [[Extrinsic]]] has been finalised and included
*/
export class Finalised extends Hash { export class Finalised extends Hash {
} }
/**
* @name Usurped
* @description
* An [[ExtrinsicStatus]] indicating that the [[Extrinsic]] has been usurped
*/
export class Usurped extends Hash { export class Usurped extends Hash {
} }
/**
* @name ExtrinsicStatus
* @description
* An [[EnumType]] that indicates the status of the [[Extrinsic]] as been submitted
*/
export default class ExtrinsicStatus extends EnumType<Finalised | Usurped | Broadcast | Dropped> { export default class ExtrinsicStatus extends EnumType<Finalised | Usurped | Broadcast | Dropped> {
constructor (value: any, index?: number) { constructor (value: any, index?: number) {
super([ super([
+5 -1
View File
@@ -5,6 +5,10 @@
import Vector from './codec/Vector'; import Vector from './codec/Vector';
import Extrinsic from './Extrinsic'; import Extrinsic from './Extrinsic';
// A list of extrinsics /**
* @name Extrinsics
* @description
* A [[Vector]] of [[Extrinsic]]
*/
export default class Extrinsics extends Vector.with(Extrinsic) { export default class Extrinsics extends Vector.with(Extrinsic) {
} }
+5 -1
View File
@@ -4,6 +4,10 @@
import U64 from './U64'; import U64 from './U64';
// Gas for contracts /**
* @name Gas
* @description
* A gas number type for Substrate, extending [[U64]]
*/
export default class Gas extends U64 { export default class Gas extends U64 {
} }
+6 -2
View File
@@ -6,8 +6,12 @@ import { AnyU8a } from './types';
import U8aFixed from './codec/U8aFixed'; import U8aFixed from './codec/U8aFixed';
// Hash containing 256 bits (32 bytes), typically used in blocks, extrinsics and /**
// as a sane default for fixed-length hash representations. * @name H256
* @description
* Hash containing 256 bits (32 bytes), typically used in blocks, extrinsics and
* as a sane default for fixed-length hash representations.
*/
export default class H256 extends U8aFixed { export default class H256 extends U8aFixed {
constructor (value?: AnyU8a) { constructor (value?: AnyU8a) {
super(value, 256); super(value, 256);
+5 -1
View File
@@ -6,7 +6,11 @@ import { AnyU8a } from './types';
import U8aFixed from './codec/U8aFixed'; import U8aFixed from './codec/U8aFixed';
// Hash containing 512 bits (64 bytes), typically used for signatures /**
* @name H512
* @description
* Hash containing 512 bits (64 bytes), typically used for signatures
*/
export default class H512 extends U8aFixed { export default class H512 extends U8aFixed {
constructor (value?: AnyU8a) { constructor (value?: AnyU8a) {
super(value, 512); super(value, 512);
+6 -2
View File
@@ -4,7 +4,11 @@
import H256 from './H256'; import H256 from './H256';
// The default hash that is used accross the system. It is basically just a thin /**
// wrapper around H256, representing a 32-byte blake2b (Substrate) value * @name Hash
* @description
* The default hash that is used accross the system. It is basically just a thin
* wrapper around [[H256]], representing a 32-byte blake2b (Substrate) value
*/
export default class Hash extends H256 { export default class Hash extends H256 {
} }
+5 -1
View File
@@ -21,7 +21,11 @@ export type HeaderValue = {
stateRoot?: AnyU8a stateRoot?: AnyU8a
}; };
// A block header. /**
* @name Header
* @description
* A [[Block]] header
*/
export default class Header extends Struct { export default class Header extends Struct {
constructor (value?: HeaderValue | Uint8Array) { constructor (value?: HeaderValue | Uint8Array) {
super({ super({
+10 -2
View File
@@ -17,11 +17,19 @@ export type RhdJustificationValue = {
signatures?: Array<BftAuthoritySignatureValue> signatures?: Array<BftAuthoritySignatureValue>
}; };
// generic justification, this is specific per consensus implementation /**
* @name Justification
* @description
* A generic justification as a stream of [[Bytes]], this is specific per consensus implementation
*/
export default class Justification extends Bytes { export default class Justification extends Bytes {
} }
// justification for Rhododendron /**
* @name RhdJustification
* @description
* [[Justification]] for the Rhododendron consensus algorithm
*/
export class RhdJustification extends Struct { export class RhdJustification extends Struct {
constructor (value?: RhdJustificationValue | Uint8Array) { constructor (value?: RhdJustificationValue | Uint8Array) {
super({ super({
+15 -7
View File
@@ -15,10 +15,14 @@ type KeyValueValue = {
value?: AnyU8a value?: AnyU8a
}; };
// KeyValue structure. Since most of the keys and resultant values in Subtrate is /**
// hashed and/or encoded, this does not wrap a Text, but rather a Bytes * @name KeyValue
// for the keys and values. (Not to be confused with the KeyValue in Metadata, that * @description
// is actually for Maps, whereas this is a representation of actaul storage values) * KeyValue structure. Since most of the keys and resultant values in Subtrate is
* hashed and/or encoded, this does not wrap [[Text]], but rather a [[Bytes]]
* for the keys and values. (Not to be confused with the KeyValue in [[Metadata]], that
* is actually for Maps, whereas this is a representation of actaul storage values)
*/
export default class KeyValue extends Struct { export default class KeyValue extends Struct {
constructor (value?: KeyValueValue | Uint8Array) { constructor (value?: KeyValueValue | Uint8Array) {
super({ super({
@@ -41,9 +45,13 @@ export type KeyValueOptionValue = {
value?: AnyU8a value?: AnyU8a
}; };
// A key/value change. This is similar to the KeyValue structure, /**
// however in this case the value could be optional. Here it extends * @name KeyValueOption
// from a Tuple, indicating the use inside areas such as StorageChangeSet * @description
* A key/value change. This is similar to the [[KeyValue]] structure,
* however in this case the value could be optional. Here it extends
* from a [[Tuple]], indicating the use inside areas such as [[StorageChangeSet]]
*/
export class KeyValueOption extends Tuple { export class KeyValueOption extends Tuple {
constructor (value?: KeyValueOptionValue | Uint8Array) { constructor (value?: KeyValueOptionValue | Uint8Array) {
super({ super({
+5
View File
@@ -334,6 +334,11 @@ export class RuntimeModuleMetadata extends Struct {
} }
} }
/**
* @name Metadata
* @description
* The runtime metadata as a decoded structure
*/
export default class RuntimeMetadata extends Struct { export default class RuntimeMetadata extends Struct {
constructor (value?: any) { constructor (value?: any) {
super({ super({
+2
View File
@@ -57,6 +57,8 @@ class MethodIndex extends U8aFixed {
} }
/** /**
* @name Method
* @description
* Extrinsic function descriptor, as defined in * Extrinsic function descriptor, as defined in
* {@link https://github.com/paritytech/wiki/blob/master/Extrinsic.md#the-extrinsic-format-for-node}. * {@link https://github.com/paritytech/wiki/blob/master/Extrinsic.md#the-extrinsic-format-for-node}.
*/ */
+36 -7
View File
@@ -21,9 +21,12 @@ type BftAtReportValue = BftAtReportValueSingle & {
b?: BftHashSignatureValue b?: BftHashSignatureValue
}; };
// A report of a/b hash-signature pairs for a specific index. This is the same /**
// structure as is used in BftDoublePrepare & BftDoubleCommit * @name BftAtReport
// * @description
* A report of a/b hash-signature pairs for a specific index. This is the same
* structure as is used in BftDoublePrepare & BftDoubleCommit
*/
// FIXME It is not entirely obvious from the actual Rust code what the specific // FIXME It is not entirely obvious from the actual Rust code what the specific
// items in the structure is called, except a & b (one should be expected, the // items in the structure is called, except a & b (one should be expected, the
// other actual) // other actual)
@@ -49,6 +52,11 @@ export class BftAtReport extends Struct {
} }
} }
/**
* @name BftProposeOutOfTurn
* @description
* A report for out-of-turn proposals
*/
export class BftProposeOutOfTurn extends Struct { export class BftProposeOutOfTurn extends Struct {
constructor (value?: BftAtReportValue | Uint8Array) { constructor (value?: BftAtReportValue | Uint8Array) {
super({ super({
@@ -66,18 +74,35 @@ export class BftProposeOutOfTurn extends Struct {
} }
} }
// Report of a double-propose /**
* @name BftDoublePropose
* @description
* Report of a double-propose
*/
export class BftDoublePropose extends BftAtReport { export class BftDoublePropose extends BftAtReport {
} }
// Report of a double-prepare /**
* @name BftDoublePrepare
* @description
* Report of a double-prepare
*/
export class BftDoublePrepare extends BftAtReport { export class BftDoublePrepare extends BftAtReport {
} }
// Report of a double-commit /**
* @name BftDoubleCommit
* @description
* Report of a double-commit
*/
export class BftDoubleCommit extends BftAtReport { export class BftDoubleCommit extends BftAtReport {
} }
/**
* @name MisbehaviorKind
* @description
* An [[EnumType]] containing a Bft misbehaviour
*/
export class MisbehaviorKind extends EnumType<BftProposeOutOfTurn | BftDoublePropose | BftDoublePrepare | BftDoubleCommit> { export class MisbehaviorKind extends EnumType<BftProposeOutOfTurn | BftDoublePropose | BftDoublePrepare | BftDoubleCommit> {
constructor (value?: BftAtReportValue | Uint8Array, index?: number) { constructor (value?: BftAtReportValue | Uint8Array, index?: number) {
super([ super([
@@ -96,7 +121,11 @@ type MisbehaviorReportValue = {
target?: AuthorityId | string target?: AuthorityId | string
}; };
// A Misbehaviour report against a specific AuthorityId /**
* @name MisbehaviorReport
* @description
* A Misbehaviour report of [[MisbehavioirKind]] against a specific [[AuthorityId]]
*/
export default class MisbehaviorReport extends Struct { export default class MisbehaviorReport extends Struct {
constructor (value?: MisbehaviorReportValue | Uint8Array) { constructor (value?: MisbehaviorReportValue | Uint8Array) {
super({ super({
+18 -14
View File
@@ -10,10 +10,14 @@ import { AnyNumber, Codec } from './types';
const BITLENGTH: UIntBitLength = 64; const BITLENGTH: UIntBitLength = 64;
// A wrapper around seconds/timestamps. Internally the representation only has /**
// second precicion (aligning with Rust), so any numbers passed an/out are always * @name Moment
// per-second. For any encoding/decoding the 1000 multiplier would be applied to * @description
// get it in line with JavaScript formats * A wrapper around seconds/timestamps. Internally the representation only has
* second precicion (aligning with Rust), so any numbers passed an/out are always
* per-second. For any encoding/decoding the 1000 multiplier would be applied to
* get it in line with JavaScript formats
*/
export default class Moment extends Date implements Codec { export default class Moment extends Date implements Codec {
public raw: Date; // FIXME Remove this once we convert all types out of Base public raw: Date; // FIXME Remove this once we convert all types out of Base
@@ -39,12 +43,16 @@ export default class Moment extends Date implements Codec {
); );
} }
get encodedLength (): number {
return BITLENGTH / 8;
}
bitLength (): UIntBitLength { bitLength (): UIntBitLength {
return BITLENGTH; return BITLENGTH;
} }
get encodedLength (): number { toBn (): BN {
return BITLENGTH / 8; return new BN(this.toNumber());
} }
toHex (): string { toHex (): string {
@@ -55,15 +63,11 @@ export default class Moment extends Date implements Codec {
return this.toNumber(); return this.toNumber();
} }
toU8a (isBare?: boolean): Uint8Array {
return bnToU8a(this.toNumber(), BITLENGTH, true);
}
toBn (): BN {
return new BN(this.toNumber());
}
toNumber (): number { toNumber (): number {
return Math.ceil(this.getTime() / 1000); return Math.ceil(this.getTime() / 1000);
} }
toU8a (isBare?: boolean): Uint8Array {
return bnToU8a(this.toNumber(), BITLENGTH, true);
}
} }
+5 -1
View File
@@ -5,7 +5,11 @@
import Enum from './codec/Enum'; import Enum from './codec/Enum';
import U8a from './codec/U8a'; import U8a from './codec/U8a';
// Enum to track the outcome for creation of an account /**
* @name NewAccountOutcome
* @description
* Enum to track the outcome for creation of an [[AccountId]]
*/
export default class NewAccountOutcome extends Enum { export default class NewAccountOutcome extends Enum {
constructor (index?: U8a | Uint8Array | number) { constructor (index?: U8a | Uint8Array | number) {
super([ super([
+7 -2
View File
@@ -4,7 +4,12 @@
import U64 from './U64'; import U64 from './U64';
// The Nonce or number of transactiosn sent by a specific account. Generally used /**
// with extrinsics to determine the order of execution. * @name Nonce
* @description
* The Nonce or number of transactions sent by a specific account. Generally used
* with extrinsics to determine the order of execution. implemented as a Substrate
* [[U64]]
*/
export default class Index extends U64 { export default class Index extends U64 {
} }
+19 -5
View File
@@ -4,7 +4,11 @@
import { Codec } from './types'; import { Codec } from './types';
// Implements a type that does not contain anything (apart from `null`) /**
* @name Null
* @description
* Implements a type that does not contain anything (apart from `null`)
*/
export default class Null implements Codec { export default class Null implements Codec {
get encodedLength (): number { get encodedLength (): number {
return 0; return 0;
@@ -14,15 +18,25 @@ export default class Null implements Codec {
return '0x'; return '0x';
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return null; return null;
} }
toU8a (isBare?: boolean): Uint8Array { /**
return new Uint8Array(); * @description Returns the string representation of the value
} */
toString (): string { toString (): string {
return ''; return '';
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
return new Uint8Array();
}
} }
+6 -1
View File
@@ -2,7 +2,12 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
// Where Origin occurs, it should be ignored, so it should never actually be constructed /**
* @name Origin
* @description
* Where Origin occurs, it should be ignored as an internal-only value, so it should
* never actually be constructed
*/
export default class Origin { export default class Origin {
constructor () { constructor () {
throw new Error('Origin should not be constructed, it is only a placeholder for compatibility'); throw new Error('Origin should not be constructed, it is only a placeholder for compatibility');
+5 -1
View File
@@ -4,6 +4,10 @@
import U64 from './U64'; import U64 from './U64';
// Identifier for a deployed parachain /**
* @name ParachainId
* @description
* Identifier for a deployed parachain implemented as a [[U64]]
*/
export default class ParachainId extends U64 { export default class ParachainId extends U64 {
} }
+5 -1
View File
@@ -4,6 +4,10 @@
import Extrinsics from './Extrinsics'; import Extrinsics from './Extrinsics';
// A list of pending extrinsics /**
* @name PendingExtrinsics
* @description
* A list of pending [[Extrinsics]]
*/
export default class PendingExtrinsics extends Extrinsics { export default class PendingExtrinsics extends Extrinsics {
} }
+5 -2
View File
@@ -4,8 +4,11 @@
import U32 from './U32'; import U32 from './U32';
// Parts per billion (see also Permill) /**
// * @name Perbill
* @description
* Parts per billion (see also [[Permill]])
*/
// TODO We need to think about the toNumber() and toString() here, so we // TODO We need to think about the toNumber() and toString() here, so we
// want to multiply by 1_000_000_000 for those purposes? // want to multiply by 1_000_000_000 for those purposes?
export default class Perbill extends U32 { export default class Perbill extends U32 {
+5 -2
View File
@@ -4,8 +4,11 @@
import U32 from './U32'; import U32 from './U32';
// Parts per million (See also Perbill) /**
// * @name Permill
* @description
* Parts per million (See also [[Perbill]])
*/
// TODO We need to think about the toNumber() and toString() here, so we // TODO We need to think about the toNumber() and toString() here, so we
// want to multiply by 1_000_000 for those purposes? // want to multiply by 1_000_000 for those purposes?
export default class Permill extends U32 { export default class Permill extends U32 {
+6 -1
View File
@@ -4,6 +4,11 @@
import U32 from './U32'; import U32 from './U32';
// An increasing number that represents a specific public proposal index in the system /**
* @name PropIndex
* @description
* An increasing number that represents a specific public proposal index in the
* system, implemented as a [[U32]]
*/
export default class PropIndex extends U32 { export default class PropIndex extends U32 {
} }
+5 -1
View File
@@ -4,6 +4,10 @@
import Method from './Method'; import Method from './Method';
// A proposal in the system. It just extends a method (Proposal = Call in Rust) /**
* @name Proposal
* @description
* A proposal in the system. It just extends [[Method]] (Proposal = Call in Rust)
*/
export default class Proposal extends Method { export default class Proposal extends Method {
} }
+6 -1
View File
@@ -4,6 +4,11 @@
import U32 from './U32'; import U32 from './U32';
// An increasing number that represents a specific council proposal index in the system /**
* @name ProposalIndex
* @description
* An increasing number that represents a specific council proposal index in
* the system, implemented as [[U32]]
*/
export default class ProposalIndex extends U32 { export default class ProposalIndex extends U32 {
} }
+6 -2
View File
@@ -4,7 +4,11 @@
import U32 from './U32'; import U32 from './U32';
// An increasing number that represents a specific referendum in the system. It /**
// is unique per chain. * @name ReferendumIndex
* @description
* An increasing number that represents a specific referendum in the system. It
* is unique per chain. Implemented as [[U32]]
*/
export default class ReferendumIndex extends U32 { export default class ReferendumIndex extends U32 {
} }
+17 -2
View File
@@ -11,7 +11,12 @@ import Vector from './codec/Vector';
import Text from './Text'; import Text from './Text';
import U32 from './U32'; import U32 from './U32';
class ApiId extends U8aFixed { /**
* @name ApiId
* @description
* An identifier for the runtime API
*/
export class ApiId extends U8aFixed {
constructor (value?: AnyU8a) { constructor (value?: AnyU8a) {
super(value, 64); super(value, 64);
} }
@@ -22,7 +27,12 @@ type RuntimeVersionApiValue = {
version?: AnyNumber version?: AnyNumber
}; };
class RuntimeVersionApi extends Tuple { /**
* @name RuntimeVersionApi
* @description
* A [[Tuple]] that conatins the [[ApiId]] and [[U32]] version
*/
export class RuntimeVersionApi extends Tuple {
constructor (value?: RuntimeVersionApiValue | Uint8Array) { constructor (value?: RuntimeVersionApiValue | Uint8Array) {
super({ super({
id: ApiId, id: ApiId,
@@ -48,6 +58,11 @@ type RuntimeVersionValue = {
apis?: Array<RuntimeVersionApiValue> apis?: Array<RuntimeVersionApiValue>
}; };
/**
* @name RuntimeVersion
* @description
* A defintion of the runtime and the associated versions thereof
*/
export default class RuntimeVersion extends Struct { export default class RuntimeVersion extends Struct {
constructor (value?: RuntimeVersionValue | Uint8Array) { constructor (value?: RuntimeVersionValue | Uint8Array) {
super({ super({
+6 -2
View File
@@ -4,7 +4,11 @@
import AuthorityId from './AuthorityId'; import AuthorityId from './AuthorityId';
// Wrapper for a SessionKey. Same as an normal AuthorityId, i.e. a wrapper /**
// around publicKey. * @name SessionKey
* @description
* Wrapper for a SessionKey. Same as an normal [[AuthorityId]], i.e. a wrapper
* around publicKey.
*/
export default class SessionKey extends AuthorityId { export default class SessionKey extends AuthorityId {
} }
+6 -2
View File
@@ -4,7 +4,11 @@
import H512 from './H512'; import H512 from './H512';
// The default signature that is used accross the system. It is currectly defined /**
// as a 512-bit value, represented by a hash. * @name Signature
* @description
* The default signature that is used accross the system. It is currectly defined
* as a 512-bit value, represented by a [[H512]].
*/
export default class Signature extends H512 { export default class Signature extends H512 {
} }
+11 -5
View File
@@ -18,11 +18,17 @@ type SignaturePayloadValue = {
blockHash?: AnyU8a blockHash?: AnyU8a
}; };
// Signing Payload. /**
// 8 bytes: The Transaction Index/Nonce as provided in the transaction itself. * @name SignaturePayload
// 2+ bytes: The Function Descriptor as provided in the transaction itself. * @description
// 2 bytes: The Transaction Era as provided in the transaction itself. * A signing payload for an [[Extrinsic]]. For the final encoding, it is variable length based
// 32 bytes: The hash of the authoring block implied by the Transaction Era and the current block. * on the conetnts included
*
* 8 bytes: The Transaction Index/Nonce as provided in the transaction itself.
* 2+ bytes: The Function Descriptor as provided in the transaction itself.
* 2 bytes: The Transaction Era as provided in the transaction itself.
* 32 bytes: The hash of the authoring block implied by the Transaction Era and the current block.
*/
export default class SignaturePayload extends Struct { export default class SignaturePayload extends Struct {
protected _signature?: Uint8Array; protected _signature?: Uint8Array;
+5
View File
@@ -13,6 +13,11 @@ type SignedBlockValue = {
justification?: AnyU8a justification?: AnyU8a
}; };
/**
* @name SignedBlock
* @description
* A [[Block]] that has been signed and contains a [[Justification]]
*/
export default class SignedBlock extends Struct { export default class SignedBlock extends Struct {
constructor (value?: SignedBlockValue | Uint8Array) { constructor (value?: SignedBlockValue | Uint8Array) {
super({ super({
+7 -2
View File
@@ -14,8 +14,13 @@ type StorageChangeSetValue = {
changes?: Array<KeyValueOptionValue> changes?: Array<KeyValueOptionValue>
}; };
// A set of storage changes. It contains the hash/block and /**
// a list of the actual changes that took place * @name StorageChangeSet
* @description
* A set of storage changes. It contains the [[Block]] hash and
* a list of the actual changes that took place as an array of
* [[KeyValueOption]]
*/
export default class StorageChangeSet extends Struct { export default class StorageChangeSet extends Struct {
constructor (value?: StorageChangeSetValue | Uint8Array) { constructor (value?: StorageChangeSetValue | Uint8Array) {
super({ super({
+5 -1
View File
@@ -4,6 +4,10 @@
import Bytes from './Bytes'; import Bytes from './Bytes';
// Data retrieve via Storage queries and data for KeyValue pairs /**
* @name StorageData
* @description
* Data retrieved via Storage queries and data for KeyValue pairs
*/
export default class StorageData extends Bytes { export default class StorageData extends Bytes {
} }
+6 -2
View File
@@ -17,8 +17,12 @@ export interface StorageFunction {
toJSON: () => any; toJSON: () => any;
} }
// A representation of a storage key (typically hashed) in the system. It can be constructed /**
// by passing in a raw key or a StorageFunction with (optional) arguments. * @name StorageKey
* @description
* A representation of a storage key (typically hashed) in the system. It can be
* constructed by passing in a raw key or a StorageFunction with (optional) arguments.
*/
export default class StorageKey extends Bytes { export default class StorageKey extends Bytes {
private _outputType: string | null; private _outputType: string | null;
+11 -2
View File
@@ -23,7 +23,12 @@ export type StoredPendingChangeValue = {
nextAuthorities?: Array<Uint8Array | NextAuthorityValue> nextAuthorities?: Array<Uint8Array | NextAuthorityValue>
}; };
class NextAuthority extends Tuple { /**
* @name NextAuthority
* @description
* The next authority available as [[SessionKey]]
*/
export class NextAuthority extends Tuple {
constructor (value?: Uint8Array | NextAuthorityValue) { constructor (value?: Uint8Array | NextAuthorityValue) {
super({ super({
sessionKey: SessionKey, sessionKey: SessionKey,
@@ -40,7 +45,11 @@ class NextAuthority extends Tuple {
} }
} }
// Stored pending change for a Grandpa events /**
* @name StoredPendingChange
* @description
* Stored pending change for a Grandpa events
*/
export default class StoredPendingChange extends Struct { export default class StoredPendingChange extends Struct {
constructor (value?: Uint8Array | StoredPendingChangeValue) { constructor (value?: Uint8Array | StoredPendingChangeValue) {
super({ super({
+6 -3
View File
@@ -7,9 +7,12 @@ import { isFunction, isString, stringToU8a, u8aToString, u8aToHex } from '@polka
import { AnyU8a, Codec } from './types'; import { AnyU8a, Codec } from './types';
import Compact from './codec/Compact'; import Compact from './codec/Compact';
// This is a string wrapper, along with the length. It is used both for strings as well /**
// as stuff like documentation. * @name Text
// * @description
* This is a string wrapper, along with the length. It is used both for strings as well
* as items such as documentation.
*/
// TODO // TODO
// - Strings should probably be trimmed (docs do come through with extra padding) // - Strings should probably be trimmed (docs do come through with extra padding)
// - Potentially we want a "TypeString" extension to this. Basically something that // - Potentially we want a "TypeString" extension to this. Basically something that
+13 -9
View File
@@ -9,9 +9,13 @@ type Mapper = (value: string) => string;
const ALLOWED_BOXES = ['Compact', 'Option', 'Vec']; const ALLOWED_BOXES = ['Compact', 'Option', 'Vec'];
// This is a extended version of String, specifically to handle types. Here we rely full on /**
// what string provides us, however we also "tweak" the types received from the runtime, i.e. * @name Type
// we remove the `T::` prefixes found in some types for consistency accross implementation. * @description
* This is a extended version of String, specifically to handle types. Here we rely fully
* on what string provides us, however we also adjust the types received from the runtime,
* i.e. we remove the `T::` prefixes found in some types for consistency accross implementation.
*/
export default class Type extends Text { export default class Type extends Text {
private _originalLength: number; private _originalLength: number;
@@ -57,17 +61,17 @@ export default class Type extends Text {
}, value).trim(); }, value).trim();
} }
// NOTE Length is used in the decoding calculations, so return the original (pre-cleanup)
// length of the data. Since toU8a is disabled, this does not affect encoding, but rather
// only the decoding leg, allowing the decoders to work with original pointers
get encodedLength (): number { get encodedLength (): number {
// NOTE Length is used in the decoding calculations, so return the original (pre-cleanup)
// length of the data. Since toU8a is disabled, this does not affect encoding, but rather
// only the decoding leg, allowing the decoders to work with original pointers
return this._originalLength + Compact.encodeU8a(this._originalLength).length; return this._originalLength + Compact.encodeU8a(this._originalLength).length;
} }
// Note Since we are mangling what we get in beyond recognition, we really should
// not allow the re-encoding. Additionally, this is probably more of a decoder-only
// helper, so treat it as such.
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
// Note Since we are mangling what we get in beyond recognition, we really should
// not allow the re-encoding. Additionally, this is probably more of a decoder-only
// helper, so treat it as such.
throw new Error('Type::toU8a: unimplemented'); throw new Error('Type::toU8a: unimplemented');
} }
+5
View File
@@ -6,6 +6,11 @@ import { AnyNumber } from './types';
import UInt from './codec/UInt'; import UInt from './codec/UInt';
/**
* @name U128
* @description
* An 128-bit number
*/
export default class U128 extends UInt { export default class U128 extends UInt {
constructor (value?: AnyNumber) { constructor (value?: AnyNumber) {
super(value, 128); super(value, 128);
+5
View File
@@ -6,6 +6,11 @@ import { AnyNumber } from './types';
import UInt from './codec/UInt'; import UInt from './codec/UInt';
/**
* @name U16
* @description
* An 16-bit number
*/
export default class U16 extends UInt { export default class U16 extends UInt {
constructor (value?: AnyNumber) { constructor (value?: AnyNumber) {
super(value, 16, false); super(value, 16, false);
+5
View File
@@ -6,6 +6,11 @@ import { AnyNumber } from './types';
import UInt from './codec/UInt'; import UInt from './codec/UInt';
/**
* @name U256
* @description
* An 256-bit number
*/
export default class U256 extends UInt { export default class U256 extends UInt {
constructor (value?: AnyNumber) { constructor (value?: AnyNumber) {
super(value, 256); super(value, 256);
+5
View File
@@ -6,6 +6,11 @@ import { AnyNumber } from './types';
import UInt from './codec/UInt'; import UInt from './codec/UInt';
/**
* @name U32
* @description
* An 32-bit number
*/
export default class U32 extends UInt { export default class U32 extends UInt {
constructor (value?: AnyNumber) { constructor (value?: AnyNumber) {
super(value, 32, false); super(value, 32, false);
+5
View File
@@ -6,6 +6,11 @@ import { AnyNumber } from './types';
import UInt from './codec/UInt'; import UInt from './codec/UInt';
/**
* @name U64
* @description
* An 64-bit number
*/
export default class U64 extends UInt { export default class U64 extends UInt {
constructor (value?: AnyNumber) { constructor (value?: AnyNumber) {
super(value, 64, false); super(value, 64, false);
+5
View File
@@ -6,6 +6,11 @@ import { AnyNumber } from './types';
import UInt from './codec/UInt'; import UInt from './codec/UInt';
/**
* @name U8
* @description
* An 8-bit number
*/
export default class U8 extends UInt { export default class U8 extends UInt {
constructor (value?: AnyNumber) { constructor (value?: AnyNumber) {
super(value, 8, false); super(value, 8, false);
+5
View File
@@ -13,6 +13,11 @@ type ValidatorPrefsValue = {
validatorPayment?: AnyNumber validatorPayment?: AnyNumber
}; };
/**
* @name ValidatorPrefs
* @description
* Validator preferences
*/
export default class ValidatorPrefs extends Struct { export default class ValidatorPrefs extends Struct {
constructor (value?: ValidatorPrefsValue | Uint8Array) { constructor (value?: ValidatorPrefsValue | Uint8Array) {
super({ super({
+5
View File
@@ -4,5 +4,10 @@
import U32 from './U32'; import U32 from './U32';
/**
* @name VoteIndex
* @description
* Voting index, implemented as a [[U32]]
*/
export default class VoteIndex extends U32 { export default class VoteIndex extends U32 {
} }
+5 -1
View File
@@ -4,7 +4,11 @@
import Enum from './codec/Enum'; import Enum from './codec/Enum';
// Voting threshold, used inside proposals to set change the voting tally /**
* @name VoteThreshold
* @description
* Voting threshold, used inside proposals to set change the voting tally
*/
export default class VoteThreshold extends Enum { export default class VoteThreshold extends Enum {
constructor (index?: number | Uint8Array) { constructor (index?: number | Uint8Array) {
super([ super([
+2 -1
View File
@@ -3,7 +3,8 @@
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
/** /**
* A type extends the Base class, when it holds a value * @name Base
* @description A type extends the Base class, when it holds a value
*/ */
export default class Base<T = any> { export default class Base<T = any> {
protected raw: T; protected raw: T;
+37 -19
View File
@@ -11,21 +11,14 @@ import Base from './Base';
import UInt, { UIntBitLength } from './UInt'; import UInt, { UIntBitLength } from './UInt';
import Moment from '../Moment'; import Moment from '../Moment';
// A new compact length-encoding algorithm. It performs the same function as Length, however /**
// differs in that it uses a variable number of bytes to do the actual encoding. From the Rust * @name Compact
// implementation for compact encoding * @description
// * A compact length-encoding codec wrapper. It performs the same function as Length, however
// 0b00 00 00 00 / 00 00 00 00 / 00 00 00 00 / 00 00 00 00 * differs in that it uses a variable number of bytes to do the actual encoding. This is mostly
// (0 ... 2**6 - 1) (u8) * used by other types to add length-prefixed encoding, or in the case of wrapped types, taking
// xx xx xx 00 * a number and making the compact representation thereof
// (2**6 ... 2**14 - 1) (u8, u16) low LH high */
// yL yL yL 01 / yH yH yH yL
// (2**14 ... 2**30 - 1) (u16, u32) low LMMH high
// zL zL zL 10 / zM zM zM zL / zM zM zM zM / zH zH zH zM
// (2**30 ... 2**536 - 1) (u32, u64, u128, U256, U512, U520) straight LE-encoded
// nn nn nn 11 [ / zz zz zz zz ]{4 + n}
//
// Note: we use *LOW BITS* of the LSB in LE encoding to encode the 2 bit key.
export default class Compact extends Base<UInt | Moment> implements Codec { export default class Compact extends Base<UInt | Moment> implements Codec {
constructor (Type: Constructor<UInt | Moment>, value: AnyNumber = 0) { constructor (Type: Constructor<UInt | Moment>, value: AnyNumber = 0) {
super(Compact.decodeCompact(Type, value)); super(Compact.decodeCompact(Type, value));
@@ -72,34 +65,59 @@ export default class Compact extends Base<UInt | Moment> implements Codec {
return new Type(value.toBn()); return new Type(value.toBn());
} }
bitLength (): UIntBitLength { /**
return this.raw.bitLength(); * @description The length of the value when encoded as a Uint8Array
} */
get encodedLength (): number { get encodedLength (): number {
return this.toU8a().length; return this.toU8a().length;
} }
/**
* @description Returns the number of bits in the value
*/
bitLength (): UIntBitLength {
return this.raw.bitLength();
}
/**
* @description Returns the BN representation of the number
*/
toBn (): BN { toBn (): BN {
return this.raw.toBn(); return this.raw.toBn();
} }
/**
* @description Returns a hex string representation of the value
*/
toHex (): any { toHex (): any {
return this.raw.toHex(); return this.raw.toHex();
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this.raw.toJSON(); return this.raw.toJSON();
} }
/**
* @description Returns the number representation for the value
*/
toNumber (): number { toNumber (): number {
return this.raw.toNumber(); return this.raw.toNumber();
} }
/**
* @description Returns the string representation of the value
*/
toString (): string { toString (): string {
return this.raw.toString(); return this.raw.toString();
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
return Compact.encodeU8a(this.raw.toBn(), this.bitLength()); return Compact.encodeU8a(this.raw.toBn(), this.bitLength());
} }
+27 -5
View File
@@ -11,11 +11,14 @@ type EnumDef = {
[index: number]: string [index: number]: string
} | Array<string>; } | Array<string>;
// A codec wrapper for an enum. Enums are encoded as a single byte, where the byte /**
// is a zero-indexed value. This class allows you to retrieve the value either * @name Enum
// by `toNumber()` exposing the actual raw index, or `toString()` returning a * @description
// string representation (as provided as part of the constructor) * A codec wrapper for an enum. Enums are encoded as a single byte, where the byte
// * is a zero-indexed value. This class allows you to retrieve the value either
* by `toNumber()` exposing the actual raw index, or `toString()` returning a
* string representation (as provided as part of the constructor)
*/
// TODO: // TODO:
// - It would be great if this could actually wrap actual TS enums // - It would be great if this could actually wrap actual TS enums
export default class Enum extends Base<number> implements Codec { export default class Enum extends Base<number> implements Codec {
@@ -39,26 +42,45 @@ export default class Enum extends Base<number> implements Codec {
} }
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number { get encodedLength (): number {
return 1; return 1;
} }
/**
* @description Returns a hex string representation of the value
*/
toHex (): string { toHex (): string {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this.raw; return this.raw;
} }
/**
* @description Returns the number representation for the value
*/
toNumber (): number { toNumber (): number {
return this.raw; return this.raw;
} }
/**
* @description Returns the string representation of the value
*/
toString (): string { toString (): string {
return this._enum[this.raw] || `${this.raw}`; return this._enum[this.raw] || `${this.raw}`;
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
return new Uint8Array([this.raw]); return new Uint8Array([this.raw]);
} }
+53 -15
View File
@@ -13,9 +13,12 @@ type TypesDef = {
[index: number]: Constructor [index: number]: Constructor
} | TypesArray; } | TypesArray;
// This implements an enum, that based on the value wraps a different type. It is effectively an /**
// extension to enum where the value type is determined by the actual index. * @name EnumType
// * @description
* This implements an enum, that based on the value wraps a different type. It is effectively
* an extension to enum where the value type is determined by the actual index.
*/
// TODO: // TODO:
// - As per Enum, actually use TS enum // - As per Enum, actually use TS enum
// - It should rather probably extend Enum instead of copying code // - It should rather probably extend Enum instead of copying code
@@ -78,38 +81,73 @@ export default class EnumType<T> extends Base<Codec> implements Codec {
return { index: 0, value: new (Object.values(def)[0])() }; return { index: 0, value: new (Object.values(def)[0])() };
} }
get isNull (): boolean { /**
return this.raw instanceof Null; * @description The length of the value when encoded as a Uint8Array
} */
get type (): string {
return this._Types[this._index].name;
}
get value (): Codec {
return this.raw;
}
get encodedLength (): number { get encodedLength (): number {
return 1 + this.raw.encodedLength; return 1 + this.raw.encodedLength;
} }
/**
* @description Checks if the Enum points to a [[Null]] type
*/
get isNone (): boolean {
return this.raw instanceof Null;
}
/**
* @description Checks if the Enum points to a [[Null]] type (deprecated, use isNone)
*/
get isNull (): boolean {
return this.raw instanceof Null;
}
/**
* @description The name of the type this enum value represents
*/
get type (): string {
return this._Types[this._index].name;
}
/**
* @description The value of the enum
*/
get value (): Codec {
return this.raw;
}
/**
* @description Returns a hex string representation of the value
*/
toHex (): string { toHex (): string {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this.raw; return this.raw;
} }
/**
* @description Returns the number representation for the value
*/
toNumber (): number { toNumber (): number {
return this._index; return this._index;
} }
/**
* @description Returns the string representation of the value
*/
toString (): string { toString (): string {
return this.type; return this.type;
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
const index = this._indexes[this._index]; const index = this._indexes[this._index];
+46 -12
View File
@@ -8,10 +8,14 @@ import Base from './Base';
import { Codec, Constructor } from '../types'; import { Codec, Constructor } from '../types';
import Null from '../Null'; import Null from '../Null';
// An Option is an optional field. Basically the first byte indicates that there is /**
// is value to follow. If the byte is `1` there is an actual value. So the Option * @name Option
// implements that - decodes, checks for optionality and wraps the required structure * @description
// with a value if/as required/found. * An Option is an optional field. Basically the first byte indicates that there is
* is value to follow. If the byte is `1` there is an actual value. So the Option
* implements that - decodes, checks for optionality and wraps the required structure
* with a value if/as required/found.
*/
export default class Option<T extends Codec> extends Base<T> implements Codec { export default class Option<T extends Codec> extends Base<T> implements Codec {
constructor (Type: Constructor, value?: any) { constructor (Type: Constructor, value?: any) {
super( super(
@@ -42,30 +46,60 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
}; };
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
// boolean byte (has value, doesn't have) along with wrapped length
return 1 + this.raw.encodedLength;
}
/**
* @description Checks if the Option has no value
*/
get isNone (): boolean { get isNone (): boolean {
return this.raw instanceof Null; return this.raw instanceof Null;
} }
/**
* @description Checks if the Option has a value
*/
get isSome (): boolean { get isSome (): boolean {
return !this.isNone; return !this.isNone;
} }
/**
* @description The actual value for the Option
*/
get value (): Codec { get value (): Codec {
return this.raw; return this.raw;
} }
get encodedLength (): number { /**
return 1 + this.raw.encodedLength; * @description Returns a hex string representation of the value
} */
toHex (): string { toHex (): string {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this.raw.toJSON(); return this.raw.toJSON();
} }
/**
* @description Returns the string representation of the value
*/
toString (): string {
return this.raw.toString();
}
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
if (isBare) { if (isBare) {
return this.raw.toU8a(true); return this.raw.toU8a(true);
@@ -81,14 +115,14 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
return u8a; return u8a;
} }
toString (): string { /**
return this.raw.toString(); * @description Returns the value that the Option represents (if available)
} */
unwrap (): T { unwrap (): T {
if (this.isNone) { if (this.isNone) {
throw new Error('Option: unwrapping a None value'); throw new Error('Option: unwrapping a None value');
} }
return this.raw; return this.raw;
} }
} }
+36 -8
View File
@@ -11,10 +11,13 @@ type SetValues = {
[index: string]: number [index: string]: number
}; };
// An Set is an array of string values, represented an an encoded type by /**
// a bitwise representation of the values. * @name Set
// * @description
// FIXME This is a prime candidate to potentially extend Set * An Set is an array of string values, represented an an encoded type by
* a bitwise representation of the values.
*/
// FIXME This is a prime candidate to extend the JavaScript built-in Set
export default class Set extends Base<Array<string>> implements Codec { export default class Set extends Base<Array<string>> implements Codec {
private _setValues: SetValues; private _setValues: SetValues;
@@ -63,35 +66,60 @@ export default class Set extends Base<Array<string>> implements Codec {
}, 0); }, 0);
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number { get encodedLength (): number {
return 1; return 1;
} }
/**
* @description true is the Set contains no values
*/
get isEmpty (): boolean { get isEmpty (): boolean {
return this.values.length === 0; return this.values.length === 0;
} }
/**
* @description The actual set values as a Array<string>
*/
get values (): Array<string> { get values (): Array<string> {
return this.raw; return this.raw;
} }
/**
* @description The encoded value for the set members
*/
get valueEncoded (): number { get valueEncoded (): number {
return Set.encodeSet(this._setValues, this.raw); return Set.encodeSet(this._setValues, this.raw);
} }
/**
* @description Returns a hex string representation of the value
*/
toHex (): string { toHex (): string {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this.values; return this.values;
} }
/**
* @description Returns the string representation of the value
*/
toString (): string {
return `[${this.values.join(', ')}]`;
}
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
return new Uint8Array(this.valueEncoded); return new Uint8Array(this.valueEncoded);
} }
toString (): string {
return `[${this.values.map((value) => value).join(', ')}]`;
}
} }
+31 -5
View File
@@ -6,11 +6,15 @@ import { hexToU8a, isHex, isObject, isU8a, u8aConcat, u8aToHex } from '@polkadot
import { Codec, Constructor, ConstructorDef } from '../types'; import { Codec, Constructor, ConstructorDef } from '../types';
// A Struct defines an Object with key/values - where the values are Codec values. It removes /**
// a lot of repetition from the actual coding, define a structure type, pass it the key/Codec * @name Struct
// values in the constructor and it manages the decoding. It is important that the constructor * @description
// values matches 100% to the order in th Rust code, i.e. don't go crazy and make it alphabetical, * A Struct defines an Object with key/values - where the values are Codec values. It removes
// it needs to decoded in the specific defined order. * a lot of repetition from the actual coding, define a structure type, pass it the key/Codec
* values in the constructor and it manages the decoding. It is important that the constructor
* values matches 100% to the order in th Rust code, i.e. don't go crazy and make it alphabetical,
* it needs to decoded in the specific defined order.
*/
export default class Struct< export default class Struct<
// The actual Class structure, i.e. key -> Class // The actual Class structure, i.e. key -> Class
S extends ConstructorDef = ConstructorDef, S extends ConstructorDef = ConstructorDef,
@@ -126,24 +130,39 @@ export default class Struct<
return this._Types; return this._Types;
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number { get encodedLength (): number {
return this.toArray().reduce((length, entry) => { return this.toArray().reduce((length, entry) => {
return length += entry.encodedLength; return length += entry.encodedLength;
}, 0); }, 0);
} }
/**
* @description Returns the values of a member at a specific index (Rather use get(name) for performance)
*/
getAtIndex (index: number): Codec { getAtIndex (index: number): Codec {
return this.toArray()[index]; return this.toArray()[index];
} }
/**
* @description Converts the Object to an standard JavaScript Array
*/
toArray (): Array<Codec> { toArray (): Array<Codec> {
return [...this.values()]; return [...this.values()];
} }
/**
* @description Returns a hex string representation of the value
*/
toHex () { toHex () {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return [...this.keys()].reduce((json, key) => { return [...this.keys()].reduce((json, key) => {
const jsonKey = this._jsonMap.get(key) || key; const jsonKey = this._jsonMap.get(key) || key;
@@ -155,10 +174,17 @@ export default class Struct<
}, {} as any); }, {} as any);
} }
/**
* @description Returns the string representation of the value
*/
toString () { toString () {
return JSON.stringify(this.toJSON()); return JSON.stringify(this.toJSON());
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
return u8aConcat( return u8aConcat(
...this.toArray().map((entry) => ...this.toArray().map((entry) =>
+10 -3
View File
@@ -5,9 +5,13 @@
import { Codec, Constructor, ConstructorDef } from '../types'; import { Codec, Constructor, ConstructorDef } from '../types';
import Struct from './Struct'; import Struct from './Struct';
// A Tuple defines an anonymous Object with key/values - where the values are Codec values. It /**
// is a specialization of the Struct type where the toJSON operates on Array structures, * @name Tuple
// while the U8a encoding is handled in the same way as a Struct * @description
* A Tuple defines an anonymous Object with key/values - where the values are Codec values.
* It is a specialization of the Struct type where the toJSON operates on Array structures,
* while the U8a encoding is handled in the same way as a Struct
*/
export default class Tuple< export default class Tuple<
// S & T definitions maps to what we have in Struct (naming documented there) // S & T definitions maps to what we have in Struct (naming documented there)
S extends ConstructorDef = { [index: string]: Constructor<Codec> }, S extends ConstructorDef = { [index: string]: Constructor<Codec> },
@@ -24,6 +28,9 @@ export default class Tuple<
}; };
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return [...this.values()].map((entry) => return [...this.values()].map((entry) =>
entry.toJSON() entry.toJSON()
+28 -8
View File
@@ -6,10 +6,14 @@ import { isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
import { AnyU8a, Codec } from '../types'; import { AnyU8a, Codec } from '../types';
// A U8a. A basic wrapper around Uint8Array, with no frills and no fuss. It /**
// wraps a Uint8Array. It does differ from other implementations wher it will * @name U8a
// consume the full u8a as passed to it in U8a. As such it is meant to be * @description
// subclassed where the wrapper takes care of the actual lengths. * A basic wrapper around Uint8Array, with no frills and no fuss. It does differ
* from other implementations wher it will consume the full Uint8Array as passed to
* it. As such it is meant to be subclassed where the wrapper takes care of the
* actual lengths instead of used directly.
*/
export default class U8a extends Uint8Array implements Codec { export default class U8a extends Uint8Array implements Codec {
constructor (value: AnyU8a) { constructor (value: AnyU8a) {
super( super(
@@ -25,6 +29,9 @@ export default class U8a extends Uint8Array implements Codec {
} }
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number { get encodedLength (): number {
return this.length; return this.length;
} }
@@ -35,19 +42,32 @@ export default class U8a extends Uint8Array implements Codec {
return Uint8Array.from(this).subarray(begin, end); return Uint8Array.from(this).subarray(begin, end);
} }
/**
* @description Returns a hex string representation of the value
*/
toHex (): string { toHex (): string {
return u8aToHex(this); return u8aToHex(this);
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this.toHex(); return this.toHex();
} }
toU8a (isBare?: boolean): Uint8Array { /**
return Uint8Array.from(this); * @description Returns the string representation of the value
} */
toString (): string { toString (): string {
return this.toHex(); return this.toHex();
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
return Uint8Array.from(this);
}
} }
+9 -2
View File
@@ -10,8 +10,12 @@ import U8a from './U8a';
type BitLength = 8 | 16 | 32 | 64 | 128 | 256 | 512; type BitLength = 8 | 16 | 32 | 64 | 128 | 256 | 512;
// A U8a that manages a a sequence of bytes up to the specified bitLength. Not meant /**
// to be used directly, rather is should be subclassed with the specific lengths. * @name U8aFixed
* @description
* A U8a that manages a a sequence of bytes up to the specified bitLength. Not meant
* to be used directly, rather is should be subclassed with the specific lengths.
*/
export default class U8aFixed extends U8a { export default class U8aFixed extends U8a {
constructor (value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) { constructor (value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) {
super( super(
@@ -29,6 +33,9 @@ export default class U8aFixed extends U8a {
return value; return value;
} }
/**
* @description Returns the number of bits in the value
*/
bitLength () { bitLength () {
return this.length * 8; return this.length * 8;
} }
+35 -13
View File
@@ -11,12 +11,15 @@ export type UIntBitLength = 8 | 16 | 32 | 64 | 128 | 256;
export const DEFAULT_UINT_BITS = 64; export const DEFAULT_UINT_BITS = 64;
// A generic number codec. For Substrate all numbers are LE encoded, this handles the encoding /**
// and decoding of those numbers. Upon construction the bitLength is provided and any additional * @name UInt
// use keeps the number to this length. * @description
// * A generic number codec. For Substrate all numbers are LE encoded, this handles the encoding
* and decoding of those numbers. Upon construction the bitLength is provided and any additional
* use keeps the number to this length.
*/
// TODO: // TODO:
// - Apart from encoding/decoding we don't actuall keep check on the sizes, is this good enough? // - Apart from encoding/decoding we don't actually keep check on the sizes, is this good enough?
export default class UInt extends BN implements Codec { export default class UInt extends BN implements Codec {
protected _bitLength: UIntBitLength; protected _bitLength: UIntBitLength;
private _isHexJson: boolean; private _isHexJson: boolean;
@@ -46,29 +49,48 @@ export default class UInt extends BN implements Codec {
return bnToBn(value).toString(); return bnToBn(value).toString();
} }
bitLength (): UIntBitLength { /**
return this._bitLength; * @description The length of the value when encoded as a Uint8Array
} */
get encodedLength (): number { get encodedLength (): number {
return this._bitLength / 8; return this._bitLength / 8;
} }
/**
* @description Returns the number of bits in the value
*/
bitLength (): UIntBitLength {
return this._bitLength;
}
/**
* @description Returns the BN representation of the number. (Compatibility)
*/
toBn (): BN {
return this;
}
/**
* @description Returns a hex string representation of the value
*/
toHex (): string { toHex (): string {
return bnToHex(this, this._bitLength); return bnToHex(this, this._bitLength);
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this._isHexJson return this._isHexJson
? this.toHex() ? this.toHex()
: this.toNumber(); : this.toNumber();
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
return bnToU8a(this, this._bitLength, true); return bnToU8a(this, this._bitLength, true);
} }
toBn (): BN {
return this;
}
} }
+26 -5
View File
@@ -7,11 +7,13 @@ import { u8aConcat, u8aToU8a, u8aToHex } from '@polkadot/util';
import Compact from './Compact'; import Compact from './Compact';
import { Codec, Constructor } from '../types'; import { Codec, Constructor } from '../types';
// This manages codec arrays. Intrernally it keeps track of the length (as decoded) and allows /**
// construction with the passed `Type` in the constructor. It aims to be an array-like structure, * @name Vector
// i.e. while it wraps an array, it provides a `length` property to get the actual length, `at(index)` * @description
// to retrieve a specific item. Additionally the helper functions `map`, `filter`, `forEach` and * This manages codec arrays. Intrernally it keeps track of the length (as decoded) and allows
// `reduce` is exposed on the interface. * construction with the passed `Type` in the constructor. It is an extension to Array, providing
* specific encoding/decoding on top of the base type.
*/
export default class Vector< export default class Vector<
T extends Codec T extends Codec
> extends Array<T> implements Codec { > extends Array<T> implements Codec {
@@ -63,26 +65,41 @@ export default class Vector<
return this._Type.name; return this._Type.name;
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number { get encodedLength (): number {
return this.reduce((total, raw) => { return this.reduce((total, raw) => {
return total + raw.encodedLength; return total + raw.encodedLength;
}, Compact.encodeU8a(this.length).length); }, Compact.encodeU8a(this.length).length);
} }
/**
* @description Converts the Object to an standard JavaScript Array
*/
toArray (): Array<T> { toArray (): Array<T> {
return Array.from(this); return Array.from(this);
} }
/**
* @description Returns a hex string representation of the value
*/
toHex (): string { toHex (): string {
return u8aToHex(this.toU8a()); return u8aToHex(this.toU8a());
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any { toJSON (): any {
return this.map((entry) => return this.map((entry) =>
entry.toJSON() entry.toJSON()
); );
} }
/**
* @description Returns the string representation of the value
*/
toString (): string { toString (): string {
// Overwrite the default toString representation of Array. // Overwrite the default toString representation of Array.
const data = this.map((entry) => const data = this.map((entry) =>
@@ -92,6 +109,10 @@ export default class Vector<
return `[${data.join(', ')}]`; return `[${data.join(', ')}]`;
} }
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array { toU8a (isBare?: boolean): Uint8Array {
const encoded = this.map((entry) => const encoded = this.map((entry) =>
entry.toU8a(isBare) entry.toU8a(isBare)
+3
View File
@@ -7,6 +7,9 @@
// perspective these are the value classes. (Codec is for the cases where you need // perspective these are the value classes. (Codec is for the cases where you need
// to construct values dynamically) // to construct values dynamically)
/**
* @summary Type definitions that are used in the system
*/
export { default as AccountId } from './AccountId'; export { default as AccountId } from './AccountId';
export { default as AccountIndex } from './AccountIndex'; export { default as AccountIndex } from './AccountIndex';
export { default as Address } from './Address'; export { default as Address } from './Address';
+27
View File
@@ -13,11 +13,38 @@ export type AnyString = string | String;
export type AnyU8a = Uint8Array | Array<number> | string; export type AnyU8a = Uint8Array | Array<number> | string;
/**
* @name Codec
* @description
* The base Codec interface. All types implement the interface provided here. Additionally
* implementors can add their own specific interfaces and helpres with getters and functions.
* The Codec Base is however required for operating as an encoding/decoding layer
*/
export interface Codec { export interface Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
encodedLength: number; encodedLength: number;
/**
* @description Returns a hex string representation of the value
*/
toHex (): string; toHex (): string;
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any; toJSON (): any;
/**
* @description Returns the string representation of the value
*/
toString (): string; toString (): string;
/**
* @description Encodes the value as a Uint8Array as per the parity-codec specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array; toU8a (isBare?: boolean): Uint8Array;
} }