/
index.js
274 lines (241 loc) · 8.52 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
const async = require('async');
import { __ } from 'embark-i18n';
const Web3 = require('web3');
const util = require('util');
const { blockchain: blockchainConstants } = require('embark-core/constants');
import { dappPath, hexToNumber } from 'embark-utils';
import { getAddressToContract, getTransactionParams } from './transactionUtils';
export { getAddressToContract, getTransactionParams };
const Transaction = require('ethereumjs-tx');
const ethUtil = require('ethereumjs-util');
const LISTENED_METHODS = [
blockchainConstants.transactionMethods.eth_call,
blockchainConstants.transactionMethods.eth_getTransactionReceipt,
blockchainConstants.transactionMethods.eth_sendTransaction,
blockchainConstants.transactionMethods.eth_sendRawTransaction
];
export default class TransactionLogger {
constructor(embark, _options) {
this.embark = embark;
this.logger = embark.logger;
this.events = embark.events;
this.fs = embark.fs;
this.addressToContract = [];
this.contractsConfig = embark.config.contractsConfig;
this.contractsDeployed = false;
this.outputDone = false;
this.logFile = dappPath(".embark", "contractLogs.json");
this.transactions = {};
this._listenForLogRequests();
this._registerAPI();
this.events.on("contracts:log", this._saveLog.bind(this));
this.events.on('outputDone', () => {
this.outputDone = true;
});
this.embark.registerActionForEvent("deployment:deployContracts:afterAll", { priority: 38 }, (params, cb) => {
this.contractsDeployed = true;
this._getContractsList((contractsList) => {
this.addressToContract = getAddressToContract(contractsList, this.addressToContract);
cb(null, params);
});
});
this.writeLogFile = async.cargo((tasks, callback) => {
// TODO change this to only read once then use memory, because it slows things down a lot to read on each TX
const data = this._readLogs();
tasks.forEach(task => {
data[new Date().getTime()] = task;
});
this.fs.writeJson(this.logFile, data, err => {
if (err) {
console.error(err);
}
callback();
});
});
}
get web3() {
return (async () => {
if (!this._web3) {
const provider = await this.events.request2("blockchain:client:provider", "ethereum");
this._web3 = new Web3(provider);
}
return this._web3;
})();
}
get web3Accounts() {
return (async () => {
if (!this._web3Accounts) {
const web3 = await this.web3;
this._web3Accounts = await web3.eth.getAccounts();
}
return this._web3Accounts;
})();
}
_getContractsList(callback) {
this.events.request("contracts:list", (err, contractsList) => {
if (err) {
this.logger.error(__("no contracts found"));
return callback();
}
callback(contractsList);
});
}
_listenForLogRequests() {
this.events.on('deploy:contract:receipt', receipt => {
this.events.emit('contracts:log', {
name: receipt.className,
functionName: 'constructor',
paramString: '',
address: receipt.contractAddress,
status: receipt.status ? '0x1' : '0x0',
gasUsed: receipt.gasUsed,
blockNumber: receipt.blockNumber,
transactionHash: receipt.transactionHash
});
});
this.events.on('blockchain:proxy:response', this._onLogRequest.bind(this));
}
async _onLogRequest(args) {
/*eslint complexity: ["error", 22]*/
const method = args.request.method;
if (!this.contractsDeployed || !LISTENED_METHODS.includes(method)) {
return;
}
if (method === blockchainConstants.transactionMethods.eth_sendTransaction) {
// We just gather data and wait for the receipt
this.transactions[args.response.result] = {
address: args.request.params[0].to,
data: args.request.params[0].data,
value: args.request.params[0].value,
txHash: args.response.result
};
return;
} else if (method === blockchainConstants.transactionMethods.eth_sendRawTransaction) {
const rawData = Buffer.from(ethUtil.stripHexPrefix(args.request.params[0]), 'hex');
const tx = new Transaction(rawData, 'hex');
this.transactions[args.response.result] = {
address: '0x' + tx.to.toString('hex'),
data: '0x' + tx.data.toString('hex')
};
return;
}
let dataObject;
if (method === blockchainConstants.transactionMethods.eth_getTransactionReceipt) {
dataObject = args.response.result;
if (!dataObject) {
return;
}
if (this.transactions[args.response.result.transactionHash]) {
// This is the normal case. If we don't get here, it's because we missed a TX
dataObject = Object.assign(dataObject, this.transactions[args.response.result.transactionHash]);
delete this.transactions[args.response.result.transactionHash]; // No longer needed
} else {
// Was not a eth_getTransactionReceipt in the context of a transaction
return;
}
} else {
dataObject = args.request.params[0];
}
const { to: address, data } = dataObject;
if (!address) {
// It's a deployment
return;
}
const accounts = await this.web3Accounts;
if (accounts.map(account => account.toLowerCase()).includes(address.toLowerCase())) {
const web3 = await this.web3;
const value = web3.utils.fromWei(web3.utils.hexToNumberString(dataObject.value));
return this.logger.info(`Blockchain>`.underline + ` transferring ${value} ETH from ${dataObject.from} to ${address}`.bold);
}
const contract = this.addressToContract[address];
if (!contract) {
this.logger.debug(`Contract log for unknown contract: ${util.inspect(args)}`);
return this._getContractsList((contractsList) => {
this.addressToContract = getAddressToContract(contractsList, this.addressToContract);
});
}
const { name, silent } = contract;
if (silent && !this.outputDone) {
return;
}
let functionName, paramString;
if (!data) {
// We missed the TX
functionName = 'unknown';
paramString = 'unknown';
} else {
const txParams = getTransactionParams(contract, data);
functionName = txParams.functionName;
paramString = txParams.paramString;
}
if (method === blockchainConstants.transactionMethods.eth_call) {
const log = Object.assign({}, args, { name, functionName, paramString });
log.status = '0x1';
return this.events.emit('contracts:log', log);
}
let { transactionHash, blockNumber, gasUsed, status } = args.response.result;
let reason;
if (status !== '0x0' && status !== '0x1') {
status = !status ? '0x0' : '0x1';
}
if (status === '0x0') {
const web3 = await this.web3;
const tx = await web3.eth.getTransaction(transactionHash);
if (tx) {
const code = await web3.eth.call(tx, tx.blockNumber);
// Convert to Ascii and remove the useless bytes around the revert message
reason = web3.utils.hexToAscii('0x' + code.substring(138)).toString().replace(/[^\x20-\x7E]/g, '');
}
}
gasUsed = hexToNumber(gasUsed);
blockNumber = hexToNumber(blockNumber);
const log = Object.assign({}, args, { name, functionName, paramString, gasUsed, blockNumber, reason, status, transactionHash });
this.events.emit('contracts:log', log);
this.logger.info(`Blockchain>`.underline + ` ${name}.${functionName}(${paramString})`.bold + ` | ${transactionHash} | gas:${gasUsed} | blk:${blockNumber} | status:${status}${reason ? ` | reason: "${reason}"` : ''}`);
this.events.emit('blockchain:tx', {
name,
functionName,
paramString,
transactionHash,
gasUsed,
blockNumber,
status,
reason
});
}
_registerAPI() {
const apiRoute = '/embark-api/contracts/logs';
this.embark.registerAPICall(
'ws',
apiRoute,
(ws, _req) => {
this.events.on('contracts:log', (log) => {
ws.send(JSON.stringify(log), () => {
});
});
}
);
this.embark.registerAPICall(
'get',
apiRoute,
(req, res) => {
res.send(JSON.stringify(this._getLogs()));
}
);
}
_getLogs() {
const data = this._readLogs();
return Object.values(data).reverse();
}
_saveLog(log) {
this.writeLogFile.push(log);
}
_readLogs() {
this.fs.ensureFileSync(this.logFile);
try {
return JSON.parse(this.fs.readFileSync(this.logFile));
} catch (_error) {
return {};
}
}
}