Rename api-codec -> types (#183)
* Rename api-codec -> types * Cleanups with exports (as found with use) * Docs to build for /types
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import AccountId from './AccountId';
|
||||
|
||||
describe('AccountId', () => {
|
||||
it('decodes from u8a', () => {
|
||||
expect(
|
||||
new AccountId()
|
||||
.fromU8a(
|
||||
new Uint8Array([
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8
|
||||
])
|
||||
)
|
||||
.toString()
|
||||
).toEqual(
|
||||
'5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s'
|
||||
);
|
||||
});
|
||||
|
||||
it('decodes from address', () => {
|
||||
expect(
|
||||
new AccountId()
|
||||
.fromJSON('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s')
|
||||
.toHex()
|
||||
).toEqual(
|
||||
'0x0102030405060708010203040506070801020304050607080102030405060708'
|
||||
);
|
||||
});
|
||||
|
||||
it('decodes from hex', () => {
|
||||
expect(
|
||||
new AccountId()
|
||||
.fromJSON('0x0102030405060708010203040506070801020304050607080102030405060708')
|
||||
.toJSON()
|
||||
).toEqual(
|
||||
'5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s'
|
||||
);
|
||||
});
|
||||
|
||||
it('allows creation from another', () => {
|
||||
expect(
|
||||
new AccountId(
|
||||
new AccountId(
|
||||
'0x0102030405060708010203040506070801020304050607080102030405060708'
|
||||
)
|
||||
).toString()
|
||||
).toEqual(
|
||||
'5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import encodeAddress from '@polkadot/util-keyring/address/encode';
|
||||
import decodeAddress from '@polkadot/util-keyring/address/decode';
|
||||
import hexToU8a from '@polkadot/util/hex/toU8a';
|
||||
import isHex from '@polkadot/util/is/hex';
|
||||
import isU8a from '@polkadot/util/is/u8a';
|
||||
import u8aToU8a from '@polkadot/util/u8a/toU8a';
|
||||
|
||||
import U8a from './codec/U8a';
|
||||
import U8aFixed from './codec/U8aFixed';
|
||||
|
||||
// A wrapper around an AccountId/PublicKey representation. Since we are dealing with
|
||||
// underlying PublicKeys (32 bytes in length), we extend from U8aFixed which is
|
||||
// just a Uint8Array wrapper with a fixed length.
|
||||
export default class AccountId extends U8aFixed {
|
||||
constructor (value: AnyU8a = new Uint8Array()) {
|
||||
super(
|
||||
value instanceof U8a
|
||||
? value.raw
|
||||
: AccountId.decode(value),
|
||||
256
|
||||
);
|
||||
}
|
||||
|
||||
static encode (value: Uint8Array): string {
|
||||
return encodeAddress(value);
|
||||
}
|
||||
|
||||
static decode (value: string | Uint8Array | Array<number>): Uint8Array {
|
||||
if (isU8a(value) || Array.isArray(value)) {
|
||||
return u8aToU8a(value);
|
||||
} else if (isHex(value)) {
|
||||
return hexToU8a(value);
|
||||
}
|
||||
|
||||
return decodeAddress(value);
|
||||
}
|
||||
|
||||
fromJSON (input: any): AccountId {
|
||||
super.fromJSON(AccountId.decode(input));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): AccountId {
|
||||
super.fromU8a(input);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return AccountId.encode(this.raw);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import u8aToHex from '@polkadot/util/u8a/toHex';
|
||||
import u8aToU8a from '@polkadot/util/u8a/toU8a';
|
||||
|
||||
import U8a from './codec/U8a';
|
||||
|
||||
// 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.
|
||||
export default class AccountIndex extends U8a {
|
||||
constructor (value: AnyU8a = new Uint8Array()) {
|
||||
super(
|
||||
value instanceof U8a
|
||||
? value.raw
|
||||
: AccountIndex.decode(value)
|
||||
);
|
||||
}
|
||||
|
||||
// FIXME Not 100% sure how to handle the encoding of short addresses. It is (mostly)
|
||||
// unused atm, options are to go to hex or to utf8. Here we go the hex route.
|
||||
static encode (value: Uint8Array): string {
|
||||
return u8aToHex(value);
|
||||
}
|
||||
|
||||
static decode (value: string | Uint8Array | Array<number>): Uint8Array {
|
||||
return u8aToU8a(value);
|
||||
}
|
||||
|
||||
fromJSON (input: any): AccountIndex {
|
||||
super.fromJSON(AccountIndex.decode(input));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// TODO Without specific data and actual real-world tests, unsure about how the
|
||||
// actual encoding here fits together. It is quite possibly prefix-encoded, so
|
||||
// prefixes may have to be stripped.
|
||||
fromU8a (input: Uint8Array): AccountIndex {
|
||||
super.fromU8a(input);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return AccountIndex.encode(this.raw);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Address from './Address';
|
||||
|
||||
describe('Address', () => {
|
||||
it('decodes with a prefix (255)', () => {
|
||||
expect(
|
||||
new Address()
|
||||
.fromU8a(
|
||||
new Uint8Array([
|
||||
255,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8
|
||||
])
|
||||
)
|
||||
.toString()
|
||||
).toEqual('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s');
|
||||
});
|
||||
|
||||
it('encodes with a prefix', () => {
|
||||
expect(
|
||||
new Address()
|
||||
.fromJSON('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s')
|
||||
.toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([
|
||||
255,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('encodes address to ss-58 format', () => {
|
||||
expect(
|
||||
new Address()
|
||||
.fromU8a(
|
||||
new Uint8Array([
|
||||
255,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8
|
||||
])
|
||||
)
|
||||
.toString()
|
||||
).toEqual('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s');
|
||||
});
|
||||
|
||||
it('decodes with a prefix (1-byte)', () => {
|
||||
expect(
|
||||
new Address()
|
||||
.fromU8a(
|
||||
new Uint8Array([
|
||||
1, 17
|
||||
])
|
||||
)
|
||||
.toString()
|
||||
).toEqual('0x11');
|
||||
});
|
||||
|
||||
it('decodes with a prefix (2-bytes)', () => {
|
||||
expect(
|
||||
new Address()
|
||||
.fromU8a(
|
||||
new Uint8Array([
|
||||
0xfc, 17, 18
|
||||
])
|
||||
)
|
||||
.toString()
|
||||
).toEqual('0x1112');
|
||||
});
|
||||
|
||||
it('decodes with a prefix (4-bytes)', () => {
|
||||
expect(
|
||||
new Address()
|
||||
.fromU8a(
|
||||
new Uint8Array([
|
||||
0xfd, 17, 18, 19, 20
|
||||
])
|
||||
)
|
||||
.toString()
|
||||
).toEqual('0x11121314');
|
||||
});
|
||||
|
||||
it('decodes with a prefix (8-bytes)', () => {
|
||||
expect(
|
||||
new Address()
|
||||
.fromU8a(
|
||||
new Uint8Array([
|
||||
0xfe, 17, 18, 19, 20, 21, 22, 23, 24
|
||||
])
|
||||
)
|
||||
.toString()
|
||||
).toEqual('0x1112131415161718');
|
||||
});
|
||||
|
||||
it('fails to code invalid lengths', () => {
|
||||
expect(
|
||||
() => Address.writeLength(34)
|
||||
).toThrow(/Invalid bitLength/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import isHex from '@polkadot/util/is/hex';
|
||||
import isU8a from '@polkadot/util/is/u8a';
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
import u8aToU8a from '@polkadot/util/u8a/toU8a';
|
||||
|
||||
import Base from './codec/Base';
|
||||
import AccountId from './AccountId';
|
||||
import AccountIndex from './AccountIndex';
|
||||
|
||||
// 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
|
||||
// [ <prefix-byte>, ...publicKey/...bytes ]
|
||||
export default class Address extends Base<AccountId | AccountIndex> {
|
||||
constructor (value: Address | AccountId | AccountIndex | string | Uint8Array = new Uint8Array()) {
|
||||
super(
|
||||
value instanceof Address
|
||||
? value.raw
|
||||
: Address.decode(value)
|
||||
);
|
||||
}
|
||||
|
||||
static decode (value: AccountId | AccountIndex | string | Uint8Array | Array<number>): AccountId | AccountIndex {
|
||||
if (value instanceof AccountId || value instanceof AccountIndex) {
|
||||
return value;
|
||||
} else if (isU8a(value) || Array.isArray(value)) {
|
||||
return value.length === 32
|
||||
? new AccountId(u8aToU8a(value))
|
||||
: new AccountIndex(u8aToU8a(value));
|
||||
} else if (isHex(value)) {
|
||||
return value.length === 66
|
||||
? new AccountId(value)
|
||||
: new AccountIndex(value);
|
||||
}
|
||||
|
||||
// FIXME This _may_ be an issue. Depending on how the actual AccountIndex is
|
||||
// actually encoded as a string. Here we just assume that it is an ss-58 value
|
||||
// and use the stock-stand AccountId as PublicKey
|
||||
return new AccountId(value);
|
||||
}
|
||||
|
||||
// TODO
|
||||
// - Double-check this logic again - if really <= 0xef, the throw
|
||||
// is unneeded since all cases are catered for here
|
||||
// - We probably want to clean the read/write up with enums if it
|
||||
// is an exact check and not a <= check (first item)
|
||||
static readLength (input: Uint8Array): number {
|
||||
const first = input[0];
|
||||
|
||||
if (first <= 0xef) {
|
||||
return 1;
|
||||
} else if (first === 0xfc) {
|
||||
return 2;
|
||||
} else if (first === 0xfd) {
|
||||
return 4;
|
||||
} else if (first === 0xfe) {
|
||||
return 8;
|
||||
} else if (first === 0xff) {
|
||||
return 32;
|
||||
}
|
||||
|
||||
throw new Error(`Invalid account index byte, 0x${first.toString(16)}`);
|
||||
}
|
||||
|
||||
static writeLength (length: number): Uint8Array {
|
||||
if (length === 1) {
|
||||
return new Uint8Array([0xef]);
|
||||
} else if (length === 2) {
|
||||
return new Uint8Array([0xfc]);
|
||||
} else if (length === 4) {
|
||||
return new Uint8Array([0xfd]);
|
||||
} else if (length === 8) {
|
||||
return new Uint8Array([0xfe]);
|
||||
} else if (length === 32) {
|
||||
return new Uint8Array([0xff]);
|
||||
}
|
||||
|
||||
throw new Error(`Invalid bitLength, ${length * 8}`);
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return 1 + super.byteLength();
|
||||
}
|
||||
|
||||
fromJSON (input: any): Address {
|
||||
this.raw = Address.decode(input);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// FIXME I actually believe this is wrong, it needs to be checked. Here 1-byte
|
||||
// addresses are actually 2 bytes, 2-byte is 3-bytes, etc. I believe the actual
|
||||
// short-encoding should be left completely inside AccountId (For now, leaving
|
||||
// as-is until we can actually pull storage data and check - and/or read the
|
||||
// actual code again to check the implementation)
|
||||
fromU8a (input: Uint8Array): Address {
|
||||
this.raw = Address.readLength(input) === 32
|
||||
? new AccountId().fromU8a(input.subarray(1))
|
||||
: new AccountIndex().fromU8a(input.subarray(1));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.raw.toJSON();
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this.raw.toString();
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return isBare
|
||||
? this.raw.toU8a(true)
|
||||
: u8aConcat(
|
||||
Address.writeLength(this.raw.byteLength()),
|
||||
this.raw.toU8a(isBare)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import AccountId from './AccountId';
|
||||
|
||||
// Wrapper for a AuthorityId. Same as an normal AccountId, i.e. a wrapper
|
||||
// around publicKey, however specialized since it specifically points to
|
||||
// an authority.
|
||||
export default class AuthorityId extends AccountId {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U128 from './U128';
|
||||
|
||||
// The Substrate Balance representation.
|
||||
export default class Balance extends U128 {
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { BftAuthoritySignature, BftHashSignature, Justification } from './Bft';
|
||||
|
||||
describe('BftAuthoritySignature', () => {
|
||||
const sig = new BftAuthoritySignature({
|
||||
authorityId: '0x12344321',
|
||||
signature: '0x567890098765'
|
||||
});
|
||||
|
||||
it('has the correct authorityId', () => {
|
||||
expect(sig.authorityId.toHex()).toEqual('0x12344321');
|
||||
});
|
||||
|
||||
it('has the correct signature', () => {
|
||||
expect(sig.signature.toHex()).toEqual('0x567890098765');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BftHashSignature', () => {
|
||||
const sig = new BftHashSignature({
|
||||
hash: '0x12344321',
|
||||
signature: '0x567890098765'
|
||||
});
|
||||
|
||||
it('has the correct hash', () => {
|
||||
expect(sig.hash.toHex()).toEqual('0x12344321');
|
||||
});
|
||||
|
||||
it('has the correct signature', () => {
|
||||
expect(sig.signature.toHex()).toEqual('0x567890098765');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Justification', () => {
|
||||
const just = new Justification({
|
||||
round: 32,
|
||||
hash: '0xabcd',
|
||||
signatures: [
|
||||
{ authorityId: '0x1234', signature: '0x5678' },
|
||||
{ authorityId: '0x9876', signature: '0x5432' }
|
||||
]
|
||||
});
|
||||
|
||||
it('has the correct hash', () => {
|
||||
expect(just.hash.toHex()).toEqual('0xabcd');
|
||||
});
|
||||
|
||||
it('has the correct round', () => {
|
||||
expect(just.round.toNumber()).toEqual(32);
|
||||
});
|
||||
|
||||
it('has the correct signatures', () => {
|
||||
const sig = just.signatures.get(1);
|
||||
|
||||
expect(sig.authorityId.toHex()).toEqual('0x9876');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber, AnyU8a } from './types';
|
||||
|
||||
import Struct from './codec/Struct';
|
||||
import Tuple from './codec/Tuple';
|
||||
import Vector from './codec/Vector';
|
||||
import AuthorityId from './AuthorityId';
|
||||
import Hash from './Hash';
|
||||
import Signature from './Signature';
|
||||
import U32 from './U32';
|
||||
|
||||
export type BftAuthoritySignatureValue = {
|
||||
authorityId?: AnyU8a,
|
||||
signature?: AnyU8a
|
||||
};
|
||||
|
||||
// Represents a Bft Hash and Signature pairing, typically used in reporting
|
||||
// network behaviour.
|
||||
export class BftAuthoritySignature extends Tuple {
|
||||
constructor (value?: BftAuthoritySignatureValue) {
|
||||
super({
|
||||
authorityId: AuthorityId,
|
||||
signature: Signature
|
||||
}, value);
|
||||
}
|
||||
|
||||
get authorityId (): AuthorityId {
|
||||
return this.raw.authorityId as AuthorityId;
|
||||
}
|
||||
|
||||
get signature (): Signature {
|
||||
return this.raw.signature as Signature;
|
||||
}
|
||||
}
|
||||
|
||||
export type BftHashSignatureValue = {
|
||||
hash?: AnyU8a,
|
||||
signature?: AnyU8a
|
||||
};
|
||||
|
||||
// Represents a Bft Hash and Signature pairing, typically used in reporting
|
||||
// network behaviour.
|
||||
export class BftHashSignature extends Tuple {
|
||||
constructor (value?: BftHashSignatureValue) {
|
||||
super({
|
||||
hash: Hash,
|
||||
signature: Signature
|
||||
}, value);
|
||||
}
|
||||
|
||||
get hash (): Hash {
|
||||
return this.raw.hash as Hash;
|
||||
}
|
||||
|
||||
get signature (): Signature {
|
||||
return this.raw.signature as Signature;
|
||||
}
|
||||
}
|
||||
|
||||
export type JustificationValue = {
|
||||
round?: AnyNumber,
|
||||
hash?: AnyU8a,
|
||||
signatures?: Array<BftAuthoritySignatureValue>
|
||||
};
|
||||
|
||||
export class Justification extends Struct {
|
||||
constructor (value?: JustificationValue) {
|
||||
super({
|
||||
// FIXME Rust returns this as "round_number", we actually want a JSON alias
|
||||
// in the structure to take care of these renames...
|
||||
round: U32,
|
||||
hash: Hash,
|
||||
signatures: Vector.with(BftAuthoritySignature)
|
||||
}, value, new Map([['round', 'round_number']]));
|
||||
}
|
||||
|
||||
get hash (): Hash {
|
||||
return this.raw.hash as Hash;
|
||||
}
|
||||
|
||||
get round (): U32 {
|
||||
return this.raw.round as U32;
|
||||
}
|
||||
|
||||
get signatures (): Vector<BftAuthoritySignature> {
|
||||
return this.raw.signatures as Vector<BftAuthoritySignature>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import hexToU8a from '@polkadot/util/hex/toU8a';
|
||||
|
||||
import Block from './Block';
|
||||
|
||||
describe('Block', () => {
|
||||
it('decodes a block properly', () => {
|
||||
const block = new Block();
|
||||
|
||||
block.fromU8a(hexToU8a(
|
||||
'0x' +
|
||||
// parent_hash
|
||||
'0900000000000000000000000000000000000000000000000000000000000009' +
|
||||
// number
|
||||
'4300000000000000' +
|
||||
// state_root
|
||||
'0800000000000000000000000000000000000000000000000000000000000008' +
|
||||
// transaction_root
|
||||
'0700000000000000000000000000000000000000000000000000000000000007' +
|
||||
// digest
|
||||
'08' + // 2 << 2
|
||||
'0401' +
|
||||
'0402' +
|
||||
// transactions
|
||||
'04' + // 1 << 2
|
||||
// 111 bytes in compact encoding
|
||||
'bd01' +
|
||||
// prefix
|
||||
'ff' +
|
||||
'0000000000000000000000000000000000000000000000000000000000000000' +
|
||||
'00000000' +
|
||||
'0300' +
|
||||
'7527000000000000' +
|
||||
'0000000000000000000000000000000000000000000000000000000000000000' +
|
||||
'0000000000000000000000000000000000000000000000000000000000000000'
|
||||
));
|
||||
|
||||
expect(
|
||||
block.header.blockNumber.toNumber()
|
||||
).toEqual(67);
|
||||
expect(
|
||||
block.extrinsics.length
|
||||
).toEqual(1); // eslint-disable-line
|
||||
expect(
|
||||
block.extrinsics.get(0).length
|
||||
).toEqual(111); // eslint-disable-line
|
||||
});
|
||||
|
||||
// FIXME check again when we have a valid chain/UI
|
||||
it.skip('has a valid block hash', () => {
|
||||
expect(
|
||||
new Block({
|
||||
extrinsics: [
|
||||
[255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 139, 165, 170, 91, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
[255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
],
|
||||
header: {
|
||||
digest: {
|
||||
logs: []
|
||||
},
|
||||
extrinsicsRoot: '0x5ce1a2c55efaf371f06fd94672779daf130591a12f7513ae786bea4fa7bd499e',
|
||||
number: 1556355,
|
||||
parentHash: '0x09223919f63b5ded0c7bf7d953ba22bf30ea8a19e6be4de35f25163b2b268490',
|
||||
stateRoot: '0xd45159e04f36955ecb9c73d6ca514ac2d0e3ce00f58588b7c142d36cf7d237ec'
|
||||
}
|
||||
}).hash.toHex()
|
||||
).toEqual('0xd1b7e2c8f1ba2665d89dba334dcf45caa12e34d22587a09e2d03372366a81d8b');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import blake2Asu8a from '@polkadot/util-crypto/blake2/asU8a';
|
||||
|
||||
import Struct from './codec/Struct';
|
||||
import Extrinsics from './Extrinsics';
|
||||
import Hash from './Hash';
|
||||
import Header, { HeaderValue } from './Header';
|
||||
|
||||
export type BlockValue = {
|
||||
extrinsics?: Array<AnyU8a>
|
||||
header?: HeaderValue
|
||||
};
|
||||
|
||||
// A block encoded with header and extrinsics
|
||||
export default class Block extends Struct {
|
||||
constructor (value?: BlockValue) {
|
||||
super({
|
||||
header: Header,
|
||||
extrinsics: Extrinsics
|
||||
}, value);
|
||||
}
|
||||
|
||||
get extrinsics (): Extrinsics {
|
||||
return this.raw.extrinsics as Extrinsics;
|
||||
}
|
||||
|
||||
// convenience, encodes the header and returns the actual hash
|
||||
get hash (): Hash {
|
||||
return new Hash(
|
||||
blake2Asu8a(this.toU8a(), 256)
|
||||
);
|
||||
}
|
||||
|
||||
get header (): Header {
|
||||
return this.raw.header as Header;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U64 from './U64';
|
||||
|
||||
export default class BlockNumber extends U64 {
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Base from './codec/Base';
|
||||
|
||||
export default class Bool extends Base<boolean> {
|
||||
constructor (value: Bool | boolean = false) {
|
||||
super(
|
||||
value instanceof Bool
|
||||
? value.raw
|
||||
: value
|
||||
);
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return 1;
|
||||
}
|
||||
|
||||
fromJSON (input: any): Bool {
|
||||
this.raw = input === true;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Bool {
|
||||
this.raw = input[0] === 1;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return new Uint8Array([this.raw ? 1 : 0]);
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return `${this.raw}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
|
||||
import Length from './codec/Length';
|
||||
import U8a from './codec/U8a';
|
||||
|
||||
// A Bytes. 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 String and Array)
|
||||
export default class Bytes extends U8a {
|
||||
protected _length: Length;
|
||||
|
||||
constructor (value?: AnyU8a) {
|
||||
super(value);
|
||||
|
||||
this._length = new Length(this.raw.length);
|
||||
}
|
||||
|
||||
get length (): number {
|
||||
return this._length.toNumber();
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return this._length.byteLength() + this.length;
|
||||
}
|
||||
|
||||
fromJSON (input: any): Bytes {
|
||||
super.fromJSON(input);
|
||||
|
||||
this._length.setValue(this.raw.length);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Bytes {
|
||||
this._length.fromU8a(input);
|
||||
|
||||
const length = this._length.toNumber();
|
||||
const offset = this._length.byteLength();
|
||||
|
||||
super.fromU8a(input.subarray(offset, offset + length));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return u8aConcat(
|
||||
this._length.toU8a(isBare),
|
||||
this.raw
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import blake2Asu8a from '@polkadot/util-crypto/blake2/asU8a';
|
||||
|
||||
import Bytes from './Bytes';
|
||||
import Hash from './Hash';
|
||||
|
||||
// Representation of an Extrinsic in the system.
|
||||
//
|
||||
// NOTE At this point we are just keeping to a bare-bones Vec<u8> structure,
|
||||
// this should be expanded to do the automatic decoding of an extrinsic
|
||||
export default class Extrinsic extends Bytes {
|
||||
// convernience, encodes the extrinsic and returns the actual hash
|
||||
get hash (): Hash {
|
||||
return new Hash(
|
||||
blake2Asu8a(this.toU8a(), 256)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Vector from './codec/Vector';
|
||||
import Extrinsic from './Extrinsic';
|
||||
|
||||
// A list of extrinsics
|
||||
export default class Extrinsics extends Vector.with(Extrinsic) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U64 from './U64';
|
||||
|
||||
// Gas for contracts
|
||||
export default class Gas extends U64 {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
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.
|
||||
export default class H256 extends U8aFixed {
|
||||
constructor (value?: AnyU8a) {
|
||||
super(value, 256);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import U8aFixed from './codec/U8aFixed';
|
||||
|
||||
// Hash containing 512 bits (64 bytes), typically used for signatures
|
||||
export default class H512 extends U8aFixed {
|
||||
constructor (value?: AnyU8a) {
|
||||
super(value, 512);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
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
|
||||
export default class Hash extends H256 {
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"digest":{"logs":[]},"extrinsicsRoot":"0x45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0","number":0,"parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","stateRoot":"0x294c3470ae3be7555240b9d034ec19c3715ba2c3f20b92441f8cea0cab66ab56"}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Header from './Header';
|
||||
import json from './Header.only.json';
|
||||
|
||||
describe('Header', () => {
|
||||
it('decodes an actual JSON response', () => {
|
||||
const header = new Header();
|
||||
|
||||
header.fromJSON(json);
|
||||
|
||||
expect(
|
||||
header.blockNumber.toNumber()
|
||||
).toEqual(0);
|
||||
expect(
|
||||
header.extrinsicsRoot.toString()
|
||||
).toEqual('0x45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0');
|
||||
expect(
|
||||
header.parentHash.toString()
|
||||
).toEqual('0x0000000000000000000000000000000000000000000000000000000000000000');
|
||||
expect(
|
||||
header.stateRoot.toString()
|
||||
).toEqual('0x294c3470ae3be7555240b9d034ec19c3715ba2c3f20b92441f8cea0cab66ab56');
|
||||
expect(
|
||||
header.digest.logs.toString()
|
||||
).toEqual('[]');
|
||||
});
|
||||
|
||||
// FIXME check again when we have a valid chain/UI
|
||||
it.skip('creates actual valid hash', () => {
|
||||
expect(
|
||||
new Header({
|
||||
digest: {
|
||||
logs: []
|
||||
},
|
||||
extrinsicsRoot: '0x5ce1a2c55efaf371f06fd94672779daf130591a12f7513ae786bea4fa7bd499e',
|
||||
number: 1556355,
|
||||
parentHash: '0x09223919f63b5ded0c7bf7d953ba22bf30ea8a19e6be4de35f25163b2b268490',
|
||||
stateRoot: '0xd45159e04f36955ecb9c73d6ca514ac2d0e3ce00f58588b7c142d36cf7d237ec'
|
||||
}).hash.toHex()
|
||||
).toEqual('0x3a91467e3d298684c2d3ee68362615e9b21fa9e37739c02c25f8075918e1ab11');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber, AnyU8a } from './types';
|
||||
|
||||
import blake2Asu8a from '@polkadot/util-crypto/blake2/asU8a';
|
||||
|
||||
import Struct from './codec/Struct';
|
||||
import Vector from './codec/Vector';
|
||||
|
||||
import BlockNumber from './BlockNumber';
|
||||
import Bytes from './Bytes';
|
||||
import Hash from './Hash';
|
||||
|
||||
type DigestValue = {
|
||||
logs?: Array<AnyU8a>
|
||||
};
|
||||
|
||||
export type HeaderValue = {
|
||||
digest?: DigestValue,
|
||||
extrinsicsRoot?: AnyU8a,
|
||||
number?: AnyNumber,
|
||||
parentHash?: AnyU8a,
|
||||
stateRoot?: AnyU8a
|
||||
};
|
||||
|
||||
// A block header digest.
|
||||
export class Digest extends Struct {
|
||||
constructor (value?: DigestValue) {
|
||||
super({
|
||||
logs: Vector.with(Bytes)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get logs (): Vector<Bytes> {
|
||||
return this.raw.logs as Vector<Bytes>;
|
||||
}
|
||||
}
|
||||
|
||||
// A block header.
|
||||
export default class Header extends Struct {
|
||||
constructor (value?: HeaderValue) {
|
||||
super({
|
||||
parentHash: Hash,
|
||||
number: BlockNumber,
|
||||
stateRoot: Hash,
|
||||
extrinsicsRoot: Hash,
|
||||
digest: Digest
|
||||
}, value);
|
||||
}
|
||||
|
||||
get blockNumber (): BlockNumber {
|
||||
return this.raw.number as BlockNumber;
|
||||
}
|
||||
|
||||
get digest (): Digest {
|
||||
return this.raw.digest as Digest;
|
||||
}
|
||||
|
||||
get extrinsicsRoot (): Hash {
|
||||
return this.raw.extrinsicsRoot as Hash;
|
||||
}
|
||||
|
||||
// convenience, encodes the header and returns the actual hash
|
||||
get hash (): Hash {
|
||||
return new Hash(
|
||||
blake2Asu8a(this.toU8a(), 256)
|
||||
);
|
||||
}
|
||||
|
||||
get parentHash (): Hash {
|
||||
return this.raw.parentHash as Hash;
|
||||
}
|
||||
|
||||
get stateRoot (): Hash {
|
||||
return this.raw.stateRoot as Hash;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import KeyValue, { KeyValueOption } from './KeyValue';
|
||||
|
||||
describe('KeyValue', () => {
|
||||
it('decodes KeyValue from u8a', () => {
|
||||
expect(
|
||||
new KeyValue().fromU8a(
|
||||
new Uint8Array([
|
||||
4 << 2,
|
||||
0x11, 0x22, 0x33, 0x44,
|
||||
9 << 2,
|
||||
0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11
|
||||
])
|
||||
).toJSON()
|
||||
).toEqual({
|
||||
key: '0x11223344',
|
||||
value: '0x998877665544332211'
|
||||
});
|
||||
});
|
||||
|
||||
it('encodes KeyValue from JSON', () => {
|
||||
expect(
|
||||
new KeyValue().fromJSON({
|
||||
key: '0x11223344',
|
||||
value: '0x998877665544332211'
|
||||
}).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([
|
||||
4 << 2,
|
||||
0x11, 0x22, 0x33, 0x44,
|
||||
9 << 2,
|
||||
0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('exposes the properties for key/value', () => {
|
||||
const kv = new KeyValue({
|
||||
key: '0x11223344',
|
||||
value: '0x998877665544332211'
|
||||
});
|
||||
|
||||
expect(kv.key.toHex()).toEqual('0x11223344');
|
||||
expect(kv.value.toHex()).toEqual('0x998877665544332211');
|
||||
});
|
||||
});
|
||||
|
||||
describe('KeyValueOption', () => {
|
||||
it('exposes the properties for key/value', () => {
|
||||
const kv = new KeyValueOption({
|
||||
key: '0x11223344'
|
||||
});
|
||||
|
||||
expect(kv.key.toHex()).toEqual('0x11223344');
|
||||
expect(kv.value.isEmpty).toEqual(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import Option from './codec/Option';
|
||||
import Struct from './codec/Struct';
|
||||
import Tuple from './codec/Tuple';
|
||||
import StorageData from './StorageData';
|
||||
import StorageKey from './StorageKey';
|
||||
|
||||
type KeyValueValue = {
|
||||
key?: 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
|
||||
// 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) {
|
||||
super({
|
||||
key: StorageKey,
|
||||
value: StorageData
|
||||
}, value);
|
||||
}
|
||||
|
||||
get key (): StorageKey {
|
||||
return this.raw.key as StorageKey;
|
||||
}
|
||||
|
||||
get value (): StorageData {
|
||||
return this.raw.value as StorageData;
|
||||
}
|
||||
}
|
||||
|
||||
export type KeyValueOptionValue = {
|
||||
key?: 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
|
||||
// from a Tuple, indicating the use inside areas such as StorageChangeSet
|
||||
export class KeyValueOption extends Tuple {
|
||||
constructor (value?: KeyValueOptionValue) {
|
||||
super({
|
||||
key: StorageKey,
|
||||
value: Option.with(StorageData)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get key (): StorageKey {
|
||||
return this.raw.key as StorageKey;
|
||||
}
|
||||
|
||||
get value (): Option<StorageData> {
|
||||
return this.raw.value as Option<StorageData>;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Metadata from './Metadata';
|
||||
import rpcdata from './Metadata.rpc';
|
||||
|
||||
describe('Metadata', () => {
|
||||
it('decodes properly', () => {
|
||||
const decoded = new Metadata().fromJSON(rpcdata);
|
||||
|
||||
const str = JSON.stringify(decoded.toJSON());
|
||||
|
||||
console.error(str);
|
||||
console.error(decoded.getUniqTypes());
|
||||
|
||||
expect(str).not.toBe(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,351 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import toU8a from '@polkadot/util/u8a/toU8a';
|
||||
|
||||
import Vector from './codec/Vector';
|
||||
import Base from './codec/Base';
|
||||
import Enum from './codec/Enum';
|
||||
import EnumType from './codec/EnumType';
|
||||
import Option from './codec/Option';
|
||||
import Struct from './codec/Struct';
|
||||
import Text from './Text';
|
||||
import Type from './Type';
|
||||
import U16 from './U16';
|
||||
|
||||
// Decodes the runtime metadata as passed through from the `state_getMetadata` call. This
|
||||
// file is probably best understood from the bottom-up, i.e. start reading right at the
|
||||
// end and work up. (Just so we don't use before definition)
|
||||
|
||||
export class EventMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
arguments: Vector.with(Type),
|
||||
documentation: Vector.with(Text)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get arguments (): Vector<Type> {
|
||||
return this.raw.arguments as Vector<Type>;
|
||||
}
|
||||
|
||||
get documentation (): Vector<Text> {
|
||||
return this.raw.documentation as Vector<Text>;
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
}
|
||||
|
||||
export class OuterEventMetadataEvent extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
events: Vector.with(EventMetadata)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get events (): Vector<EventMetadata> {
|
||||
return this.raw.events as Vector<EventMetadata>;
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
}
|
||||
|
||||
export class OuterEventMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
events: Vector.with(OuterEventMetadataEvent)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get events (): Vector<OuterEventMetadataEvent> {
|
||||
return this.raw.events as Vector<OuterEventMetadataEvent>;
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
}
|
||||
|
||||
export class FunctionArgumentMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
type: Type
|
||||
}, value);
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
|
||||
get type (): Type {
|
||||
return this.raw.type as Type;
|
||||
}
|
||||
}
|
||||
|
||||
export class FunctionMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
id: U16,
|
||||
name: Text,
|
||||
arguments: Vector.with(FunctionArgumentMetadata),
|
||||
documentation: Vector.with(Text)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get arguments (): Vector<FunctionArgumentMetadata> {
|
||||
return this.raw.arguments as Vector<FunctionArgumentMetadata>;
|
||||
}
|
||||
|
||||
get documentation (): Vector<Text> {
|
||||
return this.raw.documentation as Vector<Text>;
|
||||
}
|
||||
|
||||
get id (): U16 {
|
||||
return this.raw.id as U16;
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
}
|
||||
|
||||
export class CallMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
functions: Vector.with(FunctionMetadata)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get functions (): Vector<FunctionMetadata> {
|
||||
return this.raw.functions as Vector<FunctionMetadata>;
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
}
|
||||
|
||||
export class ModuleMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
call: CallMetadata
|
||||
}, value);
|
||||
}
|
||||
|
||||
get call (): CallMetadata {
|
||||
return this.raw.call as CallMetadata;
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageFunctionModifier extends Enum {
|
||||
constructor (value?: any) {
|
||||
super(['None', 'Default', 'Required'], value);
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageFunctionType$Map extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
key: Type,
|
||||
value: Type
|
||||
}, value);
|
||||
}
|
||||
|
||||
get key (): Type {
|
||||
return this.raw.type as Type;
|
||||
}
|
||||
|
||||
get value (): Type {
|
||||
return this.raw.value as Type;
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageFunctionType extends EnumType<Type | StorageFunctionType$Map> {
|
||||
constructor (index?: number, value?: any) {
|
||||
super([
|
||||
Type,
|
||||
StorageFunctionType$Map
|
||||
], index, value);
|
||||
}
|
||||
|
||||
get isMap (): boolean {
|
||||
return this.toNumber() === 1;
|
||||
}
|
||||
|
||||
get asMap (): StorageFunctionType$Map {
|
||||
return (this.raw as Base<StorageFunctionType$Map>).raw;
|
||||
}
|
||||
|
||||
get asType (): Type {
|
||||
return (this.raw as Base<Type>).raw;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this.isMap
|
||||
? this.asMap.value.toString()
|
||||
: this.asType.toString();
|
||||
}
|
||||
}
|
||||
|
||||
type StorageFunctionMetadataValue = {
|
||||
name?: string | Text,
|
||||
modifier?: StorageFunctionModifier | AnyNumber,
|
||||
type?: StorageFunctionType,
|
||||
documentation?: Vector<Text> | Array<string>
|
||||
};
|
||||
|
||||
export class StorageFunctionMetadata extends Struct {
|
||||
constructor (value?: StorageFunctionMetadataValue) {
|
||||
super({
|
||||
name: Text,
|
||||
modifier: StorageFunctionModifier,
|
||||
type: StorageFunctionType,
|
||||
documentation: Vector.with(Text)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get documentation (): Vector<Text> {
|
||||
return this.raw.documentation as Vector<Text>;
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
return this.raw.name as Text;
|
||||
}
|
||||
|
||||
get modifier (): StorageFunctionModifier {
|
||||
return this.raw.modifier as StorageFunctionModifier;
|
||||
}
|
||||
|
||||
get type (): StorageFunctionType {
|
||||
return this.raw.type as StorageFunctionType;
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
prefix: Text,
|
||||
functions: Vector.with(StorageFunctionMetadata)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get functions (): Vector<StorageFunctionMetadata> {
|
||||
return this.raw.functions as Vector<StorageFunctionMetadata>;
|
||||
}
|
||||
|
||||
get prefix (): Text {
|
||||
return this.raw.prefix as Text;
|
||||
}
|
||||
}
|
||||
|
||||
export class RuntimeModuleMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
prefix: Text,
|
||||
module: ModuleMetadata,
|
||||
storage: Option.with(StorageMetadata)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get module (): ModuleMetadata {
|
||||
return this.raw.module as ModuleMetadata;
|
||||
}
|
||||
|
||||
get prefix (): Text {
|
||||
return this.raw.prefix as Text;
|
||||
}
|
||||
|
||||
get storage (): StorageMetadata | undefined {
|
||||
return (this.raw.storage as Option<StorageMetadata>).value;
|
||||
}
|
||||
}
|
||||
|
||||
export default class RuntimeMetadata extends Struct {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
outerEvent: OuterEventMetadata,
|
||||
modules: Vector.with(RuntimeModuleMetadata)
|
||||
}, value);
|
||||
}
|
||||
|
||||
// We receive this as an Array<number> in the JSON output from the Node. Convert
|
||||
// to u8a and use the fromU8a to do the actual parsing
|
||||
fromJSON (input: Uint8Array | string | Array<number>): RuntimeMetadata {
|
||||
return this.fromU8a(
|
||||
toU8a(input)
|
||||
) as RuntimeMetadata;
|
||||
}
|
||||
|
||||
// FIXME Currently toJSON creates a struct, so it is not a one-to-one mapping
|
||||
// with what is actually found on the RPC layer. This needs to be adjusted to
|
||||
// match fromJSON. (However for now, it is useful in debugging)
|
||||
toJSON (): any {
|
||||
return super.toJSON();
|
||||
}
|
||||
|
||||
get events (): Vector<OuterEventMetadataEvent> {
|
||||
return (this.raw.outerEvent as OuterEventMetadata).events;
|
||||
}
|
||||
|
||||
get modules (): Vector<RuntimeModuleMetadata> {
|
||||
return this.raw.modules as Vector<RuntimeModuleMetadata>;
|
||||
}
|
||||
|
||||
// Helper to retrieve a list of all type that are found, sorted and de-deuplicated
|
||||
getUniqTypes (): Array<string> {
|
||||
// Quick and dirty flatten (.flat() not available)
|
||||
const flatten = (list: Array<any>): Array<any> =>
|
||||
list.reduce((result, entry) => {
|
||||
return result.concat(
|
||||
Array.isArray(entry)
|
||||
? flatten(entry)
|
||||
: entry
|
||||
);
|
||||
}, []);
|
||||
|
||||
const events = this.events.map((module) =>
|
||||
module.events.map((event) =>
|
||||
event.arguments.map((argument) =>
|
||||
argument.raw
|
||||
)
|
||||
)
|
||||
);
|
||||
const storages = this.modules.map((module) =>
|
||||
module.storage
|
||||
? module.storage.functions.map((fn) =>
|
||||
fn.type.isMap
|
||||
? [fn.type.asMap.key.raw, fn.type.asMap.value.raw]
|
||||
: [fn.type.asType.raw]
|
||||
)
|
||||
: []
|
||||
);
|
||||
const args = this.modules.map((module) =>
|
||||
module.module.call.functions.map((fn) =>
|
||||
fn.arguments.map((argument) =>
|
||||
argument.type.raw
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
return [...new Set(
|
||||
flatten([events, storages, args]).filter((value) => value)
|
||||
)].sort();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import MisbehaviorReport, { BftAtReport } from './MisbehaviorReport';
|
||||
|
||||
describe('BftAtReport', () => {
|
||||
const report = new BftAtReport({
|
||||
round: 16,
|
||||
a: {
|
||||
hash: '0x1234',
|
||||
signature: '0x5678'
|
||||
},
|
||||
b: {
|
||||
hash: '0x8765',
|
||||
signature: '0x4321'
|
||||
}
|
||||
});
|
||||
|
||||
it('has the correct round', () => {
|
||||
expect(report.round.toNumber()).toEqual(16);
|
||||
});
|
||||
|
||||
it('has the correct hash (a)', () => {
|
||||
expect(report.a.hash.toHex()).toEqual('0x1234');
|
||||
});
|
||||
|
||||
it('has the correct signature (b)', () => {
|
||||
expect(report.b.signature.toHex()).toEqual('0x4321');
|
||||
});
|
||||
});
|
||||
|
||||
describe('MisbehaviorReport', () => {
|
||||
const report = new MisbehaviorReport({
|
||||
parentHash: '0x01020304',
|
||||
parentNumber: 78,
|
||||
target: '0x11112222',
|
||||
misbehavior: 0x12
|
||||
});
|
||||
|
||||
it('has the correct misbehavior type', () => {
|
||||
expect(report.misbehavior.Type).toEqual('BftDoubleCommit');
|
||||
});
|
||||
|
||||
it('has the correct parent block', () => {
|
||||
expect(report.parentHash.toHex()).toEqual('0x01020304');
|
||||
expect(report.parentNumber.toNumber()).toEqual(78);
|
||||
});
|
||||
|
||||
it('identifies the misbehaving authority', () => {
|
||||
expect(report.target.toHex()).toEqual('0x11112222');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import EnumType from './codec/EnumType';
|
||||
import Struct from './codec/Struct';
|
||||
import AuthorityId from './AuthorityId';
|
||||
import { BftHashSignature, BftHashSignatureValue } from './Bft';
|
||||
import BlockNumber from './BlockNumber';
|
||||
import Hash from './Hash';
|
||||
import U32 from './U32';
|
||||
|
||||
type BftAtReportValue = {
|
||||
round?: AnyNumber,
|
||||
a?: 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
|
||||
//
|
||||
// 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)
|
||||
export class BftAtReport extends Struct {
|
||||
constructor (value?: BftAtReportValue) {
|
||||
super({
|
||||
round: U32,
|
||||
a: BftHashSignature,
|
||||
b: BftHashSignature
|
||||
}, value);
|
||||
}
|
||||
|
||||
get a (): BftHashSignature {
|
||||
return this.raw.a as BftHashSignature;
|
||||
}
|
||||
|
||||
get b (): BftHashSignature {
|
||||
return this.raw.b as BftHashSignature;
|
||||
}
|
||||
|
||||
get round (): U32 {
|
||||
return this.raw.round as U32;
|
||||
}
|
||||
}
|
||||
|
||||
// Report of a double-prepare
|
||||
export class BftDoublePrepare extends BftAtReport {
|
||||
}
|
||||
|
||||
// Report of a double-commit
|
||||
export class BftDoubleCommit extends BftAtReport {
|
||||
}
|
||||
|
||||
export class MisbehaviorKind extends EnumType<BftDoublePrepare | BftDoubleCommit> {
|
||||
constructor (index: number = 0x11, value?: BftAtReportValue) {
|
||||
super({
|
||||
0x11: BftDoublePrepare,
|
||||
0x12: BftDoubleCommit
|
||||
}, index, value);
|
||||
}
|
||||
}
|
||||
|
||||
type MisbehaviorReportValue = {
|
||||
unstakeThreshold?: AnyNumber,
|
||||
validatorPayment?: AnyNumber
|
||||
};
|
||||
|
||||
// A Misbehaviour report against a specific AuthorityId
|
||||
export default class MisbehaviorReport extends Struct {
|
||||
constructor (value?: MisbehaviorReportValue) {
|
||||
super({
|
||||
parentHash: Hash,
|
||||
parentNumber: BlockNumber,
|
||||
target: AuthorityId,
|
||||
misbehavior: MisbehaviorKind
|
||||
}, value);
|
||||
}
|
||||
|
||||
get misbehavior (): MisbehaviorKind {
|
||||
return this.raw.misbehavior as MisbehaviorKind;
|
||||
}
|
||||
|
||||
get parentHash (): Hash {
|
||||
return this.raw.parentHash as Hash;
|
||||
}
|
||||
|
||||
get parentNumber (): BlockNumber {
|
||||
return this.raw.parentNumber as BlockNumber;
|
||||
}
|
||||
|
||||
get target (): AuthorityId {
|
||||
return this.raw.target as AuthorityId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Moment from './Moment';
|
||||
import U64 from './U64';
|
||||
|
||||
describe('Moment', () => {
|
||||
it('constructs via Date', () => {
|
||||
expect(
|
||||
new Moment(
|
||||
new Date(1537968546280)
|
||||
).toString()
|
||||
).toEqual('2018-09-26T13:29:07.000Z');
|
||||
});
|
||||
|
||||
it('wraps from another Moment', () => {
|
||||
expect(
|
||||
new Moment(
|
||||
new Moment(1234)
|
||||
).toJSON()
|
||||
).toEqual(1234);
|
||||
});
|
||||
|
||||
it('reads values from JSON', () => {
|
||||
expect(
|
||||
new Moment().fromJSON(42).toNumber()
|
||||
).toEqual(42);
|
||||
});
|
||||
|
||||
it('reads values from u8a', () => {
|
||||
expect(
|
||||
new Moment().fromU8a(
|
||||
new U64(69).toU8a()
|
||||
).toNumber()
|
||||
).toEqual(69);
|
||||
});
|
||||
|
||||
it('creates valid U64 u8a outputs', () => {
|
||||
expect(
|
||||
new U64().fromU8a(
|
||||
new Moment(421).toU8a()
|
||||
).toNumber()
|
||||
).toEqual(421);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import BN from 'bn.js';
|
||||
import bnToBn from '@polkadot/util/bn/toBn';
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
import isU8a from '@polkadot/util/is/u8a';
|
||||
import u8aToBn from '@polkadot/util/u8a/toBn';
|
||||
|
||||
import Base from './codec/Base';
|
||||
|
||||
const BITLENGTH = 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
|
||||
export default class Moment extends Base<Date> {
|
||||
constructor (value: Uint8Array | Moment | Date | BN | number = 0) {
|
||||
super(
|
||||
value instanceof Date
|
||||
? new Date(Math.ceil(value.getTime() / 1000) * 1000)
|
||||
: Moment.decode(value)
|
||||
);
|
||||
}
|
||||
|
||||
static decode (value: Uint8Array | Moment | number | BN): Date {
|
||||
if (value instanceof Moment) {
|
||||
return value.raw;
|
||||
} if (isU8a(value)) {
|
||||
value = u8aToBn(value, true);
|
||||
}
|
||||
|
||||
return new Date(
|
||||
bnToBn(value).toNumber() * 1000
|
||||
);
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return BITLENGTH / 8;
|
||||
}
|
||||
|
||||
fromJSON (input: any): Moment {
|
||||
this.raw = Moment.decode(input);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Moment {
|
||||
this.raw = Moment.decode(
|
||||
u8aToBn(input.subarray(0, this.byteLength()), true)
|
||||
);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
getTime (): number {
|
||||
return this.raw.getTime();
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.toNumber();
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return bnToU8a(this.toNumber(), BITLENGTH, true);
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this.raw.toISOString();
|
||||
}
|
||||
|
||||
toBn (): BN {
|
||||
return new BN(this.toNumber());
|
||||
}
|
||||
|
||||
toNumber (): number {
|
||||
return Math.ceil(this.raw.getTime() / 1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import NewAccountOutcome from './NewAccountOutcome';
|
||||
|
||||
describe('NewAccountOutcome', () => {
|
||||
it('allows setting value in constructor', () => {
|
||||
expect(
|
||||
new NewAccountOutcome(2).toNumber()
|
||||
).toEqual(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Enum from './codec/Enum';
|
||||
|
||||
// Enum to track the outcome for creation of an account
|
||||
export default class NewAccountOutcome extends Enum {
|
||||
constructor (index?: number) {
|
||||
super([
|
||||
'NoHint',
|
||||
'GoodHint',
|
||||
'BadHint'
|
||||
], index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U32 from './U32';
|
||||
|
||||
// The Nonce or number of transactiosn sent by a specific account. Generally used
|
||||
// with extrinsics to determine the order of execution.
|
||||
export default class Index extends U32 {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Origin from './Origin';
|
||||
|
||||
describe('Origin', () => {
|
||||
it('does not allow construction', () => {
|
||||
expect(
|
||||
() => new Origin()
|
||||
).toThrow(/placeholder/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Base from './codec/Base';
|
||||
|
||||
// Where Origin occurs, it should be ignored, so it should never actually be constructed
|
||||
export default class Origin extends Base {
|
||||
constructor () {
|
||||
super();
|
||||
|
||||
throw new Error('Origin should not be constructed, it is only a placeholder for compatibility');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U64 from './U64';
|
||||
|
||||
// Identifier for a deployed parachain
|
||||
export default class ParachainId extends U64 {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Extrinsics from './Extrinsics';
|
||||
|
||||
// A list of pending extrinsics
|
||||
export default class PendingExtrinsics extends Extrinsics {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U32 from './U32';
|
||||
|
||||
// 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 {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U32 from './U32';
|
||||
|
||||
// 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 {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U32 from './U32';
|
||||
|
||||
// An increasing number that represents a specific proposal in the system
|
||||
export default class PropIndex extends U32 {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Extrinsic from './Extrinsic';
|
||||
|
||||
// The Nonce or number of transactiosn sent by a specific account. Generally used
|
||||
// with extrinsics to determine the order of execution.
|
||||
export default class Proposal extends Extrinsic {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U32 from './U32';
|
||||
|
||||
// An increasing number that represents a specific proposal in the system
|
||||
export default class ProposalIndex extends U32 {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Address from './Address';
|
||||
|
||||
// Wrapper for a RawAddress.
|
||||
// NOTE Not 100% on the differences between this and Address in the runtime
|
||||
export default class RawAddress extends Address {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U32 from './U32';
|
||||
|
||||
// An increasing number that represents a specific referendum in the system. It
|
||||
// is unique per chain.
|
||||
export default class ReferendumIndex extends U32 {
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"jsonrpc":"2.0","result":{"apis":[[[105,110,104,101,114,101,110,116],1],[[118,97,108,105,100,97,116,120],1]],"authoring_version":1,"impl_name":"substrate-node","impl_version":0,"spec_name":"node","spec_version":1},"id":1}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import rpc from './RuntimeVersion.rpc.json';
|
||||
import RuntimeVersion from './RuntimeVersion';
|
||||
|
||||
describe('RuntimeVersion', () => {
|
||||
const version = new RuntimeVersion().fromJSON(rpc.result);
|
||||
|
||||
it('has the correct authoring', () => {
|
||||
expect(version.authoringVersion.toNumber()).toEqual(1);
|
||||
});
|
||||
|
||||
it('has the apis', () => {
|
||||
const api = version.apis.get(0);
|
||||
|
||||
expect(api.id.toHex()).toEqual('0x696e686572656e74');
|
||||
expect(api.version.toNumber()).toEqual(1);
|
||||
});
|
||||
|
||||
it('has the correct implementation', () => {
|
||||
expect(version.implName.toString()).toEqual('substrate-node');
|
||||
expect(version.implVersion.toNumber()).toEqual(0);
|
||||
});
|
||||
|
||||
it('has the correct spec', () => {
|
||||
expect(version.specName.toString()).toEqual('node');
|
||||
expect(version.specVersion.toNumber()).toEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber, AnyU8a } from './types';
|
||||
|
||||
import Struct from './codec/Struct';
|
||||
import Tuple from './codec/Tuple';
|
||||
import U8aFixed from './codec/U8aFixed';
|
||||
import Vector from './codec/Vector';
|
||||
import Text from './Text';
|
||||
import U32 from './U32';
|
||||
|
||||
class ApiId extends U8aFixed {
|
||||
constructor (value?: AnyU8a) {
|
||||
super(value, 64);
|
||||
}
|
||||
}
|
||||
|
||||
type RuntimeVersionApiValue = {
|
||||
id?: AnyU8a,
|
||||
version?: AnyNumber
|
||||
};
|
||||
|
||||
class RuntimeVersionApi extends Tuple {
|
||||
constructor (value?: RuntimeVersionApiValue) {
|
||||
super({
|
||||
id: ApiId,
|
||||
version: U32
|
||||
}, value);
|
||||
}
|
||||
|
||||
get id (): ApiId {
|
||||
return this.raw.id as ApiId;
|
||||
}
|
||||
|
||||
get version (): U32 {
|
||||
return this.raw.version as U32;
|
||||
}
|
||||
}
|
||||
|
||||
type RuntimeVersionValue = {
|
||||
specName?: string,
|
||||
implName?: string,
|
||||
authoringVersion?: AnyNumber,
|
||||
specVersion?: AnyNumber,
|
||||
implVersion?: AnyNumber,
|
||||
apis?: Array<RuntimeVersionApiValue>
|
||||
};
|
||||
|
||||
export default class RuntimeVersion extends Struct {
|
||||
constructor (value?: RuntimeVersionValue) {
|
||||
super({
|
||||
specName: Text,
|
||||
implName: Text,
|
||||
authoringVersion: U32,
|
||||
specVersion: U32,
|
||||
implVersion: U32,
|
||||
apis: Vector.with(RuntimeVersionApi)
|
||||
}, value, new Map([
|
||||
['authoringVersion', 'authoring_version'],
|
||||
['implName', 'impl_name'],
|
||||
['implVersion', 'impl_version'],
|
||||
['specName', 'spec_name'],
|
||||
['specVersion', 'spec_version']
|
||||
]));
|
||||
}
|
||||
|
||||
get apis (): Vector<RuntimeVersionApi> {
|
||||
return this.raw.apis as Vector<RuntimeVersionApi>;
|
||||
}
|
||||
|
||||
get authoringVersion (): U32 {
|
||||
return this.raw.authoringVersion as U32;
|
||||
}
|
||||
|
||||
get implName (): Text {
|
||||
return this.raw.implName as Text;
|
||||
}
|
||||
|
||||
get implVersion (): U32 {
|
||||
return this.raw.implVersion as U32;
|
||||
}
|
||||
|
||||
get specName (): Text {
|
||||
return this.raw.specName as Text;
|
||||
}
|
||||
|
||||
get specVersion (): U32 {
|
||||
return this.raw.specVersion as U32;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
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.
|
||||
export default class Signature extends H512 {
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"jsonrpc":"2.0","result":{"block":{"extrinsics":[[255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,64,95,171,91,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],"header":{"digest":{"logs":[]},"extrinsicsRoot":"0x233cf65d6f67f628b694c7da2d08020a937bc272560df7dd5cc1f11a7f85dc69","number":1565249,"parentHash":"0x0b0f28f64fdef451b6e2636ef18e9670183e1e4841db5a32ce476186611f6baf","stateRoot":"0xc372e08fa6edddd0ee415742eb551b8475100a40fe47a3d6470ad46b9b7b460d"}},"justification":{"hash":"0x737f58ac7f964353c56160187821ef4d2295d196c8479c21c7ae37f708550b57","round_number":1,"signatures":[["0x65d2273adeb04478658e183dc5edf41f1d86e42255442af62e72dbf1e6c0b977","0x6bfe453137983a7ef474cf3108e7cc0260621fac893e92c41d17952430164a1ee1600fd3f8c9d2d8440d391ac1f1a488ac6fd0185fa0ba722698903753c8bb0c"],["0x8c25a8812190a86c0c086b1c4087e31d82e3375652f9a75e828a4301c98245be","0x9e0ecfe993846758fb15920a7103a5cb4199e03481eec1ebf7abb43cb35e9703baf04b606000c788244ccde5d6fb0b22fc940099ced61e8a404d71787757980b"],["0xbb8943a83c953cc96f927ca2e7062e4819f0b258107e495fb40a78d27c2e1ad7","0xa282bc57b27feccc752f194dfe6e2281986a46bac31d06b629c9b62401804ad00a400a67d3770b7470d207d349f167eda72436d6eae7b90469a61eefe1c99800"],["0xea1a15140e562d9f582b38d64d8d1f575b9f837556fdec40fcc3e564259471c7","0x45926cb65bb59595f447eaac5e782029f7fabd47579fe4fec7b79c1c554abf1c31067a500362c2d84aadca3686bfc455d780d2c3265674154d33ea0349db2307"],["0x432d983331d08c86121cd2c86456cf3eeeb5a2f37bab7f2969453b51b4eed783","0x3a09b440194aa714606a2a223422b7795f7d1ac75dca4b6bc5f5031d51b4e282b264d231ca73ee234a814ea5f60e135e7df6dfa02b363ca1204dfe56c2a4ad03"],["0x2e5baf22ac662c0a3883ccf3e17580e6c41f056642040ddc16a877176becdc53","0x02a5605a3f28f7ed9063a4f465601af8625a7fbb69b4757b9838a90ed3e5e1598671853ee106512a833ab1eb7db48f7915b7b48d0b5c2915898d05f54ce23205"],["0x10b9ddcb0d59f795ab64608bd22215b55868ee01efe6d690b8988c63859a6b27","0x04a3e8d9b12163b8c3488968d447bf8b4968bbce55c09ee18ba57f5b9e10dd8f3ae344551d9014e8a1efb0e7e6e83d7cedf440a1d512266a83d4d25d8759ee06"],["0x044b0abaa1854772c75282aa9187935a56926e9c5f5e0b30cf6993c530c09d26","0x3844d377dc958c96eefbb56c777439142af43aebb764c230b74c3f56a4df3207abf4a347d8fe88e5d2641e82c48522079000c02fd89748705d9efb843128e40d"],["0x1689d1d5c9c5b072034ed95aa1ee22c2dd60df78d82de93dc0e3872bfa4c715a","0x481613e2c0b16ae14adc2e463bda352ebb5a839836c4e384bb4770608cdb38ad02b5ca571d19853f6e706ebf880edf12dc5d448d8d331ea2b8926b03aa9bcd0c"],["0x22fdc8c92de49cd1a11f03f591e507b0827e1e19df35b3b0a2a90ee35df4b06c","0xac7802d1e824c656b3e094cf18d1ff4758d2d8df0874a0be123893a0d8c95ddbe9cf40a765b6cfeecb7756b9f18294f9dca35451499c8a7a99d7621d9cd5610b"],["0xcb7cc7b2f624c92c6fad8ee77458a35c7acaade2b03e5f0634509cef1db7ce09","0x5fc45de00c1291ea605c6929ebe77bd5d2d998c7ad44d1f88bce4b86ecefbd447adbbf0290ea12b2b8a34db2c71f266ddccb54f2074340825edd8f7b0b235503"],["0x5d87486121bcfdfbb7b6d8cbd91558059f798587e194c36efb8b379bb8b3dd8e","0x47f046ecb4aca2ba36994b7e11565306a382615f589d26e827de357623c22d271e0998c4617fa8be3902acdf33cb72538839ca731d4476a0f2b41a4c8297000d"],["0xd164f617a7b5144504166c305f9940fb17cd1656e46ba55f344ee4e5f716c12f","0x663502ec1e40325992d2b7307764f6bd524d30968acf2bd3b0a6d43c5f973eebd192a796a455127d6750f407d14650201b225dc107361c2d634e46c3e0c9340e"],["0x3005b5aab73dc485beecf1df7732876a61c81c8f13d7a4883f1243ecbb9497dd","0x4fdcbb79bd4f852ede225e9e90e5bc6c8b9c8760ac016c4f081f1dfc93ef055b8bbd545b459dd82ef107b20013fae2da55fc31784d933a29261d55466628cd01"],["0xfbf09129e1ca12face363366917add306357e8f6221e57edbfa4e820784cf712","0xc620ff8b940e9be7eaf0f5c8d034c8fec33d1fafc2ea5921660486eff5087027e44bb1b38641894aadb055b9bdece9e480f6042ad801a07588bf19f4ba87cb0e"]]}},"id":8}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import rpc from './SignedBlock.rpc.json';
|
||||
import SignedBlock from './SignedBlock';
|
||||
|
||||
describe('SignedBlock', () => {
|
||||
const block = new SignedBlock().fromJSON(rpc.result);
|
||||
|
||||
it('has the correct stateRoot', () => {
|
||||
expect(
|
||||
block.block.header.stateRoot.toString()
|
||||
).toEqual('0xc372e08fa6edddd0ee415742eb551b8475100a40fe47a3d6470ad46b9b7b460d');
|
||||
});
|
||||
|
||||
it('has the justification', () => {
|
||||
expect(
|
||||
block.justification.hash.toHex()
|
||||
).toEqual('0x737f58ac7f964353c56160187821ef4d2295d196c8479c21c7ae37f708550b57');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Struct from './codec/Struct';
|
||||
import { Justification, JustificationValue } from './Bft';
|
||||
import Block, { BlockValue } from './Block';
|
||||
|
||||
type SignedBlockValue = {
|
||||
block?: BlockValue,
|
||||
justification?: JustificationValue
|
||||
};
|
||||
|
||||
export default class SignedBlock extends Struct {
|
||||
constructor (value?: SignedBlockValue) {
|
||||
super({
|
||||
block: Block,
|
||||
justification: Justification
|
||||
}, value);
|
||||
}
|
||||
|
||||
get block (): Block {
|
||||
return this.raw.block as Block;
|
||||
}
|
||||
|
||||
get justification (): Justification {
|
||||
return this.raw.justification as Justification;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import StorageChangeSet from './StorageChangeSet';
|
||||
|
||||
describe('StorageChangeSet', () => {
|
||||
const set = new StorageChangeSet({
|
||||
hash: '0x1234',
|
||||
changes: [
|
||||
{ key: '0xab', value: '0xcd' }
|
||||
]
|
||||
});
|
||||
|
||||
it('wraps hash', () => {
|
||||
expect(
|
||||
set.hash.toHex()
|
||||
).toEqual('0x1234');
|
||||
});
|
||||
|
||||
it('wraps key/value', () => {
|
||||
expect(
|
||||
set.changes.get(0).value.toString()
|
||||
).toEqual('0xcd');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import Struct from './codec/Struct';
|
||||
import Vector from './codec/Vector';
|
||||
import Hash from './Hash';
|
||||
import { KeyValueOption, KeyValueOptionValue } from './KeyValue';
|
||||
|
||||
type StorageChangeSetValue = {
|
||||
hash?: AnyU8a,
|
||||
changes?: Array<KeyValueOptionValue>
|
||||
};
|
||||
|
||||
// A set of storage changes. It contains the hash/block and
|
||||
// a list of the actual changes that took place
|
||||
export default class StorageChangeSet extends Struct {
|
||||
constructor (value?: StorageChangeSetValue) {
|
||||
super({
|
||||
hash: Hash,
|
||||
changes: Vector.with(KeyValueOption)
|
||||
}, value);
|
||||
}
|
||||
|
||||
get changes (): Vector<KeyValueOption> {
|
||||
return this.raw.changes as Vector<KeyValueOption>;
|
||||
}
|
||||
|
||||
get hash (): Hash {
|
||||
return this.raw.hash as Hash;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Bytes from './Bytes';
|
||||
|
||||
export default class StorageData extends Bytes {
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
import isFunction from '@polkadot/util/is/function';
|
||||
import toU8a from '@polkadot/util/u8a/toU8a';
|
||||
|
||||
import U8a from './codec/U8a';
|
||||
import Bytes from './Bytes';
|
||||
import { StorageFunctionMetadata } from './Metadata';
|
||||
|
||||
export interface StorageFunction {
|
||||
(arg?: any): Uint8Array;
|
||||
meta: StorageFunctionMetadata;
|
||||
method: string;
|
||||
section: string;
|
||||
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.
|
||||
export default class StorageKey extends Bytes {
|
||||
private _outputType: string | null;
|
||||
|
||||
constructor (value: AnyU8a | StorageKey | StorageFunction | [StorageFunction, any]) {
|
||||
super(StorageKey.encode(value));
|
||||
|
||||
this._outputType = StorageKey.getType(value as StorageKey);
|
||||
}
|
||||
|
||||
static encode (value: AnyU8a | StorageKey | StorageFunction | [StorageFunction, any]): Uint8Array {
|
||||
if (value instanceof StorageKey || value instanceof U8a) {
|
||||
return value.raw;
|
||||
} else if (isFunction(value)) {
|
||||
return value();
|
||||
} else if (Array.isArray(value)) {
|
||||
const [fn, arg] = value;
|
||||
|
||||
if (isFunction(fn)) {
|
||||
return fn(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return toU8a(value);
|
||||
}
|
||||
|
||||
static getType (value: StorageKey | StorageFunction | [StorageFunction, any]): string | null {
|
||||
if (value instanceof StorageKey) {
|
||||
return value.outputType;
|
||||
} else if (isFunction(value)) {
|
||||
return value.meta.type.toString();
|
||||
} else if (Array.isArray(value)) {
|
||||
const [fn] = value;
|
||||
|
||||
return fn.meta.type.toString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
get outputType (): string | null {
|
||||
return this._outputType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import u8aFromUtf8 from '@polkadot/util/u8a/fromUtf8';
|
||||
import u8aToUtf8 from '@polkadot/util/u8a/toUtf8';
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
|
||||
import Base from './codec/Base';
|
||||
import Length from './codec/Length';
|
||||
|
||||
// This is a string wrapper, along with the length. It is used both for strings as well
|
||||
// as stuff like 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
|
||||
// wraps the `Balance`, `T::AccountId`, etc. The reasoning - with a "TypeString"
|
||||
// we can nicely strip types down like "T::AcountId" -> "AccountId"
|
||||
export default class Text extends Base<string> {
|
||||
protected _length: Length;
|
||||
|
||||
constructor (value: Text | string = '') {
|
||||
super(
|
||||
value instanceof Text
|
||||
? value.raw
|
||||
: value.trim()
|
||||
);
|
||||
|
||||
this._length = new Length(value.length);
|
||||
}
|
||||
|
||||
get length (): number {
|
||||
return this.raw.length;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
// NOTE String gets trimmed in the fromU8a, so get the original length from the length
|
||||
// placeholder and the associtated byteLength from that encoding
|
||||
return this._length.toNumber() +
|
||||
this._length.byteLength();
|
||||
}
|
||||
|
||||
fromJSON (input: any): Text {
|
||||
this.raw = `${input || ''}`;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Text {
|
||||
this._length.fromU8a(input);
|
||||
|
||||
const length = this._length.toNumber();
|
||||
const offset = this._length.byteLength();
|
||||
|
||||
this.raw = u8aToUtf8(input.subarray(offset, offset + length)).trim();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
// NOTE Since we trim in the fromU8a, here we re-calculate the actual length
|
||||
const encoded = u8aFromUtf8(this.raw);
|
||||
|
||||
this._length.setValue(encoded.length);
|
||||
|
||||
return u8aConcat(
|
||||
this._length.toU8a(isBare),
|
||||
encoded
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Text from './Text';
|
||||
import Type from './Type';
|
||||
|
||||
describe('Type', () => {
|
||||
it('fails to cleanup invalid boxes', () => {
|
||||
expect(
|
||||
() => new Type().fromJSON('Box<Proposal')
|
||||
).toThrow(/find closing matching/);
|
||||
});
|
||||
|
||||
it('handles nested types', () => {
|
||||
expect(
|
||||
new Type().fromJSON('Box<Vec<AccountId>>').toString()
|
||||
).toEqual('Vec<AccountId>');
|
||||
});
|
||||
|
||||
it('handles aliasses, multiples per line', () => {
|
||||
expect(
|
||||
new Type().fromJSON('(Vec<u8>, AccountId, Vec<u8>)').toString()
|
||||
).toEqual('(Bytes, AccountId, Bytes)');
|
||||
});
|
||||
|
||||
it('does not allow toU8a', () => {
|
||||
expect(
|
||||
() => new Type().toU8a()
|
||||
).toThrow(/unimplemented/);
|
||||
});
|
||||
|
||||
it('has a length for the type', () => {
|
||||
expect(
|
||||
new Type(
|
||||
new Text(' Box<Proposal> ')
|
||||
).length
|
||||
).toEqual('Proposal'.length); // eslint-disable-line
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Text from './Text';
|
||||
|
||||
type Mapper = (value: string) => string;
|
||||
|
||||
const ALLOWED_BOXES = ['Vec', 'Option'];
|
||||
|
||||
// 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.
|
||||
export default class Type extends Text {
|
||||
constructor (value?: Text | string) {
|
||||
super(value);
|
||||
|
||||
this._cleanupTypes();
|
||||
}
|
||||
|
||||
fromJSON (input: any): Type {
|
||||
super.fromJSON(input);
|
||||
|
||||
return this._cleanupTypes();
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Type {
|
||||
super.fromU8a(input);
|
||||
|
||||
return this._cleanupTypes();
|
||||
}
|
||||
|
||||
// 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 {
|
||||
throw new Error('Type::toU8a: unimplemented');
|
||||
}
|
||||
|
||||
// HACK(ery) Take the types and tweak them (slightly?) for consistency
|
||||
private _cleanupTypes (): Type {
|
||||
const mappings: Array<Mapper> = [
|
||||
// Remove all the trait prefixes
|
||||
this._removeTraits(),
|
||||
// remove boxing, `Box<Proposal>` -> `Proposal`
|
||||
this._removeWrap('Box'),
|
||||
// remove generics, `MisbehaviorReport<Hash, BlockNumber>` -> `MisbehaviorReport`
|
||||
this._removeGenerics(),
|
||||
// alias String -> Text (compat with jsonrpc methods)
|
||||
this._alias('String', 'Text'),
|
||||
// alias Vec<u8> -> Bytes
|
||||
this._alias('Vec<u8>', 'Bytes')
|
||||
// TODO Check these for possibly matching -
|
||||
// `RawAddress` -> `Address` (implementation looks the same)
|
||||
// `PropIndex` -> `ProposalIndex` (implementation looks the same, however meant as diff)
|
||||
];
|
||||
|
||||
this.raw = mappings.reduce((result, fn) => {
|
||||
return fn(result);
|
||||
}, this.raw);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// given a starting index, find the closing >
|
||||
private _findClosing (value: string, start: number): number {
|
||||
let depth = 0;
|
||||
|
||||
for (let index = start; index < value.length; index++) {
|
||||
if (value[index] === '>') {
|
||||
if (!depth) {
|
||||
return index;
|
||||
} else {
|
||||
depth--;
|
||||
}
|
||||
} else if (value[index] === '<') {
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`);
|
||||
}
|
||||
|
||||
private _alias (src: string, dest: string): Mapper {
|
||||
return (value: string): string => {
|
||||
return value.replace(
|
||||
new RegExp(src, 'g'), dest
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
private _removeGenerics (): Mapper {
|
||||
return (value: string): string => {
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
if (value[index] === '<') {
|
||||
// check against the allowed wrappers, be it Vec<..>, Option<...> ...
|
||||
const box = ALLOWED_BOXES.find((box) => {
|
||||
const start = index - box.length;
|
||||
|
||||
return start >= 0 && value.substr(start, box.length) === box;
|
||||
});
|
||||
|
||||
// we have not found anything, unwrap generic innards
|
||||
if (!box) {
|
||||
const end = this._findClosing(value, index + 1);
|
||||
|
||||
value = `${value.substr(0, index)}${value.substr(end + 1)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
// remove the type traits
|
||||
private _removeTraits (): Mapper {
|
||||
return (value: string): string => {
|
||||
return value
|
||||
// anything `T::<type>` to end up as `<type>`
|
||||
.replace(/T::/g, '')
|
||||
// `system::` with `` - basically we find `<T as system::Trait>`
|
||||
.replace(/system::/g, '')
|
||||
// replace `<T as Trait>::` (possibly sanitiused just above)
|
||||
.replace(/<T as Trait>::/g, '');
|
||||
};
|
||||
}
|
||||
|
||||
// remove wrapping values, i.e. Box<Proposal> -> Proposal
|
||||
private _removeWrap (_check: string): Mapper {
|
||||
const check = `${_check}<`;
|
||||
|
||||
return (value: string): string => {
|
||||
let index = 0;
|
||||
|
||||
while (index !== -1) {
|
||||
index = value.indexOf(check);
|
||||
|
||||
if (index !== -1) {
|
||||
const start = index + check.length;
|
||||
const end = this._findClosing(value, start);
|
||||
|
||||
value = `${value.substr(start, end - start)}`;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import UInt from './codec/UInt';
|
||||
|
||||
export default class U128 extends UInt {
|
||||
constructor (value?: AnyNumber) {
|
||||
super(value, 128);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import UInt from './codec/UInt';
|
||||
|
||||
export default class U16 extends UInt {
|
||||
constructor (value?: AnyNumber) {
|
||||
super(value, 16);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import UInt from './codec/UInt';
|
||||
|
||||
export default class U256 extends UInt {
|
||||
constructor (value?: AnyNumber) {
|
||||
super(value, 256);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import UInt from './codec/UInt';
|
||||
|
||||
export default class U32 extends UInt {
|
||||
constructor (value?: AnyNumber) {
|
||||
super(value, 32);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import UInt from './codec/UInt';
|
||||
|
||||
export default class U64 extends UInt {
|
||||
constructor (value?: AnyNumber) {
|
||||
super(value, 64);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import UInt from './codec/UInt';
|
||||
|
||||
export default class U8 extends UInt {
|
||||
constructor (value?: AnyNumber) {
|
||||
super(value, 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import ValidatorPrefs from './ValidatorPrefs';
|
||||
|
||||
describe('ValidatorPrefs', () => {
|
||||
it('starts with empty values', () => {
|
||||
expect(
|
||||
new ValidatorPrefs().validatorPayment.toNumber()
|
||||
).toEqual(0);
|
||||
});
|
||||
|
||||
it('exposes the internal values via get', () => {
|
||||
const prefs = new ValidatorPrefs({
|
||||
unstakeThreshold: 3,
|
||||
validatorPayment: 12345
|
||||
});
|
||||
|
||||
expect(prefs.unstakeThreshold.toNumber()).toEqual(3);
|
||||
expect(prefs.validatorPayment.toNumber()).toEqual(12345);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import Struct from './codec/Struct';
|
||||
import Balance from './Balance';
|
||||
import U32 from './U32';
|
||||
|
||||
type ValidatorPrefsValue = {
|
||||
unstakeThreshold?: AnyNumber,
|
||||
validatorPayment?: AnyNumber
|
||||
};
|
||||
|
||||
export default class ValidatorPrefs extends Struct {
|
||||
constructor (value?: ValidatorPrefsValue) {
|
||||
super({
|
||||
unstakeThreshold: U32,
|
||||
validatorPayment: Balance
|
||||
}, value);
|
||||
}
|
||||
|
||||
get unstakeThreshold (): U32 {
|
||||
return this.raw.unstakeThreshold as U32;
|
||||
}
|
||||
|
||||
get validatorPayment (): Balance {
|
||||
return this.raw.validatorPayment as Balance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U32 from './U32';
|
||||
|
||||
export default class VoteIndex extends U32 {
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import VoteThreshold from './VoteThreshold';
|
||||
|
||||
describe('VoteThreshold', () => {
|
||||
it('starts with default value', () => {
|
||||
expect(
|
||||
new VoteThreshold().toString()
|
||||
).toEqual('Super majority approval');
|
||||
});
|
||||
|
||||
it('allows setting value in constructor', () => {
|
||||
expect(
|
||||
new VoteThreshold(2).toNumber()
|
||||
).toEqual(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Enum from './codec/Enum';
|
||||
|
||||
// Voting threshold, used inside proposals to set change the voting tally
|
||||
export default class VoteThreshold extends Enum {
|
||||
constructor (index?: number) {
|
||||
super([
|
||||
'Super majority approval',
|
||||
'Super majority rejection',
|
||||
'Simple majority'
|
||||
], index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Base from './Base';
|
||||
|
||||
describe('Base', () => {
|
||||
it('has the contructor value on raw', () => {
|
||||
expect(new Base('foo-bar').raw).toEqual('foo-bar');
|
||||
});
|
||||
|
||||
['byteLength', 'fromJSON', 'fromU8a', 'toJSON', 'toString', 'toU8a'].forEach((method) => {
|
||||
it(`has abstract (?) impl for ${method}`, () => {
|
||||
expect(
|
||||
() => new Base()[method]()
|
||||
).toThrow(/unimplemented/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import logger from '@polkadot/util/logger';
|
||||
|
||||
export const l = logger('codec');
|
||||
|
||||
// The actual base class for any type. As it stands, this should not be used on it's own,
|
||||
// so we expose the interface, but throw on anything. This allows subclasses to actaully
|
||||
// only implement part (things that are unused/unexpected should just error-out)
|
||||
//
|
||||
// TODO
|
||||
// - This could probably be abstract, as long as we have the functions abstract as well
|
||||
// - Not convinced about abstratc - there are a number of extensions to this class that
|
||||
// don't provide some implementations (e.g. Length, good example and should not be
|
||||
// used-as-is). In those case it just relies in the throw in here.
|
||||
export default class Base <T = any> {
|
||||
raw: T;
|
||||
|
||||
constructor (value?: any) {
|
||||
this.raw = value;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
throw new Error('Base::byteLength: unimplemented');
|
||||
}
|
||||
|
||||
fromJSON (input: any): Base <T> {
|
||||
throw new Error('Base::fromJSON: unimplemented');
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Base <T> {
|
||||
throw new Error('Base::fromU8a: unimplemented');
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
throw new Error('Base::toJSON: unimplemented');
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
throw new Error('Base::toString: unimplemented');
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
throw new Error('Base::toU8a: unimplemented');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import BN from 'bn.js';
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
import u8aToBn from '@polkadot/util/u8a/toBn';
|
||||
|
||||
const MAX_U8 = new BN(2).pow(new BN(8 - 2)).subn(1);
|
||||
const MAX_U16 = new BN(2).pow(new BN(16 - 2)).subn(1);
|
||||
const MAX_U32 = new BN(2).pow(new BN(32 - 2)).subn(1);
|
||||
|
||||
type BitLength = 32;
|
||||
|
||||
// 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.
|
||||
export default class Compact {
|
||||
static decode (input: Uint8Array, bitLength: BitLength): BN {
|
||||
const flag = input[0] & 0b11;
|
||||
|
||||
if (flag === 0b00) {
|
||||
return new BN(input[0]).shrn(2);
|
||||
} else if (flag === 0b01) {
|
||||
return u8aToBn(input.slice(0, 2), true).shrn(2);
|
||||
} else if (flag === 0b10) {
|
||||
return u8aToBn(input.slice(0, 4), true).shrn(2);
|
||||
}
|
||||
|
||||
const byteLength = bitLength / 8;
|
||||
|
||||
return u8aToBn(input.subarray(1, 1 + byteLength), true);
|
||||
}
|
||||
|
||||
static encode (length: BN, bitLength: BitLength): Uint8Array {
|
||||
if (length.lte(MAX_U8)) {
|
||||
return new Uint8Array([length.toNumber() << 2]);
|
||||
} else if (length.lte(MAX_U16)) {
|
||||
return bnToU8a(length.shln(2).addn(0b01), 16, true);
|
||||
} else if (length.lte(MAX_U32)) {
|
||||
return bnToU8a(length.shln(2).addn(0b10), 32, true);
|
||||
}
|
||||
|
||||
return u8aConcat(
|
||||
new Uint8Array([
|
||||
0b11
|
||||
]),
|
||||
bnToU8a(length, bitLength, true)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Enum from './Enum';
|
||||
|
||||
describe('Struct', () => {
|
||||
it('provides a clean toString()', () => {
|
||||
expect(
|
||||
new Enum(['foo', 'bar']).toString()
|
||||
).toEqual('foo');
|
||||
});
|
||||
|
||||
it('provides a clean toString() (enum)', () => {
|
||||
expect(
|
||||
new Enum(['foo', 'bar'], new Enum([], 1)).toNumber()
|
||||
).toEqual(1);
|
||||
});
|
||||
|
||||
it('converts to and from U8a', () => {
|
||||
expect(
|
||||
new Enum(['foo', 'bar']).fromU8a(new Uint8Array([1])).toU8a()
|
||||
).toEqual(new Uint8Array([1]));
|
||||
});
|
||||
|
||||
it('converts from JSON', () => {
|
||||
expect(
|
||||
new Enum(['foo', 'bar']).fromJSON(5).toString()
|
||||
).toEqual('5');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Base from './Base';
|
||||
|
||||
type EnumDef = {
|
||||
[index: number]: 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
|
||||
// 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<number> {
|
||||
private _enum: EnumDef;
|
||||
|
||||
constructor (def: EnumDef, value: Enum | number = 0) {
|
||||
super(
|
||||
value instanceof Enum
|
||||
? value.raw
|
||||
: value
|
||||
);
|
||||
|
||||
this._enum = def;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return 1;
|
||||
}
|
||||
|
||||
fromJSON (input: any): Enum {
|
||||
// FIXME We potentially want to assert that the value is actually inside this._enum
|
||||
this.raw = input;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Enum {
|
||||
// FIXME We potentially want to assert that the value is actually inside this._enum
|
||||
this.raw = input[0];
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return new Uint8Array([this.raw]);
|
||||
}
|
||||
|
||||
toNumber (): number {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this._enum[this.raw] || `${this.raw}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import EnumType from './EnumType';
|
||||
import Text from '../Text';
|
||||
import U32 from '../U32';
|
||||
|
||||
describe('Struct', () => {
|
||||
it('provides a clean toString() (raw)', () => {
|
||||
expect(
|
||||
new EnumType(
|
||||
[Text, U32]
|
||||
).fromU8a(new Uint8Array([0, 2 << 2, 49, 50])).raw.toString()
|
||||
).toEqual('12');
|
||||
});
|
||||
|
||||
it('provides a clean toString() (enum)', () => {
|
||||
expect(
|
||||
new EnumType(
|
||||
[Text, U32]
|
||||
).fromU8a(new Uint8Array([1, 2 << 2, 49, 50])).toString()
|
||||
).toEqual('U32');
|
||||
});
|
||||
|
||||
it('allows checking against defined indexes', () => {
|
||||
expect(
|
||||
new EnumType(
|
||||
{ 1: Text, 5: U32 }
|
||||
).fromU8a(new Uint8Array([1, 2 << 2, 49, 50])).toString()
|
||||
).toEqual('Text');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Base from './Base';
|
||||
|
||||
type TypesArray = Array<{ new(value?: any): Base }>;
|
||||
type TypesDef = {
|
||||
[index: number]: { new(value?: any): Base }
|
||||
} | 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.
|
||||
//
|
||||
// TODO:
|
||||
// - As per Enum, actually use TS enum
|
||||
// - It should rather probably extend Enum instead of copying code
|
||||
// - There doesn't actually seem to be a way to get to the actual determined/wrapped value
|
||||
export default class EnumType <T> extends Base<Base<T>> {
|
||||
private _Types: TypesArray;
|
||||
private _index: number;
|
||||
private _indexes: Array<number>;
|
||||
|
||||
constructor (def: TypesDef, index?: number | EnumType<T>, value?: any) {
|
||||
super(
|
||||
new (Object.values(def)[0])()
|
||||
);
|
||||
|
||||
this._Types = Array.isArray(def)
|
||||
? def
|
||||
: Object.values(def);
|
||||
this._indexes = Object.keys(def).map((index) =>
|
||||
parseInt(index, 10)
|
||||
);
|
||||
this._index = this._indexes[0];
|
||||
|
||||
this.setValue(index, value);
|
||||
}
|
||||
|
||||
get Type (): string {
|
||||
return this._Types[this._index].name;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return 1 + this.raw.byteLength();
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): EnumType<T> {
|
||||
this.setValue(input[0]);
|
||||
this.raw.fromU8a(input.subarray(1));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
setValue (index?: | EnumType<T> | number, value?: any): void {
|
||||
if (index instanceof EnumType) {
|
||||
this._index = index._index;
|
||||
this.raw = new this._Types[this._index](index.raw);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this._index = this._indexes.indexOf(index || 0);
|
||||
|
||||
if (this._index === -1) {
|
||||
this._index = this._indexes[0];
|
||||
}
|
||||
|
||||
this.raw = new this._Types[this._index](value);
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toNumber (): number {
|
||||
return this._index;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this._Types[this._index].name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Length from './Length';
|
||||
import UInt from './UInt';
|
||||
|
||||
describe('Length', () => {
|
||||
it('encodes short u8', () => {
|
||||
expect(
|
||||
new Length(18).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([18 << 2])
|
||||
);
|
||||
});
|
||||
|
||||
it('encodes max u8 values', () => {
|
||||
expect(
|
||||
new Length(new UInt(63)).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([0b11111100])
|
||||
);
|
||||
});
|
||||
|
||||
it('encodes basic u16 value', () => {
|
||||
expect(
|
||||
new Length(511).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([0b11111101, 0b00000111])
|
||||
);
|
||||
});
|
||||
|
||||
it('encodes basic ua6 (not at edge)', () => {
|
||||
expect(
|
||||
new Length(111).toHex()
|
||||
).toEqual('0xbd01');
|
||||
});
|
||||
|
||||
it('decodes from same u16 encoded value', () => {
|
||||
expect(
|
||||
new Length()
|
||||
.fromU8a(new Uint8Array([0b11111101, 0b00000111]))
|
||||
.toNumber()
|
||||
).toEqual(511);
|
||||
});
|
||||
|
||||
it('encodes basic u32 values (short)', () => {
|
||||
expect(
|
||||
new Length(0xffff).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([254, 255, 3, 0])
|
||||
);
|
||||
});
|
||||
|
||||
it('decodes from same u32 encoded value (short)', () => {
|
||||
expect(
|
||||
new Length()
|
||||
.fromU8a(new Uint8Array([254, 255, 3, 0]))
|
||||
.toNumber()
|
||||
).toEqual(0xffff);
|
||||
});
|
||||
|
||||
it('encodes basic u32 values (full)', () => {
|
||||
expect(
|
||||
new Length(0xfffffff9).toU8a()
|
||||
).toEqual(
|
||||
new Uint8Array([3, 249, 255, 255, 255])
|
||||
);
|
||||
});
|
||||
|
||||
it('decodes from same u32 encoded value (full)', () => {
|
||||
expect(
|
||||
new Length()
|
||||
.fromU8a(new Uint8Array([3, 249, 255, 255, 255]))
|
||||
.toNumber()
|
||||
).toEqual(0xfffffff9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import bnToBn from '@polkadot/util/bn/toBn';
|
||||
import u8aToHex from '@polkadot/util/u8a/toHex';
|
||||
|
||||
import Base from './Base';
|
||||
import Compact from './Compact';
|
||||
import UInt from './UInt';
|
||||
|
||||
type BitLength = 32;
|
||||
|
||||
// A Length-prefix that can be added to any variable length stream of bytes, e.g. String,
|
||||
// Vectors and Bytes
|
||||
//
|
||||
// FIXME Not crazy about the use of Length. If we look at Vector, Bytes & String,
|
||||
// the implementations are basically the same. Vector is slightly different since
|
||||
// it iterates over the length. We need a cleaner way where we have less copied
|
||||
// code and a more generic implementation around the use of Length. Looking at
|
||||
// Array or Struct, the same type of wrapper would be useful here.
|
||||
export default class Length extends Base<BN> {
|
||||
private _bitLength: BitLength;
|
||||
|
||||
constructor (value: AnyNumber = new BN(0), bitLength: BitLength = 32) {
|
||||
super(
|
||||
UInt.decode(value)
|
||||
);
|
||||
|
||||
this._bitLength = bitLength;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return this.toU8a().length;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Length {
|
||||
this.raw = Compact.decode(input, this._bitLength);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toHex (): string {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
toNumber (): number {
|
||||
return this.raw.toNumber();
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return isBare
|
||||
? new Uint8Array()
|
||||
: Compact.encode(this.raw, this._bitLength);
|
||||
}
|
||||
|
||||
setValue (value: BN | number): void {
|
||||
this.raw = bnToBn(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Option from './Option';
|
||||
import Text from '../Text';
|
||||
|
||||
describe('Option', () => {
|
||||
it('converts fromJSON() with', () => {
|
||||
const o = new Option(Text).fromJSON('1234');
|
||||
|
||||
expect(o.isEmpty).toEqual(false);
|
||||
expect(o.toString()).toEqual('1234');
|
||||
});
|
||||
|
||||
it('converts fromJSON() without', () => {
|
||||
const o = new Option(Text, '1234').fromJSON();
|
||||
|
||||
expect(o.isEmpty).toEqual(true);
|
||||
expect(o.toString()).toEqual('');
|
||||
});
|
||||
|
||||
it('has empty toString() (undefined)', () => {
|
||||
expect(
|
||||
new Option(Text).toString()
|
||||
).toEqual('');
|
||||
});
|
||||
|
||||
it('has value toString() (provided)', () => {
|
||||
expect(
|
||||
new Option(Text).fromU8a(new Uint8Array([1, 4 << 2, 49, 50, 51, 52])).toString()
|
||||
).toEqual('1234');
|
||||
});
|
||||
|
||||
it('converts toU8a() with', () => {
|
||||
expect(
|
||||
new Option(Text, '1234').toU8a()
|
||||
).toEqual(new Uint8Array([1, 4 << 2, 49, 50, 51, 52]));
|
||||
});
|
||||
|
||||
it('converts toU8a() without', () => {
|
||||
expect(
|
||||
new Option(Text).toU8a()
|
||||
).toEqual(new Uint8Array([0]));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import isUndefined from '@polkadot/util/is/undefined';
|
||||
|
||||
import Base from './Base';
|
||||
|
||||
// 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 Base<Base<T>> {
|
||||
private _isEmpty: boolean;
|
||||
|
||||
constructor (Value: { new(value?: any): Base<T> }, value?: any) {
|
||||
super(
|
||||
new Value(value)
|
||||
);
|
||||
|
||||
this._isEmpty = isUndefined(value);
|
||||
}
|
||||
|
||||
static with <O> (Type: { new(value?: any): Base<O> }): { new(value?: any): Option<O> } {
|
||||
return class extends Option<O> {
|
||||
constructor (value?: any) {
|
||||
super(Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
get isEmpty (): boolean {
|
||||
return this._isEmpty;
|
||||
}
|
||||
|
||||
get value (): T | undefined {
|
||||
return this._isEmpty
|
||||
? undefined
|
||||
: this.raw.raw;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
const childLength = this._isEmpty
|
||||
? 0
|
||||
: this.raw.byteLength();
|
||||
|
||||
return 1 + childLength;
|
||||
}
|
||||
|
||||
fromJSON (input: any): Option<T> {
|
||||
this._isEmpty = isUndefined(input);
|
||||
|
||||
if (!this._isEmpty) {
|
||||
this.raw.fromJSON(input);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Option<T> {
|
||||
this._isEmpty = input[0] === 0;
|
||||
|
||||
if (!this._isEmpty) {
|
||||
this.raw.fromU8a(input.subarray(1));
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this._isEmpty
|
||||
? undefined
|
||||
: this.raw.toJSON();
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
if (isBare) {
|
||||
return this.raw.toU8a(true);
|
||||
}
|
||||
|
||||
const u8a = new Uint8Array(this.byteLength());
|
||||
|
||||
if (!this._isEmpty) {
|
||||
u8a.set([1]);
|
||||
u8a.set(this.raw.toU8a(), 1);
|
||||
}
|
||||
|
||||
return u8a;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this._isEmpty
|
||||
? ''
|
||||
: this.raw.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Struct from './Struct';
|
||||
import Text from '../Text';
|
||||
import U32 from '../U32';
|
||||
|
||||
describe('Struct', () => {
|
||||
it('provides a clean toString()', () => {
|
||||
expect(
|
||||
new (
|
||||
Struct.with({
|
||||
txt: Text,
|
||||
u32: U32
|
||||
})
|
||||
)({ txt: 'foo', u32: 0x123456 }).toString()
|
||||
).toEqual(`{txt: foo, u32: 1193046}`);
|
||||
});
|
||||
|
||||
it('exposes the types', () => {
|
||||
expect(
|
||||
new Struct({
|
||||
foo: Text,
|
||||
bar: Text,
|
||||
baz: U32
|
||||
}).Type
|
||||
).toEqual({
|
||||
foo: 'Text',
|
||||
bar: 'Text',
|
||||
baz: 'U32'
|
||||
});
|
||||
});
|
||||
|
||||
it('exposes the keys/values', () => {
|
||||
const test = new Struct({
|
||||
foo: Text,
|
||||
bar: U32
|
||||
}, { foo: 'bazzing', bar: 69 });
|
||||
|
||||
expect(test.keys()).toEqual(['foo', 'bar']);
|
||||
expect(
|
||||
test.values().map((v) =>
|
||||
v.toString()
|
||||
)
|
||||
).toEqual(['bazzing', '69']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import hexToU8a from '@polkadot/util/hex/toU8a';
|
||||
import isHex from '@polkadot/util/is/hex';
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
|
||||
import Base from './Base';
|
||||
|
||||
// A Struct defines an Object with key/values - where the values are Base<T> values. It removes
|
||||
// a lot of repetition from the actual coding, define a structure type, pass it the key/Base<T>
|
||||
// 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 = { [index: string]: { new(value?: any): Base } },
|
||||
// internal type, instance of classes mapped by key
|
||||
T = { [K in keyof S]: Base },
|
||||
// input values, mapped by key can be anything (construction)
|
||||
V = { [K in keyof S]: any },
|
||||
// type names, mapped by key, name of Class in S
|
||||
E = { [K in keyof S]: string }
|
||||
> extends Base<T> {
|
||||
protected _jsonMap: Map<keyof S, string>;
|
||||
protected _Types: E;
|
||||
|
||||
constructor (Types: S, value: V | Array<any> = {} as V, jsonMap: Map<keyof S, string> = new Map(), isTuple: boolean = false) {
|
||||
super(
|
||||
Struct.decode(Types, value, isTuple)
|
||||
);
|
||||
|
||||
this._jsonMap = jsonMap;
|
||||
this._Types = Object
|
||||
.keys(Types)
|
||||
.reduce((result: E, key) => {
|
||||
// @ts-ignore Same as above, can't do a simple one, I'm missing something simple
|
||||
result[key] = Types[key].name;
|
||||
|
||||
return result;
|
||||
}, {} as E);
|
||||
}
|
||||
|
||||
static decode <S, V, T> (Types: S, value: V | Array<any>, isTuple: boolean): T {
|
||||
// l.debug(() => ['Struct.decode', { Types, value }]);
|
||||
|
||||
return Object
|
||||
.keys(Types)
|
||||
.reduce((raw: T, key, index) => {
|
||||
// @ts-ignore FIXME Ok, something weird is going on here or I just don't get it...
|
||||
// it works, so ignore the checker, although it drives me batty. (It started when
|
||||
// the [key in keyof T] was added, the idea is to provide better checks, which
|
||||
// does backfire here, but works externally.)
|
||||
raw[key] = new Types[key](
|
||||
isTuple && Array.isArray(value)
|
||||
? value[index]
|
||||
// @ts-ignore as above
|
||||
: value[key]
|
||||
);
|
||||
|
||||
return raw;
|
||||
}, {} as T);
|
||||
}
|
||||
|
||||
static with <
|
||||
S = { [index: string]: { new(value?: any): Base } }
|
||||
> (Types: S): { new(value?: any): Struct<S> } {
|
||||
return class extends Struct<S> {
|
||||
constructor (value?: any, jsonMap?: Map<keyof S, string>) {
|
||||
super(Types, value, jsonMap);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
get Type (): E {
|
||||
return this._Types;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return Object.values(this.raw).reduce((length, entry) => {
|
||||
return length += entry.byteLength();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
fromJSON (input: any): Struct<S, T, V, E> {
|
||||
if (isHex(input)) {
|
||||
return this.fromU8a(hexToU8a(input));
|
||||
}
|
||||
|
||||
Object.keys(this.raw).forEach((key) => {
|
||||
const jsonKey = this._jsonMap.get(key as any) || key;
|
||||
|
||||
// @ts-ignore as above...
|
||||
this.raw[key].fromJSON(input[jsonKey]);
|
||||
});
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Struct<S, T, V, E> {
|
||||
Object.values(this.raw).reduce((offset, entry) => {
|
||||
entry.fromU8a(input.subarray(offset));
|
||||
|
||||
return offset + entry.byteLength();
|
||||
}, 0);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
get (index: number): Base {
|
||||
return this.values()[index];
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return Object.keys(this.raw).reduce((json, key) => {
|
||||
const jsonKey = this._jsonMap.get(key as any) || key;
|
||||
|
||||
// @ts-ignore as above...
|
||||
json[jsonKey] = this.raw[key].toJSON();
|
||||
|
||||
return json;
|
||||
}, {} as any);
|
||||
}
|
||||
|
||||
keys (): Array<string> {
|
||||
return Object.keys(this.raw);
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return u8aConcat(
|
||||
...Object.values(this.raw).map((entry) =>
|
||||
entry.toU8a(isBare)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
const data = Object.keys(this.raw).map((key) =>
|
||||
// @ts-ignore as above...
|
||||
`${key}: ${this.raw[key].toString()}`
|
||||
).join(', ');
|
||||
|
||||
return `{${data}}`;
|
||||
}
|
||||
|
||||
values (): Array<Base> {
|
||||
return Object.values(this.raw);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Text from '../Text';
|
||||
import U32 from '../U32';
|
||||
import Tuple from './Tuple';
|
||||
|
||||
describe('Tuple', () => {
|
||||
let tuple;
|
||||
|
||||
beforeEach(() => {
|
||||
tuple = new Tuple({
|
||||
foo: Text,
|
||||
bar: U32
|
||||
}, { foo: 'foo', bar: 69 });
|
||||
});
|
||||
|
||||
it('returns array with toJSON', () => {
|
||||
expect(
|
||||
tuple.toJSON()
|
||||
).toEqual([
|
||||
'foo',
|
||||
'0x00000045'
|
||||
]);
|
||||
});
|
||||
|
||||
it('initialises via JSON array', () => {
|
||||
const test = new (Tuple.with({
|
||||
a: Text,
|
||||
b: U32,
|
||||
c: Text
|
||||
}))();
|
||||
|
||||
expect(
|
||||
test.fromJSON([
|
||||
'bazzing', 32
|
||||
]).toJSON()
|
||||
).toEqual([
|
||||
'bazzing',
|
||||
'0x00000020',
|
||||
''
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import hexToU8a from '@polkadot/util/hex/toU8a';
|
||||
import isHex from '@polkadot/util/is/hex';
|
||||
|
||||
import Base from './Base';
|
||||
import Struct from './Struct';
|
||||
|
||||
// A Tuple defines an anonymous Object with key/values - where the values are Base<T> values.It
|
||||
// is a specialization of the Struct type where the toJSON/fromJSON 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 = { [index: string]: { new(value?: any): Base } },
|
||||
T = { [K in keyof S]: Base },
|
||||
V = { [K in keyof S]: any }
|
||||
> extends Struct<S, T, V> {
|
||||
constructor (Types: S, value?: V | Array<any>, jsonMap?: Map<keyof S, string>) {
|
||||
super(Types, value, jsonMap, true);
|
||||
}
|
||||
|
||||
static with <
|
||||
S = { [index: string]: { new(value?: any): Base } }
|
||||
> (Types: S): { new(value?: any): Tuple<S> } {
|
||||
return class extends Tuple<S> {
|
||||
constructor (value?: any) {
|
||||
super(Types, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fromJSON (input: any): Tuple<S, T, V> {
|
||||
if (isHex(input)) {
|
||||
return this.fromU8a(hexToU8a(input));
|
||||
}
|
||||
|
||||
Object.values(this.raw).forEach((entry, index) => {
|
||||
entry.fromJSON(input[index]);
|
||||
});
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return Object.values(this.raw).map((entry) =>
|
||||
entry.toJSON()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U8a from './U8a';
|
||||
|
||||
describe('U8a', () => {
|
||||
let u8a;
|
||||
|
||||
beforeEach(() => {
|
||||
u8a = new U8a([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('contains the length of the elements', () => {
|
||||
expect(u8a.length).toEqual(5); // eslint-disable-line
|
||||
});
|
||||
|
||||
it('allows wrapping of a pre-existing instance', () => {
|
||||
expect(
|
||||
new U8a(u8a).length
|
||||
).toEqual(5); // eslint-disable-line
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from '../types';
|
||||
|
||||
import u8aToHex from '@polkadot/util/u8a/toHex';
|
||||
import toU8a from '@polkadot/util/u8a/toU8a';
|
||||
|
||||
import Base from './Base';
|
||||
|
||||
// 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 fromU8a. As such it is meant to be
|
||||
// subclassed where the wrapper takes care of the actual lengths.
|
||||
export default class U8a extends Base<Uint8Array> {
|
||||
constructor (value: AnyU8a = new Uint8Array()) {
|
||||
super(
|
||||
value instanceof U8a
|
||||
? value.raw
|
||||
: toU8a(value)
|
||||
);
|
||||
}
|
||||
|
||||
get length (): number {
|
||||
return this.byteLength();
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return this.raw.length;
|
||||
}
|
||||
|
||||
fromJSON (input: any): U8a {
|
||||
this.raw = toU8a(input);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): U8a {
|
||||
this.raw = input;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toHex (): string {
|
||||
return u8aToHex(this.raw);
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.toHex();
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this.toHex();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import U8aFixed from './U8aFixed';
|
||||
|
||||
describe('U8aFixed', () => {
|
||||
let u8a;
|
||||
|
||||
beforeEach(() => {
|
||||
u8a = new U8aFixed([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 32);
|
||||
});
|
||||
|
||||
it('limits the length', () => {
|
||||
expect(u8a.length).toEqual(4); // eslint-disable-line
|
||||
});
|
||||
|
||||
it('allows wrapping of a pre-existing instance', () => {
|
||||
expect(
|
||||
u8a.toU8a()
|
||||
).toEqual(new Uint8Array([1, 2, 3, 4]));
|
||||
});
|
||||
|
||||
it('allows empty values', () => {
|
||||
expect(
|
||||
new U8aFixed().toHex()
|
||||
).toEqual('0x');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyU8a } from '../types';
|
||||
|
||||
import U8a from './U8a';
|
||||
|
||||
type BitLength = 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.
|
||||
export default class U8aFixed extends U8a {
|
||||
protected _bitLength: number;
|
||||
|
||||
constructor (value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) {
|
||||
super(value);
|
||||
|
||||
this._bitLength = bitLength;
|
||||
|
||||
this._trimLength();
|
||||
}
|
||||
|
||||
private _trimLength (): void {
|
||||
this.raw = this.raw.subarray(0, this.byteLength());
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return this._bitLength / 8;
|
||||
}
|
||||
|
||||
fromJSON (input: any): U8aFixed {
|
||||
super.fromJSON(input);
|
||||
|
||||
this._trimLength();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): U8aFixed {
|
||||
super.fromU8a(input.subarray(0, this.byteLength()));
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import UInt from './UInt';
|
||||
|
||||
describe('UInt', () => {
|
||||
it('provides a toBn interface', () => {
|
||||
expect(
|
||||
new UInt(987).toBn().toNumber()
|
||||
).toEqual(987);
|
||||
});
|
||||
|
||||
it('provides a toNumber interface', () => {
|
||||
expect(
|
||||
new UInt(4567).toNumber()
|
||||
).toEqual(4567);
|
||||
});
|
||||
|
||||
it('converts to LE from the provided value', () => {
|
||||
expect(
|
||||
new UInt(1234567).toU8a()
|
||||
).toEqual(new Uint8Array([135, 214, 18, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('converts to LE from the provided value (bitLength)', () => {
|
||||
expect(
|
||||
new UInt(1234567, 32).toU8a()
|
||||
).toEqual(new Uint8Array([135, 214, 18, 0]));
|
||||
});
|
||||
|
||||
it('converts to hex/string', () => {
|
||||
const u = new UInt('0x12', 16);
|
||||
|
||||
expect(u.toHex()).toEqual('0x0012');
|
||||
expect(u.toString()).toEqual('18');
|
||||
});
|
||||
|
||||
it('converts to equivalents', () => {
|
||||
const a = new UInt('123');
|
||||
|
||||
expect(
|
||||
new UInt(a).toNumber()
|
||||
).toEqual(123);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import isHex from '@polkadot/util/is/hex';
|
||||
import isString from '@polkadot/util/is/string';
|
||||
import isU8a from '@polkadot/util/is/u8a';
|
||||
import bnToBn from '@polkadot/util/bn/toBn';
|
||||
import bnToHex from '@polkadot/util/bn/toHex';
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
import hexToBn from '@polkadot/util/hex/toBn';
|
||||
import u8aToBn from '@polkadot/util/u8a/toBn';
|
||||
|
||||
import Base from './Base';
|
||||
|
||||
type BitLength = 8 | 16 | 32 | 64 | 128 | 256;
|
||||
|
||||
// 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?
|
||||
export default class UInt extends Base<BN> {
|
||||
private _bitLength: BitLength;
|
||||
|
||||
constructor (value: AnyNumber = 0, bitLength: BitLength = 64) {
|
||||
super(
|
||||
UInt.decode(value)
|
||||
);
|
||||
|
||||
this._bitLength = bitLength;
|
||||
}
|
||||
|
||||
static decode (value: AnyNumber): BN {
|
||||
if (value instanceof UInt) {
|
||||
return value.raw;
|
||||
} else if (isHex(value)) {
|
||||
return hexToBn(value as string);
|
||||
} else if (isU8a(value)) {
|
||||
// NOTE When passing u8a in (typically from decoded data), it is always u8a
|
||||
return u8aToBn(value, true);
|
||||
} else if (isString(value)) {
|
||||
return new BN(value, 10);
|
||||
}
|
||||
|
||||
return bnToBn(value);
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return this._bitLength / 8;
|
||||
}
|
||||
|
||||
fromJSON (input: any): UInt {
|
||||
this.raw = UInt.decode(input);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): UInt {
|
||||
this.raw = u8aToBn(input.subarray(0, this.byteLength()), true);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toHex (): string {
|
||||
return bnToHex(this.raw, this._bitLength);
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.toHex();
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return bnToU8a(this.raw, this._bitLength, true);
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this.raw.toString();
|
||||
}
|
||||
|
||||
toBn (): BN {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toNumber (): number {
|
||||
return this.raw.toNumber();
|
||||
}
|
||||
|
||||
// helpers from BN, this would be great as a "don't do this", i.e. extending properly
|
||||
// from BN. Underlying these will always return BN (unless it is compare checks)
|
||||
add (other: UInt | BN | number): BN {
|
||||
return other instanceof UInt
|
||||
? this.raw.add(other.raw)
|
||||
: this.raw.add(bnToBn(other));
|
||||
}
|
||||
|
||||
cmp (other: UInt | BN | number): number {
|
||||
return other instanceof UInt
|
||||
? this.raw.cmp(other.raw)
|
||||
: this.raw.cmp(bnToBn(other));
|
||||
}
|
||||
|
||||
div (other: UInt | BN | number): BN {
|
||||
return other instanceof UInt
|
||||
? this.raw.div(other.raw)
|
||||
: this.raw.div(bnToBn(other));
|
||||
}
|
||||
|
||||
isZero (): boolean {
|
||||
return this.raw.isZero();
|
||||
}
|
||||
|
||||
lt (test: UInt | BN | number): boolean {
|
||||
return test instanceof UInt
|
||||
? this.raw.lt(test.raw)
|
||||
: this.raw.lt(bnToBn(test));
|
||||
}
|
||||
|
||||
lte (test: UInt | BN | number): boolean {
|
||||
return test instanceof UInt
|
||||
? this.raw.lte(test.raw)
|
||||
: this.raw.lte(bnToBn(test));
|
||||
}
|
||||
|
||||
gt (test: UInt | BN | number): boolean {
|
||||
return test instanceof UInt
|
||||
? this.raw.gt(test.raw)
|
||||
: this.raw.gt(bnToBn(test));
|
||||
}
|
||||
|
||||
gte (test: UInt | BN | number): boolean {
|
||||
return test instanceof UInt
|
||||
? this.raw.gte(test.raw)
|
||||
: this.raw.gte(bnToBn(test));
|
||||
}
|
||||
|
||||
mul (other: UInt | BN | number): BN {
|
||||
return other instanceof UInt
|
||||
? this.raw.mul(other.raw)
|
||||
: this.raw.mul(bnToBn(other));
|
||||
}
|
||||
|
||||
sub (other: UInt | BN | number): BN {
|
||||
return other instanceof UInt
|
||||
? this.raw.sub(other.raw)
|
||||
: this.raw.sub(bnToBn(other));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Text from '../Text';
|
||||
import Vector from './Vector';
|
||||
|
||||
describe('Vector', () => {
|
||||
let array;
|
||||
|
||||
beforeEach(() => {
|
||||
array = new Vector(Text, [ '1', '23', '345', '4567', new Text('56789') ]);
|
||||
});
|
||||
|
||||
it('wraps a sequence of values', () => {
|
||||
expect(array.length).toEqual(5); // eslint-disable-line
|
||||
});
|
||||
|
||||
it('has a sane representation for toString', () => {
|
||||
expect(array.toString()).toEqual('[1, 23, 345, 4567, 56789]');
|
||||
});
|
||||
|
||||
it('encodes with length prefix', () => {
|
||||
expect(array.toU8a()).toEqual(new Uint8Array([
|
||||
5 << 2,
|
||||
1 << 2, 49,
|
||||
2 << 2, 50, 51,
|
||||
3 << 2, 51, 52, 53,
|
||||
4 << 2, 52, 53, 54, 55,
|
||||
5 << 2, 53, 54, 55, 56, 57
|
||||
]));
|
||||
});
|
||||
|
||||
it('allows contruction via JSON', () => {
|
||||
expect(
|
||||
new Vector(Text).fromJSON(['6', '7']).toString()
|
||||
).toEqual('[6, 7]');
|
||||
});
|
||||
|
||||
it('exposes the type', () => {
|
||||
expect(array.Type).toEqual('Text');
|
||||
});
|
||||
|
||||
describe('array-like functions', () => {
|
||||
it('allows retrieval of a specific item', () => {
|
||||
expect(
|
||||
array.get(2).toString()
|
||||
).toEqual('345');
|
||||
});
|
||||
|
||||
it('exposes a working forEach', () => {
|
||||
const result = {};
|
||||
|
||||
array.forEach((e, i) => {
|
||||
result[i] = e.toString();
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
0: '1',
|
||||
1: '23',
|
||||
2: '345',
|
||||
3: '4567',
|
||||
4: '56789'
|
||||
});
|
||||
});
|
||||
|
||||
it('exposes a working filter', () => {
|
||||
expect(
|
||||
array.filter((e, i) => i >= 3).toString()
|
||||
).toEqual('4567,56789');
|
||||
});
|
||||
|
||||
it('exposes a working map', () => {
|
||||
expect(
|
||||
array.map((e) => e.toString().substr(0, 1))
|
||||
).toEqual(['1', '2', '3', '4', '5']);
|
||||
});
|
||||
|
||||
it('exposes a working reduce', () => {
|
||||
expect(
|
||||
array.reduce((r, e) => `${r}${e}`, '')
|
||||
).toEqual('123345456756789');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
|
||||
import Base from './Base';
|
||||
import Length from './Length';
|
||||
|
||||
// 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.
|
||||
export default class Vector <
|
||||
T extends Base
|
||||
> extends Base<Array<T>> {
|
||||
private _length: Length;
|
||||
private _Type: { new(value?: any): T };
|
||||
|
||||
constructor (Type: { new(value?: any): T }, value: Array<any> = [] as Array<any>) {
|
||||
super(
|
||||
value.map((entry) =>
|
||||
entry instanceof Type
|
||||
? entry
|
||||
: new Type(entry)
|
||||
)
|
||||
);
|
||||
|
||||
this._length = new Length(value.length);
|
||||
this._Type = Type;
|
||||
}
|
||||
|
||||
static with <O extends Base> (Type: { new(value?: any): O }): { new(value?: any): Vector<O> } {
|
||||
return class extends Vector<O> {
|
||||
constructor (value?: Array<any>) {
|
||||
super(Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
get Type (): string {
|
||||
return this._Type.name;
|
||||
}
|
||||
|
||||
get length (): number {
|
||||
return this.raw.length;
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
return this.raw.reduce((total, raw) => {
|
||||
return total + raw.byteLength();
|
||||
}, this._length.byteLength());
|
||||
}
|
||||
|
||||
filter (fn: (item: T, index?: number) => any): Array<T> {
|
||||
return this.raw.filter(fn);
|
||||
}
|
||||
|
||||
find (fn: (item: T, index?: number) => any): T | undefined {
|
||||
return this.raw.find(fn);
|
||||
}
|
||||
|
||||
forEach (fn: (item: T, index?: number) => any): any {
|
||||
return this.raw.forEach(fn);
|
||||
}
|
||||
|
||||
fromJSON (input: any): Vector<T> {
|
||||
this.raw = input.map((input: any) =>
|
||||
new this._Type().fromJSON(input)
|
||||
);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
fromU8a (input: Uint8Array): Vector<T> {
|
||||
this._length.fromU8a(input);
|
||||
|
||||
const length = this._length.toNumber();
|
||||
let offset = this._length.byteLength();
|
||||
this.raw = [];
|
||||
|
||||
for (let index = 0; index < length; index++) {
|
||||
const raw = new this._Type().fromU8a(input.subarray(offset));
|
||||
|
||||
this.raw.push(raw as T);
|
||||
offset += raw.byteLength();
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
get (index: number): T {
|
||||
return this.raw[index];
|
||||
}
|
||||
|
||||
map <O> (fn: (item: T, index?: number) => O): Array<O> {
|
||||
return this.raw.map(fn);
|
||||
}
|
||||
|
||||
push (item: T): void {
|
||||
this.raw.push(item);
|
||||
this._length.setValue(this.raw.length);
|
||||
}
|
||||
|
||||
reduce <O> (fn: (result: O, item: T, index?: number) => O, initial: O): O {
|
||||
return this.raw.reduce(fn, initial);
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.raw.map((entry) =>
|
||||
entry.toJSON()
|
||||
);
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return u8aConcat(
|
||||
this._length.toU8a(isBare),
|
||||
...this.raw.map((entry) =>
|
||||
entry.toU8a(isBare)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
const data = this.raw.map((entry) =>
|
||||
entry.toString()
|
||||
);
|
||||
|
||||
return `[${data.join(', ')}]`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { typeSplit, getType, getTupleType, getVectorType } from './createType';
|
||||
|
||||
describe('typeSplit', () => {
|
||||
it('splits simple types into an array', () => {
|
||||
expect(
|
||||
typeSplit('Text, u32, u64')
|
||||
).toEqual(['Text', 'u32', 'u64']);
|
||||
});
|
||||
|
||||
it('splits nested combinations', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32), Vec<u64>')
|
||||
).toEqual(['Text', '(u32)', 'Vec<u64>']);
|
||||
});
|
||||
|
||||
it('keeps nested tuples together', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32, u128), Vec<u64>')
|
||||
).toEqual(['Text', '(u32, u128)', 'Vec<u64>']);
|
||||
});
|
||||
|
||||
it('keeps nested vector tuples together', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32, u128), Vec<(u64, u32)>')
|
||||
).toEqual(['Text', '(u32, u128)', 'Vec<(u64, u32)>']);
|
||||
});
|
||||
|
||||
it('allows for deep nesting', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32, (u128, u8)), Vec<(u64, (u32, u32))>')
|
||||
).toEqual(['Text', '(u32, (u128, u8))', 'Vec<(u64, (u32, u32))>']);
|
||||
});
|
||||
|
||||
it('checks for unclosed vec', () => {
|
||||
expect(
|
||||
() => typeSplit('Text, Vec<u64')
|
||||
).toThrow(/Invalid Vector/);
|
||||
});
|
||||
|
||||
it('checks for unclosed tuple', () => {
|
||||
expect(
|
||||
() => typeSplit('Text, (u64, u32')
|
||||
).toThrow(/Invalid Tuple/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTupleType', () => {
|
||||
it('does not allow invalid tuples, end )', () => {
|
||||
expect(
|
||||
() => getTupleType('(u64, u32')
|
||||
).toThrow(/tuple wrapped/);
|
||||
});
|
||||
|
||||
it('does not allow invalid tuples, start (', () => {
|
||||
expect(
|
||||
() => getTupleType('u64, u32)')
|
||||
).toThrow(/tuple wrapped/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getVectorType', () => {
|
||||
it('does not allow invalid vectors, end >', () => {
|
||||
expect(
|
||||
() => getVectorType('Vec<u64')
|
||||
).toThrow(/Vec wrapped/);
|
||||
});
|
||||
|
||||
it('does not allow invalid vectors, start Vec<', () => {
|
||||
expect(
|
||||
() => getVectorType('u64>')
|
||||
).toThrow(/Vec wrapped/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getType', () => {
|
||||
it('does not allow invalid types', () => {
|
||||
expect(
|
||||
() => getType('SomethingInvalid')
|
||||
).toThrow(/determine type/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import assert from '@polkadot/util/assert';
|
||||
|
||||
import * as Types from '../index';
|
||||
import Base from './Base';
|
||||
import Tuple from './Tuple';
|
||||
import Vector from './Vector';
|
||||
|
||||
type Constructor = { new (value?: any): Base };
|
||||
|
||||
// safely split a string on ', ' while taking care of any nested occurences
|
||||
export function typeSplit (type: string): Array<string> {
|
||||
let tDepth = 0;
|
||||
let vDepth = 0;
|
||||
let start = 0;
|
||||
const result = [];
|
||||
|
||||
for (let index = 0; index < type.length; index++) {
|
||||
switch (type[index]) {
|
||||
case ',':
|
||||
// we are not nested, add the type
|
||||
if (tDepth === 0 && vDepth === 0) {
|
||||
result.push(type.substr(start, index - start).trim());
|
||||
start = index + 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case '(':
|
||||
// inc tuple depth
|
||||
tDepth++;
|
||||
break;
|
||||
|
||||
case ')':
|
||||
// dec tuple depth
|
||||
tDepth--;
|
||||
break;
|
||||
|
||||
case '<':
|
||||
// inc vec depth
|
||||
vDepth++;
|
||||
break;
|
||||
|
||||
case '>':
|
||||
// dec tuple depth
|
||||
vDepth--;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert(tDepth === 0, `Invalid Tuple in ${type}`);
|
||||
assert(vDepth === 0, `Invalid Vector in ${type}`);
|
||||
|
||||
// the final leg of the journey
|
||||
result.push(type.substr(start, type.length - start).trim());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle Vector types, i.e Vec<AccountId> or Vec<(AccountId, Balance)>
|
||||
export function getVectorType (type: string): Constructor {
|
||||
// l.debug(() => ['getVectorType', { type }]);
|
||||
|
||||
assert(type.substr(0, 4) === 'Vec<' && type[type.length - 1] === '>', `Expected Vec wrapped with <>`);
|
||||
|
||||
// strip wrapping Vec<>
|
||||
const subType = type.substr(4, type.length - 5);
|
||||
|
||||
return Vector.with(
|
||||
getType(subType)
|
||||
);
|
||||
}
|
||||
|
||||
// Handle tuple types, (u32, String, AccountId). It could be nested and wrapped in other
|
||||
// types, i.e. (u32, Vec<(AccountId, Balance)>)
|
||||
export function getTupleType (type: string): Constructor {
|
||||
// l.debug(() => ['getTupleType', { type }]);
|
||||
|
||||
assert(type[0] === '(' && type[type.length - 1] === ')', `Expected tuple wrapped with ()`);
|
||||
|
||||
// strip wrapping ()'s
|
||||
const innerTypes = typeSplit(type.substr(1, type.length - 2));
|
||||
|
||||
return Tuple.with(
|
||||
innerTypes.reduce((result, type, index) => {
|
||||
result[`entry${index}`] = getType(type);
|
||||
|
||||
return result;
|
||||
}, {} as { [index: string]: Constructor })
|
||||
);
|
||||
}
|
||||
|
||||
// Returns the type Class for construction
|
||||
export function getType (_type: string): Constructor {
|
||||
const type = _type.trim();
|
||||
|
||||
// l.debug(() => ['getType', { type }]);
|
||||
|
||||
if (type[0] === '(') {
|
||||
return getTupleType(type);
|
||||
} else if (type.substr(0, 4) === 'Vec<') {
|
||||
return getVectorType(type);
|
||||
}
|
||||
|
||||
const Type = (Types as any)[type];
|
||||
|
||||
assert(Type, `Unable to determine type from '${type}'`);
|
||||
|
||||
return Type;
|
||||
}
|
||||
|
||||
export default function createType (type: string, value?: any): Base {
|
||||
// l.debug(() => ['createType', { type, value }]);
|
||||
|
||||
const Type = getType(type);
|
||||
|
||||
return new Type(value);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
// NOTE We are not exporting everything here. These _should_ be enough to use the
|
||||
// actual interfaces from a "create-a-working-coder" perspective. If not, we should
|
||||
// expand with slight care (for instance, Length is really only used internally to
|
||||
// others, so there _should_ not be need for direct use)
|
||||
|
||||
// These are the base codec types, generally used for construction
|
||||
export { default as Base } from './Base';
|
||||
export { default as Struct } from './Struct';
|
||||
export { default as Tuple } from './Tuple';
|
||||
export { default as Vector } from './Vector';
|
||||
|
||||
// Convenience base classes, used as "anything of this type" bases
|
||||
export { default as U8a } from './U8a';
|
||||
export { default as UInt } from './UInt';
|
||||
|
||||
// Type management helper functions
|
||||
export { default as createType } from './createType';
|
||||
@@ -0,0 +1,65 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
// NOTE We are not re-exporting the index.ts from codec here. The reasoning being
|
||||
// that these should be enough to actually _use_ the codec, i.e. from a api-user
|
||||
// perspective these are the value classes. (Codec is for the cases where you need
|
||||
// to construct values dynamically)
|
||||
|
||||
export { default as AccountId } from './AccountId';
|
||||
export { default as AccountIndex } from './AccountIndex';
|
||||
export { default as Address } from './Address';
|
||||
export { default as AuthorityId } from './AuthorityId';
|
||||
export { default as Balance } from './Balance';
|
||||
// NOTE Bft items are only used in internal structures
|
||||
// export * from './Bft;
|
||||
export { default as Block } from './Block';
|
||||
export { default as BlockNumber } from './BlockNumber';
|
||||
export { default as Bool } from './Bool';
|
||||
export { default as Bytes } from './Bytes';
|
||||
export { default as Extrinsic } from './Extrinsic';
|
||||
// NOTE Only used internally, exported as PendingExtrinsics
|
||||
// export { default as Extrinsics } from './Extrinsics';
|
||||
export { default as Gas } from './Gas';
|
||||
// NOTE These are currently only used internally, no direct mapping to Rust strings
|
||||
// export { default as H256 } from './H256';
|
||||
// export { default as H512 } from './H512';
|
||||
export { default as Hash } from './Hash';
|
||||
export { default as Header } from './Header';
|
||||
export { default as KeyValue } from './KeyValue';
|
||||
export { default as Metadata } from './Metadata';
|
||||
export { default as MisbehaviorReport } from './MisbehaviorReport';
|
||||
export { default as Moment } from './Moment';
|
||||
export { default as NewAccountOutcome } from './NewAccountOutcome';
|
||||
// NOTE Nonce is renamed to Index
|
||||
export { default as Index } from './Nonce';
|
||||
export { default as Origin } from './Origin';
|
||||
export { default as ParachainId } from './ParachainId';
|
||||
export { default as PendingExtrinsics } from './PendingExtrinsics';
|
||||
export { default as Permill } from './Permill';
|
||||
export { default as Perbill } from './Perbill';
|
||||
export { default as PropIndex } from './PropIndex';
|
||||
export { default as Proposal } from './Proposal';
|
||||
export { default as ProposalIndex } from './ProposalIndex';
|
||||
export { default as RawAddress } from './RawAddress';
|
||||
export { default as ReferendumIndex } from './ReferendumIndex';
|
||||
export { default as RuntimeVersion } from './RuntimeVersion';
|
||||
export { default as Signature } from './Signature';
|
||||
export { default as SignedBlock } from './SignedBlock';
|
||||
export { default as StorageChangeSet } from './StorageChangeSet';
|
||||
export { default as StorageData } from './StorageData';
|
||||
export { default as StorageKey } from './StorageKey';
|
||||
export { default as Text } from './Text';
|
||||
// NOTE Type is currently only used internally (possibly in codec-related work)
|
||||
// export { default as Type } from './Type';
|
||||
// NOTE We are exporting the U* classes as lowercase, matching with Rust
|
||||
export { default as u8 } from './U8';
|
||||
export { default as u16 } from './U16';
|
||||
export { default as u32 } from './U32';
|
||||
export { default as u64 } from './U64';
|
||||
export { default as u128 } from './U128';
|
||||
export { default as u256 } from './U256';
|
||||
export { default as ValidatorPrefs } from './ValidatorPrefs';
|
||||
export { default as VoteThreshold } from './VoteThreshold';
|
||||
export { default as VoteIndex } from './VoteIndex';
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2018 @polkadot/types authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import BN from 'bn.js';
|
||||
import * as Classes from './index';
|
||||
|
||||
import { U8a, UInt } from './codec';
|
||||
|
||||
export type AnyNumber = UInt | BN | Uint8Array | number | string;
|
||||
|
||||
export type AnyU8a = U8a | Uint8Array | Array<number> | string;
|
||||
|
||||
export type CodecTypes = keyof typeof Classes;
|
||||
Reference in New Issue
Block a user