Skip to content

Commit

Permalink
pr review updates
Browse files Browse the repository at this point in the history
  • Loading branch information
rh0delta committed Aug 27, 2024
1 parent 0adff48 commit 820717e
Show file tree
Hide file tree
Showing 17 changed files with 179 additions and 186 deletions.
12 changes: 6 additions & 6 deletions src/balance/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@ import { cliWrite, endpointOption, passwordOption } from "src/common/utils-cli";
import { EntropyBalance } from "./main";

export async function entropyBalanceCommand (entropy: Entropy, rootCommand: Command) {
const programCommand = rootCommand.command('balance')
const balanceCommand = rootCommand.command('balance')
.description('Commands to retrieive account balances on the Entropy Network')
entropyAccountBalance(entropy, programCommand)
entropyAccountBalance(entropy, balanceCommand)
}

async function entropyAccountBalance (entropy: Entropy, programCommand: Command) {
programCommand
async function entropyAccountBalance (entropy: Entropy, balanceCommand: Command) {
balanceCommand
.argument('address', 'Account address whose balance you want to query')
.addOption(passwordOption())
.addOption(endpointOption())
.action(async (address, opts) => {
const balanceCommand = new EntropyBalance(entropy, opts.endpoint)
const balance = await balanceCommand.getBalance(address)
const BalanceService = new EntropyBalance(entropy, opts.endpoint)
const balance = await BalanceService.getAccountBalance(address)
cliWrite(balance)
process.exit(0)
})
Expand Down
4 changes: 2 additions & 2 deletions src/balance/interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { EntropyBalance } from "./main"

export async function entropyBalance (entropy, endpoint, storedConfig) {
try {
const entropyBalance = new EntropyBalance(entropy, endpoint)
const balanceString = await entropyBalance.getBalance(storedConfig.selectedAccount)
const BalanceService = new EntropyBalance(entropy, endpoint)
const balanceString = await BalanceService.getAccountBalance(storedConfig.selectedAccount)
print(`Address ${storedConfig.selectedAccount} has a balance of: ${balanceString}`)
} catch (error) {
console.error('There was an error retrieving balance', error)
Expand Down
25 changes: 23 additions & 2 deletions src/balance/main.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
import Entropy from "@entropyxyz/sdk"
import { EntropyBase } from "../common/entropy-base"
import * as BalanceUtils from "./utils"
import { BalanceInfo } from "./types"

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

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

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

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

return balanceInfo
}

public async getAccountBalance (address: string) {
const balance = await this.getBalance(address)

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

Expand Down
25 changes: 1 addition & 24 deletions src/balance/utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1 @@
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
}
export const hexToBigInt = (hexString: string) => BigInt(hexString)
11 changes: 0 additions & 11 deletions src/common/utils-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,6 @@ export function currentAccountAddressOption () {
.default(storedConfig.selectedAccount)
}


export function aliasOrAddressOption () {
return new Option(
'-a, --address <aliasOrAddress>',
'The alias or address of the verifying key to use for this command. Can be an alias or hex address.'
// TODO: describe default behaviour when "sessions" are introduced?
)
// QUESTION: as this is a function, this could be a viable way to set the VK?
// .default(process.env.ENTROPY_SESSION)
}

export async function loadEntropy (entropy: Entropy | undefined, address: string, endpoint: string, password?: string): Promise<Entropy> {
const storedConfig = config.getSync()
const selectedAccount = getSelectedAccount(storedConfig.accounts, address)
Expand Down
12 changes: 6 additions & 6 deletions src/signing/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { cliWrite, currentAccountAddressOption, endpointOption, passwordOption,
import { EntropySign } from './main'

export async function entropySignCommand (entropy: Entropy, rootCommand: Command) {
const programCommand = rootCommand.command('sign')
const signCommand = rootCommand.command('sign')
.description('Commands for working with signing with the Entropy Network')

entropySign(entropy, programCommand)
entropySign(entropy, signCommand)
}

function entropySign (entropy: Entropy, programCommand: Command) {
programCommand.command('sign')
function entropySign (entropy: Entropy, signCommand: Command) {
signCommand.command('sign')
.description('Sign a message using the Entropy network. Output is a signature (string)')
.argument('msg', 'Message or Path to Message you would like to sign')
.addOption(passwordOption('Password for the source account (if required)'))
Expand All @@ -31,14 +31,14 @@ function entropySign (entropy: Entropy, programCommand: Command) {
entropy.keyring.accounts.registration.address, opts.endpoint
)
}
const signingCommand = new EntropySign(entropy, opts.endpoint)
const SigningService = new EntropySign(entropy, opts.endpoint)
// TO-DO: Add ability for raw signing here, maybe? new raw option can be used for the conditional
/**
* if (opts.raw) {
* implement raw sign here
* }
*/
const signature = await signingCommand.signMessageWithAdapters({ msg, msgPath: msg })
const signature = await SigningService.signMessageWithAdapters({ msg, msgPath: msg })
cliWrite(signature)
process.exit(0)
})
Expand Down
5 changes: 3 additions & 2 deletions src/signing/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ export const SIGNING_CONTENT = {
message: 'Please choose how you would like to input your message to sign:',
choices: [
'Text Input',
'From a File',
// Input from file requires more design
// 'From a File',
],
},
textInput: {
Expand All @@ -21,7 +22,7 @@ export const SIGNING_CONTENT = {
name: "interactionChoice",
message: "What would you like to do?",
choices: [
"Raw Sign",
// "Raw Sign",
"Sign With Adapter",
"Exit to Main Menu",
],
Expand Down
35 changes: 17 additions & 18 deletions src/signing/interaction.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
import { print } from "src/common/utils"
import { getMsgFromUser, interactionChoiceQuestions, rawSignParamsQuestions } from "./utils"
import { getMsgFromUser, interactionChoiceQuestions } from "./utils"
import inquirer from "inquirer"
import { readFileSync } from "fs"
import Entropy from "@entropyxyz/sdk"
import { EntropySign } from "./main"

export async function entropySign (entropy: Entropy, endpoint: string) {
const Sign = new EntropySign(entropy, endpoint)
const SigningService = new EntropySign(entropy, endpoint)
const { interactionChoice } = await inquirer.prompt(interactionChoiceQuestions)
switch (interactionChoice) {
case 'Raw Sign': {
const { msg, msgPath } = await getMsgFromUser(inquirer)
const { hashingAlgorithm, auxiliaryDataFile } = await inquirer.prompt(rawSignParamsQuestions)
let hash = hashingAlgorithm
const auxiliaryData = JSON.parse(readFileSync(auxiliaryDataFile).toString())
if (JSON.parse(hashingAlgorithm)) {
hash = JSON.parse(hashingAlgorithm)
}
// case 'Raw Sign': {
// const { msg, msgPath } = await getMsgFromUser(inquirer)
// const { hashingAlgorithm, auxiliaryDataFile } = await inquirer.prompt(rawSignParamsQuestions)
// let hash = hashingAlgorithm
// const auxiliaryData = JSON.parse(readFileSync(auxiliaryDataFile).toString())
// if (JSON.parse(hashingAlgorithm)) {
// hash = JSON.parse(hashingAlgorithm)
// }

const { signature, verifyingKey } = await Sign.rawSignMessage({ msg, msgPath, hashingAlgorithm: hash, auxiliaryData })
print('msg to be signed:', msg)
print('verifying key:', verifyingKey)
print('signature:', signature)
return
}
// const { signature, verifyingKey } = await Sign.rawSignMessage({ msg, msgPath, hashingAlgorithm: hash, auxiliaryData })
// print('msg to be signed:', msg)
// print('verifying key:', verifyingKey)
// print('signature:', signature)
// return
// }
case 'Sign With Adapter': {
const { msg, msgPath } = await getMsgFromUser(inquirer)
const { signature, verifyingKey } = await Sign.signMessageWithAdapters({ msg, msgPath })
const { signature, verifyingKey } = await SigningService.signMessageWithAdapters({ msg, msgPath })
print('msg to be signed:', msg)
print('verifying key:', verifyingKey)
print('signature:', signature)
Expand Down
70 changes: 43 additions & 27 deletions src/signing/main.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,62 @@
import Entropy from "@entropyxyz/sdk"
import { u8aToHex } from '@polkadot/util'
import { EntropyBase } from "../common/entropy-base";
import { getMsgFromInputOrFile, rawSign, signWithAdapters } from "./utils";
import { SignResult } from "./types";
import { SignResult, SignWithAdapterInput } from "./types";
import { FLOW_CONTEXT } from "./constants";
import { stringToHex } from "./utils";

export class EntropySign extends EntropyBase {
constructor (entropy: Entropy, endpoint: string) {
super(entropy, endpoint, FLOW_CONTEXT)
}

public async rawSignMessage ({ msg, msgPath, auxiliaryData, hashingAlgorithm }): Promise<SignResult> {
const message = getMsgFromInputOrFile(msg, msgPath)
// async rawSign (entropy: Entropy, payload: RawSignPayload) {
// return entropy.sign(payload)
// }

try {
this.logger.log(`Msg to be signed: ${msg}`, 'SIGN_MSG')
this.logger.log( `Verifying Key used: ${this.entropy.signingManager.verifyingKey}`)
const signature = await rawSign(
this.entropy,
{
sigRequestHash: Buffer.from(message).toString('hex'),
hash: hashingAlgorithm,
auxiliaryData
}
)
const signatureHexString = u8aToHex(signature)
this.logger.log(`Signature: ${signatureHexString}`)

return { signature: signatureHexString, verifyingKey: this.entropy.signingManager.verifyingKey }
} catch (error) {
this.logger.error('Error signing message', error)
throw error
}
async signWithAdapters (input: SignWithAdapterInput): Promise<any> {
return this.entropy.signWithAdaptersInOrder({
msg: {
msg: stringToHex(input.msg)
},
// type
order: ['deviceKeyProxy', 'noop'],
signatureVerifyingKey: input.verifyingKey
// auxillaryData
})
}

public async signMessageWithAdapters ({ msg, msgPath }: { msg?: string, msgPath?: string }): Promise<SignResult> {
const message = getMsgFromInputOrFile(msg, msgPath)
// async rawSignMessage ({ msg, msgPath, auxiliaryData, hashingAlgorithm }): Promise<SignResult> {
// const message = getMsgFromInputOrFile(msg, msgPath)

// try {
// this.logger.log(`Msg to be signed: ${msg}`, 'SIGN_MSG')
// this.logger.log( `Verifying Key used: ${this.entropy.signingManager.verifyingKey}`)
// const signature = await rawSign(
// this.entropy,
// {
// sigRequestHash: stringAsHex(message),
// hash: hashingAlgorithm,
// auxiliaryData
// }
// )
// const signatureHexString = u8aToHex(signature)
// this.logger.log(`Signature: ${signatureHexString}`)

// return { signature: signatureHexString, verifyingKey: this.entropy.signingManager.verifyingKey }
// } catch (error) {
// this.logger.error('Error signing message', error)
// throw error
// }
// }

async signMessageWithAdapters ({ msg }: { msg?: string, msgPath?: string }): Promise<SignResult> {
// const message = getMsgFromInputOrFile(msg, msgPath)

try {
this.logger.log(`Msg to be signed: ${message}`, 'SIGN_MSG')
this.logger.log(`Msg to be signed: ${msg}`, 'SIGN_MSG')
this.logger.log( `Verifying Key used: ${this.entropy.signingManager.verifyingKey}`)
const signature = await signWithAdapters(this.entropy, { msg: message })
const signature = await this.signWithAdapters({ msg })
const signatureHexString = u8aToHex(signature)
this.logger.log(`Signature: ${signatureHexString}`)

Expand Down
34 changes: 10 additions & 24 deletions src/signing/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { readFileSync } from "fs"
import { SIGNING_CONTENT } from "./constants"
import { RawSignPayload, SignWithAdapterInput } from "./types"
import { isHex } from '@polkadot/util'

function stringToHex (str: string): string {
export function stringToHex (str: string): string {
if (isHex(str)) return str;
return Buffer.from(str).toString('hex')
}

Expand Down Expand Up @@ -59,12 +60,13 @@ export async function getMsgFromUser (inquirer) {
msg = userInput
break
}
case 'From a File': {
const { pathToFile } = await inquirer.prompt(filePathInputQuestions)
// TODO: relative/absolute path? encoding?
msgPath = pathToFile
break
}
// Msg input from a file requires more design
// case 'From a File': {
// const { pathToFile } = await inquirer.prompt(filePathInputQuestions)
// // TODO: relative/absolute path? encoding?
// msgPath = pathToFile
// break
// }
default: {
const error = new Error('SigningError: Unsupported User Input Action')
this.logger.error('Error signing with adapter', error)
Expand All @@ -88,20 +90,4 @@ export function getMsgFromInputOrFile (msg?: string, msgPath?: string) {
}

return result
}

export async function rawSign (entropy, payload: RawSignPayload) {
return entropy.sign(payload)
}

export async function signWithAdapters (entropy, input: SignWithAdapterInput) {
return entropy.signWithAdaptersInOrder({
msg: {
msg: stringToHex(input.msg)
},
// type
order: ['deviceKeyProxy', 'noop'],
signatureVerifyingKey: input.verifyingKey
// auxillaryData
})
}
7 changes: 3 additions & 4 deletions src/transfer/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ import { EntropyTransfer } from "./main"
export async function entropyTransferCommand (entropy: Entropy, rootCommand: Command) {
rootCommand.command('transfer')
.description('Transfer funds between two Entropy accounts.') // TODO: name the output
.argument('source', 'Account address funds will be drawn from')
.argument('destination', 'Account address funds will be sent to')
.argument('amount', 'Amount of funds to be moved')
.addOption(passwordOption('Password for the source account (if required)'))
.addOption(endpointOption())
.addOption(currentAccountAddressOption())
.action(async (_source, destination, amount, opts) => {
const transferCommand = new EntropyTransfer(entropy, opts.endpoint)
await transferCommand.sendTransfer(destination, amount)
.action(async (destination, amount, opts) => {
const TransferService = new EntropyTransfer(entropy, opts.endpoint)
await TransferService.sendTransfer(destination, amount)
// cliWrite(??) // TODO: write the output
process.exit(0)
})
Expand Down
Loading

0 comments on commit 820717e

Please sign in to comment.