Rewrite type-extrinsics (#173)

* Cleanup jsonrpc, refer to api-codec

* Remove misplaced debug log

* Add metadat array (hack around json import)

* Move json metadata to ts

* Rewrite type-extrinsics

* Make tests pass in type-params

* Skip failing tests in type-primitives

* Use legacy type for legacy stuff

* Remove useless comments

* Remove type params (finally)

* Remove type-primitives (!)

* Remove legacy stuff

* Remove useless import

* Remove useless file

* Update header

* Remove useless files

* Fix test

* Typo

* Export default

* Fix test

* Add index counting

* Fix test index counting

* toNumber() on id

* Fix bug u8a
This commit is contained in:
Amaury Martiny
2018-10-01 10:43:05 +02:00
committed by Jaco Greeff
parent 3d552d96fd
commit 8840f33d20
169 changed files with 140 additions and 4982 deletions
-2
View File
@@ -11,8 +11,6 @@
"license": "ISC",
"dependencies": {
"@babel/runtime": "^7.0.0",
"@polkadot/params": "^0.30.3",
"@polkadot/primitives": "^0.30.3",
"@polkadot/util": "^0.30.7"
}
}
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { UncheckedRaw } from '@polkadot/primitives/extrinsic';
import u8aToBn from '@polkadot/util/u8a/toBn';
export default function decodeLength (unchecked: Uint8Array): UncheckedRaw {
const length = u8aToBn(unchecked.subarray(0, 4), true).toNumber();
return unchecked.slice(4, length + 4);
}
@@ -1,52 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import testingPairs from '@polkadot/util-keyring/testingPairs';
import call from './call';
const keyring = testingPairs();
describe('call', () => {
it('encodes the call correctly (poc-1)', () => {
expect(
call(
keyring.one.publicKey(),
1234,
new Uint8Array([0xab, 0xcd]),
'poc-1'
)
).toEqual(
new Uint8Array([
// key
47, 140, 97, 41, 216, 22, 207, 81, 195, 116, 188, 127, 8, 195, 230, 62, 209, 86, 207, 120, 174, 251, 74, 101, 80, 217, 123, 135, 153, 121, 119, 238,
// nonce (u64)
210, 4, 0, 0, 0, 0, 0, 0,
// data
171, 205
])
);
});
it('encodes the call correctly (latest)', () => {
expect(
call(
keyring.one.publicKey(),
1234,
new Uint8Array([0xab, 0xcd]),
'latest'
)
).toEqual(
new Uint8Array([
// key
47, 140, 97, 41, 216, 22, 207, 81, 195, 116, 188, 127, 8, 195, 230, 62, 209, 86, 207, 120, 174, 251, 74, 101, 80, 217, 123, 135, 153, 121, 119, 238,
// nonce (u32)
210, 4, 0, 0,
// data
171, 205
])
);
});
});
@@ -1,20 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics 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 { EncodingVersions } from '@polkadot/params/types';
import { ExtrinsicWithAccount, ExtrinsicWithIndex } from '../types';
import sizes from '@polkadot/params/sizes';
import defaultSizes from '@polkadot/primitives/sizes';
import bnToU8a from '@polkadot/util/bn/toU8a';
import u8aConcat from '@polkadot/util/u8a/concat';
export default function encodeCall (publicKey: Uint8Array, nonce: number | BN, data: ExtrinsicWithIndex, version: EncodingVersions): ExtrinsicWithAccount {
return u8aConcat(
publicKey,
bnToU8a(nonce, sizes.AccountIndex.get(version) || defaultSizes.AccountIndex, true),
data
);
}
@@ -1,27 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import extrinsics from '../../index';
import extrinsic from './extrinsic';
describe('extrinsic', () => {
it('encodes extrinsic correctly', () => {
expect(
extrinsic(
extrinsics.timestamp.public.set,
[10101],
'latest'
)
).toEqual(
new Uint8Array([
// index
3, 0,
// values
117, 39, 0, 0, 0, 0, 0, 0
])
);
});
});
@@ -1,17 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, SectionItem } from '@polkadot/params/types';
import { Extrinsics } from '../../types';
import { ExtrinsicWithIndex } from '../types';
import encodeParams from '@polkadot/params/encode';
import u8aConcat from '@polkadot/util/u8a/concat';
export default function encodeExtrinsic (extrinsic: SectionItem<Extrinsics>, values: Array<any>, version: EncodingVersions): ExtrinsicWithIndex {
return u8aConcat(
extrinsic.index,
encodeParams(extrinsic.params, values, version)
);
}
@@ -1,35 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import testingPairs from '@polkadot/util-keyring/testingPairs';
import extrinsics from '../../index';
import encode from './index';
const keyring = testingPairs();
describe('encode', () => {
it('encodes extrinsic correctly', () => {
expect(
encode(
keyring.nobody.publicKey(), 1234,
extrinsics.timestamp.public.set,
[10101],
'latest'
)
).toEqual(
new Uint8Array([
// publicKey
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,
// account nonce
210, 4, 0, 0,
// extrinsic index
3, 0,
// values
117, 39, 0, 0, 0, 0, 0, 0
])
);
});
});
@@ -1,20 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics 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 { EncodingVersions, SectionItem } from '@polkadot/params/types';
import { Extrinsics } from '../../types';
import { ExtrinsicWithAccount } from '../types';
import encodeCall from './call';
import encodeExtrinsic from './extrinsic';
export default function encode (publicKey: Uint8Array, index: number | BN, extrinsic: SectionItem<Extrinsics>, values: Array<any>, version: EncodingVersions): ExtrinsicWithAccount {
return encodeCall(
publicKey,
index,
encodeExtrinsic(extrinsic, values, version),
version
);
}
@@ -1,17 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import bnToU8a from '@polkadot/util/bn/toU8a';
import u8aConcat from '@polkadot/util/u8a/concat';
export default function encodeLength (...values: Array<Uint8Array>): Uint8Array {
const length = values.reduce((length, u8a) => {
return length + u8a.length;
}, 0);
return u8aConcat(
bnToU8a(length, 32, true),
...values
);
}
@@ -1,25 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// https://github.com/paritytech/polkadot/pull/195
// 0xff, 32-byte account id
// 0xfe, 8-byte account index
// 0xfd, 4-byte account index
// 0xfc, 2-byte account index
// [0xf0...0xfb] (invalid, reserved for future use)
// [0x00...0xef] 1-byte account index (less than 0xf0)
const bytes8 = new Uint8Array([0xfe]);
const bytes4 = new Uint8Array([0xfd]);
const bytes2 = new Uint8Array([0xfc]);
const none = new Uint8Array([]);
const publicKey = new Uint8Array([0xff]);
export default {
bytes8,
bytes4,
bytes2,
none,
publicKey
};
@@ -1,121 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import extrinsics from '../../index';
import hexToU8a from '@polkadot/util/hex/toU8a';
import testingPairs from '@polkadot/util-keyring/testingPairs';
import encode from './unchecked';
const keyring = testingPairs();
describe('unchecked', () => {
it('encodes extrinsic correctly (nobody)', () => {
expect(
encode(
keyring.nobody, 1234,
extrinsics.timestamp.public.set,
[10101]
)
).toEqual(
new Uint8Array([
255,
// publicKey
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,
// account nonce
210, 4, 0, 0,
// extrinsic index
3, 0,
// values
117, 39, 0, 0, 0, 0, 0, 0,
// signature
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
])
);
});
it('encodes extrinsic correctly (one)', () => {
expect(
encode(
keyring.one, 258,
extrinsics.staking.public.transfer,
[keyring.two.publicKey(), 69],
'poc-1'
)
).toEqual(
new Uint8Array([
// publicKey
47, 140, 97, 41, 216, 22, 207, 81, 195, 116, 188, 127, 8, 195, 230, 62, 209, 86, 207, 120, 174, 251, 74, 101, 80, 217, 123, 135, 153, 121, 119, 238,
// account nonce
2, 1, 0, 0, 0, 0, 0, 0,
// extrinsic index
2, 0,
// values
// (recipient)
215, 90, 152, 1, 130, 177, 10, 183, 213, 75, 254, 211, 201, 100, 7, 58, 14, 225, 114, 243, 218, 166, 35, 37, 175, 2, 26, 104, 247, 7, 81, 26,
// (amount)
69, 0, 0, 0, 0, 0, 0, 0,
// signature
144, 233, 93, 195, 106, 86, 2, 230, 182, 5, 62, 128, 120, 148, 21, 128, 86, 5, 74, 15, 128, 100, 255, 179, 172, 13, 102, 206, 117, 208, 175, 107, 107, 77, 209, 126, 129, 51, 1, 198, 184, 202, 100, 240, 0, 118, 150, 188, 67, 10, 154, 84, 224, 103, 17, 151, 163, 45, 78, 249, 219, 169, 96, 2
])
);
});
it('encodes extrinsic correctly (one + latest)', () => {
expect(
encode(
keyring.one, 258,
extrinsics.staking.public.transfer,
[keyring.two.publicKey(), 69]
)
).toEqual(
new Uint8Array([
255,
// publicKey
47, 140, 97, 41, 216, 22, 207, 81, 195, 116, 188, 127, 8, 195, 230, 62, 209, 86, 207, 120, 174, 251, 74, 101, 80, 217, 123, 135, 153, 121, 119, 238,
// account nonce
2, 1, 0, 0,
// extrinsic index
2, 0,
// values
// (recipient)
255,
215, 90, 152, 1, 130, 177, 10, 183, 213, 75, 254, 211, 201, 100, 7, 58, 14, 225, 114, 243, 218, 166, 35, 37, 175, 2, 26, 104, 247, 7, 81, 26,
// (amount)
69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// signature
56, 1, 89, 195, 60, 171, 128, 242, 136, 64, 45, 43, 252, 199, 13, 115, 2, 76, 9, 19, 16, 80, 38, 164, 58, 229, 107, 225, 141, 107, 115, 176, 241, 242, 153, 177, 48, 92, 6, 61, 104, 112, 45, 223, 86, 198, 203, 78, 240, 223, 59, 190, 156, 116, 135, 188, 244, 219, 182, 58, 39, 140, 159, 11
])
);
});
it('encodes timetamp.set extrinsic correctly (actual values)', () => {
expect(
encode(
keyring.nobody, 0,
extrinsics.timestamp.public.set,
[0x5b13c37b]
)
).toEqual(
hexToU8a(
'0xff00000000000000000000000000000000000000000000000000000000000000000000000003007bc3135b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
)
);
});
it('encoded parachains.setHeads correctly (actual values)', () => {
expect(
encode(
keyring.nobody, 0,
extrinsics.parachains.public.setHeads,
[[]]
)
).toEqual(
hexToU8a(
'0xff00000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
)
);
});
});
@@ -1,27 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics 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 { EncodingVersions, SectionItem } from '@polkadot/params/types';
import { UncheckedRaw } from '@polkadot/primitives/extrinsic';
import { KeyringPair } from '@polkadot/util-keyring/types';
import { Extrinsics } from '../../types';
import u8aConcat from '@polkadot/util/u8a/concat';
import encode from './index';
import prefixes from './prefixes';
export default function unchecked (pair: KeyringPair, index: number | BN, extrinsic: SectionItem<Extrinsics>, values: Array<any>, version: EncodingVersions = 'latest'): UncheckedRaw {
const message = encode(pair.publicKey(), index, extrinsic, values, version);
const signature = pair.sign(message);
return u8aConcat(
version === 'poc-1'
? prefixes.none
: prefixes.publicKey,
message,
signature
);
}
@@ -1,24 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics 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 { EncodingVersions, SectionItem } from '@polkadot/params/types';
import { UncheckedRaw } from '@polkadot/primitives/extrinsic';
import { KeyringPair } from '@polkadot/util-keyring/types';
import { Extrinsics } from '../../types';
import encodeUnchecked from './unchecked';
import encodeLength from './length';
export default function uncheckedLength (pair: KeyringPair, index: number | BN, extrinsic: SectionItem<Extrinsics>, values: Array<any>, version: EncodingVersions = 'latest'): UncheckedRaw {
return encodeLength(
encodeUnchecked(
pair,
index,
extrinsic,
values,
version
)
);
}
-9
View File
@@ -1,9 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
export type ExtrinsicWithAccount = Uint8Array;
export type ExtrinsicWithIndex = Uint8Array;
export type ExtrinsicUnchecked = Uint8Array;
-48
View File
@@ -1,48 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const reportMisbehavior: CreateItemOptions = {
description: 'Report misbehavior',
params: [
param('report', 'MisbehaviorReport')
],
type: []
};
const setCode: CreateItemOptions = {
description: 'Set new code',
params: [
param('code', 'Code')
],
type: []
};
const setStorage: CreateItemOptions = {
description: 'Set storage entries',
params: [
param('entries', ['StorageKeyValue'])
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Consensus',
public: {
reportMisbehavior:
createMethod('reportMisbehavior', 0)(reportMisbehavior)
},
private: {
setCode:
createMethod('setCode', 0)(setCode),
setStorage:
createMethod('setStorage', 1)(setStorage)
}
}));
-114
View File
@@ -1,114 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const setApprovals: CreateItemOptions = {
description: 'Set approvals',
params: [
param('votes', ['bool']),
param('index', 'u32')
],
type: []
};
const reapInactiveVoter: CreateItemOptions = {
description: 'Remove insactive voter',
params: [
param('signedIndex', 'u32'),
param('who', 'AccountId'),
param('whoIndex', 'u32'),
param('assumedVoteIndex', 'u32')
],
type: []
};
const retractVoter: CreateItemOptions = {
description: 'Retract voter',
params: [
param('index', 'u32')
],
type: []
};
const submitCandidacy: CreateItemOptions = {
description: 'Submit candidacy',
params: [
param('slot', 'u32')
],
type: []
};
const presentWinner: CreateItemOptions = {
description: 'Present winner',
params: [
param('candidate', 'AccountId'),
param('total', 'Balance'),
param('index', 'u32')
],
type: []
};
const setDesiredSeats: CreateItemOptions = {
description: 'Set desired seats',
params: [
param('count', 'u32')
],
type: []
};
const removeMember: CreateItemOptions = {
description: 'Remove member',
params: [
param('member', 'AccountId')
],
type: []
};
const setPresentationDuration: CreateItemOptions = {
description: 'Set presentation duration',
params: [
param('duration', 'u64')
],
type: []
};
const setTermDuration: CreateItemOptions = {
description: 'Set term duration',
params: [
param('duration', 'u64')
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Council',
public: {
setApprovals:
createMethod('setApprovals', 0)(setApprovals),
reapInactiveVoter:
createMethod('reapInactiveVoter', 1)(reapInactiveVoter),
retractVoter:
createMethod('retractVoter', 2)(retractVoter),
submitCandidacy:
createMethod('submitCandidacy', 3)(submitCandidacy),
presentWinner:
createMethod('presentWinner', 4)(presentWinner)
},
private: {
setDesiredSeats:
createMethod('setDesiredSeats', 0)(setDesiredSeats),
removeMember:
createMethod('removeMember', 1)(removeMember),
setPresentationDuration:
createMethod('setPresentationDuration', 2)(setPresentationDuration),
setTermDuration:
createMethod('setTermDuration', 3)(setTermDuration)
}
}));
@@ -1,69 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const propose: CreateItemOptions = {
description: 'Propose',
params: [
param('proposal', 'Proposal')
],
type: []
};
const vote: CreateItemOptions = {
description: 'Vote',
params: [
param('proposal', 'Hash'),
param('approve', 'bool')
],
type: []
};
const veto: CreateItemOptions = {
description: 'Veto',
params: [
param('proposal', 'Hash')
],
type: []
};
const setCooloffPeriod: CreateItemOptions = {
description: 'Set cooloff period',
params: [
param('blocks', 'BlockNumber')
],
type: []
};
const setVotingPeriod: CreateItemOptions = {
description: 'Set voting period',
params: [
param('blocks', 'BlockNumber')
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Council Voting',
public: {
propose:
createMethod('propose', 0)(propose),
vote:
createMethod('vote', 1)(vote),
veto:
createMethod('veto', 2)(veto)
},
private: {
setCooloffPeriod:
createMethod('setCooloffPeriod', 0)(setCooloffPeriod),
setVotingPeriod:
createMethod('setVotingPeriod', 1)(setVotingPeriod)
}
}));
-71
View File
@@ -1,71 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const propose: CreateItemOptions = {
description: 'Propose',
params: [
param('proposal', 'Proposal'),
param('value', 'Balance')
],
type: []
};
const second: CreateItemOptions = {
description: 'Second',
params: [
param('proposal', 'PropIndex')
],
type: []
};
const vote: CreateItemOptions = {
description: 'Vote',
params: [
param('referendumIndex', 'ReferendumIndex'),
param('vote', 'bool')
],
type: []
};
const startReferendum: CreateItemOptions = {
description: 'Start referendum',
params: [
param('proposal', 'Proposal'),
param('voteThreshold', 'VoteThreshold')
],
type: []
};
const cancelReferendum: CreateItemOptions = {
description: 'Cancel referendum',
params: [
param('referendumIndex', 'ReferendumIndex')
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Democracy',
public: {
propose:
createMethod('propose', 0)(propose),
second:
createMethod('second', 1)(second),
vote:
createMethod('vote', 2)(vote)
},
private: {
startReferendum:
createMethod('startReferendum', 0)(startReferendum),
cancelReferendum:
createMethod('cancelReferendum', 1)(cancelReferendum)
}
}));
@@ -0,0 +1,33 @@
// Copyright 2017-2018 @polkadot/extrinsics 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 '@polkadot/api-codec/Metadata';
import json from '@polkadot/api-codec/Metadata.rpc';
import fromMetadata from './fromMetadata';
// Use the pre-generated metadata
const metadata = new Metadata().fromJSON(json);
const newExtrinsics = fromMetadata({}, metadata);
describe('fromMetadata', () => {
it('should throw if an incorrect number of args is supplied', () => {
expect(() => newExtrinsics.balances.setBalance()).toThrowError(/expects 3 arguments/);
});
it('should return a value if the storage function does not expect an argument', () => {
expect(() => newExtrinsics.balances.setBalance('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s', 2, 3)).not.toThrow();
});
it('should return the correct storage key', () => {
expect(newExtrinsics.timestamp.set([10101]).toU8a(true)).toEqual(
new Uint8Array([
// index
3, 0,
// values
117, 39, 0, 0, 0, 0, 0, 0
])
);
});
});
@@ -0,0 +1,43 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import camelCase from '@polkadot/util/string/camelCase';
import Metadata, { RuntimeModuleMetadata } from '@polkadot/api-codec/Metadata';
import createExtrinsic from './utils/createExtrinsic';
import { Extrinsics, ModuleExtrinsics } from './types';
/**
* Extend a storage object with the storage modules & module functions present
* in the metadata.
*
* @param extrinsics - An extrinsics object to be extended.
* @param metadata - The metadata to extend the storage object against.
*/
export default function fromMetadata (extrinsics: Extrinsics, metadata: Metadata) {
// Dont' clobber the input, create new
const result = Object.keys(extrinsics).reduce((result, key) => {
result[key] = extrinsics[key];
return result;
}, {} as Extrinsics);
return metadata.modules.reduce((result, moduleMetadata: RuntimeModuleMetadata, index) => {
if (!moduleMetadata.module.call) {
return result;
}
const prefix = moduleMetadata.prefix.toString();
result[moduleMetadata.prefix.toString()] = moduleMetadata.module.call.functions
.reduce((newModule, func) => {
// extrinsics.balances.set_balance -> extrinsics.balances.setBalance
newModule[camelCase(func.name.toString())] = createExtrinsic(prefix, func.name, index as number, func);
return newModule;
}, {} as ModuleExtrinsics);
return result;
}, result);
}
+2 -22
View File
@@ -2,28 +2,8 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Extrinsics } from '@polkadot/extrinsics/types';
import { Extrinsics } from './types';
import consensus from './consensus';
import council from './council';
import councilVoting from './councilVoting';
import democracy from './democracy';
import session from './session';
import parachains from './parachains';
import staking from './staking';
import timestamp from './timestamp';
import treasury from './treasury';
const extrinsics: Extrinsics = {
consensus: consensus('consensus', 0),
session: session('session', 1),
staking: staking('staking', 2),
timestamp: timestamp('timestamp', 3),
treasury: treasury('treasury', 4),
democracy: democracy('democracy', 5),
council: council('council', 6),
councilVoting: councilVoting('councilVoting', 7),
parachains: parachains('parachains', 8)
};
const extrinsics: Extrinsics = {};
export default extrinsics;
@@ -1,51 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const deregisterParachain: CreateItemOptions = {
description: 'Deregister a parachain',
params: [
param('id', 'ParachainId')
],
type: []
};
const registerParachain: CreateItemOptions = {
description: 'Register a parachain',
params: [
param('id', 'ParachainId'),
param('code', 'Code'),
param('headData', 'Bytes')
],
type: []
};
const setHeads: CreateItemOptions = {
description: 'Sets parachain heads',
isHidden: true, // inherent
params: [
param('heads', ['CandidateReceipt'])
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Parchains',
public: {
setHeads:
createMethod('setHeads', 0)(setHeads)
},
private: {
deregisterParachain:
createMethod('deregisterParachain', 1)(deregisterParachain),
registerParachain:
createMethod('registerParachain', 0)(registerParachain)
}
}));
-56
View File
@@ -1,56 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const forceNewSession: CreateItemOptions = {
description: 'Force new session',
params: [],
type: []
};
const noteOffline: CreateItemOptions = {
description: 'Indicate offline validators',
params: [
param('indexes', ['u32'])
],
type: []
};
const setKey: CreateItemOptions = {
description: 'Set session key',
params: [
param('key', 'SessionKey')
],
type: []
};
const setLength: CreateItemOptions = {
description: 'Set session length',
params: [
param('length', 'u64')
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Session',
public: {
setKey:
createMethod('setKey', 0)(setKey),
noteOffline:
createMethod('noteOffline', 1)(noteOffline)
},
private: {
setLength:
createMethod('setLength', 0)(setLength),
forceNewSession:
createMethod('forceNewSession', 1)(forceNewSession)
}
}));
-149
View File
@@ -1,149 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const nominate: CreateItemOptions = {
description: 'Nominate',
params: [
param('target', 'AccountId')
],
type: []
};
const unnominate: CreateItemOptions = {
description: 'Unnominate',
params: [
param('targetIndex', 'u32')
],
type: []
};
const transfer: CreateItemOptions = {
description: 'Transfer',
params: [
param('recipient', 'AccountId'),
param('value', 'Balance')
],
type: []
};
const stake: CreateItemOptions = {
description: 'Stake',
params: [],
type: []
};
const unstake: CreateItemOptions = {
description: 'Unstake',
params: [
param('position', 'u32')
],
type: []
};
const registerSlashPreference: CreateItemOptions = {
description: 'Preference for slashing',
params: [
param('intentionIndex', 'u32'),
// FIXME This is actually a 'SlashPreference' struct (for now only a single value)
param('unstakeThreshold', 'u32')
],
type: []
};
const noteMissedProposal: CreateItemOptions = {
description: 'Indicate that a proposal has been missed',
params: [
param('offlineValIndices', ['u32'])
],
type: []
};
const setSessionsPerEra: CreateItemOptions = {
description: 'Set sessions per era',
params: [
param('sessions', 'BlockNumber')
],
type: []
};
const setBondingDuration: CreateItemOptions = {
description: 'Set bonding duration',
params: [
param('duration', 'BlockNumber')
],
type: []
};
const setValidatorCount: CreateItemOptions = {
description: 'Set validator count',
params: [
param('count', 'u32')
],
type: []
};
const forceNewEra: CreateItemOptions = {
description: 'Force new era',
params: [],
type: []
};
const setOfflineSlashGrace: CreateItemOptions = {
description: 'Sets the offline grace period before slashing',
params: [
param('value', 'u32')
],
type: []
};
const setBalance: CreateItemOptions = {
description: 'Sets the balance for an account',
params: [
param('who', 'AccountId'),
param('free', 'Balance'),
param('reserved', 'Balance')
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Staking',
public: {
transfer:
createMethod('transfer', 0)(transfer),
stake:
createMethod('stake', 1)(stake),
unstake:
createMethod('unstake', 2)(unstake),
nominate:
createMethod('nominate', 3)(nominate),
unnominate:
createMethod('unnominate', 4)(unnominate),
registerSlashPreference:
createMethod('registerSlashPreference', 5)(registerSlashPreference),
noteMissedProposal:
createMethod('noteMissedProposal', 6)(noteMissedProposal)
},
private: {
setSessionsPerEra:
createMethod('setSessionsPerEra', 0)(setSessionsPerEra),
setBondingDuration:
createMethod('setBondingDuration', 1)(setBondingDuration),
setValidatorCount:
createMethod('setValidatorCount', 2)(setValidatorCount),
forceNewEra:
createMethod('forceNewEra', 3)(forceNewEra),
setOfflineSlashGrace:
createMethod('setOfflineSlashGrace', 4)(setOfflineSlashGrace),
setBalance:
createMethod('setBalance', 5)(setBalance)
}
}));
-28
View File
@@ -1,28 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, CreateItemOptions, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import param from '@polkadot/params/param';
import createSection from '@polkadot/params/section';
const set: CreateItemOptions = {
description: 'Set timestamp',
isHidden: true, // inherent
params: [
param('timestamp', 'Timestamp')
],
type: []
};
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Timestamp',
public: {
set:
createMethod('set', 0)(set)
},
private: {}
}));
-13
View File
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { CreateItems, Section } from '@polkadot/params/types';
import { Extrinsics, Extrinsic$Sections } from './types';
import createSection from '@polkadot/params/section';
export default (name: Extrinsic$Sections, index: number): Section<Extrinsics, any, any> =>
createSection(name, index)((createMethod: CreateItems<Extrinsics>) => ({
description: 'Timestamp'
}));
+11 -15
View File
@@ -2,20 +2,16 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Section } from '@polkadot/params/types';
import BN from 'bn.js';
export type Extrinsics = {
// substrate
consensus: Section<Extrinsics, any, any>,
council: Section<Extrinsics, any, any>,
councilVoting: Section<Extrinsics, any, any>,
democracy: Section<Extrinsics, any, any>,
session: Section<Extrinsics, any, any>,
staking: Section<Extrinsics, any, any>,
timestamp: Section<Extrinsics, any, any>,
treasury: Section<Extrinsics, any, any>,
// polkadot
parachains: Section<Extrinsics, any, any>
};
export interface ExtrinsicFunction {
(...args: any[]): void
}
export type Extrinsic$Sections = keyof Extrinsics;
export interface ModuleExtrinsics {
[key: string]: ExtrinsicFunction;
}
export interface Extrinsics {
[key: string]: ModuleExtrinsics; // Will hold modules returned by state_getMetadata
}
@@ -0,0 +1,51 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { createType } from '@polkadot/api-codec/codec';
import { FunctionMetadata } from '@polkadot/api-codec/Metadata';
import { Extrinsic, Text } from '@polkadot/api-codec/index';
import u8aConcat from '@polkadot/util/u8a/concat';
import { ExtrinsicFunction } from '../types';
/**
* From the metadata of a function in the module's storage, generate the function
* that will return the correctly-encoded Extrinsic.
*
* @param index - Index of the module section in the modules array.
*/
export default function createExtrinsic (
prefix: string | Text,
name: string | Text,
index: number,
meta: FunctionMetadata
): ExtrinsicFunction {
let extrinsicFn: any;
// If the extrinsic function has an argument of type `Origin`, we ignore it
// FIXME should be `arg.type !== Origin`, but doesn't work...
const expectedArgs = meta.arguments.filter((arg) => arg.type.toString() !== 'Origin');
extrinsicFn = (...args: any[]): Extrinsic => {
if (expectedArgs.length.valueOf() !== args.length) {
throw new Error(`Extrinsic ${prefix}.${name} expects ${expectedArgs.length.valueOf()} arguments, got ${args.length}.`);
}
return new Extrinsic(
u8aConcat(
new Uint8Array([index, meta.id.toNumber()]),
...expectedArgs.map((argument, index) => {
const type = argument.type.toString(); // Argument type, as string
return createType(type, args[index]).toU8a();
})
)
);
};
extrinsicFn.meta = meta;
return extrinsicFn as ExtrinsicFunction;
}
View File
-15
View File
@@ -1,15 +0,0 @@
ISC License (ISC)
Copyright 2017-2018 @polkadot/params authors & contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
-9
View File
@@ -1,9 +0,0 @@
[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org)
![isc](https://img.shields.io/badge/license-ISC-lightgrey.svg?style=flat-square)
[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard)
[![npm](https://img.shields.io/npm/v/@polkadot/primitives.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/primitives)
[![travis](https://img.shields.io/travis/polkadot-js/api.svg?style=flat-square)](https://travis-ci.org/polkadot-js/api)
[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/api.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/api/maintainability)
[![coverage](https://img.shields.io/coveralls/polkadot-js/api.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/api?branch=master)
[![dependency](https://david-dm.org/polkadot-js/api.svg?style=flat-square&path=packages/type-params)](https://david-dm.org/polkadot-js/api?path=packages/type-params)
[![devDependency](https://david-dm.org/polkadot-js/api/dev-status.svg?style=flat-square&path=packages/type-params)](https://david-dm.org/polkadot-js/api?path=packages/type-params#info=devDependencies)
-38
View File
@@ -1,38 +0,0 @@
{
"name": "@polkadot/params",
"version": "0.30.3",
"description": "Type defintions for parameters as passed in calls",
"main": "index.js",
"engines": {
"node": ">=6.4"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/api.git"
},
"keywords": [
"Polkadot"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [],
"license": "ISC",
"bugs": {
"url": "https://github.com/polkadot-js/api/issues"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-params#readme",
"dependencies": {
"@babel/runtime": "^7.0.0",
"@polkadot/extrinsics": "^0.30.3",
"@polkadot/params": "^0.30.3",
"@polkadot/primitives": "^0.30.3",
"@polkadot/util": "^0.30.7",
"@polkadot/util-keyring": "^0.30.7"
}
}
@@ -1,101 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import decode from './index';
describe('decode', () => {
it('decodes single types', () => {
expect(
JSON.stringify(
decode('BlockNumber', new Uint8Array([
0x69, 0, 0, 0, 0, 0, 0, 0
]))
)
).toEqual('{"length":8,"value":"69"}');
});
it('decodes simple arrays', () => {
expect(
JSON.stringify(
decode(['BlockNumber'], new Uint8Array([
0x03, 0, 0, 0,
0x69, 0, 0, 0, 0, 0, 0, 0,
0x42, 0, 0, 0, 0, 0, 0, 0,
0x15, 0, 0, 0, 0, 0, 0, 0
]))
)
).toEqual('{"length":28,"value":["69","42","15"]}');
});
it('decodes tuple arrays', () => {
expect(
JSON.stringify(
decode(['BlockNumber', 'bool'], new Uint8Array([
0x69, 0, 0, 0, 0, 0, 0, 0,
0x01
]))
)
).toEqual('{"length":9,"value":["69",true]}');
});
it('decodes arrays with tuples', () => {
expect(
JSON.stringify(
decode([['BlockNumber', 'bool']], new Uint8Array([
0x03, 0, 0, 0,
0x69, 0, 0, 0, 0, 0, 0, 0,
0x01,
0x42, 0, 0, 0, 0, 0, 0, 0,
0x00,
0x15, 0, 0, 0, 0, 0, 0, 0,
0x01
]))
)
).toEqual('{"length":31,"value":[["69",true],["42",false],["15",true]]}');
});
it('decodes tuples with arrays', () => {
expect(
JSON.stringify(
decode(['BlockNumber', ['bool']], new Uint8Array([
0x69, 0, 0, 0, 0, 0, 0, 0,
0x03, 0, 0, 0,
0x01,
0x00,
0x01
]))
)
).toEqual('{"length":15,"value":["69",[true,false,true]]}');
});
it('decodes StorageKeyValue arrays', () => {
expect(
decode(['StorageKeyValue'], new Uint8Array([
2, 0, 0, 0,
4, 0, 0, 0,
0x11, 0x22, 0x33, 0x44,
9, 0, 0, 0,
0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11,
1, 0, 0, 0,
0x11,
2, 0, 0, 0,
0x99, 0x88
]))
).toEqual({
length: 36,
value: [
{
key: toU8a('0x11223344'),
value: toU8a('0x998877665544332211')
},
{
key: toU8a('0x11'),
value: toU8a('0x9988')
}
]
});
});
});
-80
View File
@@ -1,80 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, Param$Decoded, Param$Type$Array, Param$Types, Param$Value, Param$Value$Array } from '../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
import toU8a from '@polkadot/util/u8a/toU8a';
import isNull from '@polkadot/util/is/null';
import isUndefined from '@polkadot/util/is/undefined';
import decodeValue from './value';
function decodeTuple (type: Param$Type$Array, input: Uint8Array | null | undefined, version: EncodingVersions, isStorage: boolean): Param$Decoded {
if (!input) {
return {
length: 0,
value: []
};
}
const value: Param$Value$Array = [];
let length = 0;
type.forEach((_type: Param$Types) => {
const decoded = decode(_type, input.subarray(length), version, isStorage);
// NOTE small TS hack, since we don't have recursive arrays, assume primitives to push
value.push(decoded.value as Param$Value);
length += decoded.length;
});
return {
length,
value
};
}
function decodeArray ([ type ]: Param$Type$Array, input: Uint8Array | null | undefined, version: EncodingVersions, isStorage: boolean): Param$Decoded {
if (!input) {
return {
length: 0,
value: []
};
}
const arrayLength = u8aToBn(input.subarray(0, 4), true).toNumber();
const value: Param$Value$Array = [];
let length = 4;
for (let index = 0; index < arrayLength; index++) {
const decoded = decode(type, input.subarray(length), version, isStorage);
// NOTE small TS hack, since we don't have recursive arrays, assume primitives to push
value.push(decoded.value as Param$Value);
length += decoded.length;
}
return {
length,
value
};
}
export default function decode (type: Param$Types, _input: Uint8Array | string | null | undefined, version: EncodingVersions, isStorage: boolean = false): Param$Decoded {
const input: Uint8Array | null | undefined = isUndefined(_input) || isNull(_input)
? _input
: toU8a(_input);
if (Array.isArray(type)) {
// Arrays have single entries, Tuples will have multiple types
if (type.length === 1) {
return decodeArray(type, input, version, isStorage);
} else {
return decodeTuple(type, input, version, isStorage);
}
}
return decodeValue(decode, type, input, version, isStorage);
}
-7
View File
@@ -1,7 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, Param$Types, Param$Decoded } from '../types';
export type Decoder = (type: Param$Types, input: Uint8Array, version: EncodingVersions, isStorage: boolean) => Param$Decoded;
@@ -1,75 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import decode from './accountId';
describe('AccountId', () => {
it('decodes null as null', () => {
expect(
decode(null)
).toEqual({
length: 0,
value: null
});
});
it('encodes without a prefix (storage)', () => {
expect(
decode(
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
]),
'latest', true
)
).toEqual({
length: 32,
value: '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s'
});
});
it('encodes without a prefix (poc-1)', () => {
expect(
decode(
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
]),
'poc-1', false
)
).toEqual({
length: 32,
value: '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s'
});
});
it('decodes with a prefix (255)', () => {
expect(
decode(
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
]),
'latest', false
)
).toEqual({
length: 33,
value: '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s'
});
});
it('codes with a prefix (1-byte)', () => {
expect(
decode(
new Uint8Array([
1, 17
])
)
).toEqual({
length: 2,
value: '0x11'
});
});
});
@@ -1,52 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, Param$Decoded } from '../../types';
import encodeAddress from '@polkadot/util-keyring/address/encode';
import ExtError from '@polkadot/util/ext/error';
import u8aToHex from '@polkadot/util/u8a/toHex';
import u8a from './u8a';
export default function accountId (input: Uint8Array | null | undefined, version: EncodingVersions, isStorage: boolean): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const withoutPrefix = isStorage || version === 'poc-1';
const offset = withoutPrefix ? 0 : 1;
const length = withoutPrefix
? 256
: (() => {
const first = input[0];
if (first <= 0xef) {
return 1 * 8;
} else if (first === 0xfc) {
return 2 * 8;
} else if (first === 0xfd) {
return 4 * 8;
} else if (first === 0xfe) {
return 8 * 8;
} else if (first === 0xff) {
return 32 * 8;
}
throw new ExtError(`Invalid account index byte, 0x${first.toString(16)}`);
})();
const u8aDecoded = u8a(input, length, offset);
const publicKey = u8aDecoded.value as Uint8Array;
return {
length: u8aDecoded.length,
value: length === 256
? encodeAddress(publicKey)
: u8aToHex(publicKey)
};
}
@@ -1,24 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import BN from 'bn.js';
import u8aToBn from '@polkadot/util/u8a/toBn';
export default function bn (input: Uint8Array | null | undefined, bitLength: 32 | 64 | 128): Param$Decoded {
if (!input) {
return {
length: 0,
value: new BN(0)
};
}
const length = bitLength / 8;
return {
length,
value: u8aToBn(input.subarray(0, length), true)
};
}
@@ -1,22 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import isNull from '@polkadot/util/is/null';
import isUndefined from '@polkadot/util/is/undefined';
export default function bool (input: Uint8Array | null | undefined): Param$Decoded {
if (isUndefined(input) || isNull(input)) {
return {
length: 0,
value: false
};
}
return {
length: 1,
value: input[0] !== 0
};
}
@@ -1,19 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
export default function byte (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: 0
};
}
return {
length: 1,
value: input[0]
};
}
@@ -1,23 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
export default function bytes (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const length = u8aToBn(input.subarray(0, 4), true).toNumber();
return {
length: length + 4,
value: input.subarray(4, length + 4)
};
}
@@ -1,24 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
export default function code (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const length = u8aToBn(input.subarray(0, 4), true).toNumber() + 4;
const value = input.subarray(4, length);
return {
length,
value
};
}
@@ -1,40 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Digest } from '@polkadot/primitives/digest';
import { Param$Decoded } from '../../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
import bytes from './bytes';
export default function digest (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const logLength = input
? u8aToBn(input.subarray(0, 4), true).toNumber()
: 0;
const value: Digest = {
logs: []
};
let length = 4;
for (let index = 0; index < logLength; index++) {
const decoded = bytes(input.subarray(length));
length += decoded.length;
value.logs.push((decoded.value as Uint8Array));
}
return {
length,
value
};
}
@@ -1,25 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import decodeHeader from '@polkadot/primitives/codec/header/decode';
export default function header (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
// FIXME We don't have a way to determine the length atm
const length = input.length;
const value = decodeHeader(input);
return {
length,
value
};
}
@@ -1,127 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, Param$Decoded, Param$Type } from '../../types';
import { Decoder } from '../types';
import defaultSizes from '@polkadot/primitives/sizes';
import toU8a from '@polkadot/util/u8a/toU8a';
import isNull from '@polkadot/util/is/null';
import isUndefined from '@polkadot/util/is/undefined';
import sizes from '../../sizes';
import accountId from './accountId';
import bool from './bool';
import bn from './bn';
import byte from './byte';
import bytes from './bytes';
import code from './code';
import digest from './digest';
import header from './header';
import keyValue from './keyValue';
import method from './method';
import misbehavior from './misbehavior';
import passThrough from './passThrough';
import string from './string';
import time from './time';
import u8a from './u8a';
export default function decodeValue (decode: Decoder, type: Param$Type, _input: Uint8Array | string | null | undefined, version: EncodingVersions, isStorage: boolean): Param$Decoded {
const input: Uint8Array | null | undefined = isUndefined(_input) || isNull(_input)
? _input
: toU8a(_input);
try {
switch (type) {
// TODO Pass back the actual address, not publicKey?
case 'AccountId':
return accountId(input, version, isStorage);
case 'AccountIndex':
return bn(input, sizes.AccountIndex.get(version) || defaultSizes.AccountIndex);
case 'Balance':
return bn(input, sizes.Balance.get(version) || defaultSizes.Balance);
case 'BlockNumber':
case 'Gas':
case 'SessionKey':
case 'u64':
return bn(input, 64);
case 'bool':
return bool(input);
case 'Bytes':
case 'StorageKey':
return bytes(input);
case 'Call':
case 'Proposal':
return method(decode, input, type === 'Call', version, isStorage);
case 'Code':
return code(input);
case 'CandidateReceipt':
return passThrough(input);
case 'Digest':
return digest(input);
case 'Header':
return header(input);
case 'Hash':
return u8a(input, 256, 0);
case 'KeyValue':
case 'StorageKeyValue':
return keyValue(input);
// HACKY, but a stopgap...
case 'Metadata':
return u8a(input, (input as Uint8Array).length * 8, 0);
case 'MisbehaviorReport':
return misbehavior(input);
case 'ParachainId':
case 'PropIndex':
case 'ReferendumIndex':
case 'u32':
case 'VoteIndex':
return bn(input, 32);
case 'RuntimeVersion':
return u8a(input, 256, 0);
case 'Signature':
return u8a(input, 512, 0);
case 'String':
return string(input);
case 'Timestamp':
return time(input);
case 'u128':
return bn(input, 128);
case 'VoteThreshold':
return byte(input);
case 'StorageData':
case 'StorageChangeSet':
default:
// tslint:disable-next-line
(type as never);
throw new Error(`No value decoder for type='${type}'`);
}
} catch (error) {
console.error('Failed decoding', type, 'encoded as', input, error);
throw error;
}
}
@@ -1,55 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import decode from './index';
describe('keyValue', () => {
const nullDecoder = () => {};
it('encodes StorageKeyValue -> Uint8Array properly', () => {
expect(
decode(
nullDecoder,
'KeyValue',
new Uint8Array([
4, 0, 0, 0,
0x11, 0x22, 0x33, 0x44,
9, 0, 0, 0,
0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11
]),
'poc-1'
)
).toEqual({
length: (4 + 4 + 4 + 9),
value: {
key: toU8a('0x11223344'),
value: toU8a('0x998877665544332211')
}
});
});
it('encodes KeyValue -> Uint8Array properly', () => {
expect(
decode(
nullDecoder,
'KeyValue',
new Uint8Array([
1, 0, 0, 0,
0x11,
2, 0, 0, 0,
0x99, 0x88
]),
'poc-1'
)
).toEqual({
length: (4 + 1 + 4 + 2),
value: {
key: toU8a('0x11'),
value: toU8a('0x9988')
}
});
});
});
@@ -1,30 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
export default function bytes (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const keyLength = u8aToBn(input.subarray(0, 4), true).toNumber();
const key = input.subarray(4, keyLength + 4);
const valLength = u8aToBn(input.subarray(keyLength + 4, keyLength + 8), true).toNumber();
const length = valLength + keyLength + 8;
const value = input.subarray(keyLength + 8, length);
return {
length,
value: {
key,
value
}
};
}
@@ -1,61 +0,0 @@
// Copyright 2017-2018 @polkadot/params 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 '@polkadot/extrinsics/types';
import { EncodingVersions, ExtrinsicDecoded, Param, Param$Decoded, Section } from '../../types';
import { Decoder } from '../types';
import assert from '@polkadot/util/assert';
import extrinsics from '@polkadot/extrinsics/index';
import isUndefined from '@polkadot/util/is/undefined';
// type Section =
type Result = {
length: number,
value: ExtrinsicDecoded
};
export default function call (decode: Decoder, input: Uint8Array | null | undefined, isPublic: boolean, version: EncodingVersions, isStorage: boolean): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const _section: Section<Extrinsics, any, any> | undefined = Object.values(extrinsics).find(({ index }) =>
index[0] === input[0]
);
assert(!isUndefined(_section), `Unable to find extrinsic section ${input[0]}`);
const section = _section as Section<Extrinsics, any, any>;
const methods = section[isPublic ? 'public' : 'private'];
const extrinsic = Object.values(methods).find(({ index }) =>
index[1] === input[1]
);
assert(!isUndefined(extrinsic), `Unable to find method ${input[1]} for section '${section.name}'`);
// @ts-ignore checked above
const params = extrinsic.params;
const result = {
length: 2, // sectionId + methodId
value: ({
extrinsic,
params: []
} as ExtrinsicDecoded)
};
return params.reduce(({ length, value }: Result, { type }: Param) => {
const decoded = decode(type, input.subarray(length), version, isStorage);
value.params.push(decoded.value);
return {
length: length + decoded.length,
value
};
}, result);
}
@@ -1,47 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { MisbehaviorReport } from '@polkadot/primitives/misbehavior';
import { Param$Decoded } from '../../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
const O_PHASH = 0;
const O_PNUM = 32;
const O_AUTH = O_PNUM + 8;
const O_TYPE = O_AUTH + 32;
const A_HASH = O_TYPE + 1;
const A_SIG = A_HASH + 32;
const B_HASH = A_SIG + 64;
const B_SIG = B_HASH + 32;
const length = B_SIG + 64;
export default function misbehavior (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0
} as Param$Decoded;
}
return {
length,
value: ({
parentHash: input.subarray(O_PHASH, O_PNUM),
number: u8aToBn(input.subarray(O_PNUM, O_AUTH), true),
authorityId: input.subarray(O_AUTH, O_TYPE),
type: input[O_TYPE],
data: [
{
header: input.subarray(A_HASH, A_SIG),
signature: input.subarray(A_SIG, B_HASH)
},
{
header: input.subarray(B_HASH, B_SIG),
signature: input.subarray(B_SIG)
}
]
} as MisbehaviorReport)
};
}
@@ -1,19 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
export default function passThrough (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
return {
length: input.length,
value: input
};
}
@@ -1,28 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
import u8aToUtf8 from '@polkadot/util/u8a/toUtf8';
import isNull from '@polkadot/util/is/null';
import isUndefined from '@polkadot/util/is/undefined';
export default function string (input: Uint8Array | null | undefined): Param$Decoded {
if (isUndefined(input) || isNull(input)) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const length = u8aToBn(input.subarray(0, 4), true).toNumber();
return {
length: length + 4,
value: u8aToUtf8(
input.subarray(4, length + 4)
)
};
}
@@ -1,25 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
import u8aToBn from '@polkadot/util/u8a/toBn';
export default function time (input: Uint8Array | null | undefined): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
return {
length: 8,
value: new Date(
u8aToBn(input.subarray(0, 8), true)
.imuln(1000)
.toNumber()
)
};
}
@@ -1,21 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Decoded } from '../../types';
export default function u8a (input: Uint8Array | null | undefined, bitLength: number, offset: number): Param$Decoded {
if (!input) {
return {
length: 0,
value: input
} as Param$Decoded;
}
const length = (bitLength / 8) + offset;
return {
length,
value: input.subarray(offset, length)
};
}
-18
View File
@@ -1,18 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, Params } from '../types';
import assert from '@polkadot/util/assert';
import u8aConcat from '@polkadot/util/u8a/concat';
import encodeParam from './param';
export default function encodeParams (params: Params, values: Array<any>, version: EncodingVersions): Uint8Array {
assert(params.length === values.length, `Expected values to have ${params.length} items, found ${values.length} instead`);
return u8aConcat.apply(null, params.map((param, index) =>
encodeParam(param, values[index], version)
));
}
@@ -1,49 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import encodeParam from './param';
describe('encodeParam', () => {
it('encodes a single parameter', () => {
expect(
encodeParam({ type: 'Balance' }, 0)
).toEqual(new Uint8Array(16));
});
it('checks for array types with array values', () => {
expect(
() => encodeParam({ type: ['Balance'] }, 64)
).toThrow(/Expected array values/);
});
it('encodes array types with empty array values', () => {
expect(
encodeParam({ type: ['Balance'] }, [])
).toEqual(new Uint8Array(4));
});
it('encodes array types with actual array values', () => {
expect(
encodeParam({ type: ['Balance'] }, [3, 4])
).toEqual(
new Uint8Array([
2, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
])
);
});
it('encodes tuple types with actual array values', () => {
expect(
encodeParam({ type: ['Balance', 'AccountIndex'] }, [3, 4])
).toEqual(
new Uint8Array([
2, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4, 0, 0, 0
])
);
});
});
-40
View File
@@ -1,40 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, Param, Param$Type } from '../types';
import assert from '@polkadot/util/assert';
import u8aConcat from '@polkadot/util/u8a/concat';
import bnToU8a from '@polkadot/util/bn/toU8a';
import typeToString from '../typeToString';
import encodeType from './type';
export default function encodeParam (param: Param, value: any, version: EncodingVersions = 'latest'): Uint8Array {
if (Array.isArray(param.type)) {
assert(Array.isArray(value), () => `Expected array values of type '${typeToString(param.type)}'`);
const arr = (value as Array<any>);
const types = (param.type as Array<Param$Type>);
if (types.length === 1) {
return u8aConcat(
bnToU8a(arr.length, 32, true),
u8aConcat.apply(null, arr.map((v, index) =>
encodeType(types[0], v, version)
))
);
}
return u8aConcat(
bnToU8a(arr.length, 32, true),
u8aConcat.apply(null, arr.map((v, index) =>
// NOTE since we may have embedded again, move to Param shape
encodeParam(({ type: types[index] } as Param), v, version)
))
);
}
return encodeType(param.type, value, version);
}
@@ -1,111 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { EncodingVersions, Param$Type } from '../../types';
import addrPrefixes from '@polkadot/extrinsics/codec/encode/prefixes';
import bnToU8a from '@polkadot/util/bn/toU8a';
import u8aConcat from '@polkadot/util/u8a/concat';
import u8aFromString from '@polkadot/util/u8a/fromString';
import u8aToU8a from '@polkadot/util/u8a/toU8a';
import addressDecode from '@polkadot/util-keyring/address/decode';
import defaultSizes from '@polkadot/primitives/sizes';
import sizes from '../../sizes';
import keyValue from './keyValue';
import storageKey from './storageKey';
export default function encodeType (type: Param$Type, value: any, version: EncodingVersions): Uint8Array {
try {
switch (type) {
case 'AccountId':
return u8aConcat(
version === 'poc-1'
? addrPrefixes.none
: addrPrefixes.publicKey,
addressDecode(value)
);
case 'Balance':
return bnToU8a(value, sizes.Balance.get(version) || defaultSizes.Balance, true);
case 'BlockNumber':
case 'Gas':
case 'SessionKey':
case 'u64':
return bnToU8a(value, 64, true);
case 'bool':
return bnToU8a(value ? 1 : 0, 8, true);
case 'Bytes':
case 'Code':
return u8aToU8a(value);
// FIXME Here we should pass through the actual objects
case 'Call':
case 'CandidateReceipt':
case 'Digest':
case 'Header':
case 'MisbehaviorReport':
case 'Proposal':
return u8aToU8a(value);
// TODO Here we should do actual length conversions, i.e. 256/512
case 'Hash':
case 'Signature':
return u8aToU8a(value);
case 'AccountIndex':
return bnToU8a(value, sizes.AccountIndex.get(version) || defaultSizes.Balance, true);
case 'KeyValue':
case 'StorageKeyValue':
return keyValue(value);
case 'ParachainId':
case 'PropIndex':
case 'ReferendumIndex':
case 'VoteIndex':
case 'u32':
return bnToU8a(value, 32, true);
case 'StorageKey':
return storageKey(value);
case 'String':
return (() => {
const u8a = u8aFromString(value);
return u8aConcat(
bnToU8a(u8a.length, 32, true),
u8a
);
})();
case 'Timestamp':
if (value instanceof Date) {
value = Math.ceil(value.getTime() / 1000);
}
return bnToU8a(value, 64, true);
case 'u128':
return bnToU8a(value, 128, true);
// TODO enums?
case 'VoteThreshold':
return bnToU8a(value || 0, 8, true);
default:
// tslint:disable-next-line
(type as never);
throw new Error(`No formatter for ${type}`);
}
} catch (error) {
console.error('Failed encoding', type, 'with', value, error);
throw error;
}
}
@@ -1,41 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import encode from './index';
describe('keyValue', () => {
it('encodes StorageKeyValue -> Uint8Array properly', () => {
expect(
encode('StorageKeyValue', {
key: toU8a('0x11223344'),
value: toU8a('0x998877665544332211')
})
).toEqual(
new Uint8Array([
4, 0, 0, 0,
0x11, 0x22, 0x33, 0x44,
9, 0, 0, 0,
0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11
])
);
});
it('encodes KeyValue -> Uint8Array properly', () => {
expect(
encode('KeyValue', {
key: toU8a('0x11'),
value: toU8a('0x9988')
})
).toEqual(
new Uint8Array([
1, 0, 0, 0,
0x11,
2, 0, 0, 0,
0x99, 0x88
])
);
});
});
@@ -1,19 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { KeyValue } from '../../types';
import bnToU8a from '@polkadot/util/bn/toU8a';
import u8aConcat from '@polkadot/util/u8a/concat';
// NOTE reverse of ../../decode/value/keyValue
export default function keyValue ({ key, value }: KeyValue): Uint8Array {
return u8aConcat(
bnToU8a(key.length, 32, true),
key,
bnToU8a(value.length, 32, true),
value
);
}
@@ -1,21 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import storage from '@polkadot/storage';
import toU8a from '@polkadot/util/u8a/toU8a';
import encode from './index';
describe.skip('storageKey', () => {
it('encodes storageKey -> Uint8Array properly', () => {
expect(
encode('StorageKey', [
storage.balances.freeBalance,
'5EhmTa7fL6SdjgKXo9g6hetR6nHnRAmrtisoGFWEESjzECtY'
])
).toEqual(
toU8a('0x11cf1094db4db43356b7787c3e59c39f')
);
});
});
@@ -1,11 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { SectionItem } from '@polkadot/params/types';
import createStorageKey from '../../key';
export default function storageKey ([key, ...params]: [SectionItem<any>, any]): Uint8Array {
return createStorageKey(key).apply(null, params);
}
-28
View File
@@ -1,28 +0,0 @@
// Copyright 2017-2018 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { SectionItem } from '@polkadot/params/types';
import u8aConcat from '@polkadot/util/u8a/concat';
import u8aFromString from '@polkadot/util/u8a/fromString';
import xxhash from '@polkadot/util-crypto/xxhash/asU8a';
import formatParams from './params';
export type Keygen = (...keyParams: Array<any>) => Uint8Array;
export default function bindKey <T> ({ isUnhashed, key, params }: SectionItem<T>): Keygen {
const prefix = u8aFromString(key);
return (...keyParams: Array<any>): Uint8Array => {
const postfix = keyParams.length !== 0
? u8aConcat.apply(null, formatParams(params, keyParams))
: new Uint8Array([]);
const prefixedKey = u8aConcat(prefix, postfix);
return isUnhashed
? prefixedKey
: xxhash(prefixedKey, 128);
};
}
-89
View File
@@ -1,89 +0,0 @@
// Copyright 2017-2018 @polkadot/storage 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 { Param, Params } from '@polkadot/params/types';
import sizes from '@polkadot/primitives/sizes';
import bnToU8a from '@polkadot/util/bn/toU8a';
import u8aToU8a from '@polkadot/util/u8a/toU8a';
import u8aFromString from '@polkadot/util/u8a/fromString';
import addressDecode from '@polkadot/util-keyring/address/decode';
export default function formatParams (params: Params, values: Array<any> = []): Array<Uint8Array> {
const paramTypes = Object.values(params).map(({ type }: Param) => type);
return values.map((value: any, index: number): Uint8Array => {
try {
if (Array.isArray(paramTypes[index])) {
throw new Error('Unable to handle Array type');
}
const type = paramTypes[index];
switch (type) {
case 'AccountId':
return addressDecode((value as Uint8Array));
case 'Balance':
return bnToU8a((value as BN), sizes.Balance, true);
case 'u128':
return bnToU8a((value as BN), 128, true);
case 'BlockNumber':
case 'Gas':
case 'u64':
return bnToU8a((value as BN), 64, true);
case 'bool':
return new Uint8Array([value ? 1 : 0]);
case 'Bytes':
case 'Call':
case 'CandidateReceipt':
case 'Code':
case 'Digest':
case 'Hash':
case 'Header':
case 'KeyValue':
case 'StorageKey':
case 'StorageKeyValue':
case 'StorageResult':
case 'StorageResultSet':
case 'MisbehaviorReport':
case 'Proposal':
case 'Signature':
return u8aToU8a((value as Uint8Array));
case 'AccountIndex':
return bnToU8a((value as BN), sizes.AccountIndex, true);
case 'ParachainId':
case 'PropIndex':
case 'ReferendumIndex':
case 'SessionKey':
case 'VoteIndex':
case 'VoteThreshold':
case 'u32':
return bnToU8a((value as BN), 32, true);
case 'String':
return u8aFromString((value as string));
case 'Timestamp':
return bnToU8a((value as Date).getTime(), 64, true);
default:
// tslint:disable-next-line
(type as never);
throw new Error('Unable to find handler');
}
} catch (error) {
console.error('formatParams', value, index, paramTypes[index], error);
throw error;
}
});
}
-28
View File
@@ -1,28 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { SectionItem, CreateItem, CreateItems, CreateItemOptions } from './types';
import bnToU8a from '@polkadot/util/bn/toU8a';
import u8aConcat from '@polkadot/util/u8a/concat';
import isUndefined from '@polkadot/util/is/undefined';
export default function createMethod<T> (section: keyof T, sectionIndex: Uint8Array): CreateItems<T> {
return (name: string, index: number = 0): CreateItem<T> =>
({ description, key = '', params, type, isDeprecated = false, isHidden = false, isSigned = false, isUnhashed = false, subscribe }: CreateItemOptions): SectionItem<T> => ({
description,
index: u8aConcat(sectionIndex, bnToU8a(index, 8, true)),
isDeprecated,
isHidden,
isSigned,
isSubscription: !isUndefined(subscribe),
isUnhashed,
key,
name,
params,
section,
subscribe: subscribe || ['', ''],
type
});
}
-13
View File
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param, Param$Options, Param$Types } from './types';
export default function createParam (name: string, type: Param$Types, { isOptional = false }: Param$Options = { isOptional: false }): Param {
return {
isOptional,
name,
type
};
}
-36
View File
@@ -1,36 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Section, CreateSection, CreateSectionOptions } from './types';
import bnToU8a from '@polkadot/util/bn/toU8a';
import createMethod from './method';
export default function createSection <T> (name: keyof T, _index: number = 0): CreateSection<T, any, any> {
const index = bnToU8a(_index, 8, true);
const creator = (optOrFn: CreateSectionOptions<T, any, any>): Section<T, any, any> => {
if (typeof optOrFn === 'function') {
return creator(
optOrFn(
createMethod(name, index)
)
);
}
const { description, isDeprecated = false, isHidden = false } = optOrFn;
return {
description,
isDeprecated,
isHidden,
index,
name,
private: optOrFn.private || {},
public: optOrFn.public || {}
};
};
return creator;
}
@@ -1,33 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import param from './param';
import signature from './signature';
describe('jsonrpcSignature', () => {
it('formats the signature according to the specification', () => {
expect(
signature({
name: 'test',
description: 'test',
params: [
param('a', 'AccountId'),
param('b', 'Bytes')
],
type: 'Signature'
})
).toEqual('test (a: AccountId, b: Bytes): Signature');
});
it('empty inputs format correctly', () => {
expect(
signature({
name: 'test',
description: 'test',
params: [],
type: 'AccountId'
})
).toEqual('test (): AccountId');
});
});
-26
View File
@@ -1,26 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { SectionItem } from './types';
import typeToString from './typeToString';
/**
* @name signature
* @signature jsonrpcSignature (method: InterfaceMethodDefinition): string
* @summary Returns a string representation of the method with inputs and outputs.
* @description
* Formats the name, inputs and outputs into a human-readable string. This contains the input parameter names input types and output type.
* @example
* import signature from '@polkadot/params/signature';
*
* signature({ name: 'test_method', params: [ { name: 'dest', type: 'Address' } ], type: 'Address' }); // => test_method (dest: Address): Address
*/
export default function signature<T> ({ name, params, type }: SectionItem<T>): string {
const inputs = params.map(({ name, type }) =>
`${name}: ${typeToString(type)}`
).join(', ');
return `${name} (${inputs}): ${typeToString(type)}`;
}
-21
View File
@@ -1,21 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import sizes, { SizeType } from '@polkadot/primitives/sizes';
import { EncodingVersions } from './types';
const Balance: Map<EncodingVersions, SizeType> = new Map([
['latest' as EncodingVersions, sizes.Balance],
['poc-1' as EncodingVersions, 64 as SizeType]
]);
const AccountIndex: Map<EncodingVersions, SizeType> = new Map([
['latest' as EncodingVersions, sizes.AccountIndex],
['poc-1' as EncodingVersions, 64 as SizeType]
]);
export default {
AccountIndex,
Balance
};
@@ -1,31 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import typeToString from './typeToString';
describe('typeToString', () => {
it('formats single types', () => {
expect(
typeToString('BlockNumber')
).toEqual('BlockNumber');
});
it('formats array types', () => {
expect(
typeToString(['BlockNumber'])
).toEqual('Array<BlockNumber>');
});
it('formats tuple types', () => {
expect(
typeToString(['AccountId', 'BlockNumber'])
).toEqual('(AccountId, BlockNumber)');
});
it('formats tuple arrays', () => {
expect(
typeToString([['AccountId', 'BlockNumber']])
).toEqual('Array<(AccountId, BlockNumber)>');
});
});
-17
View File
@@ -1,17 +0,0 @@
// Copyright 2017-2018 @polkadot/params authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Param$Types } from './types';
export default function typeToString (type: Param$Types): string {
if (!Array.isArray(type)) {
return type;
}
const text = type.map(typeToString).join(', ');
return type.length !== 1
? `(${text})`
: `Array<${text}>`;
}
-146
View File
@@ -1,146 +0,0 @@
// Copyright 2017-2018 @polkadot/params 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 { Extrinsics } from '@polkadot/extrinsics/types';
import { Digest } from '@polkadot/primitives/digest';
import { Header } from '@polkadot/primitives/header';
import { MisbehaviorReport } from '@polkadot/primitives/misbehavior';
export type EncodingVersions = 'poc-1' | 'latest';
// TODO: Also update the following
// - @polkadot/storage/key/params.ts
// - decode/value/index.js
// - encode/type/index.js
export type Param$Type = 'AccountId' | 'AccountIndex' | 'Balance' | 'BlockNumber' | 'bool' | 'Bytes' | 'Call' | 'CandidateReceipt' | 'Code' | 'Digest' | 'Gas' | 'Hash' | 'Header' | 'KeyValue' | 'Metadata' | 'MisbehaviorReport' | 'ParachainId' | 'PendingExtrinsics' | 'PropIndex' | 'Proposal' | 'ReferendumIndex' | 'RuntimeVersion' | 'SessionKey' | 'Signature' | 'SignedBlock' | 'StorageKey' | 'StorageKeyValue' | 'StorageData' | 'StorageChangeSet' | 'String' | 'Timestamp' | 'u32' | 'u64' | 'u128' | 'VoteIndex' | 'VoteThreshold' | 'Vec<StorageKey>';
export type Param$Type$Array = Array<Param$Type | Array<Param$Type | Array<Param$Type>>>;
export type Param$Types = Param$Type | Param$Type$Array;
export type ExtrinsicDecoded = {
extrinsic: SectionItem<Extrinsics>,
params: Array<any>
}
export type BlockExtrinsicDecoded = {
address: string,
accountIndex: BN,
extrinsic: SectionItem<Extrinsics>,
params: Array<any>,
signature: Uint8Array
}
export type BlockJustificationDecoded = {
hash: Uint8Array,
round: BN,
signatures: Array<{
address: string,
signature: Uint8Array
}>
}
export type BlockDecoded = {
header: Header,
extrinsics: Array<BlockExtrinsicDecoded>,
justification: BlockJustificationDecoded
};
export type Metadata = {
};
export type KeyValue = {
key: Uint8Array,
value: Uint8Array
}
export type Param$Value = Digest | Header | KeyValue | Metadata | MisbehaviorReport | ExtrinsicDecoded | BN | Date | Uint8Array | boolean | number | string | null;
export type Param$Value$Array = Array<Param$Value | Array<Param$Value | Array<Param$Value>>>;
export type Param$Values = Param$Value | Param$Value$Array;
export type Param$Decoded = {
length: number,
value: Param$Values
}
export type Param$Options = {
isOptional: boolean
};
export type Param = Param$Options & {
name: string,
type: Param$Types
};
export type Params = Array<Param>;
// FIXME: This is a bit horrible, since not all the params (apart from deprecated/hidden) is applicable to all. Not a major inconveninece, but it is itching
export type SectionItem<T> = {
description: string,
index: Uint8Array, // only for extrinsics,
isDeprecated: boolean,
isHidden: boolean,
isSigned: boolean, // only for extrinsics
isSubscription: boolean, // only for jsonrpc
isUnhashed: boolean, // only for storage
key: string, // only for storage
name: string,
params: Params,
section: keyof T,
subscribe: [string, string], // only for jsonrpc
type: Param$Types
};
export type SectionItems<T, K> = {
[key in keyof K]: SectionItem<T>
};
export type Section<T, Priv, Pub> = {
isDeprecated: boolean,
isHidden: boolean,
description: string,
index: Uint8Array,
name: keyof T,
private: SectionItems<T, Priv>,
public: SectionItems<T, Pub>
};
export type Sections<T, Priv, Pub> = Map<T, Section<T, Priv, Pub>>;
export type CreateItemOptions = {
description: string,
isDeprecated?: boolean,
isHidden?: boolean,
isSigned?: boolean,
isUnhashed?: boolean,
key?: string,
params: Params,
subscribe?: [string, string],
type: Param$Types
};
export type CreateItemOptionsMap = {
[index: string]: CreateItemOptions
};
export type CreateItem<T> = (options: CreateItemOptions) => SectionItem<T>;
export type CreateItems<T> = (name: string, index?: number) => CreateItem<T>;
export type CreateSectionOptions$Only<T, Priv, Pub> = {
description: string,
isDeprecated?: boolean,
isHidden?: boolean,
'private'?: SectionItems<T, Priv>,
'public'?: SectionItems<T, Pub>
};
export type CreateSectionOptions$Fn<T, Priv, Pub> = (method: CreateItems<T>) => CreateSectionOptions$Only<T, Priv, Pub>;
export type CreateSectionOptions<T, Priv, Pub> = CreateSectionOptions$Only<T, Priv, Pub> | CreateSectionOptions$Fn<T, Priv, Pub>;
export type CreateSection<T, Priv, Pub> = (options: CreateSectionOptions<T, Priv, Pub>) => Section<T, Priv, Pub>;
View File
-15
View File
@@ -1,15 +0,0 @@
ISC License (ISC)
Copyright 2017-2018 @polkadot/primitives authors & contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
-33
View File
@@ -1,33 +0,0 @@
[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org)
![isc](https://img.shields.io/badge/license-ISC-lightgrey.svg?style=flat-square)
[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard)
[![npm](https://img.shields.io/npm/v/@polkadot/primitives.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/primitives)
[![travis](https://img.shields.io/travis/polkadot-js/api.svg?style=flat-square)](https://travis-ci.org/polkadot-js/api)
[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/api.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/api/maintainability)
[![coverage](https://img.shields.io/coveralls/polkadot-js/api.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/api?branch=master)
[![dependency](https://david-dm.org/polkadot-js/api.svg?style=flat-square&path=packages/type-primitives)](https://david-dm.org/polkadot-js/api?path=packages/type-primitives)
[![devDependency](https://david-dm.org/polkadot-js/api/dev-status.svg?style=flat-square&path=packages/type-primitives)](https://david-dm.org/polkadot-js/api?path=packages/type-primitives#info=devDependencies)
# @polkadot/primitives
Base [flow](https://flow.org/) definitions for the base Polkadot types as defined in the [specification](https://github.com/w3f/polkadot-spec). It is useful for implementations, applications and libraries, where type-checking of the JavaScript base types is of importance.
## Usage
Installation -
```
npm install --save @polkadot/primitives
```
Usage -
```js
// @flow
import type { AccountId, Balance } from '@polkadot/primitives/base';
function getBalance (accountId: AccountId): Balance {
...
}
```
-38
View File
@@ -1,38 +0,0 @@
{
"name": "@polkadot/primitives",
"version": "0.30.3",
"description": "Type defintions for the Polkadot network",
"main": "index.js",
"engines": {
"node": ">=6.4"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/api.git"
},
"keywords": [
"Polkadot"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [],
"license": "ISC",
"bugs": {
"url": "https://github.com/polkadot-js/api/issues"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-primitives#readme",
"dependencies": {
"@babel/runtime": "^7.0.0",
"@polkadot/trie-hash": "^0.30.7",
"@polkadot/util": "^0.30.7"
},
"devDependencies": {
"bn.js": "^4.11.8"
}
}
-27
View File
@@ -1,27 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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';
export type Bytes = Uint8Array;
export type Hash = Uint8Array;
export type H160 = Uint8Array;
export type H256 = Uint8Array;
export type H512 = Uint8Array;
export type U32 = BN;
export type U64 = BN;
export type U128 = BN;
export type U256 = BN;
export type AccountId = H256;
export type Balance = U128;
export type BlockNumber = U64;
export type ChainId = U32;
export type HeaderHash = H256;
export type Index = U32;
export type ObjectId = U64;
export type ParaChainId = U64;
export type Proportion = U64;
export type Signature = H512;
export type Timestamp = U64;
-13
View File
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { AccountId, HeaderHash, Signature } from './base';
export type Justification$Signature = [AccountId, Signature];
export type Justification = {
roundNumber: number,
hash: HeaderHash,
signatures: Array<Justification$Signature>
}
-11
View File
@@ -1,11 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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 { UncheckedRaw } from './extrinsic';
export type Block = {
header: Header,
extrinsics: Array<UncheckedRaw>
};
-24
View File
@@ -1,24 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { AccountId, Balance, Bytes, ChainId, Hash, Signature } from './base';
export type Candidate = {
parachainIndex: ChainId,
collatorSignature: Signature,
unprocessedIngress: Array<Array<Array<Bytes>>>,
blockData: Bytes
};
export type CandidateReceipt$BalanceUpload = [AccountId, Balance];
export type CandidateReceipt$EgressQueueRoot = [ChainId, Hash];
export type CandidateReceipt = {
parachainIndex: ChainId,
collator: AccountId,
headData: Bytes,
balanceUploads: Array<CandidateReceipt$BalanceUpload>,
egressQueueRoots: Array<CandidateReceipt$EgressQueueRoot>,
fees: Balance
};
@@ -1,18 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Block } from '../../block';
import createBlock from '../../create/block';
import decodeHeader from '../header/decode';
import decodeRaw from './decodeRaw';
export default function decodeBlock (u8a: Uint8Array): Block {
const { header, extrinsics } = decodeRaw(u8a);
return createBlock({
header: decodeHeader(header),
extrinsics
});
}
@@ -1,55 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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 '@polkadot/extrinsics';
import encodeUnchecked from '@polkadot/extrinsics/codec/encode/unchecked';
import hexToU8a from '@polkadot/util/hex/toU8a';
import testingPairs from '@polkadot/util-keyring/testingPairs';
import decode from './decodeRaw';
const keyring = testingPairs();
describe('decodeRaw', () => {
it('encodes the block properly', () => {
expect(
decode(
hexToU8a(
'0x' +
// parent_hash
'0900000000000000000000000000000000000000000000000000000000000009' +
// number
'4300000000000000' +
// state_root
'0800000000000000000000000000000000000000000000000000000000000008' +
// transaction_root
'0700000000000000000000000000000000000000000000000000000000000007' +
// digest
'02000000' +
'0100000001' +
'0100000002' +
// transactions
'01000000' +
'6f000000' +
// prefix
'ff' +
'0000000000000000000000000000000000000000000000000000000000000000' +
'00000000' +
'0300' +
'7527000000000000' +
'0000000000000000000000000000000000000000000000000000000000000000' +
'0000000000000000000000000000000000000000000000000000000000000000'
)
)
).toMatchObject({
extrinsics: [
encodeUnchecked(
keyring.nobody, 0,
extrinsics.timestamp.public.set,
[10101]
)
]
});
});
});
@@ -1,41 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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 decodeExtrinsic from '@polkadot/extrinsics/codec/decode/length';
import u8aToBn from '@polkadot/util/u8a/toBn';
import decodeHeader from '../header/decodeRaw';
type RawData = {
body: Uint8Array,
extrinsics: Array<Uint8Array>,
header: Uint8Array,
number: BN
};
export default function decodeRaw (u8a: Uint8Array): RawData {
// tslint:disable-next-line:variable-name
const { body, header, number } = decodeHeader(u8a);
const length = u8aToBn(body.subarray(0, 4), true).toNumber();
const extrinsics = [];
let offset = 4;
for (let index = 0; index < length; index++) {
const extrinsic = decodeExtrinsic(
body.subarray(offset)
);
offset += extrinsic.length + 4;
extrinsics.push(extrinsic);
}
return {
body,
extrinsics,
header,
number
};
}
@@ -1,48 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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 '@polkadot/extrinsics';
import encodeUnchecked from '@polkadot/extrinsics/codec/encode/unchecked';
import hexToU8a from '@polkadot/util/hex/toU8a';
import testingPairs from '@polkadot/util-keyring/testingPairs';
import blockBuilder from '../../create/block';
import { encodeBlock } from './index';
const keyring = testingPairs();
describe('encodeBlock', () => {
it('encodes a block correctly (actual values)', () => {
expect(
encodeBlock(
blockBuilder({
header: {
number: 9,
parentHash: hexToU8a('0x737d699e4e42f78dc2fb098f01bb85389f2c7f0a77bb41918adac6bfa5b3ee46'),
stateRoot: hexToU8a('0xf707774183723f201b875024069f30e7089b7f83c3c3cdc534b10d15fca91262')
},
extrinsics: [
encodeUnchecked
(keyring.nobody, 0,
extrinsics.timestamp.public.set,
[0x5b13c3a4]
),
encodeUnchecked(
keyring.nobody, 0,
extrinsics.parachains.public.setHeads,
[[]]
)
]
})
)
).toEqual(
new Uint8Array([
115, 125, 105, 158, 78, 66, 247, 141, 194, 251, 9, 143, 1, 187, 133, 56, 159, 44, 127, 10, 119, 187, 65, 145, 138, 218, 198, 191, 165, 179, 238, 70, 9, 0, 0, 0, 0, 0, 0, 0, 247, 7, 119, 65, 131, 114, 63, 32, 27, 135, 80, 36, 6, 159, 48, 231, 8, 155, 127, 131, 195, 195, 205, 197, 52, 177, 13, 21, 252, 169, 18, 98, 140, 102, 133, 98, 214, 123, 73, 173, 122, 252, 247, 48, 181, 86, 77, 188, 213, 161, 17, 19, 73, 96, 158, 181, 249, 69, 97, 15, 186, 12, 45, 157, 0, 0, 0, 0, 2, 0, 0, 0, 111, 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, 3, 0, 164, 195, 19, 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, 107, 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
])
// hexToU8a(
// '0x737d699e4e42f78dc2fb098f01bb85389f2c7f0a77bb41918adac6bfa5b3ee460900000000000000f707774183723f201b875024069f30e7089b7f83c3c3cdc534b10d15fca91262ab602f7974bbfb513f021f39777e2195094dc64a2c1b7c82a1781cb9fd4768a800000000020000006e0000000000000000000000000000000000000000000000000000000000000000000000000000000300a4c3135b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006a00000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
// )
);
});
});
@@ -1,15 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Block } from '../../block';
import headerEncode from '../header/encode';
import encodeRaw from './encodeRaw';
export default function encodeBlock ({ extrinsics, header }: Block): Uint8Array {
return encodeRaw(
headerEncode(header, extrinsics),
extrinsics
);
}
@@ -1,37 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import encodeRaw from './encodeRaw';
describe('encodeRaw', () => {
it('encodes correctly (actual values)', () => {
expect(
encodeRaw(
new Uint8Array([
168, 135, 224, 93, 140, 222, 226, 83, 13, 116, 138, 197, 164, 6, 48, 190, 101, 18, 221, 166, 40, 179, 158, 112, 133, 154, 215, 198, 177, 76, 212, 228,
1, 0, 0, 0, 0, 0, 0, 0,
159, 216, 180, 61, 159, 12, 131, 80, 22, 196, 220, 94, 6, 222, 68, 159, 97, 60, 16, 69, 163, 149, 125, 138, 175, 36, 30, 93, 235, 4, 1, 168,
245, 208, 141, 24, 250, 136, 158, 84, 67, 170, 59, 146, 17, 149, 62, 67, 254, 66, 126, 53, 20, 146, 252, 243, 137, 89, 224, 145, 252, 79, 109, 15,
0, 0, 0, 0
]),
[
new Uint8Array([
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, 188, 29, 21, 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
]),
new Uint8Array([
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
])
]
)
).toEqual(
new Uint8Array([
168, 135, 224, 93, 140, 222, 226, 83, 13, 116, 138, 197, 164, 6, 48, 190, 101, 18, 221, 166, 40, 179, 158, 112, 133, 154, 215, 198, 177, 76, 212, 228, 1, 0, 0, 0, 0, 0, 0, 0, 159, 216, 180, 61, 159, 12, 131, 80, 22, 196, 220, 94, 6, 222, 68, 159, 97, 60, 16, 69, 163, 149, 125, 138, 175, 36, 30, 93, 235, 4, 1, 168, 245, 208, 141, 24, 250, 136, 158, 84, 67, 170, 59, 146, 17, 149, 62, 67, 254, 66, 126, 53, 20, 146, 252, 243, 137, 89, 224, 145, 252, 79, 109, 15, 0, 0, 0, 0, 2, 0, 0, 0,
110, 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, 3, 0, 188, 29, 21, 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,
106, 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, 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
])
);
});
});
@@ -1,21 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { UncheckedRaw } from '../../extrinsic';
import uncheckedLength from '@polkadot/extrinsics/codec/encode/length';
import u8aConcat from '@polkadot/util/u8a/concat';
import encodeArray from '../encoder/array';
export default function encodeBlockRaw (header: Uint8Array, extrinsics: Array<UncheckedRaw> = []): Uint8Array {
return u8aConcat(
header,
encodeArray(
extrinsics.map((extrinsic) =>
uncheckedLength(extrinsic)
)
)
);
}
@@ -1,9 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import encodeBlock from './encode';
export {
encodeBlock
};
@@ -1,37 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import decodeArray from './array';
describe('decodeArray', () => {
it('decodes an array with the length', () => {
expect(
decodeArray(
new Uint8Array([
2, 0, 0, 0, // length
1, 2, // first
3, 4 // second
])
)
).toEqual({
length: 2,
data: new Uint8Array([1, 2, 3, 4])
});
});
it('decodes where array is an subarray', () => {
expect(
decodeArray(
new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, // padding
1, 0, 0, 0, // length
1, 2, 3, 4 // entry
]).subarray(8)
)
).toEqual({
length: 1,
data: new Uint8Array([1, 2, 3, 4])
});
});
});
@@ -1,18 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import u8aToBn from '@polkadot/util/u8a/toBn';
type DecodedArray = {
length: number,
data: Uint8Array
};
export default function decodeArray (input: Uint8Array): DecodedArray {
return {
// FIXME: This conversion is horrible, however Dataview on subarray yields wrong getUint32 value
length: u8aToBn(input.subarray(0, 4), true).toNumber(),
data: input.slice(4)
};
}
@@ -1,36 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import decodeU8a from './u8a';
describe('decodeU8a', () => {
it('decodes an input with the length', () => {
expect(
decodeU8a(
new Uint8Array([
4, 0, 0, 0, // length
1, 2, 3, 4, // data
5, 5, 5, 5 // extra
])
)
).toEqual(
new Uint8Array([1, 2, 3, 4])
);
});
it('decodes an subarray', () => {
expect(
decodeU8a(
new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, // padding
4, 0, 0, 0, // length
1, 2, 3, 4, // data
5, 5, 5, 5 // extra
]).subarray(8)
)
).toEqual(
new Uint8Array([1, 2, 3, 4])
);
});
});
@@ -1,12 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import u8aToBn from '@polkadot/util/u8a/toBn';
export default function decodeU8a (input: Uint8Array): Uint8Array {
// FIXME: This conversion is horrible, however Dataview on subarray yields wrong getUint32 value
const length = u8aToBn(input.subarray(0, 4), true).toNumber();
return input.slice(4, 4 + length);
}
@@ -1,22 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import encodeArray from './array';
describe('encodeArray', () => {
it('encodes an array with the length', () => {
expect(
encodeArray([
new Uint8Array([1, 2]),
new Uint8Array([3, 4])
])
).toEqual(
new Uint8Array([
2, 0, 0, 0, // length
1, 2, // first
3, 4 // second
])
);
});
});
@@ -1,18 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
export default function encodeArray (input: Array<Uint8Array>): Uint8Array {
const total = input.reduce((total, input) => total + input.length, 0);
const output = new Uint8Array(total + 4);
let offset = 4;
new DataView(output.buffer).setUint32(0, input.length, true);
return input.reduce((output, input) => {
output.set(input, offset);
offset += input.length;
return output;
}, output);
}
@@ -1,20 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import encodeU8a from './u8a';
describe('encodeU8a', () => {
it('encodes an input with the length', () => {
expect(
encodeU8a(
new Uint8Array([1, 2, 3, 4])
)
).toEqual(
new Uint8Array([
4, 0, 0, 0, // length
1, 2, 3, 4 // data
])
);
});
});
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
export default function encodeU8a (input: Uint8Array): Uint8Array {
const output = new Uint8Array(input.length + 4);
new DataView(output.buffer).setUint32(0, input.length, true);
output.set(input, 4);
return output;
}
@@ -1,47 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import createHeader from '../../create/header';
import { decodeHeader } from './index';
describe('decodeHeader', () => {
it('decodes properly', () => {
expect(
JSON.stringify(
decodeHeader(
new Uint8Array([
// parent_hash
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, 5,
// number
67, 0, 0, 0, 0, 0, 0, 0,
// state_root
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,
// transaction_root
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, 6,
// digest (length, log1, log2)
2, 0, 0, 0,
1, 0, 0, 0, 1,
1, 0, 0, 0, 2
])
)
)
).toEqual(
JSON.stringify(
createHeader({
digest: {
logs: [
new Uint8Array([1]),
new Uint8Array([2])
]
},
extrinsicsRoot: new Uint8Array([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, 6]),
number: 67,
parentHash: new Uint8Array([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, 5]),
stateRoot: new Uint8Array([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])
})
)
);
});
});
@@ -1,37 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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 BN from 'bn.js';
import createHeader from '../../create/header';
import decodeRaw from './decodeRaw';
import { OFF_PARENT_HASH, OFF_STATE_ROOT, OFF_TX_ROOT } from './offsets';
export default function decodeHeader (u8a: Uint8Array | null): Header {
// tslint:disable-next-line:variable-name
const { number, logs } = u8a
? decodeRaw(u8a)
: {
number: new BN(0),
logs: []
};
return createHeader({
digest: {
logs
},
extrinsicsRoot: u8a
? u8a.subarray(OFF_TX_ROOT, OFF_TX_ROOT + 32)
: new Uint8Array(),
number,
parentHash: u8a
? u8a.subarray(OFF_PARENT_HASH, OFF_PARENT_HASH + 32)
: new Uint8Array(),
stateRoot: u8a
? u8a.subarray(OFF_STATE_ROOT, OFF_STATE_ROOT + 32)
: new Uint8Array()
});
}
@@ -1,57 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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 decode from './decodeRaw';
describe('decodeRaw', () => {
it('returns the raw parts', () => {
expect(
JSON.stringify(
decode(
new Uint8Array([
// parent_hash
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, 5,
// number
67, 0, 0, 0, 0, 0, 0, 0,
// state_root
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,
// transaction_root
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, 6,
// digest (length, log1, log2)
2, 0, 0, 0,
1, 0, 0, 0, 1,
1, 0, 0, 0, 2,
// remainder
1, 2, 3, 4, 5, 4, 3, 2, 1
])
)
)
).toEqual(
JSON.stringify({
body: new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]),
header: new Uint8Array([
// parent_hash
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, 5,
// number
67, 0, 0, 0, 0, 0, 0, 0,
// state_root
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,
// transaction_root
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, 6,
// digest (length, log1, log2)
2, 0, 0, 0,
1, 0, 0, 0, 1,
1, 0, 0, 0, 2
]),
logs: [
new Uint8Array([1]),
new Uint8Array([2])
],
number: new BN(67)
})
);
});
});
@@ -1,39 +0,0 @@
// Copyright 2017-2018 @polkadot/primitives 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 u8aToBn from '@polkadot/util/u8a/toBn';
import decodeArray from '../decoder/array';
import decodeU8a from '../decoder/u8a';
import { OFF_DIGEST, OFF_NUMBER } from './offsets';
type DecodedRaw = {
body: Uint8Array,
header: Uint8Array,
logs: Array<Uint8Array>,
number: BN
};
export default function decodeHeader (u8a: Uint8Array): DecodedRaw {
const logs = [];
const dd = decodeArray(u8a.subarray(OFF_DIGEST));
let offset = 0;
for (let index = 0; index < dd.length; index++) {
const log = decodeU8a(dd.data.subarray(offset));
logs.push(log);
offset += log.length + 4;
}
return {
body: dd.data.subarray(offset),
header: u8a.subarray(0, OFF_DIGEST + offset + 4),
logs,
number: u8aToBn(u8a.subarray(OFF_NUMBER, OFF_NUMBER + 8), true)
};
}

Some files were not shown because too many files have changed in this diff Show More