ERC721 How to sign EIP-712 and verify if the signer of signature is the owner of the NFT? - solidity

How to sign EIP-712 and verify if the signer of signature is the owner of the NFT ?
using Counters for Counters.Counter;
using ECDSA for bytes32;
Counters.Counter private _tokenIdCounter;
mapping(address => uint256) private userInfo;
bytes32 private constant TYPEHASH =
keccak256("NFT(EIP712 nftcontract,uint256 tokenId)");
constructor() EIP712("aaa", "1.0.0") {}
function depositNFT(NFT calldata nft, bytes calldata signature) public override returns (bool signerIsOwner)
{
require(verify(nft, signature));
uint256 tokenId = _tokenIdCounter.current();
userInfo[msg.sender] = tokenId;
_tokenIdCounter.increment();
return signerIsOwner;
}
function verify(NFT calldata nft, bytes calldata signature) public view returns (bool) {
address signer = _hashTypedDataV4(
keccak256(abi.encode(TYPEHASH, nft.nftcontract, nft.tokenId))
).recover(signature);
return true;
}
The idea here is when I try to deposit NFT (using the depositNFT function) the metasmask sign a message and verify if you are the owner of the NFT or not

Related

I generated a flattened of my contract using Remix but it gives error: Definition of base has to precede definition of derived contract

I thibk the error is occurring because the contract "ERC721Burnable" is trying to inherit from two other contracts "Context" and "ERC721", but "Context" is not defined in the code you provided. So, the definition of a base contract must precede the definition of a derived contract.
How can I make sure that the definition of the "Context" contract is included before the definition of the "ERC721Burnable" contract. Additionally, How can I make sure that "Context" is defined in the same file or imported from a different file.
Bellow is the code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/token/common/ERC2981.sol";
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts/security/Pausable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "#openzeppelin/contracts/utils/math/SafeMath.sol";
contract AliveNatureNFT is ERC721, ERC721Enumerable, ERC721URIStorage, ERC2981, Pausable, ERC721Burnable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
// percentage split for commission and liquidity pool
uint96 public commissionPercentage;
uint96 public liquidityPercentage;
// address of the commission recipient
address public commissionRecipient;
// address of the liquidity pool
address public liquidityPoolRecipient;
// Owner address
address public ownerNFT;
//Base URI
string private url;
struct ProjectData {
string name;
uint256 projectTokenId;
string methodology;
string region;
string emissionType;
string uri;
address creator;
}
struct RetireData {
uint256 retireTokenId;
address beneficiary;
string retirementMessage;
uint256 timeStamp;
uint256 amount;
}
mapping (uint256 => ProjectData) private _projectData;
mapping (uint256 => RetireData) private _retireData;
modifier onlyOwner(address _sender) {
require(_sender == ownerNFT, "Only the owner can call this function");
_;
}
modifier onlyAdmin (address _sender) {
require(_sender == commissionRecipient, "Only the heir can call this function");
_;
}
constructor(
uint96 _liquidityPercentage, address _liquidityPoolRecipient,
string memory _MyToken, string memory _Symbol, string memory _url, address _ownerNFT
) ERC721(_MyToken, _Symbol) {
commissionPercentage = 100;
liquidityPercentage = _liquidityPercentage;
commissionRecipient = 0xE3506A38C80D8bA1ef219ADF55E31E18FB88EbF4;
liquidityPoolRecipient = _liquidityPoolRecipient;
ownerNFT = _ownerNFT;
_setDefaultRoyalty(commissionRecipient, commissionPercentage);
url = _url;
}
function _baseURI() internal view override returns (string memory) {
return url;
}
function pause(address _sender) external onlyAdmin(_sender) {
_pause();
}
function unpause(address _sender) external onlyAdmin(_sender) {
_unpause();
}
function safeMint(address _to, string memory _uri, string memory _name,
string memory _methodology, string memory _region, string memory _emissionType, address _sender) public whenNotPaused onlyOwner(_sender) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(_to, tokenId);
_setTokenURI(tokenId, _uri);
// Create a new ProjectData struct and store it in the contract's storage
_projectData[tokenId] = ProjectData({
projectTokenId : tokenId,
uri : _uri,
name : _name,
methodology : _methodology,
region : _region,
emissionType : _emissionType,
creator : _sender
});
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId, uint256 batchSize)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId, batchSize);
if (from != address(0)) {
address owner = ownerOf(tokenId);
require(owner == msg.sender, "Only the owner of NFT can transfer or burn it");
}
}
function _burn(uint256 tokenId) internal whenNotPaused override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function burnToken(uint256 tokenId, string memory _retirementMessage, uint256 _amount, address _sender) public whenNotPaused onlyOwner(_sender) {
address owner = ownerOf(tokenId);
require(owner == msg.sender, "Only the owner of NFT can burn it");
_burn(tokenId);
// Create a new ProjectData struct and store it in the contract's storage
_retireData[tokenId] = RetireData({
retireTokenId : tokenId,
beneficiary : msg.sender,
retirementMessage : _retirementMessage,
timeStamp : block.timestamp,
amount : _amount
});
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC2981, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
I'm trying to group everything in a flattened contract to have the complete ABI

solidity : Allowance too low

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

What does LINK_TOKEN_POINTER do

I am trying to get chainlink to work on harmony one block chain, I am trying to deploy a testing contract extending chainlinkclient.sol to test out the setup but for some reason it won't deploy. I am wondering if it's because of the LINK_TOKEN_POINTER hardcoded to 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571. Does anyone know what that address is? Is it the same for all the ETH testnets (rinkeby, kovan, etc) and other chains as well?
I am trying to deploy the TestConsumer.sol contract onto the Harmony One chain but am getting an error. I was able to get it to work on Kovan.
I suspect it might be due to the LINK_TOKEN_POINTER. Does anyone know how I can get this to work?
pragma solidity 0.4.24;
import "https://github.com/smartcontractkit/chainlink/evm-contracts/src/v0.4/ChainlinkClient.sol";
import "https://github.com/smartcontractkit/chainlink/evm-contracts/src/v0.4/vendor/Ownable.sol";
contract ATestnetConsumer is ChainlinkClient, Ownable {
uint256 constant private ORACLE_PAYMENT = 1 * LINK;
uint256 public currentPrice;
int256 public changeDay;
bytes32 public lastMarket;
event RequestEthereumPriceFulfilled(
bytes32 indexed requestId,
uint256 indexed price
);
event RequestEthereumChangeFulfilled(
bytes32 indexed requestId,
int256 indexed change
);
event RequestEthereumLastMarket(
bytes32 indexed requestId,
bytes32 indexed market
);
constructor() public Ownable() {
setPublicChainlinkToken();
}
function requestEthereumPrice(address _oracle, string _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillEthereumPrice.selector);
req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
req.add("path", "USD");
req.addInt("times", 100);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function requestEthereumChange(address _oracle, string _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillEthereumChange.selector);
req.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
req.add("path", "RAW.ETH.USD.CHANGEPCTDAY");
req.addInt("times", 1000000000);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function requestEthereumLastMarket(address _oracle, string _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillEthereumLastMarket.selector);
req.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
string[] memory path = new string[](4);
path[0] = "RAW";
path[1] = "ETH";
path[2] = "USD";
path[3] = "LASTMARKET";
req.addStringArray("path", path);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function fulfillEthereumPrice(bytes32 _requestId, uint256 _price)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumPriceFulfilled(_requestId, _price);
currentPrice = _price;
}
function fulfillEthereumChange(bytes32 _requestId, int256 _change)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumChangeFulfilled(_requestId, _change);
changeDay = _change;
}
function fulfillEthereumLastMarket(bytes32 _requestId, bytes32 _market)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumLastMarket(_requestId, _market);
lastMarket = _market;
}
function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunctionId,
uint256 _expiration
)
public
onlyOwner
{
cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
}
The LINK_TOKEN_POINTER is a contract that is hard-coded with pointers to the LINK token on various chains. This is so that the contract knows which LINK token to use.
For a chain like harmony, the LINK token pointer probably has not been added for that chain.
To get around this, you'll want to manually set the LINK token, like so:
constructor(address _link) public {
if (_link == address(0)) {
setPublicChainlinkToken();
} else {
setChainlinkToken(_link);
}
It looks like there isn't a LINK token on the Harmony chain yet, so you could deploy a dummy LINK token and point the address to that.

DeclarationError: Undeclared identifier

I am trying to create a token using solidity programming, but I keep getting this undeclared identifier error when I compile on remix browser IDE. I am new to solidity and how can I solve this problem?
I have attached my code here:
pragma solidity >=0.4.16 < 0.6.0;
/*declare an interfaced named tokenReceipent so that any contract that implements receiveApproval function counts as a tokenReceipent*/
interface tokenRecipient
{
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external;
}
contract TokenERC20 //create a contract ERC20 and declare public variables of the token
{
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256)public balanceOf; // create mapping with all balances
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value); //create an event on blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from,uint256 value); //create an event that notifies clients about the amount burn
constructor(uint256 initialSupply, string memory tokenName, string memory tokenSymbol) // create a construct that initialized tokens to the creator of the contract
public
{
totalSupply = initialSupply*10** uint256(decimals); //update total supply with des 1 1 out
balanceOf[msg.sender]=totalSupply;//give creator all initial tokens
name=tokenName; //set the name and symbol for display purposes
symbol=tokenSymbol;
}
//create an internal function and can only be called by this smartContract
function _transfer(address _from, address _to, uint _value) internal
{
//prevent transfer to 0x0 address
//check that the balance of the sender has enough
//add thesame to the recepient
//insert assert to use static analysis to find bugs in your code,they should never fail
require(_to!=address(0x0));
//subtract from the sender
require(balanceOf[_from]>= _value);
//add thesame to the receipent
require(balanceOf[_to] + _value>= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_from] += _value;
emit Transfer(_from , _to, _value);
//assert are used to find static analysis in your code,they should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
//create to transfer function
function transfer(address _to, uint256 _value)
public returns(bool success)
{
_transfer(msg.sender, _to, _value);
return true;
}
//create a from transfer function to transfer tokens from other address
function transferFrom(address _from, address _to, uint256 _value)
public returns(bool success)
{
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
//create allowances for other address
//allows spender not spend a certain allowance on your behalf
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public returns(bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value)
public returns (bool success)
{
require(balanceOf[msg.sender]>= _value);
balanceOf[msg.sender] -= _value; //subtract from the sender
totalSupply -= _value; //update the total supply of tokens
emit Burn(msg.sender, _value);
return true;
}
// function that destroys token from other(users/subscribers) accounts
function burnFrom(address _from, uint256 _value)
public returns(bool success)
{
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
The code is failing to compile due to the error:
browser/Token.sol:73:17: DeclarationError: Undeclared identifier.
if (approve(_spender, _value)) {
^-----^
Your code doesn't declare an approve function, hence the error.
If you didn't write the code yourself, I suggest you check the original source of the code for the approve function.
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public returns(bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
To learn about tokens I suggest you read the OpenZeppelin documentation on tokens:
https://docs.openzeppelin.org/v2.3.0/tokens
You could deploy to a testnet a simple token that uses OpenZeppelin with Remix
pragma solidity ^0.5.0;
import "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
/**
* #title SimpleToken
* #dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `ERC20` functions.
*/
contract SimpleToken is ERC20, ERC20Detailed {
/**
* #dev Constructor that gives msg.sender all of existing tokens.
*/
constructor () public ERC20Detailed("SimpleToken", "SIM", 18) {
_mint(msg.sender, 10000 * (10 ** uint256(decimals())));
}
}
You can also ask questions at:
Ethereum Stack Exchange: https://ethereum.stackexchange.com/
Zeppelin Community Forum: https://forum.zeppelin.solutions/

Openzeppelin ERC20 make revert

my intent is making ERC721 token can transfer by my ERC20 token only
the transfer flow is
Buyer approve ERC20 to Seller.
Seller transfer ERC721 to Buyer.
My ERC721 Token's transfer function transfer ERC20 to Seller from Buyer first, and transfer ERC721 to Buyer from Seller.
revert error occur to ERC20 transfer step.
i try to every single line delete to find revert point.
and i found that.
this is my test code
const token20 = artifacts.require("MyToken20");
const token721 = artifacts.require("MyToken721");
contract("Test", async()=>{
//...
// Buyer token20 approve to Seller
it("Token20 approve", async()=>{
var value = web3.toWei(token721Price, "ether");
await contract20.approve(seller, value, {from:buyer});
var allowed = await contract20.allowance(buyer, seller);
allowed = web3.fromWei(allowed, "ether");
assert.equal(allowed, token721Price);
});
// Seller transfer token721 to Buyer
// token20 transfer to Seller inside of function transferMy721
it("Token721 transfer", async()=>{
var allowed = await contract20.allowance(buyer, seller);
allowed = web3.fromWei(allowed, "ether");
assert.equal(allowed, token721Price);
await contract721.transferMy721(buyer, token721Id, {from:seller}); // <--- revert here
var newOwner = await contract721.ownerOf(token721Id);
assert.equal(newOwner, buyer);
});
});
and revert point in my contract is here
contract MyToken721 is ERC721Token{
string public name = "My ERC721 Token Product";
string public symbol = "MTP";
mapping(uint256 => uint256) my721TokenPrice;
MyToken20 token;
constructor(MyToken20 _token) public ERC721Token(name, symbol){
require(_token != address(0));
token = _token;
}
function mint(address _to, uint256 _tokenId, uint256 _price) public {
_mint(_to, _tokenId);
my721TokenPrice[_tokenId] = _price;
}
function transferMy721(address _to, uint256 _tokenId) public returns(bool){
require(msg.sender == ownerOf(_tokenId));
uint256 tokenPrice = my721TokenPrice[_tokenId];
if( token.transferFrom(_to, msg.sender, tokenPrice) == false ) // <--- revert here
return false;
super.approve(_to, _tokenId);
super.transferFrom(msg.sender, _to, _tokenId);
return true;
}
//...
}
and revert point in ERC20 StandardToken contract is here
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]); // <--- revert here
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
//...
}
as you can see, in my test code, i double check
allowed[_from][msg.sender]
please check my full code here
the one calling transferFrom is my erc721 contract.
so, i change test code
await contract20.approve(seller, value, {from:buyer});
change to
await contract20.approve(contract721.address, value, {from:buyer});
thank you for SylTi