-
Notifications
You must be signed in to change notification settings - Fork 10
/
sendtx_klaytn.js
258 lines (217 loc) · 8.54 KB
/
sendtx_klaytn.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Klaytn transaction latency measurement.
// Reference of Sending Transaction using CaverJS: https://docs.kaikas.io/02_api_reference/02_caver_methods
const fs = require('fs')
const Caver = require('caver-js')
const axios = require('axios')
const path = require('path')
var parquet = require('parquetjs-lite');
const AWS = require('aws-sdk');
const moment = require('moment');
const CoinGecko = require('coingecko-api');
const CoinGeckoClient = new CoinGecko();
const {Storage} = require('@google-cloud/storage');
async function uploadToS3(data) {
if(process.env.S3_BUCKET === "") {
throw "undefined bucket name"
}
const s3 = new AWS.S3();
const filename = await makeParquetFile(data)
const param = {
'Bucket':process.env.S3_BUCKET,
'Key':filename,
'Body':fs.createReadStream(filename),
'ContentType':'application/octet-stream'
}
await s3.upload(param).promise()
fs.unlinkSync(filename)
}
async function uploadToGCS(data) {
if(process.env.GCP_PROJECT_ID === "" || process.env.GCP_KEY_FILE_PATH === "" || process.env.GCP_BUCKET === "") {
throw "undefined parameters"
}
const storage = new Storage({
projectId: process.env.GCP_PROJECT_ID,
keyFilename: process.env.GCP_KEY_FILE_PATH
});
const filename = await makeParquetFile(data)
const destFileName = `tx-latency-measurement/klaytn/${filename}`;
async function uploadFile() {
const options = {
destination: destFileName,
};
await storage.bucket(process.env.GCP_BUCKET).upload(filename, options);
console.log(`${filename} uploaded to ${process.env.GCP_BUCKET}`);
}
await uploadFile().catch(console.error);
fs.unlinkSync(filename)
}
async function uploadChoice(data) {
if (process.env.UPLOAD_METHOD === "AWS") {
await uploadToS3(data)
}
else if (process.env.UPLOAD_METHOD === "GCP") {
await uploadToGCS(data)
}
else {
throw "Improper upload method"
}
}
async function makeParquetFile(data) {
var schema = new parquet.ParquetSchema({
executedAt:{type:'TIMESTAMP_MILLIS'},
txhash:{type:'UTF8'},
startTime:{type:'TIMESTAMP_MILLIS'},
endTime:{type:'TIMESTAMP_MILLIS'},
chainId:{type:'INT64'},
latency:{type:'INT64'},
error:{type:'UTF8'},
txFee:{type:'DOUBLE'},
txFeeInUSD:{type:'DOUBLE'},
resourceUsedOfLatestBlock:{type:'INT64'},
numOfTxInLatestBlock:{type:'INT64'},
pingTime:{type:'INT64'}
})
var d = new Date()
//20220101_032921
var datestring = moment().format('YYYYMMDD_HHmmss')
var filename = `${datestring}_${data.chainId}.parquet`
// create new ParquetWriter that writes to 'fruits.parquet`
var writer = await parquet.ParquetWriter.openFile(schema, filename);
await writer.appendRow(data)
await writer.close()
return filename;
}
function loadConfig() {
if(process.env.NODE_ENV === undefined) {
// console.log("using .env")
require('dotenv').config({path:path.join(__dirname,'.env')})
} else {
// console.log(`using .env.${process.env.NODE_ENV}`)
require('dotenv').config({path:path.join(__dirname,`.env.${process.env.NODE_ENV}`)})
}
}
async function sendSlackMsg(msg) {
await axios.post(process.env.SLACK_API_URL, {
'channel':process.env.SLACK_CHANNEL,
'mrkdown':true,
'text':msg
}, {
headers: {
'Content-type':'application/json',
'Authorization':`Bearer ${process.env.SLACK_AUTH}`
}
})
}
async function checkBalance(addr) {
const caver = new Caver(process.env.CAVER_URL)
const balance = await caver.rpc.klay.getBalance(addr)
const balanceInKLAY = caver.utils.convertFromPeb(balance, 'KLAY')
const now = new Date();
if(parseFloat(balanceInKLAY) < parseFloat(process.env.BALANCE_ALERT_CONDITION_IN_KLAY)) {
await sendSlackMsg(`${now}, Current balance of <${process.env.SCOPE_URL}/account/${addr}|${addr}> is less than ${process.env.BALANCE_ALERT_CONDITION_IN_KLAY} KLAY! balance=${balanceInKLAY}`)
}
}
async function sendTx() {
var data = {
executedAt: new Date().getTime(),
txhash: '',
startTime: 0,
endTime: 0,
chainId: 0,
latency:0,
error:'',
txFee: 0.0,
txFeeInUSD: 0.0,
resourceUsedOfLatestBlock: 0,
numOfTxInLatestBlock: 0,
pingTime:0
}
try {
const caver = new Caver(process.env.CAVER_URL)
const keyring = caver.wallet.keyring.createFromPrivateKey(process.env.PRIVATE_KEY)
caver.wallet.add(keyring)
checkBalance(keyring.address)
// Create value transfer transaction
const vt = caver.transaction.valueTransfer.create({
from: keyring.address,
to: keyring.address,
value: 0,
gas: 25000,
})
// Sign to the transaction
const signed = await caver.wallet.sign(keyring.address, vt)
const chainId = caver.utils.hexToNumber(signed.chainId)
data.chainId = chainId
// Measure latency of getBlock
const startGetBlockNumber = new Date().getTime()
const latestBlockNumber = await caver.klay.getBlockNumber()
const endGetBlockNumber = new Date().getTime()
data.pingTime = endGetBlockNumber - startGetBlockNumber
// Get latest block info
const blockInfo = await caver.klay.getBlock(latestBlockNumber)
data.resourceUsedOfLatestBlock = caver.utils.hexToNumber(blockInfo.gasUsed)
data.numOfTxInLatestBlock = blockInfo.transactions.length
const start = new Date().getTime()
data.startTime = start
// Send transaction to the Klaytn blockchain platform (Klaytn)
const receipt = await caver.rpc.klay.sendRawTransaction(signed)
const end = new Date().getTime()
data.txhash = receipt.transactionHash
data.endTime = end
data.latency = end-start
var KLAYtoUSD;
await axios.get(`https://api.coingecko.com/api/v3/simple/price?ids=klay-token&vs_currencies=usd&x_cg_demo_api_key=${process.env.COIN_GECKO_API_KEY}`)
.then(response => {
KLAYtoUSD = response.data["klay-token"].usd;
});
data.txFee = caver.utils.convertFromPeb(receipt.gasPrice, 'KLAY') * receipt.gasUsed
data.txFeeInUSD = KLAYtoUSD * data.txFee
// console.log(`${data.executedAt},${data.chainId},${data.txhash},${data.startTime},${data.endTime},${data.latency},${data.txFee},${data.txFeeInUSD},${data.resourceUsedOfLatestBlock},${data.numOfTxInLatestBlock},${data.pingTime},${data.error}`)
try{
await uploadChoice(data)
} catch(err){
await sendSlackMsg(`failed to upload Klaytn, ${err.toString()}`);
console.log(`failed to ${process.env.UPLOAD_METHOD === 'AWS'? 's3': 'gcs'}.upload!! Printing instead!`, err.toString())
console.log(JSON.stringify(data))
}
} catch (err) {
const now = new Date();
await sendSlackMsg(`${now}, failed to execute Klaytn, ${err.toString()}, ${err.stack}`);
console.log("failed to execute.", err.toString(), err.stack)
data.error = err.toString()
console.log(`${data.executedAt},${data.chainId},${data.txhash},${data.startTime},${data.endTime},${data.latency},${data.txFee},${data.txFeeInUSD},${data.resourceUsedOfLatestBlock},${data.numOfTxInLatestBlock},${data.pingTime},${data.error}`)
}
}
async function main() {
const start = new Date().getTime()
console.log(`starting tx latency measurement... start time = ${start}`)
if(process.env.PRIVATE_KEY === "") {
const caver = new Caver(process.env.CAVER_URL)
const keyring = caver.wallet.keyring.generate()
console.log(`Private key is not defined. Use this new private key(${keyring.key.privateKey}).`)
console.log(`Get test KLAY from the faucet: https://baobab.wallet.klaytn.foundation/faucet`)
console.log(`Your Klaytn address = ${keyring.address}`)
return
}
// run sendTx every 1 min.
const interval = eval(process.env.SEND_TX_INTERVAL)
setInterval(async()=>{
try{
await sendTx()
} catch(err){
console.log("failed to execute sendTx", err.toString(), err.stack)
}
}, interval)
try{
await sendTx()
} catch(err){
console.log("failed to execute sendTx", err.toString(), err.stack)
}
}
loadConfig();
try{
main()
}
catch(err){
console.log("failed to execute main", err.toString(), err.stack)
}