Skip to content

Commit 15c2d32

Browse files
authored
add sendNativeToken to web3Connection (#105)
1 parent e7422d9 commit 15c2d32

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/base/web3-connection.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import Web3 from 'web3';
33
import {Account, provider as Provider} from 'web3-core';
44
import {HttpProviderOptions, WebsocketProviderOptions} from 'web3-core-helpers';
55
import {Web3ConnectionOptions} from '@interfaces/web3-connection-options';
6-
import {Utils} from 'web3-utils';
6+
import {fromWei, Utils} from 'web3-utils';
77
import {Eth} from 'web3-eth';
88

99
export class Web3Connection {
@@ -34,8 +34,8 @@ export class Web3Connection {
3434
(await this.eth?.givenProvider?.request({method: 'eth_requestAccounts'}) || [""])[0];
3535
}
3636

37-
async getBalance(): Promise<string> {
38-
return this.eth?.getBalance(await this.getAddress());
37+
async getBalance(ofAddress?: string): Promise<string> {
38+
return fromWei(await this.eth?.getBalance(ofAddress || await this.getAddress()));
3939
}
4040

4141
async getETHNetworkId(): Promise<number> {
@@ -115,4 +115,8 @@ export class Web3Connection {
115115
}
116116
/* eslint-enable complexity */
117117

118+
async sendNativeToken(to: string, amount: number) {
119+
return this.eth.sendTransaction({from: await this.getAddress(), to, value: this.utils.toWei(amount.toString())})
120+
}
121+
118122
}

test/base/web3-connection.spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,5 +43,12 @@ describe(`Web3Connection`, () => {
4343
it(`Has restartModelOnDeploy as true by default`, () => {
4444
expect(web3Connection.options.restartModelOnDeploy).to.be.true;
4545
})
46+
47+
it(`Sends native token to another address`, async () => {
48+
const AliceAddress = web3Connection.eth.accounts.privateKeyToAccount(getPrivateKeyFromFile(1))?.address;
49+
const balance = await web3Connection.getBalance(AliceAddress);
50+
await web3Connection.sendNativeToken(AliceAddress, 1);
51+
expect(await web3Connection.getBalance(AliceAddress)).to.be.eq((+balance+1).toString())
52+
})
4653
})
4754
})

0 commit comments

Comments
 (0)