Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: chainSpec based controller config; Types from apps-config #351

Merged
merged 27 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
ae1de13
feat: chainSpec based controller config; Types from apps-config
emostov Nov 24, 2020
5d254dd
Update mock api to include derive getBlock - specs work
emostov Nov 24, 2020
7072fdc
Update to reflect TS 4.1
emostov Nov 24, 2020
c682665
Clean up comments
emostov Nov 24, 2020
4ab1b2d
Save
emostov Dec 2, 2020
cc9a962
Merge origin master
emostov Dec 2, 2020
ede1787
feat: Token query param for non-native token balance-info
emostov Dec 2, 2020
39e1a1a
Revert package.json
emostov Dec 2, 2020
be66056
Initial reply david review
emostov Dec 2, 2020
e465092
Update src/main.ts
emostov Dec 2, 2020
19a66e7
Remove kulupu controller
emostov Dec 2, 2020
0ac5573
Merge branch 'types-package' of https://github.com/paritytech/substra…
emostov Dec 2, 2020
c5e9284
Add chain builder integration guide
emostov Dec 3, 2020
0c57ecd
Patch CHAIN_INTEGRATION.md
emostov Dec 3, 2020
6692e50
Apply suggestions from code review
emostov Dec 4, 2020
4b4d9a2
Update CHAIN_INTEGRATION.md
emostov Dec 4, 2020
b81c0d1
Bump deps
emostov Dec 8, 2020
46f067d
Merge remote-tracking branch 'origin' into types-package
emostov Dec 8, 2020
92a8856
Use whole options object for controller creation
emostov Dec 8, 2020
8451309
Apply suggestions from code review
emostov Dec 9, 2020
87572a9
Respond to maciej feedback
emostov Dec 9, 2020
c38c105
Merge branch 'types-package' of https://github.com/paritytech/substra…
emostov Dec 9, 2020
a1a988a
Update chain integration guide
emostov Dec 9, 2020
79f9eb8
Remove excessive nullish colescing operators
emostov Dec 9, 2020
cf84d63
Merge origin master
emostov Dec 9, 2020
b34cca2
Fix merge issue
emostov Dec 9, 2020
a16235a
Update CHAIN_INTEGRATION.md
emostov Dec 9, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions CHAIN_INTEGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Substrate Api Sidecar chain integration guide

This guide aims to help chain builders integrate their Substrate FRAME based chain with Substrate API Sidecar.

## Table of contents

- [Polkadot-js API type definition support](#polkadot-js-API-type-definition-support)
- [Controller configuration](controller-configuration)

## Polkadot-js API type definition support

In order decode the SCALE encoded data from a substrate based node, polkadot-js needs to have a registry of type definitions. Sidecar pulls in chain type definitions from the [@polkadot/apps-config package hosted on NPM](https://www.npmjs.com/package/@polkadot/apps-config).

If the chain's type definitions do not already exist in [@polkadot/apps-config](https://github.com/polkadot-js/apps/tree/master/packages/apps-config) they will need to be added via PR to polkadot-js/apps by following their [instructions for API config](https://github.com/polkadot-js/apps/tree/master/packages/apps-config#api).

Before taking any other steps to integrate a chain with Sidecar, a chain's up-to-date type definitions must be included in a published version of @polkadot/apps-config.

## Controller configuration

Sidecar offers the ability to configure which controllers to mount. Sidecar uses a chain's spec name to determine which controller config to use, and if no config is linked to a spec name, then the [default config](/src/chains-config/defaultControllers.ts) is used.

A chain builder can follow the below steps and submit a chain's controller config via PR, where it will be reviewed and merged once deemed ready by the maintainers.

#### 1) Create a controller config

Create a controller config for your chain. The shape of the controller config is specified [here](/src/chains-config/ControllerConfig.ts). The `controller` property has keys from the [controller export](/src/controllers/index.ts), which is an exhaustive collection of the available controller classes. In order to see the path(s) associated with a controller one must look in the controller source code.

The easiest way to start creating a controller config would be to copy [defaultControllers.ts](/src/chains-config/ControllerConfig.ts) and name the file and export `{specName}Controllers`. Then change the boolean values to indicate wether or not to mount a controller and its paths. Ensure to export the controller config from `chains-config` by adding `export * from './{specName}Controllers.ts'` in [/src/chains-config/index.ts](/src/chains-config/index.ts).

To determine what controllers to include, one must consider the runtime logic, specifically what pallets the chain uses. It is important to keep in mind the assumptions the service's logic makes and what exact pallets the service queries. E.g. in order to use [`PalletsStakingProgressController`](/src/controllers/pallets/PalletsStakingProgressController.ts), one would check [`PalletsStakingProgressService.ts`](/src/services/pallets/PalletsStakingProgressService.ts). There one would see it queries `staking`, `sessions`, `babe` pallets and makes certain assumptions about how the pallets are used together in the runtime.

In some circumstance, a chain may need a new path, modify a path or altered business logic for a path. Path changes that help a chain support wallets will be given priority. Breaking path changes are strongly not preferred.

##### Basic balance transfer support

In order to support traditional balance transfers the chain's Sidecar endpoints should support account balance lookup, transaction submission, transaction material retrieval, and block queries.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice. Even if we haven't decided the exact token standard, good to start somewhere.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be good to link to examples of how each of these look like.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dvdplm - what exactly do you have in mind for examples? My idea here was essentially to say "make sure to add the relevant controllers for these endpoints".

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah maybe it's dumb but my thinking was to link to example implementations of the existing Polkadot/Kusama endpoints; a dev adding sidecar for their chain might want to peek at how you did those endpoints as theirs will likely be fairly similar?


To support those actions the following endpoints are necessary:

| Path | Controller | Description |
|:----------------------------------------:|:-----------------------------:|:--------------------------------------------------------------------------:|
| GET `/transaction/material` | TransactionMaterialController | Get all the network information needed to construct a transaction offline. |
| POST `/transaction` | TransactionSubmitController | Submit a transaction to the node's transaction pool. |
| GET `/blocks/head` & `/blocks/{number}` | BlocksController | Get a block. |
| GET `accounts/{accountId}/balance-info` | AccountsBalanceInfoController | Get balance information for an account. |

#### 2) Update `specToControllerMap`

In order for Sidecar to use your controller config, the `specToControllerMap` in [/src/chains-config/index.ts](/src/chains-config/index.ts) must be updated with the chain's `specName` and controller config by adding them as a property to `specToControllerMap`:

```javascript
const specToControllerMap = {
kulupu: kulupuControllers,
mandala: mandalaControllers,
{specName}: {specName}Controllers,
};
```

#### 3) Test

Run it against an archive version of your chain's node:

- Ensure all the correct paths work, including the root path
- Exercise each query param of every path
- Make sure transaction submission works
- Try out historic queries across runtimes where types might change

#### 4) Submit your PR

Make sure it passes lint with `yarn lint --fix` and tests with `yarn test`. Then submit a PR for review.

#### 5) Maintenance

- Keep types up-to-date in `@polkadot/apps-config`
- If the business logic or storage of a chain's pallet queried by a Sidecar endpoint is changed, ensure Sidecar has service logic has any relevant updates.
12 changes: 3 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ This service requires Node version 12 or higher.
- [Configuration](#configuration)
- [Debugging fee and payout calculations](#debugging-fee-and-payout-calculations)
- [Available endpoints](https://paritytech.github.io/substrate-api-sidecar/dist/)
- [Chain compatibility](#chain-compatibility)
- [Chain integration guide](/CHAIN_INTEGRATION.md)
- [Docker](#docker)
- [Note for maintainers](#note-for-maintainers)
- [Roadmap](#roadmap)
Expand Down Expand Up @@ -200,15 +200,9 @@ CALC_DEBUG=1 yarn

[Click here for full endpoint docs.](https://paritytech.github.io/substrate-api-sidecar/dist/)

## Chain compatibility
## Chain integration guide

Sidecar should be compatible with any [Substrate](https://substrate.dev/) based chain, given
constraints:

- The chain ought to use FRAME and the `balances` pallet.
- The chain is being finalized (by running `grandpa`).
- If the chain is running on custom Node binaries, the JSON-RPC API should be backwards compatible
with the default Substrate Node.
[Click here for chain integration guide.](/CHAIN_INTEGRATION.md)

## Docker

Expand Down
13 changes: 13 additions & 0 deletions docs/src/openapi-v1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ paths:
description: Block height (as a non-negative integer) or hash
(as a hex string).
format: unsignedInteger or $hex
- name: token
in: query
description: 'Token to query the balance of. If not specified it will query
the chains native token (e.g. DOT for Polkadot). Note: this is only relevant
for chains that support multiple tokens through the ORML tokens pallet.'
required: false
schema:
type: string
description: Token symbol
responses:
"200":
description: successful operation
Expand Down Expand Up @@ -717,6 +726,10 @@ components:
type: string
description: Account nonce.
format: unsignedInteger
tokenSymbol:
type: string
description: Token symbol of the balances displayed in this response.
format: unsignedInteger
free:
type: string
description: Free balance of the account. Not equivalent to _spendable_
Expand Down
13 changes: 7 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"test": "jest --silent"
},
"dependencies": {
"@polkadot/api": "^2.9.1",
"@polkadot/api": "^2.10.1",
"@polkadot/apps-config": "^0.70.1",
"@polkadot/util-crypto": "^4.2.1",
"@substrate/calc": "^0.1.2",
"confmgr": "^1.0.6",
Expand All @@ -52,11 +53,11 @@
"@types/jest": "^26.0.16",
"@types/morgan": "^1.9.2",
"@types/triple-beam": "^1.3.2",
"@typescript-eslint/eslint-plugin": "4.9.0",
"@typescript-eslint/parser": "4.9.0",
"eslint": "^7.14.0",
"eslint-config-prettier": "^6.15.0",
"eslint-plugin-prettier": "^3.1.4",
"@typescript-eslint/eslint-plugin": "4.9.1",
"@typescript-eslint/parser": "4.9.1",
"eslint": "^7.15.0",
"eslint-config-prettier": "^7.0.0",
"eslint-plugin-prettier": "^3.2.0",
"eslint-plugin-simple-import-sort": "^6.0.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
Expand Down
3 changes: 3 additions & 0 deletions src/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ export default class App {
listen(): void {
this.app.listen(this.port, this.host, () => {
console.log(`Listening on http://${this.host}:${this.port}/`);
console.log(
`Check the root endpoint (http://${this.host}:${this.port}/) to see the available endpoints for the current node`
);
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/Config.ts → src/SidecarConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ConfigManager } from 'confmgr';

import * as configTypes from '../config/types.json';
import { Specs } from './Specs';
import { CONFIG, ISidecarConfig, MODULES } from './types/config';
import { CONFIG, ISidecarConfig, MODULES } from './types/sidecar-config';

function hr(): string {
return Array(80).fill('━').join('');
Expand All @@ -11,7 +11,7 @@ function hr(): string {
/**
* Access a singleton config object that will be intialized on first use.
*/
export class Config {
export class SidecarConfig {
private static _config: ISidecarConfig | undefined;
/**
* Gather env vars for config and make sure they are valid.
Expand Down
2 changes: 1 addition & 1 deletion src/Specs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ConfigSpecs, SpecsFactory } from 'confmgr';

import { CONFIG, MODULES } from './types/config';
import { CONFIG, MODULES } from './types/sidecar-config';

/**
* Access a singleton specification for config enviroment variables that will
Expand Down
30 changes: 30 additions & 0 deletions src/chains-config/defaultControllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ControllerConfig } from '../types/chains-config';

/**
* Controllers that Sidecar will always default to. This will always be
* the optimal controller selection for Polkadot and Kusama.
*/
export const defaultControllers: ControllerConfig = {
controllers: {
Blocks: true,
AccountsStakingPayouts: true,
AccountsBalanceInfo: true,
AccountsStakingInfo: true,
AccountsVestingInfo: true,
NodeNetwork: true,
NodeVersion: true,
NodeTransactionPool: true,
RuntimeCode: true,
RuntimeSpec: true,
RuntimeMetadata: true,
TransactionDryRun: true,
TransactionMaterial: true,
TransactionFeeEstimate: true,
TransactionSubmit: true,
PalletsStakingProgress: true,
PalletsStorage: true,
},
options: {
finalizes: true,
},
};
56 changes: 56 additions & 0 deletions src/chains-config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { ApiPromise } from '@polkadot/api';
import AbstractController from 'src/controllers/AbstractController';
import { AbstractService } from 'src/services/AbstractService';

import { controllers } from '../controllers';
import { ControllerConfig } from '../types/chains-config';
import { defaultControllers } from './defaultControllers';
import { kulupuControllers } from './kulupuControllers';
import { mandalaControllers } from './mandalaControllers';

const specToControllerMap = {
kulupu: kulupuControllers,
mandala: mandalaControllers,
};

/**
* Return an array of instantiated controller instances based off of a `specName`.
*
* @param api ApiPromise to inject into controllers
* @param implName
*/
export function getControllersForSpec(
api: ApiPromise,
specName: string
): AbstractController<AbstractService>[] {
if (specToControllerMap[specName]) {
return getControllersFromConfig(api, specToControllerMap[specName]);
}

// If we don't have the specName in the specToControllerMap we use the default
// contoller config
return getControllersFromConfig(api, defaultControllers);
}

/**
* Return an array of instantiated controller instances based off of a
* `ControllerConfig`.
*
* @param api ApiPromise to inject into controllers
* @param config controller mount configuration object
*/
function getControllersFromConfig(api: ApiPromise, config: ControllerConfig) {
// If we don't typecast here, tsc thinks its just [string, any][]
const controllersToInclude = Object.entries(config.controllers) as [
keyof typeof controllers,
boolean
][];

return controllersToInclude.reduce((acc, [controllerName, shouldMount]) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One day JavaScript will get filterMap on arrays, one day... :)

if (shouldMount) {
acc.push(new controllers[controllerName](api, config.options));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}

return acc;
}, [] as AbstractController<AbstractService>[]);
}
26 changes: 26 additions & 0 deletions src/chains-config/kulupuControllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ControllerConfig } from '../types/chains-config';

export const kulupuControllers: ControllerConfig = {
controllers: {
Blocks: true,
AccountsStakingPayouts: false,
AccountsBalanceInfo: true,
AccountsStakingInfo: false,
AccountsVestingInfo: false,
NodeNetwork: true,
NodeVersion: true,
NodeTransactionPool: true,
RuntimeCode: true,
RuntimeSpec: true,
RuntimeMetadata: true,
TransactionDryRun: true,
TransactionMaterial: true,
TransactionFeeEstimate: true,
TransactionSubmit: true,
PalletsStakingProgress: false,
PalletsStorage: true,
},
options: {
finalizes: false,
},
};
29 changes: 29 additions & 0 deletions src/chains-config/mandalaControllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { ControllerConfig } from '../types/chains-config';

/**
* Controllers for mandala, acala's test network.
*/
export const mandalaControllers: ControllerConfig = {
controllers: {
Blocks: true,
AccountsStakingPayouts: true,
AccountsBalanceInfo: true,
AccountsStakingInfo: true,
AccountsVestingInfo: true,
NodeNetwork: true,
NodeVersion: true,
NodeTransactionPool: true,
RuntimeCode: true,
RuntimeSpec: true,
RuntimeMetadata: true,
TransactionDryRun: true,
TransactionMaterial: true,
TransactionFeeEstimate: true,
TransactionSubmit: true,
PalletsStakingProgress: true,
PalletsStorage: true,
},
options: {
finalizes: true,
},
};
9 changes: 7 additions & 2 deletions src/controllers/accounts/AccountsBalanceInfoController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,19 @@ export default class AccountsBalanceController extends AbstractController<Accoun
* @param res Express Response
*/
private getAccountBalanceInfo: RequestHandler<IAddressParam> = async (
{ params: { address }, query: { at } },
{ params: { address }, query: { at, token } },
res
): Promise<void> => {
const tokenArg =
typeof token === 'string'
? token.toUpperCase()
: this.api.registry.chainToken;

const hash = await this.getHashFromAt(at);

AccountsBalanceController.sanitizedSend(
res,
await this.service.fetchAccountBalanceInfo(hash, address)
await this.service.fetchAccountBalanceInfo(hash, address, tokenArg)
);
};
}
8 changes: 6 additions & 2 deletions src/controllers/blocks/BlocksController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { BlocksService } from '../../services';
import { INumberParam } from '../../types/requests';
import AbstractController from '../AbstractController';

interface ControllerOptions {
finalizes: boolean;
}

/**
* GET a block.
*
Expand Down Expand Up @@ -65,7 +69,7 @@ import AbstractController from '../AbstractController';
* - `OnFinalize`: https://crates.parity.io/frame_support/traits/trait.OnFinalize.html
*/
export default class BlocksController extends AbstractController<BlocksService> {
constructor(api: ApiPromise) {
constructor(api: ApiPromise, private readonly options: ControllerOptions) {
super(api, '/blocks', new BlocksService(api));
this.initRoutes();
}
Expand All @@ -91,7 +95,7 @@ export default class BlocksController extends AbstractController<BlocksService>
const extrsinsicDocsArg = extrinsicDocs === 'true';

const hash =
finalized === 'false'
finalized === 'false' || !this.options.finalizes
? (await this.api.rpc.chain.getHeader()).hash
: await this.api.rpc.chain.getFinalizedHead();

Expand Down
Loading