Remove balances.freeBalance & system.accountNonce refs (#1847)

* Remove freeBalance references

* Cleanup placeholders

* Add substrate templates to .gitignore

* Swap all use of system.accountNonce

* typo
This commit is contained in:
Jaco Greeff
2020-02-14 13:52:45 +01:00
committed by GitHub
parent 679e31668e
commit 5c4920db6f
31 changed files with 95 additions and 1703 deletions
+1
View File
@@ -3,6 +3,7 @@ build/
build-docs/
coverage/
docs/.vuepress/dist/
docs/substrate/*.md
node_modules/
tmp/
.DS_Store
@@ -13,21 +13,23 @@ async function main () {
// Retrieve the initial balance. Since the call has no callback, it is simply a promise
// that resolves to the current on-chain value
let previous = await api.query.balances.freeBalance(Alice);
let [previousNonce, { free: previousFree }] = await api.query.system.account(Alice);
console.log(`${Alice} has a balance of ${previous}`);
console.log(`${Alice} has a balance of ${previousFree}, nonce ${previousNonce}`);
console.log(`You may leave this example running and start example 06 or transfer any value to ${Alice}`);
// Here we subscribe to any balance changes and update the on-screen value
api.query.balances.freeBalance(Alice, (current) => {
api.query.system.account(Alice, ([currentNonce, { free: currentFree }]) => {
// Calculate the delta
const change = current.sub(previous);
const change = currentFree.sub(previousFree);
// Only display positive value changes (Since we are pulling `previous` above already,
// the initial balance change will also be zero)
if (!change.isZero()) {
previous = current;
console.log(`New balance change of: ${change}`);
console.log(`New balance change of ${change}, nonce ${currentNonce}`);
previousFree = currentFree;
previousNonce = currentNonce;
}
});
}
@@ -15,8 +15,8 @@ async function main () {
console.log('Tracking balances for:', [ALICE, BOB]);
// Subscribe and listen to several balance changes
api.query.balances.freeBalance.multi([ALICE, BOB], (balances) => {
console.log('Change detected, new balances: ', balances);
api.query.system.account.multi([ALICE, BOB], (balances) => {
console.log('Change detected, new balances: ', balances.map(([, { free }]) => free));
});
}
@@ -12,8 +12,8 @@ async function main () {
const api = await ApiPromise.create();
// Make our basic chain state/storage queries, all in one go
const [accountNonce, now, validators] = await Promise.all([
api.query.system.accountNonce(ALICE),
const [[accountNonce], now, validators] = await Promise.all([
api.query.system.account(ALICE),
api.query.timestamp.now(),
api.query.session.validators()
]);
@@ -25,14 +25,15 @@ async function main () {
// Retrieve the balances for all validators
const validatorBalances = await Promise.all(
validators.map(authorityId =>
api.query.balances.freeBalance(authorityId)
api.query.system.account(authorityId)
)
);
// Print out the authorityIds and balances of all validators
console.log('validators', validators.map((authorityId, index) => ({
address: authorityId.toString(),
balance: validatorBalances[index].toString()
balance: validatorBalances[index][1].free.toString(),
nonce: validatorBalances[index][0].toString()
})));
}
}
@@ -19,14 +19,14 @@ async function main () {
// Retrieve the balance at the preceding block for Alice. For at queries
// the format is always `.at(<blockhash>, ...params)`
const balance = await api.query.balances.freeBalance.at(parentHash, ALICE);
const balance = await api.query.system.account.at(parentHash, ALICE);
console.log(`Alice's balance at ${parentHash.toHex()} was ${balance}`);
console.log(`Alice's balance at ${parentHash.toHex()} was ${balance[1].free}`);
// Now perform a multi query, returning multiple balances at once
const balances = await api.query.balances.freeBalance.multi([ALICE, BOB]);
const balances = await api.query.system.account.multi([ALICE, BOB]);
console.log(`Current balances for Alice and Bob are ${balances[0]} and ${balances[1]}`);
console.log(`Current balances for Alice and Bob are ${balances[0][1].free} and ${balances[1][1].free}`);
}
main().catch(console.error).finally(() => process.exit());
@@ -19,7 +19,7 @@ async function main () {
const alice = keyring.addFromUri('//Alice');
// Get nonce for account
const nonce = await api.query.system.accountNonce(alice.address);
const [nonce] = await api.query.system.account(alice.address);
// Get current block
const signedBlock = await api.rpc.chain.getBlock();
@@ -24,7 +24,7 @@ async function main () {
const keyring = testKeyring.default();
// Get the nonce for the admin key
const nonce = await api.query.system.accountNonce(ALICE);
const [nonce] = await api.query.system.account(ALICE);
// Find the actual keypair in the keyring
const alicePair = keyring.getPair(ALICE);
@@ -14,7 +14,7 @@ async function main () {
// Here we subscribe to any balance changes and update the on-screen value.
// We're using RxJs pairwise() operator to get the previous and current values as an array.
api.query.balances.freeBalance(Alice)
api.query.system.account(Alice)
.pipe(
// since pairwise only starts emitting values on the second emission, we prepend an
// initial value with the startWith() operator to be able to also receive the first value
@@ -25,12 +25,13 @@ async function main () {
if (balance[0] === 'first') {
// Now we know that if the previous value emitted as balance[0] is `first`,
// then balance[1] is the initial value of Alice account.
console.log(`Alice ${Alice} has a balance of ${balance[1]}`);
console.log(`Alice ${Alice} has a balance of ${balance[1][1].free}`);
console.log('You may leave this example running and start the "Make a transfer" example or transfer any value to Alice address');
return;
}
const change = balance[1].sub(balance[0]);
const change = balance[1][1].free.sub(balance[0][1].free);
// Only display value changes
if (!change.isZero()) {
console.log(`New balance change of: ${change}`);
+5 -4
View File
@@ -22,13 +22,13 @@ function main () {
// In the next step, we're checking if the node has active validators.
// If it does, we're making another call to the api to get the balances for all validators
const balances = (validators && validators.length > 0)
? combineLatest(validators.map(authorityId => api.query.balances.freeBalance(authorityId).pipe(first())))
? combineLatest(validators.map(authorityId => api.query.system.account(authorityId).pipe(first())))
: of(null);
// We're combining the results together with the emitted value 'validators',
// which we're turning back into an observable using of()
return combineLatest(
api.query.system.accountNonce(Alice).pipe(first()),
api.query.system.account(Alice).pipe(first()),
api.query.timestamp.blockPeriod().pipe(first()),
of(validators),
balances
@@ -36,7 +36,7 @@ function main () {
})
)
// Then we're subscribing to the emitted results
.subscribe(([accountNonce, blockPeriod, validators, validatorBalances]) => {
.subscribe(([[accountNonce], blockPeriod, validators, validatorBalances]) => {
console.log(`accountNonce(${Alice}) ${accountNonce}`);
console.log(`blockPeriod ${blockPeriod.toNumber()} seconds`);
@@ -44,7 +44,8 @@ function main () {
// And lastly we print out the authorityIds and balances of all validators
console.log('validators', validators.map((authorityId, index) => ({
address: authorityId.toString(),
balance: validatorBalances[index].toString()
balance: validatorBalances[index][1].free.toString(),
nonce: validatorBalances[index][0].toString()
})));
}
});
+6 -10
View File
@@ -16,24 +16,20 @@ const ADDR = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE';
// Retrieve the last timestamp
const now = await api.query.timestamp.now();
// Retrieve the account nonce via the system module
const nonce = await api.query.system.accountNonce(ADDR);
// Retrieve the account balance & nonce via the system module
const [nonce, balance] = await api.query.system.account(ADDR);
// Retrieve the account balance via the balances module
const balance = await api.query.balances.freeBalance(ADDR);
console.log(`${now}: balance of ${balance} and a nonce of ${nonce}`);
console.log(`${now}: balance of ${balance.free} and a nonce of ${nonce}`);
```
There have been some additions in the code above comparing with retrieving runtime constants. In these cases, since we are making a query to the actual chain, we use the `await` syntax to retrieve the information. Since the API is Promise-based, this means we can also rewrite the above to follow a Promise pattern,
```js
...
// Retrieve last block timestamp, account nonce & balance
const [now, nonce, balance] = await Promise.all([
// Retrieve last block timestamp, account nonce & balances
const [now, [nonce, balances]] = await Promise.all([
api.query.timestamp.now(),
api.query.system.accountNonce(ADDR),
api.query.balances.freeBalance(ADDR)
api.query.system.account(ADDR)
]);
```
+10 -11
View File
@@ -10,14 +10,14 @@ Where possible, the use of multi queries are encouraged since it tracks a number
...
// Subscribe to balance changes for 2 accounts, ADDR1 & ADDR2 (already defined)
const unsub = await api.query.balances.freeBalance.multi([ADDR1, ADDR2], (balances) => {
const [balance1, balance2] = balances;
const unsub = await api.query.system.account.multi([ADDR1, ADDR2], (balances) => {
const [[, balance1], [, balance2]] = balances;
console.log(`The balances are ${balance1} and ${balance2}`);
console.log(`The balances are ${balance1.free} and ${balance2.free}`);
});
```
A couple of items to note in the example above: we don't call `freeBalance` directly, but rather `freeBalance.multi`. We pass the addresses we want to query as an array, and the length thereof would depend on the number of addresses we want to query. As an extended example, we can track the balances of a list of validators,
A couple of items to note in the example above: we don't call `account` directly, but rather `account.multi`. We pass the addresses we want to query as an array, and the length thereof would depend on the number of addresses we want to query. As an extended example, we can track the balances of a list of validators,
```js
...
@@ -26,8 +26,8 @@ A couple of items to note in the example above: we don't call `freeBalance` dire
const validators = await api.query.session.validators();
// Subscribe to the balances for these accounts
const unsub = await api.query.balances.freeBalance.multi(validators, (balances) => {
console.log(`The balances are: ${balances}`);
const unsub = await api.query.balances.account.multi(validators, (balances) => {
console.log(`The nonce and free balances are: ${balances.map(([nonce, { free }]) => [nonce, free])}`);
});
```
@@ -43,17 +43,16 @@ The previous `.multi` examples assumes that we do queries for the same types, i.
// Subscribe to the timestamp, our index and balance
const unsub = await api.queryMulti([
api.query.timestamp.now,
[api.query.system.accountNonce, ADDR],
[api.query.balances.freeBalance, ADDR]
], ([now, nonce, balance]) => {
console.log(`${now}: balance of ${balance} and a nonce of ${nonce}`);
[api.query.system.account, ADDR]
], ([now, [nonce, balance]]) => {
console.log(`${now}: balance of ${balance.free} and a nonce of ${nonce}`);
});
```
The above example certainly does not quite look as ergonomic and clean, but the API needs to understand (a) which are all the calls we need to make and (b) the calls and their params (if required). So breaking it down -
- `api.query.timestamp.now` - the timestamp is passed naked without any params. Also note that we do not call it while passing, but rather only provides a reference to the function, i.e. we do not have the expected `()` at the end. (This could also be of the form `[api.query.timestamp.now]`, aligning with subsequent entries)
- `[api.query.system.accountNonce, ADDR]` - the nonce query is passed as an array containing the function (once again naked), followed by the parameters that apply.
- `[api.query.system.account, ADDR]` - the nonce & balance query is passed as an array containing the function (once again naked), followed by the parameters that apply.
## Rounding out queries
+8 -8
View File
@@ -13,13 +13,13 @@ Quite often is is useful (taking pruning into account, more on this later) to re
const lastHdr = await api.rpc.chain.getHeader();
// Retrieve the balance at both the current and the parent hashes
const [balanceNow, balancePrev] = await Promise.all([
api.query.balances.freeBalance.at(lastHdr.hash, ADDR),
api.query.balances.freeBalance.at(lastHdr.parentHash, ADDR)
const [[, balanceNow], [, balancePrev]] = await Promise.all([
api.query.system.account.at(lastHdr.hash, ADDR),
api.query.system.account.at(lastHdr.parentHash, ADDR)
]);
// Display the difference
console.log(`The delta was ${balanceNow.sub(balancePrev)}`);
console.log(`The delta was ${balanceNow.free.sub(balancePrev.free)}`);
```
In the above example, we introduce the `.at(<hash>[, ...params])` query. For all `.at` queries, the first parameter is always the block hash at which we want to make the query, in our example we use both the last retrieved block and the parent thereof. The params are optional as per the type of query made, for instance to retrieve the timestamp for a previous block, it would be -
@@ -44,8 +44,8 @@ In addition to using `api.query` to make actual on-chain queries, it can also be
// Retrieve the hash & size of the entry as stored on-chain
const [entryHash, entrySize] = await Promise.all([
api.query.balances.freeBalance.hash(ADDR),
api.query.balances.freeBalance.size(ADDR)
api.query.system.account.hash(ADDR),
api.query.system.account.size(ADDR)
]);
// Output the info
@@ -60,11 +60,11 @@ It has been explained that the `api.query` interfaces are decorated from the met
```js
// Extract the info
const { meta, method, section } = api.query.balances.freeBalance;
const { meta, method, section } = api.query.system.account;
// Display some info on a specific entry
console.log(`${section}.${method}: ${meta.documentation.join(' ')}`);
console.log(`query key: ${api.query.balances.freeBalance.key(ADDR)}`);
console.log(`query key: ${api.query.system.account.key(ADDR)}`);
```
The `section` & `method` is an indication of where it is exposed on the API. In addition the `meta` holds an array with the metadata documentation for the entry.
+2 -2
View File
@@ -25,8 +25,8 @@ If we had a query with parameters, i.e. where we wish to perform a query for a s
...
// Subscribe to balance changes for our account
const unsub = await api.query.balances.freeBalance(ADDR, (balance) => {
console.log(`Your account balance is ${balance}`);
const unsub = await api.query.system.account(ADDR, ([nonce, balance]) => {
console.log(`free balance is ${balance.freee} with ${balance.reserved} reserved and a nonce of ${nonce}`);
});
```
+2 -2
View File
@@ -8,8 +8,8 @@ To unpack this, we will start with the Metadata and explain what it actually pro
When the API connects to a node, one of the first things it does is to retrieve the metadata. The metadata, effectively provides data in the form of `api.<type>.<module>.<section>` that fits into one of the following categories -
- [consts](../substrate/constants.md) - All runtime constants, e.g. `api.consts.balances.creationFee`. These are not functions, rather accessing the endpoint immediately yields the result as defined.
- [query](../substrate/storage.md) - All chain state, e.g. `api.query.balances.freeBalance(<accountId>)`.
- [consts](../substrate/constants.md) - All runtime constants, e.g. `api.consts.balances.existentialDeposit`. These are not functions, rather accessing the endpoint immediately yields the result as defined.
- [query](../substrate/storage.md) - All chain state, e.g. `api.query.system.account(<accountId>)`.
- [tx](../substrate/extrinsics.md) - All extrinsics, e.g. `api.tx.balances.transfer(<accountId>, <value>)`.
Additionally the metadata also provides information on [events](../substrate/events.md), these are query-able via the `api.query.system.events()` interface and also appear on transactions... both these cases are detailed later.
+2 -3
View File
@@ -30,11 +30,10 @@ For any interface injected by metadata, the types are not available by default (
However, to make this sane from a developer perspective the injected methods are generic, effectively making the following possible -
```js
import { Balance, Index } from '@polkadot/types/interfaces';
import { AccountData, Index } from '@polkadot/types/interfaces';
...
const nonce = await api.query.system.accountNonce<Index>(ADDR);
const balance = await api.query.balances.freeBalance<Balance>(ADDR);
const [nonce, balance] = await api.query.system.account<[Index, AccountData]>(ADDR);
```
In both these case we can instruct the TypeScript compiler that the type we are expecting in `Index` and `Balance` respectively, not just pure `Codec`. This means that functions like `.toNumber()` is available on both these types - as opposed to just the [general type defaults](types.basics.md#everything-is-a-type) with `.toHex()` and friends.
+1 -225
View File
@@ -1,225 +1 @@
## Constants
The following sections contain the module constants, also known as parameter types. These can only be changed as part of a runtime upgrade. On the api, these are exposed via `api.consts.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[babe](#babe)**
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[finalityTracker](#finalityTracker)**
- **[session](#session)**
- **[staking](#staking)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
___
### babe
▸ **epochDuration**: `u64`
- **summary**: The number of **slots** that an epoch takes. We couple sessions to epochs, i.e. we start a new session once the new epoch begins.
▸ **expectedBlockTime**: `Moment`
- **summary**: The expected average block time at which BABE should be creating blocks. Since BABE is probabilistic it is not trivial to figure out what the expected average block time should be based on the slot duration and the security parameter `c` (where `1 - c` represents the probability of a slot being empty).
___
### balances
▸ **creationFee**: `Balance`
- **summary**: The fee required to create an account.
▸ **existentialDeposit**: `Balance`
- **summary**: The minimum amount required to keep an account open.
▸ **transactionBaseFee**: `Balance`
- **summary**: The fee to be paid for making a transaction; the base.
▸ **transactionByteFee**: `Balance`
- **summary**: The fee to be paid for making a transaction; the per-byte portion.
▸ **transferFee**: `Balance`
- **summary**: The fee required to make a transfer.
___
### contracts
▸ **blockGasLimit**: `Gas`
- **summary**: The maximum amount of gas that could be expended per block. A reasonable default value is 10_000_000.
▸ **callBaseFee**: `Gas`
- **summary**: The base fee charged for calling into a contract. A reasonable default value is 135.
▸ **contractFee**: `BalanceOf`
- **summary**: The fee required to instantiate a contract instance. A reasonable default value is 21.
▸ **creationFee**: `BalanceOf`
- **summary**: The fee required to create an account.
▸ **instantiateBaseFee**: `Gas`
- **summary**: The base fee charged for instantiating a contract. A reasonable default value is 175.
▸ **maxDepth**: `u32`
- **summary**: The maximum nesting level of a call/instantiate stack. A reasonable default value is 100.
▸ **maxValueSize**: `u32`
- **summary**: The maximum size of a storage value in bytes. A reasonable default is 16 KiB.
▸ **rentByteFee**: `BalanceOf`
- **summary**: Price of a byte of storage per one block interval. Should be greater than 0.
▸ **rentDepositOffset**: `BalanceOf`
- **summary**: The amount of funds a contract should deposit in order to offset the cost of one byte. Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day, then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent. But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000, then it would pay 500 BU/day.
▸ **signedClaimHandicap**: `BlockNumber`
- **summary**: Number of block delay an extrinsic claim surcharge has. When claim surcharge is called by an extrinsic the rent is checked for current_block - delay
▸ **storageSizeOffset**: `u32`
- **summary**: Size of a contract at the time of instantiaion. This is a simple way to ensure that empty contracts eventually gets deleted.
▸ **surchargeReward**: `BalanceOf`
- **summary**: Reward that is received by the party whose touch has led to removal of a contract.
▸ **tombstoneDeposit**: `BalanceOf`
- **summary**: The minimum amount required to generate a tombstone.
▸ **transactionBaseFee**: `BalanceOf`
- **summary**: The fee to be paid for making a transaction; the base.
▸ **transactionByteFee**: `BalanceOf`
- **summary**: The fee to be paid for making a transaction; the per-byte portion.
▸ **transferFee**: `BalanceOf`
- **summary**: The fee required to make a transfer.
___
### democracy
▸ **cooloffPeriod**: `BlockNumber`
- **summary**: Period in blocks where an external proposal may not be re-submitted after being vetoed.
▸ **emergencyVotingPeriod**: `BlockNumber`
- **summary**: Minimum voting period allowed for an emergency referendum.
▸ **enactmentPeriod**: `BlockNumber`
- **summary**: The minimum period of locking and the period between a proposal being approved and enacted. It should generally be a little more than the unstake period to ensure that voting stakers have an opportunity to remove themselves from the system in the case where they are on the losing side of a vote.
▸ **launchPeriod**: `BlockNumber`
- **summary**: How often (in blocks) new public referenda are launched.
▸ **minimumDeposit**: `BalanceOf`
- **summary**: The minimum amount to be used as a deposit for a public referendum proposal.
▸ **votingPeriod**: `BlockNumber`
- **summary**: How often (in blocks) to check for new votes.
___
### elections
▸ **approvalSetSize**: `u32`
- **summary**: The chunk size of the approval vector.
▸ **candidacyBond**: `BalanceOf`
- **summary**: How much should be locked up in order to submit one's candidacy. A reasonable default value is 9.
▸ **carryCount**: `u32`
- **summary**: How many runners-up should have their approvals persist until the next vote. A reasonable default value is 2.
▸ **decayRatio**: `u32`
- **summary**: Decay factor of weight when being accumulated. It should typically be set to __at least__ `membership_size -1` to keep the collective secure. When set to `N`, it indicates `(1/N)^t` of staked is decayed at weight increment step `t`. 0 will result in no weight being added at all (normal approval voting). A reasonable default value is 24.
▸ **inactiveGracePeriod**: `VoteIndex`
- **summary**: How many vote indices need to go by after a target voter's last vote before they can be reaped if their approvals are moot. A reasonable default value is 1.
▸ **minimumVotingLock**: `BalanceOf`
- **summary**: Minimum about that can be used as the locked value for voting.
▸ **presentSlashPerVoter**: `BalanceOf`
- **summary**: The punishment, per voter, if you provide an invalid presentation. A reasonable default value is 1.
▸ **voterSetSize**: `u32`
- **summary**: The chunk size of the voter vector.
▸ **votingBond**: `BalanceOf`
- **summary**: How much should be locked up in order to be able to submit votes.
▸ **votingFee**: `BalanceOf`
- **summary**: The amount of fee paid upon each vote submission, unless if they submit a _hole_ index and replace it.
▸ **votingPeriod**: `BlockNumber`
- **summary**: How often (in blocks) to check for new votes. A reasonable default value is 1000.
___
### finalityTracker
▸ **reportLatency**: `BlockNumber`
- **summary**: The delay after which point things become suspicious. Default is 1000.
▸ **windowSize**: `BlockNumber`
- **summary**: The number of recent samples to keep from this chain. Default is 101.
___
### session
▸ **dedupKeyPrefix**: `Bytes`
- **summary**: Used as first key for `NextKeys` and `KeyOwner` to put all the data into the same branch of the trie.
___
### staking
▸ **bondingDuration**: `EraIndex`
- **summary**: Number of eras that staked funds must remain bonded for.
▸ **sessionsPerEra**: `SessionIndex`
- **summary**: Number of sessions per era.
___
### timestamp
▸ **minimumPeriod**: `Moment`
- **summary**: The minimum period between blocks. Beware that this is different to the *expected* period that the block production apparatus provides. Your chosen consensus system will generally work with this to determine a sensible block time. e.g. For Aura, it will be double this period on default settings.
___
### treasury
▸ **burn**: `Permill`
- **summary**: Percentage of spare funds (if any) that are burnt per spend period.
▸ **proposalBond**: `Permill`
- **summary**: Fraction of a proposal's value that should be bonded in order to place the proposal. An accepted proposal gets these back. A rejected proposal does not.
▸ **proposalBondMinimum**: `BalanceOf`
- **summary**: Minimum amount of funds that should be placed in a deposit for making a proposal.
▸ **spendPeriod**: `BlockNumber`
- **summary**: Period between successive spends.
_placeholder_
+1
View File
@@ -0,0 +1 @@
_placeholder_
+1 -298
View File
@@ -1,298 +1 @@
## Events
Events are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[council](#council)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[grandpa](#grandpa)**
- **[imOnline](#imOnline)**
- **[indices](#indices)**
- **[offences](#offences)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[technicalCommittee](#technicalCommittee)**
- **[technicalMembership](#technicalMembership)**
- **[treasury](#treasury)**
- **[utility](#utility)**
___
### balances
▸ **NewAccount**(`AccountId`, `Balance`)
- **summary**: A new account was created.
▸ **ReapedAccount**(`AccountId`)
- **summary**: An account was reaped.
▸ **Transfer**(`AccountId`, `AccountId`, `Balance`, `Balance`)
- **summary**: Transfer succeeded (from, to, value, fees).
___
### contracts
▸ **CodeStored**(`Hash`)
- **summary**: Code with the specified hash has been stored.
▸ **Contract**(`AccountId`, `Bytes`)
- **summary**: An event from contract of account.
▸ **Dispatched**(`AccountId`, `bool`)
- **summary**: A call was dispatched from the given account. The bool signals whether it was successful execution or not.
▸ **Instantiated**(`AccountId`, `AccountId`)
- **summary**: Contract deployed by address at the specified address.
▸ **ScheduleUpdated**(`u32`)
- **summary**: Triggered when the current schedule is updated.
▸ **Transfer**(`AccountId`, `AccountId`, `Balance`)
- **summary**: Transfer happened `from` to `to` with given `value` as part of a `call` or `instantiate`.
___
### council
▸ **Approved**(`Hash`)
- **summary**: A motion was approved by the required threshold.
▸ **Disapproved**(`Hash`)
- **summary**: A motion was not approved by the required threshold.
▸ **Executed**(`Hash`, `bool`)
- **summary**: A motion was executed; `bool` is true if returned without error.
▸ **MemberExecuted**(`Hash`, `bool`)
- **summary**: A single member did some action; `bool` is true if returned without error.
▸ **Proposed**(`AccountId`, `ProposalIndex`, `Hash`, `MemberCount`)
- **summary**: A motion (given hash) has been proposed (by given account) with a threshold (given `MemberCount`).
▸ **Voted**(`AccountId`, `Hash`, `bool`, `MemberCount`, `MemberCount`)
- **summary**: A motion (given hash) has been voted on by given account, leaving a tally (yes votes and no votes given respectively as `MemberCount`).
___
### democracy
▸ **Cancelled**(`ReferendumIndex`)
▸ **Delegated**(`AccountId`, `AccountId`)
▸ **Executed**(`ReferendumIndex`, `bool`)
▸ **ExternalTabled**()
▸ **NotPassed**(`ReferendumIndex`)
▸ **Passed**(`ReferendumIndex`)
▸ **Proposed**(`PropIndex`, `Balance`)
▸ **Started**(`ReferendumIndex`, `VoteThreshold`)
▸ **Tabled**(`PropIndex`, `Balance`, `Vec<AccountId>`)
▸ **Undelegated**(`AccountId`)
▸ **Vetoed**(`AccountId`, `Hash`, `BlockNumber`)
___
### elections
▸ **BadReaperSlashed**(`AccountId`)
- **summary**: slashed reaper
▸ **TallyFinalized**(`Vec<AccountId>`, `Vec<AccountId>`)
- **summary**: A tally (for approval votes of seat(s)) has ended (with one or more new members).
▸ **TallyStarted**(`u32`)
- **summary**: A tally (for approval votes of seat(s)) has started.
▸ **VoterReaped**(`AccountId`, `AccountId`)
- **summary**: reaped voter, reaper
___
### grandpa
▸ **NewAuthorities**(`Vec<(AuthorityId,AuthorityWeight)>`)
- **summary**: New authority set has been applied.
▸ **Paused**()
- **summary**: Current authority set has been paused.
▸ **Resumed**()
- **summary**: Current authority set has been resumed.
___
### imOnline
▸ **HeartbeatReceived**(`AuthorityId`)
- **summary**: A new heartbeat was received from `AuthorityId`
___
### indices
▸ **NewAccountIndex**(`AccountId`, `AccountIndex`)
- **summary**: A new account index was assigned. This event is not triggered when an existing index is reassigned to another `AccountId`.
___
### offences
▸ **Offence**(`Kind`, `OpaqueTimeSlot`)
- **summary**: There is an offence reported of the given `kind` happened at the `session_index` and (kind-specific) time slot. This event is not deposited for duplicate slashes.
___
### session
▸ **NewSession**(`SessionIndex`)
- **summary**: New session has happened. Note that the argument is the session index, not the block number as the type might suggest.
___
### staking
▸ **OldSlashingReportDiscarded**(`SessionIndex`)
- **summary**: An old slashing report from a prior era was discarded because it could not be processed.
▸ **Reward**(`Balance`)
- **summary**: All validators have been rewarded by the given balance.
▸ **Slash**(`AccountId`, `Balance`)
- **summary**: One validator (and its nominators) has been slashed by the given amount.
___
### sudo
▸ **KeyChanged**(`AccountId`)
- **summary**: The sudoer just switched identity; the old key is supplied.
▸ **Sudid**(`bool`)
- **summary**: A sudo just took place.
▸ **SudoAsDone**(`bool`)
- **summary**: A sudo just took place.
___
### system
▸ **ExtrinsicFailed**(`DispatchError`)
- **summary**: An extrinsic failed.
▸ **ExtrinsicSuccess**()
- **summary**: An extrinsic completed successfully.
___
### technicalCommittee
▸ **Approved**(`Hash`)
- **summary**: A motion was approved by the required threshold.
▸ **Disapproved**(`Hash`)
- **summary**: A motion was not approved by the required threshold.
▸ **Executed**(`Hash`, `bool`)
- **summary**: A motion was executed; `bool` is true if returned without error.
▸ **MemberExecuted**(`Hash`, `bool`)
- **summary**: A single member did some action; `bool` is true if returned without error.
▸ **Proposed**(`AccountId`, `ProposalIndex`, `Hash`, `MemberCount`)
- **summary**: A motion (given hash) has been proposed (by given account) with a threshold (given `MemberCount`).
▸ **Voted**(`AccountId`, `Hash`, `bool`, `MemberCount`, `MemberCount`)
- **summary**: A motion (given hash) has been voted on by given account, leaving a tally (yes votes and no votes given respectively as `MemberCount`).
___
### technicalMembership
▸ **Dummy**(`PhantomData`)
- **summary**: Phantom member, never used.
▸ **MemberAdded**()
- **summary**: The given member was added; see the transaction for who.
▸ **MemberRemoved**()
- **summary**: The given member was removed; see the transaction for who.
▸ **MembersReset**()
- **summary**: The membership was reset; see the transaction for who the new set is.
▸ **MembersSwapped**()
- **summary**: Two members were swapped; see the transaction for who.
___
### treasury
▸ **Awarded**(`ProposalIndex`, `Balance`, `AccountId`)
- **summary**: Some funds have been allocated.
▸ **Burnt**(`Balance`)
- **summary**: Some of our funds have been burnt.
▸ **Proposed**(`ProposalIndex`)
- **summary**: New proposal.
▸ **Rollover**(`Balance`)
- **summary**: Spending has finished; this is the amount that rolls over until next spend.
▸ **Spending**(`Balance`)
- **summary**: We have ended a spend period and will now allocate funds.
___
### utility
▸ **BatchExecuted**(`Vec<DispatchResult>`)
_placeholder_
+1 -370
View File
@@ -1,370 +1 @@
## Extrinsics
The following sections contain Extrinsics methods are part of the default Substrate runtime. On the api, these are exposed via `api.tx.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[authorship](#authorship)**
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[council](#council)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[finalityTracker](#finalityTracker)**
- **[grandpa](#grandpa)**
- **[imOnline](#imOnline)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[technicalCommittee](#technicalCommittee)**
- **[technicalMembership](#technicalMembership)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
- **[utility](#utility)**
___
### authorship
▸ **setUncles**(new_uncles: `Vec<Header>`)
- **summary**: Provide a set of uncles.
___
### balances
▸ **forceTransfer**(source: `Address`, dest: `Address`, value: `Compact<Balance>`)
- **summary**: Exactly as `transfer`, except the origin must be root and the source account may be specified.
▸ **setBalance**(who: `Address`, new_free: `Compact<Balance>`, new_reserved: `Compact<Balance>`)
- **summary**: Set the balances of a given account. This will alter `FreeBalance` and `ReservedBalance` in storage. it will also decrease the total issuance of the system (`TotalIssuance`). If the new free or reserved balance is below the existential deposit, it will reset the account nonce (`system::AccountNonce`). The dispatch origin for this call is `root`. # <weight> - Independent of the arguments. - Contains a limited number of reads and writes. # </weight>
▸ **transfer**(dest: `Address`, value: `Compact<Balance>`)
- **summary**: Transfer some liquid free balance to another account. `transfer` will set the `FreeBalance` of the sender and receiver. It will decrease the total issuance of the system by the `TransferFee`. If the sender's account is below the existential deposit as a result of the transfer, the account will be reaped. The dispatch origin for this call must be `Signed` by the transactor. # <weight> - Dependent on arguments but not critical, given proper implementations for input config types. See related functions below. - It contains a limited number of reads and writes internally and no complex computation. Related functions: - `ensure_can_withdraw` is always called internally but has a bounded complexity. - Transferring balances to accounts that did not exist before will cause `T::OnNewAccount::on_new_account` to be called. - Removing enough funds from an account will trigger `T::DustRemoval::on_unbalanced` and `T::OnFreeBalanceZero::on_free_balance_zero`. # </weight>
___
### contracts
▸ **call**(dest: `Address`, value: `Compact<BalanceOf>`, gas_limit: `Compact<Gas>`, data: `Bytes`)
- **summary**: Makes a call to an account, optionally transferring some balance. * If the account is a smart-contract account, the associated code will be executed and any value will be transferred. * If the account is a regular account, any value will be transferred. * If no account exists and the call value is not less than `existential_deposit`, a regular account will be created and any value will be transferred.
▸ **claimSurcharge**(dest: `AccountId`, aux_sender: `Option<AccountId>`)
- **summary**: Allows block producers to claim a small reward for evicting a contract. If a block producer fails to do so, a regular users will be allowed to claim the reward. If contract is not evicted as a result of this call, no actions are taken and the sender is not eligible for the reward.
▸ **instantiate**(endowment: `Compact<BalanceOf>`, gas_limit: `Compact<Gas>`, code_hash: `CodeHash`, data: `Bytes`)
- **summary**: Instantiates a new contract from the `codehash` generated by `put_code`, optionally transferring some balance. Instantiation is executed as follows: - The destination address is computed based on the sender and hash of the code. - The smart-contract account is created at the computed address. - The `ctor_code` is executed in the context of the newly-created account. Buffer returned after the execution is saved as the `code` of the account. That code will be invoked upon any call received by this account. - The contract is initialized.
▸ **putCode**(gas_limit: `Compact<Gas>`, code: `Bytes`)
- **summary**: Stores the given binary Wasm code into the chain's storage and returns its `codehash`. You can instantiate contracts only with stored code.
▸ **updateSchedule**(schedule: `Schedule`)
- **summary**: Updates the schedule for metering contracts. The schedule must have a greater version than the stored schedule.
___
### council
▸ **execute**(proposal: `Proposal`)
- **summary**: Dispatch a proposal from a member using the `Member` origin. Origin must be a member of the collective.
▸ **propose**(threshold: `Compact<MemberCount>`, proposal: `Proposal`)
- **summary**: # <weight> - Bounded storage reads and writes. - Argument `threshold` has bearing on weight. # </weight>
▸ **setMembers**(new_members: `Vec<AccountId>`)
- **summary**: Set the collective's membership manually to `new_members`. Be nice to the chain and provide it pre-sorted. Requires root origin.
▸ **vote**(proposal: `Hash`, index: `Compact<ProposalIndex>`, approve: `bool`)
- **summary**: # <weight> - Bounded storage read and writes. - Will be slightly heavier if the proposal is approved / disapproved after the vote. # </weight>
___
### democracy
▸ **cancelQueued**(when: `Compact<BlockNumber>`, which: `Compact<u32>`, what: `Compact<ReferendumIndex>`)
- **summary**: Cancel a proposal queued for enactment.
▸ **cancelReferendum**(ref_index: `Compact<ReferendumIndex>`)
- **summary**: Remove a referendum.
▸ **delegate**(to: `AccountId`, conviction: `Conviction`)
- **summary**: Delegate vote. # <weight> - One extra DB entry. # </weight>
▸ **emergencyCancel**(ref_index: `ReferendumIndex`)
- **summary**: Schedule an emergency cancellation of a referendum. Cannot happen twice to the same referendum.
▸ **externalPropose**(proposal: `Proposal`)
- **summary**: Schedule a referendum to be tabled once it is legal to schedule an external referendum.
▸ **externalProposeDefault**(proposal: `Proposal`)
- **summary**: Schedule a negative-turnout-bias referendum to be tabled next once it is legal to schedule an external referendum. Unlike `external_propose`, blacklisting has no effect on this and it may replace a pre-scheduled `external_propose` call.
▸ **externalProposeMajority**(proposal: `Proposal`)
- **summary**: Schedule a majority-carries referendum to be tabled next once it is legal to schedule an external referendum. Unlike `external_propose`, blacklisting has no effect on this and it may replace a pre-scheduled `external_propose` call.
▸ **fastTrack**(proposal_hash: `Hash`, voting_period: `BlockNumber`, delay: `BlockNumber`)
- **summary**: Schedule the currently externally-proposed majority-carries referendum to be tabled immediately. If there is no externally-proposed referendum currently, or if there is one but it is not a majority-carries referendum then it fails. - `proposal_hash`: The hash of the current external proposal. - `voting_period`: The period that is allowed for voting on this proposal. - `delay`: The number of block after voting has ended in approval and this should be enacted. Increased to `EmergencyVotingPeriod` if too low.
▸ **propose**(proposal: `Proposal`, value: `Compact<BalanceOf>`)
- **summary**: Propose a sensitive action to be taken. # <weight> - O(1). - Two DB changes, one DB entry. # </weight>
▸ **proxyVote**(ref_index: `Compact<ReferendumIndex>`, vote: `Vote`)
- **summary**: Vote in a referendum on behalf of a stash. If `vote.is_aye()`, the vote is to enact the proposal; otherwise it is a vote to keep the status quo. # <weight> - O(1). - One DB change, one DB entry. # </weight>
▸ **removeProxy**(proxy: `AccountId`)
- **summary**: Clear the proxy. Called by the stash. # <weight> - One DB clear. # </weight>
▸ **resignProxy**()
- **summary**: Clear the proxy. Called by the proxy. # <weight> - One DB clear. # </weight>
▸ **second**(proposal: `Compact<PropIndex>`)
- **summary**: Propose a sensitive action to be taken. # <weight> - O(1). - One DB entry. # </weight>
▸ **setProxy**(proxy: `AccountId`)
- **summary**: Specify a proxy. Called by the stash. # <weight> - One extra DB entry. # </weight>
▸ **undelegate**()
- **summary**: Undelegate vote. # <weight> - O(1). # </weight>
▸ **vetoExternal**(proposal_hash: `Hash`)
- **summary**: Veto and blacklist the external proposal hash.
▸ **vote**(ref_index: `Compact<ReferendumIndex>`, vote: `Vote`)
- **summary**: Vote in a referendum. If `vote.is_aye()`, the vote is to enact the proposal; otherwise it is a vote to keep the status quo. # <weight> - O(1). - One DB change, one DB entry. # </weight>
___
### elections
▸ **presentWinner**(candidate: `Address`, total: `Compact<BalanceOf>`, index: `Compact<VoteIndex>`)
- **summary**: Claim that `candidate` is one of the top `carry_count + desired_seats` candidates. Only works iff the presentation period is active. `candidate` should have at least collected some non-zero `total` votes and `origin` must have enough funds to pay for a potential slash. # <weight> - O(voters) compute. - One DB change. # </weight>
▸ **proxySetApprovals**(votes: `Vec<bool>`, index: `Compact<VoteIndex>`, hint: `SetIndex`, value: `Compact<BalanceOf>`)
- **summary**: Set candidate approvals from a proxy. Approval slots stay valid as long as candidates in those slots are registered. # <weight> - Same as `set_approvals` with one additional storage read. # </weight>
▸ **reapInactiveVoter**(reporter_index: `Compact<u32>`, who: `Address`, who_index: `Compact<u32>`, assumed_vote_index: `Compact<VoteIndex>`)
- **summary**: Remove a voter. For it not to be a bond-consuming no-op, all approved candidate indices must now be either unregistered or registered to a candidate that registered the slot after the voter gave their last approval set. Both indices must be provided as explained in [`voter_at`] function. May be called by anyone. Returns the voter deposit to `signed`. # <weight> - O(1). - Two fewer DB entries, one DB change. # </weight>
▸ **removeMember**(who: `Address`)
- **summary**: Remove a particular member from the set. This is effective immediately. Note: A tally should happen instantly (if not already in a presentation period) to fill the seat if removal means that the desired members are not met.
▸ **retractVoter**(index: `Compact<u32>`)
- **summary**: Remove a voter. All votes are cancelled and the voter deposit is returned. The index must be provided as explained in [`voter_at`] function. Also removes the lock on the balance of the voter. See [`do_set_approvals()`]. # <weight> - O(1). - Two fewer DB entries, one DB change. # </weight>
▸ **setApprovals**(votes: `Vec<bool>`, index: `Compact<VoteIndex>`, hint: `SetIndex`, value: `Compact<BalanceOf>`)
- **summary**: Set candidate approvals. Approval slots stay valid as long as candidates in those slots are registered. Locks `value` from the balance of `origin` indefinitely. Only [`retract_voter`] or [`reap_inactive_voter`] can unlock the balance. `hint` argument is interpreted differently based on: - if `origin` is setting approvals for the first time: The index will be checked for being a valid _hole_ in the voter list. - if the hint is correctly pointing to a hole, no fee is deducted from `origin`. - Otherwise, the call will succeed but the index is ignored and simply a push to the last chunk with free space happens. If the new push causes a new chunk to be created, a fee indicated by [`VotingFee`] is deducted. - if `origin` is already a voter: the index __must__ be valid and point to the correct position of the `origin` in the current voters list. Note that any trailing `false` votes in `votes` is ignored; In approval voting, not voting for a candidate and voting false, are equal. # <weight> - O(1). - Two extra DB entries, one DB change. - Argument `votes` is limited in length to number of candidates. # </weight>
▸ **setDesiredSeats**(count: `Compact<u32>`)
- **summary**: Set the desired member count; if lower than the current count, then seats will not be up election when they expire. If more, then a new vote will be started if one is not already in progress.
▸ **setPresentationDuration**(count: `Compact<BlockNumber>`)
- **summary**: Set the presentation duration. If there is currently a vote being presented for, will invoke `finalize_vote`.
▸ **setTermDuration**(count: `Compact<BlockNumber>`)
- **summary**: Set the presentation duration. If there is current a vote being presented for, will invoke `finalize_vote`.
▸ **submitCandidacy**(slot: `Compact<u32>`)
- **summary**: Submit oneself for candidacy. Account must have enough transferrable funds in it to pay the bond. NOTE: if `origin` has already assigned approvals via [`set_approvals`], it will NOT have any usable funds to pass candidacy bond and must first retract. Note that setting approvals will lock the entire balance of the voter until retraction or being reported. # <weight> - Independent of input. - Three DB changes. # </weight>
___
### finalityTracker
▸ **finalHint**(hint: `Compact<BlockNumber>`)
- **summary**: Hint that the author of this block thinks the best finalized block is the given number.
___
### grandpa
▸ **reportMisbehavior**(_report: `Bytes`)
- **summary**: Report some misbehavior.
___
### imOnline
▸ **heartbeat**(heartbeat: `Heartbeat`, signature: `Signature`)
___
### session
▸ **setKeys**(keys: `Keys`, proof: `Bytes`)
- **summary**: Sets the session key(s) of the function caller to `key`. Allows an account to set its session key prior to becoming a validator. This doesn't take effect until the next session. The dispatch origin of this function must be signed. # <weight> - O(log n) in number of accounts. - One extra DB entry. # </weight>
___
### staking
▸ **bond**(controller: `Address`, value: `Compact<BalanceOf>`, payee: `RewardDestination`)
- **summary**: Take the origin account as a stash and lock up `value` of its balance. `controller` will be the account that controls it. `value` must be more than the `minimum_balance` specified by `T::Currency`. The dispatch origin for this call must be _Signed_ by the stash account. # <weight> - Independent of the arguments. Moderate complexity. - O(1). - Three extra DB entries. NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned unless the `origin` falls below _existential deposit_ and gets removed as dust. # </weight>
▸ **bondExtra**(max_additional: `Compact<BalanceOf>`)
- **summary**: Add some extra amount that have appeared in the stash `free_balance` into the balance up for staking. Use this if there are additional funds in your stash account that you wish to bond. Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount that can be added. The dispatch origin for this call must be _Signed_ by the stash, not the controller. # <weight> - Independent of the arguments. Insignificant complexity. - O(1). - One DB entry. # </weight>
▸ **chill**()
- **summary**: Declare no desire to either validate or nominate. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - Independent of the arguments. Insignificant complexity. - Contains one read. - Writes are limited to the `origin` account key. # </weight>
▸ **forceNewEra**()
- **summary**: Force there to be a new era at the end of the next session. After this, it will be reset to normal (non-forced) behaviour. # <weight> - No arguments. # </weight>
▸ **forceNoEras**()
- **summary**: Force there to be no new eras indefinitely. # <weight> - No arguments. # </weight>
▸ **nominate**(targets: `Vec<Address>`)
- **summary**: Declare the desire to nominate `targets` for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - The transaction's complexity is proportional to the size of `targets`, which is capped at `MAX_NOMINATIONS`. - Both the reads and writes follow a similar pattern. # </weight>
▸ **setController**(controller: `Address`)
- **summary**: (Re-)set the controller of a stash. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the stash, not the controller. # <weight> - Independent of the arguments. Insignificant complexity. - Contains a limited number of reads. - Writes are limited to the `origin` account key. # </weight>
▸ **setInvulnerables**(validators: `Vec<AccountId>`)
- **summary**: Set the validators who cannot be slashed (if any).
▸ **setPayee**(payee: `RewardDestination`)
- **summary**: (Re-)set the payment target for a controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - Independent of the arguments. Insignificant complexity. - Contains a limited number of reads. - Writes are limited to the `origin` account key. # </weight>
▸ **setValidatorCount**(new: `Compact<u32>`)
- **summary**: The ideal number of validators.
▸ **unbond**(value: `Compact<BalanceOf>`)
- **summary**: Schedule a portion of the stash to be unlocked ready for transfer out after the bond period ends. If this leaves an amount actively bonded less than T::Currency::minimum_balance(), then it is increased to the full amount. Once the unlock period is done, you can call `withdraw_unbonded` to actually move the funds out of management ready for transfer. No more than a limited number of unlocking chunks (see `MAX_UNLOCKING_CHUNKS`) can co-exists at the same time. In that case, [`Call::withdraw_unbonded`] need to be called first to remove some of the chunks (if possible). The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::withdraw_unbonded`]. # <weight> - Independent of the arguments. Limited but potentially exploitable complexity. - Contains a limited number of reads. - Each call (requires the remainder of the bonded balance to be above `minimum_balance`) will cause a new entry to be inserted into a vector (`Ledger.unlocking`) kept in storage. The only way to clean the aforementioned storage item is also user-controlled via `withdraw_unbonded`. - One DB entry. </weight>
▸ **validate**(prefs: `ValidatorPrefs`)
- **summary**: Declare the desire to validate for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - Independent of the arguments. Insignificant complexity. - Contains a limited number of reads. - Writes are limited to the `origin` account key. # </weight>
▸ **withdrawUnbonded**()
- **summary**: Remove any unlocked chunks from the `unlocking` queue from our management. This essentially frees up that balance to be used by the stash account to do whatever it wants. The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::unbond`]. # <weight> - Could be dependent on the `origin` argument and how much `unlocking` chunks exist. It implies `consolidate_unlocked` which loops over `Ledger.unlocking`, which is indirectly user-controlled. See [`unbond`] for more detail. - Contains a limited number of reads, yet the size of which could be large based on `ledger`. - Writes are limited to the `origin` account key. # </weight>
___
### sudo
▸ **setKey**(new: `Address`)
- **summary**: Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key. The dispatch origin for this call must be _Signed_. # <weight> - O(1). - Limited storage reads. - One DB change. # </weight>
▸ **sudo**(proposal: `Proposal`)
- **summary**: Authenticates the sudo key and dispatches a function call with `Root` origin. The dispatch origin for this call must be _Signed_. # <weight> - O(1). - Limited storage reads. - One DB write (event). - Unknown weight of derivative `proposal` execution. # </weight>
▸ **sudoAs**(who: `Address`, proposal: `Proposal`)
- **summary**: Authenticates the sudo key and dispatches a function call with `Signed` origin from a given account. The dispatch origin for this call must be _Signed_. # <weight> - O(1). - Limited storage reads. - One DB write (event). - Unknown weight of derivative `proposal` execution. # </weight>
___
### system
▸ **fillBlock**()
- **summary**: A big dispatch that will disallow any other transaction to be included.
▸ **killPrefix**(prefix: `Key`)
- **summary**: Kill all storage items with a key that starts with the given prefix.
▸ **killStorage**(keys: `Vec<Key>`)
- **summary**: Kill some items from storage.
▸ **remark**(_remark: `Bytes`)
- **summary**: Make some on-chain remark.
▸ **setCode**(new: `Bytes`)
- **summary**: Set the new code.
▸ **setHeapPages**(pages: `u64`)
- **summary**: Set the number of pages in the WebAssembly environment's heap.
▸ **setStorage**(items: `Vec<KeyValue>`)
- **summary**: Set some items of storage.
___
### technicalCommittee
▸ **execute**(proposal: `Proposal`)
- **summary**: Dispatch a proposal from a member using the `Member` origin. Origin must be a member of the collective.
▸ **propose**(threshold: `Compact<MemberCount>`, proposal: `Proposal`)
- **summary**: # <weight> - Bounded storage reads and writes. - Argument `threshold` has bearing on weight. # </weight>
▸ **setMembers**(new_members: `Vec<AccountId>`)
- **summary**: Set the collective's membership manually to `new_members`. Be nice to the chain and provide it pre-sorted. Requires root origin.
▸ **vote**(proposal: `Hash`, index: `Compact<ProposalIndex>`, approve: `bool`)
- **summary**: # <weight> - Bounded storage read and writes. - Will be slightly heavier if the proposal is approved / disapproved after the vote. # </weight>
___
### technicalMembership
▸ **addMember**(who: `AccountId`)
- **summary**: Add a member `who` to the set. May only be called from `AddOrigin` or root.
▸ **removeMember**(who: `AccountId`)
- **summary**: Remove a member `who` from the set. May only be called from `RemoveOrigin` or root.
▸ **resetMembers**(members: `Vec<AccountId>`)
- **summary**: Change the membership to a new set, disregarding the existing membership. Be nice and pass `members` pre-sorted. May only be called from `ResetOrigin` or root.
▸ **swapMember**(remove: `AccountId`, add: `AccountId`)
- **summary**: Swap out one member `remove` for another `add`. May only be called from `SwapOrigin` or root.
___
### timestamp
▸ **set**(now: `Compact<Moment>`)
- **summary**: Set the current time. This call should be invoked exactly once per block. It will panic at the finalization phase, if this call hasn't been invoked by that time. The timestamp should be greater than the previous one by the amount specified by `MinimumPeriod`. The dispatch origin for this call must be `Inherent`.
___
### treasury
▸ **approveProposal**(proposal_id: `Compact<ProposalIndex>`)
- **summary**: Approve a proposal. At a later time, the proposal will be allocated to the beneficiary and the original deposit will be returned. # <weight> - O(1). - Limited storage reads. - One DB change. # </weight>
▸ **proposeSpend**(value: `Compact<BalanceOf>`, beneficiary: `Address`)
- **summary**: Put forward a suggestion for spending. A deposit proportional to the value is reserved and slashed if the proposal is rejected. It is returned once the proposal is awarded. # <weight> - O(1). - Limited storage reads. - One DB change, one extra DB entry. # </weight>
▸ **rejectProposal**(proposal_id: `Compact<ProposalIndex>`)
- **summary**: Reject a proposed spend. The original deposit will be slashed. # <weight> - O(1). - Limited storage reads. - One DB clear. # </weight>
___
### utility
▸ **batch**(calls: `Vec<Call>`)
- **summary**: Send a batch of dispatch calls (only root).
_placeholder_
+1 -175
View File
@@ -1,175 +1 @@
## JSON-RPC
The following sections contain RPC methods that are Remote Calls available by default and allow you to interact with the actual node, query, and submit.
- **[account](#account)**
- **[author](#author)**
- **[chain](#chain)**
- **[contracts](#contracts)**
- **[rpc](#rpc)**
- **[state](#state)**
- **[system](#system)**
___
### account
_(Optional) Methods that retrieves account-specific information_
▸ **nextIndex**(accountId: `AccountId`): `Index`
- **summary**: Retrieves the next accountIndex as available on the node
___
### author
_Authoring of network items_
▸ **insertKey**(keyType: `Text`, suri: `Text`, publicKey: `Bytes`): `Bytes`
- **summary**: Insert a key into the keystore.
▸ **pendingExtrinsics**(): `Vec<Extrinsic>`
- **summary**: Returns all pending extrinsics, potentially grouped by sender
▸ **removeExtrinsic**(bytesOrHash: `Vec<ExtrinsicOrHash>`): `Vec<Hash>`
- **summary**: Remove given extrinsic from the pool and temporarily ban it to prevent reimporting
▸ **rotateKeys**(): `Bytes`
- **summary**: Generate new session keys and returns the corresponding public keys
▸ **submitAndWatchExtrinsic**(extrinsic: `Extrinsic`): `ExtrinsicStatus`
- **summary**: Submit and subscribe to watch an extrinsic until unsubscribed
▸ **submitExtrinsic**(extrinsic: `Extrinsic`): `Hash`
- **summary**: Submit a fully formatted extrinsic for block inclusion
___
### chain
_Retrieval of chain data_
▸ **getBlock**(hash?: `Hash`): `SignedBlock`
- **summary**: Get header and body of a relay chain block
▸ **getBlockHash**(blockNumber?: `BlockNumber`): `Hash`
- **summary**: Get the block hash for a specific block
▸ **getFinalizedHead**(): `Hash`
- **summary**: Get hash of the last finalized block in the canon chain
▸ **getHeader**(hash?: `Hash`): `Header`
- **summary**: Retrieves the header for a specific block
▸ **subscribeFinalizedHeads**(): `Header`
- **summary**: Retrieves the best finalized header via subscription
▸ **subscribeNewHeads**(): `Header`
- **summary**: Retrieves the best header via subscription
___
### contracts
_(Optional) Methods that performs actions on contracts_
▸ **call**(callRequest: `ContractCallRequest`, at?: `Hash`): `ContractExecResult`
- **summary**: Executes a call to a contract
___
### rpc
_Retrieves information about the RPC endpoints_
▸ **methods**(): `RpcMethods`
- **summary**: Retrieves the list of RPC methods that are exposed by the node
___
### state
_Query of state_
▸ **call**(method: `Text`, data: `Bytes`, block?: `Hash`): `Bytes`
- **summary**: Perform a call to a builtin on the chain
▸ **getChildKeys**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `Vec<StorageKey>`
- **summary**: Retrieves the keys with prefix of a specific child storage
▸ **getChildStorage**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `StorageData`
- **summary**: Retrieves the child storage for a key
▸ **getChildStorageHash**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `Hash`
- **summary**: Retrieves the child storage hash
▸ **getChildStorageSize**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `u64`
- **summary**: Retrieves the child storage size
▸ **getKeys**(key: `StorageKey`, block?: `Hash`): `Vec<StorageKey>`
- **summary**: Retrieves the keys with a certain prefix
▸ **getMetadata**(block?: `Hash`): `Metadata`
- **summary**: Returns the runtime metadata
▸ **getRuntimeVersion**(hash?: `Hash`): `RuntimeVersion`
- **summary**: Get the runtime version
▸ **getStorage**(key: `StorageKey`, block?: `Hash`): `StorageData`
- **summary**: Retrieves the storage for a key
▸ **getStorageHash**(key: `StorageKey`, block?: `Hash`): `Hash`
- **summary**: Retrieves the storage hash
▸ **getStorageSize**(key: `StorageKey`, block?: `Hash`): `u64`
- **summary**: Retrieves the storage size
▸ **queryStorage**(keys: `Vec<StorageKey>`, startBlock: `Hash`, block?: `Hash`): `Vec<StorageChangeSet>`
- **summary**: Query historical storage entries (by key) starting from a start block
▸ **subscribeRuntimeVersion**(): `RuntimeVersion`
- **summary**: Retrieves the runtime version via subscription
▸ **subscribeStorage**(keys: `Vec<StorageKey>`): `StorageChangeSet`
- **summary**: Subscribes to storage changes for the provided keys
___
### system
_Calls to retrieve system info_
▸ **chain**(): `Text`
- **summary**: Retrieves the chain
▸ **health**(): `Health`
- **summary**: Return health status of the node
▸ **name**(): `Text`
- **summary**: Retrieves the node name
▸ **networkState**(): `NetworkState`
- **summary**: Returns current state of the network
▸ **peers**(): `Vec<PeerInfo>`
- **summary**: Returns the currently connected peers
▸ **properties**(): `ChainProperties`
- **summary**: Get a custom set of properties as a JSON object, defined in the chain spec
▸ **version**(): `Text`
- **summary**: Retrieves the version of the node
_placeholder_
+6 -6
View File
@@ -1,23 +1,23 @@
---
### substrate
## substrate
_These are keys that are always available to the runtime implementation_
▸ **changesTrieConfig**(): `u32`
▸ ### changesTrieConfig(): `u32`
- **summary**: Changes trie configuration is stored under this key.
▸ **childStorageKeyPrefix**(): `u32`
▸ ### childStorageKeyPrefix(): `u32`
- **summary**: Prefix of child storage keys.
▸ **code**(): `Bytes`
▸ ### code(): `Bytes`
- **summary**: Wasm code of the runtime.
▸ **extrinsicIndex**(): `u32`
▸ ### extrinsicIndex(): `u32`
- **summary**: Current extrinsic index (u32) is stored under this key.
▸ **heapPages**(): `u64`
▸ ### heapPages(): `u64`
- **summary**: Number of wasm linear memory pages required for execution of the runtime.
---
+1 -545
View File
@@ -1,545 +1 @@
## Storage
The following sections contain Storage methods are part of the default Substrate runtime. On the api, these are exposed via `api.query.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[authorship](#authorship)**
- **[babe](#babe)**
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[council](#council)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[grandpa](#grandpa)**
- **[imOnline](#imOnline)**
- **[indices](#indices)**
- **[offences](#offences)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[technicalCommittee](#technicalCommittee)**
- **[technicalMembership](#technicalMembership)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
- **[substrate](#substrate)**
___
### authorship
▸ **author**(): `Option<AccountId>`
- **summary**: Author of current block.
▸ **didSetUncles**(): `bool`
- **summary**: Whether uncles were already set in this block.
▸ **uncles**(): `Vec<UncleEntryItem>`
- **summary**: Uncles
___
### babe
▸ **authorities**(): `Vec<(AuthorityId,BabeAuthorityWeight)>`
- **summary**: Current epoch authorities.
▸ **currentSlot**(): `u64`
- **summary**: Current slot number.
▸ **epochIndex**(): `u64`
- **summary**: Current epoch index.
▸ **genesisSlot**(): `u64`
- **summary**: The slot at which the first epoch actually started. This is 0 until the first block of the chain.
▸ **initialized**(): `Option<MaybeVrf>`
- **summary**: Temporary value (cleared at block finalization) which is `Some` if per-block initialization has already been called for current block.
▸ **nextRandomness**(): `[u8;32]`
- **summary**: Next epoch randomness.
▸ **randomness**(): `[u8;32]`
- **summary**: The epoch randomness for the *current* epoch. # Security This MUST NOT be used for gambling, as it can be influenced by a malicious validator in the short term. It MAY be used in many cryptographic protocols, however, so long as one remembers that this (like everything else on-chain) it is public. For example, it can be used where a number is needed that cannot have been chosen by an adversary, for purposes such as public-coin zero-knowledge proofs.
▸ **segmentIndex**(): `u32`
- **summary**: Randomness under construction. We make a tradeoff between storage accesses and list length. We store the under-construction randomness in segments of up to `UNDER_CONSTRUCTION_SEGMENT_LENGTH`. Once a segment reaches this length, we begin the next one. We reset all segments and return to `0` at the beginning of every epoch.
▸ **underConstruction**(`u32`): `Vec<[u8;32]>`
___
### balances
▸ **freeBalance**(`AccountId`): `Balance`
- **summary**: The 'free' balance of a given account. This is the only balance that matters in terms of most operations on tokens. It alone is used to determine the balance when in the contract execution environment. When this balance falls below the value of `ExistentialDeposit`, then the 'current account' is deleted: specifically `FreeBalance`. Further, the `OnFreeBalanceZero` callback is invoked, giving a chance to external modules to clean up data associated with the deleted account. `system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`.
▸ **locks**(`AccountId`): `Vec<BalanceLock>`
- **summary**: Any liquidity locks on some account balances.
▸ **reservedBalance**(`AccountId`): `Balance`
- **summary**: The amount of the balance of a given account that is externally reserved; this can still get slashed, but gets slashed last of all. This balance is a 'reserve' balance that other subsystems use in order to set aside tokens that are still 'owned' by the account holder, but which are suspendable. When this balance falls below the value of `ExistentialDeposit`, then this 'reserve account' is deleted: specifically, `ReservedBalance`. `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`.)
▸ **totalIssuance**(): `Balance`
- **summary**: The total units issued in the system.
▸ **vesting**(`AccountId`): `Option<VestingSchedule>`
- **summary**: Information regarding the vesting of a given account.
___
### contracts
▸ **accountCounter**(): `u64`
- **summary**: The subtrie counter.
▸ **codeStorage**(`CodeHash`): `Option<PrefabWasmModule>`
- **summary**: A mapping between an original code hash and instrumented wasm code, ready for execution.
▸ **contractInfoOf**(`AccountId`): `Option<ContractInfo>`
- **summary**: The code associated with a given account.
▸ **currentSchedule**(): `Schedule`
- **summary**: Current cost schedule for contracts.
▸ **gasPrice**(): `BalanceOf`
- **summary**: The price of one unit of gas.
▸ **gasSpent**(): `Gas`
- **summary**: Gas spent so far in this block.
▸ **pristineCode**(`CodeHash`): `Option<Bytes>`
- **summary**: A mapping from an original code hash to the original code, untouched by instrumentation.
___
### council
▸ **members**(): `Vec<AccountId>`
- **summary**: The current members of the collective. This is stored sorted (just by value).
▸ **proposalCount**(): `u32`
- **summary**: Proposals so far.
▸ **proposalOf**(`Hash`): `Option<Proposal>`
- **summary**: Actual proposal for a given hash, if it's current.
▸ **proposals**(): `Vec<Hash>`
- **summary**: The hashes of the active proposals.
▸ **voting**(`Hash`): `Option<Votes>`
- **summary**: Votes on a given proposal, if it is ongoing.
___
### democracy
▸ **blacklist**(`Hash`): `Option<(BlockNumber,Vec<AccountId>)>`
- **summary**: A record of who vetoed what. Maps proposal hash to a possible existent block number (until when it may not be resubmitted) and who vetoed it.
▸ **cancellations**(`Hash`): `bool`
- **summary**: Record of all proposals that have been subject to emergency cancellation.
▸ **delegations**(`AccountId`): `((AccountId,Conviction), Linkage<AccountId>)`
- **summary**: Get the account (and lock periods) to which another account is delegating vote.
▸ **depositOf**(`PropIndex`): `Option<(BalanceOf,Vec<AccountId>)>`
- **summary**: Those who have locked a deposit.
▸ **dispatchQueue**(`BlockNumber`): `Vec<Option<(Proposal,ReferendumIndex)>>`
- **summary**: Queue of successful referenda to be dispatched.
▸ **lastTabledWasExternal**(): `bool`
- **summary**: True if the last referendum tabled was submitted externally. False if it was a public proposal.
▸ **nextExternal**(): `Option<(Proposal,VoteThreshold)>`
- **summary**: The referendum to be tabled whenever it would be valid to table an external proposal. This happens when a referendum needs to be tabled and one of two conditions are met: - `LastTabledWasExternal` is `false`; or - `PublicProps` is empty.
▸ **nextTally**(): `ReferendumIndex`
- **summary**: The next referendum index that should be tallied.
▸ **proxy**(`AccountId`): `Option<AccountId>`
- **summary**: Who is able to vote for whom. Value is the fund-holding account, key is the vote-transaction-sending account.
▸ **publicPropCount**(): `PropIndex`
- **summary**: The number of (public) proposals that have been made so far.
▸ **publicProps**(): `Vec<(PropIndex,Proposal,AccountId)>`
- **summary**: The public proposals. Unsorted.
▸ **referendumCount**(): `ReferendumIndex`
- **summary**: The next free referendum index, aka the number of referenda started so far.
▸ **referendumInfoOf**(`ReferendumIndex`): `Option<ReferendumInfo>`
- **summary**: Information concerning any given referendum.
▸ **voteOf**(`(ReferendumIndex,AccountId)`): `Vote`
- **summary**: Get the vote in a given referendum of a particular voter. The result is meaningful only if `voters_for` includes the voter when called with the referendum (you'll get the default `Vote` value otherwise). If you don't want to check `voters_for`, then you can also check for simple existence with `VoteOf::exists` first.
▸ **votersFor**(`ReferendumIndex`): `Vec<AccountId>`
- **summary**: Get the voters for the current proposal.
___
### elections
▸ **approvalsOf**(`(AccountId,SetIndex)`): `Vec<ApprovalFlag>`
▸ **candidateCount**(): `u32`
- **summary**: Current number of active candidates
▸ **candidates**(): `Vec<AccountId>`
- **summary**: The present candidate list.
▸ **desiredSeats**(): `u32`
- **summary**: Number of accounts that should constitute the collective.
▸ **leaderboard**(): `Option<Vec<(BalanceOf,AccountId)>>`
- **summary**: Get the leaderboard if we're in the presentation phase. The first element is the weight of each entry; It may be the direct summed approval stakes, or a weighted version of it. Sorted from low to high.
▸ **members**(): `Vec<(AccountId,BlockNumber)>`
- **summary**: The current membership. When there's a vote going on, this should still be used for executive matters. The block number (second element in the tuple) is the block that their position is active until (calculated by the sum of the block number when the member was elected and their term duration).
▸ **nextFinalize**(): `Option<(BlockNumber,u32,Vec<AccountId>)>`
- **summary**: The accounts holding the seats that will become free on the next tally.
▸ **nextVoterSet**(): `SetIndex`
- **summary**: the next free set to store a voter in. This will keep growing.
▸ **presentationDuration**(): `BlockNumber`
- **summary**: How long to give each top candidate to present themselves after the vote ends.
▸ **proxy**(`AccountId`): `Option<AccountId>`
- **summary**: Who is able to vote for whom. Value is the fund-holding account, key is the vote-transaction-sending account.
▸ **registerInfoOf**(`AccountId`): `Option<(VoteIndex,u32)>`
- **summary**: The vote index and list slot that the candidate `who` was registered or `None` if they are not currently registered.
▸ **termDuration**(): `BlockNumber`
- **summary**: How long each position is active for.
▸ **voteCount**(): `VoteIndex`
- **summary**: The total number of vote rounds that have happened or are in progress.
▸ **voterCount**(): `SetIndex`
- **summary**: Current number of Voters.
▸ **voterInfoOf**(`AccountId`): `Option<VoterInfo>`
- **summary**: Basic information about a voter.
▸ **voters**(`SetIndex`): `Vec<Option<AccountId>>`
- **summary**: The present voter list (chunked and capped at [`VOTER_SET_SIZE`]).
___
### grandpa
▸ **authorities**(): `Vec<(AuthorityId,AuthorityWeight)>`
- **summary**: The current authority set.
▸ **currentSetId**(): `SetId`
- **summary**: The number of changes (both in terms of keys and underlying economic responsibilities) in the "set" of Grandpa validators from genesis.
▸ **nextForced**(): `Option<BlockNumber>`
- **summary**: next block number where we can force a change.
▸ **pendingChange**(): `Option<StoredPendingChange>`
- **summary**: Pending change: (signaled at, scheduled change).
▸ **setIdSession**(`SetId`): `Option<SessionIndex>`
- **summary**: A mapping from grandpa set ID to the index of the *most recent* session for which its members were responsible.
▸ **stalled**(): `Option<(BlockNumber,BlockNumber)>`
- **summary**: `true` if we are currently stalled.
▸ **state**(): `StoredState`
- **summary**: State of the current authority set.
___
### imOnline
▸ **gossipAt**(): `BlockNumber`
- **summary**: The block number when we should gossip.
▸ **keys**(): `Vec<AuthorityId>`
- **summary**: The current set of keys that may issue a heartbeat.
▸ **receivedHeartbeats**(`SessionIndex, AuthIndex`): `Bytes`
- **summary**: For each session index we keep a mapping of `AuthorityId` to `offchain::OpaqueNetworkState`.
___
### indices
▸ **enumSet**(`AccountIndex`): `Vec<AccountId>`
- **summary**: The enumeration sets.
▸ **nextEnumSet**(): `AccountIndex`
- **summary**: The next free enumeration set.
___
### offences
▸ **concurrentReportsIndex**(`Kind, OpaqueTimeSlot`): `Vec<ReportIdOf>`
- **summary**: A vector of reports of the same kind that happened at the same time slot.
▸ **reports**(`ReportIdOf`): `Option<OffenceDetails>`
- **summary**: The primary structure that holds all offence records keyed by report identifiers.
▸ **reportsByKindIndex**(`Kind`): `Bytes`
- **summary**: Enumerates all reports of a kind along with the time they happened. All reports are sorted by the time of offence. Note that the actual type of this mapping is `Vec<u8>`, this is because values of different types are not supported at the moment so we are doing the manual serialization.
___
### session
▸ **currentIndex**(): `SessionIndex`
- **summary**: Current index of the session.
▸ **disabledValidators**(): `Vec<u32>`
- **summary**: Indices of disabled validators. The set is cleared when `on_session_ending` returns a new set of identities.
▸ **keyOwner**(`Bytes, (KeyTypeId,Bytes)`): `Option<ValidatorId>`
- **summary**: The owner of a key. The second key is the `KeyTypeId` + the encoded key. The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of the trie. Having all data in the same branch should prevent slowing down other queries.
▸ **nextKeys**(`Bytes, ValidatorId`): `Option<Keys>`
- **summary**: The next session keys for a validator. The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of the trie. Having all data in the same branch should prevent slowing down other queries.
▸ **queuedChanged**(): `bool`
- **summary**: True if the underlying economic identities or weighting behind the validators has changed in the queued validator set.
▸ **queuedKeys**(): `Vec<(ValidatorId,Keys)>`
- **summary**: The queued keys for the next session. When the next session begins, these keys will be used to determine the validator's session keys.
▸ **validators**(): `Vec<ValidatorId>`
- **summary**: The current set of validators.
___
### staking
▸ **bonded**(`AccountId`): `Option<AccountId>`
- **summary**: Map from all locked "stash" accounts to the controller account.
▸ **bondedEras**(): `Vec<(EraIndex,SessionIndex)>`
- **summary**: A mapping from still-bonded eras to the first session index of that era.
▸ **currentElected**(): `Vec<AccountId>`
- **summary**: The currently elected validator set keyed by stash account ID.
▸ **currentEra**(): `EraIndex`
- **summary**: The current era index.
▸ **currentEraPointsEarned**(): `EraPoints`
- **summary**: Rewards for the current era. Using indices of current elected set.
▸ **currentEraStart**(): `MomentOf`
- **summary**: The start of the current era.
▸ **currentEraStartSessionIndex**(): `SessionIndex`
- **summary**: The session index at which the current era started.
▸ **eraSlashJournal**(`EraIndex`): `Vec<SlashJournalEntry>`
- **summary**: All slashes that have occurred in a given era.
▸ **forceEra**(): `Forcing`
- **summary**: True if the next session change will be a new era regardless of index.
▸ **invulnerables**(): `Vec<AccountId>`
- **summary**: Any validators that may never be slashed or forcibly kicked. It's a Vec since they're easy to initialize and the performance hit is minimal (we expect no more than four invulnerables) and restricted to testnets.
▸ **ledger**(`AccountId`): `Option<StakingLedger>`
- **summary**: Map from all (unlocked) "controller" accounts to the info regarding the staking.
▸ **minimumValidatorCount**(): `u32`
- **summary**: Minimum number of staking participants before emergency conditions are imposed.
▸ **nominators**(`AccountId`): `(Vec<AccountId>, Linkage<AccountId>)`
- **summary**: The map from nominator stash key to the set of stash keys of all validators to nominate.
▸ **payee**(`AccountId`): `RewardDestination`
- **summary**: Where the reward payment should be made. Keyed by stash.
▸ **slashRewardFraction**(): `Perbill`
- **summary**: The percentage of the slash that is distributed to reporters. The rest of the slashed value is handled by the `Slash`.
▸ **slotStake**(): `BalanceOf`
- **summary**: The amount of balance actively at stake for each validator slot, currently. This is used to derive rewards and punishments.
▸ **stakers**(`AccountId`): `Exposure`
- **summary**: Nominators for a particular account that is in action right now. You can't iterate through validators here, but you can find them in the Session module. This is keyed by the stash account.
▸ **validatorCount**(): `u32`
- **summary**: The ideal number of staking participants.
▸ **validators**(`AccountId`): `(ValidatorPrefs, Linkage<AccountId>)`
- **summary**: The map from (wannabe) validator stash key to the preferences of that validator.
___
### sudo
▸ **key**(): `AccountId`
- **summary**: The `AccountId` of the sudo key.
___
### system
▸ **accountNonce**(`AccountId`): `Index`
- **summary**: Extrinsics nonce for accounts.
▸ **allExtrinsicsLen**(): `Option<u32>`
- **summary**: Total length (in bytes) for all extrinsics put together, for the current block.
▸ **allExtrinsicsWeight**(): `Option<Weight>`
- **summary**: Total weight for all extrinsics put together, for the current block.
▸ **blockHash**(`BlockNumber`): `Hash`
- **summary**: Map of block numbers to block hashes.
▸ **digest**(): `DigestOf`
- **summary**: Digest of the current block, also part of the block header.
▸ **eventCount**(): `EventIndex`
- **summary**: The number of events in the `Events<T>` list.
▸ **events**(): `Vec<EventRecord>`
- **summary**: Events deposited for the current block.
▸ **eventTopics**(`Null, Hash`): `Vec<(BlockNumber,EventIndex)>`
- **summary**: Mapping between a topic (represented by T::Hash) and a vector of indexes of events in the `<Events<T>>` list. The first key serves no purpose. This field is declared as double_map just for convenience of using `remove_prefix`. All topic vectors have deterministic storage locations depending on the topic. This allows light-clients to leverage the changes trie storage tracking mechanism and in case of changes fetch the list of events of interest. The value has the type `(T::BlockNumber, EventIndex)` because if we used only just the `EventIndex` then in case if the topic has the same contents on the next block no notification will be triggered thus the event might be lost.
▸ **extrinsicCount**(): `Option<u32>`
- **summary**: Total extrinsics count for the current block.
▸ **extrinsicData**(`u32`): `Bytes`
- **summary**: Extrinsics data for the current block (maps an extrinsic's index to its data).
▸ **extrinsicsRoot**(): `Hash`
- **summary**: Extrinsics root of the current block, also part of the block header.
▸ **nextWeightMultiplier**(): `WeightMultiplier`
- **summary**: The next weight multiplier. This should be updated at the end of each block based on the saturation level (weight).
▸ **number**(): `BlockNumber`
- **summary**: The current block number being processed. Set by `execute_block`.
▸ **parentHash**(): `Hash`
- **summary**: Hash of the previous block.
▸ **randomMaterial**(): `(i8,Vec<Hash>)`
- **summary**: Series of block headers from the last 81 blocks that acts as random seed material. This is arranged as a ring buffer with the `i8` prefix being the index into the `Vec` of the oldest hash.
___
### technicalCommittee
▸ **members**(): `Vec<AccountId>`
- **summary**: The current members of the collective. This is stored sorted (just by value).
▸ **proposalCount**(): `u32`
- **summary**: Proposals so far.
▸ **proposalOf**(`Hash`): `Option<Proposal>`
- **summary**: Actual proposal for a given hash, if it's current.
▸ **proposals**(): `Vec<Hash>`
- **summary**: The hashes of the active proposals.
▸ **voting**(`Hash`): `Option<Votes>`
- **summary**: Votes on a given proposal, if it is ongoing.
___
### technicalMembership
▸ **members**(): `Vec<AccountId>`
- **summary**: The current membership, stored as an ordered Vec.
___
### timestamp
▸ **didUpdate**(): `bool`
- **summary**: Did the timestamp get updated in this block?
▸ **now**(): `Moment`
- **summary**: Current time for the current block.
___
### treasury
▸ **approvals**(): `Vec<ProposalIndex>`
- **summary**: Proposal indices that have been approved but not yet awarded.
▸ **proposalCount**(): `ProposalIndex`
- **summary**: Number of proposals that have been made.
▸ **proposals**(`ProposalIndex`): `Option<TreasuryProposal>`
- **summary**: Proposals that have been made.
---
### substrate
_These are keys that are always available to the runtime implementation_
▸ **changesTrieConfig**(): `u32`
- **summary**: Changes trie configuration is stored under this key.
▸ **childStorageKeyPrefix**(): `u32`
- **summary**: Prefix of child storage keys.
▸ **code**(): `Bytes`
- **summary**: Wasm code of the runtime.
▸ **extrinsicIndex**(): `u32`
- **summary**: Current extrinsic index (u32) is stored under this key.
▸ **heapPages**(): `u64`
- **summary**: Number of wasm linear memory pages required for execution of the runtime.
---
_placeholder_
+6 -6
View File
@@ -123,14 +123,14 @@ export default abstract class ApiBase<ApiType extends ApiTypes> extends Init<Api
/**
* @description Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.
*
* All calls inside the namespace, is denoted by `section`.`method` and may take an optional query parameter. As an example, `api.query.timestamp.now()` (current block timestamp) does not take parameters, while `api.query.system.accountNonce(<accountId>)` (retrieving the associated nonce for an account), takes the `AccountId` as a parameter.
* All calls inside the namespace, is denoted by `section`.`method` and may take an optional query parameter. As an example, `api.query.timestamp.now()` (current block timestamp) does not take parameters, while `api.query.system.account(<accountId>)` (retrieving the associated nonce & balances for an account), takes the `AccountId` as a parameter.
*
* @example
* <BR>
*
* ```javascript
* api.query.balances.freeBalance(<accountId>, (balance) => {
* console.log('new balance', balance);
* api.query.system.account(<accountId>, ([nonce, balance]) => {
* console.log('new free balance', balance.free, 'new nonce', nonce);
* });
* ```
*/
@@ -150,10 +150,10 @@ export default abstract class ApiBase<ApiType extends ApiTypes> extends Init<Api
* // you can include the storage without any parameters
* api.query.balances.totalIssuance,
* // or you can pass parameters to the storage query
* [api.query.balances.freeBalance, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']
* [api.query.system.account, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']
* ],
* ([existential, balance]) => {
* console.log(`You have ${balance.sub(existential)} more than the existential deposit`);
* ([existential, [, { free }]]) => {
* console.log(`You have ${free.sub(existential)} more than the existential deposit`);
*
* unsub();
* }
+5 -4
View File
@@ -45,16 +45,17 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
const override = await api.query.balances.totalIssuance<Header>(); // override is still available
const oldBal = await api.query.balances.totalIssuance.at('abcd');
// It's hard to correctly type .multi. Expected: `Balance[]`, actual: Codec[].
// In the meantime, we can case with `<Balance>`
// In the meantime, we can case with `<Balance>` (this is not available on recent chains)
const multi = await api.query.balances.freeBalance.multi<Balance>([keyring.alice.address, keyring.bob.address]);
console.log('query types:', bar, bal, bal2, override, oldBal, multi);
// check multi for unsub
const multiUnsub = await api.queryMulti([
[api.query.system.accountNonce, keyring.eve.address],
[api.query.system.account, keyring.eve.address],
// older chains only
[api.query.system.accountNonce, keyring.bob.address]
], (balances): void => {
console.log('balances', balances);
], (values): void => {
console.log('values', values);
multiUnsub();
});
+4 -5
View File
@@ -154,7 +154,7 @@ export function decorateMethod<Method extends AnyFunction> (method: Method, opti
* import ApiPromise from '@polkadot/api/promise';
*
* ApiPromise.create().then((api) => {
* const nonce = await api.query.system.accountNonce(keyring.alice.address);
* const [nonce] = await api.query.system.account(keyring.alice.address);
*
* api.tx.balances
* // create transfer
@@ -256,10 +256,9 @@ export default class ApiPromise extends ApiBase<'promise'> {
* // combines values from balance & nonce as it updates
* api.combineLatest([
* api.rpc.chain.subscribeNewHeads,
* [api.query.balances.freeBalance, address],
* (cb) => api.query.system.accountNonce(address, cb)
* ], ([head, balance, nonce]) => {
* console.log(`#${head.number}: You have ${balance} units, with ${nonce} transactions sent`);
* (cb) => api.query.system.account(address, cb)
* ], ([head, [balance, nonce]]) => {
* console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
* });
* ```
*/
+2 -2
View File
@@ -91,11 +91,11 @@ export function decorateMethod <Method extends AnyFunction> (method: Method): Me
*
* // retrieve nonce for the account
* api.query.system
* .accountNonce(keyring.alice.address)
* .account(keyring.alice.address)
* .pipe(
* first(),
* // pipe nonce into transfer
* switchMap((nonce) =>
* switchMap(([nonce]) =>
* api.tx.balances
* // create transfer
* .transfer(keyring.bob.address, 12345)
@@ -196,7 +196,7 @@ export default function createFunction (registry: Registry, itemFn: CreateItemFn
const [hasher, key2Hasher] = getHashers(itemFn);
// Can only have zero or one argument:
// - storage.balances.freeBalance(address)
// - storage.system.account(address)
// - storage.timestamp.blockPeriod()
// For doublemap queries the params is passed in as an tuple, [key1, key2]
const _storageFn = (arg?: CreateArgType | [CreateArgType?, CreateArgType?]): Uint8Array =>
@@ -23,7 +23,7 @@ export default function fromMetadata (registry: Registry, metadata: Metadata): S
const unwrapped = moduleMetadata.storage.unwrap();
const prefix = unwrapped.prefix.toString();
// For access, we change the index names, i.e. Balances.FreeBalance -> balances.freeBalance
// For access, we change the index names, i.e. System.Account -> system.account
result[section] = unwrapped.items.reduce((newModule, meta): ModuleStorage => {
const method = meta.name.toString();
+2 -2
View File
@@ -267,10 +267,10 @@ export default class Rpc implements RpcInterface {
// Delete from cache
// Reason:
// ```
// const s = api.query.system.accountNonce(addr1).subscribe(); // let's say it's 6
// const s = api.query.system.account(addr1).subscribe(); // let's say it's 6
// s.unsubscribe();
// // wait a bit, for the nonce to increase to 7
// api.query.system.accountNonce(addr1).subscribe(); // will output 6 instead of 7 if we don't clear cache
// api.query.system.account(addr1).subscribe(); // will output 6 instead of 7 if we don't clear cache
// // that's because all our observables are replay(1)
// ```
// eslint-disable-next-line @typescript-eslint/no-use-before-define
-1
View File
@@ -176,7 +176,6 @@ export default class Mock implements ProviderInterface {
// increment the balances and nonce for each account
keyring.getPairs().forEach(({ publicKey }, index): void => {
// this.setStateBn(metadata.query.balances.freeBalance(publicKey), newHead.number.toBn().muln(3).iaddn(index));
this.setStateBn(metadata.query.system.account(publicKey), newHead.number.toBn().addn(index));
});
+1 -1
View File
@@ -229,7 +229,7 @@ export default class WsProvider implements WSProviderInterface {
* const provider = new WsProvider('ws://127.0.0.1:9944');
* const rpc = new Rpc(provider);
*
* rpc.state.subscribeStorage([[storage.balances.freeBalance, <Address>]], (_, values) => {
* rpc.state.subscribeStorage([[storage.system.account, <Address>]], (_, values) => {
* console.log(values)
* }).then((subscriptionId) => {
* console.log('balance changes subscription id: ', subscriptionId)