Skip to content

Commit

Permalink
Merge branch 'naynay/file-restructure' of github.com:entropyxyz/cli i…
Browse files Browse the repository at this point in the history
…nto mixmix/deploy_cli
  • Loading branch information
mixmix committed Aug 22, 2024
2 parents 0a7be2d + 038051d commit 014062a
Show file tree
Hide file tree
Showing 22 changed files with 276 additions and 223 deletions.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,22 @@ Version header format: `[version] Name - year-month-day (entropy-core compatibil
- new: 'src/flows/user-program-management/view.ts' - service file for pure functions of viewing user programs
- new: 'src/flows/user-program-management/helpers/utils.ts' - utility helper file for user program management specific methods
- new: './src/flows/user-program-management/remove.ts' - service file for removing user program pure function
- new: './src/common/base-commands.ts' - base abstract class for new command classes
- new: './src/balance' - new file structure for our CLI/TUI flows
- new: './src/balance/command.ts' - main entry file for balance command for tui/cli
- new: './src/balance/utils.ts' - utilities and helper methods for all things balance
- new: './src/transfer' - new file structure for our CLI/TUI flows
- new: './src/transfer/command.ts' - main entry file for transfer command for tui/cli
- new: './src/transfer/utils.ts' - utilities and helper methods for all things transfer

### Changed

- folder name for user programs to match the kebab-case style for folder namespace
- updated SDK version to v0.2.3
- logger to handle nested contexts for better organization of logs
- merged user + dev program folders + tests
- removed flows/balance/*.ts directory with file restructure
- removed flows/entropyTransfer/*.ts directory with file restructure


### Broke
Expand Down
18 changes: 18 additions & 0 deletions src/balance/command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Entropy from "@entropyxyz/sdk"
import { BaseCommand } from "../common/base-command"
import * as BalanceUtils from "./utils"

const FLOW_CONTEXT = 'ENTROPY-BALANCE'
export class BalanceCommand extends BaseCommand {
constructor (entropy: Entropy, endpoint: string) {
super(entropy, endpoint, FLOW_CONTEXT)
}

public async getBalance (address: string) {
const balance = await BalanceUtils.getBalance(this.entropy, address)

this.logger.log(`Current balance of ${address}: ${balance}`, `${BalanceCommand.name}`)

return `${balance.toLocaleString('en-US')} BITS`
}
}
File renamed without changes.
24 changes: 24 additions & 0 deletions src/balance/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Entropy from "@entropyxyz/sdk";
import { BalanceInfo } from "./types";

const hexToBigInt = (hexString: string) => BigInt(hexString)

export async function getBalance (entropy: Entropy, address: string): Promise<number> {
const accountInfo = (await entropy.substrate.query.system.account(address)) as any
return parseInt(hexToBigInt(accountInfo.data.free).toString())
}

export async function getBalances (entropy: Entropy, addresses: string[]): Promise<BalanceInfo> {
const balanceInfo: BalanceInfo = {}
await Promise.all(addresses.map(async address => {
try {
const balance = await getBalance(entropy, address)

balanceInfo[address] = { balance }
} catch (error) {
balanceInfo[address] = { error: error.message }
}
}))

return balanceInfo
}
70 changes: 60 additions & 10 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,51 @@
import { Command, Option } from 'commander'
import launchTui from './tui'
import { EntropyTuiOptions } from './types'
import * as config from './config'

import { cliGetBalance } from './flows/balance/cli'
import { cliListAccounts } from './flows/manage-accounts/cli'
import { cliEntropyTransfer } from './flows/entropyTransfer/cli'
import { cliSign } from './flows/sign/cli'

import { cliWrite, passwordOption, endpointOption } from './cli/util'
import { entropyProgram } from './cli/commands'
import { cliWrite, passwordOption, endpointOption, currentAccountAddressOption } from './cli/util'
import { entropyProgram } from './cli/commands' // TODO move
import { getSelectedAccount, stringify } from './common/utils'
import Entropy from '@entropyxyz/sdk'
import { initializeEntropy } from './common/initializeEntropy'
import { BalanceCommand } from './balance/command'
import { TransferCommand } from './transfer/command'

const program = new Command()
// Array of restructured commands to make it easier to migrate them to the new "flow"
const RESTRUCTURED_COMMANDS = ['balance']

let entropy: Entropy

export async function loadEntropy (address: string, endpoint: string, password?: string): Promise<Entropy> {
const storedConfig = config.getSync()
const selectedAccount = getSelectedAccount(storedConfig.accounts, address)

if (!selectedAccount) throw Error(`No account with address ${address}`)

// check if data is encrypted + we have a password
if (typeof selectedAccount.data === 'string' && !password) {
throw Error('This account requires a password, add --password <password>')
}

entropy = await initializeEntropy({ keyMaterial: selectedAccount.data, endpoint, password })

if (!entropy?.keyring?.accounts?.registration?.pair) {
throw new Error("Signer keypair is undefined or not properly initialized.")
}

return entropy
}

/* no command */
program
.name('entropy')
.description('CLI interface for interacting with entropy.xyz. Running without commands starts an interactive ui')
.addOption(endpointOption())
.addOption(currentAccountAddressOption())
.addOption(
new Option(
'-d, --dev',
Expand All @@ -28,8 +57,20 @@ program
.env('DEV_MODE')
.hideHelp()
)
.hook('preAction', async (_thisCommand, actionCommand) => {
if (!entropy || (entropy.keyring.accounts.registration.address !== actionCommand.args[0] || entropy.keyring.accounts.registration.address !== actionCommand.opts().account)) {
// balance includes an address argument, use that address to instantiate entropy
// can keep the conditional to check for length of args, and use the first index since it is our pattern to have the address as the first argument
if (RESTRUCTURED_COMMANDS.includes(actionCommand.name()) && actionCommand.args.length) {
await loadEntropy(actionCommand.args[0], actionCommand.opts().endpoint, actionCommand.opts().password)
} else {
// if address is not an argument, use the address from the option
await loadEntropy(actionCommand.opts().account, actionCommand.opts().endpoint, actionCommand.opts().password)
}
}
})
.action((options: EntropyTuiOptions) => {
launchTui(options)
launchTui(entropy, options)
})

/* Install commands */
Expand Down Expand Up @@ -58,8 +99,9 @@ program.command('balance')
.addOption(passwordOption())
.addOption(endpointOption())
.action(async (address, opts) => {
const balance = await cliGetBalance({ address, ...opts })
cliWrite(balance)
const balanceCommand = new BalanceCommand(entropy, opts.endpoint)
const balance = await balanceCommand.getBalance(address)
writeOut(balance)
process.exit(0)
})

Expand All @@ -71,8 +113,10 @@ program.command('transfer')
.argument('amount', 'Amount of funds to be moved')
.addOption(passwordOption('Password for the source account (if required)'))
.addOption(endpointOption())
.action(async (source, destination, amount, opts) => {
await cliEntropyTransfer({ source, destination, amount, ...opts })
.addOption(currentAccountAddressOption())
.action(async (_source, destination, amount, opts) => {
const transferCommand = new TransferCommand(entropy, opts.endpoint)
await transferCommand.sendTransfer(destination, amount)
// writeOut(??) // TODO: write the output
process.exit(0)
})
Expand All @@ -84,10 +128,16 @@ program.command('sign')
.argument('message', 'Message you would like to sign')
.addOption(passwordOption('Password for the source account (if required)'))
.addOption(endpointOption())
.addOption(currentAccountAddressOption())
.action(async (address, message, opts) => {
const signature = await cliSign({ address, message, ...opts })
cliWrite(signature)
process.exit(0)
})

program.parse()
program.parseAsync().then(() => {})

function writeOut (result) {
const prettyResult = stringify(result)
process.stdout.write(prettyResult)
}
20 changes: 20 additions & 0 deletions src/cli/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@ export function passwordOption (description?: string) {
)
}

export function currentAccountAddressOption () {
const storedConfig = config.getSync()
return new Option(
'-a, --account <accountAddress>',
'Sets the current account for the session or defaults to the account stored in the config'
)
.env('ACCOUNT_ADDRESS')
.argParser(async (address) => {
if (address === storedConfig.selectedAccount) return address
// Updated selected account in config with new address from this option
const newConfigUpdates = { selectedAccount: address }
await config.set({ ...storedConfig, ...newConfigUpdates })

return address
})
.hideHelp()
.default(storedConfig.selectedAccount)
}


export function aliasOrAddressOption () {
return new Option(
'-a, --address <aliasOrAddress>',
Expand Down
12 changes: 12 additions & 0 deletions src/common/base-command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import Entropy from "@entropyxyz/sdk";
import { EntropyLogger } from "./logger";

export abstract class BaseCommand {
protected logger: EntropyLogger
protected entropy: Entropy

constructor (entropy: Entropy, endpoint: string, flowContext: string) {
this.logger = new EntropyLogger(flowContext, endpoint)
this.entropy = entropy
}
}
2 changes: 1 addition & 1 deletion src/common/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export class EntropyLogger {
this.winstonLogger.log({
level,
message: maskPayload(message),
context: context || this.context,
context: context ? `${this.context}:${context}` : this.context,
endpoint: this.endpoint,
description,
stack,
Expand Down
4 changes: 2 additions & 2 deletions src/common/progress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export function setupProgress (label: string): { start: () => void; stop: () =>
})

const start = () => {
// 160 was found through trial and error, don't believe there is a formula to
// 150 was found through trial and error, don't believe there is a formula to
// determine the exact time it takes for the transaction to be processed and finalized
// TO-DO: Change progress bar to loading animation?
b1.start(160, 0, {
b1.start(150, 0, {
speed: "N/A"
})
// update values
Expand Down
36 changes: 0 additions & 36 deletions src/flows/balance/balance.ts

This file was deleted.

24 changes: 0 additions & 24 deletions src/flows/balance/cli.ts

This file was deleted.

19 changes: 0 additions & 19 deletions src/flows/balance/index.ts

This file was deleted.

32 changes: 0 additions & 32 deletions src/flows/entropyTransfer/cli.ts

This file was deleted.

Loading

0 comments on commit 014062a

Please sign in to comment.