diff --git a/.travis.yml b/.travis.yml index 6fee6456..7748f129 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,7 +14,7 @@ node_js: script: - yarn lint - yarn build - - yarn test --coverage --coverageReporters=text-lcov | coveralls ; test ${PIPESTATUS[0]} -eq 0 + - yarn test --silent --coverage --coverageReporters=text-lcov | coveralls ; test ${PIPESTATUS[0]} -eq 0 before_deploy: - npm install --global gitbook-cli deploy: diff --git a/jest.config.js b/jest.config.js index 8e3da968..b9bcebdb 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,11 +1,15 @@ module.exports = { - collectCoverageFrom: ['**/*.{ts,tsx}', '!**/node_modules/**', '!**/*.d.ts'], + collectCoverageFrom: [ + '**/*.{ts,tsx}', + '!**/node_modules/**', + '!**/*.d.ts', + '!**/index.ts' + ], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], rootDir: '.', transform: { '^.+\\.tsx?$': 'ts-jest' }, // testRegex: 'spec\\.(ts|tsx)$' // TODO Skip api/ tests for now, as it's still WIP - testRegex: - 'packages/(abi|electron|light.js|light.js-react)/.*spec\\.(ts|tsx)$' + testRegex: `packages/(abi|electron|light\.js|light\.js-react)/.*spec\\.(ts|tsx)$` }; diff --git a/packages/light.js-react/src/ambient.d.ts b/packages/light.js-react/src/ambient.d.ts new file mode 100644 index 00000000..2459c03e --- /dev/null +++ b/packages/light.js-react/src/ambient.d.ts @@ -0,0 +1,11 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +declare module '@parity/abi'; +declare module '@parity/abi/lib/spec/function'; +declare module '@parity/api'; +declare module '@parity/api/lib/util'; +declare module '@parity/api/lib/util/encode'; +declare module '@parity/api/lib/util/types'; diff --git a/packages/light.js/docs/SUMMARY.md b/packages/light.js/docs/SUMMARY.md index 8c6ddc74..fddc38e2 100644 --- a/packages/light.js/docs/SUMMARY.md +++ b/packages/light.js/docs/SUMMARY.md @@ -30,11 +30,14 @@ - [rpc/other/makeContract](api/modules/_rpc_other_makecontract_.md) - [rpc/other/post](api/modules/_rpc_other_post_.md) - [rpc/parity/parity](api/modules/_rpc_parity_parity_.md) - - Types - - [FrequencyObservable](api/interfaces/_types_.frequencyobservable.md) - - [Metadata](api/interfaces/_types_.metadata.md) - - [RpcObservable](api/interfaces/_types_.rpcobservable.md) - - [TxStatus](api/interfaces/_types_.txstatus.md) + * [Types](modules/_types_.md) + - [FrequencyObservable](interfaces/_types_.frequencyobservable.md) + - [FrequencyObservableOptions](interfaces/_types_.frequencyobservableoptions.md) + - [MakeContract](interfaces/_types_.makecontract.md) + - [Metadata](interfaces/_types_.metadata.md) + - [RpcObservable](interfaces/_types_.rpcobservable.md) + - [RpcObservableOptions](interfaces/_types_.rpcobservableoptions.md) + - [TxStatus](interfaces/_types_.txstatus.md) - utils - [utils/isLoading](api/modules/_utils_isloading_.md) - [utils/operators/withoutLoading](api/modules/_utils_operators_withoutloading_.md) diff --git a/packages/light.js/docs/api/SUMMARY.md b/packages/light.js/docs/api/SUMMARY.md index 9aac0c6b..9208dd64 100644 --- a/packages/light.js/docs/api/SUMMARY.md +++ b/packages/light.js/docs/api/SUMMARY.md @@ -1,27 +1,33 @@ * ["api"](modules/_api_.md) * ["frequency/accounts"](modules/_frequency_accounts_.md) * ["frequency/blocks"](modules/_frequency_blocks_.md) +* ["frequency/frequency"](modules/_frequency_frequency_.md) * ["frequency/health"](modules/_frequency_health_.md) * ["frequency/other"](modules/_frequency_other_.md) * ["frequency/time"](modules/_frequency_time_.md) -* ["frequency/utils/createOnFromPubsub"](modules/_frequency_utils_createonfrompubsub_.md) -* ["rpc/eth/eth"](modules/_rpc_eth_eth_.md) -* ["rpc/net/net"](modules/_rpc_net_net_.md) +* ["frequency/utils/createPubsubObservable"](modules/_frequency_utils_createpubsubobservable_.md) +* ["rpc/eth"](modules/_rpc_eth_.md) +* ["rpc/net"](modules/_rpc_net_.md) * ["rpc/other/makeContract"](modules/_rpc_other_makecontract_.md) + * [MakeContract](interfaces/_rpc_other_makecontract_.makecontract.md) * ["rpc/other/post"](modules/_rpc_other_post_.md) -* ["rpc/parity/parity"](modules/_rpc_parity_parity_.md) + * [PostOptions](interfaces/_rpc_other_post_.postoptions.md) +* ["rpc/parity"](modules/_rpc_parity_.md) +* ["rpc/rpc"](modules/_rpc_rpc_.md) * ["rpc/utils/createRpc"](modules/_rpc_utils_createrpc_.md) * ["types"](modules/_types_.md) * [FrequencyObservable](interfaces/_types_.frequencyobservable.md) + * [FrequencyObservableOptions](interfaces/_types_.frequencyobservableoptions.md) + * [MakeContract](interfaces/_types_.makecontract.md) * [Metadata](interfaces/_types_.metadata.md) * [RpcObservable](interfaces/_types_.rpcobservable.md) + * [RpcObservableOptions](interfaces/_types_.rpcobservableoptions.md) * [TxStatus](interfaces/_types_.txstatus.md) * ["utils/isLoading"](modules/_utils_isloading_.md) * ["utils/isObservable"](modules/_utils_isobservable_.md) * ["utils/operators/distinctReplayRefCount"](modules/_utils_operators_distinctreplayrefcount_.md) +* ["utils/operators/distinctValues"](modules/_utils_operators_distinctvalues_.md) * ["utils/operators/switchMapPromise"](modules/_utils_operators_switchmappromise_.md) * ["utils/operators/withoutLoading"](modules/_utils_operators_withoutloading_.md) * ["utils/testHelpers/mockApi"](modules/_utils_testhelpers_mockapi_.md) * ["utils/testHelpers/mockRpc"](modules/_utils_testhelpers_mockrpc_.md) -* ["utils/testHelpers/testFrequency"](modules/_utils_testhelpers_testfrequency_.md) -* ["utils/testHelpers/testRpc"](modules/_utils_testhelpers_testrpc_.md) diff --git a/packages/light.js/docs/api/interfaces/_rpc_other_makecontract_.makecontract.md b/packages/light.js/docs/api/interfaces/_rpc_other_makecontract_.makecontract.md new file mode 100644 index 00000000..d32b762d --- /dev/null +++ b/packages/light.js/docs/api/interfaces/_rpc_other_makecontract_.makecontract.md @@ -0,0 +1,40 @@ + + +# Hierarchy + +**MakeContract** + +# Indexable + +\[index: `string`\]:  `any` | `string` | `function` + +# Properties + + + +## abi + +**● abi**: *`any`* + +*Defined in [rpc/other/makeContract.ts:18](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/other/makeContract.ts#L18)* + +___ + + +## address + +**● address**: *`string`* + +*Defined in [rpc/other/makeContract.ts:19](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/other/makeContract.ts#L19)* + +___ + + +## contractObject + +**● contractObject**: *`any`* + +*Defined in [rpc/other/makeContract.ts:20](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/other/makeContract.ts#L20)* + +___ + diff --git a/packages/light.js/docs/api/interfaces/_rpc_other_post_.postoptions.md b/packages/light.js/docs/api/interfaces/_rpc_other_post_.postoptions.md new file mode 100644 index 00000000..f1a3c89e --- /dev/null +++ b/packages/light.js/docs/api/interfaces/_rpc_other_post_.postoptions.md @@ -0,0 +1,31 @@ + + +# Hierarchy + + [RpcObservableOptions](_types_.rpcobservableoptions.md) + +**↳ PostOptions** + +# Properties + + + +## `` estimate + +**● estimate**: *`boolean`* + +*Defined in [rpc/other/post.ts:13](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/other/post.ts#L13)* + +___ + + +## `` provider + +**● provider**: *`any`* + +*Inherited from [RpcObservableOptions](_types_.rpcobservableoptions.md).[provider](_types_.rpcobservableoptions.md#provider)* + +*Defined in [types.ts:72](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L72)* + +___ + diff --git a/packages/light.js/docs/api/interfaces/_types_.__global.window.md b/packages/light.js/docs/api/interfaces/_types_.__global.window.md new file mode 100644 index 00000000..f9df7551 --- /dev/null +++ b/packages/light.js/docs/api/interfaces/_types_.__global.window.md @@ -0,0 +1,18 @@ + + +# Hierarchy + +**Window** + +# Properties + + + +## parity + +**● parity**: *`any`* + +*Defined in [types.ts:14](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L14)* + +___ + diff --git a/packages/light.js/docs/api/interfaces/_types_.frequencyobservable.md b/packages/light.js/docs/api/interfaces/_types_.frequencyobservable.md index 97ffae11..cedb5397 100644 --- a/packages/light.js/docs/api/interfaces/_types_.frequencyobservable.md +++ b/packages/light.js/docs/api/interfaces/_types_.frequencyobservable.md @@ -4,585 +4,18 @@ #### T # Hierarchy - `Observable`<`T`> +**FrequencyObservable** -**↳ FrequencyObservable** +# Callable +▸ **__call**(options?: *[FrequencyObservableOptions](_types_.frequencyobservableoptions.md)*): `Observable`<`T`> -# Implements - -* `Subscribable`<`T`> - -# Constructors - - - -## constructor - -⊕ **new FrequencyObservable**(subscribe?: *`function`*): [FrequencyObservable](_types_.frequencyobservable.md) - -*Inherited from Observable.__constructor* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:19* - -*__constructor__*: - -**Parameters:** - -| Param | Type | Description | -| ------ | ------ | ------ | -| `Optional` subscribe | `function` | the function that is called when the Observable is initially subscribed to. This function is given a Subscriber, to which new values can be \`next\`ed, or an \`error\` method can be called to raise an error, or \`complete\` can be called to notify of a successful completion. | - -**Returns:** [FrequencyObservable](_types_.frequencyobservable.md) - -___ - -# Properties - - - -## _isScalar - -**● _isScalar**: *`boolean`* - -*Inherited from Observable._isScalar* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:15* - -Internal implementation detail, do not use directly. - -___ - - -## `` metadata - -**● metadata**: *`object`* - -*Defined in [types.ts:38](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L38)* - -#### Type declaration - -___ - - -## operator - -**● operator**: *`Operator`<`any`, `T`>* - -*Inherited from Observable.operator* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:19* - -*__deprecated__*: This is an internal implementation detail, do not use. - -___ - - -## source - -**● source**: *`Observable`<`any`>* - -*Inherited from Observable.source* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:17* - -*__deprecated__*: This is an internal implementation detail, do not use. - -___ - - -## `` create - -**● create**: *`Function`* - -*Inherited from Observable.create* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:37* - -Creates a new cold Observable by calling the Observable constructor -*__static__*: true - -*__owner__*: Observable - -*__method__*: create - -*__param__*: the subscriber function to be passed to the Observable constructor - -*__returns__*: a new cold observable - -*__nocollapse__*: - -___ - - -## `` if - -**● if**: *`iif`* - -*Inherited from Observable.if* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:64* - -*__nocollapse__*: - -*__deprecated__*: In favor of iif creation function: import { iif } from 'rxjs'; - -___ - - -## `` throw - -**● throw**: *`throwError`* - -*Inherited from Observable.throw* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:69* - -*__nocollapse__*: - -*__deprecated__*: In favor of throwError creation function: import { throwError } from 'rxjs'; - -___ - -# Methods - - - -## _subscribe - -▸ **_subscribe**(subscriber: *`Subscriber`<`any`>*): `TeardownLogic` - -*Inherited from Observable._subscribe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:59* - -*__deprecated__*: This is an internal implementation detail, do not use. +*Defined in [types.ts:46](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L46)* **Parameters:** | Param | Type | | ------ | ------ | -| subscriber | `Subscriber`<`any`> | - -**Returns:** `TeardownLogic` - -___ - - -## _trySubscribe - -▸ **_trySubscribe**(sink: *`Subscriber`<`T`>*): `TeardownLogic` - -*Inherited from Observable._trySubscribe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:49* - -*__deprecated__*: This is an internal implementation detail, do not use. - -**Parameters:** - -| Param | Type | -| ------ | ------ | -| sink | `Subscriber`<`T`> | - -**Returns:** `TeardownLogic` - -___ - - -## forEach - -▸ **forEach**(next: *`function`*, promiseCtor?: *`PromiseConstructorLike`*): `Promise`<`void`> - -*Inherited from Observable.forEach* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:57* - -*__method__*: forEach - -**Parameters:** - -| Param | Type | Description | -| ------ | ------ | ------ | -| next | `function` | a handler for each value emitted by the observable | -| `Optional` promiseCtor | `PromiseConstructorLike` | - -**Returns:** `Promise`<`void`> -a promise that either resolves on observable completion or - rejects with the handled error - -___ - - -## lift - -▸ **lift**R(operator: *`Operator`<`T`, `R`>*): `Observable`<`R`> - -*Inherited from Observable.lift* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:45* - -Creates a new Observable, with this Observable as the source, and the passed operator defined as the new observable's operator. -*__method__*: lift - -**Type parameters:** - -#### R -**Parameters:** - -| Param | Type | Description | -| ------ | ------ | ------ | -| operator | `Operator`<`T`, `R`> | the operator defining the operation to take on the observable | - -**Returns:** `Observable`<`R`> -a new observable with the Operator applied - -___ - - -## pipe - -▸ **pipe**(): `Observable`<`T`> - -▸ **pipe**A(op1: *`OperatorFunction`<`T`, `A`>*): `Observable`<`A`> - -▸ **pipe**A,B(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*): `Observable`<`B`> - -▸ **pipe**A,B,C(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*, op3: *`OperatorFunction`<`B`, `C`>*): `Observable`<`C`> - -▸ **pipe**A,B,C,D(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*, op3: *`OperatorFunction`<`B`, `C`>*, op4: *`OperatorFunction`<`C`, `D`>*): `Observable`<`D`> - -▸ **pipe**A,B,C,D,E(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*, op3: *`OperatorFunction`<`B`, `C`>*, op4: *`OperatorFunction`<`C`, `D`>*, op5: *`OperatorFunction`<`D`, `E`>*): `Observable`<`E`> - -▸ **pipe**A,B,C,D,E,F(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*, op3: *`OperatorFunction`<`B`, `C`>*, op4: *`OperatorFunction`<`C`, `D`>*, op5: *`OperatorFunction`<`D`, `E`>*, op6: *`OperatorFunction`<`E`, `F`>*): `Observable`<`F`> - -▸ **pipe**A,B,C,D,E,F,G(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*, op3: *`OperatorFunction`<`B`, `C`>*, op4: *`OperatorFunction`<`C`, `D`>*, op5: *`OperatorFunction`<`D`, `E`>*, op6: *`OperatorFunction`<`E`, `F`>*, op7: *`OperatorFunction`<`F`, `G`>*): `Observable`<`G`> - -▸ **pipe**A,B,C,D,E,F,G,H(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*, op3: *`OperatorFunction`<`B`, `C`>*, op4: *`OperatorFunction`<`C`, `D`>*, op5: *`OperatorFunction`<`D`, `E`>*, op6: *`OperatorFunction`<`E`, `F`>*, op7: *`OperatorFunction`<`F`, `G`>*, op8: *`OperatorFunction`<`G`, `H`>*): `Observable`<`H`> - -▸ **pipe**A,B,C,D,E,F,G,H,I(op1: *`OperatorFunction`<`T`, `A`>*, op2: *`OperatorFunction`<`A`, `B`>*, op3: *`OperatorFunction`<`B`, `C`>*, op4: *`OperatorFunction`<`C`, `D`>*, op5: *`OperatorFunction`<`D`, `E`>*, op6: *`OperatorFunction`<`E`, `F`>*, op7: *`OperatorFunction`<`F`, `G`>*, op8: *`OperatorFunction`<`G`, `H`>*, op9: *`OperatorFunction`<`H`, `I`>*): `Observable`<`I`> - -▸ **pipe**R(...operations: *`OperatorFunction`<`any`, `any`>[]*): `Observable`<`R`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:70* +| `Optional` options | [FrequencyObservableOptions](_types_.frequencyobservableoptions.md) | **Returns:** `Observable`<`T`> -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:71* - -**Type parameters:** - -#### A -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | - -**Returns:** `Observable`<`A`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:72* - -**Type parameters:** - -#### A -#### B -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | - -**Returns:** `Observable`<`B`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:73* - -**Type parameters:** - -#### A -#### B -#### C -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | -| op3 | `OperatorFunction`<`B`, `C`> | - -**Returns:** `Observable`<`C`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:74* - -**Type parameters:** - -#### A -#### B -#### C -#### D -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | -| op3 | `OperatorFunction`<`B`, `C`> | -| op4 | `OperatorFunction`<`C`, `D`> | - -**Returns:** `Observable`<`D`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:75* - -**Type parameters:** - -#### A -#### B -#### C -#### D -#### E -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | -| op3 | `OperatorFunction`<`B`, `C`> | -| op4 | `OperatorFunction`<`C`, `D`> | -| op5 | `OperatorFunction`<`D`, `E`> | - -**Returns:** `Observable`<`E`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:76* - -**Type parameters:** - -#### A -#### B -#### C -#### D -#### E -#### F -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | -| op3 | `OperatorFunction`<`B`, `C`> | -| op4 | `OperatorFunction`<`C`, `D`> | -| op5 | `OperatorFunction`<`D`, `E`> | -| op6 | `OperatorFunction`<`E`, `F`> | - -**Returns:** `Observable`<`F`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:77* - -**Type parameters:** - -#### A -#### B -#### C -#### D -#### E -#### F -#### G -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | -| op3 | `OperatorFunction`<`B`, `C`> | -| op4 | `OperatorFunction`<`C`, `D`> | -| op5 | `OperatorFunction`<`D`, `E`> | -| op6 | `OperatorFunction`<`E`, `F`> | -| op7 | `OperatorFunction`<`F`, `G`> | - -**Returns:** `Observable`<`G`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:78* - -**Type parameters:** - -#### A -#### B -#### C -#### D -#### E -#### F -#### G -#### H -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | -| op3 | `OperatorFunction`<`B`, `C`> | -| op4 | `OperatorFunction`<`C`, `D`> | -| op5 | `OperatorFunction`<`D`, `E`> | -| op6 | `OperatorFunction`<`E`, `F`> | -| op7 | `OperatorFunction`<`F`, `G`> | -| op8 | `OperatorFunction`<`G`, `H`> | - -**Returns:** `Observable`<`H`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:79* - -**Type parameters:** - -#### A -#### B -#### C -#### D -#### E -#### F -#### G -#### H -#### I -**Parameters:** - -| Param | Type | -| ------ | ------ | -| op1 | `OperatorFunction`<`T`, `A`> | -| op2 | `OperatorFunction`<`A`, `B`> | -| op3 | `OperatorFunction`<`B`, `C`> | -| op4 | `OperatorFunction`<`C`, `D`> | -| op5 | `OperatorFunction`<`D`, `E`> | -| op6 | `OperatorFunction`<`E`, `F`> | -| op7 | `OperatorFunction`<`F`, `G`> | -| op8 | `OperatorFunction`<`G`, `H`> | -| op9 | `OperatorFunction`<`H`, `I`> | - -**Returns:** `Observable`<`I`> - -*Inherited from Observable.pipe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:80* - -**Type parameters:** - -#### R -**Parameters:** - -| Param | Type | -| ------ | ------ | -| `Rest` operations | `OperatorFunction`<`any`, `any`>[] | - -**Returns:** `Observable`<`R`> - -___ - - -## subscribe - -▸ **subscribe**(observer?: *`PartialObserver`<`T`>*): `Subscription` - -▸ **subscribe**(next?: *`function`*, error?: *`function`*, complete?: *`function`*): `Subscription` - -*Inherited from Observable.subscribe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:46* - -**Parameters:** - -| Param | Type | -| ------ | ------ | -| `Optional` observer | `PartialObserver`<`T`> | - -**Returns:** `Subscription` - -*Inherited from Observable.subscribe* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:47* - -**Parameters:** - -| Param | Type | -| ------ | ------ | -| `Optional` next | `function` | -| `Optional` error | `function` | -| `Optional` complete | `function` | - -**Returns:** `Subscription` - -___ - - -## toPromise - -▸ **toPromise**T(this: *`Observable`<`T`>*): `Promise`<`T`> - -▸ **toPromise**T(this: *`Observable`<`T`>*, PromiseCtor: *`PromiseConstructor`*): `Promise`<`T`> - -▸ **toPromise**T(this: *`Observable`<`T`>*, PromiseCtor: *`PromiseConstructorLike`*): `Promise`<`T`> - -*Inherited from Observable.toPromise* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:81* - -**Type parameters:** - -#### T -**Parameters:** - -| Param | Type | -| ------ | ------ | -| this | `Observable`<`T`> | - -**Returns:** `Promise`<`T`> - -*Inherited from Observable.toPromise* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:82* - -**Type parameters:** - -#### T -**Parameters:** - -| Param | Type | -| ------ | ------ | -| this | `Observable`<`T`> | -| PromiseCtor | `PromiseConstructor` | - -**Returns:** `Promise`<`T`> - -*Inherited from Observable.toPromise* - -*Defined in /Users/amaurymartiny/Workspaces/js-libs/node_modules/rxjs/internal/Observable.d.ts:83* - -**Type parameters:** - -#### T -**Parameters:** - -| Param | Type | -| ------ | ------ | -| this | `Observable`<`T`> | -| PromiseCtor | `PromiseConstructorLike` | - -**Returns:** `Promise`<`T`> - -___ - diff --git a/packages/light.js/docs/api/interfaces/_types_.frequencyobservableoptions.md b/packages/light.js/docs/api/interfaces/_types_.frequencyobservableoptions.md new file mode 100644 index 00000000..ef5355e9 --- /dev/null +++ b/packages/light.js/docs/api/interfaces/_types_.frequencyobservableoptions.md @@ -0,0 +1,18 @@ + + +# Hierarchy + +**FrequencyObservableOptions** + +# Properties + + + +## `` provider + +**● provider**: *`any`* + +*Defined in [types.ts:43](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L43)* + +___ + diff --git a/packages/light.js/docs/api/interfaces/_types_.makecontract.md b/packages/light.js/docs/api/interfaces/_types_.makecontract.md new file mode 100644 index 00000000..a348d0ba --- /dev/null +++ b/packages/light.js/docs/api/interfaces/_types_.makecontract.md @@ -0,0 +1,40 @@ + + +# Hierarchy + +**MakeContract** + +# Indexable + +\[index: `string`\]:  `any` | `string` | `function` + +# Properties + + + +## abi + +**● abi**: *`any`* + +*Defined in [types.ts:55](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L55)* + +___ + + +## address + +**● address**: *`string`* + +*Defined in [types.ts:56](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L56)* + +___ + + +## contractObject + +**● contractObject**: *`any`* + +*Defined in [types.ts:57](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L57)* + +___ + diff --git a/packages/light.js/docs/api/interfaces/_types_.metadata.md b/packages/light.js/docs/api/interfaces/_types_.metadata.md index 8042242d..c68cdcd3 100644 --- a/packages/light.js/docs/api/interfaces/_types_.metadata.md +++ b/packages/light.js/docs/api/interfaces/_types_.metadata.md @@ -15,7 +15,7 @@ **● calledWithArgs**: *`object`* -*Defined in [types.ts:27](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L27)* +*Defined in [types.ts:30](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L30)* #### Type declaration @@ -28,7 +28,7 @@ ___ **● calls**: *`string`[]* -*Defined in [types.ts:30](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L30)* +*Defined in [types.ts:33](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L33)* ___ @@ -37,7 +37,7 @@ ___ **● dependsOn**: *[RpcObservable](_types_.rpcobservable.md)<`any`, `Source`>* -*Defined in [types.ts:31](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L31)* +*Defined in [types.ts:34](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L34)* ___ @@ -46,7 +46,7 @@ ___ **● frequency**: *[FrequencyObservable](_types_.frequencyobservable.md)<`Source`>[]* -*Defined in [types.ts:32](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L32)* +*Defined in [types.ts:35](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L35)* ___ @@ -55,7 +55,7 @@ ___ **● name**: *`string`* -*Defined in [types.ts:33](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L33)* +*Defined in [types.ts:36](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L36)* ___ @@ -64,7 +64,7 @@ ___ **● pipes**: *`function`* -*Defined in [types.ts:34](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L34)* +*Defined in [types.ts:37](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L37)* #### Type declaration ▸(...args: *`any`[]*): `OperatorFunction`<`Source`, `Out`>[] diff --git a/packages/light.js/docs/api/interfaces/_types_.rpcobservable.md b/packages/light.js/docs/api/interfaces/_types_.rpcobservable.md index a861fd98..4a2ba505 100644 --- a/packages/light.js/docs/api/interfaces/_types_.rpcobservable.md +++ b/packages/light.js/docs/api/interfaces/_types_.rpcobservable.md @@ -10,7 +10,7 @@ # Callable ▸ **__call**(...args: *`any`[]*): `Observable`<`Out`> -*Defined in [types.ts:41](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L41)* +*Defined in [types.ts:63](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L63)* **Parameters:** @@ -28,7 +28,7 @@ **● metadata**: *[Metadata](_types_.metadata.md)<`Source`, `Out`>* -*Defined in [types.ts:43](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L43)* +*Defined in [types.ts:65](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L65)* ___ @@ -40,7 +40,7 @@ ___ ▸ **setFrequency**(frequency: *[FrequencyObservable](_types_.frequencyobservable.md)<`Source`>[]*): `void` -*Defined in [types.ts:44](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L44)* +*Defined in [types.ts:66](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L66)* **Parameters:** diff --git a/packages/light.js/docs/api/interfaces/_types_.rpcobservableoptions.md b/packages/light.js/docs/api/interfaces/_types_.rpcobservableoptions.md new file mode 100644 index 00000000..9ec1f835 --- /dev/null +++ b/packages/light.js/docs/api/interfaces/_types_.rpcobservableoptions.md @@ -0,0 +1,20 @@ + + +# Hierarchy + +**RpcObservableOptions** + +↳ [PostOptions](_rpc_other_post_.postoptions.md) + +# Properties + + + +## `` provider + +**● provider**: *`any`* + +*Defined in [types.ts:72](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L72)* + +___ + diff --git a/packages/light.js/docs/api/interfaces/_types_.txstatus.md b/packages/light.js/docs/api/interfaces/_types_.txstatus.md index a96f23af..eb958f32 100644 --- a/packages/light.js/docs/api/interfaces/_types_.txstatus.md +++ b/packages/light.js/docs/api/interfaces/_types_.txstatus.md @@ -12,7 +12,7 @@ **● confirmed**: *`any`* -*Defined in [types.ts:55](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L55)* +*Defined in [types.ts:83](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L83)* ___ @@ -21,7 +21,7 @@ ___ **● estimated**: *`BigNumber`* -*Defined in [types.ts:57](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L57)* +*Defined in [types.ts:85](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L85)* ___ @@ -30,7 +30,7 @@ ___ **● estimating**: *`boolean`* -*Defined in [types.ts:56](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L56)* +*Defined in [types.ts:84](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L84)* ___ @@ -39,7 +39,7 @@ ___ **● failed**: *`Error`* -*Defined in [types.ts:58](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L58)* +*Defined in [types.ts:86](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L86)* ___ @@ -48,7 +48,7 @@ ___ **● requested**: *`string`* -*Defined in [types.ts:59](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L59)* +*Defined in [types.ts:87](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L87)* ___ @@ -57,7 +57,7 @@ ___ **● schedule**: *`any`* -*Defined in [types.ts:60](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L60)* +*Defined in [types.ts:88](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L88)* ___ @@ -66,7 +66,7 @@ ___ **● signed**: *`string`* -*Defined in [types.ts:61](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L61)* +*Defined in [types.ts:89](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L89)* ___ diff --git a/packages/light.js/docs/api/modules/_api_.md b/packages/light.js/docs/api/modules/_api_.md index 5166a29d..4ec425c5 100644 --- a/packages/light.js/docs/api/modules/_api_.md +++ b/packages/light.js/docs/api/modules/_api_.md @@ -1,5 +1,17 @@ +# Variables + + + +## `` api + +**● api**: *`any`* + +*Defined in [api.ts:10](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/api.ts#L10)* + +___ + # Functions @@ -8,7 +20,7 @@ ▸ **getApi**(): `any` -*Defined in [api.ts:62](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/api.ts#L62)* +*Defined in [api.ts:51](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/api.ts#L51)* We only ever use api() at call-time of functions; this allows the options (particularly the transport option) to be changed dynamically and the data structure to be reused. @@ -22,7 +34,7 @@ ___ ▸ **setApi**(newApi: *`any`*): `void` -*Defined in [api.ts:32](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/api.ts#L32)* +*Defined in [api.ts:26](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/api.ts#L26)* Sets a new Api object. @@ -39,9 +51,9 @@ ___ ## `` setProvider -▸ **setProvider**(provider: *`any`*): `void` +▸ **setProvider**(provider?: *`any`*): `void` -*Defined in [api.ts:46](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/api.ts#L46)* +*Defined in [api.ts:40](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/api.ts#L40)* Sets a new Ethereum provider object. @@ -49,7 +61,7 @@ Sets a new Ethereum provider object. | Param | Type | Description | | ------ | ------ | ------ | -| provider | `any` | An Ethereum provider object. | +| `Optional` provider | `any` | An Ethereum provider object. | **Returns:** `void` diff --git a/packages/light.js/docs/api/modules/_frequency_accounts_.md b/packages/light.js/docs/api/modules/_frequency_accounts_.md index a2ef8b73..898f830d 100644 --- a/packages/light.js/docs/api/modules/_frequency_accounts_.md +++ b/packages/light.js/docs/api/modules/_frequency_accounts_.md @@ -1,33 +1,43 @@ -# Variables +# Functions -## `` onAccountsChanged$ +## onAccountsChanged$ -**● onAccountsChanged$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`string`[]>* = createOnFromPubsub( - 'eth_accounts', - api -) +▸ **onAccountsChanged$**(options?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`<`string`[]> -*Defined in [frequency/accounts.ts:13](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/accounts.ts#L13)* +*Defined in [frequency/accounts.ts:14](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/accounts.ts#L14)* Observable that emits each time the default account changes +**Parameters:** + +| Param | Type | Description | +| ------ | ------ | ------ | +| `Optional` options | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | Options to pass to [FrequencyObservable](../interfaces/_types_.frequencyobservable.md). | + +**Returns:** `Observable`<`string`[]> + ___ -## `` onAccountsInfoChanged$ +## onAccountsInfoChanged$ -**● onAccountsInfoChanged$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`object`>* = createOnFromPubsub( - 'parity_accountsInfo', - api -) +▸ **onAccountsInfoChanged$**(options?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`<`object`> -*Defined in [frequency/accounts.ts:22](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/accounts.ts#L22)* +*Defined in [frequency/accounts.ts:23](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/accounts.ts#L23)* Observable that emits each time the default account changes +**Parameters:** + +| Param | Type | Description | +| ------ | ------ | ------ | +| `Optional` options | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | Options to pass to [FrequencyObservable](../interfaces/_types_.frequencyobservable.md). | + +**Returns:** `Observable`<`object`> + ___ diff --git a/packages/light.js/docs/api/modules/_frequency_blocks_.md b/packages/light.js/docs/api/modules/_frequency_blocks_.md index 819efd2d..70503df2 100644 --- a/packages/light.js/docs/api/modules/_frequency_blocks_.md +++ b/packages/light.js/docs/api/modules/_frequency_blocks_.md @@ -1,45 +1,24 @@ -# Variables +# Functions - - -## `` onEvery2Blocks$ - -**● onEvery2Blocks$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`BigNumber`>* = onEveryBlock$.pipe( - filter(n => +n % 2 === 0) // Around ~30s on mainnet // TODO Use isEqualTo and mod from bignumber.js -) as FrequencyObservable - -*Defined in [frequency/blocks.ts:25](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/blocks.ts#L25)* - -Observable that emits on every 2nd block. - -___ - - -## `` onEvery4Blocks$ - -**● onEvery4Blocks$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`BigNumber`>* = onEveryBlock$.pipe( - filter(n => +n % 4 === 0) // Around ~1min on mainnet // TODO Use isEqualTo and mod from bignumber.js -) as FrequencyObservable + -*Defined in [frequency/blocks.ts:33](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/blocks.ts#L33)* +## onEveryBlock$ -Observable that emits on every 4th block. +▸ **onEveryBlock$**(options?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`<`BigNumber`> -___ - +*Defined in [frequency/blocks.ts:16](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/blocks.ts#L16)* -## `` onEveryBlock$ +Observable that emits on every new block. -**● onEveryBlock$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`BigNumber`>* = createOnFromPubsub( - 'eth_blockNumber', - api -) +**Parameters:** -*Defined in [frequency/blocks.ts:16](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/blocks.ts#L16)* +| Param | Type | Description | +| ------ | ------ | ------ | +| `Optional` options | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | Options to pass to [FrequencyObservable](../interfaces/_types_.frequencyobservable.md). | -Observable that emits on every new block. +**Returns:** `Observable`<`BigNumber`> ___ diff --git a/packages/light.js/docs/api/modules/_frequency_frequency_.md b/packages/light.js/docs/api/modules/_frequency_frequency_.md new file mode 100644 index 00000000..33e31125 --- /dev/null +++ b/packages/light.js/docs/api/modules/_frequency_frequency_.md @@ -0,0 +1,14 @@ + + +# Object literals + + + +## `` frequency + +**frequency**: *`object`* + +*Defined in [frequency/frequency.ts:12](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/frequency.ts#L12)* + +___ + diff --git a/packages/light.js/docs/api/modules/_frequency_health_.md b/packages/light.js/docs/api/modules/_frequency_health_.md index 252e97b5..c86cba05 100644 --- a/packages/light.js/docs/api/modules/_frequency_health_.md +++ b/packages/light.js/docs/api/modules/_frequency_health_.md @@ -1,19 +1,24 @@ -# Variables +# Functions -## `` onSyncingChanged$ +## onSyncingChanged$ -**● onSyncingChanged$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)< `false` | `true` | `object`>* = createOnFromPubsub( - 'eth_syncing', - api -) +▸ **onSyncingChanged$**(options?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`< `false` | `object`> -*Defined in [frequency/health.ts:22](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/health.ts#L22)* +*Defined in [frequency/health.ts:19](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/health.ts#L19)* Observable that emits when syncing status changes. +**Parameters:** + +| Param | Type | Description | +| ------ | ------ | ------ | +| `Optional` options | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | Options to pass to [FrequencyObservable](../interfaces/_types_.frequencyobservable.md). | + +**Returns:** `Observable`< `false` | `object`> + ___ diff --git a/packages/light.js/docs/api/modules/_frequency_other_.md b/packages/light.js/docs/api/modules/_frequency_other_.md index 4199b29e..85ba7329 100644 --- a/packages/light.js/docs/api/modules/_frequency_other_.md +++ b/packages/light.js/docs/api/modules/_frequency_other_.md @@ -1,16 +1,24 @@ -# Variables +# Functions -## `` onStartup$ +## onStartup$ -**● onStartup$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`number`>* = of(0) as FrequencyObservable +▸ **onStartup$**(_?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`<`number`> -*Defined in [frequency/other.ts:13](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/other.ts#L13)* +*Defined in [frequency/other.ts:16](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/other.ts#L16)* Observable that emits only once. +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` _ | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | + +**Returns:** `Observable`<`number`> + ___ diff --git a/packages/light.js/docs/api/modules/_frequency_time_.md b/packages/light.js/docs/api/modules/_frequency_time_.md index f960a5d4..dd21ef80 100644 --- a/packages/light.js/docs/api/modules/_frequency_time_.md +++ b/packages/light.js/docs/api/modules/_frequency_time_.md @@ -1,38 +1,62 @@ -# Variables +# Functions -## `` onEvery2Seconds$ +## onEvery2Seconds$ -**● onEvery2Seconds$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`number`>* = timer(0, 2000) as FrequencyObservable +▸ **onEvery2Seconds$**(_?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`<`number`> -*Defined in [frequency/time.ts:19](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/time.ts#L19)* +*Defined in [frequency/time.ts:23](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/time.ts#L23)* Observable that emits on every other second. +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` _ | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | + +**Returns:** `Observable`<`number`> + ___ -## `` onEvery5Seconds$ +## onEvery5Seconds$ -**● onEvery5Seconds$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`number`>* = timer(0, 5000) as FrequencyObservable +▸ **onEvery5Seconds$**(_?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`<`number`> -*Defined in [frequency/time.ts:25](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/time.ts#L25)* +*Defined in [frequency/time.ts:32](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/time.ts#L32)* Observable that emits every five seconds. +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` _ | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | + +**Returns:** `Observable`<`number`> + ___ -## `` onEverySecond$ +## onEverySecond$ -**● onEverySecond$**: *[FrequencyObservable](../interfaces/_types_.frequencyobservable.md)<`number`>* = timer(0, 1000) as FrequencyObservable +▸ **onEverySecond$**(_?: *[FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md)*): `Observable`<`number`> -*Defined in [frequency/time.ts:13](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/frequency/time.ts#L13)* +*Defined in [frequency/time.ts:14](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/frequency/time.ts#L14)* Observable that emits on every second. +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` _ | [FrequencyObservableOptions](../interfaces/_types_.frequencyobservableoptions.md) | + +**Returns:** `Observable`<`number`> + ___ diff --git a/packages/light.js/docs/api/modules/_frequency_utils_createonfrompubsub_.md b/packages/light.js/docs/api/modules/_frequency_utils_createpubsubobservable_.md similarity index 100% rename from packages/light.js/docs/api/modules/_frequency_utils_createonfrompubsub_.md rename to packages/light.js/docs/api/modules/_frequency_utils_createpubsubobservable_.md diff --git a/packages/light.js/docs/api/modules/_rpc_eth_.md b/packages/light.js/docs/api/modules/_rpc_eth_.md new file mode 100644 index 00000000..0a300f7d --- /dev/null +++ b/packages/light.js/docs/api/modules/_rpc_eth_.md @@ -0,0 +1,128 @@ + + +# Functions + + + +## accounts$ + +▸ **accounts$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`<`string`[]> + +*Defined in [rpc/eth.ts:25](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/eth.ts#L25)* + +Observable which contains the array of all addresses managed by the light client. + +Calls eth_accounts. + +**Parameters:** + +| Param | Type | Description | +| ------ | ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | Options to pass to [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md). | + +**Returns:** `Observable`<`string`[]> +- An Observable containing the list of public addresses. + +___ + + +## balanceOf$ + +▸ **balanceOf$**(address: *[Address](_types_.md#address)*, options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`< `BigNumber` | `Symbol`> + +*Defined in [rpc/eth.ts:39](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/eth.ts#L39)* + +Get the balance of a given account. Calls `eth_getBalance`. + +**Parameters:** + +| Param | Type | Description | +| ------ | ------ | ------ | +| address | [Address](_types_.md#address) | The account address to query the balance. | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | Options to pass to [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md). | + +**Returns:** `Observable`< `BigNumber` | `Symbol`> +- An Observable containing the balance. + +___ + + +## blockNumber$ + +▸ **blockNumber$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`<`BigNumber`> + +*Defined in [rpc/eth.ts:68](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/eth.ts#L68)* + +Get the current block number. + +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | + +**Returns:** `Observable`<`BigNumber`> +- An Observable containing the block height. + +___ + + +## defaultAccount$ + +▸ **defaultAccount$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`<`string`> + +*Defined in [rpc/eth.ts:55](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/eth.ts#L55)* + +Get the default account managed by the light client. + +**Parameters:** + +| Param | Type | Description | +| ------ | ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | Options to pass to [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md). | + +**Returns:** `Observable`<`string`> +- An Observable containing the public address +of the default account. + +___ + + +## myBalance$ + +▸ **myBalance$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`< `BigNumber` | `Symbol`> + +*Defined in [rpc/eth.ts:78](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/eth.ts#L78)* + +Shorthand for fetching the current account's balance. + +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | + +**Returns:** `Observable`< `BigNumber` | `Symbol`> + +___ + + +## syncStatus$ + +▸ **syncStatus$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`< `false` | `true` | `object`> + +*Defined in [rpc/eth.ts:99](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/eth.ts#L99)* + +Get the syncStatus state. + +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | + +**Returns:** `Observable`< `false` | `true` | `object`> +- An Observable containing the syncing state object, or false. + +___ + diff --git a/packages/light.js/docs/api/modules/_rpc_eth_eth_.md b/packages/light.js/docs/api/modules/_rpc_eth_eth_.md deleted file mode 100644 index 8bc6bfe0..00000000 --- a/packages/light.js/docs/api/modules/_rpc_eth_eth_.md +++ /dev/null @@ -1,112 +0,0 @@ - - -# Variables - - - -## `` accounts$ - -**● accounts$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`string`[], `string`[]>* = createRpc$({ - frequency: [onAccountsChanged$], - name: 'accounts$' -}) - -*Defined in [rpc/eth/eth.ts:30](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/eth/eth.ts#L30)* - -Observable which contains the array of all addresses managed by the light client. - -Calls eth_accounts. -*__returns__*: * An Observable containing the list of public addresses. - -___ - - -## `` balanceOf$ - -**● balanceOf$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`any`, `BigNumber`>* = createRpc$({ - calls: ['eth_getBalance'], - frequency: [onEveryBlock$, onStartup$], - name: 'balanceOf$', - pipes: (address: Address) => [ - switchMapPromise(() => api().eth.getBalance(address)) - ] -}) - -*Defined in [rpc/eth/eth.ts:41](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/eth/eth.ts#L41)* - -Get the balance of a given account. Calls `eth_getBalance`. -*__param__*: The account address to query the balance. - -*__returns__*: * An Observable containing the balance. - -___ - - -## `` blockNumber$ - -**● blockNumber$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`BigNumber`, `BigNumber`>* = createRpc$({ - frequency: [onEveryBlock$], - name: 'blockNumber$' -}) - -*Defined in [rpc/eth/eth.ts:67](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/eth/eth.ts#L67)* - -Get the current block number. -*__returns__*: * An Observable containing the block height. - -___ - - -## `` defaultAccount$ - -**● defaultAccount$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`string`[], `string`>* = createRpc$({ - dependsOn: accounts$, - name: 'defaultAccount$', - pipes: () => [map(accounts => accounts[0])] -}) - -*Defined in [rpc/eth/eth.ts:56](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/eth/eth.ts#L56)* - -Get the default account managed by the light client. -*__returns__*: * An Observable containing the public address of the default account. - -___ - - -## `` myBalance$ - -**● myBalance$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`string`, `BigNumber`>* = createRpc$({ - calls: [`eth_getBalance`], - dependsOn: defaultAccount$, - name: 'myBalance$', - pipes: () => [ - switchMap( - defaultAccount => - isNullOrLoading(defaultAccount) - ? of(RPC_LOADING) - : balanceOf$(defaultAccount) - ) - ] -}) - -*Defined in [rpc/eth/eth.ts:75](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/eth/eth.ts#L75)* - -Shorthand for fetching the current account's balance. - -___ - - -## `` syncStatus$ - -**● syncStatus$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)< `false` | `true` | `object`, `false` | `true` | `object`>* = createRpc$({ - frequency: [onSyncingChanged$], - name: 'syncStatus$' -}) - -*Defined in [rpc/eth/eth.ts:94](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/eth/eth.ts#L94)* - -Get the syncStatus state. -*__returns__*: * An Observable containing the syncing state object, or false. - -___ - diff --git a/packages/light.js/docs/api/modules/_rpc_net_.md b/packages/light.js/docs/api/modules/_rpc_net_.md new file mode 100644 index 00000000..d8771d18 --- /dev/null +++ b/packages/light.js/docs/api/modules/_rpc_net_.md @@ -0,0 +1,27 @@ + + +# Functions + + + +## peerCount$ + +▸ **peerCount$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`<`BigNumber`> + +*Defined in [rpc/net.ts:21](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/net.ts#L21)* + +Get the amount of peers. + +Calls `net_peerCount` + +**Parameters:** + +| Param | Type | Description | +| ------ | ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | Options to pass to [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md). | + +**Returns:** `Observable`<`BigNumber`> +- An Observable containing the number. + +___ + diff --git a/packages/light.js/docs/api/modules/_rpc_net_net_.md b/packages/light.js/docs/api/modules/_rpc_net_net_.md deleted file mode 100644 index f28b02f0..00000000 --- a/packages/light.js/docs/api/modules/_rpc_net_net_.md +++ /dev/null @@ -1,24 +0,0 @@ - - -# Variables - - - -## `` peerCount$ - -**● peerCount$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`number`, `BigNumber`>* = createRpc$({ - calls: ['net_peerCount'], - frequency: [onEvery5Seconds$], - name: 'peerCount$', - pipes: () => [switchMapPromise(() => api().net.peerCount())] -}) - -*Defined in [rpc/net/net.ts:20](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/net/net.ts#L20)* - -Get the amount of peers. - -Calls `net_peerCount` -*__returns__*: * An Observable containing the number. - -___ - diff --git a/packages/light.js/docs/api/modules/_rpc_other_makecontract_.md b/packages/light.js/docs/api/modules/_rpc_other_makecontract_.md index c9a102be..ac782080 100644 --- a/packages/light.js/docs/api/modules/_rpc_other_makecontract_.md +++ b/packages/light.js/docs/api/modules/_rpc_other_makecontract_.md @@ -2,76 +2,57 @@ # Variables - + -## `` makeContract +## `` getContract -**● makeContract**: * `(Anonymous function)` & `Memoized`<`(Anonymous function)`> +**● getContract**: * `(Anonymous function)` & `Memoized`<`(Anonymous function)`> * = memoizee( - (address: Address, abiJson: any[]) => { - // use types from @parity/abi - const abi = new Abi(abiJson); - // Variable result will hold the final object to return - const result: MakeContract = { - abi, - address, - get contractObject() { - return getContract(address, abiJson); - } - }; - - // We then copy every key inside contract.instance into our `result` object, - // replacing each the value by an Observable instead of a Promise. - abi.functions.forEach(({ name }: any) => { - // use types from @parity/abi - result[`${name}$`] = (...args: any[]) => { - // We only get the contract when the function is called for the 1st - // time. Note: getContract is memoized, won't create contract on each - // call. - const contract = getContract(address, abiJson); - const method = contract.instance[name]; // Hold the method from the Abi - - // The last arguments in args can be an options object - const options = - args.length === method.inputs.length + 1 ? args.pop() : {}; - - if (method.constant) { - return createRpc({ - frequency: [onEveryBlock$], - name, - pipes: () => [ - switchMapPromise(() => - contract.instance[name].call(options, args) - ) - ] - })(...args); - } else { - return post$({ - to: address, - data: abiEncode( - method.name, - method.inputs.map(({ kind: { type } }: any) => type), // TODO Use @parity/api types - args - ), - ...options - }); - } - }; - }); - - return result; - }, + (address: Address, abiJson: any[], api: any) => + api.newContract(abiJson, address), // use types from @parity/abi { length: 1 } // Only memoize by address ) -*Defined in [rpc/other/makeContract.ts:48](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/other/makeContract.ts#L48)* +*Defined in [rpc/other/makeContract.ts:35](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/other/makeContract.ts#L35)* -Create a contract. +Cache contracts, so that they are: + +* only created after the first call/transaction to a contract has been made +* further calls/transactions to the same contract doesn't recreate the contract *__param__*: The contract address. *__param__*: The contract abi. -*__returns__*: * An object whose keys are all the functions of the contract, and each function return an Observable which will fire when the function resolves. +*__param__*: The api Object. + +*__returns__*: * The contract object as defined in @parity/api. + +___ + +# Functions + + + +## `` makeContract + +▸ **makeContract**(address: *[Address](_types_.md#address)*, abiJson: *`any`[]*, options?: *`object`*): [MakeContract](../interfaces/_rpc_other_makecontract_.makecontract.md) + +*Defined in [rpc/other/makeContract.ts:119](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/other/makeContract.ts#L119)* + +Create a contract. + +**Parameters:** + +| Param | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| address | [Address](_types_.md#address) | - | The contract address. | +| abiJson | `any`[] | - | The contract abi. | +| `Default value` options | `object` | {} | The options to pass in when creating the contract. | + +**Returns:** [MakeContract](../interfaces/_rpc_other_makecontract_.makecontract.md) +- An object whose keys are all the functions of the +contract, and each function return an Observable which will fire when the +function resolves. ___ diff --git a/packages/light.js/docs/api/modules/_rpc_other_post_.md b/packages/light.js/docs/api/modules/_rpc_other_post_.md index 9d7d5855..8b2abfde 100644 --- a/packages/light.js/docs/api/modules/_rpc_other_post_.md +++ b/packages/light.js/docs/api/modules/_rpc_other_post_.md @@ -4,11 +4,11 @@ -## `` post$ +## post$ -▸ **post$**(tx: *[Tx](_types_.md#tx)*, options?: *`object`*): `any` +▸ **post$**(tx: *[Tx](_types_.md#tx)*, options?: *[PostOptions](../interfaces/_rpc_other_post_.postoptions.md)*): `Observable`<[TxStatus](../interfaces/_types_.txstatus.md)> -*Defined in [rpc/other/post.ts:22](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/other/post.ts#L22)* +*Defined in [rpc/other/post.ts:26](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/other/post.ts#L26)* Post a transaction to the network. @@ -19,9 +19,9 @@ Calls, in this order, `eth_estimateGas`, `parity_postTransaction`, `parity_check | Param | Type | Default value | | ------ | ------ | ------ | | tx | [Tx](_types_.md#tx) | - | -| `Default value` options | `object` | {} | +| `Default value` options | [PostOptions](../interfaces/_rpc_other_post_.postoptions.md) | {} | -**Returns:** `any` +**Returns:** `Observable`<[TxStatus](../interfaces/_types_.txstatus.md)> - The status of the transaction. ___ diff --git a/packages/light.js/docs/api/modules/_rpc_parity_.md b/packages/light.js/docs/api/modules/_rpc_parity_.md new file mode 100644 index 00000000..f2a4c913 --- /dev/null +++ b/packages/light.js/docs/api/modules/_rpc_parity_.md @@ -0,0 +1,47 @@ + + +# Functions + + + +## accountsInfo$ + +▸ **accountsInfo$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`<`object`> + +*Defined in [rpc/parity.ts:17](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/parity.ts#L17)* + +Get accounts info. Calls `parity_accountsInfo`. + +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | + +**Returns:** `Observable`<`object`> +- An Observable containing all info that can be +accessed by user concerning accounts. + +___ + + +## chainName$ + +▸ **chainName$**(options?: *[RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md)*): `Observable`<`string`> + +*Defined in [rpc/parity.ts:30](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/parity.ts#L30)* + +Get the name of the current chain. Calls `parity_netChain`. + +**Parameters:** + +| Param | Type | +| ------ | ------ | +| `Optional` options | [RpcObservableOptions](../interfaces/_types_.rpcobservableoptions.md) | + +**Returns:** `Observable`<`string`> +- An Observable containing the name of the +current chain. + +___ + diff --git a/packages/light.js/docs/api/modules/_rpc_parity_parity_.md b/packages/light.js/docs/api/modules/_rpc_parity_parity_.md deleted file mode 100644 index 9bc85347..00000000 --- a/packages/light.js/docs/api/modules/_rpc_parity_parity_.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Variables - - - -## `` accountsInfo$ - -**● accountsInfo$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`object`, `object`>* = createRpc$({ - frequency: [onAccountsInfoChanged$], - name: 'accountsInfo$' -}) - -*Defined in [rpc/parity/parity.ts:18](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/parity/parity.ts#L18)* - -Get accounts info. Calls `parity_accountsInfo`. -*__returns__*: * An Observable containing all info that can be accessed by user concerning accounts. - -___ - - -## `` chainName$ - -**● chainName$**: *[RpcObservable](../interfaces/_types_.rpcobservable.md)<`any`, `string`>* = createRpc$({ - calls: ['parity_netChain'], - frequency: [onStartup$], - name: 'chainName$', - pipes: () => [switchMapPromise(() => api().parity.netChain())] -}) - -*Defined in [rpc/parity/parity.ts:29](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/rpc/parity/parity.ts#L29)* - -Get the name of the current chain. Calls `parity_netChain`. -*__returns__*: * An Observable containing the name of the current chain. - -___ - diff --git a/packages/light.js/docs/api/modules/_rpc_rpc_.md b/packages/light.js/docs/api/modules/_rpc_rpc_.md new file mode 100644 index 00000000..a0119b6c --- /dev/null +++ b/packages/light.js/docs/api/modules/_rpc_rpc_.md @@ -0,0 +1,24 @@ + + +# Object literals + + + +## `` rpc + +**rpc**: *`object`* + +*Defined in [rpc/rpc.ts:11](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/rpc.ts#L11)* + + + +### post$ + +**● post$**: *[post$](_rpc_other_post_.md#post_)* + +*Defined in [rpc/rpc.ts:11](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/rpc/rpc.ts#L11)* + +___ + +___ + diff --git a/packages/light.js/docs/api/modules/_types_.__global.md b/packages/light.js/docs/api/modules/_types_.__global.md new file mode 100644 index 00000000..419912d9 --- /dev/null +++ b/packages/light.js/docs/api/modules/_types_.__global.md @@ -0,0 +1,10 @@ + + +# Index + +### Interfaces + +* [Window](../interfaces/_types_.__global.window.md) + +--- + diff --git a/packages/light.js/docs/api/modules/_types_.md b/packages/light.js/docs/api/modules/_types_.md index d321086f..06507197 100644 --- a/packages/light.js/docs/api/modules/_types_.md +++ b/packages/light.js/docs/api/modules/_types_.md @@ -8,10 +8,12 @@ **ΤAccountsInfo**: *`object`* -*Defined in [types.ts:16](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L16)* +*Defined in [types.ts:19](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L19)* #### Type declaration + name: `String` + ___ @@ -19,7 +21,7 @@ ___ **ΤAddress**: *`string`* -*Defined in [types.ts:21](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L21)* +*Defined in [types.ts:24](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L24)* ___ @@ -28,7 +30,47 @@ ___ **ΤApiValue**: *`any`* -*Defined in [types.ts:24](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L24)* +*Defined in [types.ts:27](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L27)* + +___ + + +## FrequencyKey + +**ΤFrequencyKey**: *`keyof object`* + +*Defined in [types.ts:40](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L40)* + +___ + + +## FrequencyMap + +**ΤFrequencyMap**: *`object`* + +*Defined in [types.ts:50](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L50)* + +#### Type declaration + +___ + + +## RpcKey + +**ΤRpcKey**: *`keyof object`* + +*Defined in [types.ts:61](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L61)* + +___ + + +## RpcMap + +**ΤRpcMap**: *`object`* + +*Defined in [types.ts:69](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L69)* + +#### Type declaration ___ @@ -37,9 +79,15 @@ ___ **ΤTx**: *`object`* -*Defined in [types.ts:48](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/types.ts#L48)* +*Defined in [types.ts:76](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/types.ts#L76)* #### Type declaration + condition: `any` + + from: [Address](_types_.md#address) + + to: [Address](_types_.md#address) + ___ diff --git a/packages/light.js/docs/api/modules/_utils_isloading_.md b/packages/light.js/docs/api/modules/_utils_isloading_.md index 270b3f7d..2a717978 100644 --- a/packages/light.js/docs/api/modules/_utils_isloading_.md +++ b/packages/light.js/docs/api/modules/_utils_isloading_.md @@ -8,7 +8,7 @@ **● RPC_LOADING**: *`unique symbol`* = Symbol('Fetching RPC...') -*Defined in [utils/isLoading.ts:6](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/utils/isLoading.ts#L6)* +*Defined in [utils/isLoading.ts:6](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/isLoading.ts#L6)* ___ @@ -20,7 +20,7 @@ ___ ▸ **isLoading**(value: *`any`*): `boolean` -*Defined in [utils/isLoading.ts:14](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/utils/isLoading.ts#L14)* +*Defined in [utils/isLoading.ts:14](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/isLoading.ts#L14)* Check if a rpc$ value is loading. @@ -40,7 +40,7 @@ ___ ▸ **isNullOrLoading**(value: *`any`*): `boolean` -*Defined in [utils/isLoading.ts:22](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/utils/isLoading.ts#L22)* +*Defined in [utils/isLoading.ts:22](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/isLoading.ts#L22)* Check if a rpc$ value is `null,`undefined` or loading. diff --git a/packages/light.js/docs/api/modules/_utils_testhelpers_testfrequency_.md b/packages/light.js/docs/api/modules/_utils_operators_distinctvalues_.md similarity index 100% rename from packages/light.js/docs/api/modules/_utils_testhelpers_testfrequency_.md rename to packages/light.js/docs/api/modules/_utils_operators_distinctvalues_.md diff --git a/packages/light.js/docs/api/modules/_utils_operators_withoutloading_.md b/packages/light.js/docs/api/modules/_utils_operators_withoutloading_.md index f5984e17..81020891 100644 --- a/packages/light.js/docs/api/modules/_utils_operators_withoutloading_.md +++ b/packages/light.js/docs/api/modules/_utils_operators_withoutloading_.md @@ -8,7 +8,7 @@ ▸ **withoutLoading**(): `(Anonymous function)` -*Defined in [utils/operators/withoutLoading.ts:14](https://github.com/paritytech/js-libs/blob/70247e1/packages/light.js/src/utils/operators/withoutLoading.ts#L14)* +*Defined in [utils/operators/withoutLoading.ts:15](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/operators/withoutLoading.ts#L15)* Filter out the loading states in our observable. diff --git a/packages/light.js/docs/api/modules/_utils_testhelpers_mockapi_.md b/packages/light.js/docs/api/modules/_utils_testhelpers_mockapi_.md index 139597f9..ff124d1e 100644 --- a/packages/light.js/docs/api/modules/_utils_testhelpers_mockapi_.md +++ b/packages/light.js/docs/api/modules/_utils_testhelpers_mockapi_.md @@ -1,2 +1,63 @@ +# Variables + + + +## `` providerCount + +**● providerCount**: *`number`* = 0 + +*Defined in [utils/testHelpers/mockApi.ts:10](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/testHelpers/mockApi.ts#L10)* + +___ + +# Object literals + + + +## `` listOfMockRps + +**listOfMockRps**: *`object`* + +*Defined in [utils/testHelpers/mockApi.ts:24](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/testHelpers/mockApi.ts#L24)* + + + +### eth + +**● eth**: *`string`[]* = ['accounts', 'blockNumber', 'getBalance', 'syncing'] + +*Defined in [utils/testHelpers/mockApi.ts:25](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/testHelpers/mockApi.ts#L25)* + +___ + + +### fake + +**● fake**: *`string`[]* = ['method'] + +*Defined in [utils/testHelpers/mockApi.ts:26](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/testHelpers/mockApi.ts#L26)* + +___ + + +### net + +**● net**: *`string`[]* = ['peerCount'] + +*Defined in [utils/testHelpers/mockApi.ts:27](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/testHelpers/mockApi.ts#L27)* + +___ + + +### parity + +**● parity**: *`string`[]* = ['accountsInfo', 'netChain', 'postTransaction'] + +*Defined in [utils/testHelpers/mockApi.ts:28](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/testHelpers/mockApi.ts#L28)* + +___ + +___ + diff --git a/packages/light.js/docs/api/modules/_utils_testhelpers_mockrpc_.md b/packages/light.js/docs/api/modules/_utils_testhelpers_mockrpc_.md index 139597f9..a1b38d6a 100644 --- a/packages/light.js/docs/api/modules/_utils_testhelpers_mockrpc_.md +++ b/packages/light.js/docs/api/modules/_utils_testhelpers_mockrpc_.md @@ -1,2 +1,14 @@ +# Variables + + + +## `` mockRpc$ + +**● mockRpc$**: *`(Anonymous function)`* = createRpc({ frequency: [() => timer(0, 1000)] })() + +*Defined in [utils/testHelpers/mockRpc.ts:18](https://github.com/paritytech/js-libs/blob/3a885fe/packages/light.js/src/utils/testHelpers/mockRpc.ts#L18)* + +___ + diff --git a/packages/light.js/docs/api/modules/_utils_testhelpers_testrpc_.md b/packages/light.js/docs/api/modules/_utils_testhelpers_testrpc_.md deleted file mode 100644 index 139597f9..00000000 --- a/packages/light.js/docs/api/modules/_utils_testhelpers_testrpc_.md +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/packages/light.js/docs/guides/tutorial3-manipulating-rpcobservables.md b/packages/light.js/docs/guides/tutorial3-manipulating-rpcobservables.md index 2bef650f..1d082849 100644 --- a/packages/light.js/docs/guides/tutorial3-manipulating-rpcobservables.md +++ b/packages/light.js/docs/guides/tutorial3-manipulating-rpcobservables.md @@ -12,17 +12,21 @@ Concretely, in your app, a possible UX would be to show a loading spinner while ### Removing the loading state -However, if this behavior is not desirable for you, the you can add the `withoutLoading` options: +However, if this behavior is not desirable for you, the you can add the `withoutLoading` operator: ```javascript balanceOf$('0x407d73d8a49eeb85d32cf465507dd71d507100c1', { withoutLoading: true -}).subscribe(balance => console.log('balance', balance)); +}) + .pipe(withoutLoading()) + .subscribe(balance => console.log('balance', balance)); ``` In this case, the `Symbol(Fetching RPC...)` will never be logged, and you will only be notified when the balance actually changes. -See here for a working example: https://codesandbox.io/s/z6549wqm5l +See here for a working example: https://codesandbox.io/s/z6549wqm5l. + +`withoutLoading()` here is what we call an RxJS _operator_. It modifies the result each time an Observable fires. Let's see some other operators. ## Operations on Observables diff --git a/packages/light.js/example/src/BalanceOf/BalanceOfAddress/BalanceOfAddress.js b/packages/light.js/example/src/BalanceOf/BalanceOfAddress/BalanceOfAddress.js index ef3b9c3b..722ec9fe 100644 --- a/packages/light.js/example/src/BalanceOf/BalanceOfAddress/BalanceOfAddress.js +++ b/packages/light.js/example/src/BalanceOf/BalanceOfAddress/BalanceOfAddress.js @@ -6,12 +6,15 @@ import React, { Component } from 'react'; import { map } from 'rxjs/operators'; -import { balanceOf$ } from '../../light.js'; +import { balanceOf$, withoutLoading } from '../../light.js'; import light from '../../hoc'; @light({ balance: ownProps => - balanceOf$(ownProps.address, { withoutLoading: true }).pipe(map(_ => +_)) + balanceOf$(ownProps.address).pipe( + withoutLoading(), + map(_ => +_) + ) }) class BalanceOfAddress extends Component { render() { diff --git a/packages/light.js/example/src/index.js b/packages/light.js/example/src/index.js index e4fbfd75..3398dadd 100644 --- a/packages/light.js/example/src/index.js +++ b/packages/light.js/example/src/index.js @@ -8,10 +8,9 @@ import ReactDOM from 'react-dom'; import 'symbol-observable'; // TODO Remove this once https://github.com/acdlite/recompose/pull/660 is merged import App from './App'; -import light, { balanceOf$, frequency } from './light.js'; +import light from './light.js'; import provider from './provider'; light.setProvider(provider); -balanceOf$.setFrequency([frequency.onEvery2Seconds$]); ReactDOM.render(, document.getElementById('root')); diff --git a/packages/light.js/example/src/provider.js b/packages/light.js/example/src/provider.js index 607e1620..58cc4564 100644 --- a/packages/light.js/example/src/provider.js +++ b/packages/light.js/example/src/provider.js @@ -5,10 +5,9 @@ import Api from '@parity/api'; -const provider = - // new Api.Provider.Ws('ws://127.0.0.1:8546', 'VrS2FTt3oWz5CJbe') // Force to use local secure Api - window.web3 - ? window.web3.currentProvider - : new Api.Provider.Ws('ws://127.0.0.1:8546'); // Can add PARITY_TOKEN as 2nd argument to access secure API, e.g. switch default account +export const currentProvider = window.web3 && window.web3.currentProvider; +export const localProvider = new Api.Provider.Ws('ws://127.0.0.1:8546'); + +const provider = currentProvider || localProvider; export default provider; diff --git a/packages/light.js/package.json b/packages/light.js/package.json index 0b47565d..85603fc3 100644 --- a/packages/light.js/package.json +++ b/packages/light.js/package.json @@ -30,13 +30,12 @@ "@parity/api": "^2.1.23", "bignumber.js": "^7.2.1", "debug": "^3.1.0", - "eventemitter3": "^3.1.0", - "json-prune": "^1.1.0", "memoizee": "^0.4.12" }, "devDependencies": { "@types/debug": "^0.0.30", "@types/memoizee": "^0.4.2", + "eventemitter3": "^3.1.0", "rxjs": "^6.2.1" }, "peerDependencies": { diff --git a/packages/light.js/src/ambient.d.ts b/packages/light.js/src/ambient.d.ts index f65322c2..2459c03e 100644 --- a/packages/light.js/src/ambient.d.ts +++ b/packages/light.js/src/ambient.d.ts @@ -9,4 +9,3 @@ declare module '@parity/api'; declare module '@parity/api/lib/util'; declare module '@parity/api/lib/util/encode'; declare module '@parity/api/lib/util/types'; -declare module 'json-prune'; diff --git a/packages/light.js/src/api.spec.ts b/packages/light.js/src/api.spec.ts index 0a540d5d..f843bffa 100644 --- a/packages/light.js/src/api.spec.ts +++ b/packages/light.js/src/api.spec.ts @@ -3,21 +3,23 @@ // // SPDX-License-Identifier: MIT -import { getApi, NullProvider, setApi } from './api'; +import * as Api from '@parity/api'; + +import { getApi, setApi, setProvider } from './api'; import { resolveApi } from './utils/testHelpers/mockApi'; it('should return the Null provider', () => { - expect(getApi().provider instanceof NullProvider).toBe(true); + expect(getApi).toThrow(); }); -it('should correctly set a new Api', () => { - const mockApi = resolveApi(undefined, false); // Pubsub - setApi(mockApi); - expect(getApi()).toBe(mockApi); +it('should correctly set a new api', () => { + const api = resolveApi(); + setApi(api); + expect(getApi()).toBe(api); }); -it('should correctly set a new Api', () => { - const mockApi = resolveApi(undefined, false); // Not pubsub - setApi(mockApi); - expect(getApi()).toBe(mockApi); +it('should correctly set a new provider', () => { + const provider = new Api.Provider.Ws('ws://127.0.0.1:8546'); + setProvider(provider); + expect(getApi().provider).toBe(provider); }); diff --git a/packages/light.js/src/api.ts b/packages/light.js/src/api.ts index 7bbbca77..429a2d3d 100644 --- a/packages/light.js/src/api.ts +++ b/packages/light.js/src/api.ts @@ -4,25 +4,19 @@ // SPDX-License-Identifier: MIT import * as Api from '@parity/api'; -import * as debug from 'debug'; -import * as EventEmitter from 'eventemitter3'; +import * as memoizee from 'memoizee'; +// This is our global api object, to be used if no provider is passed to RpcObservables. let api: any; // TODO @parity/api /** - * Use this null Api provider if the Api hasn't been set by the end user yet. + * Like `return new Api(provider);`, but memoized. * * @ignore */ -export class NullProvider extends EventEmitter { - send(method: string, params: any[]) { - debug('@parity/light.js:api')( - `Calling "${method}" rpc with params "${JSON.stringify( - params - )}", ignoring because Api object not set yet.` - ); - } -} +export const createApiFromProvider = memoizee( + (provider?: any) => new Api(provider) +); /** * Sets a new Api object. @@ -43,13 +37,8 @@ export const setApi = (newApi: any) => { * * @param provider - An Ethereum provider object. */ -export const setProvider = (provider: any) => { - api = new Api(provider); - if (!api.isPubSub) { - console.warn( - `Current provider does not support pubsub. @parity/light.js will poll every second to listen to changes.` - ); - } +export const setProvider = (provider?: any) => { + setApi(createApiFromProvider(provider)); }; /** @@ -61,7 +50,7 @@ export const setProvider = (provider: any) => { */ export const getApi = () => { if (!api) { - api = new Api(new NullProvider()); + throw new Error('Please define a provider before using any RpcObservable.'); } return api; }; diff --git a/packages/light.js/src/frequency/accounts.spec.ts b/packages/light.js/src/frequency/accounts.spec.ts deleted file mode 100644 index 9475277f..00000000 --- a/packages/light.js/src/frequency/accounts.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as accounts from './accounts'; -import testFrequency from '../utils/testHelpers/testFrequency'; - -Object.keys(accounts).forEach(key => - testFrequency(key, (accounts as any)[key]) -); diff --git a/packages/light.js/src/frequency/accounts.ts b/packages/light.js/src/frequency/accounts.ts index 05c5eb46..3b4b22bb 100644 --- a/packages/light.js/src/frequency/accounts.ts +++ b/packages/light.js/src/frequency/accounts.ts @@ -3,24 +3,23 @@ // // SPDX-License-Identifier: MIT -import { AccountsInfo, Address, FrequencyObservable } from '../types'; -import api from '../api'; -import createOnFromPubsub from './utils/createOnFromPubsub'; +import { AccountsInfo, Address, FrequencyObservableOptions } from '../types'; +import createPubsubObservable from './utils/createPubsubObservable'; /** * Observable that emits each time the default account changes + * + * @param options - Options to pass to {@link FrequencyObservable}. */ -export const onAccountsChanged$ = createOnFromPubsub( - 'eth_accounts', - api -); -onAccountsChanged$.metadata = { name: 'onAccountsChanged$' }; +export function onAccountsChanged$(options?: FrequencyObservableOptions) { + return createPubsubObservable('eth_accounts', options); +} /** * Observable that emits each time the default account changes + * + * @param options - Options to pass to {@link FrequencyObservable}. */ -export const onAccountsInfoChanged$ = createOnFromPubsub( - 'parity_accountsInfo', - api -); -onAccountsInfoChanged$.metadata = { name: 'onAccountsInfoChanged$' }; +export function onAccountsInfoChanged$(options?: FrequencyObservableOptions) { + return createPubsubObservable('parity_accountsInfo', options); +} diff --git a/packages/light.js/src/frequency/blocks.spec.ts b/packages/light.js/src/frequency/blocks.spec.ts deleted file mode 100644 index d3ba3bac..00000000 --- a/packages/light.js/src/frequency/blocks.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as blocks from './blocks'; -import testFrequency from '../utils/testHelpers/testFrequency'; - -Object.keys(blocks).forEach(key => testFrequency(key, (blocks as any)[key])); diff --git a/packages/light.js/src/frequency/blocks.ts b/packages/light.js/src/frequency/blocks.ts index d0ab34ed..9bb1551e 100644 --- a/packages/light.js/src/frequency/blocks.ts +++ b/packages/light.js/src/frequency/blocks.ts @@ -4,33 +4,15 @@ // SPDX-License-Identifier: MIT import BigNumber from 'bignumber.js'; -import { filter } from 'rxjs/operators'; -import api from '../api'; -import createOnFromPubsub from './utils/createOnFromPubsub'; -import { FrequencyObservable } from '../types'; +import createPubsubObservable from './utils/createPubsubObservable'; +import { FrequencyObservableOptions } from '../types'; /** * Observable that emits on every new block. + * + * @param options - Options to pass to {@link FrequencyObservable}. */ -export const onEveryBlock$ = createOnFromPubsub( - 'eth_blockNumber', - api -); -onEveryBlock$.metadata = { name: 'onEveryBlock$' }; - -/** - * Observable that emits on every 2nd block. - */ -export const onEvery2Blocks$ = onEveryBlock$.pipe( - filter(n => +n % 2 === 0) // Around ~30s on mainnet // TODO Use isEqualTo and mod from bignumber.js -) as FrequencyObservable; -onEvery2Blocks$.metadata = { name: 'onEvery2Blocks$' }; - -/** - * Observable that emits on every 4th block. - */ -export const onEvery4Blocks$ = onEveryBlock$.pipe( - filter(n => +n % 4 === 0) // Around ~1min on mainnet // TODO Use isEqualTo and mod from bignumber.js -) as FrequencyObservable; -onEvery4Blocks$.metadata = { name: 'onEvery4Blocks$' }; +export function onEveryBlock$(options?: FrequencyObservableOptions) { + return createPubsubObservable('eth_blockNumber', options); +} diff --git a/packages/light.js/src/frequency/frequency.spec.ts b/packages/light.js/src/frequency/frequency.spec.ts new file mode 100644 index 00000000..a72797a0 --- /dev/null +++ b/packages/light.js/src/frequency/frequency.spec.ts @@ -0,0 +1,93 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import * as Api from '@parity/api'; +import { take } from 'rxjs/operators'; + +import frequency from './frequency'; +import { FrequencyObservable, FrequencyKey, FrequencyMap } from '../types'; +import isObservable from '../utils/isObservable'; +import { + MockProvider, + rejectApi, + resolveApi +} from '../utils/testHelpers/mockApi'; +import { setApi } from '@parity/light.js/src/api'; + +jest.mock('@parity/api'); +Api.mockImplementation(() => resolveApi('4')); + +/** + * Helper function to make basic tests for frequency$ observables. + * + * @ignore + */ +const testFrequency = ( + name: string, + frequency$: FrequencyObservable, + resolveWith: any = 'foo' +) => + describe(`${name} frequency`, () => { + beforeEach(() => { + setApi(resolveApi(resolveWith)); + }); + + it('should be an Observable', () => { + expect(isObservable(frequency$())).toBe(true); + }); + + it('should be subscribable', () => { + expect(() => frequency$().subscribe()).not.toThrow(); + }); + + it('should return the same Observable upon re-running (memoization)', () => { + const initial$ = frequency$(); + expect(frequency$()).toBe(initial$); + }); + + it('should return values', done => { + frequency$() + .pipe(take(1)) + .subscribe(data => { + expect(data).not.toBeNull(); + done(); + }); + }); + + // Only the following FrequencyObservables are concerned with API changing + if ( + [ + 'onAccountsChanged', + 'onAccountsInfoChanged', + 'onEveryBlock$', + 'onSyncingChanged' + ].includes(name) + ) { + it('should not return the same Observable if we change Api in between', () => { + const initial$ = frequency$(); + setApi(rejectApi()); + expect(frequency$()).not.toBe(initial$); + }); + + it('should not return the same Observable if options are passed', () => { + const initial$ = frequency$(); + expect(frequency$({ provider: new MockProvider() })).not.toBe(initial$); + }); + + it('should return the same Observable if same options are passed', () => { + const provider = new MockProvider(); + const initial$ = frequency$({ provider }); + expect(frequency$({ provider })).toBe(initial$); + }); + } + }); + +Object.keys(frequency).forEach(key => + testFrequency( + key, + (frequency as FrequencyMap)[key as FrequencyKey], + key.includes('Account') ? ['foo'] : 4 // Give string[] for accounts pubsub, or number elsewhere + ) +); diff --git a/packages/light.js/src/frequency/frequency.ts b/packages/light.js/src/frequency/frequency.ts new file mode 100644 index 00000000..b46434ac --- /dev/null +++ b/packages/light.js/src/frequency/frequency.ts @@ -0,0 +1,20 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import * as accounts from './accounts'; +import * as blocks from './blocks'; +import * as health from './health'; +import * as other from './other'; +import * as time from './time'; + +const frequency = { + ...accounts, + ...blocks, + ...health, + ...other, + ...time +}; + +export default frequency; diff --git a/packages/light.js/src/frequency/health.spec.ts b/packages/light.js/src/frequency/health.spec.ts deleted file mode 100644 index 9e07c991..00000000 --- a/packages/light.js/src/frequency/health.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as health from './health'; -import testFrequency from '../utils/testHelpers/testFrequency'; - -Object.keys(health).forEach(key => testFrequency(key, (health as any)[key])); diff --git a/packages/light.js/src/frequency/health.ts b/packages/light.js/src/frequency/health.ts index a23c86d3..3b4efb6e 100644 --- a/packages/light.js/src/frequency/health.ts +++ b/packages/light.js/src/frequency/health.ts @@ -3,27 +3,19 @@ // // SPDX-License-Identifier: MIT -import api from '../api'; -import createOnFromPubsub from './utils/createOnFromPubsub'; +import createPubsubObservable from './utils/createPubsubObservable'; +import { FrequencyObservableOptions } from '../types'; /** * Observable that emits when syncing status changes. */ // TODO Pubsub doesn't exist on `net_peerCount` -// export const onPeersChange$ = createOnFromPubsub('net_peerCount', api); -// onPeersChange$.metadata = { -// calls: ['net_peerCount'], -// name: 'onPeersChange$' -// }; /** * Observable that emits when syncing status changes. + * + * @param options - Options to pass to {@link FrequencyObservable}. */ -export const onSyncingChanged$ = createOnFromPubsub( - 'eth_syncing', - api -); -onSyncingChanged$.metadata = { - calls: ['eth_syncing'], - name: 'onSyncingChanged$' -}; +export function onSyncingChanged$(options?: FrequencyObservableOptions) { + return createPubsubObservable('eth_syncing', options); +} diff --git a/packages/light.js/src/frequency/index.ts b/packages/light.js/src/frequency/index.ts index c09361f6..148a183d 100644 --- a/packages/light.js/src/frequency/index.ts +++ b/packages/light.js/src/frequency/index.ts @@ -3,8 +3,6 @@ // // SPDX-License-Identifier: MIT -export * from './accounts'; -export * from './blocks'; -export * from './health'; -export * from './other'; -export * from './time'; +import frequency from './frequency'; + +export default frequency; diff --git a/packages/light.js/src/frequency/other.spec.ts b/packages/light.js/src/frequency/other.spec.ts deleted file mode 100644 index 3682df7d..00000000 --- a/packages/light.js/src/frequency/other.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as other from './other'; -import testFrequency from '../utils/testHelpers/testFrequency'; - -Object.keys(other).forEach(key => testFrequency(key, (other as any)[key])); diff --git a/packages/light.js/src/frequency/other.ts b/packages/light.js/src/frequency/other.ts index db57eb53..420abefa 100644 --- a/packages/light.js/src/frequency/other.ts +++ b/packages/light.js/src/frequency/other.ts @@ -4,11 +4,19 @@ // SPDX-License-Identifier: MIT import { of } from 'rxjs'; +import * as memoizee from 'memoizee'; -import { FrequencyObservable } from '../types'; +import { FrequencyObservableOptions } from '../types'; /** * Observable that emits only once. + * + * @param options - Options to pass to {@link FrequencyObservable}. */ -export const onStartup$ = of(0) as FrequencyObservable; -onStartup$.metadata = { name: 'onStartup$' }; +function onStartup$(_?: FrequencyObservableOptions) { + return of(0); +} +// @ts-ignore +onStartup$ = memoizee(onStartup$); + +export { onStartup$ }; diff --git a/packages/light.js/src/frequency/time.spec.ts b/packages/light.js/src/frequency/time.spec.ts deleted file mode 100644 index 45c1a40c..00000000 --- a/packages/light.js/src/frequency/time.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as time from './time'; -import testFrequency from '../utils/testHelpers/testFrequency'; - -Object.keys(time).forEach(key => testFrequency(key, (time as any)[key])); diff --git a/packages/light.js/src/frequency/time.ts b/packages/light.js/src/frequency/time.ts index dd4f637b..bc52db16 100644 --- a/packages/light.js/src/frequency/time.ts +++ b/packages/light.js/src/frequency/time.ts @@ -4,23 +4,35 @@ // SPDX-License-Identifier: MIT import { timer } from 'rxjs'; +import * as memoizee from 'memoizee'; -import { FrequencyObservable } from '../types'; +import { FrequencyObservableOptions } from '../types'; /** * Observable that emits on every second. */ -export const onEverySecond$ = timer(0, 1000) as FrequencyObservable; -onEverySecond$.metadata = { name: 'onEverySecond$' }; +function onEverySecond$(_?: FrequencyObservableOptions) { + return timer(0, 1000); +} +// @ts-ignore +onEverySecond$ = memoizee(onEverySecond$); /** * Observable that emits on every other second. */ -export const onEvery2Seconds$ = timer(0, 2000) as FrequencyObservable; -onEvery2Seconds$.metadata = { name: 'onEvery2Seconds$' }; +function onEvery2Seconds$(_?: FrequencyObservableOptions) { + return timer(0, 2000); +} +// @ts-ignore +onEvery2Seconds$ = memoizee(onEvery2Seconds$); /** * Observable that emits every five seconds. */ -export const onEvery5Seconds$ = timer(0, 5000) as FrequencyObservable; -onEvery5Seconds$.metadata = { name: 'onEvery5Seconds$' }; +function onEvery5Seconds$(_?: FrequencyObservableOptions) { + return timer(0, 5000); +} +// @ts-ignore +onEvery5Seconds$ = memoizee(onEvery5Seconds$); + +export { onEverySecond$, onEvery2Seconds$, onEvery5Seconds$ }; diff --git a/packages/light.js/src/frequency/utils/createOnFromPubsub.ts b/packages/light.js/src/frequency/utils/createOnFromPubsub.ts deleted file mode 100644 index f56448e7..00000000 --- a/packages/light.js/src/frequency/utils/createOnFromPubsub.ts +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as debug from 'debug'; -import { FrequencyObservable } from '../../types'; -import { Observable, Observer, timer } from 'rxjs'; -import { switchMap } from 'rxjs/operators'; - -import { distinctReplayRefCount } from '../../utils/operators/distinctReplayRefCount'; - -/** - * Observable that emits on each pubsub event. - * - * @ignore - * @example onAccountsChanged$, onEveryBlock$... - */ -const createOnFromPubsub = ( - pubsub: string, - api: any // TODO @parity/api -): FrequencyObservable => { - const [namespace, method] = pubsub.split('_'); - - // There's a chance the provider doesn't support pubsub, for example - // MetaMaskProvider. In this case, as suggested on their Github, the best - // solution for now is to poll. - if (!api().isPubSub) { - debug('@parity/light.js:api')( - `Pubsub not available for ${ - api().provider - ? api().provider.constructor.name - : 'current Api provider' - }, polling "${pubsub}" every second.` - ); - return timer(0, 1000).pipe( - switchMap(() => api()[namespace][method]()) - ) as FrequencyObservable; - } - - return Observable.create((observer: Observer) => { - const subscription = api().pubsub[namespace][method]( - (error: Error, result: any) => { - // TODO use @parity/api type for result - if (error) { - observer.error(error); - } else { - observer.next(result); - } - } - ); - return () => - subscription.then((subscriptionId: string) => - api().pubsub.unsubscribe(subscriptionId) - ); - }).pipe(distinctReplayRefCount()); -}; - -export default createOnFromPubsub; diff --git a/packages/light.js/src/frequency/utils/createOnFromPubsub.spec.ts b/packages/light.js/src/frequency/utils/createPubsubObservable.spec.ts similarity index 52% rename from packages/light.js/src/frequency/utils/createOnFromPubsub.spec.ts rename to packages/light.js/src/frequency/utils/createPubsubObservable.spec.ts index d83f0440..669799c4 100644 --- a/packages/light.js/src/frequency/utils/createOnFromPubsub.spec.ts +++ b/packages/light.js/src/frequency/utils/createPubsubObservable.spec.ts @@ -3,43 +3,43 @@ // // SPDX-License-Identifier: MIT -import createOnFromPubsub from './createOnFromPubsub'; +import createPubsubObservable from './createPubsubObservable'; import isObservable from '../../utils/isObservable'; import { rejectApi, resolveApi } from '../../utils/testHelpers/mockApi'; +import { setApi } from '../../api'; it('should return an Observable', () => { - expect(isObservable(createOnFromPubsub('fake_method', resolveApi))).toBe( - true - ); + setApi(resolveApi()); + expect(isObservable(createPubsubObservable('fake_method'))).toBe(true); }); it('should fire an event when pubsub publishes', done => { - createOnFromPubsub('fake_method', resolveApi).subscribe(data => { + setApi(resolveApi()); + createPubsubObservable('fake_method').subscribe(data => { expect(data).toBe('foo'); done(); }); }); it('should fire an error when pubsub errors', done => { - createOnFromPubsub('fake_method', rejectApi).subscribe(null, err => { + setApi(rejectApi()); + createPubsubObservable('fake_method').subscribe(null, err => { expect(err).toEqual(new Error('bar')); done(); }); }); -it('should fire an event when polling pubsub publishes', done => { - createOnFromPubsub('fake_method', () => - resolveApi(undefined, false) - ).subscribe(data => { +it('should fire an event when polling pubsub publishes', done => { + setApi(resolveApi('foo', false)); + createPubsubObservable('fake_method').subscribe(data => { expect(data).toBe('foo'); done(); }); }); it('should fire an error when polling pubsub errors', done => { - createOnFromPubsub('fake_method', () => - rejectApi(undefined, false) - ).subscribe(null, err => { + setApi(rejectApi(new Error('bar'), false)); + createPubsubObservable('fake_method').subscribe(null, err => { expect(err).toEqual(new Error('bar')); done(); }); diff --git a/packages/light.js/src/frequency/utils/createPubsubObservable.ts b/packages/light.js/src/frequency/utils/createPubsubObservable.ts new file mode 100644 index 00000000..9534ace3 --- /dev/null +++ b/packages/light.js/src/frequency/utils/createPubsubObservable.ts @@ -0,0 +1,74 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import * as debug from 'debug'; +import { FrequencyObservableOptions } from '../../types'; +import * as memoizee from 'memoizee'; +import { Observable, Observer, timer } from 'rxjs'; +import { switchMap } from 'rxjs/operators'; + +import { createApiFromProvider, getApi } from '../../api'; +import { distinctReplayRefCount } from '../../utils/operators/distinctReplayRefCount'; + +/** + * Given an api, returns an Observable that emits on each pubsub event. + * Pure function version of {@link createPubsubObservable}. + * + * @ignore + */ +const createPubsubObservableWithApi = memoizee( + (pubsub: string, api: any) => { + const [namespace, method] = pubsub.split('_'); + + // There's a chance the provider doesn't support pubsub, for example + // MetaMaskProvider. In this case, as suggested on their Github, the best + // solution for now is to poll. + if (!api.isPubSub) { + debug('@parity/light.js:api')( + `Pubsub not available for ${ + api.provider ? api.provider.constructor.name : 'current Api' + } provider, polling "${pubsub}" every second.` + ); + + return timer(0, 1000).pipe( + switchMap(() => api[namespace][method]()) + ) as Observable; + } + + return Observable.create((observer: Observer) => { + const subscription = api.pubsub[namespace][method]( + (error: Error, result: any) => { + // TODO use @parity/api type for result + if (error) { + observer.error(error); + } else { + observer.next(result); + } + } + ); + return () => + subscription.then((subscriptionId: string) => + api.pubsub.unsubscribe(subscriptionId) + ); + }).pipe(distinctReplayRefCount()) as Observable; + } +); + +/** + * Given a provider, returns an Observable that emits on each pubsub event. + * + * @ignore + * @example onAccountsChanged$, onEveryBlock$... + */ +const createPubsubObservable = ( + pubsub: string, + { provider }: FrequencyObservableOptions = {} +) => { + const api = provider ? createApiFromProvider(provider) : getApi(); + + return createPubsubObservableWithApi(pubsub, api); +}; + +export default createPubsubObservable; diff --git a/packages/light.js/src/index.ts b/packages/light.js/src/index.ts index b129cd41..1870a7d1 100644 --- a/packages/light.js/src/index.ts +++ b/packages/light.js/src/index.ts @@ -4,13 +4,25 @@ // SPDX-License-Identifier: MIT import { setApi, setProvider } from './api'; -import * as frequency from './frequency'; -import './overview'; +import frequency from './frequency'; +import { makeContract } from './rpc/other/makeContract'; +import rpc from './rpc'; -export * from './rpc'; export * from './utils/isLoading'; export * from './types'; export { withoutLoading } from './utils/operators/withoutLoading'; -export { frequency }; +export { frequency, makeContract }; // makeContract is a bit special, because it's not a RpcObservable +export const { + accounts$, + accountsInfo$, + balanceOf$, + blockNumber$, + chainName$, + defaultAccount$, + myBalance$, + peerCount$, + post$, + syncStatus$ +} = rpc; export default { setApi, setProvider }; diff --git a/packages/light.js/src/overview/index.ts b/packages/light.js/src/overview/index.ts deleted file mode 100644 index 9b8ea928..00000000 --- a/packages/light.js/src/overview/index.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import { ApiValue, RpcObservable } from '../types'; -import * as rpc from '../rpc'; - -interface CalledWithArgsItem { - currentValue: ApiValue; - subscribersCount: number; -} - -interface Overview { - [index: string]: { - calledWithArgs?: { - [key: string]: CalledWithArgsItem; - }; - calls?: string[]; - dependsOn?: string; - frequency?: string[]; - }; -} - -/** - * Add a property on window, so that the subscribed object can be viewed in the - * JS console via `window.parity.rpcOverview()` - */ -if (typeof window !== 'undefined') { - // == null means null or undefined - if (window.parity == null) { - window.parity = {}; - } - - window.parity.rpcOverview = () => { - const overview: Overview = {}; - Object.keys(rpc).forEach(key => { - // This one's more complex, we leave it for later - if (key === 'makeContract') { - return; - } - - const rpc$: RpcObservable = (rpc as any)[key]; - - // If the rpc$ has not been called, then we don't show it - if (!rpc$.metadata.calledWithArgs) { - return; - } - - // We populate the `calledWithArgs` field, in a human-readable way - Object.keys(rpc$.metadata.calledWithArgs).map(calledWithArgsKey => { - const subject$ = rpc$.metadata.calledWithArgs[calledWithArgsKey]; - - // Don't show this calledWithArgs item if there are not active - // subscribers. - if (!subject$.observers.length) { - return; - } - - // Safely initialize the fields - overview[key] = overview[key] || {}; - overview[key].calledWithArgs = overview[key].calledWithArgs || {}; - - // Populate each arg the RpcObservable has been called with, with its - // currentValue and subscribersCount - overview[key].calledWithArgs[calledWithArgsKey] = { - // @ts-ignore We need to access private properties here - currentValue: subject$._events && subject$._events[0], - subscribersCount: subject$.observers.length - }; - }); - - // Don't show this RpcObservable if it has no active subscribers on any - // of its args. - if (!overview[key] || !overview[key].calledWithArgs) { - return; - } - - // We add all calls of this RpcObservable - if (rpc$.metadata.calls) { - overview[key].calls = rpc$.metadata.calls; - } - - // We add all dependsOn of this RpcObservable - if (rpc$.metadata.dependsOn) { - overview[key].dependsOn = rpc$.metadata.dependsOn.metadata.name; - } - - // We add a human-readable version of `frequency` field - if (rpc$.metadata.frequency) { - overview[key].frequency = rpc$.metadata.frequency.map( - frequency$ => frequency$.metadata.name - ); - } - }); - - return overview; - }; -} diff --git a/packages/light.js/src/rpc/eth.ts b/packages/light.js/src/rpc/eth.ts new file mode 100644 index 00000000..a5e190a1 --- /dev/null +++ b/packages/light.js/src/rpc/eth.ts @@ -0,0 +1,104 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import BigNumber from 'bignumber.js'; +import { of } from 'rxjs'; +import { map, switchMap } from 'rxjs/operators'; + +import { Address, RpcObservableOptions } from '../types'; +import createRpc$ from './utils/createRpc'; +import frequency from '../frequency'; +import { isNullOrLoading, RPC_LOADING } from '../utils/isLoading'; +import { switchMapPromise } from '../utils/operators'; + +/** + * Observable which contains the array of all addresses managed by the light + * client. + * + * Calls eth_accounts. + * + * @param options - Options to pass to {@link RpcObservableOptions}. + * @return - An Observable containing the list of public addresses. + */ +export function accounts$(options?: RpcObservableOptions) { + return createRpc$({ + frequency: [frequency.onAccountsChanged$], + name: 'accounts$' + })(options)(); +} + +/** + * Get the balance of a given account. Calls `eth_getBalance`. + * + * @param address - The account address to query the balance. + * @param options - Options to pass to {@link RpcObservableOptions}. + * @return - An Observable containing the balance. + */ +export function balanceOf$(address: Address, options?: RpcObservableOptions) { + return createRpc$({ + calls: ['eth_getBalance'], + frequency: [frequency.onEveryBlock$, frequency.onStartup$], + name: 'balanceOf$', + pipes: api => [switchMapPromise(() => api.eth.getBalance(address))] + })(options)(address); +} + +/** + * Get the default account managed by the light client. + * + * @param options - Options to pass to {@link RpcObservableOptions}. + * @return - An Observable containing the public address + * of the default account. + */ +export function defaultAccount$(options?: RpcObservableOptions) { + return createRpc$({ + dependsOn: accounts$, + name: 'defaultAccount$', + pipes: () => [map(accounts => accounts[0])] + })(options)(); +} + +/** + * Get the current block number. + * + * @return {Observable} - An Observable containing the block height. + */ +export function blockNumber$(options?: RpcObservableOptions) { + return createRpc$({ + frequency: [frequency.onEveryBlock$], + name: 'blockNumber$' + })(options)(); +} + +/** + * Shorthand for fetching the current account's balance. + */ +export function myBalance$(options?: RpcObservableOptions) { + return createRpc$({ + calls: [`eth_getBalance`], + dependsOn: defaultAccount$, + name: 'myBalance$', + pipes: () => [ + switchMap( + defaultAccount => + isNullOrLoading(defaultAccount) + ? of(RPC_LOADING) + : balanceOf$(defaultAccount) + ) + ] + })(options)(); +} + +/** + * Get the syncStatus state. + * + * @return - An Observable containing the syncing state object, or false. + */ +export function syncStatus$(options?: RpcObservableOptions) { + return createRpc$({ + frequency: [frequency.onSyncingChanged$], + name: 'syncStatus$' + })(options)(); +} diff --git a/packages/light.js/src/rpc/eth/eth.spec.ts b/packages/light.js/src/rpc/eth/eth.spec.ts deleted file mode 100644 index 9c43eeeb..00000000 --- a/packages/light.js/src/rpc/eth/eth.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as eth from './eth'; -import testRpc from '../../utils/testHelpers/testRpc'; - -Object.keys(eth).forEach(key => testRpc(key, (eth as any)[key])); diff --git a/packages/light.js/src/rpc/eth/eth.ts b/packages/light.js/src/rpc/eth/eth.ts deleted file mode 100644 index 55900dd4..00000000 --- a/packages/light.js/src/rpc/eth/eth.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import BigNumber from 'bignumber.js'; -import { of } from 'rxjs'; -import { map, switchMap } from 'rxjs/operators'; - -import { Address } from '../../types'; -import api from '../../api'; -import createRpc$ from '../utils/createRpc'; -import { isNullOrLoading, RPC_LOADING } from '../../utils/isLoading'; -import { - onAccountsChanged$, - onEveryBlock$, - onStartup$, - onSyncingChanged$ -} from '../../frequency'; -import { switchMapPromise } from '../../utils/operators'; - -/** - * Observable which contains the array of all addresses managed by the light - * client. - * - * Calls eth_accounts. - * - * @return - An Observable containing the list of public addresses. - */ -export const accounts$ = createRpc$({ - frequency: [onAccountsChanged$], - name: 'accounts$' -}); - -/** - * Get the balance of a given account. Calls `eth_getBalance`. - * - * @param address - The account address to query the balance. - * @return - An Observable containing the balance. - */ -export const balanceOf$ = createRpc$({ - calls: ['eth_getBalance'], - frequency: [onEveryBlock$, onStartup$], - name: 'balanceOf$', - pipes: (address: Address) => [ - switchMapPromise(() => api().eth.getBalance(address)) - ] -}); - -/** - * Get the default account managed by the light client. - * - * @return - An Observable containing the public address - * of the default account. - */ -export const defaultAccount$ = createRpc$({ - dependsOn: accounts$, - name: 'defaultAccount$', - pipes: () => [map(accounts => accounts[0])] -}); - -/** - * Get the current block number. - * - * @return {Observable} - An Observable containing the block height. - */ -export const blockNumber$ = createRpc$({ - frequency: [onEveryBlock$], - name: 'blockNumber$' -}); - -/** - * Shorthand for fetching the current account's balance. - */ -export const myBalance$ = createRpc$({ - calls: [`eth_getBalance`], - dependsOn: defaultAccount$, - name: 'myBalance$', - pipes: () => [ - switchMap( - defaultAccount => - isNullOrLoading(defaultAccount) - ? of(RPC_LOADING) - : balanceOf$(defaultAccount) - ) - ] -}); - -/** - * Get the syncStatus state. - * - * @return - An Observable containing the syncing state object, or false. - */ -export const syncStatus$ = createRpc$({ - frequency: [onSyncingChanged$], - name: 'syncStatus$' -}); diff --git a/packages/light.js/src/rpc/eth/index.ts b/packages/light.js/src/rpc/eth/index.ts deleted file mode 100644 index 7c87bd1d..00000000 --- a/packages/light.js/src/rpc/eth/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -export * from './eth'; diff --git a/packages/light.js/src/rpc/index.ts b/packages/light.js/src/rpc/index.ts index c62500b5..7b99583c 100644 --- a/packages/light.js/src/rpc/index.ts +++ b/packages/light.js/src/rpc/index.ts @@ -3,7 +3,6 @@ // // SPDX-License-Identifier: MIT -export * from './eth'; -export * from './net'; -export * from './other'; -export * from './parity'; +import rpc from './rpc'; + +export default rpc; diff --git a/packages/light.js/src/rpc/net.ts b/packages/light.js/src/rpc/net.ts new file mode 100644 index 00000000..b67c5436 --- /dev/null +++ b/packages/light.js/src/rpc/net.ts @@ -0,0 +1,28 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import BigNumber from 'bignumber.js'; + +import createRpc$ from './utils/createRpc'; +import frequency from '../frequency'; +import { RpcObservableOptions } from '../types'; +import { switchMapPromise } from '../utils/operators'; + +/** + * Get the amount of peers. + * + * Calls `net_peerCount` + * + * @param options - Options to pass to {@link RpcObservableOptions}. + * @return - An Observable containing the number. + */ +export function peerCount$(options?: RpcObservableOptions) { + return createRpc$({ + calls: ['net_peerCount'], + frequency: [frequency.onEvery5Seconds$], + name: 'peerCount$', + pipes: api => [switchMapPromise(() => api.net.peerCount())] + })(options)(); +} diff --git a/packages/light.js/src/rpc/net/index.ts b/packages/light.js/src/rpc/net/index.ts deleted file mode 100644 index c05ea419..00000000 --- a/packages/light.js/src/rpc/net/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -export * from './net'; diff --git a/packages/light.js/src/rpc/net/net.spec.ts b/packages/light.js/src/rpc/net/net.spec.ts deleted file mode 100644 index 4236209d..00000000 --- a/packages/light.js/src/rpc/net/net.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as net from './net'; -import testRpc from '../../utils/testHelpers/testRpc'; - -Object.keys(net).forEach(key => testRpc(key, (net as any)[key])); diff --git a/packages/light.js/src/rpc/net/net.ts b/packages/light.js/src/rpc/net/net.ts deleted file mode 100644 index 65a9daba..00000000 --- a/packages/light.js/src/rpc/net/net.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import BigNumber from 'bignumber.js'; - -import api from '../../api'; -import createRpc$ from '../utils/createRpc'; -import { onEvery5Seconds$ } from '../../frequency'; -import { switchMapPromise } from '../../utils/operators'; - -/** - * Get the amount of peers. - * - * Calls `net_peerCount` - * - * @return - An Observable containing the number. - */ -export const peerCount$ = createRpc$({ - calls: ['net_peerCount'], - frequency: [onEvery5Seconds$], - name: 'peerCount$', - pipes: () => [switchMapPromise(() => api().net.peerCount())] -}); diff --git a/packages/light.js/src/rpc/other/makeContract.ts b/packages/light.js/src/rpc/other/makeContract.ts index ab8e423a..a8145c9f 100644 --- a/packages/light.js/src/rpc/other/makeContract.ts +++ b/packages/light.js/src/rpc/other/makeContract.ts @@ -8,10 +8,10 @@ import { abiEncode } from '@parity/api/lib/util/encode'; import * as memoizee from 'memoizee'; import { Address } from '../../types'; +import { createApiFromProvider, getApi } from '../../api'; import createRpc from '../utils/createRpc'; import { switchMapPromise } from '../../utils/operators'; -import api from '../../api'; -import { onEveryBlock$ } from '../../frequency'; +import frequency from '../../frequency'; import { post$ } from './post'; interface MakeContract { @@ -29,32 +29,36 @@ interface MakeContract { * * @param address - The contract address. * @param abiJson - The contract abi. + * @param api - The api Object. * @return - The contract object as defined in @parity/api. */ const getContract = memoizee( - (address: Address, abiJson: any[]) => api().newContract(abiJson, address), // use types from @parity/abi - { length: 1 } // Only memoize by address + (address: Address, abiJson: any[], api: any) => + api.newContract(abiJson, address), // use types from @parity/abi ); /** - * Create a contract. + * Create a contract, givan an api object. + * Pure function version of {@link makeContract}. * + * @ignore * @param address - The contract address. - * @param - The contract abi. + * @param abiJson - The contract abi. + * @param api - The api Object. * @return - An object whose keys are all the functions of the * contract, and each function return an Observable which will fire when the * function resolves. */ -export const makeContract = memoizee( - (address: Address, abiJson: any[]) => { - // use types from @parity/abi - const abi = new Abi(abiJson); +const makeContractWithApi = memoizee( + (address: Address, abiJson: any[], api: any) => { + const abi = new Abi(abiJson); // use types from @parity/abi + // Variable result will hold the final object to return const result: MakeContract = { abi, address, get contractObject() { - return getContract(address, abiJson); + return getContract(address, abiJson, api); } }; @@ -66,7 +70,7 @@ export const makeContract = memoizee( // We only get the contract when the function is called for the 1st // time. Note: getContract is memoized, won't create contract on each // call. - const contract = getContract(address, abiJson); + const contract = getContract(address, abiJson, api); const method = contract.instance[name]; // Hold the method from the Abi // The last arguments in args can be an options object @@ -75,14 +79,14 @@ export const makeContract = memoizee( if (method.constant) { return createRpc({ - frequency: [onEveryBlock$], + frequency: [frequency.onEveryBlock$], name, pipes: () => [ switchMapPromise(() => contract.instance[name].call(options, args) ) ] - })(...args); + })({ provider: api.provider })(...args); } else { return post$({ to: address, @@ -98,6 +102,26 @@ export const makeContract = memoizee( }); return result; - }, - { length: 1 } // Only memoize by address + } ); + +/** + * Create a contract. + * + * @param address - The contract address. + * @param abiJson - The contract abi. + * @param options - The options to pass in when creating the contract. + * @return - An object whose keys are all the functions of the + * contract, and each function return an Observable which will fire when the + * function resolves. + */ +export const makeContract = ( + address: Address, + abiJson: any[], + options: { provider?: any } = {} +) => { + const { provider } = options; + const api = provider ? createApiFromProvider(provider) : getApi(); + + return makeContractWithApi(address, abiJson, api); +}; diff --git a/packages/light.js/src/rpc/other/post.ts b/packages/light.js/src/rpc/other/post.ts index 21e30dd1..6766037b 100644 --- a/packages/light.js/src/rpc/other/post.ts +++ b/packages/light.js/src/rpc/other/post.ts @@ -5,9 +5,13 @@ import { Observable, Observer } from 'rxjs'; -import api from '../../api'; +import { createApiFromProvider, getApi } from '../../api'; import { distinctReplayRefCount } from '../../utils/operators'; -import { RpcObservable, Tx, TxStatus } from '../../types'; +import { RpcObservableOptions, Tx, TxStatus } from '../../types'; + +interface PostOptions extends RpcObservableOptions { + estimate?: boolean; +} /** * Post a transaction to the network. @@ -16,23 +20,23 @@ import { RpcObservable, Tx, TxStatus } from '../../types'; * `parity_checkRequest` and `eth_getTransactionReceipt` to get the status of * the transaction. * - * @param options? - Options to pass. + * @param options? - Options to pass to the {@link RpcObservable}. * @return - The status of the transaction. */ -export const post$: RpcObservable = ( - tx: Tx, - options: { estimate?: boolean } = {} -) => { +export function post$(tx: Tx, options: PostOptions = {}) { + const { estimate, provider } = options; + const api = provider ? createApiFromProvider(provider) : getApi(); + const source$ = Observable.create(async (observer: Observer) => { try { - if (options.estimate) { + if (estimate) { observer.next({ estimating: true }); - const gas = await api().eth.estimateGas(tx); + const gas = await api.eth.estimateGas(tx); observer.next({ estimated: gas }); } - const signerRequestId = await api().parity.postTransaction(tx); + const signerRequestId = await api.parity.postTransaction(tx); observer.next({ requested: signerRequestId }); - const transactionHash = await api().pollMethod( + const transactionHash = await api.pollMethod( 'parity_checkRequest', signerRequestId ); @@ -40,7 +44,7 @@ export const post$: RpcObservable = ( observer.next({ signed: transactionHash, schedule: tx.condition }); } else { observer.next({ signed: transactionHash }); - const receipt = await api().pollMethod( + const receipt = await api.pollMethod( 'eth_getTransactionReceipt', transactionHash, ( @@ -58,14 +62,5 @@ export const post$: RpcObservable = ( }).pipe(distinctReplayRefCount()); source$.subscribe(); // Run this Observable immediately; - return source$; -}; -post$.metadata = { - calls: [ - 'eth_estimateGas', - 'parity_postTransaction', - 'parity_checkRequest', - 'eth_getTransactionReceipt' - ], - name: 'post$' -}; + return source$ as Observable; +} diff --git a/packages/light.js/src/rpc/parity.ts b/packages/light.js/src/rpc/parity.ts new file mode 100644 index 00000000..d0067564 --- /dev/null +++ b/packages/light.js/src/rpc/parity.ts @@ -0,0 +1,37 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import { AccountsInfo, RpcObservableOptions } from '../types'; +import createRpc$ from './utils/createRpc'; +import frequency from '../frequency'; +import { switchMapPromise } from '../utils/operators'; + +/** + * Get accounts info. Calls `parity_accountsInfo`. + * + * @return - An Observable containing all info that can be + * accessed by user concerning accounts. + */ +export function accountsInfo$(options?: RpcObservableOptions) { + return createRpc$({ + frequency: [frequency.onAccountsInfoChanged$], + name: 'accountsInfo$' + })()(options); +} + +/** + * Get the name of the current chain. Calls `parity_netChain`. + * + * @return - An Observable containing the name of the + * current chain. + */ +export function chainName$(options?: RpcObservableOptions) { + return createRpc$({ + calls: ['parity_netChain'], + frequency: [frequency.onStartup$], + name: 'chainName$', + pipes: api => [switchMapPromise(() => api.parity.netChain())] + })(options)(); +} diff --git a/packages/light.js/src/rpc/parity/index.ts b/packages/light.js/src/rpc/parity/index.ts deleted file mode 100644 index 330123e1..00000000 --- a/packages/light.js/src/rpc/parity/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -export * from './parity'; diff --git a/packages/light.js/src/rpc/parity/parity.spec.ts b/packages/light.js/src/rpc/parity/parity.spec.ts deleted file mode 100644 index 6439af00..00000000 --- a/packages/light.js/src/rpc/parity/parity.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import * as parity from './parity'; -import testRpc from '../../utils/testHelpers/testRpc'; - -Object.keys(parity).forEach(key => testRpc(key, (parity as any)[key])); diff --git a/packages/light.js/src/rpc/parity/parity.ts b/packages/light.js/src/rpc/parity/parity.ts deleted file mode 100644 index cf8845d4..00000000 --- a/packages/light.js/src/rpc/parity/parity.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import { AccountsInfo } from '../../types'; -import api from '../../api'; -import createRpc$ from '../utils/createRpc'; -import { onAccountsInfoChanged$, onStartup$ } from '../../frequency'; -import { switchMapPromise } from '../../utils/operators'; - -/** - * Get accounts info. Calls `parity_accountsInfo`. - * - * @return - An Observable containing all info that can be - * accessed by user concerning accounts. - */ -export const accountsInfo$ = createRpc$({ - frequency: [onAccountsInfoChanged$], - name: 'accountsInfo$' -}); - -/** - * Get the name of the current chain. Calls `parity_netChain`. - * - * @return - An Observable containing the name of the - * current chain. - */ -export const chainName$ = createRpc$({ - calls: ['parity_netChain'], - frequency: [onStartup$], - name: 'chainName$', - pipes: () => [switchMapPromise(() => api().parity.netChain())] -}); diff --git a/packages/light.js/src/rpc/rpc.spec.ts b/packages/light.js/src/rpc/rpc.spec.ts new file mode 100644 index 00000000..925d8368 --- /dev/null +++ b/packages/light.js/src/rpc/rpc.spec.ts @@ -0,0 +1,79 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import * as Api from '@parity/api'; + +import isObservable from '../utils/isObservable'; +import { + MockProvider, + rejectApi, + resolveApi +} from '../utils/testHelpers/mockApi'; +import rpc from './rpc'; +import { RpcKey, RpcMap, RpcObservable } from '../types'; +import { setApi } from '../api'; + +jest.mock('@parity/api'); +Api.mockImplementation(() => resolveApi()); + +/** + * Helper function to make basic tests for RpcObservables. + * + * @ignore + */ +const testRpc = (name: string, rpc$: RpcObservable) => + describe(`${name} rpc`, () => { + beforeEach(() => { + setApi(resolveApi()); + }); + + it('should be a function', () => { + expect(typeof rpc$).toBe('function'); + }); + + it('should return an Observable', () => { + expect(isObservable(rpc$({}))).toBe(true); + }); + + it('result Observable should be subscribable', () => { + expect(() => rpc$({}).subscribe()).not.toThrow(); + }); + + it('result Observable should return values', done => { + rpc$({}).subscribe(data => { + expect(data).toBeTruthy(); + done(); + }); + }); + + // Memoization tests don't concern post$ + if (name === 'post$') { + return; + } + + it('should return the same Observable upon re-running (memoization)', () => { + const initial$ = rpc$(); + expect(rpc$()).toBe(initial$); + }); + + it('should not return the same Observable if we change Api', () => { + const initial$ = rpc$(); + setApi(rejectApi()); + expect(rpc$()).not.toBe(initial$); + }); + + it('should not return the same Observable if options are passed', () => { + const initial$ = rpc$(); + expect(rpc$({ provider: new MockProvider() })).not.toBe(initial$); + }); + + it('should return the same Observable if same options are passed', () => { + const provider = new MockProvider(); + const initial$ = rpc$({ provider }); + expect(rpc$({ provider })).toBe(initial$); + }); + }); + +Object.keys(rpc).forEach(key => testRpc(key, (rpc as RpcMap)[key as RpcKey])); diff --git a/packages/light.js/src/rpc/rpc.ts b/packages/light.js/src/rpc/rpc.ts new file mode 100644 index 00000000..6e2de717 --- /dev/null +++ b/packages/light.js/src/rpc/rpc.ts @@ -0,0 +1,13 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT + +import * as eth from './eth'; +import * as net from './net'; +import { post$ } from './other'; +import * as parity from './parity'; + +const rpc = { ...eth, ...net, ...parity, post$ }; + +export default rpc; diff --git a/packages/light.js/src/rpc/utils/createRpc.spec.ts b/packages/light.js/src/rpc/utils/createRpc.spec.ts deleted file mode 100644 index fa867715..00000000 --- a/packages/light.js/src/rpc/utils/createRpc.spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import { timer } from 'rxjs'; - -import createRpc from './createRpc'; - -it('should return a function', () => { - expect(typeof createRpc({})).toBe('function'); -}); - -it('should add empty metadata by default', () => { - expect(createRpc({}).metadata).toEqual({}); -}); - -it('should append input metadata', () => { - expect(createRpc({ name: 'bar' }).metadata).toEqual({ - name: 'bar' - }); -}); - -it('should contain frequencyMixins', () => { - expect(typeof createRpc({}).setFrequency).toBe('function'); -}); - -it('should set correct frequency', () => { - const frequency = timer(0, 1000); - const rpc$ = createRpc({}); - rpc$.setFrequency([frequency]); - expect(rpc$.metadata.frequency).toEqual([frequency]); -}); diff --git a/packages/light.js/src/rpc/utils/createRpc.ts b/packages/light.js/src/rpc/utils/createRpc.ts index d60fe936..cb6b5d86 100644 --- a/packages/light.js/src/rpc/utils/createRpc.ts +++ b/packages/light.js/src/rpc/utils/createRpc.ts @@ -3,99 +3,78 @@ // // SPDX-License-Identifier: MIT +import { isFunction } from '@parity/api/lib/util/types'; import * as memoizee from 'memoizee'; -import { isFunction, isObject } from '@parity/api/lib/util/types'; import { merge, ReplaySubject, Observable, OperatorFunction } from 'rxjs'; import { multicast, refCount } from 'rxjs/operators'; -import * as prune from 'json-prune'; -import { Metadata, RpcObservable } from '../../types'; -import { distinctValues, withoutLoading } from '../../utils/operators'; - -interface RpcObservableWithoutMetadata<_, Out> { - (...args: any[]): Observable; -} - -/** - * Mixins that are added into an RpcObservable. - * - * @ignore - */ -const frequencyMixins = { - /** - * Change the frequency of a RPC Observable. - * - * @param frequency - An array of frequency Observables. - * @example - * balanceOf$.setFrequency([onEverySecond$, onStartup$]); // Will fetch - * balance once on startup, and then every second. - */ - setFrequency(frequency: Observable[]) { - // TODO Check that frequency is well-formed - - this.metadata.frequency = frequency; - - // If necessary, we clear the memoize cache - if (typeof this.clear === 'function') { - this.clear(); - } - } -}; +import { createApiFromProvider, getApi } from '../../api'; +import { distinctValues } from '../../utils/operators'; +import { Metadata, RpcObservableOptions } from '../../types'; /** * Add metadata to an RpcObservable, and transform it into a ReplaySubject(1). + * It's a currified function. + * Pure function version of {@link createRpc}. * * @ignore * @param metadata - The metadata to add. - * @return - The original RpcObservable with patched metadata. + * @example + * createRpc(metadata)(options) returns a RpcObservable. + * createRpc(metadata)(options)(someArgs) returns an Observable. */ -const createRpc = (metadata: Metadata) => { - // rpc$ will hold the RpcObservable minus its metadata - const rpc$: RpcObservableWithoutMetadata = (...args: any[]) => { +const createRpcWithApi = memoizee( + (metadata: Metadata, api: any, ...args: any[]) => { // The source Observable can either be another RpcObservable (in the // `dependsOn` field), or anObservable built by merging all the // FrequencyObservables const source$ = metadata.dependsOn - ? metadata.dependsOn(...args) - : merge(...metadata.frequency); - - // The last arguments is an options, if it's an object - // TODO What if we pass a single object as argument, which is not options? - const options: { withoutLoading?: boolean } = - args && args.length && isObject(args[args.length - 1]) ? args.pop() : {}; + ? metadata.dependsOn(...args, { provider: api.provider }) + : merge(...metadata.frequency.map(f => f({ provider: api.provider }))); - // A RpcObservable is a source$ Observable, a single subject$ that - // subscribesthis source, and this subject$ multicasts the fired values to - // all Observers. + // A RpcObservable is: a source$ Observable, a single subject$ that + // subscribes to this source, and this subject$ multicasts the fired values + // to all Observers. const subject$ = new ReplaySubject(1); // The pipes to add const pipes: OperatorFunction[] = []; if (metadata.pipes && isFunction(metadata.pipes)) { - pipes.push(...metadata.pipes(...args)); + pipes.push(...metadata.pipes(api)); } - pipes.push(multicast(() => subject$), refCount()); - if (options.withoutLoading === true) { - pipes.push(withoutLoading()); + pipes.push(multicast(() => subject$), refCount(), distinctValues()); + + return source$.pipe(...pipes) as Observable; + }, + { + length: false, // Dynamic args length + normalizer: (args: any) => { + // Custom memoization function, i.e. create an unique id from the args. + // `args` is arguments object as accessible in memoized function + return `${args[0].name}${args[1].provider.id}${JSON.stringify( + Array.from(args).slice(2) + )}`; } - pipes.push(distinctValues()); - - // Add a field in the calledWithArgs object, so that we know this function has - // been called with these particular args in the app. See overview.js on - // how this is used. - if (!metadata.calledWithArgs) { - metadata.calledWithArgs = {}; - } - metadata.calledWithArgs[prune(args)] = subject$; - - return source$.pipe(...pipes); - }; - - let memoizedRpc$ = memoizee(rpc$, { primitive: true, length: false }); + } +); - Object.assign(memoizedRpc$, frequencyMixins, { metadata }); +/** + * Add metadata to an RpcObservable, and transform it into a ReplaySubject(1). + * It's a currified function. + * + * @ignore + * @param metadata - The metadata to add. + * @example + * createRpc(metadata)(options) returns a RpcObservable. + * createRpc(metadata)(options)(someArgs) returns an Observable. + */ +const createRpc = (metadata: Metadata) => ( + options: RpcObservableOptions = {} +) => (...args: any[]) => { + const { provider } = options; + const api = provider ? createApiFromProvider(provider) : getApi(); - return memoizedRpc$ as RpcObservable; + return createRpcWithApi(metadata, api, ...args); }; export default createRpc; diff --git a/packages/light.js/src/types.ts b/packages/light.js/src/types.ts index da674dbf..feeea5a3 100644 --- a/packages/light.js/src/types.ts +++ b/packages/light.js/src/types.ts @@ -6,6 +6,9 @@ import BigNumber from 'bignumber.js'; import { Observable, OperatorFunction, ReplaySubject } from 'rxjs'; +import frequency from './frequency'; +import rpc from './rpc'; + declare global { interface Window { parity: any; @@ -34,16 +37,41 @@ export interface Metadata { pipes?: (...args: any[]) => OperatorFunction[]; } -export interface FrequencyObservable extends Observable { - metadata?: { calls?: string[]; name: string }; +export type FrequencyKey = keyof typeof frequency; + +export interface FrequencyObservableOptions { + provider?: any; // TODO types from @parity/abi +} + +export interface FrequencyObservable { + (options?: FrequencyObservableOptions): Observable; +} + +export type FrequencyMap = { + [index in FrequencyKey]: FrequencyObservable +}; + +export interface MakeContract { + abi: any; // TODO types from @parity/abi + address: string; + readonly contractObject: any; // TODO from @parity/api + [index: string]: any | string | ((...args: any[]) => any); // TODO types from @parity/abi } +export type RpcKey = keyof typeof rpc; + export interface RpcObservable { (...args: any[]): Observable; metadata?: Metadata; setFrequency?(frequency: FrequencyObservable[]): void; // post$, makeContract... don't have setFrequency } +export type RpcMap = { [index in RpcKey]: RpcObservable }; + +export interface RpcObservableOptions { + provider?: any; // TODO types from @parity/abi +} + // TODO This should be on @parity/api export type Tx = { from: Address; diff --git a/packages/light.js/src/utils/isLoading.spec.ts b/packages/light.js/src/utils/isLoading.spec.ts new file mode 100644 index 00000000..e2c5cfc5 --- /dev/null +++ b/packages/light.js/src/utils/isLoading.spec.ts @@ -0,0 +1,15 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT +import { isNullOrLoading, RPC_LOADING } from './isLoading'; + +it('should return true for null', () => + expect(isNullOrLoading(null)).toBe(true)); + +it('should return true for RPC_LOADING', () => + expect(isNullOrLoading(RPC_LOADING)).toBe(true)); + +it('should return false for other values', () => { + expect(isNullOrLoading('foo')).toBe(false); +}); diff --git a/packages/light.js/src/utils/operators/distinctReplayRefCount.ts b/packages/light.js/src/utils/operators/distinctReplayRefCount.ts index 3ffecfa4..f1eceda6 100644 --- a/packages/light.js/src/utils/operators/distinctReplayRefCount.ts +++ b/packages/light.js/src/utils/operators/distinctReplayRefCount.ts @@ -3,9 +3,11 @@ // // SPDX-License-Identifier: MIT -import { distinctUntilChanged, publishReplay, refCount } from 'rxjs/operators'; +import { publishReplay, refCount } from 'rxjs/operators'; import { Observable } from 'rxjs'; +import { distinctValues } from './distinctValues'; + /** * Shorthand for distinctUntilChanged(), publishReplay(1) and refCount(). * @@ -15,7 +17,7 @@ export const distinctReplayRefCount = () => ( source$: Observable ): Observable => source$.pipe( - distinctUntilChanged(), + distinctValues(), publishReplay(1), refCount() ); diff --git a/packages/light.js/src/utils/operators/switchMapPromise.spec.ts b/packages/light.js/src/utils/operators/switchMapPromise.spec.ts index 5164e300..77046dda 100644 --- a/packages/light.js/src/utils/operators/switchMapPromise.spec.ts +++ b/packages/light.js/src/utils/operators/switchMapPromise.spec.ts @@ -3,7 +3,7 @@ // // SPDX-License-Identifier: MIT -import { skip } from 'rxjs/operators'; +import { skip, take } from 'rxjs/operators'; import mockRpc$ from '../testHelpers/mockRpc'; import { rejectApi, resolveApi } from '../testHelpers/mockApi'; @@ -13,7 +13,7 @@ import { switchMapPromise } from './switchMapPromise'; it('should not error when the promise resolves with an error', done => { mockRpc$() .pipe(switchMapPromise(resolveApi({ error: 'bar' }).fake.method)) - .subscribe(); + .subscribe(null, () => done.fail('It should not error.')); // If after 0.1s, nothing has been called, then our Observable has not fired // any event, which is what we want @@ -23,23 +23,26 @@ it('should not error when the promise resolves with an error', done => { it('should not error when the promise rejects', done => { mockRpc$() .pipe(switchMapPromise(rejectApi().fake.method)) - .subscribe(); + .subscribe(null, () => done.fail('It should not error.')); // If after 0.1s, nothing has been called, then our Observable has not fired // any event, which is what we want setTimeout(done, 100); }); -it('should fire an event when the promise resolves', done => { +it('should fire a loading state frist', done => { mockRpc$() - .pipe(switchMapPromise(resolveApi().fake.method)) + .pipe( + switchMapPromise(resolveApi().fake.method), + take(1) + ) .subscribe(data => { expect(data).toBe(RPC_LOADING); done(); }); }); -it('should fire an event when the promise resolves', done => { +it('should fire the correct value when the promise resolves', done => { mockRpc$() .pipe( switchMapPromise(resolveApi().fake.method), diff --git a/packages/light.js/src/utils/operators/withoutLoading.spec.ts b/packages/light.js/src/utils/operators/withoutLoading.spec.ts new file mode 100644 index 00000000..290b8a5c --- /dev/null +++ b/packages/light.js/src/utils/operators/withoutLoading.spec.ts @@ -0,0 +1,24 @@ +// Copyright 2015-2018 Parity Technologies (UK) Ltd. +// This file is part of Parity. +// +// SPDX-License-Identifier: MIT +import { finalize } from 'rxjs/operators'; +import { of } from 'rxjs'; + +import { RPC_LOADING } from '../isLoading'; +import { withoutLoading } from './withoutLoading'; + +test('should filter out the loading states', done => { + let numberOfTimesCalled = 0; + of(1, RPC_LOADING, 2) + .pipe( + withoutLoading(), + finalize(() => { + expect(numberOfTimesCalled).toBe(2); + done(); + }) + ) + .subscribe(() => { + ++numberOfTimesCalled; + }); +}); diff --git a/packages/light.js/src/utils/operators/withoutLoading.ts b/packages/light.js/src/utils/operators/withoutLoading.ts index 09b14533..49209641 100644 --- a/packages/light.js/src/utils/operators/withoutLoading.ts +++ b/packages/light.js/src/utils/operators/withoutLoading.ts @@ -4,9 +4,10 @@ // SPDX-License-Identifier: MIT import { distinctUntilChanged, filter } from 'rxjs/operators'; +import { Observable } from 'rxjs'; import { isLoading } from '../isLoading'; -import { Observable } from 'rxjs'; + /** * Filter out the loading states in our observable. * diff --git a/packages/light.js/src/utils/testHelpers/mockApi.ts b/packages/light.js/src/utils/testHelpers/mockApi.ts index a3cee001..6b63cdec 100644 --- a/packages/light.js/src/utils/testHelpers/mockApi.ts +++ b/packages/light.js/src/utils/testHelpers/mockApi.ts @@ -3,51 +3,108 @@ // // SPDX-License-Identifier: MIT +import * as EventEmitter from 'eventemitter3'; + +// Count the number of providers we have, so that each time we call createApi, +// we create a new provider. +let providerCount = 0; + /** - * A pubsub Api object that rejects. + * Provider used for tests. * * @ignore */ -export const rejectApi = (rejectWith = new Error('bar'), isPubSub = true) => ({ - fake: { - method() { - return Promise.reject(rejectWith); - } - }, - isPubSub, - pubsub: { - fake: { - method(callback: Function) { - callback(rejectWith, null); - return Promise.resolve(1); // Resolves to subscriptionId - } - }, - unsubscribe: () => Promise.resolve() +export class MockProvider extends EventEmitter { + send() { + return Promise.resolve(); } -}); +} + +// List of JSONRPCs we want to mock +const listOfMockRps: { [index: string]: string[] } = { + eth: ['accounts', 'blockNumber', 'getBalance', 'syncing'], + fake: ['method'], + net: ['peerCount'], + parity: ['accountsInfo', 'netChain', 'postTransaction'] +}; /** - * A pubsub Api object that resolves. + * Create a mock api object from the listOfMockRps above. + * + * @ignore + */ +const createApi = ( + resolveWith: string | { error: string } | Error, + isPubSub: boolean, + isError: boolean +) => { + const result = Object.keys(listOfMockRps).reduce( + (apiObject, namespace: string) => { + // Create methods on apiObject + apiObject[namespace] = {}; + listOfMockRps[namespace].forEach(method => { + apiObject[namespace][method] = isError + ? () => Promise.reject(resolveWith) + : () => Promise.resolve(resolveWith); + }); + + // Create pubsub on apiObject + apiObject.pubsub = apiObject.pubsub || { + unsubscribe: () => Promise.resolve() + }; + apiObject.pubsub[namespace] = {}; + listOfMockRps[namespace].forEach(method => { + apiObject.pubsub[namespace][method] = isError + ? (callback: Function) => { + callback(resolveWith, null); + return Promise.resolve(1); // Resolves to subscriptionId + } + : (callback: Function) => { + callback(null, resolveWith); + return Promise.resolve(1); // Resolves to subscriptionId + }; + }); + + return apiObject; + }, + { + isPubSub, + pollMethod() { + return isError + ? Promise.reject(resolveWith) + : Promise.resolve(resolveWith); + }, + provider: { + id: ++providerCount, + on: () => { + /* Do nothing. */ + }, + send: () => { + /* Do nothing. */ + } + } + } as { [index: string]: any } + ); + + return result; +}; + +/** + * Mock api that resolves. + * + * @ignore + */ +export const rejectApi = ( + resolveWith = new Error('bar'), + isPubsub: boolean = true +) => createApi(resolveWith, isPubsub, true); + +/** + * Mock api that resolves. * * @ignore */ export const resolveApi = ( resolveWith: string | { error: string } = 'foo', - isPubSub = true -) => ({ - fake: { - method() { - return Promise.resolve(resolveWith); - } - }, - isPubSub, - pubsub: { - fake: { - method(callback: Function) { - callback(null, resolveWith); - return Promise.resolve(1); // Resolves to subscriptionId - } - }, - unsubscribe: () => Promise.resolve() - } -}); + isPubsub: boolean = true +) => createApi(resolveWith, isPubsub, false); diff --git a/packages/light.js/src/utils/testHelpers/mockRpc.ts b/packages/light.js/src/utils/testHelpers/mockRpc.ts index ffc91c85..77d879e8 100644 --- a/packages/light.js/src/utils/testHelpers/mockRpc.ts +++ b/packages/light.js/src/utils/testHelpers/mockRpc.ts @@ -6,12 +6,15 @@ import { timer } from 'rxjs'; import createRpc from '../../rpc/utils/createRpc'; +import { resolveApi } from '../testHelpers/mockApi'; +import { setApi } from '../../api'; /** * Create a fake RpcObservable. * * @ignore */ -const mockRpc$ = createRpc({ frequency: [timer(0, 1000)] }); +setApi(resolveApi()); +const mockRpc$ = createRpc({ frequency: [() => timer(0, 1000)] })(); export default mockRpc$; diff --git a/packages/light.js/src/utils/testHelpers/testFrequency.ts b/packages/light.js/src/utils/testHelpers/testFrequency.ts deleted file mode 100644 index a8f5807b..00000000 --- a/packages/light.js/src/utils/testHelpers/testFrequency.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import { FrequencyObservable } from '../../types'; -import isObservable from '../isObservable'; - -/** - * Helper function to make basic tests for frequency$ observables. - * - * @ignore - */ -const testFrequency = (name: string, frequency$: FrequencyObservable) => - describe(`${name} rpc`, () => { - it('should be an Observable', () => { - expect(isObservable(frequency$)).toBe(true); - }); - - it('should be subscribable', () => { - expect(() => frequency$.subscribe()).not.toThrow(); - }); - - it('should contain a `metadata` field', () => { - expect(frequency$.metadata).toBeTruthy(); - }); - - it('should contain `name` in metadata', () => { - const { metadata } = frequency$; - expect(metadata.name).toBeTruthy(); - }); - }); - -export default testFrequency; diff --git a/packages/light.js/src/utils/testHelpers/testRpc.ts b/packages/light.js/src/utils/testHelpers/testRpc.ts deleted file mode 100644 index bc5ba060..00000000 --- a/packages/light.js/src/utils/testHelpers/testRpc.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (UK) Ltd. -// This file is part of Parity. -// -// SPDX-License-Identifier: MIT - -import isObservable from '../isObservable'; -import { RpcObservable } from '../../types'; - -/** - * Helper function to make basic tests for RpcObservables. - * - * @ignore - */ -const testRpc = (name: string, rpc$: RpcObservable) => - describe(`${name} rpc`, () => { - it('should be a function', () => { - expect(typeof rpc$).toBe('function'); - }); - - it('function should return an Observable', () => { - expect(isObservable(rpc$())).toBe(true); - }); - - it('function result Observable should be subscribable', () => { - expect(() => rpc$().subscribe()).not.toThrow(); - }); - - it('function should return the same Observable upon re-running (memoization)', () => { - const initial$ = rpc$(); - expect(rpc$()).toBe(initial$); - }); - - it('should contain a `metadata` field', () => { - expect(rpc$.metadata).toBeTruthy(); - }); - - it('should either contain a `frequency` or `dependsOn` field in metadata', () => { - const { metadata } = rpc$; - expect( - (metadata.frequency && metadata.frequency.length) || metadata.dependsOn - ).toBeTruthy(); - }); - }); - -export default testRpc; diff --git a/packages/light.js/typedoc.js b/packages/light.js/typedoc.js index 5caa0b29..dbb91b7d 100644 --- a/packages/light.js/typedoc.js +++ b/packages/light.js/typedoc.js @@ -1,7 +1,6 @@ module.exports = { exclude: ['**/*spec.ts', '**/index.ts'], excludeExternals: true, - excludeNotExported: true, excludePrivate: true, hideGenerator: true, includes: './src', diff --git a/tslint.json b/tslint.json index 5af63118..c86026fe 100644 --- a/tslint.json +++ b/tslint.json @@ -1,6 +1,6 @@ { "extends": ["tslint-config-semistandard", "tslint-config-prettier"], "linterOptions": { - "exclude": ["**/node_modules/**/*"] + "exclude": ["**/node_modules/**/*", "**/lib/**/*", "**/example/**/*"] } } diff --git a/yarn.lock b/yarn.lock index b7aab2fd..eca5c01b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2982,10 +2982,6 @@ json-parse-better-errors@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" -json-prune@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/json-prune/-/json-prune-1.1.0.tgz#23e2fad108932b255050e3f1a70500c2b4aa30c7" - json-schema-traverse@^0.3.0: version "0.3.1" resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340"