2017-08-08 03:45:08 +00:00
|
|
|
// @flow
|
|
|
|
import Big from 'bignumber.js';
|
|
|
|
import BaseNode from '../base';
|
2017-08-23 06:57:18 +00:00
|
|
|
import type { TransactionWithoutGas } from 'libs/transaction';
|
2017-08-11 21:54:10 +00:00
|
|
|
import RPCClient, {
|
|
|
|
getBalance,
|
|
|
|
estimateGas,
|
2017-08-23 06:57:18 +00:00
|
|
|
getTransactionCount,
|
|
|
|
getTokenBalance
|
2017-08-11 21:54:10 +00:00
|
|
|
} from './client';
|
2017-08-08 03:45:08 +00:00
|
|
|
import type { Token } from 'config/data';
|
|
|
|
|
|
|
|
export default class RpcNode extends BaseNode {
|
|
|
|
client: RPCClient;
|
|
|
|
constructor(endpoint: string) {
|
|
|
|
super();
|
|
|
|
this.client = new RPCClient(endpoint);
|
|
|
|
}
|
|
|
|
|
|
|
|
async getBalance(address: string): Promise<Big> {
|
|
|
|
return this.client.call(getBalance(address)).then(response => {
|
|
|
|
if (response.error) {
|
|
|
|
throw new Error('getBalance error');
|
|
|
|
}
|
|
|
|
return new Big(Number(response.result));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async estimateGas(transaction: TransactionWithoutGas): Promise<Big> {
|
|
|
|
return this.client.call(estimateGas(transaction)).then(response => {
|
|
|
|
if (response.error) {
|
|
|
|
throw new Error('estimateGas error');
|
|
|
|
}
|
|
|
|
return new Big(Number(response.result));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-08-23 06:57:18 +00:00
|
|
|
async getTokenBalance(address: string, token: Token): Promise<Big> {
|
|
|
|
return this.client.call(getTokenBalance(address, token)).then(response => {
|
|
|
|
if (response.error) {
|
|
|
|
return Big(0);
|
|
|
|
}
|
2017-08-28 17:43:57 +00:00
|
|
|
return new Big(response.result).div(new Big(10).pow(token.decimal));
|
2017-08-23 06:57:18 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-08-08 03:45:08 +00:00
|
|
|
async getTokenBalances(address: string, tokens: Token[]): Promise<Big[]> {
|
|
|
|
return this.client
|
2017-08-23 06:57:18 +00:00
|
|
|
.batch(tokens.map(t => getTokenBalance(address, t)))
|
2017-08-08 03:45:08 +00:00
|
|
|
.then(response => {
|
|
|
|
return response.map((item, idx) => {
|
|
|
|
// FIXME wrap in maybe-like
|
|
|
|
if (item.error) {
|
|
|
|
return new Big(0);
|
|
|
|
}
|
2017-08-28 17:43:57 +00:00
|
|
|
return new Big(item.result).div(new Big(10).pow(tokens[idx].decimal));
|
2017-08-08 03:45:08 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2017-08-11 21:54:10 +00:00
|
|
|
|
2017-08-23 06:57:18 +00:00
|
|
|
async getTransactionCount(address: string): Promise<string> {
|
|
|
|
return this.client.call(getTransactionCount(address)).then(response => {
|
|
|
|
if (response.error) {
|
|
|
|
throw new Error('getTransactionCount error');
|
2017-08-11 21:54:10 +00:00
|
|
|
}
|
2017-08-23 06:57:18 +00:00
|
|
|
return response.result;
|
2017-08-11 21:54:10 +00:00
|
|
|
});
|
|
|
|
}
|
2017-08-08 03:45:08 +00:00
|
|
|
}
|