Skip to content

Commit

Permalink
cli changes promoted to marinade ts cli
Browse files Browse the repository at this point in the history
  • Loading branch information
ochaloup committed Jan 5, 2024
1 parent 682f866 commit 509967e
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 69 deletions.
13 changes: 6 additions & 7 deletions packages/lib/cli-common/src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { CliCommandError } from './error'
import { Wallet } from '@marinade.finance/web3js-common'
import { Logger } from 'pino'
import { getContext } from './context'
import { configureLogger } from './pinoLogging'
import { PINO_CONFIGURED_LOGGER } from './pinoLogging'
import { KeypairWallet } from './wallet'

export async function parsePubkey(pubkeyOrPath: string): Promise<PublicKey> {
Expand All @@ -31,7 +31,7 @@ export async function parsePubkey(pubkeyOrPath: string): Promise<PublicKey> {
}
}

export async function parsePubkeyOrKeypair(
export async function parseKeypairOrPubkey(
pubkeyOrPath: string
): Promise<PublicKey | Keypair> {
try {
Expand Down Expand Up @@ -78,7 +78,7 @@ const PARSE_SIGNER_LOCK = 'parseSignerLock'

export async function parseWallet(
pathOrLedger: string,
logger: Logger
logger: Logger | undefined
): Promise<Wallet> {
let wallet
try {
Expand All @@ -104,13 +104,12 @@ export async function parseWallet(
export async function parseWalletOrPubkey(
pubkeyOrPathOrLedger: string
): Promise<Wallet | PublicKey> {
let logger: Logger
let logger: Logger | undefined = undefined
try {
logger = getContext().logger
} catch (e) {
// context logger is not set
// let's use not fully configured (but still logger) the logger from index.ts
logger = configureLogger()
// context logger is not set, use default
logger = PINO_CONFIGURED_LOGGER
}
try {
return await parseWallet(pubkeyOrPathOrLedger, logger)
Expand Down
3 changes: 3 additions & 0 deletions packages/lib/cli-common/src/pinoLogging.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import pino, { Logger } from 'pino'

export let PINO_CONFIGURED_LOGGER: Logger | undefined

export function configureLogger(level = 'info'): Logger {
const pinoAdditionalOptions = process.env.NODE_ENV?.startsWith('prod')
? {
Expand All @@ -20,5 +22,6 @@ export function configureLogger(level = 'info'): Logger {
},
pino.destination()
)
PINO_CONFIGURED_LOGGER = logger
return logger
}
71 changes: 31 additions & 40 deletions packages/lib/ledger-utils/src/ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,14 @@ export class LedgerWallet implements Wallet {
parsedDerivedPath,
logger
)
return new LedgerWallet(api, derivedPath, pubkey)
return new LedgerWallet(api, derivedPath, pubkey, logger)
}

private constructor(
public readonly solanaApi: Solana,
public readonly derivedPath: string,
public readonly publicKey: PublicKey
public readonly publicKey: PublicKey,
public readonly logger: LoggerPlaceholder | undefined = undefined
) {}

public async signTransaction<T extends Transaction | VersionedTransaction>(
Expand Down Expand Up @@ -118,9 +119,9 @@ export class LedgerWallet implements Wallet {
let transport: TransportNodeHid | undefined = undefined
if (pubkey === undefined) {
// we don't know where to search for the derived path and thus taking first device
// when pubkey is defined we search all available devices to match the derived path with the pubkey
const firstDevicePath = ledgerDevices[0].path
transport = (await openTransports(firstDevicePath))[0]
// we will search for the provided derived path at this first device when signing message
// when pubkey is defined we search all available devices to find a match of pubkey and derived path
transport = (await openTransports(ledgerDevices[0]))[0]
} else {
const openedTransports = await openTransports(...ledgerDevices)
// if derived path is provided let's check if matches the pubkey
Expand All @@ -136,41 +137,26 @@ export class LedgerWallet implements Wallet {
logInfo(
logger,
`Public key ${pubkey.toBase58()} has not been found at the default or provided ` +
`derivation path ${derivedPath}. Going to search, will take a while...`
`derivation path ${derivedPath}. Going to search, it will take a while...`
)
const { depth, wide } = getHeuristicDepthAndWide(
derivedPath,
heuristicDepth,
heuristicWide
)
const heuristicsCombinations: number[][] = generateAllCombinations(
const searchedData = await searchDerivedPathFromPubkey(
pubkey,
logger,
depth,
wide
)
for (const openedTransport of openedTransports) {
const solanaApi = new Solana(openedTransport)
for (const combination of heuristicsCombinations) {
const strCombination = combination.map(v => v.toString())
strCombination.unshift(SOLANA_LEDGER_BIP44_BASE_PATH)
const heuristicDerivedPath = strCombination.join('/')
logDebug(logger, `search loop: ${heuristicDerivedPath}`)
const ledgerPubkey = await getPublicKey(
solanaApi,
heuristicDerivedPath
)
if (ledgerPubkey.equals(pubkey)) {
transport = openedTransport
derivedPath = heuristicDerivedPath
logInfo(
logger,
`Using derived path ${derivedPath}, pubkey ${pubkey.toBase58()}`
)
break // we found the transport
}
}
if (transport !== undefined) {
break // break out to the outer loop; we found the transport
}
if (searchedData !== null) {
transport = searchedData.transport
derivedPath = searchedData.derivedPath
logInfo(
logger,
`For public key ${pubkey.toBase58()} has been found derived path ${derivedPath}`
)
}
}
}
Expand Down Expand Up @@ -198,10 +184,11 @@ export class LedgerWallet implements Wallet {
* ```
*/
private async signMessage(message: MessageV0 | Message): Promise<Buffer> {
console.log(
'signing message',
this.derivedPath,
(await getPublicKey(this.solanaApi, this.derivedPath)).toBase58()
logDebug(
this.logger,
'signing message with pubkey ' +
(await getPublicKey(this.solanaApi, this.derivedPath)).toBase58() +
` of derived path ${this.derivedPath}`
)
const { signature } = await this.solanaApi.signTransaction(
this.derivedPath,
Expand Down Expand Up @@ -302,7 +289,11 @@ export async function searchDerivedPathFromPubkey(
logger: LoggerPlaceholder | undefined = undefined,
heuristicDepth: number | undefined = 10,
heuristicWide: number | undefined = 3
): Promise<{ derivedPath: string; solanaApi: Solana } | null> {
): Promise<{
derivedPath: string
solanaApi: Solana
transport: TransportNodeHid
} | null> {
const ledgerDevices = getDevices()
if (ledgerDevices.length === 0) {
throw new Error('No ledger device found')
Expand All @@ -314,8 +305,8 @@ export async function searchDerivedPathFromPubkey(
heuristicWide
)

for (const openedTransport of openedTransports) {
const solanaApi = new Solana(openedTransport)
for (const transport of openedTransports) {
const solanaApi = new Solana(transport)
for (const combination of heuristicsCombinations) {
const strCombination = combination.map(v => v.toString())
strCombination.unshift(SOLANA_LEDGER_BIP44_BASE_PATH)
Expand All @@ -326,9 +317,9 @@ export async function searchDerivedPathFromPubkey(
if (ledgerPubkey.equals(pubkey)) {
logDebug(
logger,
`Using derived path ${heuristicDerivedPath}, pubkey ${pubkey.toBase58()}`
`Found path ${heuristicDerivedPath}, pubkey ${pubkey.toBase58()}`
)
return { derivedPath: heuristicDerivedPath, solanaApi }
return { derivedPath: heuristicDerivedPath, solanaApi, transport }
}
}
}
Expand Down
9 changes: 5 additions & 4 deletions packages/lib/ts-common/src/signals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ function runHooks(signal: string): void {
}
})
}
if (EXIT_SIGNALS.includes(signal)) {
// eslint-disable-next-line no-process-exit
process.exit(exitSignalsToCode.get(signal) ?? 0)
}
// TODO: not sure if needed to really do the process.exit, it seems it's ok to just return
// if (EXIT_SIGNALS.includes(signal)) {
// // eslint-disable-next-line no-process-exit
// process.exit(exitSignalsToCode.get(signal) ?? 0)
// }
}

export function scheduleOn(hook: () => void, ...signals: string[]): void {
Expand Down
15 changes: 0 additions & 15 deletions packages/marinade-ts-cli/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import { Connection } from '@solana/web3.js'
import { Wallet as AnchorWalletInterface } from '@coral-xyz/anchor/dist/cjs/provider'
import { Wallet } from '@coral-xyz/anchor'
import { MarinadeConfig } from '@marinade.finance/marinade-ts-sdk'
import {
Context,
parseClusterUrl,
parseCommitment,
parseKeypair,
setContext,
getContext,
} from '@marinade.finance/cli-common'
import { parseLedgerWallet } from '@marinade.finance/ledger-utils'
import { Logger } from 'pino'

export class MarinadeCLIContext extends Context {
Expand Down Expand Up @@ -82,15 +79,3 @@ export function setMarinadeCLIContext({
export function getMarinadeCliContext(): MarinadeCLIContext {
return getContext() as MarinadeCLIContext
}

export async function parseSigner(
pathOrUrl: string,
logger: Logger
): Promise<AnchorWalletInterface> {
const wallet = await parseLedgerWallet(pathOrUrl, logger)
if (wallet) {
return wallet
}
const keypair = await parseKeypair(pathOrUrl)
return new Wallet(keypair)
}
6 changes: 3 additions & 3 deletions packages/marinade-ts-cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

/* eslint-disable no-process-exit */
import { Command } from 'commander'
import { parseSigner, setMarinadeCLIContext } from './context'
import { setMarinadeCLIContext } from './context'
import { installCommands } from './commands'
import { Logger } from 'pino'
import { configureLogger } from '@marinade.finance/cli-common'
import { configureLogger, parseWallet } from '@marinade.finance/cli-common'

const DEFAULT_KEYPAIR_PATH = '~/.config/solana/id.json'
const logger: Logger = configureLogger()
Expand Down Expand Up @@ -46,7 +46,7 @@ program
}

let walletSigner = (await command.opts().keypair) ?? DEFAULT_KEYPAIR_PATH
walletSigner = await parseSigner(walletSigner, logger)
walletSigner = await parseWallet(walletSigner, logger)

setMarinadeCLIContext({
url: command.opts().url as string,
Expand Down

0 comments on commit 509967e

Please sign in to comment.