diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index ab998e9d83..d61b1debae 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -6,6 +6,7 @@ - [rpc-provider](rpc-provider/README.md) - [HttpProvider](rpc-provider/classes/_http_index_.httpprovider.md) - [WsProvider](rpc-provider/classes/_ws_index_.wsprovider.md) +- [types (codec implementation)](types/README.md) ## Interfaces diff --git a/packages/types/src/AccountId.ts b/packages/types/src/AccountId.ts index 8f8e5d9ac6..aa9bef0198 100644 --- a/packages/types/src/AccountId.ts +++ b/packages/types/src/AccountId.ts @@ -9,9 +9,13 @@ import { hexToU8a, isHex, isString, isU8a, u8aToU8a } from '@polkadot/util'; 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 -// just a Uint8Array wrapper with a fixed length. +/** + * @name AccountId + * @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 { constructor (value: AnyU8a = new Uint8Array()) { super( diff --git a/packages/types/src/AccountIndex.ts b/packages/types/src/AccountIndex.ts index 99bee00fda..8a6dae0813 100644 --- a/packages/types/src/AccountIndex.ts +++ b/packages/types/src/AccountIndex.ts @@ -20,9 +20,12 @@ const MAX_1BYTE = new BN(PREFIX_1BYTE); const MAX_2BYTE = new BN(1).shln(16); 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 -// just a Uint8Array wrapper. +/** + * @name AccountIndex + * @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 { constructor (value: AnyNumber = new BN(0)) { super( diff --git a/packages/types/src/Address.ts b/packages/types/src/Address.ts index b0d14ea554..c17eeea25e 100644 --- a/packages/types/src/Address.ts +++ b/packages/types/src/Address.ts @@ -14,11 +14,14 @@ type AnyAddress = BN | Address | AccountId | AccountIndex | Array | Uint 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), -// we extend from Base with an AccountId/AccountIndex wrapper. Basically the Address -// is encoded as -// [ , ...publicKey/...bytes ] +/** + * @name Address + * @description + * 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), + * we extend from Base with an AccountId/AccountIndex wrapper. Basically the Address + * is encoded as `[ , ...publicKey/...bytes ]` as per spec + */ export default class Address extends Base { constructor (value: AnyAddress = new Uint8Array()) { super( @@ -58,12 +61,6 @@ export default class Address extends Base { : new AccountIndex(u8aToBn(decoded, true)); } - get rawLength (): number { - return this.raw instanceof AccountIndex - ? AccountIndex.calcLength(this.raw) - : this.raw.encodedLength; - } - get encodedLength (): number { const rawLength = this.rawLength; @@ -75,6 +72,12 @@ export default class Address extends Base { ); } + get rawLength (): number { + return this.raw instanceof AccountIndex + ? AccountIndex.calcLength(this.raw) + : this.raw.encodedLength; + } + toHex (): string { return u8aToHex(this.toU8a()); } diff --git a/packages/types/src/Balance.ts b/packages/types/src/Balance.ts index fc10e5c88d..36bce420c7 100644 --- a/packages/types/src/Balance.ts +++ b/packages/types/src/Balance.ts @@ -4,6 +4,10 @@ import U128 from './U128'; -// The Substrate Balance representation. +/** + * @name Balance + * @description + * The Substrate Balance representation as a [[U128]]. + */ export default class Balance extends U128 { } diff --git a/packages/types/src/Bft.ts b/packages/types/src/Bft.ts index 5cb283102b..90a65a2215 100644 --- a/packages/types/src/Bft.ts +++ b/packages/types/src/Bft.ts @@ -14,8 +14,12 @@ export type BftAuthoritySignatureValue = { 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 { constructor (value?: BftAuthoritySignatureValue | Uint8Array) { super({ @@ -38,8 +42,12 @@ export type BftHashSignatureValue = { 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 { constructor (value?: BftHashSignatureValue | Uint8Array) { super({ diff --git a/packages/types/src/Block.ts b/packages/types/src/Block.ts index 2ad538a8e5..3c383551b6 100644 --- a/packages/types/src/Block.ts +++ b/packages/types/src/Block.ts @@ -16,7 +16,11 @@ export type BlockValue = { 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 { constructor (value?: BlockValue | Uint8Array) { super({ diff --git a/packages/types/src/BlockNumber.ts b/packages/types/src/BlockNumber.ts index 722fbf4323..41450a74df 100644 --- a/packages/types/src/BlockNumber.ts +++ b/packages/types/src/BlockNumber.ts @@ -4,5 +4,10 @@ import U64 from './U64'; +/** + * @name BlockNumber + * @description + * A representation of a Substrate BlockNumber, implemented as a [[U64]] + */ export default class BlockNumber extends U64 { } diff --git a/packages/types/src/Bool.ts b/packages/types/src/Bool.ts index 12035eefef..bab3f3ea44 100644 --- a/packages/types/src/Bool.ts +++ b/packages/types/src/Bool.ts @@ -6,6 +6,11 @@ import { isU8a, u8aToHex } from '@polkadot/util'; import { Codec } from './types'; +/** + * @name Bool + * @description + * Representation for a boolean value in the system + */ export default class Bool extends Boolean implements Codec { constructor (value: Bool | Boolean | Uint8Array | boolean | number = false) { super( @@ -35,11 +40,11 @@ export default class Bool extends Boolean implements Codec { return u8aToHex(this.toU8a()); } - toU8a (isBare?: boolean): Uint8Array { - return new Uint8Array([this ? 1 : 0]); - } - toString (): string { return `${this.toJSON()}`; } + + toU8a (isBare?: boolean): Uint8Array { + return new Uint8Array([this ? 1 : 0]); + } } diff --git a/packages/types/src/Bytes.ts b/packages/types/src/Bytes.ts index 317f926a6b..85bea7b791 100644 --- a/packages/types/src/Bytes.ts +++ b/packages/types/src/Bytes.ts @@ -8,9 +8,13 @@ import { AnyU8a } from './types'; import Compact from './codec/Compact'; import U8a from './codec/U8a'; -// A Bytes wrapper for Vec. 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) +/** + * @name Bytes + * @description + * A Bytes wrapper for Vec. 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 { constructor (value: AnyU8a) { super(Bytes.decodeBytes(value)); diff --git a/packages/types/src/Data.ts b/packages/types/src/Data.ts index 670fc9ead0..710b656a55 100644 --- a/packages/types/src/Data.ts +++ b/packages/types/src/Data.ts @@ -4,6 +4,10 @@ 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 { } diff --git a/packages/types/src/Digest.ts b/packages/types/src/Digest.ts index b98a077df1..988df4a36a 100644 --- a/packages/types/src/Digest.ts +++ b/packages/types/src/Digest.ts @@ -12,16 +12,36 @@ import Hash from './Hash'; import Signature from './Signature'; 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) { super({ 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 { constructor (value: any) { @@ -50,6 +75,11 @@ export class DigestItem extends EnumType } = {}; -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 _method: 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) { 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 { // Currently we _only_ decode from Uint8Array, since we expect it to // be used via EventRecord diff --git a/packages/types/src/EventRecord.ts b/packages/types/src/EventRecord.ts index ae07528b01..3e89845887 100644 --- a/packages/types/src/EventRecord.ts +++ b/packages/types/src/EventRecord.ts @@ -8,13 +8,28 @@ import Event from './Event'; import Null from './Null'; 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 { +/** + * @name Phase + * @description + * An [[EnumType]] that indicates the specific phase where the [[EventRecord]] was generated + */ +export class Phase extends EnumType { constructor (value: any, index?: number) { super([ ApplyExtrinsic, @@ -23,6 +38,12 @@ class Phase extends EnumType { } } +/** + * @name EventRecord + * @description + * A record for an [[Event]] (as specified by [[Metadata]]) with the specific [[Phase]] of + * application. + */ export default class EventRecord extends Struct { constructor (value: any) { super({ diff --git a/packages/types/src/Extrinsic.ts b/packages/types/src/Extrinsic.ts index 97ec7820b1..31d85f8c43 100644 --- a/packages/types/src/Extrinsic.ts +++ b/packages/types/src/Extrinsic.ts @@ -22,6 +22,8 @@ type ExtrinsicValue = { }; /** + * @name Extrinsic + * @description * Representation of an Extrinsic in the system. It contains the actual call, * (optional) signature and encodes with an actual length prefix * @@ -75,6 +77,12 @@ export default class Extrinsic extends Struct { 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 get hash (): Hash { return new Hash( @@ -102,12 +110,6 @@ export default class Extrinsic extends Struct { 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 { this.signature.addSignature(signer, signature, nonce, era); @@ -120,14 +122,6 @@ export default class Extrinsic extends Struct { return this; } - toU8a (isBare?: boolean): Uint8Array { - const encoded = super.toU8a(); - - return isBare - ? encoded - : Compact.addLengthPrefix(encoded); - } - toHex (): string { return u8aToHex(this.toU8a()); } @@ -135,4 +129,12 @@ export default class Extrinsic extends Struct { toJSON (): any { return this.toHex(); } + + toU8a (isBare?: boolean): Uint8Array { + const encoded = super.toU8a(); + + return isBare + ? encoded + : Compact.addLengthPrefix(encoded); + } } diff --git a/packages/types/src/ExtrinsicEra.ts b/packages/types/src/ExtrinsicEra.ts index e8b556fdee..efd9da9168 100644 --- a/packages/types/src/ExtrinsicEra.ts +++ b/packages/types/src/ExtrinsicEra.ts @@ -8,6 +8,11 @@ import { u8aToU8a } from '@polkadot/util'; 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 { constructor (value?: AnyU8a) { super( diff --git a/packages/types/src/ExtrinsicSignature.ts b/packages/types/src/ExtrinsicSignature.ts index ce7a172ff5..fb81f44d10 100644 --- a/packages/types/src/ExtrinsicSignature.ts +++ b/packages/types/src/ExtrinsicSignature.ts @@ -29,12 +29,17 @@ const BIT_UNSIGNED = 0; const BIT_VERSION = 0b0000001; const EMPTY_U8A = new Uint8Array(); -// 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 +/** + * @name ExtrinsicSignature + * @description + * A container for the [[Signature]] associated with a specific [[Extrinsic]] + */ 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) { super({ signer: Address, diff --git a/packages/types/src/ExtrinsicStatus.ts b/packages/types/src/ExtrinsicStatus.ts index b5dfab51e1..8e47dd3ace 100644 --- a/packages/types/src/ExtrinsicStatus.ts +++ b/packages/types/src/ExtrinsicStatus.ts @@ -8,18 +8,43 @@ import Hash from './Hash'; import Null from './Null'; 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) { } +/** + * @name Dropped + * @description + * An [[ExtrinsicStatus]] indicating that the [[Extrinsic]] has been dropped + */ export class Dropped extends Null { } +/** + * @name Finalised + * @description + * An [[ExtrinsicStats] indicating that the [[Extrinsic]]] has been finalised and included + */ export class Finalised extends Hash { } +/** + * @name Usurped + * @description + * An [[ExtrinsicStatus]] indicating that the [[Extrinsic]] has been usurped + */ 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 { constructor (value: any, index?: number) { super([ diff --git a/packages/types/src/Extrinsics.ts b/packages/types/src/Extrinsics.ts index 078c089dd9..09712c0732 100644 --- a/packages/types/src/Extrinsics.ts +++ b/packages/types/src/Extrinsics.ts @@ -5,6 +5,10 @@ import Vector from './codec/Vector'; import Extrinsic from './Extrinsic'; -// A list of extrinsics +/** + * @name Extrinsics + * @description + * A [[Vector]] of [[Extrinsic]] + */ export default class Extrinsics extends Vector.with(Extrinsic) { } diff --git a/packages/types/src/Gas.ts b/packages/types/src/Gas.ts index 20b1ada671..3b536f42b9 100644 --- a/packages/types/src/Gas.ts +++ b/packages/types/src/Gas.ts @@ -4,6 +4,10 @@ import U64 from './U64'; -// Gas for contracts +/** + * @name Gas + * @description + * A gas number type for Substrate, extending [[U64]] + */ export default class Gas extends U64 { } diff --git a/packages/types/src/H256.ts b/packages/types/src/H256.ts index 347fad3d76..de6dbaadce 100644 --- a/packages/types/src/H256.ts +++ b/packages/types/src/H256.ts @@ -6,8 +6,12 @@ import { AnyU8a } from './types'; 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 { constructor (value?: AnyU8a) { super(value, 256); diff --git a/packages/types/src/H512.ts b/packages/types/src/H512.ts index c48ddcc622..89e04f12f5 100644 --- a/packages/types/src/H512.ts +++ b/packages/types/src/H512.ts @@ -6,7 +6,11 @@ import { AnyU8a } from './types'; 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 { constructor (value?: AnyU8a) { super(value, 512); diff --git a/packages/types/src/Hash.ts b/packages/types/src/Hash.ts index a5efe7ed3f..60b7896c38 100644 --- a/packages/types/src/Hash.ts +++ b/packages/types/src/Hash.ts @@ -4,7 +4,11 @@ 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 { } diff --git a/packages/types/src/Header.ts b/packages/types/src/Header.ts index 643bc043bf..72ce4c78be 100644 --- a/packages/types/src/Header.ts +++ b/packages/types/src/Header.ts @@ -21,7 +21,11 @@ export type HeaderValue = { stateRoot?: AnyU8a }; -// A block header. +/** + * @name Header + * @description + * A [[Block]] header + */ export default class Header extends Struct { constructor (value?: HeaderValue | Uint8Array) { super({ diff --git a/packages/types/src/Justification.ts b/packages/types/src/Justification.ts index 5fbfaba417..bfea3f4c11 100644 --- a/packages/types/src/Justification.ts +++ b/packages/types/src/Justification.ts @@ -17,11 +17,19 @@ export type RhdJustificationValue = { signatures?: Array }; -// 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 { } -// justification for Rhododendron +/** + * @name RhdJustification + * @description + * [[Justification]] for the Rhododendron consensus algorithm + */ export class RhdJustification extends Struct { constructor (value?: RhdJustificationValue | Uint8Array) { super({ diff --git a/packages/types/src/KeyValue.ts b/packages/types/src/KeyValue.ts index efd1e7094e..ba727cbd27 100644 --- a/packages/types/src/KeyValue.ts +++ b/packages/types/src/KeyValue.ts @@ -15,10 +15,14 @@ type KeyValueValue = { 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 -// 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) +/** + * @name KeyValue + * @description + * 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 { constructor (value?: KeyValueValue | Uint8Array) { super({ @@ -41,9 +45,13 @@ export type KeyValueOptionValue = { 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 -// from a Tuple, indicating the use inside areas such as StorageChangeSet +/** + * @name KeyValueOption + * @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 { constructor (value?: KeyValueOptionValue | Uint8Array) { super({ diff --git a/packages/types/src/Metadata.ts b/packages/types/src/Metadata.ts index d7fafb70d5..a95176d0fc 100644 --- a/packages/types/src/Metadata.ts +++ b/packages/types/src/Metadata.ts @@ -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 { constructor (value?: any) { super({ diff --git a/packages/types/src/Method.ts b/packages/types/src/Method.ts index 0b6b255f0a..f168a763c9 100644 --- a/packages/types/src/Method.ts +++ b/packages/types/src/Method.ts @@ -57,6 +57,8 @@ class MethodIndex extends U8aFixed { } /** + * @name Method + * @description * Extrinsic function descriptor, as defined in * {@link https://github.com/paritytech/wiki/blob/master/Extrinsic.md#the-extrinsic-format-for-node}. */ diff --git a/packages/types/src/MisbehaviorReport.ts b/packages/types/src/MisbehaviorReport.ts index 178d5c9828..a560de55cd 100644 --- a/packages/types/src/MisbehaviorReport.ts +++ b/packages/types/src/MisbehaviorReport.ts @@ -21,9 +21,12 @@ type BftAtReportValue = BftAtReportValueSingle & { 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 // items in the structure is called, except a & b (one should be expected, the // 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 { constructor (value?: BftAtReportValue | Uint8Array) { 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 { } -// Report of a double-prepare +/** + * @name BftDoublePrepare + * @description + * Report of a double-prepare + */ export class BftDoublePrepare extends BftAtReport { } -// Report of a double-commit +/** + * @name BftDoubleCommit + * @description + * Report of a double-commit + */ export class BftDoubleCommit extends BftAtReport { } +/** + * @name MisbehaviorKind + * @description + * An [[EnumType]] containing a Bft misbehaviour + */ export class MisbehaviorKind extends EnumType { constructor (value?: BftAtReportValue | Uint8Array, index?: number) { super([ @@ -96,7 +121,11 @@ type MisbehaviorReportValue = { 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 { constructor (value?: MisbehaviorReportValue | Uint8Array) { super({ diff --git a/packages/types/src/Moment.ts b/packages/types/src/Moment.ts index 899d764abe..bdabfd86a2 100644 --- a/packages/types/src/Moment.ts +++ b/packages/types/src/Moment.ts @@ -10,10 +10,14 @@ import { AnyNumber, Codec } from './types'; 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 -// per-second. For any encoding/decoding the 1000 multiplier would be applied to -// get it in line with JavaScript formats +/** + * @name Moment + * @description + * 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 { 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 { return BITLENGTH; } - get encodedLength (): number { - return BITLENGTH / 8; + toBn (): BN { + return new BN(this.toNumber()); } toHex (): string { @@ -55,15 +63,11 @@ export default class Moment extends Date implements Codec { return this.toNumber(); } - toU8a (isBare?: boolean): Uint8Array { - return bnToU8a(this.toNumber(), BITLENGTH, true); - } - - toBn (): BN { - return new BN(this.toNumber()); - } - toNumber (): number { return Math.ceil(this.getTime() / 1000); } + + toU8a (isBare?: boolean): Uint8Array { + return bnToU8a(this.toNumber(), BITLENGTH, true); + } } diff --git a/packages/types/src/NewAccountOutcome.ts b/packages/types/src/NewAccountOutcome.ts index a4661b6de6..2447dc97f0 100644 --- a/packages/types/src/NewAccountOutcome.ts +++ b/packages/types/src/NewAccountOutcome.ts @@ -5,7 +5,11 @@ import Enum from './codec/Enum'; 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 { constructor (index?: U8a | Uint8Array | number) { super([ diff --git a/packages/types/src/Nonce.ts b/packages/types/src/Nonce.ts index b3e5dfd757..90e2b68aed 100644 --- a/packages/types/src/Nonce.ts +++ b/packages/types/src/Nonce.ts @@ -4,7 +4,12 @@ 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 { } diff --git a/packages/types/src/Null.ts b/packages/types/src/Null.ts index b7bad221bd..a212794695 100644 --- a/packages/types/src/Null.ts +++ b/packages/types/src/Null.ts @@ -4,7 +4,11 @@ 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 { get encodedLength (): number { return 0; @@ -14,15 +18,25 @@ export default class Null implements Codec { return '0x'; } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return null; } - toU8a (isBare?: boolean): Uint8Array { - return new Uint8Array(); - } - + /** + * @description Returns the string representation of the value + */ toString (): string { 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(); + } } diff --git a/packages/types/src/Origin.ts b/packages/types/src/Origin.ts index a6f9101add..fa030d7f17 100644 --- a/packages/types/src/Origin.ts +++ b/packages/types/src/Origin.ts @@ -2,7 +2,12 @@ // This software may be modified and distributed under the terms // 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 { constructor () { throw new Error('Origin should not be constructed, it is only a placeholder for compatibility'); diff --git a/packages/types/src/ParachainId.ts b/packages/types/src/ParachainId.ts index 75baba5eac..094f220e66 100644 --- a/packages/types/src/ParachainId.ts +++ b/packages/types/src/ParachainId.ts @@ -4,6 +4,10 @@ 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 { } diff --git a/packages/types/src/PendingExtrinsics.ts b/packages/types/src/PendingExtrinsics.ts index cd6cf20747..6a21818318 100644 --- a/packages/types/src/PendingExtrinsics.ts +++ b/packages/types/src/PendingExtrinsics.ts @@ -4,6 +4,10 @@ import Extrinsics from './Extrinsics'; -// A list of pending extrinsics +/** + * @name PendingExtrinsics + * @description + * A list of pending [[Extrinsics]] + */ export default class PendingExtrinsics extends Extrinsics { } diff --git a/packages/types/src/Perbill.ts b/packages/types/src/Perbill.ts index 386a5a486a..c96e29cf72 100644 --- a/packages/types/src/Perbill.ts +++ b/packages/types/src/Perbill.ts @@ -4,8 +4,11 @@ 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 // want to multiply by 1_000_000_000 for those purposes? export default class Perbill extends U32 { diff --git a/packages/types/src/Permill.ts b/packages/types/src/Permill.ts index c17b5be825..f440a4a25b 100644 --- a/packages/types/src/Permill.ts +++ b/packages/types/src/Permill.ts @@ -4,8 +4,11 @@ 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 // want to multiply by 1_000_000 for those purposes? export default class Permill extends U32 { diff --git a/packages/types/src/PropIndex.ts b/packages/types/src/PropIndex.ts index 58f8811b95..7f9790208a 100644 --- a/packages/types/src/PropIndex.ts +++ b/packages/types/src/PropIndex.ts @@ -4,6 +4,11 @@ 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 { } diff --git a/packages/types/src/Proposal.ts b/packages/types/src/Proposal.ts index a19fdc5916..ef64ca0bf8 100644 --- a/packages/types/src/Proposal.ts +++ b/packages/types/src/Proposal.ts @@ -4,6 +4,10 @@ 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 { } diff --git a/packages/types/src/ProposalIndex.ts b/packages/types/src/ProposalIndex.ts index 6c4c01dd30..9e2c59aacf 100644 --- a/packages/types/src/ProposalIndex.ts +++ b/packages/types/src/ProposalIndex.ts @@ -4,6 +4,11 @@ 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 { } diff --git a/packages/types/src/ReferendumIndex.ts b/packages/types/src/ReferendumIndex.ts index daf41ed4bf..2d4f906387 100644 --- a/packages/types/src/ReferendumIndex.ts +++ b/packages/types/src/ReferendumIndex.ts @@ -4,7 +4,11 @@ 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 { } diff --git a/packages/types/src/RuntimeVersion.ts b/packages/types/src/RuntimeVersion.ts index 853757dcdf..bda2fa8c72 100644 --- a/packages/types/src/RuntimeVersion.ts +++ b/packages/types/src/RuntimeVersion.ts @@ -11,7 +11,12 @@ import Vector from './codec/Vector'; import Text from './Text'; 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) { super(value, 64); } @@ -22,7 +27,12 @@ type RuntimeVersionApiValue = { 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) { super({ id: ApiId, @@ -48,6 +58,11 @@ type RuntimeVersionValue = { apis?: Array }; +/** + * @name RuntimeVersion + * @description + * A defintion of the runtime and the associated versions thereof + */ export default class RuntimeVersion extends Struct { constructor (value?: RuntimeVersionValue | Uint8Array) { super({ diff --git a/packages/types/src/SessionKey.ts b/packages/types/src/SessionKey.ts index d3e1f4a1be..f1204193af 100644 --- a/packages/types/src/SessionKey.ts +++ b/packages/types/src/SessionKey.ts @@ -4,7 +4,11 @@ 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 { } diff --git a/packages/types/src/Signature.ts b/packages/types/src/Signature.ts index 57785b4aa7..a3f5e3f426 100644 --- a/packages/types/src/Signature.ts +++ b/packages/types/src/Signature.ts @@ -4,7 +4,11 @@ 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 { } diff --git a/packages/types/src/SignaturePayload.ts b/packages/types/src/SignaturePayload.ts index 9f78560070..a05ce1a98d 100644 --- a/packages/types/src/SignaturePayload.ts +++ b/packages/types/src/SignaturePayload.ts @@ -18,11 +18,17 @@ type SignaturePayloadValue = { blockHash?: AnyU8a }; -// Signing Payload. -// 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. +/** + * @name SignaturePayload + * @description + * A signing payload for an [[Extrinsic]]. For the final encoding, it is variable length based + * 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 { protected _signature?: Uint8Array; diff --git a/packages/types/src/SignedBlock.ts b/packages/types/src/SignedBlock.ts index 7d67069bd8..d7a61aa6bd 100644 --- a/packages/types/src/SignedBlock.ts +++ b/packages/types/src/SignedBlock.ts @@ -13,6 +13,11 @@ type SignedBlockValue = { justification?: AnyU8a }; +/** + * @name SignedBlock + * @description + * A [[Block]] that has been signed and contains a [[Justification]] + */ export default class SignedBlock extends Struct { constructor (value?: SignedBlockValue | Uint8Array) { super({ diff --git a/packages/types/src/StorageChangeSet.ts b/packages/types/src/StorageChangeSet.ts index 59796507c9..9d6add6bbc 100644 --- a/packages/types/src/StorageChangeSet.ts +++ b/packages/types/src/StorageChangeSet.ts @@ -14,8 +14,13 @@ type StorageChangeSetValue = { changes?: Array }; -// 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 { constructor (value?: StorageChangeSetValue | Uint8Array) { super({ diff --git a/packages/types/src/StorageData.ts b/packages/types/src/StorageData.ts index 39a18b6f0b..b9ecc6086a 100644 --- a/packages/types/src/StorageData.ts +++ b/packages/types/src/StorageData.ts @@ -4,6 +4,10 @@ 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 { } diff --git a/packages/types/src/StorageKey.ts b/packages/types/src/StorageKey.ts index cc5fe9d6a4..a26a9b10a2 100644 --- a/packages/types/src/StorageKey.ts +++ b/packages/types/src/StorageKey.ts @@ -17,8 +17,12 @@ export interface StorageFunction { 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 { private _outputType: string | null; diff --git a/packages/types/src/StoredPendingChange.ts b/packages/types/src/StoredPendingChange.ts index 2600e4de47..76c3087938 100644 --- a/packages/types/src/StoredPendingChange.ts +++ b/packages/types/src/StoredPendingChange.ts @@ -23,7 +23,12 @@ export type StoredPendingChangeValue = { nextAuthorities?: Array }; -class NextAuthority extends Tuple { +/** + * @name NextAuthority + * @description + * The next authority available as [[SessionKey]] + */ +export class NextAuthority extends Tuple { constructor (value?: Uint8Array | NextAuthorityValue) { super({ 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 { constructor (value?: Uint8Array | StoredPendingChangeValue) { super({ diff --git a/packages/types/src/Text.ts b/packages/types/src/Text.ts index 5021f0af7f..c2114ff3a6 100644 --- a/packages/types/src/Text.ts +++ b/packages/types/src/Text.ts @@ -7,9 +7,12 @@ import { isFunction, isString, stringToU8a, u8aToString, u8aToHex } from '@polka import { AnyU8a, Codec } from './types'; 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 // - Strings should probably be trimmed (docs do come through with extra padding) // - Potentially we want a "TypeString" extension to this. Basically something that diff --git a/packages/types/src/Type.ts b/packages/types/src/Type.ts index 5519229fad..5fb389b930 100644 --- a/packages/types/src/Type.ts +++ b/packages/types/src/Type.ts @@ -9,9 +9,13 @@ type Mapper = (value: string) => string; 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. -// we remove the `T::` prefixes found in some types for consistency accross implementation. +/** + * @name Type + * @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 { private _originalLength: number; @@ -57,17 +61,17 @@ export default class Type extends Text { }, 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 { + // 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; } - // 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 { + // 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'); } diff --git a/packages/types/src/U128.ts b/packages/types/src/U128.ts index 5de6d7345d..0a92b5c972 100644 --- a/packages/types/src/U128.ts +++ b/packages/types/src/U128.ts @@ -6,6 +6,11 @@ import { AnyNumber } from './types'; import UInt from './codec/UInt'; +/** + * @name U128 + * @description + * An 128-bit number + */ export default class U128 extends UInt { constructor (value?: AnyNumber) { super(value, 128); diff --git a/packages/types/src/U16.ts b/packages/types/src/U16.ts index 04856ee04f..c2fc552f00 100644 --- a/packages/types/src/U16.ts +++ b/packages/types/src/U16.ts @@ -6,6 +6,11 @@ import { AnyNumber } from './types'; import UInt from './codec/UInt'; +/** + * @name U16 + * @description + * An 16-bit number + */ export default class U16 extends UInt { constructor (value?: AnyNumber) { super(value, 16, false); diff --git a/packages/types/src/U256.ts b/packages/types/src/U256.ts index 92cbacfb17..a99de41fbd 100644 --- a/packages/types/src/U256.ts +++ b/packages/types/src/U256.ts @@ -6,6 +6,11 @@ import { AnyNumber } from './types'; import UInt from './codec/UInt'; +/** + * @name U256 + * @description + * An 256-bit number + */ export default class U256 extends UInt { constructor (value?: AnyNumber) { super(value, 256); diff --git a/packages/types/src/U32.ts b/packages/types/src/U32.ts index 487ad68d72..398206881a 100644 --- a/packages/types/src/U32.ts +++ b/packages/types/src/U32.ts @@ -6,6 +6,11 @@ import { AnyNumber } from './types'; import UInt from './codec/UInt'; +/** + * @name U32 + * @description + * An 32-bit number + */ export default class U32 extends UInt { constructor (value?: AnyNumber) { super(value, 32, false); diff --git a/packages/types/src/U64.ts b/packages/types/src/U64.ts index b282bd909c..089296160e 100644 --- a/packages/types/src/U64.ts +++ b/packages/types/src/U64.ts @@ -6,6 +6,11 @@ import { AnyNumber } from './types'; import UInt from './codec/UInt'; +/** + * @name U64 + * @description + * An 64-bit number + */ export default class U64 extends UInt { constructor (value?: AnyNumber) { super(value, 64, false); diff --git a/packages/types/src/U8.ts b/packages/types/src/U8.ts index cc24301ba4..c37db94a9d 100644 --- a/packages/types/src/U8.ts +++ b/packages/types/src/U8.ts @@ -6,6 +6,11 @@ import { AnyNumber } from './types'; import UInt from './codec/UInt'; +/** + * @name U8 + * @description + * An 8-bit number + */ export default class U8 extends UInt { constructor (value?: AnyNumber) { super(value, 8, false); diff --git a/packages/types/src/ValidatorPrefs.ts b/packages/types/src/ValidatorPrefs.ts index e93edc42da..c3118b03fa 100644 --- a/packages/types/src/ValidatorPrefs.ts +++ b/packages/types/src/ValidatorPrefs.ts @@ -13,6 +13,11 @@ type ValidatorPrefsValue = { validatorPayment?: AnyNumber }; +/** + * @name ValidatorPrefs + * @description + * Validator preferences + */ export default class ValidatorPrefs extends Struct { constructor (value?: ValidatorPrefsValue | Uint8Array) { super({ diff --git a/packages/types/src/VoteIndex.ts b/packages/types/src/VoteIndex.ts index f2dc241255..a030801237 100644 --- a/packages/types/src/VoteIndex.ts +++ b/packages/types/src/VoteIndex.ts @@ -4,5 +4,10 @@ import U32 from './U32'; +/** + * @name VoteIndex + * @description + * Voting index, implemented as a [[U32]] + */ export default class VoteIndex extends U32 { } diff --git a/packages/types/src/VoteThreshold.ts b/packages/types/src/VoteThreshold.ts index 4b2c6d2eb8..455f390b1a 100644 --- a/packages/types/src/VoteThreshold.ts +++ b/packages/types/src/VoteThreshold.ts @@ -4,7 +4,11 @@ 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 { constructor (index?: number | Uint8Array) { super([ diff --git a/packages/types/src/codec/Base.ts b/packages/types/src/codec/Base.ts index 6a587ad418..4d9144914b 100644 --- a/packages/types/src/codec/Base.ts +++ b/packages/types/src/codec/Base.ts @@ -3,7 +3,8 @@ // 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 { protected raw: T; diff --git a/packages/types/src/codec/Compact.ts b/packages/types/src/codec/Compact.ts index 898928a779..a2e46d6691 100644 --- a/packages/types/src/codec/Compact.ts +++ b/packages/types/src/codec/Compact.ts @@ -11,21 +11,14 @@ import Base from './Base'; import UInt, { UIntBitLength } from './UInt'; 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 -// implementation for compact encoding -// -// 0b00 00 00 00 / 00 00 00 00 / 00 00 00 00 / 00 00 00 00 -// (0 ... 2**6 - 1) (u8) -// xx xx xx 00 -// (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. +/** + * @name Compact + * @description + * A compact length-encoding codec wrapper. It performs the same function as Length, however + * differs in that it uses a variable number of bytes to do the actual encoding. This is mostly + * used by other types to add length-prefixed encoding, or in the case of wrapped types, taking + * a number and making the compact representation thereof + */ export default class Compact extends Base implements Codec { constructor (Type: Constructor, value: AnyNumber = 0) { super(Compact.decodeCompact(Type, value)); @@ -72,34 +65,59 @@ export default class Compact extends Base implements Codec { 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 { 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 { return this.raw.toBn(); } + /** + * @description Returns a hex string representation of the value + */ toHex (): any { return this.raw.toHex(); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return this.raw.toJSON(); } + /** + * @description Returns the number representation for the value + */ toNumber (): number { return this.raw.toNumber(); } + /** + * @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 { return Compact.encodeU8a(this.raw.toBn(), this.bitLength()); } diff --git a/packages/types/src/codec/Enum.ts b/packages/types/src/codec/Enum.ts index dc5d379667..5c00f33440 100644 --- a/packages/types/src/codec/Enum.ts +++ b/packages/types/src/codec/Enum.ts @@ -11,11 +11,14 @@ type EnumDef = { [index: number]: string } | Array; -// 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) -// +/** + * @name Enum + * @description + * 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: // - It would be great if this could actually wrap actual TS enums export default class Enum extends Base implements Codec { @@ -39,26 +42,45 @@ export default class Enum extends Base implements Codec { } } + /** + * @description The length of the value when encoded as a Uint8Array + */ get encodedLength (): number { return 1; } + /** + * @description Returns a hex string representation of the value + */ toHex (): string { return u8aToHex(this.toU8a()); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return this.raw; } + /** + * @description Returns the number representation for the value + */ toNumber (): number { return this.raw; } + /** + * @description Returns the string representation of the value + */ toString (): string { 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 { return new Uint8Array([this.raw]); } diff --git a/packages/types/src/codec/EnumType.ts b/packages/types/src/codec/EnumType.ts index 595adc990f..01100f8cf2 100644 --- a/packages/types/src/codec/EnumType.ts +++ b/packages/types/src/codec/EnumType.ts @@ -13,9 +13,12 @@ type TypesDef = { [index: number]: Constructor } | 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: // - As per Enum, actually use TS enum // - It should rather probably extend Enum instead of copying code @@ -78,38 +81,73 @@ export default class EnumType extends Base implements Codec { return { index: 0, value: new (Object.values(def)[0])() }; } - get isNull (): boolean { - return this.raw instanceof Null; - } - - get type (): string { - return this._Types[this._index].name; - } - - get value (): Codec { - return this.raw; - } - + /** + * @description The length of the value when encoded as a Uint8Array + */ get encodedLength (): number { 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 { return u8aToHex(this.toU8a()); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return this.raw; } + /** + * @description Returns the number representation for the value + */ toNumber (): number { return this._index; } + /** + * @description Returns the string representation of the value + */ toString (): string { 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 { const index = this._indexes[this._index]; diff --git a/packages/types/src/codec/Option.ts b/packages/types/src/codec/Option.ts index 3a5e4815c2..655d3058d7 100644 --- a/packages/types/src/codec/Option.ts +++ b/packages/types/src/codec/Option.ts @@ -8,10 +8,14 @@ import Base from './Base'; import { Codec, Constructor } from '../types'; 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 -// implements that - decodes, checks for optionality and wraps the required structure -// with a value if/as required/found. +/** + * @name Option + * @description + * 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 extends Base implements Codec { constructor (Type: Constructor, value?: any) { super( @@ -42,30 +46,60 @@ export default class Option extends Base 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 { return this.raw instanceof Null; } + /** + * @description Checks if the Option has a value + */ get isSome (): boolean { return !this.isNone; } + /** + * @description The actual value for the Option + */ get value (): Codec { return this.raw; } - get encodedLength (): number { - return 1 + this.raw.encodedLength; - } - + /** + * @description Returns a hex string representation of the value + */ toHex (): string { return u8aToHex(this.toU8a()); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { 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 { if (isBare) { return this.raw.toU8a(true); @@ -81,14 +115,14 @@ export default class Option extends Base implements Codec { return u8a; } - toString (): string { - return this.raw.toString(); - } - + /** + * @description Returns the value that the Option represents (if available) + */ unwrap (): T { if (this.isNone) { throw new Error('Option: unwrapping a None value'); } + return this.raw; } } diff --git a/packages/types/src/codec/Set.ts b/packages/types/src/codec/Set.ts index 63a879a593..52e9c60715 100644 --- a/packages/types/src/codec/Set.ts +++ b/packages/types/src/codec/Set.ts @@ -11,10 +11,13 @@ type SetValues = { [index: string]: number }; -// 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 potentially extend Set +/** + * @name Set + * @description + * 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> implements Codec { private _setValues: SetValues; @@ -63,35 +66,60 @@ export default class Set extends Base> implements Codec { }, 0); } + /** + * @description The length of the value when encoded as a Uint8Array + */ get encodedLength (): number { return 1; } + /** + * @description true is the Set contains no values + */ get isEmpty (): boolean { return this.values.length === 0; } + /** + * @description The actual set values as a Array + */ get values (): Array { return this.raw; } + /** + * @description The encoded value for the set members + */ get valueEncoded (): number { return Set.encodeSet(this._setValues, this.raw); } + /** + * @description Returns a hex string representation of the value + */ toHex (): string { return u8aToHex(this.toU8a()); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { 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 { return new Uint8Array(this.valueEncoded); } - - toString (): string { - return `[${this.values.map((value) => value).join(', ')}]`; - } } diff --git a/packages/types/src/codec/Struct.ts b/packages/types/src/codec/Struct.ts index 8886b0c3cd..bc2a2f89b9 100644 --- a/packages/types/src/codec/Struct.ts +++ b/packages/types/src/codec/Struct.ts @@ -6,11 +6,15 @@ import { hexToU8a, isHex, isObject, isU8a, u8aConcat, u8aToHex } from '@polkadot 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 -// 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. +/** + * @name Struct + * @description + * 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 + * 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< // The actual Class structure, i.e. key -> Class S extends ConstructorDef = ConstructorDef, @@ -126,24 +130,39 @@ export default class Struct< return this._Types; } + /** + * @description The length of the value when encoded as a Uint8Array + */ get encodedLength (): number { return this.toArray().reduce((length, entry) => { return length += entry.encodedLength; }, 0); } + /** + * @description Returns the values of a member at a specific index (Rather use get(name) for performance) + */ getAtIndex (index: number): Codec { return this.toArray()[index]; } + /** + * @description Converts the Object to an standard JavaScript Array + */ toArray (): Array { return [...this.values()]; } + /** + * @description Returns a hex string representation of the value + */ toHex () { return u8aToHex(this.toU8a()); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return [...this.keys()].reduce((json, key) => { const jsonKey = this._jsonMap.get(key) || key; @@ -155,10 +174,17 @@ export default class Struct< }, {} as any); } + /** + * @description Returns the string representation of the value + */ toString () { 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 { return u8aConcat( ...this.toArray().map((entry) => diff --git a/packages/types/src/codec/Tuple.ts b/packages/types/src/codec/Tuple.ts index ef7c61bae1..0258fb56b7 100644 --- a/packages/types/src/codec/Tuple.ts +++ b/packages/types/src/codec/Tuple.ts @@ -5,9 +5,13 @@ import { Codec, Constructor, ConstructorDef } from '../types'; 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, -// while the U8a encoding is handled in the same way as a Struct +/** + * @name Tuple + * @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< // S & T definitions maps to what we have in Struct (naming documented there) S extends ConstructorDef = { [index: string]: Constructor }, @@ -24,6 +28,9 @@ export default class Tuple< }; } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return [...this.values()].map((entry) => entry.toJSON() diff --git a/packages/types/src/codec/U8a.ts b/packages/types/src/codec/U8a.ts index 5710ebb276..5b4ea0a01b 100644 --- a/packages/types/src/codec/U8a.ts +++ b/packages/types/src/codec/U8a.ts @@ -6,10 +6,14 @@ import { isU8a, u8aToHex, u8aToU8a } from '@polkadot/util'; 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 -// consume the full u8a as passed to it in U8a. As such it is meant to be -// subclassed where the wrapper takes care of the actual lengths. +/** + * @name U8a + * @description + * 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 { constructor (value: AnyU8a) { 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 { return this.length; } @@ -35,19 +42,32 @@ export default class U8a extends Uint8Array implements Codec { return Uint8Array.from(this).subarray(begin, end); } + /** + * @description Returns a hex string representation of the value + */ toHex (): string { return u8aToHex(this); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return this.toHex(); } - toU8a (isBare?: boolean): Uint8Array { - return Uint8Array.from(this); - } - + /** + * @description Returns the string representation of the value + */ toString (): string { 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); + } } diff --git a/packages/types/src/codec/U8aFixed.ts b/packages/types/src/codec/U8aFixed.ts index f0af4da97a..62d387bacb 100644 --- a/packages/types/src/codec/U8aFixed.ts +++ b/packages/types/src/codec/U8aFixed.ts @@ -10,8 +10,12 @@ import U8a from './U8a'; 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 { constructor (value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) { super( @@ -29,6 +33,9 @@ export default class U8aFixed extends U8a { return value; } + /** + * @description Returns the number of bits in the value + */ bitLength () { return this.length * 8; } diff --git a/packages/types/src/codec/UInt.ts b/packages/types/src/codec/UInt.ts index 9f3c83fb25..3ad4a1d0d6 100644 --- a/packages/types/src/codec/UInt.ts +++ b/packages/types/src/codec/UInt.ts @@ -11,12 +11,15 @@ export type UIntBitLength = 8 | 16 | 32 | 64 | 128 | 256; 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 -// use keeps the number to this length. -// +/** + * @name UInt + * @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: -// - 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 { protected _bitLength: UIntBitLength; private _isHexJson: boolean; @@ -46,29 +49,48 @@ export default class UInt extends BN implements Codec { return bnToBn(value).toString(); } - bitLength (): UIntBitLength { - return this._bitLength; - } - + /** + * @description The length of the value when encoded as a Uint8Array + */ get encodedLength (): number { 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 { return bnToHex(this, this._bitLength); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return this._isHexJson ? this.toHex() : 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 { return bnToU8a(this, this._bitLength, true); } - - toBn (): BN { - return this; - } } diff --git a/packages/types/src/codec/Vector.ts b/packages/types/src/codec/Vector.ts index 9acf82f472..a25136b9e3 100644 --- a/packages/types/src/codec/Vector.ts +++ b/packages/types/src/codec/Vector.ts @@ -7,11 +7,13 @@ import { u8aConcat, u8aToU8a, u8aToHex } from '@polkadot/util'; import Compact from './Compact'; 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, -// i.e. while it wraps an array, it provides a `length` property to get the actual length, `at(index)` -// to retrieve a specific item. Additionally the helper functions `map`, `filter`, `forEach` and -// `reduce` is exposed on the interface. +/** + * @name Vector + * @description + * This manages codec arrays. Intrernally it keeps track of the length (as decoded) and allows + * 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< T extends Codec > extends Array implements Codec { @@ -63,26 +65,41 @@ export default class Vector< return this._Type.name; } + /** + * @description The length of the value when encoded as a Uint8Array + */ get encodedLength (): number { return this.reduce((total, raw) => { return total + raw.encodedLength; }, Compact.encodeU8a(this.length).length); } + /** + * @description Converts the Object to an standard JavaScript Array + */ toArray (): Array { return Array.from(this); } + /** + * @description Returns a hex string representation of the value + */ toHex (): string { return u8aToHex(this.toU8a()); } + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any { return this.map((entry) => entry.toJSON() ); } + /** + * @description Returns the string representation of the value + */ toString (): string { // Overwrite the default toString representation of Array. const data = this.map((entry) => @@ -92,6 +109,10 @@ export default class Vector< 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 { const encoded = this.map((entry) => entry.toU8a(isBare) diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index f599555887..92cdfa6adc 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -7,6 +7,9 @@ // perspective these are the value classes. (Codec is for the cases where you need // to construct values dynamically) +/** + * @summary Type definitions that are used in the system + */ export { default as AccountId } from './AccountId'; export { default as AccountIndex } from './AccountIndex'; export { default as Address } from './Address'; diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index fce9492caa..317bb2765f 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -13,11 +13,38 @@ export type AnyString = string | String; export type AnyU8a = Uint8Array | Array | 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 { + /** + * @description The length of the value when encoded as a Uint8Array + */ encodedLength: number; + + /** + * @description Returns a hex string representation of the value + */ toHex (): string; + + /** + * @description Converts the Object to JSON, typically used for RPC transfers + */ toJSON (): any; + + /** + * @description Returns the string representation of the value + */ 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; }