This repository has been archived by the owner on Sep 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
127 lines (102 loc) · 2.79 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* eslint-disable no-magic-numbers */
const { http } = require('node-service-library');
const { LinkedList } = require('crypto-linked-list');
const { generateUUID } = require('cryptography-utilities');
const { ZERO } = require('./numbers');
const {
RECORD,
NON_FUNGIBLE_RECORD
} = require('./strings');
const transactions = new LinkedList();
require('./api/transaction/load-transactions')(transactions);
const transactionApi = require('./api/transaction')(transactions);
const priceApi = require('./api/price');
const fsApi = require('./api/fs');
const onTransaction = require('./events/create-on-transaction')({
transactionApi,
priceApi
});
const { broadcast } = require('./enforcements');
const getPrice24hAgo = () => {
const transaction = transactionApi
.getTransactions()
.filter(({ timestamp }) => (
new Date().setHours(0, 0, 0, 0) ===
new Date(timestamp).setHours(0, 0, 0, 0)
))
.sort((a, b) => (
a.timestamp < b.timestamp
? 1
: a.timestamp > b.timestamp
? 0.01
: 0
))
.pop();
return transaction && transaction.price;
};
module.exports = http({
GET: {
price: async () => {
const price = await priceApi.getPrice();
const price24hAgo = await getPrice24hAgo();
return {
price,
price24hAgo: price24hAgo || price
};
},
transactions: transactionApi.getTransactions
},
POST: {
search: fsApi.search,
store: fsApi.store,
transaction: async ({
senderAddress,
recipientAddress,
usdValue,
drvValue,
contract = RECORD,
peers = [],
isTest = false
}) => {
const drv = contract === NON_FUNGIBLE_RECORD
? drvValue
: Math.max(ZERO, drvValue);
const hash = (
transactionApi.getTransactions().pop()?.next ||
generateUUID()
);
const next = generateUUID();
const transaction = {
hash,
next,
senderAddress,
recipientAddress,
contract,
usdValue,
drvValue: drv
};
if (isTest) {
return {
success: true
};
}
const transactions = transactionApi.getTransactions();
if (transactions.find(existingTransaction => existingTransaction.hash === transaction.hash)) {
console.log('<DRV> :: Transaction already exists. Skipping lifecycle, validation, & enforcements.');
return { success: false };
}
transaction.status = await broadcast(transaction, peers);
const result = await onTransaction(transaction);
if (!result?.success) {
return { success: false };
}
const price24hAgo = await getPrice24hAgo() || result.price;
return {
...result,
price24hAgo
};
}
},
PUT: {},
DELETE: {}
});