Skip to content

Commit

Permalink
fix: refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ipapandinas committed Feb 1, 2024
1 parent 93d41d6 commit 4708ab4
Show file tree
Hide file tree
Showing 9 changed files with 172 additions and 222 deletions.
34 changes: 17 additions & 17 deletions src/commands/account/create.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Flags } from "@oclif/core";
import chalk from "chalk";
import { ChainAccount, encrypt, isLocalConfigCheck } from "../../lib/index.js";
import { ChainAccount, encrypt, getSwankyConfig, isLocalConfigCheck } from "../../lib/index.js";
import { AccountData } from "../../types/index.js";
import inquirer from "inquirer";
import { SwankyCommand } from "../../lib/swankyCommand.js";
Expand All @@ -11,13 +11,17 @@ export class CreateAccount extends SwankyCommand<typeof CreateAccount> {

static flags = {
global: Flags.boolean({
description: "Create account globally: stored in both Swanky system and local configs.",
}),
generate: Flags.boolean({
char: "g",
description: "Create account globally stored in Swanky system config.",

}),
new: Flags.boolean({
char: "n",
description: "Generate a brand new account.",
}),
dev: Flags.boolean({
char: "d",
description: "Make this account a dev account for local network usage.",
}),
};

Expand Down Expand Up @@ -46,7 +50,7 @@ export class CreateAccount extends SwankyCommand<typeof CreateAccount> {
}

let tmpMnemonic = "";
if (flags.generate) {
if (flags.new) {
tmpMnemonic = ChainAccount.generate();
console.log(
`${
Expand Down Expand Up @@ -85,26 +89,22 @@ export class CreateAccount extends SwankyCommand<typeof CreateAccount> {
accountData.mnemonic = tmpMnemonic;
}

const configBuilder = new ConfigBuilder(this.swankyConfig);
const configType = flags.global ? "global" : isLocalConfigCheck() ? "local" : "global";
const config = configType === "global" ? getSwankyConfig("global") : this.swankyConfig;

const configBuilder = new ConfigBuilder(config);
configBuilder.addAccount(accountData);

if (this.swankyConfig.defaultAccount === null) {
configBuilder.setDefaultAccount(accountData.alias);
}

const updatedConfig = configBuilder.build();

try {
if (isLocalConfigCheck()) {
await this.storeConfig(updatedConfig, 'local', process.cwd());
if (flags.global) {
await this.storeConfig(updatedConfig, 'global');
}
} else {
await this.storeConfig(updatedConfig, 'global');
}
await this.storeConfig(configBuilder.build(), configType);
} catch (cause) {
throw new FileError("Error storing created account in config", { cause });
throw new FileError(`Error storing created account in ${configType} config`, {
cause,
});
}

this.log(
Expand Down
142 changes: 48 additions & 94 deletions src/commands/account/default.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import { Args, Flags } from "@oclif/core";
import chalk from "chalk";
import { AccountData } from "../../types/index.js";
import { SwankySystemConfig } from "../../types/index.js";
import inquirer from "inquirer";
import { SwankyCommand } from "../../lib/swankyCommand.js";
import { ConfigError } from "../../lib/errors.js";
import { configName, getSwankySystemConfig, isEnvConfigCheck, isLocalConfigCheck } from "../../lib/index.js";
import { ConfigError, FileError } from "../../lib/errors.js";
import { getSwankyConfig, isLocalConfigCheck } from "../../lib/index.js";
import { ConfigBuilder } from "../../lib/config-builder.js";

export class DefaultAccount extends SwankyCommand<typeof DefaultAccount> {
static description = "Set default account to use";

static flags = {
global: Flags.boolean({
char: "g",
description: "Set default account globally: stored in both Swanky system and local configs.",
description: "Set default account globally in Swanky system config.",
}),
};

Expand All @@ -32,98 +33,51 @@ export class DefaultAccount extends SwankyCommand<typeof DefaultAccount> {
async run(): Promise<void> {
const { args, flags } = await this.parse(DefaultAccount);

const systemConfig = await getSwankySystemConfig();
const configType = flags.global ? "global" : isLocalConfigCheck() ? "local" : "global";
const config = configType === "global" ? getSwankyConfig("global") : this.swankyConfig;

if (args.accountAlias) {
const accountData = this.swankyConfig.accounts.find(
(account: AccountData) => account.alias === args.accountAlias,
);
const systemAccountData = systemConfig.accounts.find(
(account: AccountData) => account.alias === args.accountAlias,
);
if (isLocalConfigCheck()) {
if (!accountData) {
if (!isEnvConfigCheck() || flags.global) {
if (!systemAccountData) {
throw new ConfigError(`Provided account alias ${chalk.yellowBright(args.accountAlias)} not found in "${configName()}" and system config`);
}
systemConfig.defaultAccount = systemAccountData.alias;
await this.storeConfig(systemConfig, "global");
console.log(chalk.greenBright(`Default account set to ${chalk.yellowBright(systemConfig.defaultAccount)} in system config`));
} else {
throw new ConfigError(`Provided account alias ${chalk.yellowBright(args.accountAlias)} not found in "${configName()}"`);
}
} else {
if (flags.global) {
if (!systemAccountData) {
throw new ConfigError(`Provided account alias ${chalk.yellowBright(args.accountAlias)} not found in system config`);
}
systemConfig.defaultAccount = accountData.alias;
await this.storeConfig(systemConfig, "global");
}
this.swankyConfig.defaultAccount = accountData.alias;
await this.storeConfig(this.swankyConfig, "local");
console.log(chalk.greenBright(`Default account set to ${chalk.yellowBright(this.swankyConfig.defaultAccount)}`));
}
} else {
if (!accountData) {
throw new ConfigError(`Provided account alias ${chalk.yellowBright(args.accountAlias)} not found in system config`);
}
this.swankyConfig.defaultAccount = accountData.alias;
await this.storeConfig(this.swankyConfig, "global");
console.log(chalk.greenBright(`Default account set to ${chalk.yellowBright(this.swankyConfig.defaultAccount)} in system config`));
}
} else {
let choices: {
name: string,
value: { alias: string, systemConfig: boolean }
}[] = [];
if(isLocalConfigCheck()) {
this.swankyConfig.accounts.forEach((account: AccountData) => {
choices.push({
name: `${account.alias} (${account.address})`,
value: { alias: account.alias, systemConfig: false },
});
});
}
if (!isEnvConfigCheck() || flags.global) {
systemConfig.accounts.forEach((account: AccountData) => {
if (!choices.find((choice: any) => choice.value.alias === account.alias)) {
choices.push({
name: `${account.alias} (${account.address}) [system config]`,
value: { alias: account.alias, systemConfig: true },
});
}
});
}
await inquirer.prompt([
{
type: "list",
name: "defaultAccount",
message: "Select default account",
choices: choices,
},
]).then((answers) => {
if (answers.defaultAccount.systemConfig) {
systemConfig.defaultAccount = answers.defaultAccount.alias;
this.storeConfig(systemConfig, "global");
console.log(chalk.greenBright(`Default account set to ${chalk.yellowBright(systemConfig.defaultAccount)} in system config`));
} else {
if (flags.global) {
const systemAccountData = systemConfig.accounts.find(
(account: AccountData) => account.alias === answers.defaultAccount.alias,
);
if (!systemAccountData) {
throw new ConfigError(`Provided account alias ${chalk.yellowBright(answers.defaultAccount.alias)} not found in system config`);
}
systemConfig.defaultAccount = answers.defaultAccount.alias;
this.storeConfig(systemConfig, "global");
}
this.swankyConfig.defaultAccount = answers.defaultAccount.alias;
this.storeConfig(this.swankyConfig, "local");
console.log(chalk.greenBright(`Default account set to ${chalk.yellowBright(this.swankyConfig.defaultAccount)}`));
}
const accountAlias = args.accountAlias ?? (await this.promptForAccountAlias(config));
this.ensureAccountExists(config, accountAlias);

const configBuilder = new ConfigBuilder(config);
configBuilder.setDefaultAccount(accountAlias);

try {
await this.storeConfig(configBuilder.build(), configType);
} catch (cause) {
throw new FileError(`Error storing default account in ${configType} config`, {
cause,
});
}

this.log(
`${chalk.greenBright("✔")} Account with alias ${chalk.yellowBright(
accountAlias
)} set as default in ${configType} config`
);
}

private async promptForAccountAlias(config: SwankySystemConfig): Promise<string> {
const choices = config.accounts.map((account) => ({
name: `${account.alias} (${account.address})`,
value: account.alias,
}));

const answer = await inquirer.prompt([
{
type: "list",
name: "defaultAccount",
message: "Select default account",
choices: choices,
},
]);

return answer.defaultAccount;
}

private ensureAccountExists(config: SwankySystemConfig, alias: string) {
const isSomeAccount = config.accounts.some((account) => account.alias === alias);
if (!isSomeAccount)
throw new ConfigError(`Provided account alias ${chalk.yellowBright(alias)} not found`);
}
}
6 changes: 0 additions & 6 deletions src/commands/contract/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,6 @@ export class DeployContract extends SwankyCommand<typeof DeployContract> {
);
}

if(this.swankyConfig.defaultAccount === null)
{
this.swankyConfig.defaultAccount = accountAlias;
await this.storeConfig(this.swankyConfig, 'local');
}

const mnemonic = accountData.isDev
? (accountData.mnemonic as string)
: decrypt(
Expand Down
4 changes: 2 additions & 2 deletions src/commands/contract/new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ export class NewContract extends SwankyCommand<typeof NewContract> {
await this.spinner.runCommand(async () => {
const configBuilder = new ConfigBuilder(this.swankyConfig);
configBuilder.addContract(args.contractName);

await this.storeConfig(configBuilder.build(), 'local')}, "Writing config");
await this.storeConfig(configBuilder.build(), "local");
}, "Writing config");

this.log("😎 New contract successfully generated! 😎");
}
Expand Down
19 changes: 5 additions & 14 deletions src/commands/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import inquirer from "inquirer";
import TOML from "@iarna/toml";
import { choice, email, name, pickTemplate } from "../../lib/prompts.js";
import {
buildSwankyConfig,
checkCliDependencies,
copyCommonTemplateFiles,
copyContractTemplateFiles,
Expand All @@ -24,7 +25,6 @@ import { merge } from "lodash-es";
import inquirerFuzzyPath from "inquirer-fuzzy-path";
import chalk from "chalk";
import { ConfigBuilder } from "../../lib/config-builder.js";
import { SwankyConfig } from "../../types/index.js";

type TaskFunction = (...args: any[]) => any;

Expand Down Expand Up @@ -90,13 +90,12 @@ export class Init extends SwankyCommand<typeof Init> {

taskQueue: Task[] = [];

configBuilder = new ConfigBuilder({} as SwankyConfig);
configBuilder = new ConfigBuilder(buildSwankyConfig());

async run(): Promise<void> {
const { args, flags } = await this.parse(Init);

this.projectPath = path.resolve(args.projectName);
this.configBuilder = new ConfigBuilder(this.swankyConfig);

// check if projectPath dir exists and is it empty
try {
Expand Down Expand Up @@ -147,8 +146,7 @@ export class Init extends SwankyCommand<typeof Init> {
task: downloadNode,
args: [this.projectPath, swankyNode, this.spinner],
runningMessage: "Downloading Swanky node",
callback: (result) =>
this.configBuilder.build().node ? (this.configBuilder.updateNodeSettings({ localPath: result })) : null,
callback: (localPath) => this.configBuilder.updateNodeSettings({ localPath }),
});
}
}
Expand All @@ -159,11 +157,8 @@ export class Init extends SwankyCommand<typeof Init> {
});

this.taskQueue.push({
task: async () => {
this.swankyConfig = this.configBuilder.build();
await this.storeConfig(this.swankyConfig, 'global');
await this.storeConfig(this.swankyConfig, 'local', this.projectPath);
},
task: async () =>
await this.storeConfig(this.configBuilder.build(), "local", this.projectPath),
args: [],
runningMessage: "Writing config",
shouldExitOnError: true,
Expand Down Expand Up @@ -331,10 +326,6 @@ export class Init extends SwankyCommand<typeof Init> {
},
});

if (!this.configBuilder.build().contracts){
this.configBuilder.updateContracts({})
}

for (const contract of confirmedCopyList.contracts) {
this.configBuilder.addContract(contract.name, contract.moduleName);
}
Expand Down
22 changes: 9 additions & 13 deletions src/commands/node/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,15 @@ export class InstallNode extends SwankyCommand<typeof InstallNode> {
)) as string;
const nodePath = path.resolve(projectPath, taskResult);

await this.spinner.runCommand(
async () => {
const configBuilder = new ConfigBuilder(this.swankyConfig);
configBuilder.updateNodeSettings({
localPath: nodePath,
polkadotPalletVersions: swankyNode.polkadotPalletVersions,
supportedInk: swankyNode.supportedInk,
})
this.swankyConfig = configBuilder.build();
await this.storeConfig(this.swankyConfig, 'local')
},
"Updating swanky config"
);
await this.spinner.runCommand(async () => {
const configBuilder = new ConfigBuilder(this.swankyConfig);
configBuilder.updateNodeSettings({
localPath: nodePath,
polkadotPalletVersions: swankyNode.polkadotPalletVersions,
supportedInk: swankyNode.supportedInk,
});
await this.storeConfig(configBuilder.build(), "local");
}, "Updating swanky config");

this.log("Swanky Node Installed successfully");
}
Expand Down
Loading

0 comments on commit 4708ab4

Please sign in to comment.