Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions tests/integration/api.security.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,11 @@ test('Api security', { timeout: 90000 }, async (main) => {
await testGetEndpointSecurity(n, httpClient, api, invalidToken, readonlyUser, encoding)
})

await main.test('Api: get finance/ebitda', async (n) => {
const api = `${appNodeBaseUrl}${ENDPOINTS.FINANCE_EBITDA}?start=1700000000000&end=1700100000000`
await testGetEndpointSecurity(n, httpClient, api, invalidToken, readonlyUser, encoding)
})

await main.test('Api: get ext-data', async (n) => {
const api = `${appNodeBaseUrl}${ENDPOINTS.EXT_DATA}?type=miner`
await testGetEndpointSecurity(n, httpClient, api, invalidToken, readonlyUser, encoding)
Expand Down
187 changes: 187 additions & 0 deletions tests/unit/handlers/finance.handlers.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
'use strict'

const test = require('brittle')
const {
getEbitda,
processTailLogData,
processTransactionData,
processPriceData,
extractCurrentPrice,
processCostsData,
calculateEbitdaSummary
} = require('../../../workers/lib/server/handlers/finance.handlers')

test('getEbitda - happy path', async (t) => {
const mockCtx = {
conf: {
orks: [{ rpcPublicKey: 'key1' }]
},
net_r0: {
jRequest: async (key, method, payload) => {
if (method === 'tailLogCustomRangeAggr') {
return [{ data: { 1700006400000: { site_power_w: 5000, hashrate_mhs_5m_sum_aggr: 100000 } } }]
}
if (method === 'getWrkExtData') {
if (payload.query && payload.query.key === 'transactions') {
return { data: [{ transactions: [{ ts: 1700006400000, changed_balance: 50000000 }] }] }
}
if (payload.query && payload.query.key === 'prices') {
return { data: [{ prices: [{ ts: 1700006400000, price: 40000 }] }] }
}
if (payload.query && payload.query.key === 'current_price') {
return { data: { USD: 40000 } }
}
}
return {}
}
},
globalDataLib: {
getGlobalData: async () => []
}
}

const mockReq = {
query: { start: 1700000000000, end: 1700100000000, period: 'daily' }
}

const result = await getEbitda(mockCtx, mockReq, {})
t.ok(result.log, 'should return log array')
t.ok(result.summary, 'should return summary')
t.ok(Array.isArray(result.log), 'log should be array')
t.ok(result.summary.currentBtcPrice !== undefined, 'summary should have currentBtcPrice')
t.pass()
})

test('getEbitda - missing start throws', async (t) => {
const mockCtx = {
conf: { orks: [] },
net_r0: { jRequest: async () => ({}) },
globalDataLib: { getGlobalData: async () => [] }
}

try {
await getEbitda(mockCtx, { query: { end: 1700100000000 } }, {})
t.fail('should have thrown')
} catch (err) {
t.is(err.message, 'ERR_MISSING_START_END', 'should throw missing start/end error')
}
t.pass()
})

test('getEbitda - invalid range throws', async (t) => {
const mockCtx = {
conf: { orks: [] },
net_r0: { jRequest: async () => ({}) },
globalDataLib: { getGlobalData: async () => [] }
}

try {
await getEbitda(mockCtx, { query: { start: 1700100000000, end: 1700000000000 } }, {})
t.fail('should have thrown')
} catch (err) {
t.is(err.message, 'ERR_INVALID_DATE_RANGE', 'should throw invalid range error')
}
t.pass()
})

test('getEbitda - empty ork results', async (t) => {
const mockCtx = {
conf: { orks: [{ rpcPublicKey: 'key1' }] },
net_r0: { jRequest: async () => ({}) },
globalDataLib: { getGlobalData: async () => [] }
}

const result = await getEbitda(mockCtx, { query: { start: 1700000000000, end: 1700100000000 } }, {})
t.ok(result.log, 'should return log array')
t.is(result.log.length, 0, 'log should be empty')
t.pass()
})

test('processTailLogData - processes power and hashrate', (t) => {
const results = [
[{ data: { 1700006400000: { site_power_w: 5000, hashrate_mhs_5m_sum_aggr: 100000 } } }]
]

const daily = processTailLogData(results)
t.ok(typeof daily === 'object', 'should return object')
t.pass()
})

test('processTailLogData - handles error results', (t) => {
const results = [{ error: 'timeout' }]
const daily = processTailLogData(results)
t.is(Object.keys(daily).length, 0, 'should be empty for errors')
t.pass()
})

test('processTransactionData - processes valid data', (t) => {
const results = [
[{ transactions: [{ ts: 1700006400000, changed_balance: 100000000 }] }]
]
const daily = processTransactionData(results)
t.ok(typeof daily === 'object', 'should return object')
t.pass()
})

test('processPriceData - processes valid data', (t) => {
const results = [
[{ prices: [{ ts: 1700006400000, price: 40000 }] }]
]
const daily = processPriceData(results)
t.ok(typeof daily === 'object', 'should return object')
t.pass()
})

test('extractCurrentPrice - extracts numeric price', (t) => {
const results = [{ data: 42000 }]
t.is(extractCurrentPrice(results), 42000, 'should extract numeric price')
t.pass()
})

test('extractCurrentPrice - extracts object price', (t) => {
const results = [{ data: { USD: 42000 } }]
t.is(extractCurrentPrice(results), 42000, 'should extract USD')
t.pass()
})

test('processCostsData - processes app-node format (energyCost)', (t) => {
const costs = [
{ site: 'site1', year: 2023, month: 11, energyCost: 30000, operationalCost: 6000 }
]

const result = processCostsData(costs)
t.ok(result['2023-11'], 'should have month key')
t.is(result['2023-11'].energyCostPerDay, 1000, 'should have daily energy cost (30000/30)')
t.is(result['2023-11'].operationalCostPerDay, 200, 'should have daily operational cost (6000/30)')
t.pass()
})

test('processCostsData - handles non-array input', (t) => {
const result = processCostsData(null)
t.is(Object.keys(result).length, 0, 'should be empty')
t.pass()
})

test('calculateEbitdaSummary - calculates from log entries', (t) => {
const log = [
{ revenueBTC: 0.5, revenueUSD: 20000, totalCostsUSD: 5000, ebitdaSelling: 15000, ebitdaHodl: 15000 },
{ revenueBTC: 0.3, revenueUSD: 12000, totalCostsUSD: 3000, ebitdaSelling: 9000, ebitdaHodl: 9000 }
]

const summary = calculateEbitdaSummary(log, 40000)
t.is(summary.totalRevenueBTC, 0.8, 'should sum BTC revenue')
t.is(summary.totalRevenueUSD, 32000, 'should sum USD revenue')
t.is(summary.totalCostsUSD, 8000, 'should sum costs')
t.is(summary.totalEbitdaSelling, 24000, 'should sum selling EBITDA')
t.is(summary.currentBtcPrice, 40000, 'should include current BTC price')
t.ok(summary.avgBtcProductionCost !== null, 'should calculate avg production cost')
t.pass()
})

test('calculateEbitdaSummary - handles empty log', (t) => {
const summary = calculateEbitdaSummary([], 40000)
t.is(summary.totalRevenueBTC, 0, 'should be zero')
t.is(summary.avgBtcProductionCost, null, 'should be null')
t.is(summary.currentBtcPrice, 40000, 'should include current price')
t.pass()
})
57 changes: 57 additions & 0 deletions tests/unit/routes/finance.routes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict'

const test = require('brittle')
const { testModuleStructure, testHandlerFunctions, testOnRequestFunctions } = require('../helpers/routeTestHelpers')
const { createRoutesForTest } = require('../helpers/mockHelpers')

const ROUTES_PATH = '../../../workers/lib/server/routes/finance.routes.js'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

include in integration test as well


test('finance routes - module structure', (t) => {
testModuleStructure(t, ROUTES_PATH, 'finance')
t.pass()
})

test('finance routes - route definitions', (t) => {
const routes = createRoutesForTest(ROUTES_PATH)

const routeUrls = routes.map(route => route.url)
t.ok(routeUrls.includes('/auth/finance/ebitda'), 'should have ebitda route')

t.pass()
})

test('finance routes - HTTP methods', (t) => {
const routes = createRoutesForTest(ROUTES_PATH)

routes.forEach(route => {
t.is(route.method, 'GET', `route ${route.url} should be GET`)
})

t.pass()
})

test('finance routes - schema integration', (t) => {
const routes = createRoutesForTest(ROUTES_PATH)

const routesWithSchemas = routes.filter(route => route.schema)
routesWithSchemas.forEach(route => {
t.ok(route.schema, `route ${route.url} should have schema`)
if (route.schema.querystring) {
t.ok(typeof route.schema.querystring === 'object', `route ${route.url} querystring should be object`)
}
})

t.pass()
})

test('finance routes - handler functions', (t) => {
const routes = createRoutesForTest(ROUTES_PATH)
testHandlerFunctions(t, routes, 'finance')
t.pass()
})

test('finance routes - onRequest functions', (t) => {
const routes = createRoutesForTest(ROUTES_PATH)
testOnRequestFunctions(t, routes, 'finance')
t.pass()
})
56 changes: 54 additions & 2 deletions workers/lib/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,10 @@ const ENDPOINTS = {
THING_CONFIG: '/auth/thing-config',

// WebSocket endpoint
WEBSOCKET: '/ws'
WEBSOCKET: '/ws',

// Finance endpoints
FINANCE_EBITDA: '/auth/finance/ebitda'
}

const HTTP_METHODS = {
Expand Down Expand Up @@ -183,6 +186,48 @@ const STATUS_CODES = {
INTERNAL_SERVER_ERROR: 500
}

const RPC_METHODS = {
TAIL_LOG_RANGE_AGGR: 'tailLogCustomRangeAggr',
GET_WRK_EXT_DATA: 'getWrkExtData',
LIST_THINGS: 'listThings',
TAIL_LOG: 'tailLog'
}

const WORKER_TYPES = {
MINER: 'miner',
POWERMETER: 'powermeter',
MINERPOOL: 'minerpool',
MEMPOOL: 'mempool'
}

const AGGR_FIELDS = {
HASHRATE_SUM: 'hashrate_mhs_5m_sum_aggr',
SITE_POWER: 'site_power_w'
}

const PERIOD_TYPES = {
DAILY: 'daily',
WEEKLY: 'weekly',
MONTHLY: 'monthly',
YEARLY: 'yearly'
}

const MINERPOOL_EXT_DATA_KEYS = {
TRANSACTIONS: 'transactions',
STATS: 'stats'
}

const NON_METRIC_KEYS = [
'ts',
'site',
'year',
'monthName',
'month',
'period'
]

const BTC_SATS = 100000000

const RPC_TIMEOUT = 15000
const RPC_CONCURRENCY_LIMIT = 2

Expand All @@ -202,5 +247,12 @@ module.exports = {
STATUS_CODES,
RPC_TIMEOUT,
RPC_CONCURRENCY_LIMIT,
USER_SETTINGS_TYPE
USER_SETTINGS_TYPE,
RPC_METHODS,
WORKER_TYPES,
AGGR_FIELDS,
PERIOD_TYPES,
MINERPOOL_EXT_DATA_KEYS,
NON_METRIC_KEYS,
BTC_SATS
}
Loading