forked from nervosnetwork/force-bridge
/
tron.ts
329 lines (292 loc) · 10.8 KB
/
tron.ts
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { TronDb } from '../db';
import { logger } from '../utils/logger';
import { asyncSleep } from '../utils';
import { ForceBridgeCore } from '../core';
import { ITronLock, TronUnlock, ICkbMint, TronLock } from '@force-bridge/db/model';
import { ChainType } from '@force-bridge/ckb/model/asset';
import { promises } from 'fs';
import { sign } from '@force-bridge/ckb/tx-helper/signer';
import { getAssetTypeByAsset } from '@force-bridge/xchain/tron/utils';
const TronWeb = require('tronweb');
const TronGrid = require('trongrid');
const TRX_ASSET_LENGTH = 3;
const TRC10_ASSET_LENGTH = 7;
type TronLockEvent = {
tx_hash: string;
index: number;
sender: string;
asset: string;
amount: string;
memo: string;
timestamp: number;
};
export class TronHandler {
private tronWeb;
private tronGrid;
private committee;
constructor(private db: TronDb) {
this.tronWeb = new TronWeb({ fullHost: ForceBridgeCore.config.tron.tronGridUrl });
this.tronGrid = new TronGrid(this.tronWeb);
this.committee = ForceBridgeCore.config.tron.committee;
}
private async getTrxAndTrc10LockEvents(min_timestamp: number): Promise<TronLockEvent[]> {
const lockEvents: TronLockEvent[] = [];
let fingerprint = '';
while (fingerprint != null) {
const txs = await this.tronGrid.account.getTransactions(this.committee.address, {
only_to: true,
only_confirmed: true,
min_timestamp: min_timestamp,
order_by: 'timestamp,asc',
limit: 200,
fingerprint: fingerprint,
});
for (const data of txs.data) {
const asset_data = data.raw_data.contract[0].parameter.value;
const event = {
tx_hash: data.txID,
index: 0,
sender: this.tronWeb.address.fromHex(asset_data.owner_address),
asset: asset_data.asset_name ? asset_data.asset_name : 'trx',
amount: asset_data.amount,
memo: data.raw_data.data ? this.tronWeb.toUtf8(data.raw_data.data) : 'no memo',
timestamp: data.block_timestamp,
};
lockEvents.push(event);
}
fingerprint = txs.meta.fingerprint;
}
return lockEvents;
}
private async getTrc20TxsLockEvents(min_timestamp: number): Promise<TronLockEvent[]> {
const lockEvents: TronLockEvent[] = [];
let fingerprint = '';
while (fingerprint != null) {
const txs = await this.tronGrid.account.getTrc20Transactions(this.committee.address, {
only_confirmed: true,
only_to: true,
min_timestamp: min_timestamp,
order_by: 'timestamp,asc',
limit: 200,
fingerprint: fingerprint,
});
for (const data of txs.data) {
if (Object.keys(data.token_info).length == 0) {
logger.debug('invalid trc20 tx, token info is undefined', data);
continue;
}
const tx = await this.tronWeb.trx.getTransaction(data.transaction_id);
const event = {
tx_hash: data.transaction_id,
index: 0,
sender: data.from,
asset: this.tronWeb.address.fromHex(data.token_info).address,
amount: data.value,
memo: this.tronWeb.toUtf8(tx.raw_data.data),
timestamp: data.block_timestamp,
};
lockEvents.push(event);
}
fingerprint = txs.meta.fingerprint;
}
return lockEvents;
}
// memo style should be "ckb_recipient,sudt_extra_data"
private analyzeMemo(memo: string) {
const splitted = memo.split(',', 2);
const ckbRecipient = splitted[0];
const sudtExtraData = splitted[1];
return { ckbRecipient, sudtExtraData };
}
private transferEventToCkbMint(event: TronLockEvent) {
const { ckbRecipient, sudtExtraData } = this.analyzeMemo(event.memo);
return {
id: event.tx_hash.concat('_').concat(event.index.toString()),
chain: ChainType.TRON,
asset: event.asset,
amount: event.amount,
recipientLockscript: ckbRecipient,
sudtExtraData: sudtExtraData,
};
}
private transferEventToTronLock(event: TronLockEvent): ITronLock {
const tronLock: ITronLock = {
txHash: event.tx_hash,
txIndex: 0,
sender: event.sender,
asset: event.asset,
assetType: getAssetTypeByAsset(event.asset),
amount: event.amount,
memo: event.memo,
timestamp: event.timestamp,
};
return tronLock;
}
// listen Tron chain and handle the new lock events
async watchLockEvents(): Promise<void> {
let startTimestamp = Date.now();
const lastTimestamp = await this.db.getLatestTimestamp();
if (lastTimestamp != 1) {
startTimestamp = lastTimestamp;
}
logger.debug('start time', startTimestamp);
let minTimestamp = startTimestamp;
try {
while (true) {
logger.debug('get new lock events and save to db');
logger.debug('min timestamp', minTimestamp);
const ckbMintRecords: ICkbMint[] = [];
const tronLockRecords: ITronLock[] = [];
const trxAndTrc10Events = await this.getTrxAndTrc10LockEvents(minTimestamp);
const trc20LockEvents = await this.getTrc20TxsLockEvents(minTimestamp);
const totalLockEvents = trxAndTrc10Events.concat(trc20LockEvents);
logger.debug('total lock events', totalLockEvents);
for (const event of totalLockEvents) {
if (event.timestamp <= minTimestamp) {
continue;
}
const ckbMint = this.transferEventToCkbMint(event);
ckbMintRecords.push(ckbMint);
const tronLock = this.transferEventToTronLock(event);
tronLockRecords.push(tronLock);
}
await this.db.createCkbMint(ckbMintRecords);
await this.db.createTronLock(tronLockRecords);
if (trxAndTrc10Events.length != 0) {
minTimestamp = Math.max(trxAndTrc10Events[trxAndTrc10Events.length - 1].timestamp, minTimestamp);
}
if (trc20LockEvents.length != 0) {
minTimestamp = Math.max(trc20LockEvents[trc20LockEvents.length - 1].timestamp, minTimestamp);
}
await asyncSleep(3000);
}
} catch (e) {
logger.error('TronHandler watchLockEvents error:', e);
setTimeout(this.watchLockEvents, 3000);
}
}
private async multiSignTransferTrx(unlockRecord: TronUnlock) {
const from = this.committee.address;
const to = unlockRecord.recipientAddress;
const amount = +unlockRecord.amount;
const memo = unlockRecord.memo;
const unsigned_tx = await this.tronWeb.transactionBuilder.sendTrx(to, amount, from, {
permissionId: this.committee.permissionId,
});
const unsignedWithMemoTx = await this.tronWeb.transactionBuilder.addUpdateData(unsigned_tx, memo, 'utf8');
let signed_tx = unsignedWithMemoTx;
for (const key of this.committee.keys) {
signed_tx = await this.tronWeb.trx.multiSign(signed_tx, key);
}
return signed_tx;
}
private async multiSignTransferTrc10(unlockRecord: TronUnlock) {
const from = this.committee.address;
const to = unlockRecord.recipientAddress;
const amount = unlockRecord.amount;
const tokenID = unlockRecord.asset;
const memo = unlockRecord.memo;
const unsigned_tx = await this.tronWeb.transactionBuilder.sendToken(to, amount, tokenID, from, {
permissionId: this.committee.permissionId,
});
const unsignedWithMemoTx = await this.tronWeb.transactionBuilder.addUpdateData(unsigned_tx, memo, 'utf8');
let signed_tx = unsignedWithMemoTx;
for (const key of this.committee.keys) {
signed_tx = await this.tronWeb.trx.multiSign(signed_tx, key);
}
return signed_tx;
}
private async multiSignTransferTrc20(unlockRecord: TronUnlock) {
const from = this.committee.address;
const to = unlockRecord.recipientAddress;
const amount = unlockRecord.amount;
const trc20ContractAddress = unlockRecord.asset;
const memo = unlockRecord.memo;
const options = {
permissionId: this.committee.permissionId,
feeLimit: ForceBridgeCore.config.tron.feeLimit,
};
const functionSelector = 'transfer(address,uint256)';
const params = [
{ type: 'address', value: to },
{ type: 'uint256', value: amount },
];
const unsigned_tx = await this.tronWeb.transactionBuilder.triggerSmartContract(
trc20ContractAddress,
functionSelector,
options,
params,
from,
);
const unsignedWithMemoTx = await this.tronWeb.transactionBuilder.addUpdateData(
unsigned_tx.transaction,
memo,
'utf8',
);
let signed_tx = unsignedWithMemoTx;
for (const key of this.committee.keys) {
signed_tx = await this.tronWeb.trx.multiSign(signed_tx, key);
}
return signed_tx;
}
// watch the tron_unlock table and handle the new unlock events
// send tx according to the data
async watchUnlockEvents(): Promise<void> {
try {
while (true) {
logger.debug('flush pending tx to confirm');
const pendingRecords = await this.db.getTronUnlockRecords('pending');
for (const pendingRecord of pendingRecords) {
try {
const confirmedTx = await this.tronWeb.trx.getConfirmedTransaction(pendingRecord.tronTxHash);
console.log(confirmedTx);
if (confirmedTx.ret[0].contractRet == 'SUCCESS') {
pendingRecord.status = 'success';
} else {
pendingRecord.status = 'error';
}
} catch (e) {
logger.debug(`${pendingRecord.tronTxHash} not confirmed yet`, e);
}
}
await this.db.saveTronUnlock(pendingRecords);
logger.debug('get new unlock events and send tx');
const unlockRecords = await this.db.getTronUnlockRecords('todo');
for (const unlockRecord of unlockRecords) {
let signedTx;
switch (unlockRecord.assetType) {
case 'trx':
signedTx = await this.multiSignTransferTrx(unlockRecord);
break;
case 'trc10':
signedTx = await this.multiSignTransferTrc10(unlockRecord);
break;
case 'trc20':
signedTx = await this.multiSignTransferTrc20(unlockRecord);
break;
}
unlockRecord.tronTxHash = signedTx.txID;
unlockRecord.tronTxIndex = 0;
unlockRecord.status = 'pending';
await this.db.saveTronUnlock([unlockRecord]);
try {
await this.tronWeb.trx.broadcast(signedTx);
} catch (e) {
logger.error(`TronHandler watchUnlockEvents broadcast tx ${signedTx} error: ${e}`);
unlockRecord.status = 'error';
await this.db.saveTronUnlock([unlockRecord]);
}
}
await asyncSleep(3000);
}
} catch (e) {
logger.error('TronHandler watchUnlockEvents error:', e);
setTimeout(this.watchLockEvents, 3000);
}
}
start() {
this.watchLockEvents();
this.watchUnlockEvents();
logger.info('tron handler started 🚀');
}
}