Skip to content

Commit

Permalink
add get balances per block, add asynchronous updates
Browse files Browse the repository at this point in the history
  • Loading branch information
arminreiter committed Dec 20, 2023
1 parent 70e8bf5 commit c2f1df1
Show file tree
Hide file tree
Showing 10 changed files with 151 additions and 18 deletions.
22 changes: 16 additions & 6 deletions src/src/app/actions-inuse/actions-inuse.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Component, OnInit } from '@angular/core';
import { faPlay, faTrash } from '@fortawesome/free-solid-svg-icons';
import { Action } from '../shared/actions/action';
import { DataService } from '../shared/services/data.service';

@Component({
Expand All @@ -19,15 +20,24 @@ export class ActionsInuseComponent implements OnInit {

async play() {
for (var action of this.dataService.actions) {
try {
let result = await action.run(this.dataService.getInput());
this.dataService.addResult(action.title, result);
} catch (error) {
this.dataService.addResult(action.title, String(error));
}
await this.executeAction(action);
}
}

private executeAction(action: Action): Promise<void> {
return new Promise(async (resolve) => {
setTimeout(async () => {
try {
let result = await action.run(this.dataService.getInput());
this.dataService.addResult(action.title, result);
} catch (error) {
this.dataService.addResult(action.title, String(error));
}
resolve();
});
});
}

clear() {
this.dataService.actions = [];
}
Expand Down
50 changes: 49 additions & 1 deletion src/src/app/shared/services/web3.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { formatNumber } from "@angular/common";
import { ethers } from "ethers";
import Web3 from "web3";
import { Network } from "../model/network";
Expand Down Expand Up @@ -69,6 +68,16 @@ export class Web3Service {
return result;
}

static async *getPrivateKeysAsync(seedPhrase: string, amount: number, derivationPath: string = "m/44'/60'/0'/0/0") {
seedPhrase = seedPhrase.trim();

for (var i = 0; i < amount; i++) {
var path = this.getPath(i, derivationPath);
var wallet = ethers.Wallet.fromMnemonic(seedPhrase, path);
yield wallet.privateKey;
}
}

static getPath(id: number, path:string = "m/44'/60'/0'/0/0") {
path = path.substring(0, path.lastIndexOf('/')+1) + id;
return path;
Expand Down Expand Up @@ -99,6 +108,38 @@ export class Web3Service {
return result;
}

static async *getBalancesAsync(addresses: string, rpcUrl: string, delimiter: string = ": "): AsyncGenerator<string> {
var web3js = new Web3(new Web3.providers.HttpProvider(rpcUrl));
var spadd = addresses.split("\n");

for (let address of spadd) {
address = address.trim();
if (address.length > 0) {
try {
const bal = await web3js.eth.getBalance(address);
const formattedBal = Web3.utils.fromWei(bal);
yield `${address}${delimiter}${formattedBal}\n`;
} catch (error) {
yield(`Error fetching balance for address ${address}: ` + error + '\n');
}
}
}
}

static async *getBalancesPerBlockAsync(address: string, rpcUrl: string, delimiter: string = ", ", startBlock: number, endBlock: number, iteration: number): AsyncGenerator<string> {
var web3js = new Web3(new Web3.providers.HttpProvider(rpcUrl));

for(let i = startBlock; i <= endBlock; i += iteration) {
try {
const bal = await web3js.eth.getBalance(address, i);
const formattedBal = Web3.utils.fromWei(bal);
yield `${i}${delimiter}${address}${delimiter}${formattedBal}\n`;
} catch (error) {
yield(`Error fetching balance for address ${address}: ` + error + '\n');
}
}
}

static async sendTransaction(from: string, network:Network, receiver: string, amount: number) {
var web3js = new Web3(new Web3.providers.HttpProvider(network.rpcUrl));
web3js.eth.sendTransaction({
Expand Down Expand Up @@ -140,6 +181,13 @@ export class Web3Service {
return result;
}


static async getLastBlockNumber(network:Network) : Promise<number> {
var web3js = new Web3(new Web3.providers.HttpProvider(network.rpcUrl));
var block = await web3js.eth.getBlock("latest");
return block.number;
}

static async getBlock(blockNumber:number, network:Network) : Promise<string> {
var web3js = new Web3(new Web3.providers.HttpProvider(network.rpcUrl));
var block = await web3js.eth.getBlock(blockNumber);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Web3Service } from 'src/app/shared/services/web3.service';

@Component({
Expand All @@ -12,7 +12,7 @@ export class GetAddressFromSeedComponent implements OnInit {
derivationPath: string = "m/44'/60'/0'/0/0";
genAddresses: string = "";

constructor() { }
constructor(private changeDetector: ChangeDetectorRef) { }

ngOnInit(): void {
}
Expand Down
20 changes: 12 additions & 8 deletions src/src/app/tools/get-balance/get-balance.component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { DataService } from 'src/app/shared/services/data.service';
import { Web3Service } from 'src/app/shared/services/web3.service';

Expand All @@ -12,17 +12,21 @@ export class GetBalanceComponent implements OnInit {
delimiter: string = ", ";
balances: string = "";

constructor(public dataService: DataService) { }
constructor(public dataService: DataService, private changeDetector: ChangeDetectorRef) { }

ngOnInit(): void {
}

getBalances() {
Web3Service.getBalances(this.addresses, this.dataService.network.rpcUrl, this.delimiter).then( (result) => {
this.balances = result;
}).catch(error => {
this.balances = String(error);
});
async getBalances() {
for await(const balance of Web3Service.getBalancesAsync(this.addresses, this.dataService.network.rpcUrl, this.delimiter)) {
this.balances += balance;
this.changeDetector.detectChanges();
}
// Web3Service.getBalances(this.addresses, this.dataService.network.rpcUrl, this.delimiter).then( (result) => {
// this.balances = result;
// }).catch(error => {
// this.balances = String(error);
// });
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<div class="card bg-dark">
<h5 class="card-header bg-dark">Get Balances from Address per Block</h5>
<div class="card-body">
<p class="card-text">
Enter public address below to get the balance (one address)
</p>
<p class="card-text">
<input type="text" class="form-control" [(ngModel)]="address"><br />
Delimiter: <br />
<input type="text" class="form-control" [(ngModel)]="delimiter"><br />

Start Block: <br />
<input type="number" class="form-control" min="1" [(ngModel)]="startBlock"><br />
End Block: <br />
<input type="number" class="form-control" min="1" [(ngModel)]="endBlock"><br />
Iteration: <br />
<input type="number" class="form-control" min="1" [(ngModel)]="iteration"><br />
</p>
<p class="card-text">
<button (click)="getBalances()" class="btn" >Get Balances</button>
</p>
<p class="card-text">
<textarea class="form-control font-code" rows="12" disabled>{{balances}}</textarea>
</p>
</div>
</div>
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { DataService } from 'src/app/shared/services/data.service';
import { Web3Service } from 'src/app/shared/services/web3.service';

@Component({
selector: 'w3tk-get-balances-per-block',
templateUrl: './get-balances-per-block.component.html',
styleUrls: ['./get-balances-per-block.component.scss']
})
export class GetBalancesPerBlockComponent implements OnInit {
address: string = "";
delimiter: string = ", ";
startBlock: number = 0;
endBlock: number = 0;
iteration: number = 17280;
balances: string = "";

constructor(public dataService: DataService, private changeDetector: ChangeDetectorRef) { }

ngOnInit(): void {
}

async getBalances() {

if(this.endBlock == 0) {
Web3Service.getLastBlockNumber(this.dataService.network).then((result) => {
this.endBlock = result;
});
}

this.balances = "";
for await(const balance of Web3Service.getBalancesPerBlockAsync(
this.address, this.dataService.network.rpcUrl, this.delimiter,
this.startBlock, this.endBlock, this.iteration)) {
this.balances += balance;
this.changeDetector.detectChanges();
}
}

}
2 changes: 2 additions & 0 deletions src/src/app/tools/tools-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { GetAddressFromKeyComponent } from './get-address-from-key/get-address-f
import { GenerateKeypairComponent } from './generate-keypair/generate-keypair.component';
import { IsValidSeedphraseComponent } from './is-valid-seedphrase/is-valid-seedphrase.component';
import { IsValidAddressComponent } from './is-valid-address/is-valid-address.component';
import { GetBalancesPerBlockComponent } from './get-balances-per-block/get-balances-per-block.component';

const routes: Routes = [
{
Expand All @@ -25,6 +26,7 @@ const routes: Routes = [
{ path: 'getaddrfromkey', component: GetAddressFromKeyComponent},
{ path: 'weiconverter', component: WeiConverterComponent },
{ path: 'getbalances', component: GetBalanceComponent },
{ path: 'getbalancesperblock', component: GetBalancesPerBlockComponent },
{ path: 'drainfunds', component: DrainfundsComponent},
{ path: 'isvalidseed', component: IsValidSeedphraseComponent },
{ path: 'isvalidaddress', component: IsValidAddressComponent }
Expand Down
1 change: 1 addition & 0 deletions src/src/app/tools/tools.data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export class ToolsData {
] },
{ module: Module.Wallet, icon: faWallet, actions: [
{ name: "Get Balances", route: "/tools/getbalances", requiresConnection: true },
{ name: "Get Balances per Block", route: "/tools/getbalancesperblock", requiresConnection: true },
{ name: "Drain Funds", route: "/tools/drainfunds", requiresConnection: true}
] },
{ module: Module.Utils, icon: faCode, actions: [
Expand Down
4 changes: 3 additions & 1 deletion src/src/app/tools/tools.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { GetAddressFromKeyComponent } from './get-address-from-key/get-address-f
import { GenerateKeypairComponent } from './generate-keypair/generate-keypair.component';
import { IsValidSeedphraseComponent } from './is-valid-seedphrase/is-valid-seedphrase.component';
import { IsValidAddressComponent } from './is-valid-address/is-valid-address.component';
import { GetBalancesPerBlockComponent } from './get-balances-per-block/get-balances-per-block.component';

@NgModule({
declarations: [
Expand All @@ -32,7 +33,8 @@ import { IsValidAddressComponent } from './is-valid-address/is-valid-address.com
GetAddressFromKeyComponent,
GenerateKeypairComponent,
IsValidSeedphraseComponent,
IsValidAddressComponent
IsValidAddressComponent,
GetBalancesPerBlockComponent

],
imports: [
Expand Down

0 comments on commit c2f1df1

Please sign in to comment.