Skip to content

Commit

Permalink
refactor: consistent config handling
Browse files Browse the repository at this point in the history
  • Loading branch information
mrfelton committed Apr 15, 2019
1 parent 91355e7 commit 2e8021e
Show file tree
Hide file tree
Showing 21 changed files with 68 additions and 96 deletions.
3 changes: 0 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@ module.exports = {
browser: true,
node: true,
},
globals: {
CONFIG: 'readable',
},
rules: {
camelcase: 0,
curly: ['error', 'all'],
Expand Down
21 changes: 7 additions & 14 deletions electron/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
* through IPC.
*
* When running `npm run build` or `npm run build-main`, this file is compiled to
* `/dist/main.prod.js` using webpack. This gives us some performance wins.
* `/dist/main.js` using webpack. This gives us some performance wins.
*/
import { app, BrowserWindow, session } from 'electron'
import isDev from 'electron-is-dev'
import installExtension, {
REACT_DEVELOPER_TOOLS,
REDUX_DEVTOOLS,
Expand All @@ -16,6 +17,7 @@ import path from 'path'
import os from 'os'
import fs from 'fs'
import bip21 from 'bip21'
import config from 'config'
import { mainLog } from '@zap/utils/log'
import themes from '@zap/renderer/themes'
import { getDbName } from '@zap/utils/db'
Expand All @@ -24,15 +26,6 @@ import ZapController from './controller'
import ZapUpdater from './updater'
import ZapMigrator from './migrator'

// When we run in production mode, this file is processd with webpack and our config is made available in the
// global CONFIG object. If this is not set then we must be running in development mode (where this file is loaded
// directly without processing with webpack), so we require the config module directly in this case.
try {
global.CONFIG = CONFIG
} catch (e) {
global.CONFIG = require('config')
}

// Set the Electron userDir to a temporary directory if the ELECTRON_USER_DIR_TEMP env var is set.
// This provides an easy way to run the app with a completely fresh environment, useful for e2e tests.
if (process.env.ELECTRON_USER_DIR_TEMP) {
Expand Down Expand Up @@ -143,7 +136,7 @@ const fetchSettings = () => {
// Once we have fetched (or failed to fetch) the user settings, destroy the window.
win.on('load-settings-done', () => process.nextTick(() => win.destroy()))

const { namespace, domain } = global.CONFIG.db
const { namespace, domain } = config.db
const { NODE_ENV: environment } = process.env
const dbName = getDbName({
namespace,
Expand Down Expand Up @@ -251,9 +244,9 @@ app.on('ready', async () => {
backgroundColor: get(theme, 'colors.primaryColor', '#242633'),
webPreferences: {
nodeIntegration: false,
preload: process.env.HOT
? path.resolve(__dirname, '..', 'dist', 'preload.dev.js')
: path.resolve(__dirname, 'preload.prod.js'),
preload: isDev
? path.resolve(__dirname, '..', 'dist', 'preload.js')
: path.resolve(__dirname, 'preload.js'),
},
})

Expand Down
4 changes: 3 additions & 1 deletion electron/migrations/purge-local-wallets.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import config from 'config'
import { purgeAllLocalWallets } from '@zap/utils/localWallets'

/**
* Migration script to purge all local wallets, causing a resync of the blockchain data.
*/
const migration = async () => {
await purgeAllLocalWallets()
const { chains, networks } = config
await purgeAllLocalWallets(chains, networks)
}

export default migration
8 changes: 3 additions & 5 deletions electron/preload.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* When running `npm run build` or `npm run build-preload`, this file is compiled to
* `/dist/preload.prod.js` using webpack.
* `/dist/preload.js` using webpack.
*/
import { ipcRenderer, remote, shell } from 'electron'
import fs from 'fs'
Expand All @@ -10,6 +10,7 @@ import assert from 'assert'
import url from 'url'
import untildify from 'untildify'
import rimraf from 'rimraf'
import config from 'config'
import { getDb } from '@zap/renderer/store/db'
import isSubDir from '@zap/utils/isSubDir'
import { getAllLocalWallets } from '@zap/utils/localWallets'
Expand Down Expand Up @@ -130,9 +131,6 @@ function getUserDataDir() {
return remote.app.getPath('userData')
}

// Expose global config.
window.CONFIG = CONFIG

// Provide access to whitelisted environment variables.
window.env = Object.keys(process.env)
.filter(key => WHITELISTED_ENV_VARS.includes(key))
Expand All @@ -142,7 +140,7 @@ window.env = Object.keys(process.env)
}, {})

// Initialise the database and make it globally accessible.
const { namespace, domain } = CONFIG.db
const { namespace, domain } = config.db
const { NODE_ENV: environment } = process.env
const dbName = getDbName({
namespace,
Expand Down
25 changes: 9 additions & 16 deletions lnd/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,10 @@ import lndconnect from 'lndconnect'
import fs from 'fs'
import util from 'util'
import pick from 'lodash.pick'
import config from 'config'
import { mainLog } from '@zap/utils/log'
import { binaryPath } from './util'

// When we run in production mode, this file is processd with webpack and our config is made available in the
// global CONFIG object. If this is not set then we must be running in development mode (where this file is loaded
// directly without processing with webpack), so we require the config module directly in this case.
try {
global.CONFIG = CONFIG
} catch (e) {
global.CONFIG = require('config')
}

const readFile = util.promisify(fs.readFile)

const debug = createDebug('zap:lnd-config')
Expand Down Expand Up @@ -60,12 +52,13 @@ const safeUntildify = val => (typeof val === 'string' ? untildify(val) : val)
*/
class LndConfig {
static getListen = async type => {
if (global.CONFIG.lnd[type].host) {
if (config.lnd[type].host) {
const port = await getPort({
host: global.CONFIG.lnd[type].host,
port: global.CONFIG.lnd[type].port,
host: config.lnd[type].host,
port: config.lnd[type].port,
})
return `${global.CONFIG.lnd[type].host}:${port}`

return `${config.lnd[type].host}:${port}`
}
return 0
}
Expand Down Expand Up @@ -144,8 +137,8 @@ class LndConfig {

// Assign default options.
this.type = 'local'
this.chain = global.CONFIG.chain
this.network = global.CONFIG.network
this.chain = config.chain
this.network = config.network

// Set base config.
const baseConfig = pick(options, ['id', 'type', 'chain', 'network', 'decoder'])
Expand All @@ -160,7 +153,7 @@ class LndConfig {
allocation: autopilotAllocation,
private: autopilotPrivate,
minconfs: autopilotMinconfs,
} = global.CONFIG.lnd.autopilot
} = config.lnd.autopilot

const lndDefaults = {
name: null,
Expand Down
12 changes: 2 additions & 10 deletions lnd/methods/invoicesController.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import config from 'config'
import { promisifiedCall } from '@zap/utils'
import pushinvoices from '../push/subscribeinvoice'

// When we run in production mode, this file is processd with webpack and our config is made available in the
// global CONFIG object. If this is not set then we must be running in development mode (where this file is loaded
// directly without processing with webpack), so we require the config module directly in this case.
try {
global.CONFIG = CONFIG
} catch (e) {
global.CONFIG = require('config')
}

/**
* Attempts to add a new invoice to the invoice database.
* @param lnd [description]
Expand All @@ -22,7 +14,7 @@ export function addInvoice(lnd, { memo, value, private: privateInvoice }) {
memo,
value,
private: privateInvoice,
expiry: global.CONFIG.invoices.expire,
expiry: config.invoices.expire,
})
}

Expand Down
12 changes: 2 additions & 10 deletions lnd/neutrino.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
import split2 from 'split2'
import { spawn } from 'child_process'
import EventEmitter from 'events'
import config from 'config'
import { mainLog, lndLog, lndLogGetLevel } from '@zap/utils/log'
import { fetchBlockHeight } from './util'
import LndConfig from './config'

// When we run in production mode, this file is processd with webpack and our config is made available in the
// global CONFIG object. If this is not set then we must be running in development mode (where this file is loaded
// directly without processing with webpack), so we require the config module directly in this case.
try {
global.CONFIG = CONFIG
} catch (e) {
global.CONFIG = require('config')
}

// Sync statuses
const CHAIN_SYNC_PENDING = 'chain-sync-pending'
const CHAIN_SYNC_WAITING = 'chain-sync-waiting'
Expand Down Expand Up @@ -120,7 +112,7 @@ class Neutrino extends EventEmitter {
// Configure neutrino backend.
neutrinoArgs.push('--bitcoin.node=neutrino')
neutrinoArgs.push(`--${this.lndConfig.chain}.${this.lndConfig.network}`)
global.CONFIG.lnd.neutrino[this.lndConfig.chain][this.lndConfig.network].forEach(node =>
config.lnd.neutrino[this.lndConfig.chain][this.lndConfig.network].forEach(node =>
neutrinoArgs.push(`--neutrino.connect=${node}`)
)

Expand Down
3 changes: 2 additions & 1 deletion lnd/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import axios from 'axios'
import { promisify } from 'util'
import { basename, dirname, join, normalize } from 'path'
import { platform } from 'os'
import { app } from 'electron'
import electron, { remote } from 'electron'
import isDev from 'electron-is-dev'
import { credentials, Metadata } from '@grpc/grpc-js'
import get from 'lodash.get'
Expand Down Expand Up @@ -31,6 +31,7 @@ const stat = promisify(fs.stat)
* @return {String} Path to the lnd binary.
*/
export const appRootPath = () => {
const app = electron.app || remote.app
return app.getAppPath().indexOf('default_app.asar') < 0 ? normalize(`${app.getAppPath()}/..`) : ''
}

Expand Down
3 changes: 2 additions & 1 deletion renderer/components/Autopay/AutopayCreateForm.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import PropTypes from 'prop-types'
import config from 'config'
import styled from 'styled-components'
import { FormattedMessage, injectIntl, intlShape } from 'react-intl'
import { Spring, animated, Transition } from 'react-spring/renderprops.cjs'
Expand All @@ -9,7 +10,7 @@ import AutopayCreateSuccess from './AutopayCreateSuccess'
import AutopayCreateSettings from './AutopayCreateSettings'
import messages from './messages'

const { min, max, defaultValue } = CONFIG.autopay
const { min, max, defaultValue } = config.autopay

const Container = styled(animated.div)`
position: absolute;
Expand Down
3 changes: 2 additions & 1 deletion renderer/components/Home/WalletLauncher.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import PropTypes from 'prop-types'
import config from 'config'
import { compose } from 'redux'
import { FormattedMessage, injectIntl, intlShape } from 'react-intl'
import { withRouter } from 'react-router-dom'
Expand All @@ -21,7 +22,7 @@ const WalletActionBar = styled(ActionBar)`
right: 0;
`

const { maxchannels, minchansize, maxchansize, allocation } = CONFIG.lnd.autopilot
const { maxchannels, minchansize, maxchansize, allocation } = config.lnd.autopilot
const autopilotDefaults = {
autopilotMaxchannels: maxchannels,
autopilotMinchansize: minchansize,
Expand Down
3 changes: 2 additions & 1 deletion renderer/components/Pay/Pay.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import PropTypes from 'prop-types'
import config from 'config'
import { Box, Flex } from 'rebass'
import { animated, Keyframes, Transition } from 'react-spring/renderprops.cjs'
import { FormattedMessage, injectIntl, intlShape } from 'react-intl'
Expand Down Expand Up @@ -294,7 +295,7 @@ class Pay extends React.Component {
payReq: values.payReq,
amt: this.amountInSats(),
feeLimit: getMaxFee(routes),
retries: CONFIG.invoices.retryCount,
retries: config.invoices.retryCount,
})
// Close the form modal once the payment has been sent
changeFilter('ALL_ACTIVITY')
Expand Down
7 changes: 4 additions & 3 deletions renderer/reducers/lnd.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import config from 'config'
import { send } from 'redux-electron-ipc'
import { createSelector } from 'reselect'
import { showSystemNotification } from '@zap/utils/notifications'
Expand Down Expand Up @@ -281,7 +282,7 @@ export const setUnlockWalletError = (event, unlockWalletError) => dispatch => {
}

export const fetchSeed = () => async dispatch => {
const { chain: defaultChain, network: defaultNetwork } = CONFIG
const { chain: defaultChain, network: defaultNetwork } = config

dispatch({ type: FETCH_SEED })
try {
Expand Down Expand Up @@ -312,7 +313,7 @@ export const fetchSeedError = (event, error) => dispatch => {

export const createNewWallet = () => async (dispatch, getState) => {
const state = getState()
const { chain: defaultChain, network: defaultNetwork } = CONFIG
const { chain: defaultChain, network: defaultNetwork } = config

// Define the wallet config.
let wallet = {
Expand All @@ -334,7 +335,7 @@ export const createNewWallet = () => async (dispatch, getState) => {

export const recoverOldWallet = () => async (dispatch, getState) => {
const state = getState()
const { chain: defaultChain, network: defaultNetwork } = CONFIG
const { chain: defaultChain, network: defaultNetwork } = config

// Define the wallet config.
let wallet = {
Expand Down
7 changes: 4 additions & 3 deletions renderer/reducers/onboarding.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import config from 'config'
import delay from '@zap/utils/delay'
import { setLoading } from './app'
import { walletSelectors } from './wallet'
Expand Down Expand Up @@ -223,9 +224,9 @@ const ACTION_HANDLERS = {
const initialState = {
onboarding: false,
isOnboarded: false,
autopilot: CONFIG.lnd.autopilot.active,
chain: CONFIG.chain,
network: CONFIG.network,
autopilot: config.lnd.autopilot.active,
chain: config.chain,
network: config.network,
validatingHost: false,
validatingCert: false,
validatingMacaroon: false,
Expand Down
3 changes: 2 additions & 1 deletion renderer/reducers/payment.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import config from 'config'
import { createSelector } from 'reselect'
import { send } from 'redux-electron-ipc'
import errorToUserFriendly from '@zap/utils/userFriendlyErrors'
Expand Down Expand Up @@ -149,7 +150,7 @@ export const paymentFailed = (event, { payment_request, error }) => async (dispa
}
const retryIndex = maxRetries - remainingRetries + 1
// add increasing delay
await delay(CONFIG.invoices.baseRetryDelay * retryIndex * retryIndex)
await delay(config.invoices.baseRetryDelay * retryIndex * retryIndex)
dispatch(payInvoice(data))
} else {
// Ensure payment stays in sending state for at least 2 seconds.
Expand Down
5 changes: 3 additions & 2 deletions renderer/reducers/ticker.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import config from 'config'
import { createSelector } from 'reselect'
import get from 'lodash.get'
import { requestTickers } from '@zap/utils/api'
Expand All @@ -16,8 +17,8 @@ export const RECIEVE_TICKERS = 'RECIEVE_TICKERS'

// Map for crypto codes to crypto tickers
const DEFAULT_CRYPTO_UNITS = {
bitcoin: CONFIG.units.bitcoin,
litecoin: CONFIG.units.litecoin,
bitcoin: config.units.bitcoin,
litecoin: config.units.litecoin,
}

// Map for crypto names to crypto tickers
Expand Down
4 changes: 3 additions & 1 deletion renderer/reducers/wallet.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import config from 'config'
import { createSelector } from 'reselect'
import { showError } from './notification'
import { putSetting } from './settings'
Expand Down Expand Up @@ -101,7 +102,8 @@ export const initWallets = () => async dispatch => {
dispatch(setWalletsLoaded())

// Create wallet entry in the database if one doesn't exist already.
const fsWallets = await window.Zap.getAllLocalWallets()
const { chains, networks } = config
const fsWallets = await window.Zap.getAllLocalWallets(chains, networks)
return fsWallets
.filter(wallet => wallet.wallet !== 'wallet-tmp')
.forEach(walletDetails => {
Expand Down
Loading

0 comments on commit 2e8021e

Please sign in to comment.