Skip to content

Commit

Permalink
fixups
Browse files Browse the repository at this point in the history
  • Loading branch information
mixmix committed Aug 29, 2024
1 parent 036936b commit 9cb1b81
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 59 deletions.
18 changes: 5 additions & 13 deletions src/account/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Command, Option } from 'commander'
import { EntropyAccount } from "./main";
import { ACCOUNTS_CONTENT } from './constants'
import * as config from '../config'
import { cliWrite, endpointOption, passwordOption } from "../common/utils-cli";
import { cliWrite, passwordOption } from "../common/utils-cli";
import { updateConfig } from "src/common/utils";

export async function entropyAccountCommand (entropy: Entropy, rootCommand: Command) {
Expand All @@ -18,7 +18,6 @@ function entropyAccountNew (accountCommand: Command) {
accountCommand.command('create')
.alias('new')
.description('Create a new entropy account from scratch. Output is JSON of form {name, address}')
.addOption(endpointOption())
.addOption(passwordOption())
.argument('<name>', 'A user friendly name for your nem account.')
.addOption(
Expand All @@ -28,13 +27,8 @@ function entropyAccountNew (accountCommand: Command) {
).default(ACCOUNTS_CONTENT.path.default)
)
.action(async (name, opts) => {
const { endpoint, path } = opts

const service = new EntropyAccount({ endpoint })
const newAccount = await service.create({
name,
path
})
const { path } = opts
const newAccount = EntropyAccount.create({ name, path })

const storedConfig = await config.get()
const { accounts } = storedConfig
Expand All @@ -58,12 +52,10 @@ function entropyAccountList (accountCommand: Command) {
accountCommand.command('list')
.alias('ls')
.description('List all accounts. Output is JSON of form [{ name, address, verifyingKeys }]')
.addOption(endpointOption())
.action(async (options) => {
.action(async () => {
// TODO: test if it's an encrypted account, if no password provided, throw because later on there's no protection from a prompt coming up
const storedConfig = await config.get()
const service = new EntropyAccount({ endpoint: options.endpoint })
const accounts = service.list(storedConfig.accounts)
const accounts = EntropyAccount.list(storedConfig.accounts)
cliWrite(accounts)
process.exit(0)
})
Expand Down
8 changes: 5 additions & 3 deletions src/account/interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {


export async function entropyManageAccounts (endpoint: string, storedConfig: EntropyConfig) {
const AccountService = new EntropyAccount({ endpoint })
const { accounts } = storedConfig
const { interactionChoice } = await inquirer.prompt(manageAccountsQuestions)
switch (interactionChoice) {
Expand All @@ -25,8 +24,11 @@ export async function entropyManageAccounts (endpoint: string, storedConfig: Ent
// isDebugMode = true
seed = seed.split('#debug')[0]
}
const newAccount = await AccountService.create({ seed, name, path })
const newAccount = seed
? EntropyAccount.import({ seed, name, path })
: EntropyAccount.create({ name, path })
accounts.push(newAccount)

return {
accounts,
selectedAccount: newAccount.address
Expand Down Expand Up @@ -55,7 +57,7 @@ export async function entropyManageAccounts (endpoint: string, storedConfig: Ent
}

export async function entropyRegister (entropy: Entropy, endpoint: string, storedConfig: EntropyConfig): Promise<Partial<EntropyConfig>> {
const AccountService = new EntropyAccount({ entropy, endpoint })
const AccountService = new EntropyAccount(entropy, endpoint)

const { accounts, selectedAccount } = storedConfig
const currentAccount = getSelectedAccount(accounts, selectedAccount)
Expand Down
87 changes: 48 additions & 39 deletions src/account/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,25 @@ import Entropy from "@entropyxyz/sdk";
import Keyring from '@entropyxyz/sdk/keys'
import { randomAsHex } from '@polkadot/util-crypto'

import { EntropyBase } from "../common/entropy-base";
import { EntropyAccountConfig } from "../config/types";

import { FLOW_CONTEXT } from "./constants";
import { AccountCreateParams, AccountRegisterParams } from "./types";
import { AccountCreateParams, AccountImportParams, AccountRegisterParams } from "./types";
import { print } from "src/common/utils";
import { formatAccountsList } from "./utils";

import { EntropyBase } from "../common/entropy-base";
import { EntropyAccountConfig } from "../config/types";

export class EntropyAccount extends EntropyBase {
// Entropy does not need to be required, as only register needs it
// Idea: We could use entropy as an argument for the register method,
// the base class has been updated to optionally require entropy in the
// constructor.
constructor ({ entropy, endpoint }: { entropy?: Entropy, endpoint: string }) {
constructor (entropy: Entropy, endpoint: string) {
super({ entropy, endpoint, flowContext: FLOW_CONTEXT })
}

async create ({ seed = randomAsHex(32), name, path }: AccountCreateParams): Promise<EntropyAccountConfig> {
static create ({ name, path }: AccountCreateParams): EntropyAccountConfig {
const seed = randomAsHex(32)
return EntropyAccount.import({ name, seed, path })
}

static import ({ name, seed, path }: AccountImportParams ): EntropyAccountConfig {
const keyring = new Keyring({ seed, path, debug: true })
const fullAccount = keyring.getAccount()
// TODO: sdk should create account on constructor
Expand All @@ -31,14 +32,14 @@ export class EntropyAccount extends EntropyBase {
// const encryptedData = password ? passwordFlow.encrypt(data, password) : data

return {
name: name,
name,
address: admin.address,
data
// data: encryptedData // TODO: replace once password input is added back
}
}

list ({ accounts }: { accounts: EntropyAccountConfig[] }) {
static list (accounts: EntropyAccountConfig[]) {
const accountsArray = Array.isArray(accounts) && accounts.length
? accounts
: []
Expand All @@ -49,49 +50,57 @@ export class EntropyAccount extends EntropyBase {
return formatAccountsList(accountsArray)
}

private async register (params?: AccountRegisterParams): Promise<string> {
async register (params?: AccountRegisterParams): Promise<string> {
const { programModAddress, programData } = params
let verifyingKey: string
try {
const registerParams = programModAddress && programData ? { programDeployer: programModAddress, programData } : undefined

verifyingKey = await this.entropy.register(registerParams)
return verifyingKey
} catch (error) {
if (!verifyingKey) {
try {
const tx = this.entropy.substrate.tx.registry.pruneRegistration()
await tx.signAndSend(this.entropy.keyring.accounts.registration.pair, ({ status }) => {
if (status.isFinalized) {
print('Successfully pruned registration');
}
})
} catch (error) {
console.error('Unable to prune registration due to:', error.message);
throw error
}
const registerParams = programModAddress && programData
? {
programDeployer: programModAddress,
programData
}
throw error
}
: undefined

return this.entropy.register(registerParams)
.catch(async error => {
await this.pruneRegistration()
throw error
})
}

// WATCH: should this be extracted to interaction.ts?
async registerAccount (account: EntropyAccountConfig, registerParams?: AccountRegisterParams): Promise<EntropyAccountConfig> {
this.logger.debug(
'about to register selectedAccount.address' +
account.address + 'keyring:' +
// @ts-expect-error Type export of ChildKey still not available from SDK
this.entropy.keyring.getLazyLoadAccountProxy('registration').pair.address,
[
`registering account: ${account.address}`,
// @ts-expect-error Type export of ChildKey still not available from SDK
`to keyring: ${this.entropy.keyring.getLazyLoadAccountProxy('registration').pair.address}`
].join(', '),
'REGISTER'
)
// Register params to be defined from user input (arguments/options or inquirer prompts)
try {
const verifyingKey = await this.register(registerParams)

account?.data?.registration?.verifyingKeys?.push(verifyingKey)
return account
} catch (error) {
this.logger.error('There was a problem registering', error)
throw error
}
}

/* PRIVATE */

private async pruneRegistration () {
try {
const tx = this.entropy.substrate.tx.registry.pruneRegistration()
await tx.signAndSend(this.entropy.keyring.accounts.registration.pair, ({ status }) => {
if (status.isFinalized) {
print('Successfully pruned registration');
}
})
} catch (error) {
console.error('Unable to prune registration due to:', error.message);
throw error
}
}
}
7 changes: 6 additions & 1 deletion src/account/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
export interface AccountCreateParams {
name: string
seed?: string
path?: string
}

export interface AccountImportParams {
seed: string
name: string
path?: string
}

Expand Down
9 changes: 6 additions & 3 deletions tests/register.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import test from 'tape'
import { registerAccount } from '../src/accounts/utils'
import { EntropyAccount } from '../src/account/main'
import { charlieStashSeed, setupTest } from './testing-utils'
import { readFileSync } from 'node:fs'

const networkType = 'two-nodes'
const endpoint = 'ws://127.0.0.1:9944'

test('Register - Default Program', async (t) => {
const { run, entropy } = await setupTest(t, { networkType, seed: charlieStashSeed })
const accountService = new EntropyAccount(entropy, endpoint)

const verifyingKey = await run('register account', registerAccount(entropy))
const verifyingKey = await run('register account', accountService.register())

const fullAccount = entropy.keyring.getAccount()

Expand All @@ -27,9 +29,10 @@ test('Register - Barebones Program', async t => {
entropy.programs.dev.deploy(dummyProgram)
)

const accountService = new EntropyAccount(entropy, endpoint)
const verifyingKey = await run(
'register - using custom params',
registerAccount(entropy, {
accountService.register({
programModAddress: entropy.keyring.accounts.registration.address,
programData: [{ program_pointer: pointer, program_config: '0x' }],
})
Expand Down

0 comments on commit 9cb1b81

Please sign in to comment.