Is there a way to check the balances of the accounts generated when running npx hardhat node?
I mean printing them on the console like when you first boot up the network, not fetching them through js or any script
Accounts
========
WARNING: These accounts, and their private keys, are publicly known.
Any funds sent to them on Mainnet or any other live network WILL BE LOST.
Account #0: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
Account #1: 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 (10000 ETH)
Private Key: 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d
Account #2: 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC (10000 ETH)
Private Key: 0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a
Account #3: 0x90F79bf6EB2c4f870365E785982E1f101E93b906 (10000 ETH)
Private Key: 0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
Account #4: 0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65 (10000 ETH)
Private Key: 0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a
Account #5: 0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc (10000 ETH)
Private Key: 0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba
Account #6: 0x976EA74026E726554dB657fA54763abd0C3a0aa9 (10000 ETH)
Private Key: 0x92db14e403b83dfe3df233f83dfa3a0d7096f21ca9b0d6d6b8d88b2b4ec1564e
Account #7: 0x14dC79964da2C08b23698B3D3cc7Ca32193d9955 (10000 ETH)
Private Key: 0x4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356
Account #8: 0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f (10000 ETH)
Private Key: 0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97
Account #9: 0xa0Ee7A142d267C1f36714E4a8F75612F20a79720 (10000 ETH)
Private Key: 0x2a871d0798f97d79848a013d4936a73bf4cc922c825d33c1cf7073dff6d409c6
Account #10: 0xBcd4042DE499D14e55001CcbB24a551F3b954096 (10000 ETH)
Private Key: 0xf214f2b2cd398c806f84e317254e0f0b801d0643303237d97a22a48e01628897
WARNING: These accounts, and their private keys, are publicly known.
Any funds sent to them on Mainnet or any other live network WILL BE LOST.
Hardhat config defines the accounts task by default. It only prints the addresses but you can modify it to retrieve and print the balances as well:
hardhat.config.js
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
const provider = hre.ethers.provider;
for (const account of accounts) {
console.log(
"%s (%i ETH)",
account.address,
hre.ethers.utils.formatEther(
// getBalance returns wei amount, format to ETH amount
await provider.getBalance(account.address)
)
);
}
});
Output of npx hardhat accounts
0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000 ETH)
0x70997970C51812dc3A010C7d01b50e0d17dc79C8 (10000 ETH)
0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC (10000 ETH)
...
You can also use the provider.getBalance() function to retrieve an account balance during runtime of your JS code.
Related
While attempting to fund me contract is tell me it encountered an error without specifying the error. I attempted to fund 0.1 eth through the fund function, and in the terminal it says:
[block:8404521 txIndex:12]
from: 0x8a9...e4303
to: FundMe.fund() 0x542...E109C
value: 100000000000000000 wei
data: 0xb60...d4288
logs: 0
hash: 0x29a...97939
and in the etherscan it says:status fail :
Contract 0x5422f3458be343e378e7a399e16fff548e7e109c
Warning! Error encountered during contract execution [execution reverted]
I tried looking for problems with my code and found none.
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6 <0.9.0;
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
//import "#chainlink/contracts/src/v0.8/vendor/SafeMathChainlink.sol"; won't need in later complier versions.
contract FundMe {
mapping(address => uint256) public addressToAmountFunded;
function fund() public payable {
uint256 minimumUSD = 50 * 10 ** 18;
require( getConversionRate(msg.value) >= minimumUSD,"You need to send more Eth");
addressToAmountFunded[msg.sender] += msg.value;
}
function getVersion() public view returns (uint256){
AggregatorV3Interface priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
return priceFeed.version();
}
function getPrice() public view returns (uint256){
AggregatorV3Interface priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
(,int256 answer,,,)=priceFeed.latestRoundData();
return uint256(answer * 10000000000);
}
//10000000000 = Gwei which is why we added 10 zeros to getPrice(answer) to convert it to Wei amount
function getConversionRate(uint256 ethAmount) public view returns (uint256){
uint256 ethPrice = getPrice();
uint256 ethAmountInUsd = (ethPrice * ethAmount)/ 1000000000000000000; //divide 2x because we added 10*((getPrice)answer))
return ethAmountInUsd;
}
}
Aggregator contract address "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419" belongs to mainnet
From here get the ETH/USD goerli testnet address:"0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e"
Now in order to call chainlink oracle you have to have LINK token in your contract. Get some link token to your conract address from the faucet
Import the token in metamask. you will see the amount
send link token from your metamask to your contract
deploy your contract. if you are using Remix IDE chose the injected provider to connect to metamask. Because chainlink contract is on goerli, so you need to be on Goerli testnet. Once deployment goes through you can call the fund function.
Since the fund function has no argument, you need to send the value alongside the transaction. That is why inside the function you have msg.value to access to the sent amount.
In Remix ide, under "GAS LIMITinput there isVALUEinput. you need to pass the amount in there before you call thefund` function.
https://github.com/balancer-labs/balancer-core/issues/249
Hello, I am Developing this BalancerOperator.sol Smart Contract:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;
pragma experimental ABIEncoderV2;
import "#openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IBPool.sol";
import "./IVault.sol";
/// #title Balancer Pool Operator Example.
/// #author Ignacio Ceaglio for 10Clouds.
/*
* - Balancer 50%USDC/50%WETH Pool and L.P. Token Smart Contract Address:
* - 0x96646936b91d6B9D7D0c47C496AfBF3D6ec7B6f8
* - Balancer 50%USDC/50%WETH Vault Smart Contract Address:
* - 0xBA12222222228d8Ba445958a75a0704d566BF2C8
* - Balancer 50%USDC/50%WETH Vault Authorizer Smart Contract Address:
* - 0xa331d84ec860bf466b4cdccfb4ac09a1b43f3ae6
* The Vault holds all pool tokens and performs the related bookkeeping. It serves
* as a single entry point for pool interactions like joins, exits and swaps and
* delegates to the respective pools.
* - Pool ID: 0x96646936b91d6b9d7d0c47c496afbf3d6ec7b6f8000200000000000000000019
* Index 0: USDC - 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
* Index 1: WETH - 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
*/
contract BalancerOperator is IVault {
/** #dev When providing your assets, you must ensure that the tokens are sorted numerically by token address. It's also important
to note that the values in maxAmountsIn correspond to the same index value in assets, so these arrays must be made in parallel
after sorting.*/
function addLiquidity(
address vaultAddr,
bytes32 poolId,
address[] calldata assets,
uint256[] calldata maxAmountsIn
) external {
uint256 oneUint256 = 1;
bytes memory userDataEncoded = abi.encode(oneUint256, maxAmountsIn, oneUint256); //https://dev.balancer.fi/helpers/encoding
JoinPoolRequest memory InRequest = JoinPoolRequest(assets, maxAmountsIn, userDataEncoded, false);
IVault(vaultAddr).joinPool(poolId, msg.sender, msg.sender, InRequest);
}
/** #dev When providing your assets, you must ensure that the tokens are sorted numerically by token address. It's also important
to note that the values in maxAmountsIn correspond to the same index value in assets, so these arrays must be made in parallel
after sorting.*/
function removeLiquidity(
address vaultAddr,
bytes32 poolId,
address[] calldata assets,
uint256[] calldata minAmountsOut
) external {
uint256 oneUint256 = 1;
bytes memory userDataEncoded = abi.encode(oneUint256, minAmountsOut, oneUint256); //https://dev.balancer.fi/helpers/encoding
ExitPoolRequest memory OutRequest = ExitPoolRequest(assets, minAmountsOut, userDataEncoded, false);
IVault(vaultAddr).exitPool(poolId, msg.sender, payable(msg.sender), OutRequest);
}
function exchangeTokens(
//address poolAddr,
address vaultAddr,
bytes32 poolId,
address tokenInAddress,
uint256 maxAmountIn,
address tokenOutAddress
) external {
uint256 oneUint256 = 1;
//uint256 maxPrice = (110 * IBPool(poolAddr).getSpotPrice(tokenInAddress, tokenOutAddress)) / 100;
//uint256 tokenAmountOut = maxPrice * maxAmountIn;
/**IERC20(tokenInAddress).approve(address(this), maxAmountIn);
IERC20(tokenInAddress).transferFrom(msg.sender, address(this), maxAmountIn);
IERC20(tokenInAddress).approve(vaultAddr, maxAmountIn);*/
bytes memory userDataEncoded = abi.encode(oneUint256, maxAmountIn, oneUint256); //https://dev.balancer.fi/helpers/encoding
SingleSwap memory SingleSwapRequest = SingleSwap(
poolId,
SwapKind.GIVEN_OUT,
tokenInAddress,
tokenOutAddress,
maxAmountIn,
userDataEncoded
);
FundManagement memory FundManagementRequest = FundManagement(msg.sender, false, payable(msg.sender), false);
IVault(vaultAddr).swap(SingleSwapRequest, FundManagementRequest, maxAmountIn, (block.timestamp + 3 minutes));
//IERC20(tokenOutAddress).transfer(msg.sender, tokenAmountOut);
}
//...
}
and when I try to test it with Hardhat by Forking the Ethereum MainNet, I have this Error Log:
1) Balancer Pool S.Contract
Balancer Pool Adds Liquidity:
Error: VM Exception while processing transaction: reverted with reason string 'BAL#401'
at <UnrecognizedContract>.<unknown> (0xba12222222228d8ba445958a75a0704d566bf2c8)
at BalancerOperator.addLiquidity (contracts/swaps/Balancer/BalancerOperator.sol:39)
at async HardhatNode._mineBlockWithPendingTxs (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:1773:23)
at async HardhatNode.mineBlock (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:466:16)
at async EthModule._sendTransactionAndReturnHash (node_modules\hardhat\src\internal\hardhat-network\provider\modules\eth.ts:1504:18)
at async HardhatNetworkProvider.request (node_modules\hardhat\src\internal\hardhat-network\provider\provider.ts:118:18)
at async EthersProviderWrapper.send (node_modules\#nomiclabs\hardhat-ethers\src\internal\ethers-provider-wrapper.ts:13:20)
2) Balancer Pool S.Contract
Balancer Pool Removes Liquidity:
Error: VM Exception while processing transaction: reverted with reason string 'BAL#401'
at <UnrecognizedContract>.<unknown> (0xba12222222228d8ba445958a75a0704d566bf2c8)
at BalancerOperator.removeLiquidity (contracts/swaps/Balancer/BalancerOperator.sol:54)
at async HardhatNode._mineBlockWithPendingTxs (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:1773:23)
at async HardhatNode.mineBlock (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:466:16)
at async EthModule._sendTransactionAndReturnHash (node_modules\hardhat\src\internal\hardhat-network\provider\modules\eth.ts:1504:18)
at async HardhatNetworkProvider.request (node_modules\hardhat\src\internal\hardhat-network\provider\provider.ts:118:18)
at async EthersProviderWrapper.send (node_modules\#nomiclabs\hardhat-ethers\src\internal\ethers-provider-wrapper.ts:13:20)
3) Balancer Pool S.Contract
Balancer Pool Exchanges Tokens:
Error: VM Exception while processing transaction: reverted with reason string 'BAL#401'
at <UnrecognizedContract>.<unknown> (0xba12222222228d8ba445958a75a0704d566bf2c8)
at BalancerOperator.exchangeTokens (contracts/swaps/Balancer/BalancerOperator.sol:83)
at async HardhatNode._mineBlockWithPendingTxs (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:1773:23)
at async HardhatNode.mineBlock (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:466:16)
at async EthModule._sendTransactionAndReturnHash (node_modules\hardhat\src\internal\hardhat-network\provider\modules\eth.ts:1504:18)
at async HardhatNetworkProvider.request (node_modules\hardhat\src\internal\hardhat-network\provider\provider.ts:118:18)
at async EthersProviderWrapper.send (node_modules\#nomiclabs\hardhat-ethers\src\internal\ethers-provider-wrapper.ts:13:20)
The Balancer Documentation About the Error Code 401 says that the User(Sender) Is not Authorized to Perform the Transaction, and if This Part of your Documentation explains how to Authorize an User, it is not Straightforward and I don't seem to Understand it.
Could you please help me to Resolve this? Thanks in Advance and Have a Nice day! :D
per Balancer Error Codes looks like an allowance issue. Could be ERC20 allowance or that the pool you are depositing to is an investment pool w/ whitelisted accounts that can add liquidity.
The issue is a repeated error message upon attempting to compile a verifiable random number smart contract in remix. This particular function (line 48 in remix or last line of code below) yields the error message consistently across compiler versions (I checked the imported documents versions too), cross brave browser+firefox, and even after checking grammar. I do not understand what this error message is conveying (I am brand new to programming) and I cannot find another thread with this same issue. I suspect the function to be faulty in some sense of how it is either defined or interacting with the other imported documents (VRFConsumerBase.sol).
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "#chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
/**
* Request testnet LINK and ETH here: https://faucets.chain.link/
* Find information on LINK Token Contracts and get the latest ETH and LINK faucets here:
* https://docs.chain.link/docs/link-token-contracts/
*/
contract RandomNumberConsumer is VRFConsumerBase {
bytes32 public keyHash;
uint256 public fee;
uint256 public randomResult;
/**
* Constructor inherits VRFConsumerBase
*
* Network: Rinkeby
* Chainlink VRF Coordinator address: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B
* LINK token address: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709
* Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311
*/
constructor() VRFConsumerBase(
0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, //VRF Coordinator
0x01BE23585060835E02B77ef475b0Cc51aA1e0709) //Rinkeby LINK Token
{
keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
fee = 0.1 * 10 ** 18; //0.1 LINK (varies by network)
}
/**
* Requests fulfillRandomness
*/
function getRandomNumber() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
return requestRandomness(keyHash, fee);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomResult = randomness;
}
}
This near identical code can be found at https://docs.chain.link/docs/get-a-random-number/ (line 52).
Here is the error message below,
from solidity:
Warning: Unused function parameter. Remove or comment out the variable name to silence this warning.
--> docs.chain.link/samples/VRF/RandomNumberConsumer.sol:52:32: function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
I am following the 'Getting A Random Number with Chainlink VRF' tutorial from Chainlink
https://www.youtube.com/watch?v=JqZWariqh5s (timestamp # 9:30) except I am testing on the Rinkeby network not Kovan. I also double checked with this tutorial.
https://www.youtube.com/watch?v=_aXumgdpnPU (timestamp # 12:00)
Neither tutorial encounters this specific error message and both are able to compile and deploy the smart contract successfully. I also receive the error message when I directly open and attempt to compile the smart contract from the Chainlink website without touching the code.
i had the same error i fixed it by leaving the bytes32 parameter empty
your code
(bytes32 requestId , uint256 randomness)
instead use:
(bytes32, uint256 randomness)
I'm writing a contract that involves transferring an ERC-721 token from one user to another. In order to test that this works with existing NFT collections, I'm using ganache-cli to fork mainnet and impersonate the holder of the ERC-721 token in question. I've confirmed on Etherscan that the address I'm unlocking is indeed the holder of the ERC-721 token that I'm trying to transfer.
First, I'm forking mainnet using ganache-cli:
ganache-cli -f <INFURA_MAINNET_ENDPOINT> -d -i 66 1 --unlock <HOLDER_ADDRESS>
My smart contract code includes:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC721 {
function ownerOf(uint256 _tokenId) external returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
}
interface CryptopunkInterface {
function transferPunk(address _to, uint _tokenId) external;
}
and contains this function:
/// #dev Sells NFT into a bid (i.e., "hits" the bid)
/// #param _bidderAddress Address of the bidder
/// #param _nftAddress Address of collection to which the bid applies
/// #param _tokenId Token id of the NFT in question
/// #param _expectedWeiPriceEach Price (in wei) that seller expects to receive for each NFT
/// #return Proceeds remitted to seller
function hitBid(address _bidderAddress, address _nftAddress, uint256 _tokenId, uint256 _expectedWeiPriceEach) public returns (uint256) {
console.log("msg.sender of hitBid: ", msg.sender);
// Initialize bid
Bid memory bid = bids[_bidderAddress][_nftAddress];
// Require that bid exists
require(bid.quantity > 0, "This bid does not exist.");
// Require that bid amount is at least what the seller expects
require(bid.weiPriceEach >= _expectedWeiPriceEach, "Bid is insufficient.");
// Decrement bidder's bid quantity for this collection
bids[_bidderAddress][_nftAddress].quantity = bid.quantity - 1;
// Compute platform fee proceeds
uint256 platformFeeProceeds = bid.weiPriceEach * platformFee / 10000;
// Remit platform fee proceeds to owner
sendValue(OWNER, platformFeeProceeds);
// Transfer NFT to bidder
// Check whether _nftAddress is Cryptopunks address
if (_nftAddress == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB) {
CryptopunkInterface(_nftAddress).transferPunk(_bidderAddress, _tokenId);
} else {
console.log("ownerOf NFT being sold: ", IERC721(_nftAddress).ownerOf(_tokenId));
IERC721(_nftAddress).safeTransferFrom(msg.sender, _bidderAddress, _tokenId);
}
// Compute seller proceeds
uint256 sellerProceeds = bid.weiPriceEach - platformFeeProceeds;
// Remit seller proceeds to seller
sendValue(payable(msg.sender), sellerProceeds);
// Emit new trade event
emit NewTrade(_bidderAddress, msg.sender, _nftAddress, bid.weiPriceEach, 1, _tokenId);
// Return seller proceeds
return sellerProceeds;
}
When I run truffle test, executing the function on behalf of the unlocked holder address, I get this error:
Error: Returned error: VM Exception while processing transaction: revert ERC721: transfer caller is not owner nor approved -- Reason given: ERC721: transfer caller is not owner nor approved.
UPDATE:
I switched from using ganache-cli to using Hardhat to fork mainnet. I'm impersonating the relevant addresses in my test.js file:
const BAYC_HOLDER_ADDRESS = "0x54BE3a794282C030b15E43aE2bB182E14c409C5e";
await hre.network.provider.request({
method: "hardhat_impersonateAccount",
params: [BAYC_HOLDER_ADDRESS],
});
I've also verified that msg.sender of hitBid is indeed the ownerOf the NFT in question with the console.log statements above.
msg.sender of hitBid: 0x54be3a794282c030b15e43ae2bb182e14c409c5e
ownerOf NFT being sold: 0x54be3a794282c030b15e43ae2bb182e14c409c5e
Nonetheless, I'm still getting the same error:
Error: VM Exception while processing transaction: reverted with reason string 'ERC721: transfer caller is not owner nor approved'
The reason you are getting this error is because msg.sender of hitBid() is not the same as msg.sender of IERC721(_nftAddress).safeTransferFrom().
The seller needs to sign two transactions:
The user needs to sign approve(yourContractAddress, tokenId)
The user needs to sign hitBid()
That will prevent hitBid() from reverting, since your contract address (msg.sender of safeTransferFrom()) will then be approved to make the transfer.
I am running ganache-cli through a node application:
const ganache = require('ganache-core');
const ethers = require('ethers');
const provider = new ethers.providers.Web3Provider(
ganache.provider({
total_accounts: 5,
account_keys_path: './accounts.json',
gasPrice: 20000000000,
gasLimit: 20000000000,
default_balance_ether: 100
})
);
This runs the ganache-cli and output acocunt details in accounts.json. The file looks like this:
{
"addresses":{
"0x73f5b3f74db1b37927696c280c04d544f4e9ff64":{
"secretKey":{
"type":"Buffer",
"data":[88, 17, .....]
},
"publicKey":{
"type":"Buffer",
"data":[13, 52, .....]
},
"address":"0x73f5b3f74db1b37927696c280c04d544f4e9ff64",
"account":{
"nonce":"0x",
"balance":"0x056bc75e2d63100000",
"stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"codeHash":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
}
}
}
}
I can see the account address, but how can I decode/get the private key from this information?
You cannot get the private key from accounts directly, but there's a few workarounds to do this with ganache-cli.
Specify a mnemonic phrase with the -m option, e.g. ganache-cli -m "stereo consider quality wild fat farm symptom bundle laundry side one lemon", this will derive private keys from the mnemonic phrase (with the derivation path m/44'/60'/0'/0/n.
Use the --account_keys_path option to save all private keys to a file, e.g. ganache-cli --account_keys_path keys.json. This will result in a JSON file with all addresses, private keys and public keys.
Use the --account option to manually specify a private key and balance, e.g. ganache-cli --account "0x31c354f57fc542eba2c56699286723e94f7bd02a4891a0a7f68566c2a2df6795,1000000000000000000". This will assign 1 ETH (= 1000000000000000000 Wei) to the address corresponding to this private key. You can use the --account option multiple times, with different private keys.