@ethersproject/units#formatEther TypeScript Examples
The following examples show how to use
@ethersproject/units#formatEther.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Balance.tsx From useDApp with MIT License | 6 votes |
export function Balance() {
const { account, chainId } = useEthers()
const userBalance = useEtherBalance(account, { chainId })
const stakingBalance = useEtherBalance(STAKING_CONTRACT, { chainId })
return (
<MainContent>
<Container>
<Section>
<SectionRow>
<Title>Balance</Title>
<AccountButton />
</SectionRow>
<ContentBlock>
{stakingBalance && (
<ContentRow>
<Label>ETH2 staking contract holds:</Label> <TextInline>{formatEther(stakingBalance)}</TextInline>{' '}
<Label>ETH</Label>
</ContentRow>
)}
{account && (
<ContentRow>
<Label>Account:</Label> <TextInline>{account}</TextInline>
</ContentRow>
)}
{userBalance && (
<ContentRow>
<Label>Ether balance:</Label> <TextInline>{formatEther(userBalance)}</TextInline> <Label>ETH</Label>
</ContentRow>
)}
</ContentBlock>
</Section>
</Container>
</MainContent>
)
}
Example #2
Source File: transactions.ts From pownft-miner with Apache License 2.0 | 6 votes |
export async function mineAtom(instance: Contract, targetAtom: TargetAtom, gasPrice: BigNumber, dryRun: boolean) : Promise<TransactionResponse | false> {
const value = targetAtom.cost;
const prefix = dryRun ? '[DRY RUN] ' : '';
console.log(`${prefix}Issuing tx to mine atom ${targetAtom.tokenId} for ${formatEther(value)} eth using gas ${formatUnits(gasPrice, 'gwei')} using nonce ${targetAtom.nonce.toString()}`);
// this will simulate the tx on chain, if anyone has mined a block it will fail with a "revert: difficulty" message
const gasLimit = await instance.estimateGas.mine(targetAtom.nonce, {value, gasPrice});
if (dryRun) {
return false;
} else {
return instance.mine(targetAtom.nonce, {value, gasPrice, gasLimit});
}
}
Example #3
Source File: amounts.ts From sdk with ISC License | 6 votes |
export function valueEther(wei: BigNumberish, opts?: RoundingOptions): string {
const weiVal = BigNumber.from(wei);
let amtEther: string = formatEther(weiVal);
opts = opts ?? { round: false, places: PLACES };
const {round, places=PLACES} = opts;
if (round) {
let exp = 18-places;
let pow = BigNumber.from(10).pow(exp);
let remainder = weiVal.mod(pow);
amtEther = formatEther(weiVal.sub(remainder));
}
return amtEther
}
Example #4
Source File: app.ts From noether with Apache License 2.0 | 6 votes |
checkBalance = async (provider: Provider, address: string) => {
// query node wallet ETH balance
const balance = await provider.getBalance(address);
const label = formatEther(balance);
// monitor ETH balance
monitoring.balance.set(Number.parseFloat(label));
// print warning if below threshold
if (balance.lt(BALANCE_THRESHOLD)) {
log.warn(`low balance: ${label} ETH, transfer more funds`);
}
}
Example #5
Source File: App.tsx From ether-swr with MIT License | 6 votes |
EthBalance = () => {
const { account } = useWeb3React<Web3Provider>()
const { data: balance, mutate } = useEtherSWR(
['getBalance', account, 'latest'],
{
subscribe: [
{
name: 'block',
on: (event: any) => {
console.log('block', { event })
// on every block we check if Ether balance has changed by re-fetching
mutate(undefined, true)
}
}
]
}
)
if (!balance) {
return <div>...</div>
}
return <div>{parseFloat(formatEther(balance)).toPrecision(4)} Ξ</div>
}
Example #6
Source File: Web3ReactConnector.tsx From useDApp with MIT License | 6 votes |
export function Web3ReactConnector() {
const { account } = useEthers()
const userBalance = useEtherBalance(account)
const stakingBalance = useEtherBalance(STAKING_CONTRACT)
return (
<MainContent>
<Container>
<Section>
<SectionRow>
<Title>Web3React Connectors Usage Example</Title>
<Web3ReactConnectorButton />
</SectionRow>
<ContentBlock>
{stakingBalance && (
<ContentRow>
<Label>ETH2 staking contract holds:</Label> <TextInline>{formatEther(stakingBalance)}</TextInline>{' '}
<Label>ETH</Label>
</ContentRow>
)}
{account && (
<ContentRow>
<Label>Account:</Label> <TextInline>{account}</TextInline>
</ContentRow>
)}
{userBalance && (
<ContentRow>
<Label>Ether balance:</Label> <TextInline>{formatEther(userBalance)}</TextInline> <Label>ETH</Label>
</ContentRow>
)}
</ContentBlock>
</Section>
</Container>
</MainContent>
)
}
Example #7
Source File: Web3Modal.tsx From useDApp with MIT License | 6 votes |
export function Web3Modal() {
const { account } = useEthers()
const userBalance = useEtherBalance(account)
const stakingBalance = useEtherBalance(STAKING_CONTRACT)
return (
<MainContent>
<Container>
<Section>
<SectionRow>
<Title>Web3Modal Usage Example</Title>
<Web3ModalButton />
</SectionRow>
<ContentBlock>
{stakingBalance && (
<ContentRow>
<Label>ETH2 staking contract holds:</Label> <TextInline>{formatEther(stakingBalance)}</TextInline>{' '}
<Label>ETH</Label>
</ContentRow>
)}
{account && (
<ContentRow>
<Label>Account:</Label> <TextInline>{account}</TextInline>
</ContentRow>
)}
{userBalance && (
<ContentRow>
<Label>Ether balance:</Label> <TextInline>{formatEther(userBalance)}</TextInline> <Label>ETH</Label>
</ContentRow>
)}
</ContentBlock>
</Section>
</Container>
</MainContent>
)
}
Example #8
Source File: index.tsx From useDApp with MIT License | 6 votes |
export function ChainState({ chainId }: ChainStateProps) {
const { chainName } = useChainMeta(chainId)
const { value } = useChainState({ chainId }) ?? {}
const { difficulty, timestamp } = useBlockMeta({ chainId })
const { account } = useEthers()
const balance = useEtherBalance(account, { chainId })
return (
<ChainBlock>
<ContentRow>
<Label>{chainName}</Label>
</ContentRow>
<ContentRow>
<Label>Chain id:</Label> <TextInline>{chainId}</TextInline>
</ContentRow>
<ContentRow>
<Label>Current block:</Label> <TextInline>{value?.blockNumber}</TextInline>
</ContentRow>
{difficulty && (
<ContentRow>
<Label>Current difficulty:</Label> <TextInline>{difficulty.toString()}</TextInline>
</ContentRow>
)}
{timestamp && (
<ContentRow>
<Label>Current block timestamp:</Label> <TextInline>{timestamp.toLocaleString()}</TextInline>
</ContentRow>
)}
{balance && (
<ContentRow>
<Label>Ether balance:</Label> <TextInline>{formatEther(balance)}</TextInline> <Label>ETH</Label>
</ContentRow>
)}
</ChainBlock>
)
}
Example #9
Source File: EthBalance.tsx From useDApp with MIT License | 6 votes |
export function App() {
const { account } = useEthers()
const etherBalance = useEtherBalance(account)
return (
<div>
<MetamaskConnect />
{etherBalance && (
<div className="balance">
Ether balance:
<p className="bold">{formatEther(etherBalance)} ETH</p>
</div>
)}
</div>
)
}
Example #10
Source File: GettingStarted.tsx From useDApp with MIT License | 6 votes |
function App() {
const { account, deactivate } = useEthers()
const etherBalance = useEtherBalance(account)
return (
<div>
<MetamaskConnect />
{account && <button onClick={() => deactivate()}>Disconnect</button>}
{etherBalance && (
<div className="balance">
<br />
Balance:
<p className="bold">{formatEther(etherBalance)}</p>
</div>
)}
</div>
)
}
Example #11
Source File: Multichain.tsx From useDApp with MIT License | 6 votes |
export function App() {
const mainnetBalance = useEtherBalance(address, { chainId: Mainnet.chainId })
const arbitrumBalance = useEtherBalance(address, { chainId: Arbitrum.chainId })
const zkSyncBalance = useEtherBalance(address, { chainId: ZkSyncTestnet.chainId })
return (
<>
<div className="balance"> Account:</div>
<div className="inline">
<AccountIcon account={address} />
<div className="account">{address}</div>
</div>
<br />
<div className="balance">
Balance on Mainnet:
<p className="bold">{mainnetBalance && formatEther(mainnetBalance)} Eth </p>
</div>
<div className="balance">
Balance on Arbitrum:
<p className="bold">{arbitrumBalance && formatEther(arbitrumBalance)} AEth</p>
</div>
<div className="balance">
Balance on ZkSync Testnet:
<p className="bold">{zkSyncBalance && formatEther(zkSyncBalance)} ZKEth</p>
</div>
</>
)
}
Example #12
Source File: TokenBalance.tsx From useDApp with MIT License | 6 votes |
export function TokenBalance() {
const { account } = useEthers()
const daiBalance = useTokenBalance(DAI, account)
return (
<div>
<MetamaskConnect />
{daiBalance && (
<div className="balance">
Dai balance:
<p className="bold">{formatEther(daiBalance)}</p>
</div>
)}
</div>
)
}
Example #13
Source File: ReadingWithoutWallet.tsx From useDApp with MIT License | 6 votes |
export function App() {
const etherBalance = useEtherBalance(STAKING_CONTRACT)
return (
<div>
{etherBalance && (
<div className="balance">
Staking contract balance:
<p className="bold">{formatEther(etherBalance)} ETH</p>
</div>
)}
</div>
)
}
Example #14
Source File: SendEthForm.tsx From useDApp with MIT License | 5 votes |
formatBalance = (balance: BigNumber | undefined) =>
formatter.format(parseFloat(formatEther(balance ?? BigNumber.from('0'))))
Example #15
Source File: ConnectingToNetwork.tsx From useDApp with MIT License | 5 votes |
export function App() {
const { account, activateBrowserWallet, deactivate } = useEthers()
const userBalance = useEtherBalance(account)
const stakingBalance = useEtherBalance(STAKING_CONTRACT)
const ConnectButton = () => (
<div>
<button onClick={() => activateBrowserWallet()}>Connect</button>
<p>Connect to wallet to interact with the example.</p>
</div>
)
const MetamaskConnect = () => (
<div>
{account && (
<div>
<div className="inline">
<AccountIcon account={account} />
<div className="account">{account}</div>
</div>
<br />
</div>
)}
{!account && <ConnectButton />}
{account && <button onClick={deactivate}>Disconnect</button>}
<br />
</div>
)
return (
<div>
<MetamaskConnect />
{userBalance && (
<div className="balance">
<br />
Ether balance:
<p className="bold">{formatEther(userBalance)} ETH</p>
</div>
)}
{stakingBalance && (
<div className="balance">
ETH2 staking balance:
<p className="bold">{formatEther(stakingBalance)} ETH</p>
</div>
)}
</div>
)
}
Example #16
Source File: index.ts From snapshot-strategies with MIT License | 5 votes |
export async function strategy(
space,
network,
provider,
addresses,
options,
snapshot
) {
const blockTag = typeof snapshot === 'number' ? snapshot : 'latest';
const stakingPool = new Multicaller(network, provider, stakingAbi, {
blockTag
});
const tokenPool = new Multicaller(network, provider, tokenAbi, {
blockTag
});
addresses.forEach((address) => {
stakingPool.call(address, options.staking, 'depositsOf', [address]);
tokenPool.call(address, options.token, 'balanceOf', [address]);
});
const [stakingResponse, tokenResponse]: [
Record<string, BigNumberish[]>,
Record<string, BigNumberish>
] = await Promise.all([stakingPool.execute(), tokenPool.execute()]);
addresses.forEach((address) => {
const tokenIds = stakingResponse[address].map((tokenId) =>
BigNumber.from(tokenId).toNumber()
);
stakingPool.call(address, options.staking, 'calculateRewards', [
address,
tokenIds
]);
});
const rewardsResponse: Record<
string,
BigNumberish[]
> = await stakingPool.execute();
return Object.fromEntries(
addresses.map((address) => {
const claimedCount = formatEther(BigNumber.from(tokenResponse[address]));
const unclaimedCount = formatEther(
rewardsResponse[address].reduce(
(prev, count) => BigNumber.from(prev).add(BigNumber.from(count)),
BigNumber.from('0')
)
);
return [address, parseInt(claimedCount) + parseInt(unclaimedCount)];
})
);
}
Example #17
Source File: 0038-layer1-deploy-rootBridgeV2.ts From perpetual-protocol with GNU General Public License v3.0 | 5 votes |
migration: MigrationDefinition = {
getTasks: (context: MigrationContext) => [
async (): Promise<void> => {
console.log("deploy metaTxGateway...")
const chainId = context.settingsDao.getChainId(Layer.Layer2)
await context.factory
.create<MetaTxGateway>(ContractFullyQualifiedName.MetaTxGateway)
.deployUpgradableContract("Perp", "1", chainId)
},
async (): Promise<void> => {
console.log("deploy rootBridgeV2...")
const ambBridgeOnEth = context.externalContract.ambBridgeOnEth!
const multiTokenMediatorOnEth = context.externalContract.multiTokenMediatorOnEth!
const metaTxGatewayContract = context.factory.create<MetaTxGateway>(
ContractFullyQualifiedName.MetaTxGateway,
)
await context.factory
.create<RootBridgeV2>(ContractFullyQualifiedName.RootBridgeV2)
.deployUpgradableContract(ambBridgeOnEth, multiTokenMediatorOnEth, metaTxGatewayContract.address!)
},
async (): Promise<void> => {
console.log("rootBridgeV2 set min deposit amount...")
const rootBridgeV2 = await context.factory
.create<RootBridgeV2>(ContractFullyQualifiedName.RootBridgeV2)
.instance()
const USDC = context.externalContract.usdc!
await (
await rootBridgeV2.setMinDepositAmount(USDC, {
d: context.deployConfig.minDepositAmount,
})
).wait(context.deployConfig.confirmations)
const minAmount = await rootBridgeV2.minWithdrawalAmountMap(USDC)
console.log(" - min deposit amount is ", formatEther(minAmount))
},
async (): Promise<void> => {
console.log("metaTxGateway add rootBridgeV2 to whitelist...")
const metaTxGateway = await context.factory
.create<MetaTxGateway>(ContractFullyQualifiedName.MetaTxGateway)
.instance()
const clientBridgeContract = context.factory.create<RootBridgeV2>(ContractFullyQualifiedName.RootBridgeV2)
await (await metaTxGateway.addToWhitelists(clientBridgeContract.address!)).wait(
context.deployConfig.confirmations,
)
},
async (): Promise<void> => {
const gov = context.externalContract.foundationGovernance!
console.log(
`transferring rootBridgeV2's owner to governance=${gov}...please remember to claim the ownership`,
)
const rootBridgeV2 = await context.factory
.create<RootBridgeV2>(ContractFullyQualifiedName.RootBridgeV2)
.instance()
await (await rootBridgeV2.setOwner(gov)).wait(context.deployConfig.confirmations)
},
async (): Promise<void> => {
const gov = context.externalContract.foundationGovernance!
console.log(
`transferring metaTxGateway's owner to governance=${gov}...please remember to claim the ownership`,
)
const metaTxGateway = await context.factory
.create<MetaTxGateway>(ContractFullyQualifiedName.MetaTxGateway)
.instance()
await (await metaTxGateway.setOwner(gov)).wait(context.deployConfig.confirmations)
},
],
}
Example #18
Source File: PerpService.ts From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License | 5 votes |
// noinspection JSMethodCanBeStatic
static fromWei(wei: BigNumber): Big {
return Big(formatEther(wei))
}
Example #19
Source File: AccountModal.tsx From useDApp with MIT License | 5 votes |
formatBalance = (balance: BigNumber | undefined) =>
formatter.format(parseFloat(formatEther(balance ?? BigNumber.from('0'))))
Example #20
Source File: TransactionForm.tsx From useDApp with MIT License | 5 votes |
formatBalance = (balance: BigNumber | undefined) =>
formatter.format(parseFloat(formatEther(balance ?? BigNumber.from('0'))))
Example #21
Source File: History.tsx From useDApp with MIT License | 5 votes |
formatBalance = (balance: BigNumber | undefined) =>
formatter.format(parseFloat(formatEther(balance ?? BigNumber.from('0'))))
Example #22
Source File: WalletConnectExample.tsx From useDApp with MIT License | 5 votes |
function App() {
const { account, activate, deactivate } = useEthers()
const etherBalance = useEtherBalance(account)
async function onConnect() {
try {
const provider = new WalletConnectProvider({
infuraId: '62687d1a985d4508b2b7a24827551934',
})
await provider.enable()
await activate(provider)
} catch (error) {
console.error(error)
}
}
const ConnectButton = () => (
<div>
<button onClick={onConnect}>Connect</button>
</div>
)
const WalletConnectConnect = () => (
<div>
{account && (
<div>
<div className="inline">
<AccountIcon account={account} />
<div className="account">{account}</div>
</div>
<br />
</div>
)}
{!account && <ConnectButton />}
{account && <button onClick={deactivate}>Disconnect</button>}
<br />
</div>
)
return (
<div>
<WalletConnectConnect />
{etherBalance && (
<div className="balance">
<br />
Balance:
<p className="bold">{formatEther(etherBalance)} ETH</p>
</div>
)}
</div>
)
}
Example #23
Source File: rarityPayouts.ts From aavegotchi-contracts with MIT License | 4 votes |
task("rarityPayout")
.addParam("season")
.addParam(
"rarityDataFile",
"File that contains all the data related to the particular rarity round"
)
.addParam("deployerAddress")
.addParam("tieBreakerIndex", "The Tiebreaker index")
.setAction(
async (taskArgs: RarityPayoutTaskArgs, hre: HardhatRuntimeEnvironment) => {
const filename: string = taskArgs.rarityDataFile;
const diamondAddress = maticDiamondAddress;
const deployerAddress = taskArgs.deployerAddress;
console.log("deployer:", deployerAddress);
const accounts = await hre.ethers.getSigners();
tiebreakerIndex = taskArgs.tieBreakerIndex;
const testing = ["hardhat", "localhost"].includes(hre.network.name);
let signer: Signer;
if (testing) {
await hre.network.provider.request({
method: "hardhat_impersonateAccount",
params: [deployerAddress],
});
signer = await hre.ethers.provider.getSigner(deployerAddress);
} else if (hre.network.name === "matic") {
signer = accounts[0];
} else {
throw Error("Incorrect network selected");
}
const managedSigner = new NonceManager(signer);
const rounds = Number(taskArgs.rounds);
const signerAddress = await signer.getAddress();
if (signerAddress !== deployerAddress) {
throw new Error(
`Deployer ${deployerAddress} does not match signer ${signerAddress}`
);
}
//Get rewards for this season
const {
rewardArgs,
} = require(`../data/airdrops/rarityfarming/szn${taskArgs.season}/rewards`);
const rewards: RarityFarmingRewardArgs = rewardArgs;
const maxProcess = 500;
const finalRewards: rarityRewards = {};
//Get data for this round from file
const {
dataArgs,
} = require(`../data/airdrops/rarityfarming/szn${taskArgs.season}/${filename}.ts`);
const data: RarityFarmingData = dataArgs;
const leaderboards = [
"withSetsRarityScore",
"kinship",
"experience",
// "kinship",
// "experience",
];
const dataNames: LeaderboardDataName[] = [
"rarityGotchis",
"kinshipGotchis",
"xpGotchis",
// "rookieKinshipGotchis",
// "rookieXpGotchis",
];
//handle rookie now
const leaderboardResults: RarityFarmingData = {
rarityGotchis: [],
xpGotchis: [],
kinshipGotchis: [],
};
// let extraFilter: string = "";
for (let index = 0; index < leaderboards.length; index++) {
// if (
// index === leaderboards.length - 1 ||
// index === leaderboards.length - 2
// ) {
// console.log("getting rookies");
// // extraFilter = rookieFilter;
// }
let element: LeaderboardType = leaderboards[index] as LeaderboardType;
const result = stripGotchis(
await fetchAndSortLeaderboard(
element,
taskArgs.blockNumber,
Number(taskArgs.tieBreakerIndex)
)
);
const dataName: LeaderboardDataName = dataNames[
index
] as LeaderboardDataName;
const correct = confirmCorrectness(result, data[dataName]);
console.log("correct:", correct);
if (correct !== 7500) {
throw new Error("Results do not line up with subgraph");
}
leaderboardResults[dataName] = result;
}
//get rewards
const rarityRoundRewards: string[] = rewards.rarity;
const kinshipRoundRewards: string[] = rewards.kinship;
const xpRoundRewards: string[] = rewards.xp;
// const rookieKinshipRoundRewards: string[] = rewards.rookieKinship;
// const rookieXpRoundRewards: string[] = rewards.rookieXp;
//Iterate through all 5000 spots
for (let index = 0; index < 7500; index++) {
const gotchis: string[] = [
leaderboardResults.rarityGotchis[index],
leaderboardResults.kinshipGotchis[index],
leaderboardResults.xpGotchis[index],
// leaderboardResults.rookieKinshipGotchis[index],
// leaderboardResults.rookieXpGotchis[index],
];
const rewards: string[][] = [
rarityRoundRewards,
kinshipRoundRewards,
xpRoundRewards,
// rookieKinshipRoundRewards,
// rookieXpRoundRewards,
];
rewards.forEach((leaderboard, i) => {
const gotchi = gotchis[i];
const reward = leaderboard[index];
if (finalRewards[gotchi])
finalRewards[gotchi] += Number(reward) / rounds;
else {
finalRewards[gotchi] = Number(reward) / rounds;
}
});
}
//Check that sent amount matches total amount per round
const roundAmount = Number(taskArgs.totalAmount) / rounds;
let talliedAmount = 0;
Object.keys(finalRewards).map((gotchiId) => {
const amount = finalRewards[gotchiId];
if (!isNaN(amount)) {
talliedAmount = talliedAmount + amount;
}
});
const sorted: string[] = [];
const sortedKeys = Object.keys(finalRewards).sort((a, b) => {
return finalRewards[b] - finalRewards[a];
});
sortedKeys.forEach((key) => {
sorted.push(`${key}: ${finalRewards[key]}`);
});
console.log("Total GHST to send:", talliedAmount);
console.log("Round amount:", roundAmount);
let totalGhstSent = BigNumber.from(0);
let txData = [];
let txGroup: TxArgs[] = [];
let tokenIdsNum = 0;
for (const gotchiID of Object.keys(finalRewards)) {
let amount = finalRewards[gotchiID];
let parsedAmount = BigNumber.from(parseEther(amount.toString()));
let finalParsed = parsedAmount.toString();
if (maxProcess < tokenIdsNum + 1) {
txData.push(txGroup);
txGroup = [];
tokenIdsNum = 0;
}
txGroup.push({
tokenID: gotchiID,
amount: amount,
parsedAmount: finalParsed,
});
tokenIdsNum += 1;
}
if (tokenIdsNum > 0) {
txData.push(txGroup);
txGroup = [];
tokenIdsNum = 0;
}
for (const [i, txGroup] of txData.entries()) {
console.log("current index:", i);
if (i < 10) continue;
let tokenIds: string[] = [];
let amounts: string[] = [];
const removeList = ["17231", "21129", "21944", "16681"];
txGroup.forEach((sendData) => {
if (removeList.includes(sendData.tokenID)) {
console.log(
`Removing ${sendData.tokenID} because it's on the bad list`
);
} else {
tokenIds.push(sendData.tokenID);
amounts.push(sendData.parsedAmount);
}
});
let totalAmount = amounts.reduce((prev, curr) => {
return BigNumber.from(prev).add(BigNumber.from(curr)).toString();
});
totalGhstSent = totalGhstSent.add(totalAmount);
console.log(
`Sending ${formatEther(totalAmount)} GHST to ${
tokenIds.length
} Gotchis (from ${tokenIds[0]} to ${tokenIds[tokenIds.length - 1]})`
);
const escrowFacet = (
await hre.ethers.getContractAt("EscrowFacet", diamondAddress)
).connect(managedSigner) as EscrowFacet;
const tx = await escrowFacet.batchDepositGHST(tokenIds, amounts, {
gasPrice: gasPrice,
});
let receipt: ContractReceipt = await tx.wait();
console.log("receipt:", receipt.transactionHash);
console.log("Gas used:", strDisplay(receipt.gasUsed.toString()));
if (!receipt.status) {
throw Error(`Error:: ${tx.hash}`);
}
console.log("Total GHST Sent:", formatEther(totalGhstSent));
}
}
);
Example #24
Source File: WalletConnect.tsx From useDApp with MIT License | 4 votes |
export function WalletConnect() {
const { account, activate, chainId, deactivate, library } = useEthers()
const [signedMessage, setSignedMessage] = useState('')
async function onConnect() {
try {
const provider = new WalletConnectProvider({
infuraId: 'd8df2cb7844e4a54ab0a782f608749dd',
})
await provider.enable()
await activate(provider)
} catch (error) {
console.error(error)
}
}
async function onDisconnect() {
deactivate()
localStorage.removeItem('walletconnect')
setSignedMessage('')
}
async function onSign() {
const msg = 'I sign Wallet Connect test message on @usedapp'
const provider = library as Web3Provider
try {
const signedMsg = await provider.getSigner().signMessage(msg)
setSignedMessage(signedMsg)
} catch (error) {
console.error(error)
}
}
const userBalance = useEtherBalance(account)
const stakingBalance = useEtherBalance(STAKING_CONTRACT)
return (
<MainContent>
<Container>
<Section>
<SectionRow>
<Title>WalletConnect Usage Example</Title>
<Button onClick={account ? onDisconnect : onConnect}>{account ? 'Disconnect' : 'Connect'}</Button>
</SectionRow>
<ContentBlock>
{chainId && account && (
<ContentRow>
<Label>Active Chain ID:</Label> <TextInline>{chainId}</TextInline>{' '}
</ContentRow>
)}
{account && (
<ContentRow>
<Label>Account:</Label> <TextInline>{account}</TextInline>
</ContentRow>
)}
{userBalance && (
<ContentRow>
<Label>Ether balance:</Label> <TextInline>{formatEther(userBalance)}</TextInline> <Label>ETH</Label>
</ContentRow>
)}
{stakingBalance && (
<ContentRow>
<Label>ETH2 staking contract holds:</Label> <TextInline>{formatEther(stakingBalance)}</TextInline>{' '}
<Label>ETH</Label>
</ContentRow>
)}
{signedMessage && account && (
<ContentRow>
<Label>Signed message signature:</Label>{' '}
<TextInline style={{ overflowWrap: 'break-word' }}>{signedMessage}</TextInline>{' '}
</ContentRow>
)}
</ContentBlock>
{account && (
<SectionRow style={{ marginTop: '20px', display: 'flex', justifyContent: 'flex-end' }}>
<Button onClick={onSign}>Sign message</Button>
</SectionRow>
)}
</Section>
</Container>
</MainContent>
)
}
Example #25
Source File: index.ts From snapshot-strategies with MIT License | 4 votes |
export async function strategy(
space,
network,
provider,
addresses,
options,
snapshot
) {
const pools = await getPools(provider, snapshot);
const userPoolBalance = await getSmartChefStakedCakeAmount(
snapshot,
pools.map((p) => p.id),
addresses
);
const blockTag = typeof snapshot === 'number' ? snapshot : 'latest';
if (
blockTag === 'latest' ||
(typeof blockTag === 'number' &&
blockTag >= onChainVotingPower.v0.blockNumber)
) {
let callData = addresses.map((address: any) => [
typeof blockTag === 'number' &&
blockTag < onChainVotingPower.v1.blockNumber
? onChainVotingPower.v0.address
: onChainVotingPower.v1.address,
'getVotingPowerWithoutPool',
[address.toLowerCase()]
]);
callData = [...chunk(callData, options.max || 300)];
const response: any[] = [];
for (const call of callData) {
const multiRes = await multicall(network, provider, abi, call, {
blockTag
});
response.push(...multiRes);
}
return Object.fromEntries(
response.map((value, i) => [
addresses[i],
parseFloat(
formatEther(
(userPoolBalance[addresses[i].toLowerCase()] || Zero).add(
value.toString()
)
)
)
])
);
}
const erc20Balance = await erc20BalanceOfStrategy(
space,
network,
provider,
addresses,
{
address: CAKE_ADDRESS,
symbol: 'CAKE',
decimals: 18
},
snapshot
);
const cakeBnbLpBalance = await masterChefPoolBalanceStrategy(
space,
network,
provider,
addresses,
{
chefAddress: MASTER_CHEF_ADDRESS.v1,
uniPairAddress: CAKE_BNB_LP_ADDRESS,
pid: '251',
symbol: 'CAKE-BNB LP',
tokenIndex: 0
},
snapshot
);
const cakeVaultBalance = await getVaultBalance(
network,
provider,
addresses,
blockTag
);
return Object.fromEntries(
addresses.map((address) => [
address,
erc20Balance[address] +
cakeBnbLpBalance[address] +
parseFloat(
formatEther(
(userPoolBalance[address.toLowerCase()] || Zero).add(
cakeVaultBalance[address] || Zero
)
)
)
])
);
}
Example #26
Source File: index.ts From snapshot-strategies with MIT License | 4 votes |
export async function strategy(
_space,
_network,
_provider,
_addresses,
_options,
_snapshot
) {
const score: Record<string, number> = {};
const blockTag = typeof _snapshot === 'number' ? _snapshot : 'latest';
const L2BlockTag =
typeof _options.L2BlockNumber === 'number'
? _options.L2BlockNumber
: 'latest';
const optimismProvider = getProvider('10');
const L1SDSValue = await calculateSDSValue(
_provider,
_snapshot,
_options.L1DebtCache,
_options.L1SDS
);
const L2SDSValue = await calculateSDSValue(
optimismProvider,
L2BlockTag,
_options.L2DebtCache,
_options.L2SDS
);
const callL1SDSBalance = new Multicaller(_network, _provider, SDSABI, {
blockTag
});
for (const walletAddress of _addresses) {
callL1SDSBalance.call(walletAddress, _options.L1SDS, 'balanceOf', [
walletAddress
]);
}
const L1SDSBalances: Record<
string,
BigNumber
> = await callL1SDSBalance.execute();
Object.entries(L1SDSBalances).forEach(([address, balance]) => {
score[getAddress(address)] = Number(formatEther(balance)) * L1SDSValue;
});
const callL2SDSBalance = new Multicaller('10', optimismProvider, SDSABI, {
blockTag: L2BlockTag
});
for (const walletAddress of _addresses) {
callL2SDSBalance.call(walletAddress, _options.L2SDS, 'balanceOf', [
walletAddress
]);
}
const L2SDSBalances: Record<
string,
BigNumber
> = await callL2SDSBalance.execute();
Object.entries(L2SDSBalances).forEach(([address, balance]) => {
score[getAddress(address)] += Number(formatEther(balance)) * L2SDSValue;
});
/** Quadratic Weighting */
if (_options.quadratic) {
return Object.fromEntries(
Object.entries(score).map(([address, balance]) => [
address,
Math.sqrt(balance)
])
);
} else {
return score;
}
}