-
Notifications
You must be signed in to change notification settings - Fork 37
/
web3.service.ts
74 lines (59 loc) · 2.21 KB
/
web3.service.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
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
declare let require: any;
const Web3 = require('web3');
const contract = require('@truffle/contract');
declare let window: any;
@Injectable()
export class Web3Service {
private web3: any;
private accounts: string[];
public ready = false;
public accountsObservable = new Subject<string[]>();
constructor() {
window.addEventListener('load', (event) => {
this.bootstrapWeb3();
});
}
public bootstrapWeb3() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof window.ethereum !== 'undefined') {
// Use Mist/MetaMask's provider
window.ethereum.enable().then(() => {
this.web3 = new Web3(window.ethereum);
});
} else {
console.log('No web3? You should consider trying MetaMask!');
// Hack to provide backwards compatibility for Truffle, which uses web3js 0.20.x
Web3.providers.HttpProvider.prototype.sendAsync = Web3.providers.HttpProvider.prototype.send;
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
this.web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
}
setInterval(() => this.refreshAccounts(), 100);
}
public async artifactsToContract(artifacts) {
if (!this.web3) {
const delay = new Promise(resolve => setTimeout(resolve, 100));
await delay;
return await this.artifactsToContract(artifacts);
}
const contractAbstraction = contract(artifacts);
contractAbstraction.setProvider(this.web3.currentProvider);
return contractAbstraction;
}
private async refreshAccounts() {
const accs = await this.web3.eth.getAccounts();
console.log('Refreshing accounts');
// Get the initial account balance so it can be displayed.
if (accs.length === 0) {
console.warn('Couldn\'t get any accounts! Make sure your Ethereum client is configured correctly.');
return;
}
if (!this.accounts || this.accounts.length !== accs.length || this.accounts[0] !== accs[0]) {
console.log('Observed new accounts');
this.accountsObservable.next(accs);
this.accounts = accs;
}
this.ready = true;
}
}