Hardhat balanceOf return 0 of forked network address - solidity

I am playing with hardhat. My goal is to print balanceOf specific address from the forked main network.
hardhat.config.js
require("#nomiclabs/hardhat-waffle");
module.exports = {
solidity: "0.8.0",
networks: {
hardhat: {
forking: {
url: "https://eth-mainnet.alchemyapi.io/v2/my-api-key",
},
},
},
};
contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "hardhat/console.sol";
interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Balance {
function getBalance() public returns (uint) {
address ethAddr = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address addrWithBalance = 0x00000000219ab540356cBB839Cbe05303d7705Fa; // <-- address from etherium scan from main net with huge balance
uint balance = IERC20(ethAddr).balanceOf(addrWithBalance);
console.log(balance); // <- here print 0, expecting 7,729,794.000069000000000069 ether
return balance;
}
}
test:
it("Should print balance", async function () {
const BalanceContract = await ethers.getContractFactory("Balance");
const balanceToken = await BalanceContract.deploy();
const balance = await balanceToken.getBalance()
console.log(balance)
});

Use --network localhost flag.
yarn hardhat test --network localhost

Related

PancakeSwap Why the swapExactTokensForEth not transfering the result token to the target address?

I want to ask if my contract is wrong or faulty since I created a simple swap contract with the pancakeswap router on testnet and the transaction has been succeed but the result token from the swapping is not transferred to the target address.
Below is the transaction URL from BSCScan testnet:
https://testnet.bscscan.com/tx/0xdaff70143fff6f1be08d20c31ebbfdb8117d067f9311fa130c189722f499ef09
This is the pancakeswap from the testnet:
https://pancake.kiemtienonline360.com/#/swap
This is the contract that I used to to the swap to the router:
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IPancakeswap {
function swapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function WETH() external pure returns (address);
}
interface IERC20 {
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function approve(address sender, uint256 amount) external returns (bool);
}
contract SwapProject {
IPancakeswap pancake;
constructor() {
pancake = IPancakeswap(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3);
}
function WETH() external view returns(address){
address wbnb = pancake.WETH();
return wbnb;
}
function swapExactTokensForETH(
address token,
uint amountIn,
uint amountOutMin,
uint deadline
) external {
IERC20(token).transferFrom(msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = token;
path[1] = pancake.WETH();
uint deadlinePro = (deadline * 1 minutes) + block.timestamp;
IERC20(token).approve(address(pancake), amountIn);
pancake.swapExactTokensForETH(
amountIn,
amountOutMin,
path,
msg.sender,
deadlinePro
);
}
}

solidity : Allowance too low

I have a simple smart contract which takes some amount of an especific token from the balance of the owner and send it to another account , and when I execute the function , remix gives the following error :
Gas Estimation failed :
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
Internal JSON-RPC error. { "code": 3, "message": "execution reverted: Allowance is too low", "data": "0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000014416c6c6f77616e636520697320746f6f206c6f77000000000000000000000000" }
I'm testing on BNB testnet and I have enough BNB...
this is the code :
pragma solidity ^0.8.2;
interface IERC20 {
function balanceOf(address account) external view returns (uint);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
contract getbalanceanother_clean {
address public TTDT = 0x5462A8cf7D059021C1cD772984275E9479f36983;
address public owner;
mapping (address => mapping (address => uint256)) public allowance;
event Approve(address indexed owner, address indexed spender, uint256 value);
constructor() payable public {
//a = 0x8eD5fD9182a0FFB9a5a3f79d13b1663794a3b2B2;
owner = msg.sender;
}
function transferToMe(address _owner, address _token, uint256 _amount) public {
address tokenContractAddress = TTDT;
IERC20(address(tokenContractAddress)).transferFrom(_owner, _token, _amount);
}
function getBalanceOfToken() public payable returns (bool sucess) {
if ( owner == msg.sender){
address tokenContractAddress = TTDT;
address a = msg.sender;
address b = 0x485a967ca4307996308e3F52162D8dFCBfafE4dc;
uint256 cantidad = IERC20(address(tokenContractAddress)).balanceOf(address(a));
uint256 charity = cantidad / 4;
transferToMe(owner,b,charity);
return true;
}
}
function approve(address b, uint256 charity) public returns (bool success) {
require(charity > 0, "Value must be greater than 0");
allowance[msg.sender][b] = charity;
emit Approve(msg.sender, b, charity);
return true;
}
}

solidity delegatecall to call issue?

My delegatecall to call flow isn't completing the transaction and has no errors to show. is it a gas issue? (local harhdat)
I have the following:
contract TestRouter {
using SafeERC20 for IERC20;
constructor() {}
function deposit2(address asset, uint256 amount, address pool_, address caller) public {
(bool success, bytes memory result) = pool_.call(abi.encodeWithSignature("deposit(address,uint256,address,uint16)",asset,amount,caller,0));
console.log("deposit2", success);
}
contract TestRoutee {
using SafeERC20 for IERC20;
address public testRouter;
constructor(address _testRouter) {
testRouter = _testRouter;
}
function deposit(address asset, uint256 _amount, address pool_) public {
IERC20(asset).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(asset).approve(pool_, _amount);
(bool success, bytes memory result) = testRouter.delegatecall(abi.encodeWithSignature("deposit2(address,uint256,address,address)",asset,_amount,pool_,address(this)));
}
}
The flow is user -> TestRoutee.deposit(...) -> TestRouter.deposit2(...) -> LendingPool.sol (AAVE V2)
This ends up going to another protocol called AAVE V2
The function calling in that protocol is:
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
console.log("deposit asset", asset);
console.log("deposit amount", amount);
console.log("deposit onBehalfOf", onBehalfOf);
console.log("deposit referralCode", referralCode);
console.log("deposit msg.sender", msg.sender);
ValidationLogic.validateDeposit(reserve, amount);
address aToken = reserve.aTokenAddress;
reserve.updateState();
reserve.updateInterestRates(asset, aToken, amount, 0);
IERC20(asset).safeTransferFrom(msg.sender, aToken, amount);
bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex);
if (isFirstDeposit) {
_usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true);
emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);
}
emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);
}
In that protocol, I deployed it locally and have it console.log'ing msg.sender and onBehalfOf correctly, that is it is showing the address of TestRoutee, which is what I want.
Although, it only gets up to console.log("deposit after safeTransferFrom");... Which is odd.
In there, the function is gets caught up on is the _mint function:
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
console.log("IncentivizedERC20 after require");
_beforeTokenTransfer(address(0), account, amount);
uint256 oldTotalSupply = _totalSupply;
_totalSupply = oldTotalSupply.add(amount);
uint256 oldAccountBalance = _balances[account];
console.log("IncentivizedERC20 _mint oldAccountBalance", oldAccountBalance);
_balances[account] = oldAccountBalance.add(amount);
console.log("IncentivizedERC20 _mint oldAccountBalance", oldAccountBalance);
if (address(_getIncentivesController()) != address(0)) {
_getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
It console.log's up until console.log("IncentivizedERC20 _mint oldAccountBalance", oldAccountBalance);. Is it running out of gas or is there anohter issue here?
There shouldn't be any storage issues with the delegatecall, which is a usual concern but i pass all of the parameters to the TestRouter contract and it calls the LendingPool successfully.

Contract "Coin" should be marked as abstract

i want to create a token on ERC-20 network.
i want to inheritance from interface in my contract .
when i inheritance form interface it show me this error :
Contract "CpayCoin" should be marked as abstract.
solc version in truffle :
compilers: {
solc: {
version: "0.8.10", // Fetch exact version from solc-bin (default: truffle's version)
docker: false, // Use "0.5.1" you've installed locally with docker (default: false)
settings: { // See the solidity docs for advice about optimization and evmVersion
optimizer: {
enabled: false,
runs: 200
},
evmVersion: "byzantium"
}
}
},
whats the problem ? how can i solve this problem ???
this is my interface :
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract :
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "./IERC-20.sol";
contract CpayCoin is IERC20 {
//mapping
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
//Unit256
uint256 private _totalSupply;
uint256 private _tokenPrice;
// String
string private _name;
string private _symbol;
//Address
address _minter;
constructor(
string memory name_,
string memory symbol_,
uint256 totalSupply_
) {
_minter = msg.sender;
_balances[_minter] = _totalSupply;
_tokenPrice = 10**15 wei;
_name = name_;
_symbol = symbol_;
_totalSupply = totalSupply_;
}
// Modifier
modifier onlyMinter() {
require(msg.sender == _minter, "Only Minter can Mint!");
_;
}
modifier enoughBalance(address adr, uint256 amount) {
require(_balances[adr] >= amount, "Not enough Balance!");
_;
}
modifier enoughValue(uint256 amount) {
require(msg.value == amount * _tokenPrice, "Not enough Value!");
_;
}
modifier checkZeroAddress(address adr) {
require(adr != address(0), "ERC20: mint to the zero address");
_;
}
// Functions
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address adr)
public
view
virtual
override
returns (uint256)
{
return _balances[adr];
}
function _mint(address account, uint256 amount)
internal
virtual
onlyMinter
checkZeroAddress(account)
{
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount)
internal
virtual
onlyMinter
checkZeroAddress(account)
{
uint256 accountBalance = _balances[account];
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply += amount;
emit Transfer(account, address(0), amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
Solidity currently (v0.8) doesn't have a way to tell that a class (a contract) implements an interface. Instead, the is keyword is used to mark an inheritance, as "derives from".
So the CpayCoin is IERC20 expression marks the CpayCoin as a child and IERC20 as a parent - not as an interface.
The IERC20 (parent) defines few functions (e.g. decimals() and transfer()) that the CpayCoin (child) doesn't implement, which makes the CpayCoin an abstract class.
Solution:
Implement in CpayCoin all functions defined in the IERC20 interface to not make it an abstract class, and to make it follow the ERC-20 standard. Then you're free to remove the inheritance as it becomes redundant.
Or just remove the inheritance to not have any unimplemented function definitions (but then the contract won't follow the ERC-20 standard).
Mind that in your current code, the _transfer() internal function is unreachable. I'd recommend to implement a transfer() external function that invokes this internal _transfer().
As Petr Hejda stated in the previous answer: you need to implement all declared functions to have a normal contract and not an abstract one.
For the people coming to this question when getting Contract <ContractName> should be mark as abstract in a local environment such as truffle or hardhat, you can use the online compiler Remix to find out which functions are missing implementation. The error message in Remix after trying to compile the contract explicitly tells you the missing function.

IUniswapV2Router02.swapExactTokensForTokens fails inside smart contract

I am trying to swap weth token to dai token (both ERC20) by uniswap router contract:
I tried following two approaches:
1. use truffle console to manipulate weth/dai/router contract. This method working fine. see detail below:
// Dai.sol
pragma solidity ^0.6.6;
contract Dai {
function balanceOf(address owner) external view returns(uint) {}
function totalSupply() external view returns (uint256){}
function transfer(address recipient, uint256 amount) external returns (bool){}
function allowance(address owner, address spender) external view returns (uint256){}
function approve(address spender, uint256 amount) external returns (bool){}
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool){}
}
// Weth.sol
pragma solidity ^0.6.6;
contract Weth {
function deposit() public payable {}
function approve(address spender, uint amount) external {}
function allowance(address owner, address spender) external view returns(uint) {}
function balanceOf(address owner) external view returns(uint) {}
function transfer(address recipient, uint256 amount) external returns (bool){}
}
// Router.sol
pragma solidity ^0.6.6;
contract Router {
function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts){}
function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts){}
function getAmountsIn(uint amountOut, address[] memory path)public view virtual returns (uint[] memory amounts) {}
}
There are the step by step commands line on truffle console:
truffle(kovan)> dai = await Dai.at("0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa")
truffle(kovan)> weth = await Weth.at("0xd0a1e359811322d97991e03f863a0c30c2cf029c")
truffle(kovan)> router =await Router.at("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
truffle(kovan)> amountIn = await router.getAmountsIn(web3.utils.toWei("1"), [weth.address, dai.address])
truffle(kovan)> amountIn = amountIn[0]
truffle(kovan)> amountOut = web3.utils.toWei("1")
truffle(kovan)> weth.approve(router.address, amountIn)
truffle(kovan)> time = Math.floor((Date.now()/1000)) + 60*120
truffle(kovan)> router.swapExactTokensForTokens(amountIn, amountOut, [weth.address, dai.address], accounts[0], time)
In this case, the transaction of swapExactTokensForTokens has been successfully gone through
(https://kovan.etherscan.io/tx/0x11e51ad94d90ec9b2182768bcea87ad5a15d5cf83a91a02d52f2990cbaed5c61)
import IUniswapV2Router02.sol from uniswapv2 and manipulate router.swapExactTokensForTokens in my contract.
// SwapToken.sol
pragma solidity ^0.6.6;
import "#uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "#uniswap/v2-core/contracts/interfaces/IERC20.sol";
contract SwapTokens {
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
event test (uint timestamp, uint amountIn, uint amountOut, address[] path, uint allowance, address sender);
function swapper(address token1, address token2) public {
address[] memory path = new address[](2);
path[0] = token1;
path[1] = token2;
uint amountOut = 1 ether;
uint amountIn = uniRouter.getAmountsIn(
amountOut,
path
)[0];
IERC20(token1).approve(address(uniRouter), amountIn);
uint allowed = IERC20(token1).allowance(msg.sender, address(uniRouter));
emit test(now+90, amountIn, amountOut, path, allowed, msg.sender);
uniRouter.swapExactTokensForTokens(
amountIn,
amountOut,
path,
msg.sender,
now + 120
);
}
}
Then I run the swapper function as below:
sw = await SwapTokens.deployed()
sw.swapper(weth.address, dai.address)
And the transaction fails with Fail with error 'TransferHelper: TRANSFER_FROM_FAILED'
(https://kovan.etherscan.io/tx/0x3324fd65004e001163b665b79583f894e17854bc3371b89f39d472504cb4b46a)
These two approches seem both the same for me.
I do not know which part I have done mistakenly.
In my opinion, it seems you're sending swapExactTokensForTokens with an 'amountOutMin' above 'amountIn', which is impossible.
See above the function prototype of swapExactTokensForTokens :
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
amountOutMin must be smaller than amountIn, due to the slippage. You can find an example here :
JS Script :
const amountIn = web3.utils.toWei("1");
const amountsOut = await uniswapv2router.getAmountsOut(amountIn, [WETH, SDT]);
const amountOutMin = amountsOut[1].mul(web3.utils.toBN(100 - SLIPPAGE_MAX)).div(web3.utils.toBN(100));
const txSwap = await swapRouter.swapTokens([WETH, SDT], amountIn, amountOutMin, account);
Contract :
IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(_amountIn, _amountOutMin, path, _to, block.timestamp);
You should approve tokens to your contract before call swapper function and need to transferFrom token from msg.sender to your contract.
uniRouter.swapExactTokensForTokens(
amountIn,
amountOut,
path,
msg.sender,
now + 120
);
This code doesn't bring tokens from msg.sender to router. This means swap token in your contract by uniRouter and send result token to msg.sender.