import _ from 'lodash' ; import { Destination } from '@statechannels/wallet-core' ; import { EngineResponse } from '../engine/engine-response' ; import { Store } from '../engine/store' ; import { LedgerRequest } from '../models/ledger-request' ; import { LedgerProtocol } from './ledger-protocol' ; interface LedgerManagerParams { store : Store ; } export class LedgerManager { static create ( params ) { return new this ( params . store ) ; } private constructor ( private store ) { } async crank ( ledgerChannelId , response ) { return this . store . transaction ( async ( tx ) => { const ledger = await this . store . getAndLockChannel ( ledgerChannelId , tx ) ; const requests = await this . store . getActiveLedgerRequests ( ledgerChannelId , tx ) ; if ( ! ledger . isRunning ) return [ ] ; if ( ! ledger . isLedger ) return [ ] ; if ( ledger . initialSupport . length === 0 && ledger . isSupported ) { await this . store . setInitialSupport ( ledger . channelId , ledger . support , tx ) ; } const statesToSign = new LedgerProtocol ( ) . crank ( ledger , requests ) ; for ( const state of statesToSign ) { const signedState = await this . store . signState ( ledger , state . signedState , tx ) ; response . queueState ( signedState , ledger . myIndex , ledger . channelId ) ; } await LedgerRequest . saveAll ( requests , tx ) ; response . queueChannel ( ledger ) ; return _ . uniq ( requests . filter ( r => ! r . isActive ) . map ( r => r . channelToBeFunded ) ) ; } ) ; } }