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

Network provider #223

Merged
merged 5 commits into from
Jun 30, 2022
Merged
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
10 changes: 0 additions & 10 deletions ext-src/api.ts

This file was deleted.

109 changes: 46 additions & 63 deletions ext-src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { ethers } from 'ethers';
import * as vscode from 'vscode';
import { InputBoxOptions, window, commands, workspace } from 'vscode';
import API from './api';
import Logger from './utils/logger';
import { InputBoxOptions, window, commands, workspace, WebviewPanel } from 'vscode';
import {
IAccountQP,
IFunctionQP,
Expand All @@ -12,7 +10,7 @@ import {
ConstructorInputValue,
TxReceipt,
GanacheAddressType,
IEthereumNetworkQP,
INetworkQP,
} from './types';
import {
parseCompiledJSONPayload,
Expand All @@ -27,10 +25,17 @@ import {
} from './lib';
import { errors } from './utils';
import { getAbi, getByteCode, CompiledJSONOutput } from './types/output';
import {
displayBalance,
getNetworkNames,
getSelectedNetwork,
getSelectedProvider,
updateSelectedNetwork,
} from './utils/networks';
import { logger } from './utils/logger';

const provider = ethers.providers;
// Create logger
const logger = new Logger();
const pwdInpOpt: InputBoxOptions = {
ignoreFocusOut: true,
password: true,
Expand Down Expand Up @@ -96,72 +101,76 @@ export async function activate(context: vscode.ExtensionContext) {
return signDeploy(context);
}),
// select ethereum networks
commands.registerCommand('ethcode.network.set', () => {
const quickPick = window.createQuickPick<IEthereumNetworkQP>();
const options: Array<IEthereumNetworkQP> = [
{ label: 'Main', networkName: '', chainId: 1 },
{ label: 'Ganache', networkName: 'ganache', chainId: 3 },
{ label: 'Ropsten', networkName: 'ropsten', chainId: 3 },
{ label: 'Rinkeby', networkName: 'rinkeby', chainId: 4 },
{ label: 'Goerli', networkName: 'goerli', chainId: 5 },
{ label: 'Kovan', networkName: 'kovan', chainId: 42 },
];
quickPick.items = options.map((network) => ({
label: network.label,
chainId: network.chainId,
networkName: network.networkName,
commands.registerCommand('ethcode.network.select', () => {
const quickPick = window.createQuickPick<INetworkQP>();

quickPick.items = getNetworkNames().map((name) => ({
label: name,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = 'Select network';
});
quickPick.onDidChangeSelection((selection: Array<IEthereumNetworkQP>) => {
quickPick.onDidChangeSelection((selection: Array<INetworkQP>) => {
if (selection[0]) {
const { chainId, networkName } = selection[0];
context.workspaceState.update('networkName', networkName);
context.workspaceState.update('chainId', chainId);
const { label } = selection[0];
updateSelectedNetwork(context, label);
quickPick.dispose();

logger.log(`Selected network is ${label}`);
}
});
quickPick.onDidHide(() => quickPick.dispose());
quickPick.show();
}),
// Set Ethereum Account
commands.registerCommand('ethcode.account.set', () => {
// Select Ethereum Account
commands.registerCommand('ethcode.account.select', () => {
const quickPick = window.createQuickPick<IAccountQP>();
const addresses: Array<LocalAddressType> | undefined = context.workspaceState.get('addresses');
const ganacheAddresses: Array<string> | undefined = context.workspaceState.get('ganache-addresses');
if (addresses && ganacheAddresses) {
let options: Array<IAccountQP> = addresses.map(
let options: Array<IAccountQP> = [];

if (addresses) {
options = addresses.map(
(account) =>
<IAccountQP>{
label: account.pubAddress,
description: 'Local account',
checksumAddr: account.checksumAddress,
}
);
}

if (ganacheAddresses) {
const gOpts: Array<IAccountQP> = ganacheAddresses.map(
(addr) => <IAccountQP>{ label: addr, description: 'Ganache account', checksumAddr: addr }
);
options = [...options, ...gOpts];
quickPick.items = options.map((account) => ({
label: account.checksumAddr,
description: account.description,
checksumAddr: account.checksumAddr,
}));
}

if (options.length === 0) return;

quickPick.items = options.map((account) => ({
label: account.checksumAddr,
description: account.description,
checksumAddr: account.checksumAddr,
}));

quickPick.onDidChangeActive(() => {
quickPick.placeholder = 'Select account';
});

quickPick.onDidChangeSelection((selection: Array<IAccountQP>) => {
if (selection[0]) {
const { checksumAddr } = selection[0];
context.workspaceState.update('account', checksumAddr);
quickPick.dispose();
}
});

quickPick.onDidHide(() => quickPick.dispose());
quickPick.show();
}),

// List local Accounts
commands.registerCommand('ethcode.account.list', () => {
const accWorker = createAccWorker();
Expand All @@ -188,44 +197,19 @@ export async function activate(context: vscode.ExtensionContext) {
console.log('error');
}
}),

// Get account balance
commands.registerCommand('ethcode.account.balance', async () => {
const networkName: any = await context.workspaceState.get('networkName');
const address: any = await context.workspaceState.get('account');
if (networkName === 'ganache') {
await new provider.JsonRpcProvider('http://127.0.0.1:7545').getBalance(address).then(async (balance) => {
const balanceinEth = ethers.utils.formatEther(balance);
await context.workspaceState.update('balance', balanceinEth);
const bal: any = await context.workspaceState.get('balance');
logger.success(`${address} has account Balance: ${bal} Eth`);
});
} else if (networkName === '') {
await provider
.getDefaultProvider()
.getBalance(address)
.then(async (balance) => {
const balanceinEth = ethers.utils.formatEther(balance);
await context.workspaceState.update('balance', balanceinEth);
const bal: any = await context.workspaceState.get('balance');
logger.success(`${address} has account Balance: ${bal} Eth`);
});
} else {
await provider
.getDefaultProvider(networkName)
.getBalance(address)
.then(async (balance) => {
const balanceinEth = ethers.utils.formatEther(balance);
await context.workspaceState.update('balance', balanceinEth);
const bal: any = await context.workspaceState.get('balance');
logger.success(`${address} has account Balance on ${networkName} network is: ${bal} Eth`);
});
}
displayBalance(context, address);
}),

// Set unsigned transaction
commands.registerCommand('ethcode.transaction.set', async (tx) => {
const unsignedTx = tx || (await window.showInputBox(unsignedTxInp));
context.workspaceState.update('unsignedTx', unsignedTx);
}),

// Create unsigned transaction
commands.registerCommand('ethcode.transaction.build', async () => {
const networkId = context.workspaceState.get('networkId');
Expand Down Expand Up @@ -458,13 +442,12 @@ export async function activate(context: vscode.ExtensionContext) {
const gas = await window.showInputBox(gasInp);
context.workspaceState.update('gasEstimate', gas);
}),

// Activate
commands.registerCommand('ethcode.activate', async () => {
commands.executeCommand('ethcode.account.list');
commands.executeCommand('ethcode.account.ganache.list');
logger.success('Welcome to Ethcode!');
})
);
const api = new API();
return api;
}
3 changes: 1 addition & 2 deletions ext-src/lib/core.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { window, ExtensionContext, InputBoxOptions } from 'vscode';
import * as fs from 'fs';
import Logger from '../utils/logger';
import { logger } from '../utils/logger';
import { ConstructorInputValue, CompiledJSONOutput } from '../types';
import { createWorker, createAccWorker } from './workerCreator';
import { getAbi, getByteCode } from '../types/output';
import * as path from 'path';

// Create logger
const logger = new Logger();
const pwdInpOpt: InputBoxOptions = {
ignoreFocusOut: true,
password: true,
Expand Down
5 changes: 2 additions & 3 deletions ext-src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,9 @@ export interface INetworkQP extends QuickPickItem {
label: string;
}
export interface IEthereumNetworkQP extends QuickPickItem {
networkName?: string;
name: string;
rpc: string;
chainId?: number | string;
RPCurl?: string | undefined;
BlockExplorerUrl?: string | undefined;
}

export interface IAccountQP extends QuickPickItem {
Expand Down
3 changes: 0 additions & 3 deletions ext-src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
import Logger from './logger';

export * from './toast';
export { Logger };
export * from './errors';
4 changes: 3 additions & 1 deletion ext-src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { window, OutputChannel } from 'vscode';
import { errorToast, successToast } from './toast';

export default class Logger {
class Logger {
private outputChannel: OutputChannel;

constructor(name?: string) {
Expand Down Expand Up @@ -34,3 +34,5 @@ export default class Logger {
successToast(m);
}
}

export const logger = new Logger();
65 changes: 65 additions & 0 deletions ext-src/utils/networks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { ethers } from 'ethers';
import * as vscode from 'vscode';
import { logger } from './logger';

const provider = ethers.providers;

const getConfiguration = () => {
return vscode.workspace.getConfiguration('ethcode');
};

const getNetworkNames = (): Array<string> => {
const networks = getConfiguration().get('networks') as object;
return Object.keys(networks);
};

// Selected Network Configuratin Helper
const getSelectedNetwork = (context: vscode.ExtensionContext): string => {
return context.workspaceState.get('selectedNetwork') as string;
};

const getSeletedRpcUrl = (context: vscode.ExtensionContext) => {
const networks = getConfiguration().get('networks') as any;
return networks[getSelectedNetwork(context)];
};

const updateSelectedNetwork = async (context: vscode.ExtensionContext, name: string) => {
context.workspaceState.update('selectedNetwork', name);
};

const isValidHttpUrl = (url_: string): boolean => {
let url;

try {
url = new URL(url_);
} catch (_) {
return false;
}

return url.protocol === 'http:' || url.protocol === 'https:';
};

const getSelectedProvider = (context: vscode.ExtensionContext) => {
const rpc = getSeletedRpcUrl(context); // default providers have a name with less than 10 chars
if (isValidHttpUrl(rpc)) return new provider.JsonRpcProvider(rpc);

return provider.getDefaultProvider(rpc);
};

const displayBalance = (context: vscode.ExtensionContext, address: string) => {
try {
getSelectedProvider(context)
.getBalance(address)
.then(async (value) => {
const balance = ethers.utils.formatEther(value);
context.workspaceState.update('balance', balance);

const networkName: any = getSelectedNetwork(context);
logger.success(`${address} has account Balance on ${networkName} network is: ${balance} Eth`);
});
} catch (_) {
logger.error(new Error("Selected network RPC isn't supported."));
}
};

export { getNetworkNames, getSelectedNetwork, getSelectedProvider, updateSelectedNetwork, displayBalance };
34 changes: 34 additions & 0 deletions ext-src/utils/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { workspace, ConfigurationTarget } from 'vscode';
import { logger } from './logger';

export function updateUserSession(valueToAssign: any, keys: string[]): Promise<string> {
return new Promise((resolve, reject) => {
try {
// @ts-ignore
const config = workspace.getConfiguration('ethcode', workspace.workspaceFolders[0].uri);
if (keys.length === 2) {
const userSession = `${keys[0]}.${keys[1]}`;
config.update(userSession, valueToAssign);
resolve(userSession);
// @ts-ignore
} else if (keys.length === 3) {
const userSession = `${keys[0]}.${keys[1]}.${keys[2]}`;
// @ts-ignore
config.update(userSession, valueToAssign);
resolve(userSession);
}
} catch (err) {
reject(err);
}
});
}

export async function updateUserSettings(accessScope: string, valueToAdd: string): Promise<boolean> {
try {
await workspace.getConfiguration('ethcode').update(accessScope, valueToAdd, ConfigurationTarget.Global);
return true;
} catch (e) {
logger.log('Error updating: ', e);
return false;
}
}
Loading