How to use @polkadot/ui-settings - 10 common examples

To help you get started, we’ve selected a few @polkadot/ui-settings examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github polkadot-js / apps / packages / apps / src / index.tsx View on Github external
import { ThemeProvider } from 'styled-components';
import { Api, registry } from '@polkadot/react-api';
import { QueueConsumer } from '@polkadot/react-components/Status/Context';
import Queue from '@polkadot/react-components/Status/Queue';
import { BlockAuthors, Events } from '@polkadot/react-query';

import Apps from './Apps';

const rootId = 'root';
const rootElement = document.getElementById(rootId);

// we split here so that both these forms are allowed
//  - http://localhost:3000/?rpc=wss://substrate-rpc.parity.io/#/explorer
//  - http://localhost:3000/#/explorer?rpc=wss://substrate-rpc.parity.io
const urlOptions = queryString.parse(location.href.split('?')[1]);
const _wsEndpoint = urlOptions.rpc || process.env.WS_URL || settings.apiUrl;

if (Array.isArray(_wsEndpoint)) {
  throw new Error('Invalid WS endpoint specified');
}

// on some combo of browsers/os, this https://polkadot.js.org/apps/?rpc=ws://127.0.0.1:9944#/explorer
// turns into ws://127.0.0.1:9944#/explorer (split these)
const wsEndpoint = _wsEndpoint.split('#')[0];

console.log('WS endpoint=', wsEndpoint);

try {
  const types = store.get('types') || {};
  const names = Object.keys(types);

  if (names.length) {
github polkadot-js / apps / packages / react-api / src / Api.tsx View on Github external
api.rpc.system.chain(),
      api.rpc.system.name(),
      api.rpc.system.version(),
      web3Accounts().then((accounts): InjectedAccountExt[] =>
        accounts.map(({ address, meta }): InjectedAccountExt => ({
          address,
          meta: {
            ...meta,
            name: `${meta.name} (${meta.source === 'polkadot-js' ? 'extension' : meta.source})`
          }
        }))
      )
    ]);
    const ss58Format = uiSettings.prefix === -1
      ? properties.ss58Format.unwrapOr(DEFAULT_SS58).toNumber()
      : uiSettings.prefix;
    const tokenSymbol = properties.tokenSymbol.unwrapOr('DEV').toString();
    const tokenDecimals = properties.tokenDecimals.unwrapOr(DEFAULT_DECIMALS).toNumber();
    const systemChain = _systemChain
      ? _systemChain.toString()
      : '';
    const isDevelopment = isTestChain(systemChain);

    console.log('api: found chain', systemChain, JSON.stringify(properties));

    // first setup the UI helpers
    formatBalance.setDefaults({
      decimals: tokenDecimals,
      unit: tokenSymbol
    });
    TokenUnit.setAbbr(tokenSymbol);
github polkadot-js / apps / packages / react-api / src / Api.tsx View on Github external
const [properties, _systemChain, _systemName, _systemVersion, injectedAccounts] = await Promise.all([
      api.rpc.system.properties(),
      api.rpc.system.chain(),
      api.rpc.system.name(),
      api.rpc.system.version(),
      web3Accounts().then((accounts): InjectedAccountExt[] =>
        accounts.map(({ address, meta }): InjectedAccountExt => ({
          address,
          meta: {
            ...meta,
            name: `${meta.name} (${meta.source === 'polkadot-js' ? 'extension' : meta.source})`
          }
        }))
      )
    ]);
    const ss58Format = uiSettings.prefix === -1
      ? properties.ss58Format.unwrapOr(DEFAULT_SS58).toNumber()
      : uiSettings.prefix;
    const tokenSymbol = properties.tokenSymbol.unwrapOr('DEV').toString();
    const tokenDecimals = properties.tokenDecimals.unwrapOr(DEFAULT_DECIMALS).toNumber();
    const systemChain = _systemChain
      ? _systemChain.toString()
      : '';
    const isDevelopment = isTestChain(systemChain);

    console.log('api: found chain', systemChain, JSON.stringify(properties));

    // first setup the UI helpers
    formatBalance.setDefaults({
      decimals: tokenDecimals,
      unit: tokenSymbol
    });
github polkadot-js / extension / packages / extension-ui / src / Popup / index.tsx View on Github external
import { AccountContext, ActionContext, AuthorizeContext, MediaContext, SigningContext } from '../components/contexts';
import { subscribeAccounts, subscribeAuthorize, subscribeSigning } from '../messaging';
import Accounts from './Accounts';
import Authorize from './Authorize';
import CreateAccount from './CreateAccount';
import Export from './Export';
import Forget from './Forget';
import ImportQr from './ImportQr';
import ImportSeed from './ImportSeed';
import Settings from './Settings';
import Signing from './Signing';
import Welcome from './Welcome';

// load the ui settings, actually only used for address prefix atm
// probably overkill (however can replace once we have actual others)
const { prefix } = settings.get();

// FIXME Duplicated in Settings, horrible...
setSS58Format(prefix === -1 ? 42 : prefix);

// Request permission for video, based on access we can hide/show import
async function requestMediaAccess (cameraOn: boolean): Promise {
  if (!cameraOn) {
    return false;
  }

  try {
    await navigator.mediaDevices.getUserMedia({ video: true });

    return true;
  } catch (error) {
    console.error('Permission for video declined', error.message);
github polkadot-js / extension / packages / extension-ui / src / components / Address.tsx View on Github external
function recodeAddress (address: string, accounts: AccountJson[], genesisHash?: string | null): [string, AccountJson | null, Chain] {
  // decode and create a shortcut for the encoded address
  const publicKey = decodeAddress(address);

  // find our account using the actual publicKey, and then find the associated chain
  const account = findAccount(accounts, publicKey);
  const chain = findChain((account && account.genesisHash) || genesisHash);

  return [
    // always allow the actual settings to override the display
    encodeAddress(publicKey, settings.prefix === -1 ? chain.ss58Format : settings.prefix),
    account,
    chain
  ];
}
github polkadot-js / extension / packages / extension-ui / src / Popup / Settings / index.tsx View on Github external
export default function Settings (): React.ReactElement<{}> {
  const [camera, setCamera] = useState(settings.camera);
  const [prefix, setPrefix] = useState(`${settings.prefix}`);

  const _onChangeCamera = (camera: string): void => {
    setCamera(camera);

    settings.set({ camera });
  };

  // FIXME check against index, we need a better solution
  const _onChangePrefix = (value: string): void => {
    const prefix = parseInt(value, 10);

    setSS58Format(prefix === -1 ? 42 : prefix);
    setPrefix(value);

    settings.set({ prefix });
  };
github polkadot-js / apps / packages / app-toolbox / src / Verify.tsx View on Github external
function Verify ({ t }: Props): React.ReactElement {
  const [{ cryptoType, isValid }, setValidity] = useState<{ cryptoType: CryptoTypes; isValid: boolean }>({ cryptoType: 'unknown', isValid: false });
  const [{ data, isHexData }, setData] = useState<{ data: string; isHexData: boolean }>({ data: '', isHexData: false });
  const [{ publicKey, isValidPk }, setPublicKey] = useState<{ publicKey: Uint8Array | null; isValidPk: boolean }>({ publicKey: null, isValidPk: false });
  const [{ signature, isValidSignature }, setSignature] = useState<{ signature: string; isValidSignature: boolean }>({ signature: '', isValidSignature: false });
  const [cryptoOptions] = useState([{ value: 'unknown', text: t('Crypto not detected') }].concat(uiSettings.availableCryptos as any[]));

  useEffect((): void => {
    let cryptoType: CryptoTypes = 'unknown';
    let isValid = isValidPk && isValidSignature;

    // We cannot just use the keyring verify since it may be an address. So here we first check
    // for ed25519, if not valid, we try against sr25519 - if neither are valid, well, we have
    // not been able to validate the signature
    if (isValid && publicKey) {
      let isValidSr = false;
      let isValidEd = false;

      try {
        isValidEd = naclVerify(data, signature, publicKey);
      } catch (error) {
        // do nothing, already set to false
github polkadot-js / apps / packages / apps-routing / src / index.ts View on Github external
import democracy from './democracy';
import explorer from './explorer';
import extrinsics from './extrinsics';
import genericAsset from './generic-asset';
import js from './js';
import parachains from './parachains';
import settings from './settings';
import staking from './staking';
import storage from './storage';
import sudo from './sudo';
import techcomm from './techcomm';
import toolbox from './toolbox';
import transfer from './transfer';
import treasury from './treasury';

const routes: Routes = appSettings.uiMode === 'light'
  ? ([] as Routes).concat(
    // dashboard,
    explorer,
    accounts,
    addressbook,
    claims,
    transfer,
    genericAsset,
    null,
    staking,
    democracy,
    council,
    // TODO Not sure about the inclusion of treasury & parachains here
    null,
    settings
  )
github polkadot-js / apps / packages / apps-routing / src / index.ts View on Github external
import collective from './collective';
import dashboard from './dashboard';
import democracy from './democracy';
import explorer from './explorer';
import extrinsics from './extrinsics';
import js from './js';
import parachains from './parachains';
import settings from './settings';
import staking from './staking';
import storage from './storage';
import sudo from './sudo';
import toolbox from './toolbox';
import transfer from './transfer';
import treasury from './treasury';

const routes: Routes = appSettings.uiMode === 'light'
  ? ([] as Routes).concat(
    dashboard,
    explorer,
    accounts,
    addressbook,
    transfer,
    null,
    staking,
    democracy,
    collective,
    // TODO Not sure about the inclusion of treasury & parachains here
    null,
    settings,
    template
  )
  : ([] as Routes).concat(
github polkadot-js / extension / packages / extension-ui / src / Popup / Settings / index.tsx View on Github external
import settings from '@polkadot/ui-settings';
import { setSS58Format } from '@polkadot/util-crypto';

import { Button, Dropdown } from '../../components';
import { windowOpen } from '../../messaging';
import { Back } from '../../partials';

interface Option {
  text: string;
  value: string;
}

// There are probably better ways, but since we set the popup size, use that
const isPopup = window.innerWidth <= 480;
const cameraOptions = settings.availableCamera.map(({ text, value }): Option => ({ text, value: `${value}` }));
const prefixOptions = settings.availablePrefixes.map(({ text, value }): Option => ({
  text: value === -1
    ? 'Default (Substrate or as specified)'
    : text,
  value: `${value}`
}));

export default function Settings (): React.ReactElement<{}> {
  const [camera, setCamera] = useState(settings.camera);
  const [prefix, setPrefix] = useState(`${settings.prefix}`);

  const _onChangeCamera = (camera: string): void => {
    setCamera(camera);

    settings.set({ camera });
  };