forked from smartcontractkit/synth-index-cc-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (75 loc) · 1.95 KB
/
index.js
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const rp = require('request-promise')
const snx = require('synthetix')
const Decimal = require('decimal.js')
const getPriceData = async (synth) => {
return rp({
url: 'https://min-api.cryptocompare.com/data/price',
qs: {
tsyms: 'USD',
fsym: synth.symbol
},
json: true
})
}
const calculateIndex = (indexes) => {
let value = new Decimal(0)
indexes.forEach(i => {
const price = i.priceData.USD;
if (price <= 0)
throw "invalid price";
value = value.plus(new Decimal(i.units).times(new Decimal(price)))
})
return value.toNumber()
}
const createRequest = async (input, callback) => {
const asset = input.data.asset || 'sCEX'
const datas = snx.getSynths({ network: 'mainnet' }).filter(({ index, inverted }) => index && !inverted)
const data = datas.find(d => d.name.toLowerCase() === asset.toLowerCase())
await Promise.all(data.index.map(async (synth) => {
synth.priceData = await getPriceData(synth)
})).catch(err => {
callback(500, {
jobRunID: input.id,
status: 'errored',
error: err,
statusCode: 500
})
})
try {
data.result = calculateIndex(data.index);
} catch (e) {
callback(500, {
jobRunID: input.id,
status: 'errored',
error: "failed getting price",
statusCode: 500
});
return
}
callback(200, {
jobRunID: input.id,
data: data,
result: data.result,
statusCode: 200
})
}
exports.gcpservice = (req, res) => {
createRequest(req.body, (statusCode, data) => {
res.status(statusCode).send(data)
})
}
exports.handler = (event, context, callback) => {
createRequest(event, (statusCode, data) => {
callback(null, data)
})
}
exports.handlerv2 = (event, context, callback) => {
createRequest(JSON.parse(event.body), (statusCode, data) => {
callback(null, {
statusCode: statusCode,
body: JSON.stringify(data),
isBase64Encoded: false
})
})
}
module.exports.createRequest = createRequest