Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@substrate/context

Package Overview
Dependencies
Maintainers
3
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@substrate/context - npm Package Compare versions

Comparing version 0.3.22 to 0.3.23

lib/util/stashes.d.ts

18

CHANGELOG.md

@@ -6,2 +6,20 @@ # Change Log

## [0.3.23](https://github.com/paritytech/Nomidot/compare/v0.3.22...v0.3.23) (2020-04-09)
### Bug Fixes
* **context:** Make provider optional in contexts ([#291](https://github.com/paritytech/Nomidot/issues/291)) ([5a129e0](https://github.com/paritytech/Nomidot/commit/5a129e05bcb6c37cc59ac25249052da6ea5bca54))
### Features
* accounts context ([#228](https://github.com/paritytech/Nomidot/issues/228)) ([909f380](https://github.com/paritytech/Nomidot/commit/909f3809a2e22e2977ccfcbeca66150171e88744))
* accounts page ([#256](https://github.com/paritytech/Nomidot/issues/256)) ([1120cba](https://github.com/paritytech/Nomidot/commit/1120cbae9202c244d1b118e3f7c89ce64a7eb6a7))
* cache accounts context results ([#285](https://github.com/paritytech/Nomidot/issues/285)) ([c25e304](https://github.com/paritytech/Nomidot/commit/c25e304cba0633bc6660543a43ea1edd66fb8b8d))
## [0.3.22](https://github.com/paritytech/Nomidot/compare/v0.3.21...v0.3.22) (2020-03-18)

@@ -8,0 +26,0 @@

15

lib/AccountsContext.d.ts

@@ -1,11 +0,18 @@

import { DerivedStakingAccount } from '@polkadot/api-derive/types';
import { DeriveBalancesAll, DeriveStakingQuery } from '@polkadot/api-derive/types';
import { InjectedAccountWithMeta, InjectedExtension } from '@polkadot/extension-inject/types';
import React from 'react';
export interface DecoratedAccount extends InjectedAccountWithMeta, DerivedStakingAccount {
}
declare type AccountBalanceMap = Record<string, DeriveBalancesAll>;
declare type StashControllerMap = Record<string, DeriveStakingQuery>;
interface AccountsContext {
decoratedAccounts: DecoratedAccount[];
accountBalanceMap: AccountBalanceMap;
allAccounts: InjectedAccountWithMeta[];
allStashes: string[];
currentAccount?: string;
readonly extension: InjectedExtension;
fetchAccounts: () => Promise<void>;
isExtensionReady: boolean;
loadingAccountStaking: boolean;
loadingBalances: boolean;
setCurrentAccount: React.Dispatch<React.SetStateAction<string | undefined>>;
stashControllerMap: StashControllerMap;
}

@@ -12,0 +19,0 @@ export declare const AccountsContext: React.Context<AccountsContext>;

@@ -5,13 +5,2 @@ "use strict";

// of the Apache-2.0 license. See the LICENSE file for details.
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -69,6 +58,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
var __importStar = (this && this.__importStar) || function (mod) {

@@ -84,4 +69,4 @@ if (mod && mod.__esModule) return mod;

var util_crypto_1 = require("@polkadot/util-crypto");
var local_storage_1 = require("@substrate/local-storage");
var react_1 = __importStar(require("react"));
var operators_1 = require("rxjs/operators");
var ApiContext_1 = require("./ApiContext");

@@ -93,66 +78,171 @@ var SystemContext_1 = require("./SystemContext");

function AccountsContextProvider(props) {
var _this = this;
var children = props.children, originName = props.originName;
var _a = react_1.useContext(ApiContext_1.ApiContext), api = _a.api, isApiReady = _a.isApiReady;
// context
var _a = react_1.useContext(ApiContext_1.ApiContext), apiPromise = _a.apiPromise, isApiReady = _a.isApiReady;
var chain = react_1.useContext(SystemContext_1.SystemContext).chain;
var _b = __read(react_1.useState([]), 2), accounts = _b[0], setAccounts = _b[1];
var _c = __read(react_1.useState([]), 2), decoratedAccounts = _c[0], setDecoratedAccounts = _c[1];
var _d = __read(react_1.useState(), 2), extension = _d[0], setExtension = _d[1];
var _e = __read(react_1.useState(false), 2), isReady = _e[0], setIsReady = _e[1];
react_1.useEffect(function () {
if (!isApiReady || !accounts) {
return;
}
else {
// make sure it's encoded correctly
accounts.map(function (account) {
account.address = util_crypto_1.encodeAddress(util_crypto_1.decodeAddress(account.address), 2);
var sub = api.derive.staking
.account(account.address)
.pipe(operators_1.take(1), operators_1.distinctUntilChanged())
.subscribe(function (derivedStakingAccount) {
setDecoratedAccounts(__spread(decoratedAccounts, [
__assign(__assign({}, account), derivedStakingAccount),
]));
});
return function () { return sub.unsubscribe(); };
});
}
}, [accounts, isApiReady]);
// state
var _b = __read(react_1.useState([]), 2), allAccounts = _b[0], setAccounts = _b[1];
var _c = __read(react_1.useState({}), 2), accountBalanceMap = _c[0], setAccountBalanceMap = _c[1];
var _d = __read(react_1.useState([]), 2), allStashes = _d[0], setAllStashes = _d[1];
var _e = __read(react_1.useState({}), 2), stashControllerMap = _e[0], setStashControllerMap = _e[1];
var _f = __read(react_1.useState(), 2), currentAccount = _f[0], setCurrentAccount = _f[1];
var _g = __read(react_1.useState(), 2), extension = _g[0], setExtension = _g[1];
var _h = __read(react_1.useState(true), 2), loadingBalances = _h[0], setLoadingBalances = _h[1];
var _j = __read(react_1.useState(true), 2), loadingAccountStaking = _j[0], setLoadingAccountStaking = _j[1];
var _k = __read(react_1.useState(false), 2), isExtensionReady = _k[0], setIsExtensionReady = _k[1];
var getDerivedBalances = function () { return __awaiter(_this, void 0, void 0, function () {
var addresses, result_1;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(allAccounts && apiPromise && isApiReady)) return [3 /*break*/, 2];
setLoadingBalances(true);
addresses = allAccounts.map(function (account) { return account.address; });
result_1 = {};
return [4 /*yield*/, Promise.all(addresses.map(function (address) { return __awaiter(_this, void 0, void 0, function () {
var derivedBalances;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, apiPromise.derive.balances.all(address)];
case 1:
derivedBalances = _a.sent();
result_1[address] = derivedBalances;
return [2 /*return*/];
}
});
}); }))];
case 1:
_a.sent();
setAccountBalanceMap(result_1);
local_storage_1.writeStorage('derivedBalances', JSON.stringify(result_1));
setLoadingBalances(false);
_a.label = 2;
case 2: return [2 /*return*/];
}
});
}); };
var getDerivedStaking = function () { return __awaiter(_this, void 0, void 0, function () {
var result_2;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(allStashes && apiPromise && isApiReady)) return [3 /*break*/, 2];
result_2 = {};
return [4 /*yield*/, Promise.all(allStashes.map(function (stashId) { return __awaiter(_this, void 0, void 0, function () {
var stakingInfo;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, apiPromise.derive.staking.query(stashId)];
case 1:
stakingInfo = _a.sent();
result_2[stashId] = stakingInfo;
return [2 /*return*/];
}
});
}); }))];
case 1:
_a.sent();
setStashControllerMap(result_2);
local_storage_1.writeStorage('derivedStaking', JSON.stringify(result_2));
_a.label = 2;
case 2: return [2 /*return*/];
}
});
}); };
var getStashInfo = function () { return __awaiter(_this, void 0, void 0, function () {
var addresses, allBonded, allLedger, stashes;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(isApiReady && apiPromise && allAccounts)) return [3 /*break*/, 3];
setLoadingAccountStaking(true);
addresses = allAccounts.map(function (account) { return account.address; });
return [4 /*yield*/, ((_a = apiPromise.query.staking) === null || _a === void 0 ? void 0 : _a.bonded.multi(addresses))];
case 1:
allBonded = _b.sent();
return [4 /*yield*/, apiPromise.query.staking.ledger.multi(addresses)];
case 2:
allLedger = _b.sent();
stashes = util_2.getStashes(addresses, allBonded, allLedger);
local_storage_1.writeStorage('allStashes', JSON.stringify(stashes));
setAllStashes(stashes);
setLoadingAccountStaking(false);
_b.label = 3;
case 3: return [2 /*return*/];
}
});
}); };
/**
* Fetch accounts from the extension
*/
function fetchAccounts() {
return __awaiter(this, void 0, void 0, function () {
var _a, web3Accounts, web3Enable, extensions, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!(typeof window !== "undefined")) return [3 /*break*/, 4];
return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require('@polkadot/extension-dapp')); })];
case 1:
_a = _c.sent(), web3Accounts = _a.web3Accounts, web3Enable = _a.web3Enable;
return [4 /*yield*/, web3Enable(originName)];
case 2:
extensions = _c.sent();
if (!extensions.length) {
throw new Error('No extension found. Please install PolkadotJS extension.');
}
if (util_2.IS_SSR) {
throw new Error('Window does not exist during SSR');
}
setExtension(extensions[0]);
_b = setAccounts;
return [4 /*yield*/, web3Accounts()];
case 3:
_b.apply(void 0, [_c.sent()]);
l.log("Accounts ready, encoded to ss58 prefix of " + chain);
setIsReady(true);
_c.label = 4;
case 4: return [2 /*return*/];
}
});
var fetchAccounts = react_1.useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
var _a, web3Accounts, web3Enable, extensions, _web3Accounts;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(typeof window !== "undefined")) return [3 /*break*/, 4];
return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require('@polkadot/extension-dapp')); })];
case 1:
_a = _b.sent(), web3Accounts = _a.web3Accounts, web3Enable = _a.web3Enable;
return [4 /*yield*/, web3Enable(originName)];
case 2:
extensions = _b.sent();
if (!extensions.length) {
throw new Error('No extension found. Please install PolkadotJS extension.');
}
if (util_2.IS_SSR) {
throw new Error('Window does not exist during SSR');
}
setExtension(extensions[0]); // accounts, signer
return [4 /*yield*/, web3Accounts()];
case 3:
_web3Accounts = _b.sent();
_web3Accounts.map(function (account) {
account.address = util_crypto_1.encodeAddress(util_crypto_1.decodeAddress(account.address), 2);
});
setAccounts(_web3Accounts);
setCurrentAccount(_web3Accounts && _web3Accounts[0] && _web3Accounts[0].address);
l.log("Accounts ready, encoded to ss58 prefix of " + chain);
setIsExtensionReady(true);
_b.label = 4;
case 4: return [2 /*return*/];
}
});
}
}); }, [chain, originName]);
var fetchCachedRpcResults = function () {
var cachedStashes = localStorage.getItem('allStashes');
var cachedBalances = localStorage.getItem('derivedBalances');
var cachedStaking = localStorage.getItem('derivedStaking');
if (cachedStashes) {
var asStashArray = JSON.parse(cachedStashes);
setAllStashes(asStashArray);
}
if (cachedBalances) {
setAccountBalanceMap(JSON.parse(cachedBalances));
}
if (cachedStaking) {
setStashControllerMap(JSON.parse(cachedStaking));
}
};
react_1.useEffect(function () {
fetchAccounts();
fetchCachedRpcResults();
}, []);
react_1.useEffect(function () {
getStashInfo();
}, [allAccounts, apiPromise, isApiReady]);
react_1.useEffect(function () {
getDerivedStaking();
getDerivedBalances();
}, [allStashes, apiPromise, isApiReady]);
return (react_1.default.createElement(exports.AccountsContext.Provider, { value: {
decoratedAccounts: decoratedAccounts,
accountBalanceMap: accountBalanceMap,
allAccounts: allAccounts,
// allControllers,
allStashes: allStashes,
currentAccount: currentAccount,
get extension() {

@@ -168,5 +258,9 @@ if (!extension) {

fetchAccounts: fetchAccounts,
isExtensionReady: isReady,
isExtensionReady: isExtensionReady,
loadingAccountStaking: loadingAccountStaking,
loadingBalances: loadingBalances,
setCurrentAccount: setCurrentAccount,
stashControllerMap: stashControllerMap,
} }, children));
}
exports.AccountsContextProvider = AccountsContextProvider;

@@ -1,2 +0,2 @@

import { ApiRx } from '@polkadot/api';
import { ApiPromise, ApiRx } from '@polkadot/api';
import { ProviderInterface } from '@polkadot/rpc-provider/types';

@@ -6,2 +6,3 @@ import React from 'react';

api: ApiRx;
apiPromise?: ApiPromise;
isApiReady: boolean;

@@ -13,3 +14,4 @@ }

provider: ProviderInterface;
promise?: boolean;
}
export declare function ApiContextProvider(props: ApiContextProviderProps): React.ReactElement;

@@ -35,5 +35,6 @@ "use strict";

function ApiContextProvider(props) {
var _a = props.children, children = _a === void 0 ? null : _a, provider = props.provider;
var _a = props.children, children = _a === void 0 ? null : _a, provider = props.provider, promise = props.promise;
var _b = __read(react_1.useState(new api_1.ApiRx({ provider: provider })), 2), api = _b[0], setApi = _b[1];
var _c = __read(react_1.useState(false), 2), isReady = _c[0], setIsReady = _c[1];
var _c = __read(react_1.useState(new api_1.ApiPromise({ provider: provider })), 2), apiPromise = _c[0], setApiPromise = _c[1];
var _d = __read(react_1.useState(false), 2), isReady = _d[0], setIsReady = _d[1];
react_1.useEffect(function () {

@@ -43,5 +44,10 @@ // We want to fetch all the information again each time we reconnect. We

// settings.
setApi(new api_1.ApiRx({ provider: provider }));
if (promise) {
setApiPromise(new api_1.ApiPromise({ provider: provider }));
}
else {
setApi(new api_1.ApiRx({ provider: provider }));
}
setIsReady(false);
}, [provider]);
}, [provider, promise]);
react_1.useEffect(function () {

@@ -51,10 +57,17 @@ // We want to fetch all the information again each time we reconnect. We

// settings.
var subscription = api.isReady.subscribe(function () {
l.log("Api ready, app is ready to use");
setIsReady(true);
});
return function () { return subscription.unsubscribe(); };
}, [api]);
return (react_1.default.createElement(exports.ApiContext.Provider, { value: { api: api, isApiReady: isReady } }, children));
if (promise) {
apiPromise.isReady.then(function (_) {
setIsReady(true);
});
}
else {
var subscription_1 = api.isReady.subscribe(function () {
l.log("Api ready, app is ready to use");
setIsReady(true);
});
return function () { return subscription_1.unsubscribe(); };
}
}, [api, apiPromise.isReady, promise]);
return (react_1.default.createElement(exports.ApiContext.Provider, { value: { api: api, apiPromise: apiPromise, isApiReady: isReady } }, children));
}
exports.ApiContextProvider = ApiContextProvider;

@@ -24,4 +24,4 @@ import { ProviderInterface } from '@polkadot/rpc-provider/types';

children?: React.ReactElement;
provider: ProviderInterface;
provider?: ProviderInterface;
}
export declare function HealthContextProvider(props: HealthContextProviderProps): React.ReactElement;

@@ -56,3 +56,3 @@ "use strict";

var hasPeers = false;
if (provider.isConnected() && health && header) {
if (provider && provider.isConnected() && health && header) {
isNodeConnected = true;

@@ -81,2 +81,5 @@ best = header.number.toNumber();

var timer;
if (!health) {
return;
}
if (!wasSyncing && health.isSyncing.eq(true)) {

@@ -83,0 +86,0 @@ wasSyncing = true;

@@ -9,10 +9,10 @@ import { ProviderInterface } from '@polkadot/rpc-provider/types';

export interface SystemContextType {
chain: Text;
genesisHash: BlockHash;
header: Header;
health: Health;
chain?: Text;
genesisHash?: BlockHash;
header?: Header;
health?: Health;
isSystemReady: boolean;
name: Text;
properties: ChainProperties;
version: Text;
name?: Text;
properties?: ChainProperties;
version?: Text;
}

@@ -22,4 +22,4 @@ export declare const SystemContext: React.Context<SystemContextType>;

children?: React.ReactElement;
provider: ProviderInterface;
provider?: ProviderInterface;
}
export declare function SystemContextProvider(props: SystemContextProviderProps): React.ReactElement;

@@ -58,4 +58,7 @@ "use strict";

var registryRef = react_1.useRef(new types_1.TypeRegistry());
var _j = __read(react_1.useState(new rpc_core_1.default(registryRef.current, provider)), 2), rpc = _j[0], setRpc = _j[1];
var _j = __read(react_1.useState(), 2), rpc = _j[0], setRpc = _j[1];
react_1.useEffect(function () {
if (!provider) {
return;
}
// Create a new RPC client each time we change provider

@@ -65,2 +68,5 @@ setRpc(new rpc_core_1.default(registryRef.current, provider));

react_1.useEffect(function () {
if (!provider || !rpc) {
return;
}
// We want to fetch all the information again each time we reconnect. We

@@ -96,2 +102,5 @@ // might be connecting to a different node, or the node might have changed

react_1.useEffect(function () {
if (!provider || !rpc) {
return;
}
var sub = util_2.providerConnected(provider)

@@ -98,0 +107,0 @@ .pipe(operators_1.filter(function (connected) { return !!connected; }), operators_1.switchMap(function () {

@@ -1,3 +0,2 @@

import { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import { KeyringPair } from '@polkadot/keyring/types';
import { AddressOrPair, SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import { Balance } from '@polkadot/types/interfaces';

@@ -14,3 +13,3 @@ import BN from 'bn.js';

recipientAddress?: string;
senderPair: KeyringPair;
senderPair: AddressOrPair;
}

@@ -42,3 +41,3 @@ /**

txQueue: PendingExtrinsic[];
submit: (extrinsicId: number) => void;
signAndSubmit: (extrinsicId: number) => void;
clear: () => void;

@@ -45,0 +44,0 @@ cancelObservable: Subject<{

@@ -45,2 +45,7 @@ "use strict";

var INIT_ERROR = new Error('TxQueueContext called without Provider.');
function isSenderPairKeyring(senderPair) {
if (senderPair.decodePkcs8 !== undefined) {
return true;
}
}
var cancelObservable = new rxjs_1.Subject();

@@ -56,3 +61,3 @@ var successObservable = new rxjs_1.Subject();

// eslint-disable-next-line @typescript-eslint/no-unused-vars
submit: function (extrinsicId) {
signAndSubmit: function (extrinsicId) {
console.error(INIT_ERROR);

@@ -112,3 +117,5 @@ },

setTxCounter(txCounter + 1);
l.log("Queued extrinsic #" + extrinsicId + " from " + details.senderPair.address + " to " + details.recipientAddress + " of amount " + details.amount, details);
l.log("Queued extrinsic #" + extrinsicId + " from " + (isSenderPairKeyring(details.senderPair)
? details.senderPair.address
: details.senderPair) + " to " + details.recipientAddress + " of amount " + details.amount, details);
setTxQueue(txQueue.concat({

@@ -133,3 +140,3 @@ details: details,

*/
var submit = function (extrinsicId) {
var signAndSubmit = function (extrinsicId) {
var pendingExtrinsic = txQueue.find(function (tx) { return tx.id === extrinsicId; });

@@ -171,3 +178,5 @@ if (!pendingExtrinsic) {

// https://github.com/polkadot-js/apps/issues/1102
senderPair.lock();
if (isSenderPairKeyring(senderPair)) {
senderPair.lock();
}
});

@@ -181,3 +190,3 @@ replaceTx(extrinsicId, __assign(__assign({}, pendingExtrinsic), { status: __assign(__assign({}, pendingExtrinsic.status), { isAskingForConfirm: false, isPending: true }), unsubscribe: function () {

enqueue: enqueue,
submit: submit,
signAndSubmit: signAndSubmit,
txQueue: txQueue,

@@ -184,0 +193,0 @@ successObservable: successObservable,

export * from './provider';
export * from './ssr';
export * from './stashes';
export * from './ui';

@@ -11,2 +11,3 @@ "use strict";

__export(require("./ssr"));
__export(require("./stashes"));
__export(require("./ui"));
{
"name": "@substrate/context",
"version": "0.3.22",
"version": "0.3.23",
"author": "Parity Technologies <admin@parity.io>",

@@ -23,3 +23,3 @@ "description": "Wrapper to connect React components to PolkadotJS Api",

},
"gitHead": "d569b71a59388bc40fce280f89e49a92d6f90a56"
"gitHead": "6ea62856ca1f8f4309e3bc5e2740165bf5d14ada"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc