1
0
mirror of https://github.com/trezor/trezor-wallet synced 2024-11-28 03:08:30 +00:00

web3 initialization simpler

This commit is contained in:
Szymon Lesisz 2018-05-09 11:15:12 +02:00
parent 5bfb5d39b2
commit 4dc908837a
2 changed files with 130 additions and 153 deletions

View File

@ -21,6 +21,7 @@ import type {
} from '../flowtype'; } from '../flowtype';
import type { ContractFactory } from 'web3'; import type { ContractFactory } from 'web3';
import type { BigNumber } from 'bignumber.js';
import type { Account } from '../reducers/AccountsReducer'; import type { Account } from '../reducers/AccountsReducer';
import type { PendingTx } from '../reducers/PendingTxReducer'; import type { PendingTx } from '../reducers/PendingTxReducer';
import type { Web3Instance } from '../reducers/Web3Reducer'; import type { Web3Instance } from '../reducers/Web3Reducer';
@ -53,7 +54,7 @@ export type Web3UpdateGasPriceAction = {
}; };
export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction { export function init(instance: ?Web3, coinIndex: number = 0): AsyncAction {
return async (dispatch: Dispatch, getState: GetState): Promise<void> => { return async (dispatch: Dispatch, getState: GetState): Promise<void> => {
const { config, ERC20Abi } = getState().localStorage; const { config, ERC20Abi } = getState().localStorage;
@ -72,20 +73,20 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
let web3host: string = urls[0]; let web3host: string = urls[0];
if (web3) { if (instance) {
const currentHost = web3.currentProvider.host; const currentHost = instance.currentProvider.host;
let currentHostIndex: number = urls.indexOf(currentHost); let currentHostIndex: number = urls.indexOf(currentHost);
if (currentHostIndex + 1 < urls.length) { if (currentHostIndex + 1 < urls.length) {
web3host = urls[currentHostIndex + 1]; web3host = urls[currentHostIndex + 1];
} else { } else {
console.error("TODO: Backend " + network + " not working", web3.currentProvider ); console.error("TODO: Backend " + network + " not working", instance.currentProvider );
dispatch({ dispatch({
type: WEB3.CREATE, type: WEB3.CREATE,
network, network,
web3, web3: instance,
erc20: web3.eth.contract(ERC20Abi), erc20: instance.eth.contract(ERC20Abi),
chainId: '0' chainId: '0'
}); });
@ -96,7 +97,7 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
} }
//const instance = new Web3(window.web3.currentProvider); //const instance = new Web3(window.web3.currentProvider);
const instance = new Web3( new Web3.providers.HttpProvider(web3host) ); const web3 = new Web3( new Web3.providers.HttpProvider(web3host) );
// instance = new Web3( new Web3.providers.HttpProvider('https://pyrus2.ubiqscan.io') ); // UBQ // instance = new Web3( new Web3.providers.HttpProvider('https://pyrus2.ubiqscan.io') ); // UBQ
//instance = new Web3( new Web3.providers.HttpProvider('https://node.expanse.tech/') ); // EXP //instance = new Web3( new Web3.providers.HttpProvider('https://node.expanse.tech/') ); // EXP
@ -106,29 +107,29 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
//instance = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io2/QGyVKozSUEh2YhL4s2G4")); //instance = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io2/QGyVKozSUEh2YhL4s2G4"));
//web3 = new Web3( new Web3.providers.HttpProvider("ws://34.230.234.51:30303") ); //web3 = new Web3( new Web3.providers.HttpProvider("ws://34.230.234.51:30303") );
// initial check if backend is running // initial check if backend is running
if (!web3.currentProvider.isConnected()) {
instance.eth.getGasPrice((error: Error, gasPrice: string) => {
if (error) {
// try different url // try different url
dispatch( init(instance, coinIndex) ); dispatch( init(web3, coinIndex) );
} else { return;
}
const erc20 = instance.eth.contract(ERC20Abi); const erc20 = web3.eth.contract(ERC20Abi);
dispatch({ dispatch({
type: WEB3.CREATE, type: WEB3.CREATE,
network, network,
web3: instance, web3: web3,
erc20, erc20,
chainId: instance.version.network chainId: web3.version.network
}); });
dispatch({ // dispatch({
type: WEB3.GAS_PRICE_UPDATED, // type: WEB3.GAS_PRICE_UPDATED,
network, // network,
gasPrice // gasPrice
}); // });
@ -147,15 +148,15 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
//const shh = instance.shh.newIdentity(); //const shh = instance.shh.newIdentity();
const latestBlockFilter = instance.eth.filter('latest'); const latestBlockFilter = web3.eth.filter('latest');
const onBlockMined = async (error: ?Error, blockHash: ?string) => { const onBlockMined = async (error: ?Error, blockHash: ?string) => {
if (error) { if (error) {
window.setTimeout(() => { // window.setTimeout(() => {
// try again // // try again
onBlockMined(new Error("manually_triggered_error"), undefined); // onBlockMined(new Error("manually_triggered_error"), undefined);
}, 30000); // }, 30000);
} }
if (blockHash) { if (blockHash) {
@ -168,9 +169,25 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
// TODO: filter only current device // TODO: filter only current device
const accounts = getState().accounts.filter(a => a.network === network); const accounts = getState().accounts.filter(a => a.network === network);
for (const addr of accounts) { for (const account of accounts) {
dispatch( getBalance(addr) ); const nonce = await getNonceAsync(web3, account.address);
dispatch( getNonce(addr) ); if (nonce !== account.nonce) {
dispatch({
type: ADDRESS.SET_NONCE,
address: account.address,
network: account.network,
nonce
});
dispatch( getBalance(account) );
// TODO: check if nonce was updated,
// update tokens balance,
// update account balance,
// update pending transactions
}
// dispatch( getNonce(account) );
} }
const tokens = getState().tokens.filter(t => t.network === network); const tokens = getState().tokens.filter(t => t.network === network);
@ -191,10 +208,8 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
// init next coin // init next coin
dispatch( init(instance, coinIndex + 1) ); dispatch( init(web3, coinIndex + 1) );
}
});
// let instance2 = new Web3( new Web3.providers.HttpProvider('https://pyrus2.ubiqscan.io') ); // let instance2 = new Web3( new Web3.providers.HttpProvider('https://pyrus2.ubiqscan.io') );
// console.log("INIT WEB3", instance, instance2); // console.log("INIT WEB3", instance, instance2);
@ -205,45 +220,6 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
} }
// export function initContracts(): AsyncAction {
// return async (dispatch: Dispatch, getState: GetState): Promise<void> => {
// const { web3, abi, tokens } = getState().web3;
// const contracts = [];
// for (let token of tokens) {
// contracts.push({
// contract: web3.eth.contract(abi).at(token.address),
// name: token.name,
// symbol: token.symbol,
// decimal: token.decimal
// });
// // web3.eth.contract(abi).at(token.address).balanceOf('0x98ead4bd2fbbb0cf0b49459aa0510ef53faa6cad', (e, r) => {
// // console.warn('contrR', e, r.toString(10));
// // });
// }
// const contract = web3.eth.contract(abi).at('0x58cda554935e4a1f2acbe15f8757400af275e084');
// contract.name.call((error, name) => {
// if (error) {
// // TODO: skip
// }
// contract.symbol.call((error, symbol) => {
// if (error) {
// // TODO: skip
// }
// contract.decimals.call((error, decimals) => {
// })
// });
// })
// }
// }
export function getGasPrice(network: string): AsyncAction { export function getGasPrice(network: string): AsyncAction {
return async (dispatch: Dispatch, getState: GetState): Promise<void> => { return async (dispatch: Dispatch, getState: GetState): Promise<void> => {
@ -271,7 +247,7 @@ export function getBalance(account: Account): AsyncAction {
const web3instance = getState().web3.filter(w3 => w3.network === account.network)[0]; const web3instance = getState().web3.filter(w3 => w3.network === account.network)[0];
const web3: Web3 = web3instance.web3; const web3: Web3 = web3instance.web3;
web3.eth.getBalance(account.address, (error, balance) => { web3.eth.getBalance(account.address, (error: Error, balance: BigNumber) => {
if (!error) { if (!error) {
const newBalance: string = web3.fromWei(balance.toString(), 'ether'); const newBalance: string = web3.fromWei(balance.toString(), 'ether');
if (account.balance !== newBalance) { if (account.balance !== newBalance) {
@ -295,8 +271,6 @@ export function getTokenBalance(token: Token): AsyncAction {
const web3 = web3instance.web3; const web3 = web3instance.web3;
const contract = web3instance.erc20.at(token.address); const contract = web3instance.erc20.at(token.address);
console.warn("Get bal", token)
contract.balanceOf(token.ethAddress, (error: ?Error, balance: ?BigNumber) => { contract.balanceOf(token.ethAddress, (error: ?Error, balance: ?BigNumber) => {
if (balance) { if (balance) {
const newBalance: string = balance.dividedBy( Math.pow(10, token.decimals) ).toString(); const newBalance: string = balance.dividedBy( Math.pow(10, token.decimals) ).toString();
@ -307,8 +281,6 @@ export function getTokenBalance(token: Token): AsyncAction {
newBalance newBalance
)); ));
} }
console.log("BALANCE!", balance, newBalance);
} }
}); });
} }
@ -422,35 +394,34 @@ export const getNonceAsync = (web3: Web3, address: string): Promise<number> => {
} }
export const getTokenInfoAsync = (erc20: any, address: string): Promise<any> => { export const getTokenInfoAsync = (erc20: ContractFactory, address: string): Promise<any> => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const contract = erc20.at(address, (error, res) => { const contract = erc20.at(address, (error, res) => {
console.warn("callack", error, res) console.warn("callback", error, res)
}); });
console.warn("AT", contract)
const info = {}; const info = {};
// TODO: handle errors // TODO: handle errors
contract.name.call((e, name) => { contract.name.call((error: ?Error, name: ?string) => {
if (e) { if (error) {
//resolve(null); //resolve(null);
//return; //return;
} }
info.name = name; info.name = name;
contract.symbol.call((e, symbol) => { contract.symbol.call((error: ?Error, symbol: ?string) => {
if (e) { if (error) {
resolve(null); resolve(null);
return; return;
} }
info.symbol = symbol; info.symbol = symbol;
contract.decimals.call((e, decimals) => { contract.decimals.call((error: ?Error, decimals: ?BigNumber) => {
if (e) { if (decimals) {
resolve(null);
return;
}
info.decimals = decimals.toString(); info.decimals = decimals.toString();
resolve(info); resolve(info);
} else {
resolve(null);
}
}); });
}) })
}); });

View File

@ -64,11 +64,17 @@ declare module 'web3' {
} }
declare export class Contract { declare export class Contract {
name: (callback: (error: Error, name: string) => void) => void; name: {
symbol: (callback: (error: Error, symbol: string) => void) => void; call: (callback: (error: Error, name: string) => void) => void;
decimals: (callback: (error: Error, decimals: BigNumber) => void) => void; },
balanceOf: (address: string, callback: (error: Error, balance: BigNumber) => void) => void; symbol: {
transfer: any; call: (callback: (error: Error, symbol: string) => void) => void;
},
decimals: {
call: (callback: (error: Error, decimals: BigNumber) => void) => void;
},
balanceOf: (address: string, callback: (error: Error, balance: BigNumber) => void) => void,
transfer: any,
} }
declare export default typeof Web3T; declare export default typeof Web3T;