How to use @ledgerhq/live-common - 10 common examples

To help you get started, weā€™ve selected a few @ledgerhq/live-common 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 LedgerHQ / ledger-live-common / cli / src / __tests__ / bridges.js View on Github external
.map(({ account, ...rest }) => {
    const bridge = getAccountBridge(account, null);
    if (!bridge) throw new Error("no bridge for " + account.id);
    let accountSyncedPromise;
    // lazy eval so we don't run this yet
    const getSynced = () =>
      accountSyncedPromise ||
      (accountSyncedPromise = syncAccount(bridge, account));
    return { getSynced, bridge, initialAccount: account, ...rest };
  })
  .forEach(arg => {
github LedgerHQ / ledger-live-desktop / src / api / Ripple.js View on Github external
// @flow
import logger from 'logger'
import { BigNumber } from 'bignumber.js'
import { RippleAPI } from 'ripple-lib'
import {
  parseCurrencyUnit,
  getCryptoCurrencyById,
  formatCurrencyUnit,
} from '@ledgerhq/live-common/lib/currencies'

const rippleUnit = getCryptoCurrencyById('ripple').units[0]

export const defaultEndpoint = 'wss://s2.ripple.com'

export const apiForEndpointConfig = (endpointConfig: ?string = null) => {
  const server = endpointConfig || defaultEndpoint
  const api = new RippleAPI({ server })
  api.on('error', (errorCode, errorMessage) => {
    logger.warn(`Ripple API error: ${errorCode}: ${errorMessage}`)
  })
  return api
}

export const parseAPIValue = (value: string) => parseCurrencyUnit(rippleUnit, value)

export const parseAPICurrencyObject = ({
  currency,
github LedgerHQ / ledger-live-common / cli / src / commands / appsUpdateTestAll.js View on Github external
job: ({ device, index }: $Shape<{ device: string, index: number }>) =>
    withDevice(device || "")(t => {
      const exec = execWithTransport(t);
      // $FlowFixMe
      return from(getDeviceInfo(t)).pipe(
        mergeMap(deviceInfo =>
          listApps(t, deviceInfo).pipe(
            filter(e => e.type === "result"),
            map(e => e.result)
          )
        ),
        mergeMap(listAppsResult => {
          return listAppsResult.appsListNames.slice(index || 0).reduce(
            ($state, name) =>
              $state.pipe(
                mergeMap(s => {
                  if (s.currentError) {
                    console.error(
github LedgerHQ / ledger-live-desktop / src / helpers / live-common-setup-internal-hw.js View on Github external
implementCountervalues({
  storeSelector: state => state.countervalues,
  pairsSelector: () => [],
  setExchangePairsAction: () => {},
})

setErrorRemapping(e => {
  // NB ideally we should solve it in ledgerjs
  if (e && e.message && e.message.indexOf('HID') >= 0) {
    return throwError(new DisconnectedDevice(e.message))
  }
  return throwError(e)
})

if (getEnv('DEVICE_PROXY_URL')) {
  const Tr = TransportHttp(getEnv('DEVICE_PROXY_URL').split('|'))

  registerTransportModule({
    id: 'proxy',
    open: () => retry(() => Tr.create(3000, 5000)),
    disconnect: () => Promise.resolve(),
  })
} else {
  registerTransportModule({
    id: 'hid',
    open: devicePath =>
      retry(
        () =>
          getEnv('EXPERIMENTAL_USB')
            ? TransportNodeHidSingleton.open()
            : TransportNodeHid.open(devicePath),
        { maxRetry: 4 },
github LedgerHQ / ledger-live-desktop / src / helpers / live-common-setup-internal-hw.js View on Github external
implementCountervalues({
  storeSelector: state => state.countervalues,
  pairsSelector: () => [],
  setExchangePairsAction: () => {},
})

setErrorRemapping(e => {
  // NB ideally we should solve it in ledgerjs
  if (e && e.message && e.message.indexOf('HID') >= 0) {
    return throwError(new DisconnectedDevice(e.message))
  }
  return throwError(e)
})

if (getEnv('DEVICE_PROXY_URL')) {
  const Tr = TransportHttp(getEnv('DEVICE_PROXY_URL').split('|'))

  registerTransportModule({
    id: 'proxy',
    open: () => retry(() => Tr.create(3000, 5000)),
    disconnect: () => Promise.resolve(),
  })
} else {
  registerTransportModule({
    id: 'hid',
    open: devicePath =>
      retry(
        () =>
          getEnv('EXPERIMENTAL_USB')
            ? TransportNodeHidSingleton.open()
            : TransportNodeHid.open(devicePath),
github LedgerHQ / ledger-live-common / tools / src / index.js View on Github external
constructor() {
    super();
    const CounterValues = getCountervalues();
    const store = initStore();

    // quick way to store countervalues with localStorage
    const LS_KEY = "countervalues_intermediary";
    try {
      const json = localStorage.getItem(LS_KEY);
      if (json) {
        store.dispatch(CounterValues.importAction(JSON.parse(json)));
      }
    } catch (e) {
      console.warn(e);
    }
    store.subscribe(() => {
      localStorage.setItem(
        LS_KEY,
        JSON.stringify(CounterValues.exportSelector(store.getState()))
github LedgerHQ / ledger-live-desktop / src / helpers / libcore.js View on Github external
showNewAccount,
}: {
  core: *,
  devicePath: string,
  currency: CryptoCurrency,
  onAccountScanned: AccountRaw => void,
  isUnsubscribed: () => boolean,
  derivationMode: DerivationMode,
  showNewAccount: boolean,
}): Promise {
  const isSegwit = isSegwitDerivationMode(derivationMode)
  const unsplitFork = isUnsplitDerivationMode(derivationMode) ? currency.forkedFrom : null
  const { coinType } = unsplitFork ? getCryptoCurrencyById(unsplitFork) : currency
  const path = `${isSegwit ? '49' : '44'}'/${coinType}'`

  const { publicKey: seedIdentifier } = await withDevice(devicePath)(transport =>
    from(getAddress(transport, currency, path)),
  ).toPromise()

  if (isUnsubscribed()) return []

  const walletName = getWalletName({
    seedIdentifier,
    currency,
    derivationMode,
  })

  // retrieve or create the wallet
  const wallet = await getOrCreateWallet(core, walletName, { currency, derivationMode })

  // recursively scan all accounts on device on the given app
  // new accounts will be created in sqlite, existing ones will be updated
github LedgerHQ / ledger-live-mobile / src / families / tezos / DelegationFlow / Summary.js View on Github external
navigation.navigate("DelegationSelectValidator", {
      ...navigation.state.params,
      transaction,
    });
  }, [rotateAnim, navigation, transaction]);

  const delegation = useDelegation(account);
  const addr =
    transaction.mode === "undelegate"
      ? (delegation && delegation.address) || ""
      : transaction.recipient;
  const baker = useBaker(addr);
  const bakerName = baker ? baker.name : shortAddressPreview(addr);
  const currency = getAccountCurrency(account);
  const color = getCurrencyColor(currency);
  const accountName = getAccountName(account);

  // handle any edit screen changes
  useTransactionChangeFromNavigation({
    navigation,
    setTransaction,
  });

  const onContinue = useCallback(async () => {
    navigation.navigate("DelegationConnectDevice", {
      accountId: account.id,
      parentId: parentAccount && parentAccount.id,
      transaction,
      status,
    });
  }, [status, account, parentAccount, navigation, transaction]);
github LedgerHQ / ledger-live-desktop / src / bridge / index.js View on Github external
export const getCurrencyBridge = (currency: CryptoCurrency): CurrencyBridge => {
  if (getEnv('MOCK')) return mockCurrencyBridge
  switch (currency.family) {
    case 'ripple':
      return RippleJSBridge.currencyBridge
    case 'ethereum':
      if (libcoreNoGo.includes(currency.id)) {
        return EthereumJSBridge.currencyBridge
      }
      return LibcoreBridge.currencyBridge
    case 'bitcoin':
      return LibcoreBridge.currencyBridge
    default:
      return mockCurrencyBridge // fallback mock until we implement it all!
  }
}
github LedgerHQ / ledger-live-desktop / src / reducers / accounts.js View on Github external
  () => getEnv('HIDE_EMPTY_TOKEN_ACCOUNTS'), // The result of this func is not used but it allows the input params to be different so that reselect recompute the output
  (accounts, ids) => flattenFilterAndSort(accounts, ids, { enforceHideEmptySubAccounts: true }),