Skip to content

Instantly share code, notes, and snippets.

@GrandSchtroumpf
Created September 2, 2018 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GrandSchtroumpf/c4b513860b5c95ecc656b2c2cceb864c to your computer and use it in GitHub Desktop.
Save GrandSchtroumpf/c4b513860b5c95ecc656b2c2cceb864c to your computer and use it in GitHub Desktop.
Handles JSON-RPC methods for Ethereum
import { Injectable } from '@angular/core';
import { Provider } from 'provider.service.ts';
import BN from 'bn';
@Injectable({ providedIn : 'root' })
export class Eth {
constructor(private provider: Provider) {}
/** Transform a value into hex or decimal string for example */
private toBN(value: string, from: number, to: number) {
return new BN(value, from).toString(to);
}
/** Get the current block number */
public getBlockNumber(): Observable<string> {
return this.provider
.rpc<string>('eth_blockNumber')
.pipe(map(block => this.toBN(block, 16, 10)));
}
/** Get the balance of an account at a specific block number, default is the latest */
public getBalance(account: string, block: number | 'latest' = 'latest'): Observable<string> {
if (typeof block === 'number') { block = this.toBN(block, 10, 16); }
return this.provider
.rpc<string>('eth_getBalance', [account, block])
.pipe(map(amount => this.toBN(amount)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment