@leverj/adapter
Version:
common utilities used in leverj exchange
55 lines (53 loc) • 2.65 kB
JavaScript
const {toChecksumAddress} = require('web3-utils')
const {Quantity} = require('@leverj/gluon-plasma.common.exchange/src/domain/quantity')
const {Order, SignedOrder, Side, OrderType} = require('@leverj/gluon-plasma.app.derivatives.exchange/src/domain/v/0/order')
const {address} = require('@leverj/gluon-plasma.common/src/utils/ethereum')
const mathUtil = require('./MathUtil')
const {affirm} = require('@leverj/affirm')
module.exports = function () {
const auth = {}
const SIDES = {buy: "1", sell: "2"}
const ORDER_TYPES = {LMT: 1, MKT: 2, SLMT: 3, SMKT: 4}
auth.sign = function (order, instrument, secret) {
const contractOrder = auth.getContractOrder(order, instrument)
const signed = contractOrder.signedByWithPersonalMessage(secret)
return signed.signature
}
auth.validate = function (order, instrument, apiKey) {
const personalMessageSigner = auth.getPersonalMessageSigner(order, instrument)
if (personalMessageSigner === apiKey) return
const signer = auth.getSigner(order, instrument)
affirm(signer === apiKey, 'M_INV_ORDSIG', 422)
}
auth.getSigner = function (order, instrument) {
return getSignedOrder(order, auth, instrument).signer
}
auth.getPersonalMessageSigner = function (order, instrument) {
return getSignedOrder(order, auth, instrument).personalMessageSigner
}
auth.getContractOrder = function (order, instrument) {
affirm(ORDER_TYPES[order.orderType] > 0, 'Invalid order orderType')
affirm(SIDES[order.side] > 0, 'Invalid order side')
affirm(instrument, 'instrument missing')
affirm(instrument.id === order.instrument, 'instrument must be same as order instrument')
affirm(!isNaN(order.timestamp), 'Invalid timestamp')
const id = order.uuid
const timestamp = order.timestamp
const orderType = OrderType[order.orderType]
const side = Side[order.side]
const quantity = Quantity.from(order.quantity)
const price = mathUtil.toBN(order.price, instrument.quote.decimals).toFixed()
const marginPerFraction = order.marginPerFraction
const quote = order.quote
const account = toChecksumAddress(order.accountId)
const originator = toChecksumAddress(order.originator)
return new Order(id, timestamp, orderType, side, instrument.id, quantity, price, marginPerFraction, quote, originator, account)
}
auth.toBN = mathUtil.toBN
function getSignedOrder(order, auth, instrument) {
const serverTimestamp = order.entryTime ? order.entryTime : 0
const contractOrder = auth.getContractOrder(order, instrument)
return new SignedOrder(contractOrder, order.signature, serverTimestamp, 0)
}
return auth
}()