Files
server/order.js
Tim Olson f0c0857d1c faucet
2023-11-14 02:13:22 -04:00

71 lines
2.8 KiB
JavaScript

import {orderFilled, orderStatuses, vaultOpenOrders} from "./cache.js"
import {applyFills} from "../web/src/blockchain/common.js"
import {dbpool} from "./db.js";
export function sendVaultOrders( socket, chainId, vault ) {
vaultOpenOrders.get(chainId, vault).then(async (orderIndexes)=>{
const statuses = {}
if( orderIndexes !== null ) {
for (const orderIndex of JSON.parse(orderIndexes)) {
// there is a race condition here since we need multiple queries to get the complete order status,
// so we check for nulls and exclude such an order, since it was deleted and no longer active.
const status = await orderStatus(chainId, vault, orderIndex)
if (status !== null)
statuses[orderIndex] = status
}
}
recentOrders(socket, chainId, vault).then(async (recents)=>{
const proms = []
for( let [orderIndex, status] of recents ) {
if( !(orderIndex in statuses) ) {
// only write the database version if there's no open order in the memcache
const orderKey = `${vault}|${orderIndex}`
proms.push(fillOrderStatus(chainId, orderKey, status))
statuses[orderIndex] = status
}
}
await Promise.all(proms)
const result = []
for( const index of Object.keys(statuses).sort())
result.push([index, statuses[index]])
socket.emit('os', chainId, vault, result)
})
})
}
export function unsubVaultOrders( socket, chainId, vault ) {
console.log('todo: unsubVaultOrders') // todo
}
export async function orderStatus( chainId, vault, orderIndex ) {
const orderKey = `${vault}|${orderIndex}`
let status = await orderStatuses.get(chainId, orderKey)
if( status !== null ) {
status = JSON.parse(status)
await fillOrderStatus(chainId, orderKey, status)
}
return status
}
async function fillOrderStatus( chainId, orderKey, status ) {
const fills = await orderFilled.get(chainId, orderKey)
if (fills !== null)
applyFills(status, JSON.parse(fills))
}
export async function recentOrders( socket, chainId, vault, limit=25 ) {
const db = await dbpool.connect()
const sql =
`select oi.order_index, sd.value from seriesdict sd, orderindex oi
where oi.chain=${chainId} and oi.vault='${vault}'
and sd.series='o' and sd.key=concat('${vault}','|',to_char(oi.order_index, 'FM00000'))
order by oi.order_index desc limit ${limit}`;
const query = await db.query(sql)
const result = []
for( const {order_index, value} of query.rows)
result.push([order_index,JSON.parse(value)])
return result
}