All files / src/modules/debug settlements.ts

100% Statements 18/18
100% Branches 0/0
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 6033x   33x 33x 33x     33x               33x 1x         1x   1x                       33x 1x         1x   1x 1x 1x 670x     1x     670x              
import { Types } from 'cafe-utility'
import type { AllSettlements, BeeRequestOptions, Settlements } from '../../types'
import { http } from '../../utils/http'
import { BZZ } from '../../utils/tokens'
import { asNumberString } from '../../utils/type'
import { PeerAddress } from '../../utils/typed-bytes'
 
const settlementsEndpoint = 'settlements'
 
/**
 * Get amount of sent and received from settlements with a peer
 *
 * @param requestOptions Options for making requests
 * @param peer  Swarm address of peer
 */
export async function getSettlements(requestOptions: BeeRequestOptions, peer: PeerAddress): Promise<Settlements> {
  const response = await http<unknown>(requestOptions, {
    url: `${settlementsEndpoint}/${peer}`,
    responseType: 'json',
  })
 
  const body = Types.asObject(response.data, { name: 'response.data' })
 
  return {
    peer: Types.asString(body.peer, { name: 'peer' }),
    sent: BZZ.fromPLUR(asNumberString(body.sent, { name: 'sent' })),
    received: BZZ.fromPLUR(asNumberString(body.received, { name: 'received' })),
  }
}
 
/**
 * Get settlements with all known peers and total amount sent or received
 *
 * @param requestOptions Options for making requests
 */
export async function getAllSettlements(requestOptions: BeeRequestOptions): Promise<AllSettlements> {
  const response = await http<unknown>(requestOptions, {
    url: settlementsEndpoint,
    responseType: 'json',
  })
 
  const body = Types.asObject(response.data, { name: 'response.data' })
 
  const totalSent = BZZ.fromPLUR(asNumberString(body.totalSent, { name: 'totalSent' }))
  const totalReceived = BZZ.fromPLUR(asNumberString(body.totalReceived, { name: 'totalReceived' }))
  const settlements = Types.asArray(body.settlements, { name: 'settlements' }).map(x =>
    Types.asObject(x, { name: 'settlement' }),
  )
 
  return {
    totalSent,
    totalReceived,
    settlements: settlements.map(x => ({
      peer: Types.asString(x.peer, { name: 'peer' }),
      sent: BZZ.fromPLUR(asNumberString(x.sent, { name: 'sent' })),
      received: BZZ.fromPLUR(asNumberString(x.received, { name: 'received' })),
    })),
  }
}