ERC20: transfer amount exceeds allowance - ethereum
I have two smart contract MLM and Token. After registration in MLM smart contract, I have to transfer token from Token smart contract. For that I have used contract address of Token and transferFrom method in MLM smart contract. Here is my MLM smart contract code.
pragma solidity >=0.4.23 <0.6.0;
interface IERC20 {
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
contract SmartLearningMLM {
struct User {
uint id;
address referrer;
uint partnersCount;
mapping(uint8 => bool) activeX3Levels;
mapping(uint8 => bool) activeX6Levels;
mapping(uint8 => X3) x3Matrix;
mapping(uint8 => X6) x6Matrix;
}
struct X3 {
address currentReferrer;
address[] referrals;
bool blocked;
uint reinvestCount;
}
struct X6 {
address currentReferrer;
address[] firstLevelReferrals;
address[] secondLevelReferrals;
bool blocked;
uint reinvestCount;
address closedPart;
}
uint8 public constant LAST_LEVEL = 12;
mapping(address => User) public users;
mapping(uint => address) public idToAddress;
mapping(uint => address) public userIds;
mapping(address => uint) public balances;
uint public lastUserId = 2;
address public owner;
IERC20 private _token;
mapping(uint8 => uint) public levelPrice;
event Registration(address indexed user, address indexed referrer, uint indexed userId, uint referrerId);
event Reinvest(address indexed user, address indexed currentReferrer, address indexed caller, uint8 matrix, uint8 level);
event Upgrade(address indexed user, address indexed referrer, uint8 matrix, uint8 level);
event NewUserPlace(address indexed user, address indexed referrer, uint8 matrix, uint8 level, uint8 place);
event MissedEthReceive(address indexed receiver, address indexed from, uint8 matrix, uint8 level);
event SentExtraEthDividends(address indexed from, address indexed receiver, uint8 matrix, uint8 level);
constructor(address ownerAddress, IERC20 token) public {
levelPrice[1] = 5 * 10 ** 18;
for (uint8 i = 2; i <= LAST_LEVEL; i++) {
levelPrice[i] = levelPrice[i-1] * 2;
}
owner = ownerAddress;
_token = token;
User memory user = User({
id: 1,
referrer: address(0),
partnersCount: uint(0)
});
users[ownerAddress] = user;
idToAddress[1] = ownerAddress;
for (uint8 i = 1; i <= LAST_LEVEL; i++) {
users[ownerAddress].activeX3Levels[i] = true;
users[ownerAddress].activeX6Levels[i] = true;
}
userIds[1] = ownerAddress;
}
function() external payable {
if(msg.data.length == 0) {
return registration(msg.sender, owner);
}
registration(msg.sender, bytesToAddress(msg.data));
}
function registrationExt(address referrerAddress) external payable {
registration(msg.sender, referrerAddress);
}
function buyNewLevel(uint8 matrix, uint8 level) external payable {
require(isUserExists(msg.sender), "user is not exists. Register first.");
require(matrix == 1 || matrix == 2, "invalid matrix");
require(level > 1 && level <= LAST_LEVEL, "invalid level");
if (matrix == 1) {
require(!users[msg.sender].activeX3Levels[level], "level already activated");
if (users[msg.sender].x3Matrix[level-1].blocked) {
users[msg.sender].x3Matrix[level-1].blocked = false;
}
address freeX3Referrer = findFreeX3Referrer(msg.sender, level);
users[msg.sender].x3Matrix[level].currentReferrer = freeX3Referrer;
users[msg.sender].activeX3Levels[level] = true;
updateX3Referrer(msg.sender, freeX3Referrer, level);
emit Upgrade(msg.sender, freeX3Referrer, 1, level);
} else {
require(!users[msg.sender].activeX6Levels[level], "level already activated");
if (users[msg.sender].x6Matrix[level-1].blocked) {
users[msg.sender].x6Matrix[level-1].blocked = false;
}
address freeX6Referrer = findFreeX6Referrer(msg.sender, level);
users[msg.sender].activeX6Levels[level] = true;
updateX6Referrer(msg.sender, freeX6Referrer, level);
emit Upgrade(msg.sender, freeX6Referrer, 2, level);
}
}
function registration(address userAddress, address referrerAddress) private {
require(!isUserExists(userAddress), "user exists");
require(isUserExists(referrerAddress), "referrer not exists");
uint32 size;
assembly {
size := extcodesize(userAddress)
}
require(size == 0, "cannot be a contract");
User memory user = User({
id: lastUserId,
referrer: referrerAddress,
partnersCount: 0
});
users[userAddress] = user;
idToAddress[lastUserId] = userAddress;
users[userAddress].referrer = referrerAddress;
users[userAddress].activeX3Levels[1] = true;
users[userAddress].activeX6Levels[1] = true;
userIds[lastUserId] = userAddress;
lastUserId++;
users[referrerAddress].partnersCount++;
address freeX3Referrer = findFreeX3Referrer(userAddress, 1);
users[userAddress].x3Matrix[1].currentReferrer = freeX3Referrer;
updateX3Referrer(userAddress, freeX3Referrer, 1);
updateX6Referrer(userAddress, findFreeX6Referrer(userAddress, 1), 1);
emit Registration(userAddress, referrerAddress, users[userAddress].id, users[referrerAddress].id);
}
function updateX3Referrer(address userAddress, address referrerAddress, uint8 level) private {
users[referrerAddress].x3Matrix[level].referrals.push(userAddress);
if (users[referrerAddress].x3Matrix[level].referrals.length < 3) {
emit NewUserPlace(userAddress, referrerAddress, 1, level, uint8(users[referrerAddress].x3Matrix[level].referrals.length));
return sendETHDividends(referrerAddress, userAddress, 1, level);
}
emit NewUserPlace(userAddress, referrerAddress, 1, level, 3);
//close matrix
users[referrerAddress].x3Matrix[level].referrals = new address[](0);
if (!users[referrerAddress].activeX3Levels[level+1] && level != LAST_LEVEL) {
users[referrerAddress].x3Matrix[level].blocked = true;
}
//create new one by recursion
if (referrerAddress != owner) {
//check referrer active level
address freeReferrerAddress = findFreeX3Referrer(referrerAddress, level);
if (users[referrerAddress].x3Matrix[level].currentReferrer != freeReferrerAddress) {
users[referrerAddress].x3Matrix[level].currentReferrer = freeReferrerAddress;
}
users[referrerAddress].x3Matrix[level].reinvestCount++;
emit Reinvest(referrerAddress, freeReferrerAddress, userAddress, 1, level);
updateX3Referrer(referrerAddress, freeReferrerAddress, level);
} else {
sendETHDividends(owner, userAddress, 1, level);
users[owner].x3Matrix[level].reinvestCount++;
emit Reinvest(owner, address(0), userAddress, 1, level);
}
}
function updateX6Referrer(address userAddress, address referrerAddress, uint8 level) private {
require(users[referrerAddress].activeX6Levels[level], "500. Referrer level is inactive");
if (users[referrerAddress].x6Matrix[level].firstLevelReferrals.length < 2) {
users[referrerAddress].x6Matrix[level].firstLevelReferrals.push(userAddress);
emit NewUserPlace(userAddress, referrerAddress, 2, level, uint8(users[referrerAddress].x6Matrix[level].firstLevelReferrals.length));
//set current level
users[userAddress].x6Matrix[level].currentReferrer = referrerAddress;
if (referrerAddress == owner) {
return sendETHDividends(referrerAddress, userAddress, 2, level);
}
address ref = users[referrerAddress].x6Matrix[level].currentReferrer;
users[ref].x6Matrix[level].secondLevelReferrals.push(userAddress);
uint len = users[ref].x6Matrix[level].firstLevelReferrals.length;
if ((len == 2) &&
(users[ref].x6Matrix[level].firstLevelReferrals[0] == referrerAddress) &&
(users[ref].x6Matrix[level].firstLevelReferrals[1] == referrerAddress)) {
if (users[referrerAddress].x6Matrix[level].firstLevelReferrals.length == 1) {
emit NewUserPlace(userAddress, ref, 2, level, 5);
} else {
emit NewUserPlace(userAddress, ref, 2, level, 6);
}
} else if ((len == 1 || len == 2) &&
users[ref].x6Matrix[level].firstLevelReferrals[0] == referrerAddress) {
if (users[referrerAddress].x6Matrix[level].firstLevelReferrals.length == 1) {
emit NewUserPlace(userAddress, ref, 2, level, 3);
} else {
emit NewUserPlace(userAddress, ref, 2, level, 4);
}
} else if (len == 2 && users[ref].x6Matrix[level].firstLevelReferrals[1] == referrerAddress) {
if (users[referrerAddress].x6Matrix[level].firstLevelReferrals.length == 1) {
emit NewUserPlace(userAddress, ref, 2, level, 5);
} else {
emit NewUserPlace(userAddress, ref, 2, level, 6);
}
}
return updateX6ReferrerSecondLevel(userAddress, ref, level);
}
users[referrerAddress].x6Matrix[level].secondLevelReferrals.push(userAddress);
if (users[referrerAddress].x6Matrix[level].closedPart != address(0)) {
if ((users[referrerAddress].x6Matrix[level].firstLevelReferrals[0] ==
users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]) &&
(users[referrerAddress].x6Matrix[level].firstLevelReferrals[0] ==
users[referrerAddress].x6Matrix[level].closedPart)) {
updateX6(userAddress, referrerAddress, level, true);
return updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
} else if (users[referrerAddress].x6Matrix[level].firstLevelReferrals[0] ==
users[referrerAddress].x6Matrix[level].closedPart) {
updateX6(userAddress, referrerAddress, level, true);
return updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
} else {
updateX6(userAddress, referrerAddress, level, false);
return updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
}
}
if (users[referrerAddress].x6Matrix[level].firstLevelReferrals[1] == userAddress) {
updateX6(userAddress, referrerAddress, level, false);
return updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
} else if (users[referrerAddress].x6Matrix[level].firstLevelReferrals[0] == userAddress) {
updateX6(userAddress, referrerAddress, level, true);
return updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
}
if (users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[0]].x6Matrix[level].firstLevelReferrals.length <=
users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.length) {
updateX6(userAddress, referrerAddress, level, false);
} else {
updateX6(userAddress, referrerAddress, level, true);
}
updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
}
function updateX6(address userAddress, address referrerAddress, uint8 level, bool x2) private {
if (!x2) {
users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[0]].x6Matrix[level].firstLevelReferrals.push(userAddress);
emit NewUserPlace(userAddress, users[referrerAddress].x6Matrix[level].firstLevelReferrals[0], 2, level, uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[0]].x6Matrix[level].firstLevelReferrals.length));
emit NewUserPlace(userAddress, referrerAddress, 2, level, 2 + uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[0]].x6Matrix[level].firstLevelReferrals.length));
//set current level
users[userAddress].x6Matrix[level].currentReferrer = users[referrerAddress].x6Matrix[level].firstLevelReferrals[0];
} else {
users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.push(userAddress);
emit NewUserPlace(userAddress, users[referrerAddress].x6Matrix[level].firstLevelReferrals[1], 2, level, uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.length));
emit NewUserPlace(userAddress, referrerAddress, 2, level, 4 + uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.length));
//set current level
users[userAddress].x6Matrix[level].currentReferrer = users[referrerAddress].x6Matrix[level].firstLevelReferrals[1];
}
}
function updateX6ReferrerSecondLevel(address userAddress, address referrerAddress, uint8 level) private {
if (users[referrerAddress].x6Matrix[level].secondLevelReferrals.length < 4) {
return sendETHDividends(referrerAddress, userAddress, 2, level);
}
address[] memory x6 = users[users[referrerAddress].x6Matrix[level].currentReferrer].x6Matrix[level].firstLevelReferrals;
if (x6.length == 2) {
if (x6[0] == referrerAddress ||
x6[1] == referrerAddress) {
users[users[referrerAddress].x6Matrix[level].currentReferrer].x6Matrix[level].closedPart = referrerAddress;
} else if (x6.length == 1) {
if (x6[0] == referrerAddress) {
users[users[referrerAddress].x6Matrix[level].currentReferrer].x6Matrix[level].closedPart = referrerAddress;
}
}
}
users[referrerAddress].x6Matrix[level].firstLevelReferrals = new address[](0);
users[referrerAddress].x6Matrix[level].secondLevelReferrals = new address[](0);
users[referrerAddress].x6Matrix[level].closedPart = address(0);
if (!users[referrerAddress].activeX6Levels[level+1] && level != LAST_LEVEL) {
users[referrerAddress].x6Matrix[level].blocked = true;
}
users[referrerAddress].x6Matrix[level].reinvestCount++;
if (referrerAddress != owner) {
address freeReferrerAddress = findFreeX6Referrer(referrerAddress, level);
emit Reinvest(referrerAddress, freeReferrerAddress, userAddress, 2, level);
updateX6Referrer(referrerAddress, freeReferrerAddress, level);
} else {
emit Reinvest(owner, address(0), userAddress, 2, level);
sendETHDividends(owner, userAddress, 2, level);
}
}
function findFreeX3Referrer(address userAddress, uint8 level) public view returns(address) {
while (true) {
if (users[users[userAddress].referrer].activeX3Levels[level]) {
return users[userAddress].referrer;
}
userAddress = users[userAddress].referrer;
}
}
function findFreeX6Referrer(address userAddress, uint8 level) public view returns(address) {
while (true) {
if (users[users[userAddress].referrer].activeX6Levels[level]) {
return users[userAddress].referrer;
}
userAddress = users[userAddress].referrer;
}
}
function usersActiveX3Levels(address userAddress, uint8 level) public view returns(bool) {
return users[userAddress].activeX3Levels[level];
}
function usersActiveX6Levels(address userAddress, uint8 level) public view returns(bool) {
return users[userAddress].activeX6Levels[level];
}
function usersX3Matrix(address userAddress, uint8 level) public view returns(address, address[] memory, bool) {
return (users[userAddress].x3Matrix[level].currentReferrer,
users[userAddress].x3Matrix[level].referrals,
users[userAddress].x3Matrix[level].blocked);
}
function usersX6Matrix(address userAddress, uint8 level) public view returns(address, address[] memory, address[] memory, bool, address) {
return (users[userAddress].x6Matrix[level].currentReferrer,
users[userAddress].x6Matrix[level].firstLevelReferrals,
users[userAddress].x6Matrix[level].secondLevelReferrals,
users[userAddress].x6Matrix[level].blocked,
users[userAddress].x6Matrix[level].closedPart);
}
function isUserExists(address user) public view returns (bool) {
return (users[user].id != 0);
}
function findEthReceiver(address userAddress, address _from, uint8 matrix, uint8 level) private returns(address, bool) {
address receiver = userAddress;
bool isExtraDividends;
if (matrix == 1) {
while (true) {
if (users[receiver].x3Matrix[level].blocked) {
emit MissedEthReceive(receiver, _from, 1, level);
isExtraDividends = true;
receiver = users[receiver].x3Matrix[level].currentReferrer;
} else {
return (receiver, isExtraDividends);
}
}
} else {
while (true) {
if (users[receiver].x6Matrix[level].blocked) {
emit MissedEthReceive(receiver, _from, 2, level);
isExtraDividends = true;
receiver = users[receiver].x6Matrix[level].currentReferrer;
} else {
return (receiver, isExtraDividends);
}
}
}
}
function sendETHDividends(address userAddress, address _from, uint8 matrix, uint8 level) private {
(address receiver, bool isExtraDividends) = findEthReceiver(userAddress, _from, matrix, level);
_token.transferFrom(_from, address(uint160(receiver)), levelPrice[level]);
if (isExtraDividends) {
emit SentExtraEthDividends(_from, receiver, matrix, level);
}
}
function bytesToAddress(bytes memory bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
}
My problem is the following line is working as expected.
_token.transferFrom(_from, address(uint160(receiver)), levelPrice[level]);
I am getting the following error,
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
execution reverted: ERC20: transfer amount exceeds allowance { "originalError": { "code": 3, "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002845524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e6365000000000000000000000000000000000000000000000000", "message": "execution reverted: ERC20: transfer amount exceeds allowance" } }
But I have added allowance _from (owner) and contract address(spender). Later I have tested. The allowance added properly. But I am getting allowance exceeds error. To avoid confusions of from and receiver address, I have hard coded as following,
_token.transferFrom(address(0xBc29513F0075736Bad940345ebBE366f993B22fC), address(0x0E6a6Bf011852cB607464f9088D05A2B1238a466), 5000000000000000000);
But I am getting same error.
If I execute transferFrom logic alone, It is working properly. Here is my working code without MLM logic,
pragma solidity >=0.4.23 <0.6.0;
interface IERC20 {
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
contract SmartLearningMLM {
IERC20 private _token;
address public owner;
constructor(address _owner, IERC20 token) public {
_token = token;
owner = _owner;
}
function() external payable {
if(msg.data.length == 0) {
return registration(msg.sender, owner);
}
registration(msg.sender, bytesToAddress(msg.data));
}
function registrationExt(address referrerAddress) external payable {
registration(msg.sender, referrerAddress);
}
function registration(address userAddress, address referrerAddress) private {
_token.transferFrom(address(0xBc29513F0075736Bad940345ebBE366f993B22fC), address(0x0E6a6Bf011852cB607464f9088D05A2B1238a466), 5000000000000000000);
}
function bytesToAddress(bytes memory bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
}
Help me to fix this issue.
Related
Borrowing 1INCH tokens from dYdX
I'm new to dydx flashloans and im builidng a flashloan that should borrow 1INCH tokens but when i tested it on remix it gave an error saying that the token wasnt supported. Is my code wrong or i just cant borrow 1INCH tokens from dydx. import "#uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "#openzeppelin/contracts/token/ERC20/IERC20.sol"; interface Structs { struct Val { uint256 value; } enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract DyDxPool is Structs { function getAccountWei(Info memory account, uint256 marketId) public view virtual returns (Wei memory); function operate(Info[] memory, ActionArgs[] memory) public virtual; } contract DyDxFlashLoan is Structs { DyDxPool pool = DyDxPool(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); address public WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; mapping(address => uint256) public currencies; constructor() { currencies[WETH] = 1; } modifier onlyPool() { require( msg.sender == address(pool), "FlashLoan: could be called by DyDx pool only" ); _; } function tokenToMarketId(address token) public view returns (uint256) { uint256 marketId = currencies[token]; require(marketId != 0, "FlashLoan: Unsupported token"); return marketId - 1; } // the DyDx will call `callFunction(address sender, Info memory accountInfo, bytes memory data) public` after during `operate` call function flashloan( address token, uint256 amount, bytes memory data ) internal { IERC20(token).approve(address(pool), amount + 1); Info[] memory infos = new Info[](1); ActionArgs[] memory args = new ActionArgs[](3); infos[0] = Info(address(this), 0); AssetAmount memory wamt = AssetAmount( false, AssetDenomination.Wei, AssetReference.Delta, amount ); ActionArgs memory withdraw; withdraw.actionType = ActionType.Withdraw; withdraw.accountId = 0; withdraw.amount = wamt; withdraw.primaryMarketId = tokenToMarketId(token); withdraw.otherAddress = address(this); args[0] = withdraw; ActionArgs memory call; call.actionType = ActionType.Call; call.accountId = 0; call.otherAddress = address(this); call.data = data; args[1] = call; ActionArgs memory deposit; AssetAmount memory damt = AssetAmount( true, AssetDenomination.Wei, AssetReference.Delta, amount + 1 ); deposit.actionType = ActionType.Deposit; deposit.accountId = 0; deposit.amount = damt; deposit.primaryMarketId = tokenToMarketId(token); deposit.otherAddress = address(this); args[2] = deposit; pool.operate(infos, args); } } contract Arbitrage is DyDxFlashLoan { IUniswapV2Router02 immutable uRouter; IUniswapV2Router02 immutable sRouter; address public owner; constructor(address _uRouter, address _sRouter) { uRouter = IUniswapV2Router02(_uRouter); sRouter = IUniswapV2Router02(_sRouter); owner = msg.sender; } function executeTrade( address _tokenA, uint _tokensFromFlashLoan, address _tokenB, bool _startOnUniswap ) external { uint balanceBefore = IERC20(_tokenA).balanceOf(address(this)); bytes memory data = abi.encode( _startOnUniswap, _tokenA, _tokenB, _tokensFromFlashLoan, balanceBefore ); flashloan(_tokenA, _tokensFromFlashLoan, data); } function callFunction( address, Info calldata, bytes calldata data ) external onlyPool { ( bool _startOnUniswap, address _tokenA, address _tokenB, uint256 _tokensFromFlashLoan, uint256 balanceBefore ) = abi.decode(data, (bool, address, address, uint256, uint256)); uint balanceAfter = IERC20(_tokenA).balanceOf(address(this)); require( balanceAfter - balanceBefore == _tokensFromFlashLoan, "didnt receive flash loan" ); address[] memory tokens; if (_startOnUniswap == true) { tokens[0] = _tokenA; tokens[1] = _tokenB; swapOnUniswap(_tokensFromFlashLoan, 0, tokens); tokens[0] = _tokenB; tokens[1] = _tokenA; swapOnSushiswap( IERC20(tokens[0]).balanceOf(address(this)), 0, tokens ); } else { tokens[0] = _tokenA; tokens[1] = _tokenB; swapOnSushiswap(_tokensFromFlashLoan, 0, tokens); tokens[0] = _tokenB; tokens[1] = _tokenA; swapOnUniswap( IERC20(tokens[0]).balanceOf(address(this)), 0, tokens ); } } function swapOnUniswap( uint _amountIn, uint _amountOut, address[] memory _path ) internal { require( IERC20(_path[0]).approve(address(uRouter), _amountIn), "Uniswap failed the approval" ); uRouter.swapExactTokensForTokens( _amountIn, _amountOut, _path, address(this), (block.timestamp + 1200) ); } function swapOnSushiswap( uint _amountIn, uint _amountOut, address[] memory _path ) internal { require( IERC20(_path[0]).approve(address(sRouter), _amountIn), "Sushiswap failed the approval" ); uRouter.swapExactTokensForTokens( _amountIn, _amountOut, _path, address(this), (block.timestamp + 1200) ); } }``` I tried to look at dydx docs but i didnt find nothing that could help me
Insufficient funds for intrinsic transaction cost on goerli network
I am working on dapp using hardhat and goerli testnet and when I run it using npx hardhat run scripts/deploy.js --network goerli, I receive this error, I do have goerli faucet eth on my wallet but still it will display that my account balance is 0: Error: insufficient funds for intrinsic transaction cost [ See: https://links.ethers.org/v5-errors-INSUFFICIENT_FUNDS ] (error={"name":"ProviderError","_stack":"ProviderError: HttpProviderError\n at HttpProvider.request (C:\\Users\\SAIFUL\\RTW3-Week7-NFT-Marketplace\\node_modules\\hardhat\\src\\internal\\core\\providers\\http.ts:78:19)\n at LocalAccountsProvider.request (C:\\Users\\SAIFUL\\RTW3-Week7-NFT-Marketplace\\node_modules\\hardhat\\src\\internal\\core\\providers\\accounts.ts:181:36)\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n at EthersProviderWrapper.send (C:\\Users\\SAIFUL\\RTW3-Week7-NFT-Marketplace\\node_modules\\#nomiclabs\\hardhat-ethers\\src\\internal\\ethers-provider-wrapper.ts:13:20)","code":-32000,"_isProviderError":true}, method="sendTransaction", transaction=undefined, code=INSUFFICIENT_FUNDS, version=providers/5.7.2) at Logger.makeError (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\logger\src.ts\index.ts:269:28) at Logger.throwError (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\logger\src.ts\index.ts:281:20) at checkError (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\providers\src.ts\json-rpc-provider.ts:98:16) at C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\providers\src.ts\json-rpc-provider.ts:265:24 at processTicksAndRejections (internal/process/task_queues.js:95:5) { reason: 'insufficient funds for intrinsic transaction cost', code: 'INSUFFICIENT_FUNDS', error: ProviderError: HttpProviderError at HttpProvider.request (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\hardhat\src\internal\core\providers\http.ts:78:19) at LocalAccountsProvider.request (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\hardhat\src\internal\core\providers\accounts.ts:181:36) at processTicksAndRejections (internal/process/task_queues.js:95:5) at EthersProviderWrapper.send (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#nomiclabs\hardhat-ethers\src\internal\ethers-provider-wrapper.ts:13:20), method: 'sendTransaction', transaction: undefined } here is my deploy.js file everything is supposed to fine and working but error won't disappear require("#nomiclabs/hardhat-waffle"); require("#nomiclabs/hardhat-ethers"); const fs = require('fs'); // const infuraId = fs.readFileSync(".infuraid").toString().trim() || ""; task("accounts", "Prints the list of accounts", async(taskArgs, hre) => { const accounts = await hre.ethers.getSigners(); for (const account of accounts) { console.log(account.address); } }); module.exports = { defaultNetwork: "hardhat", networks: { hardhat: { chainId: 1337 }, goerli: { url: "https://eth-mainnet.g.alchemy.com/v2/2Hmp7mz6XEpw6Z47cCZx2vEIAYXFGYOL", accounts: ["private key here"] } }, solidity: { version: "0.8.4", settings: { optimizer: { enabled: true, runs: 200 } } } }; here is my solidity contract: //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "hardhat/console.sol"; import "#openzeppelin/contracts/utils/Counters.sol"; import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "#openzeppelin/contracts/token/ERC721/ERC721.sol"; contract NFTMarketplace is ERC721URIStorage { address payable owner; using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter private _itemsSold; uint256 listPrice = 0.01 ether; constructor() ERC721("NFTMarketplace", "NFTM") { owner = payable(msg.sender); } struct ListedToken { uint256 tokenId; address payable owner; address payable seller; uint256 price; bool currentlyListed; } mapping(uint256 => ListedToken) private idToListedToken; function updateListPrice(uint256 _listprice) public payable { require(owner == msg.sender, "only owner can update listing price "); listPrice = _listprice; } function getListPrice() public view returns (uint256) { return listPrice; } function getLatestIdToListedtoken() public view returns (ListedToken memory) { uint256 currentTokenId = _tokenIds.current(); return idToListedToken[currentTokenId]; } function getListedForToken(uint256 tokenId) public view returns (ListedToken memory) { return idToListedToken[tokenId]; } function getCurrentToken() public view returns (uint256) { return _tokenIds.current(); } function createToken(string memory tokenURI, uint256 price) public payable returns (uint) { require(msg.value == listPrice, "Send enough ether to list"); require(price > 0, "Make sure the price isn't negative"); _tokenIds.increment(); uint256 currentTokenId = _tokenIds.current(); _safeMint(msg.sender, currentTokenId); _setTokenURI(currentTokenId, tokenURI); createListedToken(currentTokenId, price); return currentTokenId; } function createListedToken(uint256 tokenId, uint256 price) private { idToListedToken[tokenId] = ListedToken( tokenId, payable(address(this)), payable(msg.sender), price, true ); _transfer(msg.sender, address(this), tokenId); } function getAllNFTs() public view returns(ListedToken[] memory) { uint nftCount = _tokenIds.current(); ListedToken[] memory tokens = new ListedToken[](nftCount); uint currentIndex = 0; for(uint i=0; i<nftCount; i++) { uint currentId = i+1; ListedToken storage currentItem = idToListedToken[currentId]; tokens[currentIndex] = currentItem; currentIndex += 1; } return tokens; } function getMyNFTs() public view returns (ListedToken[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; uint currentId; for(uint i=0; i < totalItemCount; i++) { if(idToListedToken[i+1].owner == msg.sender || idToListedToken[i+1].seller == msg.sender){ itemCount += 1; } } ListedToken[] memory items = new ListedToken[](itemCount); for(uint i=0; i < totalItemCount; i++) { if(idToListedToken[i+1].owner == msg.sender || idToListedToken[i+1].seller == msg.sender) { currentId = i+1; ListedToken storage currentItem = idToListedToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } function executeSale(uint256 tokenId) public payable { uint price = idToListedToken[tokenId].price; require(msg.value == price, "please submit the relevant NFT price in order to purchase"); address seller = idToListedToken[tokenId].seller; idToListedToken[tokenId].currentlyListed = true; idToListedToken[tokenId].seller = payable(msg.sender); _itemsSold.increment(); _transfer(address(this), msg.sender, tokenId); approve(address(this), tokenId); payable(owner).transfer(listPrice); payable(seller).transfer(msg.value); } } I tried different networks, but I have no choice except goerli because I will use alchemy Api.
You still need to get more Goerli ETH from faucets or from your other peers. Try that and see if it will work
Finally I switched from INFURA to ALCHEMY and following the instructions here: https://hardhat.org/tutorial/deploying-to-a-live-network it worked!
Ethereum /BSC Smart Contract Question - Value Stuck in contract
Attached is the source code for the smart contract, could you advise if there's a function in it I can use to recover the 1.5 bnb? I still have access to the creation wallet and the contract isn't renounced. it would be nice to try and work this out if possible as I am still learning to code. /** *Submitted for verification at BscScan.com on 2021-08-27 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; return msg.data; } } interface IERC20 { 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 ); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Pair { function sync() external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; } // change "name1" into ur name contract BlueMoon is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; //change "name1" and "symbol" string private _name = "BlueMoon"; string private _symbol = "BMOON"; uint8 private _decimals = 8; mapping(address => uint256) internal _reflectionBalance; mapping(address => uint256) internal _tokenBalance; mapping(address => mapping(address => uint256)) internal _allowances; uint256 private constant MAX = ~uint256(0); // change this for total supply (100e8 = 100) (100000000e8 = 100000000) (dont forget the e8 it has to be there) uint256 internal _tokenTotal = 1_000_000_000e8; // change this for total supply ^^^^^^^^^^^^^^^^^^^^^ uint256 internal _reflectionTotal = (MAX - (MAX % _tokenTotal)); mapping(address => bool) isTaxless; mapping(address => bool) internal _isExcluded; address[] internal _excluded; uint256 public _feeDecimal = 2; // thats the distribution to holders (400 = 4%) uint256 public _taxFee = 100; // thats the amount for liquidity pool uint256 public _liquidityFee = 1000; // this amount gets burned by every transaction uint256 public _burnFee = 100; // this goes to a specific wallet (line 403) uint256 public _marketingFee = 300; uint256 public _taxFeeTotal; uint256 public _burnFeeTotal; uint256 public _liquidityFeeTotal; uint256 public _marketingFeeTotal; address public marketingWallet; bool public isTaxActive = true; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public maxTxAmount = _tokenTotal; uint256 public minTokensBeforeSwap = 10_000e8; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived, uint256 tokensIntoLiqudity); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() public { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // for BSC // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // for Ethereum // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); // for Sushi testnet uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; //paste the wallet adress, that earns the marketingFee here marketingWallet = 0xD64E87ad309f21De5725e91EAFB82c50e486D374; //paste the wallet ^^^^^^^^^^^^^^^^^^^^^ adress, that earns the marketingFee here isTaxless[_msgSender()] = true; isTaxless[address(this)] = true; _reflectionBalance[_msgSender()] = _reflectionTotal; emit Transfer(address(0), _msgSender(), _tokenTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public override view returns (uint256) { return _tokenTotal; } function balanceOf(address account) public override view returns (uint256) { if (_isExcluded[account]) return _tokenBalance[account]; return tokenFromReflection(_reflectionBalance[account]); } function transfer(address recipient, uint256 amount) public override virtual returns (bool) { _transfer(_msgSender(),recipient,amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override virtual returns (bool) { _transfer(sender,recipient,amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub( amount,"ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee) public view returns (uint256) { require(tokenAmount <= _tokenTotal, "Amount must be less than supply"); if (!deductTransferFee) { return tokenAmount.mul(_getReflectionRate()); } else { return tokenAmount.sub(tokenAmount.mul(_taxFee).div(10** _feeDecimal + 2)).mul( _getReflectionRate() ); } } function tokenFromReflection(uint256 reflectionAmount) public view returns (uint256) { require( reflectionAmount <= _reflectionTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getReflectionRate(); return reflectionAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require( account != address(uniswapV2Router), "ERC20: We can not exclude Uniswap router." ); require(!_isExcluded[account], "ERC20: Account is already excluded"); if (_reflectionBalance[account] > 0) { _tokenBalance[account] = tokenFromReflection( _reflectionBalance[account] ); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "ERC20: Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tokenBalance[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { 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); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(amount <= maxTxAmount, "Transfer Limit exceeded!"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (!inSwapAndLiquify && overMinTokenBalance && sender != uniswapV2Pair && swapAndLiquifyEnabled) { swapAndLiquify(contractTokenBalance); } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(isTaxActive && !isTaxless[_msgSender()] && !isTaxless[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate)); _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; //#dev tax fee if(_taxFee != 0){ uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); } //#dev liquidity fee if(_liquidityFee != 0){ uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(liquidityFee); _reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate)); if(_isExcluded[address(this)]){ _tokenBalance[address(this)] = _tokenBalance[address(this)].add(liquidityFee); } _liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee); emit Transfer(account,address(this),liquidityFee); } //#dev burn fee if(_burnFee != 0){ uint256 burnFee = amount.mul(_burnFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(burnFee); _tokenTotal = _tokenTotal.sub(burnFee); _reflectionTotal = _reflectionTotal.sub(burnFee.mul(rate)); _burnFeeTotal = _burnFeeTotal.add(burnFee); emit Transfer(account,address(0),burnFee); } //#dev Marketing fee if(_marketingFee != 0){ uint256 marketingFee = amount.mul(_marketingFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(marketingFee); _reflectionBalance[marketingWallet] = _reflectionBalance[marketingWallet].add(marketingFee.mul(rate)); if (_isExcluded[marketingWallet]) { _tokenBalance[marketingWallet] = _tokenBalance[marketingWallet].add(marketingFee); } _marketingFeeTotal = _marketingFeeTotal.add(marketingFee); emit Transfer(account,marketingWallet,marketingFee); } return transferAmount; } function _getReflectionRate() private view returns (uint256) { uint256 reflectionSupply = _reflectionTotal; uint256 tokenSupply = _tokenTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _reflectionBalance[_excluded[i]] > reflectionSupply || _tokenBalance[_excluded[i]] > tokenSupply ) return _reflectionTotal.div(_tokenTotal); reflectionSupply = reflectionSupply.sub( _reflectionBalance[_excluded[i]] ); tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]); } if (reflectionSupply < _reflectionTotal.div(_tokenTotal)) return _reflectionTotal.div(_tokenTotal); return reflectionSupply.div(tokenSupply); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if(contractTokenBalance > maxTxAmount) contractTokenBalance = maxTxAmount; uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; swapTokensForEth(half); uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, address(this), block.timestamp ); } function setPair(address pair) external onlyOwner { uniswapV2Pair = pair; } function setMarketingWallet(address account) external onlyOwner { marketingWallet = account; } function setTaxless(address account, bool value) external onlyOwner { isTaxless[account] = value; } function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner { swapAndLiquifyEnabled = enabled; SwapAndLiquifyEnabledUpdated(enabled); } function setTaxActive(bool value) external onlyOwner { isTaxActive = value; } function setTaxFee(uint256 fee) external onlyOwner { _taxFee = fee; } function setBurnFee(uint256 fee) external onlyOwner { _burnFee = fee; } function setLiquidityFee(uint256 fee) external onlyOwner { _liquidityFee = fee; } function setMarketingFee(uint256 fee) external onlyOwner { _marketingFee = fee; } function setMaxTxAmount(uint256 amount) external onlyOwner { maxTxAmount = amount; } function setMinTokensBeforeSwap(uint256 amount) external onlyOwner { minTokensBeforeSwap = amount; } receive() external payable {} } as far as im aware im sure most contracts have some sort of clear stuck balance function in them which you can use. but I dont see one here. is it an oversight? or can it still be called using other functions. Thanks for any advise. am willing to try what is recommended.
ERC721 Token abstract contract or an interface and cannot be deployed
after reading many post i can't found the issues about this Smart contract who compile but it think i miss something about the inheritance and the Abstract contract. This is the SC : // solium-disable linebreak-style pragma solidity >=0.4.21 <0.6.0; import "../node_modules/#openzeppelin/contracts/token/ERC721/ERC721.sol"; import "../node_modules/#openzeppelin/contracts/math/SafeMath.sol"; /** * #title Ownable * #dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address payable public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * #dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor (Ownable) public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * #dev Allows the current owner to transfer control of the contract to a newOwner. * #param newOwner The address to transfer ownership to. */ function transferOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Sample is Ownable { event NewResource (uint resourceId, string name , uint quality); uint qualityUnits = 16; uint qualityModulo = qualityUnits; uint cooldownTime = 1 days; struct Resource { string name; uint quality; uint32 rarity; uint256 cooldownTime; uint16 stockGain; uint16 stockLoss; uint32 readyTime; uint256 extractionTime; uint256 extractionId; uint256 magnetiteId; uint256 hematiteId; uint256 class; uint256 sediments; uint qualityUnits; } //mapping address and apply stocks mapping (uint => address) public resourceToOwner; mapping (address => uint) ownerResourceGain; Resource[] public resources; /// #dev function to crack the resource stacks function _createResource (string memory _name , uint _quality) internal { uint id = resources.push(Resource(_name,_quality ,1 , uint256( now + cooldownTime), 0 , 0, 0, 0, 0, 0, 0, 0, 0, 16) )+1; resourceToOwner[id] = msg.sender; ownerResourceGain[msg.sender]++; emit NewResource(id, _name , _quality); } //function to generate rand stats for resources function _generateRandomQuality(string memory _str ) private view returns (uint) { uint rand = uint(keccak256(abi.encode(_str))); return rand % qualityModulo; } //function to generate the resource stacks function createResourceStack(string memory _name) public { require(ownerResourceGain[msg.sender] ==0); uint randomQuality = _generateRandomQuality(_name); randomQuality = randomQuality - randomQuality % 100; _createResource(_name, randomQuality); } } contract CoreRefined is Sample { //address public newContractAddress; function getResourcesStats(uint256 _id) external view returns ( bool isRefiningInProcess, bool isReady, uint256 cooldownTime, //uint256 nextActionAt, uint256 extractionTime, uint256 extractionId, uint256 magnetiteId, uint256 hematiteId, uint256 class, uint256 sediments ) { Resource storage stats = resources[_id]; isRefiningInProcess = (stats.quality != 0); isReady = (stats.cooldownTime <= block.number); cooldownTime = uint256(stats.cooldownTime); extractionTime = uint256(stats.extractionTime); extractionId = uint256(stats.extractionId); magnetiteId = uint256(stats.magnetiteId); hematiteId = uint256(stats.hematiteId); class = uint256(stats.class); sediments = stats.sediments; } } /// #title RefiningInterface for resource modification called refining /// #dev Refining function inside for improving stats of resources. contract RefiningInterface is Sample { function refining(uint256 _id) external view returns ( bool isRefiningInProcess, bool isReady, uint256 cooldownTime, uint256 nextActionsAt, uint256 extractionTime, uint256 extractionId, uint256 magnetiteId, uint256 hematiteId, uint256 class, uint256 sediments ); } contract ResourceRefined is Sample , CoreRefined { ResourceRefined CoreRefinedContract; modifier onlyOwnerOf(uint _resourceId) { require(msg.sender == resourceToOwner[_resourceId]); _; } function SetAnotherContractAddress (address _address) external onlyOwner { CoreRefinedContract = ResourceRefined(_address); } function triggerCooldown (Resource storage _resource ) internal { _resource.readyTime = uint32(now+cooldownTime); } function _isReady ( Resource storage _resource ) internal view returns (bool) { return (_resource.readyTime <= now); } function refinedAndMultiply( uint _resourceId, uint _targetQuality, string memory _types) internal onlyOwnerOf(_resourceId) { Resource storage myResource = resources[_resourceId]; require(_isReady(myResource)); _targetQuality % qualityModulo; uint newQuality = (myResource.quality + _targetQuality) / 2; if(keccak256(abi.encode((_types))) == keccak256(abi.encode("Resources"))) { newQuality = newQuality - newQuality % 100 + 99; } _createResource("NoName", newQuality); triggerCooldown(myResource); } function refineOnInterface(uint256 _resourceId, uint256 _idResources ) public { uint256 materialUsed; (,,,,,,,,materialUsed) = CoreRefinedContract.getResourcesStats(_idResources); refinedAndMultiply(_resourceId,materialUsed,"Resources"); } } contract ResourceHelper is ResourceRefined { //cost ether for rarityUp fee uint rarityForFee = 0.001 ether; //modify rarity !=not LEVEL modifier aboveCostLevel (uint _rarity ,uint _resourceId){ require(resources[_resourceId].rarity >= _rarity); _; } //function to withdraw FIX ISSUE /*function withdraw() external onlyOwner { owner.transfer(this).balance; }*/ //rarityfee for resources improvements function setRarityFee(uint _fee) external onlyOwner { rarityForFee = _fee; } //Rarity improvement function /// #dev this function is set by using RefinedResource.sol contract in order to gain better resources function rarityUp(uint _resourceId) external payable { require(msg.value == rarityForFee); resources[_resourceId].rarity++; } //change the name of resources function changeName(uint _resourceId, string calldata _Newname) external aboveCostLevel(2, _resourceId) onlyOwnerOf (_resourceId){ resources[_resourceId].name = _Newname; } //change the qualityUnits function changeQualityUnits(uint _resourceId, uint _newQualityUnits) external aboveCostLevel(2, _resourceId) onlyOwnerOf (_resourceId) { resources[_resourceId].qualityUnits = _newQualityUnits; } //grabe the resources ! array of it. function getTheResourceToOwner( address _owner) external view returns (uint[] memory) { uint[] memory result = new uint[](ownerResourceGain[_owner]); uint counter = 0; //loop for (uint i = 0; i < resources.length; i++) { if (resourceToOwner[i] == _owner){ result[counter] = i; counter++; } } return result; } } contract ResourceUp is ResourceHelper { uint randNonce = 0; uint resourceUpProba = 70; /*function randMod(uint _modulus) internal returns(uint) { randNonce++; return uint(keccak256( (abi.encodePacked(now, msg.sender,randNonce))) % uint(_modulus)); }*/ function setUp(uint _resourceId, uint _targetId) external onlyOwnerOf(_resourceId) { Resource storage myResource = resources[_resourceId]; Resource storage anotherResource = resources[_targetId]; uint rand = 100; if (rand <= resourceUpProba) { myResource.stockGain++; myResource.rarity++; anotherResource.stockLoss++; refinedAndMultiply(_resourceId, anotherResource.quality, "resource"); } else { myResource.stockLoss++; anotherResource.stockGain++; triggerCooldown(myResource); } } } contract Harvest is ResourceUp, ERC721 { using SafeMath for uint256; mapping (uint => address) resourceApproval; function balanceOf(address _owner) public view returns (uint256 _balance) { return ownerResourceGain[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { return resourceToOwner[_tokenId]; } function _transfer(address _from, address _to, uint256 _tokenId) private { ownerResourceGain[_to] = ownerResourceGain[_to].add(1); ownerResourceGain[msg.sender] = ownerResourceGain[msg.sender].sub(1); resourceToOwner[_tokenId] = _to; _transfer(_from, _to, _tokenId); } function transferTo(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { transferTo(_to, _tokenId); } function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { resourceApproval[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } function harvest(uint256 _tokenId) public { require(resourceApproval[_tokenId] == msg.sender); address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } } My depoy js file : const Harvest = artifacts.require("Harvest"); module.exports = function(deployer) { deployer.deploy(Harvest) }; The output of the truffle migrate * Import abstractions into the '.sol' file that uses them instead of deploying them separately. * Contracts that inherit an abstraction must implement all its method signatures exactly. * A contract that only implements part of an inherited abstraction is also considered abstract. verions : Truffle v5.1.9 (core: 5.1.9) Solidity v0.5.16 (solc-js) Node v10.16.3 Web3.js v1.2.1 Thank you for your support.
The problem is with Ownable constructor constructor (Ownable) public { owner = msg.sender; } It is defined in a way that it will receive one parameter of type Ownable. To fix the error define it without any input parameter: constructor() public { owner = msg.sender; }
Gas Estimate of function: Infinite
Here's my first ever smart contract. What exactly causes such a warning and how should I improve my code? This is just one of many similar warnings Warning: Gas requirement of function Consensus.deployPmu(string) high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage) pragma solidity ^0.5.7; contract Consensus { struct PMU{ string name; address pmu; uint256[] data; bool errorFlag; uint256 errorCount; } mapping (address => PMU) PMUS; address[] accounts; uint256[] empty; function deployPmu(string memory _name) public{ PMUS[msg.sender] = PMU(_name,msg.sender,empty,false,0); accounts.push(msg.sender); } function print() public view returns(string memory name, uint256[] memory data,bool errorFlag,uint256 errorCount){ PMU memory instancePMU = PMUS[msg.sender]; return (instancePMU.name,instancePMU.data,instancePMU.errorFlag,instancePMU.errorCount); } function log(uint256[] memory roc) public{ for (uint i=0; i<roc.length;i++){ PMUS[msg.sender].data.push(roc[i]); if(roc[i]<12){ PMUS[msg.sender].errorFlag = false; errorFlags[msg.sender] = false; PMUS[msg.sender].errorCount=0; } if(roc[i]>12){ PMUS[msg.sender].errorCount= PMUS[msg.sender].errorCount+1; } if( PMUS[msg.sender].errorCount >= 5){ PMUS[msg.sender].errorFlag = true; errorFlags[msg.sender] = true; PMUS[msg.sender].errorCount = 0; } } } mapping (address => bool) errorFlags; bool GridFault=false; bool PMUfault=false; address[] tru; address[] falz; function faultStatus () public returns (address[] memory) { address[] memory empty; tru = empty; falz =empty; GridFault = false; PMUfault = false; uint256 count =0; for(uint256 i =0; i<accounts.length; i++){ if(errorFlags[accounts[i]] == true){ count = count + 1; tru.push(accounts[i]); } else{ falz.push(accounts[i]); } } if(count > (accounts.length-1)/2){ GridFault = true; if(falz.length != 0){ PMUfault = true; } } else if(count == 0){ GridFault = false; PMUfault = false; } else{ PMUfault = true; return tru; } } function gridstatus() public view returns(address[] memory, bool, bool){ if(GridFault == true){ return (falz,GridFault, PMUfault); } else{ return(tru,GridFault, PMUfault); } } }