Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add network switch #430

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"main": "dist/desktop/src/index.js",
"scripts": {
"start": "concurrently -n \"desktop,ui\" \"cross-env-shell NODE_ENV=development 'npm run clean && npm run build && electron-forge start'\" \"cd ui && npm start\"",
"start:backend": "npm run build:desktop && electron-forge start",
"package": "electron-forge package",
"make": "electron-forge make",
"publish": "electron-forge publish",
Expand Down Expand Up @@ -54,6 +55,7 @@
"@electron-forge/publisher-github": "^6.0.0-beta.64",
"@kayahr/jest-electron-runner": "^4.4.1",
"@types/cross-zip": "^4.0.0",
"@types/electron-prompt": "^1.6.5",
"@types/fs-extra": "^9.0.13",
"@types/jest": "^27.4.1",
"@types/js-yaml": "^4.0.5",
Expand Down Expand Up @@ -90,6 +92,7 @@
"dependencies": {
"@koa/router": "^10.1.1",
"cross-zip": "^4.0.0",
"electron-prompt": "^1.7.0",
"electron-squirrel-startup": "^1.0.0",
"env-paths": "2",
"ethereumjs-wallet": "^1.0.2",
Expand Down
3 changes: 0 additions & 3 deletions src/.sentry.json

This file was deleted.

16 changes: 8 additions & 8 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,27 @@ export function configYamlExists(): boolean {
return existsSync(getPath('config.yaml'))
}

export function readConfigYaml(): Record<string, unknown> {
const raw = readFileSync(getPath('config.yaml'), 'utf-8')
export function readConfigYaml(fileName = 'config.yaml'): Record<string, unknown> {
const raw = readFileSync(getPath(fileName), 'utf-8')
const data = load(raw, {
schema: FAILSAFE_SCHEMA,
})

return data as Record<string, unknown>
}

export function writeConfigYaml(newValues: Record<string, unknown>) {
const data = readConfigYaml()
export function writeConfigYaml(newValues: Record<string, unknown>, fileName = 'config.yaml') {
const data = readConfigYaml(fileName)
for (const [key, value] of Object.entries(newValues)) {
data[key] = value
}
writeFileSync(getPath('config.yaml'), dump(data))
writeFileSync(getPath(fileName), dump(data))
}

export function deleteKeyFromConfigYaml(key: string) {
const data = readConfigYaml()
export function deleteKeyFromConfigYaml(key: string, fileName = 'config.yaml') {
const data = readConfigYaml(fileName)
delete data[key]
writeFileSync(getPath('config.yaml'), dump(data))
writeFileSync(getPath(fileName), dump(data))
}

export function getDesktopVersionFromFile(): string | undefined {
Expand Down
17 changes: 17 additions & 0 deletions src/electron.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { app, Menu, nativeTheme, Tray } from 'electron'
import opener from 'opener'
import { openDashboardInBrowser, openEtherjotInBrowser } from './browser'
import { readConfigYaml } from './config'
import { runLauncher } from './launcher'
import { BeeManager } from './lifecycle'
import { getCurrentNetwork, toggleNetwork } from './network'
import { createNotification } from './notify'
import { getAssetPath, paths } from './path'

Expand All @@ -28,6 +30,12 @@
}
},
},
{
label: getCurrentNetwork() === 'main' ? 'Switch to Testnet' : 'Switch to Mainnet',
click: () => {
toggleNetwork()
},
},
{ type: 'separator' },
{
type: 'submenu',
Expand All @@ -46,6 +54,15 @@
opener(paths.log)
},
},
{
label: 'Data Directory',
click: async () => {
const config = readConfigYaml()
if (typeof config['data-dir'] === 'string') {

Check failure on line 61 in src/electron.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
opener(config['data-dir'])
}
},
},
{
label: 'Quit',
click: async () => {
Expand Down
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@
import { runServer } from './server'
import { getStatus } from './status'

// TODO: Add types definition

Check warning on line 16 in src/index.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Unexpected 'todo' comment: 'TODO: Add types definition'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import squirrelInstallingExecution from 'electron-squirrel-startup'
import { runMigrations } from './migration'
import { initializeMultinetConfig } from './network'
import { initSplash, Splash } from './splash'

runMigrations()
Expand Down Expand Up @@ -74,10 +75,15 @@
await initializeBee()
}

await initializeMultinetConfig()

runLauncher().catch(errorHandler)
runElectronTray()

if (process.env.NODE_ENV !== 'development') openDashboardInBrowser()
if (process.env.NODE_ENV !== 'development') {
openDashboardInBrowser()
}

splash.hide()
splash = undefined

Expand Down
4 changes: 4 additions & 0 deletions src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ export async function runLauncher() {
mkdirSync(getPath('data-dir'))
}

if (!checkPath('data-dir-test')) {
mkdirSync(getPath('data-dir-test'))
}

BeeManager.setUserIntention(true)
const subprocess = launchBee(abortController).catch(reason => {
logger.error(reason)
Expand Down
93 changes: 93 additions & 0 deletions src/network.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { dialog } from 'electron'
import prompt from 'electron-prompt'
import { cpSync, existsSync } from 'fs'
import fetch from 'node-fetch'
import { deleteKeyFromConfigYaml, readConfigYaml, writeConfigYaml } from './config'
import { runLauncher } from './launcher'
import { BeeManager } from './lifecycle'
import { getPath } from './path'

export function getCurrentNetwork(): 'test' | 'main' {
const config = readConfigYaml()
if (config.mainnet === true || config.mainnet === 'true') {

Check failure on line 12 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
return 'main'
}
return 'test'

Check failure on line 15 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
}

export function initializeMultinetConfig() {
if (!existsSync(getPath('config.main.yaml'))) {
cpSync(getPath('config.yaml'), getPath('config.main.yaml'))
}
if (!existsSync(getPath('config.test.yaml'))) {

Check failure on line 22 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
cpSync(getPath('config.yaml'), getPath('config.test.yaml'))
writeConfigYaml(
{
mainnet: false,
'swap-enable': false,
'chequebook-enable': false,
'data-dir': getPath('data-dir-test'),
},
'config.test.yaml',
)
deleteKeyFromConfigYaml('blockchain-rpc-endpoint', 'config.test.yaml')
}
}

export async function toggleNetwork() {
const currentNetwork = getCurrentNetwork()
if (currentNetwork === 'main') {

Check failure on line 39 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
await switchToTestnet()
} else {
await switchToMainnet()
}
}

export async function switchToTestnet() {
const testConfig = readConfigYaml('config.test.yaml')
if (!testConfig['blockchain-rpc-endpoint']) {

Check failure on line 48 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
const answer = await prompt({
title: 'Sepolia JSON RPC endpoint',
label: 'URL:',
value: 'http://example.org',
inputAttrs: {
type: 'url',
},
type: 'input',
}).catch(console.error)

Check failure on line 57 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Unexpected console statement
if (!answer) {

Check failure on line 58 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
dialog.showErrorBox('Error', 'Sepolia JSON RPC endpoint is required')
return

Check failure on line 60 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
}
const response = await fetch(answer, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 1 }),
}).catch(() => {
dialog.showErrorBox('Error', 'Sepolia JSON RPC endpoint is not reachable')
})
if (!response) {

Check failure on line 69 in src/network.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Expected blank line before this statement
return
}
const data = await response.json().catch(() => {
dialog.showErrorBox('Error', 'Sepolia JSON RPC endpoint is not returning valid JSON')
})
if (!data) {
return
}
writeConfigYaml({ 'blockchain-rpc-endpoint': answer }, 'config.test.yaml')
}
BeeManager.stop()
await BeeManager.waitForSigtermToFinish()
cpSync(getPath('config.yaml'), getPath('config.main.yaml'))
cpSync(getPath('config.test.yaml'), getPath('config.yaml'))
runLauncher()
}

export async function switchToMainnet() {
BeeManager.stop()
await BeeManager.waitForSigtermToFinish()
cpSync(getPath('config.yaml'), getPath('config.test.yaml'))
cpSync(getPath('config.main.yaml'), getPath('config.yaml'))
runLauncher()
}
11 changes: 10 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { readConfigYaml, readWalletPasswordOrThrow, writeConfigYaml } from './co
import { runLauncher } from './launcher'
import { BeeManager } from './lifecycle'
import { logger, readBeeDesktopLogs, readBeeLogs, subscribeLogServerRequests } from './logger'
import { getPath } from './path'
import { getPath, paths } from './path'
import { port } from './port'
import { getStatus } from './status'
import { swap } from './swap'
Expand Down Expand Up @@ -145,6 +145,15 @@ export function runServer() {
context.body = { message: 'Failed to swap', error }
}
})
router.post('/open/logs', async context => {
opener(paths.log)
context.body = { success: true }
})
router.post('/open/data-dir', async context => {
const config = readConfigYaml()
opener(config['data-dir'])
context.body = { success: true }
})

app.use(router.routes())
app.use(router.allowedMethods())
Expand Down
Loading