Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
feat: add function to get token balance from metamask
Browse files Browse the repository at this point in the history
  • Loading branch information
bayological committed Dec 1, 2021
1 parent 6e8f5d2 commit 9a157a9
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ test/server/data.js
build
dist
.vscode/
metamask
/metamask
.idea
*.log
test/dapp/data.js
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export type Dappeteer = {
sign: () => Promise<void>;
approve: () => Promise<void>;
addToken: (tokenAddress: string) => Promise<void>;
getTokenBalance: (tokenSymbol: string) => Promise<number>;
page: Page;
};

Expand Down
21 changes: 21 additions & 0 deletions src/metamask/getTokenBalance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Page } from 'puppeteer';

export const getTokenBalance = (page: Page) => async (tokenSymbol: string): Promise<number> => {
await page.bringToFront();
await page.waitForTimeout(1000);

const assetListItems = await page.$$('.asset-list-item__token-button');

for (let index = 0; index < assetListItems.length; index++) {
const assetListItem = assetListItems[index];

const titleAttributeValue: string = await page.evaluate((item) => item.getAttribute('title'), assetListItem);

if (titleAttributeValue.split(' ')[1].toUpperCase() === tokenSymbol.toUpperCase()) {
const balance = titleAttributeValue.split(' ')[0];
return parseFloat(balance);
}
}

return 0;
};
2 changes: 2 additions & 0 deletions src/metamask/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { addNetwork } from './addNetwork';
import { addToken } from './addToken';
import { approve } from './approve';
import { confirmTransaction } from './confirmTransaction';
import { getTokenBalance } from './getTokenBalance';
import { importPk } from './importPk';
import { lock } from './lock';
import { sign } from './sign';
Expand Down Expand Up @@ -41,6 +42,7 @@ export const getMetamask = async (page: Page, version?: string): Promise<Dappete
switchNetwork: switchNetwork(page, version),
unlock: unlock(page, setSignedIn, getSingedIn, version),
addToken: addToken(page),
getTokenBalance: getTokenBalance(page),
page,
};
};

0 comments on commit 9a157a9

Please sign in to comment.