I am creating blockchain lottery smart contract that is using my own ERC20 token.
The idea is simple. Players buy any amount of tickets they want. Each ticket that is bought is stored as a pair of address and ticketId.
When the manager calls the pickWinner() function, a random number is generated and one ticket is chosen as the winning one.
All is working good until I call the pickWinner() function. After I try to call it I get 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 { "originalError": { "code": 3, "data": "0x4e487b710000000000000000000000000000000000000000000000000000000000000032", "message": "execution reverted" } }
The problem is, it's not telling me where the problem is. I don't know how to proceed further without trying removing line by line and see where's the problem.
Here's the code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Lottery {
event TicketsBought(address playerAddress, uint256 quantity, uint256 ticketPrice);
event WinnerPicked(ticket ticket, uint256 amount);
struct ticket {
address walletAddress;
uint256 ticketId;
}
uint256 currentTicketId = 0;
address gamblinoAddress = 0xE9FEA6A6A1a8BB99E0C888c93A06D22f804A5fFA;
uint public ticketPrice = 50 * 10**18;
address public manager;
ticket public winner;
ticket[] public tickets;
uint256 public balance;
constructor() {
manager = msg.sender;
balance = 0;
}
function getPlayerAddresses() private view returns (address[] memory) {
address[] memory addresses;
for(uint i = 0; i < tickets.length; i++) {
addresses[i] = tickets[i].walletAddress;
}
return addresses;
}
function buyTickets(uint256 quantity) public payable {
uint256 amount = ticketPrice * quantity;
GamblinoToken gamblinoToken = GamblinoToken(gamblinoAddress);
uint256 allowance = gamblinoToken.allowance(msg.sender, address(this));
uint256 playerBalance = gamblinoToken.balanceOf(msg.sender);
require(playerBalance >= amount, 'Check token balance');
require(allowance >= amount, 'Check the token allowance');
balance = balance + amount;
for (uint i = 0; i < quantity; i++) {
ticket memory t = ticket(msg.sender, currentTicketId);
tickets.push(t);
currentTicketId++;
}
gamblinoToken.transferFrom(msg.sender, address(this), amount);
emit TicketsBought(msg.sender, quantity, ticketPrice);
}
function random() public view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, getPlayerAddresses())));
}
function pickWinner() public {
uint index = random() % tickets.length;
uint256 amount = balance;
GamblinoToken gamblinoToken = GamblinoToken(gamblinoAddress);
// the entitre balance of this contract to the winner.
gamblinoToken.transfer(tickets[index].walletAddress, balance);
// set balance to 0
balance = 0;
// set winner
winner = tickets[index];
// reset ticket id
currentTicketId = 0;
// clear players and start over.
delete tickets;
emit WinnerPicked(winner, amount);
}
function getTickets() public view returns (ticket[] memory) {
return tickets;
}
// restrict to only the manager (the contract creator)
modifier restricted() {
require(msg.sender == manager);
_;
}
}
interface ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract GamblinoToken is ERC20Interface {
function totalSupply() public override view returns (uint256) {}
function balanceOf(address tokenOwner) public override view returns (uint) {}
function transfer(address receiver, uint numTokens) public override returns (bool) {}
function approve(address delegate, uint numTokens) public override returns (bool) {}
function allowance(address owner, address delegate) public override view returns (uint) {}
function transferFrom(address owner, address buyer, uint numTokens) public override returns (bool) {}
}
Related
I would like to call SwapExactTokensForTokensSupportingFeeOnTransferTokens in my contract to swap tokens with a transfer fee, however, the transaction reverts with an error. I have enough balance in the contract when calling the function.
The transaction that failed, which I called from the contract: https://dashboard.tenderly.co/tx/bsc/0xe44eba37baba3705376163d94f5d1051ac7ae9b2017ab9e403bad22f6a4c0577
When I perform the following (similar) transaction on the exchange, it works as expected: https://dashboard.tenderly.co/tx/bsc/0x5ab848527c12e76c6316859bab14a454a329aeade8046418f5dd542bcf1bd691/
With the debugging mode of Tenderly, I determined that the two transactions are similar except for the fact that the transaction in the contract had one additional approval call. Also when I submitted the transaction, a gas estimation error popped up in Remix.
Below is the code snippet of my contract. The other function, SwapExactTokensForTokens, is working in the contract call as expected. In the contract, SwapFeeOnExternal and SwapExternal are called to interact with the PancakeSwap Router.
pragma solidity >=0.8.14;
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);
}
interface IUniswapV2Router {
function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts);
}
contract SwapTradeExecution {
address owner;
constructor(){
// Set the owner to the account that deployes the contract
owner = msg.sender;
}
modifier onlyOwner() {
// Only owner can execute some functions
require(msg.sender == owner, "Only the owner is allowed to execute");
_;
}
function swapFeeOn(address router, address _tokenIn, address _tokenOut, uint256 _amount) internal {
// Single swap function for uniswap v2 swap.
IERC20(_tokenIn).approve(router, _amount);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
uint deadline = block.timestamp + 300;
IUniswapV2Router(router).swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, 0, path, address(this), deadline);
}
function swapExternal(address router, address _tokenIn, address _tokenOut, uint256 _amount, uint256 minAmount) external onlyOwner {
// Single swap function for uniswap v2 swap.
IERC20(_tokenIn).approve(router, _amount);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
uint deadline = block.timestamp + 300;
IUniswapV2Router(router).swapExactTokensForTokens(_amount, minAmount, path, address(this), deadline);
}
function swapFeeOnExternal(address router, address _tokenIn, address _tokenOut, uint256 _amount,uint256 minAmount) external onlyOwner {
// Single swap function for uniswap v2 swap.
IERC20(_tokenIn).approve(router, _amount);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
uint deadline = block.timestamp + 300;
IUniswapV2Router(router).swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, minAmount, path, address(this), deadline);
}
function tokenBalance(address token) public view returns (uint256) {
IERC20 token = IERC20(token);
return token.balanceOf(address(this));
}
function withdrawFunds(address token) external onlyOwner {
IERC20 token = IERC20(token);
uint balance = token.balanceOf(address(this));
require(balance > 0, "No avaliable fund to withdraw");
token.transfer(msg.sender, balance);
}
}
What's wrong with my smart contract, because I get "Error: cannot estimate gas; transaction may fail or may require manual gas limit". On frontend I am calling approveTokens() first and acceptPayment() later
pragma solidity ^0.8.11;
import '#openzeppelin/contracts/token/ERC20/IERC20.sol';
contract PaymentProcessor {
address public owner;
IERC20 public token;
constructor(address _owner, address _token) {
owner = _owner;
token = IERC20(_token);
}
event PaymentCompleted(
address payer,
uint256 amount,
uint paymentId,
uint timestamp
);
function approveTokens(uint256 amount) public returns(bool){
token.approve(owner, amount);
return true;
}
function getAllowance() public view returns(uint256){
return token.allowance(msg.sender, owner);
}
function acceptPayment(uint256 amount, uint paymentId) payable public {
require(amount > getAllowance(), "Please approve tokens before transferring");
token.transfer(owner, amount);
emit PaymentCompleted(msg.sender, amount, paymentId, block.timestamp);
}
}
Users need to call approve() directly on the token address - not through your contract.
Your current implementation approves owner to spend PaymentProcessor's tokens because PaymentProcessor is the msg.sender in the context of the token contract.
When I trigger buyMembership function from shasta.tronscan.io I am getting this error.
library SafeMath was working fine lately. But I do not know why it is giving me this error.
Please help me sort this thing I have already wasted a complete day on this.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
This is ITRC20 interface
interface ITRC20 {
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);
}
SafeMath library I used.
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
This is my contract. buyMembership function with correct params generates this error of
REVERT opcode executed. Message: SafeMath: subtraction overflow
contract TEST101 {
ITRC20 USDT;
address payable public owner;
address payable public ma;
address payable public fw;
struct User {
uint256 commission_balance;
uint256 member_id;
uint40 membership_time;
uint256 order_history;
}
struct History {
uint256 order_amount;
uint40 order_time;
}
struct Admin {
uint256 active;
}
mapping(uint256 => User) public users;
mapping(address => Admin) public admins;
mapping(uint256 => mapping(uint256 => History)) public histories;
event BuymemberShip(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
event BuyProduct(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
event Withdraw(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
event UpdateBalance(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
constructor(address payable _ma, ITRC20 _usdt, address payable _fw) {
ma = _ma;
owner = payable(msg.sender);
USDT = _usdt;
fw = _fw;
}
function buyMembership(uint256 _mid, uint256 _amount, uint256 _charges) external {
USDT.transferFrom(msg.sender, address(this), _amount);
users[_mid].membership_time = uint40(block.timestamp);
users[_mid].order_history = 0;
users[_mid].member_id = _mid;
USDT.transfer(fw, _charges);
emit BuymemberShip(msg.sender, _mid, _amount, uint40(block.timestamp));
}
function purchase(uint256 _mid, uint256 _amount) external {
USDT.transferFrom(msg.sender, address(this), _amount);
users[_mid].order_history += 1;
histories[_mid][users[_mid].order_history].order_amount = _amount;
histories[_mid][users[_mid].order_history].order_time = uint40(block.timestamp);
emit BuyProduct(msg.sender, _mid, _amount, uint40(block.timestamp));
}
function withdraw(address addr, uint256 _mid, uint256 _amount) external {
if (admins[msg.sender].active == 1 || msg.sender == ma) {
if (users[_mid].commission_balance >= _amount) {
users[_mid].commission_balance -= _amount;
USDT.transfer(msg.sender, _amount);
emit Withdraw(msg.sender, _mid, _amount, uint40(block.timestamp));
} else {
revert("not enough balance");
}
} else {
revert("permission denied");
}
}
}
I run my code on rinkeby etherscan network and it works perfectly. But the image and descriptions are not showing on opensea testnet. I run the /validate/ url it shows Valid: "false".
Here is what I found when I force update on opensea, https://testnets-api.opensea.io/api/v1/asset/0x668D179B933af761e4732B084290D32B3235C22b/0/?force_update=true
Here is my code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "hardhat/console.sol";
contract SmoothApe is ERC721URIStorage, Ownable, ERC2981ContractWideRoyalties {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIdCounter;
event EmitNFT(address sender, uint256 tokenId);
uint256 public preSaleTokenPrice = 0.01 ether;
uint256 public costPrice = 0.02 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintNft = 10;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
bool public paused = false;
bool public revealed = true;
bool public presale = false;
// set 0x7350243981aB92E2A3646e377EBbFC28e9DE96C1 as payable admn wallet
address payable public adminWallet = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
address payable public communityWallet = payable(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);
address payable public t1Wallet = payable(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);
address payable public t2Wallet = payable(0x617F2E2fD72FD9D5503197092aC168c91465E7f2);
address payable public t3Wallet = payable(0x17F6AD8Ef982297579C203069C1DbfFE4348c372);
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
constructor(string memory _name, string memory _symbol,string memory _initBaseURI, string memory _initNotRevealedUri) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedUri(_initNotRevealedUri);
}
// inherit and override erc165
function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC2981Base) returns (bool) {
return super.supportsInterface(interfaceId);
}
// set Royalty value (between 0 and 10000)
function setRoyalties(address recipient, uint256 value) public onlyOwner {
_setRoyalties(recipient, value);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function mintApe() public payable {
uint256 tokenId = _tokenIdCounter.current();
require(!paused, "Minting is paused");
require(msg.sender != owner(), "You can't mint ape to admin");
// require(_mintAmount > 0, "Mint amount must be greater than 0");
// require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
if(presale == true) {
preSaleTokenPrice = costPrice;
}
require(msg.value >= costPrice, string(abi.encodePacked("Must send at least ", costPrice.toString(), " ether to purchase")));
require(balanceOf(msg.sender) < maxMintNft, "You can only own 11 ape at a time");
// require(_mintAmount + balanceOf(msg.sender) <= maxMintNft, "You can only own 10 ape at a time");
// adminWallet.transfer(msg.value);
payable(owner()).transfer(msg.value);
emit EmitNFT(msg.sender, tokenId);
// for(uint256 i = 1; i <= _mintAmount; i++){
_safeMint(msg.sender, tokenId);
// _setTokenURI(tokenId, _baseURI());
_tokenIdCounter.increment();
// }
}
// admin mint ape to wallet
function mintApeTo(address _to, uint256 _mintAmount) public onlyOwner {
require(!paused, "Minting is paused");
require(_mintAmount > 0, "Mint amount must be greater than 0");
require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
for(uint256 i = 1; i <= _mintAmount; i++){
uint256 tokenId = _tokenIdCounter.current();
_safeMint(_to, tokenId);
// _setTokenURI(tokenId, _baseURI());
_tokenIdCounter.increment();
}
}
function getCostPrice() public view virtual returns (uint256) {
return costPrice;
}
// function to set cost of ape
function setCost(uint256 _preSaleTokenPrice, uint256 _publicTokenPrice) public onlyOwner {
preSaleTokenPrice = _preSaleTokenPrice;
costPrice = _publicTokenPrice;
}
// set presale to true
function setPresale(bool _presale) public onlyOwner {
presale = _presale;
}
function reveal(bool _reveal) public onlyOwner {
revealed = _reveal;
}
// pause function
function pause() public onlyOwner {
paused = true;
}
// set function for setBaseURI and setNotRevealed function
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
// override tokenURI function
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
require(tokenId < _tokenIdCounter.current(), "Token ID must be less than the total supply");
if(!revealed) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension))
: "";
}
}
Here is a sample of NFT i mint:
https://testnets.opensea.io/assets/0x668D179B933af761e4732B084290D32B3235C22b/0
my ipfs CID:
ipfs://QmaoMZ19zhpC6T4id6jdBP1Qz5dQSmRZMkQZU7Zt8hyFNQ/
as you can see in the right up corner there is a "reload" button, you need to click it to reload the ipfs on opensea
I had the same problem. Turned out that I wasn't uploading the images to ipfs correctly because it was visible only to me on my machine. So try to see if the ipfs metadata are correctly formated and are accesible from different devices.
Also you shouldn't just paste your entire contract in. Tt is really hard to answer your question then. Just write out the important sections of the code.
I am using the code below to create a smart contract, which receives BNB and sends the token created by the contract back.
I'm using Remix, and selecting the DEX contract to compile.
However, when I do this, the Token information does not appear on BscScan.
Example: https://testnet.bscscan.com/token/0xb570E6Fff85CBE695c9394bDa7d55fb38a009A28
And I can't add it to my wallet either, it says that the token code doesn't recognize it.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
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 ERC20Basic is IERC20{
string public constant name = "ByeSeel";
string public constant symbol = "BYS";
uint8 public constant decimals = 18;
//event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
//event Transfer(address indexed from, address indexed to, uint tokens);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
uint256 totalSupply_ = 10000000 * 10 ** 18;
using SafeMath for uint256;
constructor() {
balances[msg.sender] = totalSupply_;
}
function totalSupply() public override view returns (uint256) {
return totalSupply_;
}
function balanceOf(address tokenOwner) public override view returns (uint256) {
return balances[tokenOwner];
}
function transfer(address receiver, uint256 numTokens) public override returns (bool) {
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[receiver] = balances[receiver].add(numTokens);
emit Transfer(msg.sender, receiver, numTokens);
return true;
}
function approve(address delegate, uint256 numTokens) public override returns (bool) {
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
function allowance(address owner, address delegate) public override view returns (uint) {
return allowed[owner][delegate];
}
function transferFrom(address owner, address buyer, uint256 numTokens) public override returns (bool) {
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
} }
contract DEX {
event Bought(uint256 amount);
event Sold(uint256 amount);
IERC20 public token;
constructor() {
token = new ERC20Basic();
}
function buy() payable public {
uint256 amountTobuy = msg.value;
uint256 dexBalance = token.balanceOf(address(this));
require(amountTobuy > 0, "You need to send some Ether");
require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
token.transfer(msg.sender, amountTobuy);
emit Bought(amountTobuy);
}
function sell(uint256 amount) public {
require(amount > 0, "You need to sell at least some tokens");
uint256 allowance = token.allowance(msg.sender, address(this));
require(allowance >= amount, "Check the token allowance");
token.transferFrom(msg.sender, address(this), amount);
payable(msg.sender).transfer(amount);
emit Sold(amount);
}
receive() external payable {
buy();
}
}
The problem is that the DEX contract was not extending to the ERC20Basic contract
So I had to do:
contract DEX is ERC20Basic
This solved it, but I still have problems with the purchase and sale contract.