import { TransportIniter } from "./options" ; const CosmosApp = require ( "ledger-cosmos-js" ) . default ; import TransportWebHID from "@ledgerhq/hw-transport-webhid" ; import TransportWebUSB from "@ledgerhq/hw-transport-webusb" ; import { signatureImport } from "secp256k1" ; export enum LedgerInitErrorOn { Transport , App , Unknown } export const LedgerWebUSBIniter = async ( ) => { return await TransportWebUSB . create ( ) ; } ; export const LedgerWebHIDIniter = async ( ) => { return await TransportWebHID . create ( ) ; } ; export class LedgerInitError extends Error { constructor ( public readonly errorOn , message ? ) { super ( message ) ; Object . setPrototypeOf ( this , LedgerInitError . prototype ) ; } } export class Ledger { constructor ( private readonly cosmosApp ) { } static async init ( transportIniter , initArgs = [ ] ) { const transport = await transportIniter ( ... initArgs ) ; try { const cosmosApp = new CosmosApp ( transport ) ; const ledger = new Ledger ( cosmosApp ) ; const versionResponse = await ledger . getVersion ( ) ; if ( versionResponse . deviceLocked ) { throw new Error ( "Device is on screen saver" ) ; } return ledger ; } catch ( e ) { if ( transport ) { await transport . close ( ) ; } if ( e . message === "Device is on screen saver" ) { throw new LedgerInitError ( LedgerInitErrorOn . Transport , e . message ) ; } throw new LedgerInitError ( LedgerInitErrorOn . App , e . message ) ; } } async getVersion ( ) { if ( ! this . cosmosApp ) { throw new Error ( "Comsos App not initialized" ) ; } const result = await this . cosmosApp . getVersion ( ) ; if ( result . error_message !== "No errors" ) { throw new Error ( result . error_message ) ; } return { deviceLocked : result . device_locked , major : result . major , minor : result . minor , patch : result . patch , targetId : result . target_id , testMode : result . test_mode , } ; } async getPublicKey ( path ) { if ( ! this . cosmosApp ) { throw new Error ( "Comsos App not initialized" ) ; } const result = await this . cosmosApp . publicKey ( path ) ; if ( result . error_message !== "No errors" ) { throw new Error ( result . error_message ) ; } return result . compressed_pk ; } async sign ( path , message ) { if ( ! this . cosmosApp ) { throw new Error ( "Comsos App not initialized" ) ; } const result = await this . cosmosApp . sign ( path , message ) ; if ( result . error_message !== "No errors" ) { throw new Error ( result . error_message ) ; } return signatureImport ( result . signature ) ; } async close ( ) { return await this . cosmosApp . transport . close ( ) ; } static async isWebHIDSupported ( ) { return await TransportWebHID . isSupported ( ) ; } }