-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
204 lines (174 loc) · 6.54 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import express from 'express';
import redis from 'redis';
import { Web3 } from 'web3';
import { tokenPriceAbi } from './tokenPriceAbi.js'
import { tokenSaleAbi } from './tokenSaleAbi.js'
import { promisify } from 'util';
import axios from 'axios'
import cors from 'cors'
import 'dotenv/config'
const app = express();
const port = 3000;
app.use(cors())
// Create a Redis client
const redisClient = redis.createClient({ url:'redis://'+process.env.REDIS_URL });
redisClient.connect()
redisClient.on('connect', function() {
console.log('Redis client connected');
});
redisClient.on('error', function (err) {
console.error('Something went wrong with Redis: ' + err);
});
const web3 = new Web3(process.env.RPC_URL);
// https://bsc-testnet.g.allthatnode.com/full/evm/e545c6a0498443ba942cd4c99408bf1e
const tokenPriceContractAddress = process.env.TOKEN_PRICE_CONTRACT_ADDRESS;
const tokenSaleContractAddress = process.env.TOKEN_SALE_CONTRACT_ADDRESS;
const account = process.env.ACCOUNT;
// The private key of the account (never share this or hardcode it in production)
const privateKey = process.env.PRIVATE_KEY;
// NOTE: this is not needed anymore, since this was insecure.
// now the exchanges updating price directly on smart contract
const fetchData = async () => {
try {
const response = await axios.get(process.env.PRICE_ENDPOINT);
const data = response.data['data'];
for(let item of data){
if(item.coin === "deda"){
const value = await redisClient.get('deda-price');
if(value != item.sell || value === null){
console.log("Updating price")
await redisClient.set('deda-price', item.sell) //, {EX: 30});
await updateBlockchainPrice(Number(item.sell))
}else{
console.log("Price is not changed")
}
}
}
} catch (error) {
console.error('Error calling the API:', error);
throw error;
}
};
// NOTE: this is not needed anymore, since this was insecure.
// now the exchanges updating price directly on smart contract
const updateBlockchainPrice = async (price) => {
try{
console.log("data type", typeof price, price, price * (10**18))
const contract = new web3.eth.Contract(tokenPriceAbi, tokenPriceContractAddress);
const method = contract.methods.setTokenPrice(price * (10**18));
const gas = await method.estimateGas({ from: account });
const gasPrice = await web3.eth.getGasPrice()
const data = method.encodeABI();
const tx = {
from: account,
to: tokenPriceContractAddress,
gas,
gasPrice,
data
};
const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey);
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('receipt', (receipt) => {
console.log('Transaction successful with receipt: ', receipt);
})
.on('error', (error) => {
console.error('Transaction failed with error: ', error);
});
} catch (error){
console.error('Error on updating price', error);
}
};
const stringifyBigIntsInArray = (array) => {
return array.map(item => {
const newItem = {};
for (const key in item) {
if (typeof item[key] === 'bigint') {
newItem[key] = item[key].toString();
} else {
newItem[key] = item[key];
}
}
return newItem;
});
};
const fetchUserPurchases = async (address) => {
try{
const contract = new web3.eth.Contract(tokenSaleAbi, tokenSaleContractAddress);
const result = await contract.methods.getPurchases(address).call()
const stringifiedResult = stringifyBigIntsInArray(result);
await redisClient.set("purchases-"+address, JSON.stringify(stringifiedResult), {EX: 30});
console.log('Purchases for ', address, 'stored in Redis');
return stringifiedResult
}catch(error){
console.error('Error fetching or storing purchases:', error);
}
}
// Fetch data every x (20 sec)
setInterval(async () => {
await fetchData();
// await fetchUserPurchases(account)
}, 20000);
app.get('/get-price', async (req, res) => {
try {
console.log('Received request for /get-price');
const reply = await redisClient.get('deda-price');
if (reply) {
console.log('Data retrieved from Redis:', reply);
res.json({ "price": Number(reply) });
} else {
console.log('Data not available yet');
res.status(503).send('Data not available yet. Please try again later.');
}
} catch (err) {
console.error('Error retrieving data from Redis:', err);
res.status(500).send('Error retrieving data from Redis');
}
});
app.get('/get-user-purchases/:address', async (req, res) => {
try {
console.log('Received request for/get-user-purchases', req.params.address);
if(req.params.address === "undefined"){
return res.status(200).send('No address!');
}
const userPurchases = await fetchUserPurchases(req.params.address)
res.json(userPurchases)
// right now, we need to get purchases directly from blockchain
//
//
// const reply = await redisClient.get('deda-price');
// if (reply) {
// console.log('Data retrieved from Redis:', reply);
// res.json({ "price": Number(reply) });
// res.json(userPurchases)
// } else {
// console.log('Data not available yet');
// res.status(503).send('Data not available yet. Please try again later.');
// }
// } catch (err) {
// console.error('Error retrieving data from Redis:', err);
// res.status(500).send('Error retrieving data from Redis');
// }
}catch(err){
console.error("Err", err)
}
});
// NOTE: this is not used because user purchases fetched directly from blockchain!
app.get('/set-user-purchases', async (req, res) => {
try {
console.log('Received request for /set-user-purchases');
const reply = await redisClient.get('deda-price');
if (reply) {
console.log('Data retrieved from Redis:', reply);
res.json({ "price": Number(reply) });
} else {
console.log('Data not available yet');
res.status(503).send('Data not available yet. Please try again later.');
}
} catch (err) {
console.error('Error retrieving data from Redis:', err);
res.status(500).send('Error retrieving data from Redis');
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});