Transfer ERC721 from owner to buyer - solidity

I'm trying to let other addresses execute the buy function, but it throws me the error ERC721: approve caller is not the owner nor approved for all
this is the code
function testbuy() public payable{
require(ownerOf(1) == _owner, "Already bought");
approve(msg.sender, 1);
safeTransferFrom(_owner, msg.sender, 1);
}
How could I make other address buy the NFT from the owner address? I'm having trouble understanding approve and setApproveForAll.. Thanks :)

Based on the error message, I'm assuming that you're using the Openzeppelin implementation of ERC721.
Since your contract derives from the OZ implementation, you can use their internal functions and don't need to go through the approve() and safeTransferFrom() process. If you wanted to go this way, you would need to invoke the approve() function from the _owner address directly - not by the buying user through the testbuy() function, as this was the logical error in your code.
Specifically, you can use the _transfer() function (source):
function testbuy() public payable{
require(ownerOf(1) == _owner, "Already bought");
_transfer(_owner, msg.sender, 1);
}

You can find your error OpenZeppelin ERC721 here:
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
Address which is calling testbuy() function has to be the owner of the token. In other case it cannot give the approval (or the token has to have approval for all), hence the approve function.

Related

There is a way to transfer / mint tokens without ERC20 owner approval method?

I trying to understand how crowdsale work in this way of buying tokens.
The part of send ether to a contract is ok, but the part of token transfer is still dark for me.
I have a ERC20Mintable token, in the latest version of openzeppelin.
My crowdsale contract will have thousands and thousands of buyers. In most tutorials, they teach transfering tokens with transferFrom, but that requires the approval of ERC20 owner correct ? Is what most of tutorials show. I can mint either, probably because only owner can mint tokens.
My question is: there is a method that users can buy tokens without any action of the ERC20 owner?
Thanks!
Owner approval is needed for transferFrom function. Because with this function you are allowing third-party account transfer from your account to someone.
Let's say I want to transfer token from your account to my brother's account. To be able to do this, you have to give permission first and this permission is stored in a mapping. If you allow me to transfer a specific amount from your account, you first add my account into this mapping
// my address is allowed to transfer token to other address
mapping(address=>mapping(address=>uint256)) allowed;
with approve function.
function approve(address _spender, uint256 _value) public override returns (bool success){
// you are calling this. so you are the msg.sender
// first we are checking if you have enough token to be transferred
require(tokenBalances[msg.sender]>=_value,"insufficient token");
// then you register my account with the _value
allowed[msg.sender][_spender]=_value;
// if in the future there is a dispute, we can check those events for verification
emit Approval(msg.sender,_spender,_value);
return true;
}
This where owner approval used. If you want to transfer money from your account to another account, you use the transfer function:
function transfer(address _to, uint256 _value) public override returns (bool success){
require(tokenBalances[msg.sender]>=_value,"you do not have enough tokens");
tokenBalances[msg.sender]-=_value;
tokenBalances[_to]+=_value;
emit Transfer(msg.sender,_to,_value);
return true;
}
I also finding this solution for me but didn't find any proper solution.
however find a solution for now.
create a function that is payable and pass amount(how much buyer buy) and make a keccak hash with (sender , value and amount) and store in a map and send transfer receive eth to _admin address.
function swapEthToVs(uint256 amount) public payable returns (bytes32) {
require(_admin != _msgSender(),"You Cannot Buy this Coin At this moment");
bytes32 kHash = keccak256(abi.encodePacked(msg.value,amount,_msgSender()));
swapHash[_origin()] = kHash;
payable(address(_admin)).transfer(msg.value);
return kHash;
}
then create api that take (sender , amount ,contractOwner) and call another function with contractOwnerSigner
function verifySwapHash(uint256 eth,address to,uint256 amount) public returns (bool) {
require(swapHash[to] == keccak256(abi.encodePacked(eth, amount, to)),"Invalid hash no trace found");
transfer(to, amount);
delete swapHash[to];
return true;
}
I know this is risky but i didn't found any solution. if you found any solution please describe solution.

Can a solidity smart contract execute the approve function in an erc20 contract on behalf of the msg.sender

Setting up a bank contract to perform deposits and withdraws. I was wondering if its possible for the bank contract can execute the approve function in the erc20 contract on behalf of the msg.sender for the tokens they are wanting to deposit.
Below is my attempt for the bank contract to call the erc20 token contracts approve function. However wouldn't the msg.sender be the bank contract address instead of the original msg.sender (second line of the depositToken function.) This sounds silly but is there a way for the contract to send the request passing in the msg.senders address? If not is there an integrated way for the msg.sender to approve the bank contract address and the amount to enable the bank contract to call the transferFrom function and be provided the allowance.
//best guess on what that would look like inside the function depositTokens
msg.sender = customer;
customer.IER20(usdt).approve.address(this), uint _amount;
address public usdt;
mapping(address => uint) public bankBalance;
constructor() public {
usdt = 0x77c24f0Af71257C0ee26e0E0a108F940D1698d53;
}
usdt = 0x77c24f0Af71257C0ee26e0E0a108F940D1698d53;
function depositTokens(uint _amount) public {
IER20(usdt).approve.address(this), uint _amount;
// Trasnfer usdt tokens to contract
IERC20(usdt).transferFrom(msg.sender, address(this), _amount);
// Update the bank balance in map
bankBalance[msg.sender] = bankBalance[msg.sender] + _amount;
}
//approve function in erc20
function approve(address delegate, uint256 numTokens) public override returns (bool) {
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
The answer is no, the approve function takes the msg.sender as the one that gives allowance. You can see the most used OpenZeppelin implementation here.
However I can see what you are trying to do and I want to add that there is a way to automatically ask an EOA (externally owned account) or a user with a wallet to approve some tokens to the contract before sending a transaction.
I don't know if a wallet does it automatically or you have to code it in the UI but I think that is what you are looking for.
And then after the user already approved your bank, you can remove your first line in the deposit function

Solidity: transferFrom can't reach allowance value

Here are the steps I follow on Remix:
Deploy my ERC20Basic token and my DEX contract.
DEX.buy > Buy ERC20Basic tokens in exchange of ETH (works fine).
ERC20Basic.approve(contractAddress, tokenAmount) (works fine).
ERC20Basic.allowance > Works fine, function returns the amount of the allowance.
The problem comes when I try to sell tokens with this function from my DEX contract:
function sell(uint256 amount) public {
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);
}
I still get "Check the token allowance".
When I log the allowance I get 0.
When I log msg.sender and address(this), I get the same addresses I used on the Remix interface to get the value of the allowance manually.
It feels like the allowance is reset to 0 when I call the sell function or that the sell function can't reach the value of the allowance. Maybe this is something about memory and storage?
My allowance function inside of ERC20Basic contract is:
function allowance(address owner, address delegate)
public
view
override
returns (uint256)
{
return allowed[owner][delegate];
}
Approval function:
function approve(address delegate, uint256 numTokens)
public
override
returns (bool)
{
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
Allowance structure:
mapping(address => mapping(address => uint256)) allowed;
How are you calling the approve function?
In your code you aren't passing the require statement because your approval wasn't successful. If it was your allowance wouldn't be 0.
You are probably calling the approve function from the contract which won't work because then the msg.sender would be address of the contract not your accounts address.
You have to approve the amount manually outside of the contract for it to work.

Burning Deployed ERC Tokens In an NFT Mint Function - Compiles, but Transaction Fails

I am very new to Solidity, and have recently been working on trying to learn the ropes. For reference, I have been using code from this video (https://www.youtube.com/watch?v=tBMk1iZa85Y) as a primer after having gone through the basic crypto zombies tutorial series.
I have been attempting to adapt the Solidity contract code presented in this video (which I had functioning just fine!) to require a Burn of a specified amount of an ERC-20 token before minting an NFT as an exercise for myself. I thought I had what should be a valid implementation which compiled in Remix, and then deployed to Rinkeby. I call the allowAccess function in Remix after deploying to Rinkeby, and that succeeds. But, when I call the mint function with the two parameters, I get: "gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? execution reverted."
If I still send the transaction, metamask yields "Transaction xx failed! Transaction encountered an error.".
I'm positive it has to do with "require(paymentToken.transfer(burnwallet, amounttopay),"transfer Failed");", though I'm not sure what's wrong. Below is my entire contract code. I'm currently just interacting with the Chainlink contract on Rinkeby as my example, since they have a convenient token faucet.
pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Counters.sol";
contract myNFTwithBurn is ERC721, Ownable {
address externalTokenAddress = 0x01BE23585060835E02B77ef475b0Cc51aA1e0709; //Token Type to burn on minting
uint256 amounttopay = 5; //number of these tokens to burn
IERC20 paymentToken = IERC20(externalTokenAddress); //my code: create an interface of the external token
address burnwallet = 0x000000000000000000000000000000000000dEaD; //burn wallet
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURIextended;
constructor() ERC721("NFTsWithBurn","NWB") {
}
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
function allowAccess() public
{
paymentToken.approve(address(this), 5000000); //This is my attempt to allow the contract access to the user's external tokens, in this case Chainlink (paymentToken)
}
function mintItem(address to, string memory tokenURI)
public
onlyOwner
returns (uint256)
{
require(paymentToken.transfer(burnwallet, amounttopay),"transfer Failed"); //Try to transfer 5 chainlink to the burn wallet
_tokenIds.increment();
uint256 id = _tokenIds.current();
_mint(to, id);
_setTokenURI(id, tokenURI);
return id;
}
}
If anybody can at least point me to what I'm doing completely wrong in the code that I've added, please do! TIA!
I'm not sure why are you trying to burn link in order to mint and nft but first check if the link code does not have a require that check if the destination address is the burn address if it has then burn the link is not possible and you should use any other erc20 maybe your own erc20, also your contract probably does not have any link and if you want to transfer the link from the user you should do this in the contract paymentToken.transferFrom(msg.sender,destinationAddress,amount) and if the user previously approve your contract you will able to send the tokens, and i suppose that the purpose of the allowAccess function is to make the user approve the contract to move the tokens that will never work, the approve function let's anyone that call it approve any address to move an amount of tokens, the thing is that to know who is approving to let other to move the tokens the function use msg.sender to explain how this work take a look at this example
let's say that your contract is the contract A and the link contract is the contract B
now a user call allowAccess in the contract A, so here the msg.sender is the user because they call the function
now internally this function call approve on contract B, here the contract A is the msg.sender, because the contract is who call the function
so what allowAccess is really doing is making the contract approving itself to move their own tokens that I assume it doesn't have

Smart Contract - BEP20: transfer amount exceeds allowance

I'm new in solidity and I'm trying to swap tokens from "Address A" to "Address B".
I used the functions approve and transferFrom, but I'm still getting the error: "Error: VM Exception while processing transaction: reverted with reason string 'BEP20: transfer amount exceeds allowance'"
Could you please help me with this issue?
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.3;
import "./CryptoPlinkoBall.sol";
import "./CryptoPlinko.sol";
import "hardhat/console.sol";
contract TokenSwap {
address admin;
address public owner;
address private _token;
constructor(address token) {
admin = msg.sender;
_token = token;
}
function swapTokens(address recipient, uint256 amount) external {
BEP20(_token).approve(msg.sender, amount);
BEP20(_token).allowance(msg.sender, address(this));
BEP20(_token).transferFrom(msg.sender, recipient, amount);
}
}
When you call BEP20(_token).approve(msg.sender, amount); you are approving the user to move that amount of tokens that the contract owns if you want to transfer the tokens from the user, the user should have called the token contract and approved the amount before calling this function, if you are doing the frontend that will interact with the contract you will need to put the call to the token contract first then the call to this contract
The approve must be mined before the transferFrom gets called.You can't do both on the same call, meanning the approve should occur before going into the swapTokens function.