-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat/add trc20 support #118
Merged
+559
−10
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
cc26ac1
feat(@fireblocks/recovery-utility): :sparkles: add trc20 support
TomerHFB 2ad8641
feat(@fireblocks/recovery-relay): :sparkles: add trc20 support
TomerHFB 1e0cf71
feat(@fireblocks/recovery-utility): :sparkles: add trc20 support
TomerHFB 497f81a
feat(@fireblocks/recovery-utility): :sparkles: add trc20 support
TomerHFB 55d7fbb
feat(@fireblocks/recovery-utility): :sparkles: add trc20 support
TomerHFB e4b9e4a
feat(@fireblocks/recovery-utility): :sparkles: add trc20 support
TomerHFB 290d347
feat(@fireblocks/recovery-utility): :sparkles: add trc20 support
TomerHFB File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
import { Tron as BaseTron, Input } from '@fireblocks/wallet-derivation'; | ||
import { ConnectedWallet } from '../ConnectedWallet'; | ||
import { abi } from './trc20.abi'; | ||
import { AccountData } from '../types'; | ||
import { WalletClasses } from '..'; | ||
import { Tron } from '../TRON'; | ||
import zlib from 'node:zlib'; | ||
import { promisify } from 'util'; | ||
|
||
export class TRC20 extends BaseTron implements ConnectedWallet { | ||
constructor(private input: Input) { | ||
super(input); | ||
} | ||
|
||
protected backendWallet: Tron | undefined; | ||
|
||
public rpcURL: string | undefined; | ||
|
||
private decimals: number | undefined; | ||
|
||
private tokenAddress: string | undefined; | ||
|
||
private toAddress: string | undefined; | ||
|
||
private tronWeb: any | undefined; | ||
|
||
public setDecimals(decimals: number): void { | ||
this.decimals = decimals; | ||
} | ||
|
||
public setTokenAddress(tokenAddress: string): void { | ||
this.tokenAddress = tokenAddress; | ||
} | ||
|
||
public setToAddress(toAddress: string) { | ||
this.toAddress = toAddress; | ||
} | ||
|
||
public setRPCUrl(url: string): void { | ||
this.rpcURL = url; | ||
const TronWeb = require('tronweb'); | ||
const { HttpProvider } = TronWeb.providers; | ||
const endpointUrl = this.rpcURL; | ||
const fullNode = new HttpProvider(endpointUrl); | ||
const solidityNode = new HttpProvider(endpointUrl); | ||
const eventServer = new HttpProvider(endpointUrl); | ||
//random prvKey is used for gas estimations | ||
const randomPrvKey = Array.from({ length: 64 }, () => Math.floor(Math.random() * 16).toString(16)).join(''); | ||
this.tronWeb = new TronWeb(fullNode, solidityNode, eventServer, randomPrvKey); | ||
} | ||
|
||
public async getBalance(): Promise<number> { | ||
const contract = await this.tronWeb.contract(abi, this.tokenAddress); | ||
return (await contract.balanceOf(this.address).call()).toNumber(); | ||
} | ||
|
||
public async prepare(): Promise<AccountData> { | ||
if (!this.decimals) { | ||
this.relayLogger.error('TRC20: Decimals not set'); | ||
throw new Error('TRC20: Decimals not set'); | ||
} | ||
const balance = ((await this.getBalance()) / 10 ** this.decimals) as number; | ||
const trxBalance = await this.getTrxBalance(); | ||
|
||
const extraParams = new Map<string, any>(); | ||
|
||
extraParams.set('t', this.tokenAddress); | ||
extraParams.set('d', this.decimals); | ||
extraParams.set('r', this.rpcURL); | ||
|
||
const feeRate = (await this.estimateGas()) ?? 40_000_000; | ||
|
||
const preparedData: AccountData = { | ||
balance, | ||
feeRate, | ||
extraParams, | ||
insufficientBalance: balance <= 0, | ||
insufficientBalanceForTokenTransfer: trxBalance < feeRate, | ||
}; | ||
|
||
this.relayLogger.logPreparedData('TRC20', preparedData); | ||
return preparedData; | ||
} | ||
|
||
public async broadcastTx(tx: string): Promise<string> { | ||
try { | ||
// decompress and decode | ||
const gunzip = promisify(zlib.gunzip); | ||
const compressedBuffer = Buffer.from(tx, 'base64'); | ||
const decompressedBuffer = await gunzip(new Uint8Array(compressedBuffer)); | ||
const signedTx = JSON.parse(decompressedBuffer.toString()); | ||
|
||
//broadcast the tx | ||
const result = await this.tronWeb.trx.sendRawTransaction(signedTx); | ||
if ('code' in result) { | ||
this.relayLogger.error(`TRC20: Error broadcasting tx: ${JSON.stringify(result, null, 2)}`); | ||
throw new Error(result.code); | ||
} | ||
this.relayLogger.debug(`TRC20: Tx broadcasted: ${result.txid}`); | ||
return result.txid; | ||
} catch (e) { | ||
this.relayLogger.error('TRC20: Error broadcasting tx:', e); | ||
throw new Error(`TRC20: Error broadcasting tx: ${e}`); | ||
} | ||
} | ||
|
||
private async getTrxBalance(): Promise<number> { | ||
return await this.tronWeb.trx.getBalance(this.address); | ||
} | ||
|
||
private async estimateGas(): Promise<number | undefined> { | ||
try { | ||
const functionSelector = 'transfer(address,uint256)'; | ||
const balance = await this.getBalance(); | ||
const parameter = [ | ||
{ type: 'address', value: this.toAddress }, | ||
{ type: 'uint256', value: balance }, | ||
]; | ||
// Trigger a dry-run of the transaction to estimate energy consumption | ||
const energyEstimate = await this.tronWeb.transactionBuilder.triggerConstantContract( | ||
this.tokenAddress, | ||
functionSelector, | ||
parameter, | ||
); | ||
|
||
// Get current energy prices from network | ||
const parameterInfo = await this.tronWeb.trx.getChainParameters(); | ||
const energyFeeParameter = parameterInfo.find((param: any) => param.key === 'getEnergyFee'); | ||
const energyFee = energyFeeParameter ? energyFeeParameter.value : 420; | ||
|
||
return energyEstimate.energy * energyFee * 1.1; // add 10% margin | ||
} catch (error) { | ||
this.relayLogger.error(`TRC20: Error estimating gas, ${error}`); | ||
return undefined; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
export const abi = [ | ||
{ | ||
outputs: [{ type: 'uint256' }], | ||
constant: true, | ||
inputs: [{ name: 'who', type: 'address' }], | ||
name: 'balanceOf', | ||
stateMutability: 'View', | ||
type: 'Function', | ||
}, | ||
{ | ||
outputs: [{ type: 'bool' }], | ||
inputs: [ | ||
{ name: '_to', type: 'address' }, | ||
{ name: '_value', type: 'uint256' }, | ||
], | ||
name: 'transfer', | ||
stateMutability: 'Nonpayable', | ||
type: 'Function', | ||
}, | ||
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
/* eslint-disable spaced-comment */ | ||
/* eslint-disable import/order */ | ||
import { Tron as BaseTron } from '@fireblocks/wallet-derivation'; | ||
import { SigningWallet } from '../SigningWallet'; | ||
import { GenerateTxInput, TxPayload } from '../types'; | ||
import zlib from 'zlib'; | ||
import { promisify } from 'util'; | ||
|
||
export class TRC20 extends BaseTron implements SigningWallet { | ||
public async generateTx({ to, amount, feeRate, extraParams }: GenerateTxInput): Promise<TxPayload> { | ||
try { | ||
const rpcUrl = extraParams?.get('r'); | ||
|
||
// eslint-disable-next-line global-require | ||
const TronWeb = require('tronweb'); | ||
const { HttpProvider } = TronWeb.providers; | ||
const fullNode = new HttpProvider(rpcUrl); | ||
const solidityNode = new HttpProvider(rpcUrl); | ||
const eventServer = new HttpProvider(rpcUrl); | ||
const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, this.privateKey?.replace('0x', '')); | ||
|
||
const decimals = extraParams?.get('d'); | ||
const tokenAddress = extraParams?.get('t'); | ||
|
||
const functionSelector = 'transfer(address,uint256)'; | ||
const parameter = [ | ||
{ type: 'address', value: to }, | ||
{ type: 'uint256', value: amount * 10 ** decimals }, | ||
]; | ||
|
||
const tx = await tronWeb.transactionBuilder.triggerSmartContract( | ||
tokenAddress, | ||
functionSelector, | ||
{ feeLimit: feeRate }, | ||
parameter, | ||
); | ||
|
||
const signedTx = await tronWeb.trx.sign(tx.transaction); | ||
|
||
this.utilityLogger.logSigningTx('TRC20', signedTx); | ||
|
||
//encode and compress for qr code | ||
const gzip = promisify(zlib.gzip); | ||
const compressedTx = (await gzip(JSON.stringify(signedTx))).toString('base64'); | ||
|
||
return { tx: compressedTx }; | ||
} catch (e) { | ||
this.utilityLogger.error('TRC20: Error generating tx:', e); | ||
throw new Error(`TRC20: Error generating tx: ${e}`); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can optimize these multiple ifs, but it's ok for now