Created
April 12, 2018 11:02
-
-
Save GrandSchtroumpf/04d1b09c7ad2df07504f175969d3f58c to your computer and use it in GitHub Desktop.
The Ethereum service to manage accounts
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
import { Injectable, Inject } from '@angular/core'; | |
// Web3 | |
import { WEB3 } from './tokens'; | |
import Web3 from 'web3'; | |
// RXJS | |
import { Observable } from 'rxjs/Observable'; | |
import { bindNodeCallback } from 'rxjs/observable/bindNodeCallback'; | |
import { of } from 'rxjs/observable/of'; | |
import { map, tap, catchError } from 'rxjs/operators'; | |
@Injectable() | |
export class AccountsService { | |
constructor(@Inject(WEB3) private web3: Web3) { } | |
/** Returns all accounts available */ | |
public getAccounts(): Observable<string[]> { | |
return bindNodeCallback(this.web3.eth.getAccounts)(); | |
} | |
/** Get the current account */ | |
public currentAccount(): Observable<string | Error> { | |
if (this.web3.eth.defaultAccount) { | |
return of(this.web3.eth.defaultAccount); | |
} else { | |
return this.getAccounts().pipe( | |
tap((accounts: string[]) => { | |
if (accounts.length === 0) { throw new Error('No accounts available'); } | |
}), | |
map((accounts: string[]) => accounts[0]), | |
tap((account: string) => this.web3.defaultAccount = account), | |
catchError((err: Error) => of(err)) | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment