Receiving a DeclarationError: Identifier not found or not unique while using counters using Remix - solidity

I am trying to run the code which is generating an error stating that DeclarationError: Identifier not found or not unique.
The smart contract NFTCollection is a solidity code which enables me to mint a specific number of ERC721 Tokens and to count the tokens of owner. I am receiving a error while displaying the error message "DeclarationError: Identifier not found or not unique" at line 20 which reads "using Counters for Counters.counter;"
Please find the code below.
Any help would be highly appreciated.
The contract and the error message.
pragma solidity ^0.8.4;
// Importing required libraries
/*
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/591c12d22de283a297e2b551175ccc914c938391/contracts/token/ERC721/ERC721.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/591c12d22de283a297e2b551175ccc914c938391/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/591c12d22de283a297e2b551175ccc914c938391/contracts/utils/Counters.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/591c12d22de283a297e2b551175ccc914c938391/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
*/
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
// This is a simple NFT contract
//Start of a contract
//INitialising contract as a ERC721, ERC721Enumerable, Ownable contract.
contract NFTCollection is ERC721, ERC721Enumerable, Ownable {
using Counters for Counters.counter;
// Specifing the maximum supply
uint256 maxSupply = 1000000;
// Initiatina a counter to store to be able to use Counters on uint265 without impacting the rest of the uint256 in the contract.
//Counter helps to find every function from a single library to a type to reduce gass fee.
Counters.Counter private _tokenIDCounter;
// Initialising a constructor.
constructor(string memory _name, string memory _symbol)
ERC721(_name, _symbol){}
// ERC721 interface is initialised and the _name, _symbol details aere passed in to hold.
//End of constructor.
//Start of function mint.
//This function is used to mint ERC721 tokens.
//Mint function adds the capability to mint ERC721 tokens and assign it to a address which accepts user address, number of tokens as arguments.
function mint(address _user, uint256 _amount) public {
//Start of for loop
for(uint256 i;i<_amount;i++)
{
//Incrementing the _tokenIdCounter by 1 using increment function.
_tokenIdCounter.increment();
// Creating a variable which stores the current value of _tokenIdCounter.
uint256 tokenId = _tokenIdcounter.current();
//Using safemint to mint ERC721 Tokens.
_safeMint(_user,tokenId);
}
}//End of function mint.
//Start of function tokensOfOwner
// This function is used to keep track of the owners Tokens.
// The function seeks a owner address to check the number of tokens he owns.
function tokensOfOwner(address _owner) public view returns (uint256[] memory)
{ // Creating a ownerTokenCount which stores the balance of the owner.
uint256 ownerTokenCount = balanceOf(_owner);
// Creating a memory variable and storing a array of ownerTokenCount.
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; ++i) {
ownedTokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}//End of for loop
return ownedTokenIds; //Return statement.
}
// Function overrides required by solidity
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
Error Message
--> contracts/nft.sol:20:24:
|
20 | using Counters for Counters.counter;~~~

Related

Is there a way to check how many times an ERC721 token has been minted?

I am using the OpenZeppelin's ERC721 Library, is there was a way to get the count of the number of times a token has been minted.
Is there a built-in mapping or function to check that?
You can use the Enumerable extension. The totalSupply() function returns the currently existing amount of tokens (minted minus burned), which in some cases might not the same thing as the total amount of minted tokens.
pragma solidity ^0.8;
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
/*
* `totalSupply()` (defined in ERC721Enumerable) returns 1
* even though 2 tokens were minted, but 1 was also burned
*/
contract MyCollection is ERC721Enumerable, ERC721Burnable {
constructor() ERC721("CollectionName", "Symbol") {
_mint(msg.sender, 1);
_burn(1);
_mint(msg.sender, 2);
}
// multiple parents define the same function
// overriding here just to point at the expected parent class
// related to the combination of `Burnable` and `Enumerable` in the same contract - not to `Enumerable` alone
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
return ERC721Enumerable._beforeTokenTransfer(from, to, tokenId);
}
// same reason for overriding as above
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return ERC721Enumerable.supportsInterface(interfaceId);
}
}
Or you can override the _beforeTokenTransfer() hook and create a custom counter that takes into account only minting and ignores burning.
pragma solidity ^0.8;
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
/*
* `mintCounter` returns 2, ignores the burned tokens
*/
contract MyCollection is ERC721Enumerable, ERC721Burnable {
uint256 public mintCounter;
constructor() ERC721("CollectionName", "Symbol") {
_mint(msg.sender, 1);
_burn(1);
_mint(msg.sender, 2);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
if (from == address(0)) {
mintCounter++;
}
return ERC721Enumerable._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return ERC721Enumerable.supportsInterface(interfaceId);
}
}

Definition of base has to precede definition of derived contract (ERC721 implementation)

The top SO or ETH Stack Exchange answers don't seem to apply to my case (I could be wrong of course)
I'm getting the error describer in the title in this file:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721Metadata.sol";
import "./ERC721.sol";
contract ERC721Connector is ERC721Metadata, ERC721 {
// ^^^^^^^ (Definition of base has to precede definition of derived contract)
constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) {}
}
Here's what ERC721Metadadata looks like:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ERC721Metadata {
string private _name;
string private _symbol;
constructor(string memory named, string memory symbolified) {
_name = named;
_symbol = symbolified;
}
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
}
And here is what ERC721 looks like:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721Metadata.sol";
import "./ERC721Connector.sol";
contract ERC721 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
mapping(uint256 => address) private _tokenOwner;
mapping(address => uint256) private _OwnedTokensCount;
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: minting to the zero address");
require(
!_exists(tokenId),
"ERC721: minting a token that already exists (been minted)"
);
_tokenOwner[tokenId] = to;
_OwnedTokensCount[to] += 1;
emit Transfer(address(0), to, tokenId);
}
}
Do you need to import ERC721Connector contract in your ERC721 contract? If not, you can remove
import "./ERC721Connector.sol"; // line 4, ERC721.sol
from your file and it should work fine. Your imports are causing the issue,
ERC721Connector tries to import ERC721, but ERC721 also needs ERC721Connector so the compiler says
Definition of base has to precede definition of derived contract
Because the base contract doesn't precede the defined contract.

Solidity - why does fallback() get called even though address.call{value:msg.value}("") does not have data?

The following contract calls another contract using an interface method (code to change):
pragma solidity 0.8.7;
interface MyStorage {
function setStorageValue(uint256) external;
}
contract StorageFactory {
uint256 storageValue;
constructor(uint256 _storageValue) {
storage = _storageValue;
}
function initStorage(MyStorage store) public payable {
store.setStorageValue(storageValue);
address payable storeAddress = payable(address(store));
storeAddress.call{value: msg.value}("");
}
}
Following is the StorageContract (code cannot be changed):
pragma solidity 0.8.7;
contract Storage {
int _storageValue;
function setStorageValue(int storageValue) public {
_storageValue = storageValue;
}
receive() external payable {
require(_storageValue == -1 || address(this).balance <= uint(_storageValue), "Invalid storage value");
}
fallback() external {
_storageValue = -1;
}
}
I use a test to call initStorage of the first contract by passing a Storage object, where the test is meant to fail because the value is set to a large amount. But somehow, the fallback() function seems to get called, setting the value to -1. I can't figure out why. Any help is appreciated.
Due to the solidity doc:
The fallback function is executed on a call to the contract if none of the other functions match the given function signature, or if no data was supplied at all and there is no receive Ether function. The fallback function always receives data, but in order to also receive Ether it must be marked payable.
Your function getting called because there's no overloading for the function
function setStorageValue(uint256 storageValue) public
So change the storageValue from int to uint256 will help.

Solidity calling contract with elevated permissions

I have two contracts, one for handling staking and one for minting a NFT. The flow I want is for the user to stake in frontend react app which will invoke the staking contract. The user will then be eligible to mint a NFT when staked.
Now the issue I am facing is that because the minting role is called from stakingExample contract, which requires the user to invoke this, but as it has a critical function (mint) of the other contract, it should be protected with permissions such that only StakingExample can call NFTExample contract.
Is there a way to allow the user to run NFTExample with elevated permissions temporary in smart contract?
Example of staking contract:
// SPDX-License-Identifier: unlicensed
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/access/AccessControl.sol";
import "#openzeppelin/contracts/token/ERC20/IERC20.sol";
import "#openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract StakingExample is AccessControl {
bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE");
NFTExample public _NFTExample;
...
function someStakingFunction() {
// code that stakes and
// set some variable that tracks if user have minted
}
function claimNFT(uint256 _pid, string memory _tokenURI) public onlyRole(CONTRACT_ROLE) {
// checks if user have unclaimed NFT
if (haveUnclaimed) {
_NFTExample.mintItem(msg.sender, _tokenURI)
}
}
}
Example of NFT contract:
// SPDX-License-Identifier: unlicensed
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/access/AccessControl.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
contract CMRGachaSeedNFT is ERC721URIStorage, AccessControl, ERC721Enumerable {
bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE");
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
...
// Only Contract Role can call mint item, which mint item and transfers it to user's address
function mintItem(address _address, string memory _tokenURI)
public
onlyRole(CONTRACT_ROLE)
returns (uint256)
{
// Do some checks
// Mint
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(_address, newItemId);
_setTokenURI(newItemId, _tokenURI);
return newItemId;
}
}
You need to add one function in staking contract which shows amount of the staking:
function showStakeAmount() external view returns(uint256){
//I don't know your codes about this but you need a mapping to store
//the stake amount of each user and here you return it but something like this:
return StakingAmountOfUsers(msg.sender);
}
Then you need an interface of the staking contract and its address, also make an modifier in NFT contract (Following changes must be added):
interface StakingInterface{
function showStakeAmount() external view returns(uint256);
}
contract CMRGachaSeedNFT is ERC721URIStorage, AccessControl, ERC721Enumerable {
uint256 AmountThatShouldBeStaked;
StakingInterface StakingContract;
constructor(address STAKING_CONTRACT_ADDRESS){
StakingContract = StakingInterface(STAKING_CONTRACT_ADDRESS);
}
modifier isStaked(){
require(StakingContract.showStakeAmount() > AmountThatShouldBeStaked, "You did not stake enough amount of X token");
_;
}
function mintItem(address _address, string memory _tokenURI)
public
onlyRole(CONTRACT_ROLE)
returns (uint256)
isStaked()
{
//Continue coding...
}
}

How to make an API call in solidity?

I have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.
"example-winner.com/winner"
And it returns simple JSON with the address of the winner:
{"winner":"0xa7D0......."}
However, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.
Any thoughts? Below is my code:
pragma solidity ^0.4.24;
contract LeagueWinners{
address public manager;
address[] public players;
uint256 MINIMUM = 1000000000000000;
constructor() public{
manager = msg.sender;
}
function enter() public payable{
assert(msg.value > MINIMUM);
players.push(msg.sender);
}
function getWinner() public{
assert(msg.sender == manager);
// TODO
// Get the winner from the API call
result = 0; // the result of the API call
players[result].transfer(address(this).balance);
// returns an adress object
// all units of transfer are in wei
players = new address[](0);
// this empties the dynamic array
}
}
You can use Chainlink as your Oracle.
As many have mentioned, you will need an oracle to get your API call. Something that is important to note, your contract is actually asking an oracle to make your API call for you, and not making the API call itself. This is because the blockchain is deterministic. For more information see this thread.
To answer your question, you can use the decentralized oracle service Chainlink.
You'd add a function:
function getWinner()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
For the purpose of the following exmaple, we are going to pretend you want to return a uint256 instead of an address. You can return a bytes32 and then convert it to an address, but for simplicity let's say the API returns the index of the winner. You'll have to find a node and jobId that can make a http.get request and return a uint256 object. You can find nodes and jobs from market.link. Each testnet (Ropsten, Mainnet, Kovan, etc) has different node addresses, so make sure you pick the right ones.
For this demo, we are going to use LinkPool's ropsten node
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
Ideally, you'd choose a number of nodes to run your job, to make it trustless and decentralized. You can read here for more information on precoordinators and aggregating data. disclosure I am the author of that blog
Your full contract would look like:
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract GetData is ChainlinkClient {
uint256 indexOfWinner;
address public manager;
address payable[] public players;
uint256 MINIMUM = 1000000000000000;
// The address of an oracle
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
//bytes32 JOB= "93fedd3377a54d8dac6b4ceadd78ac34";
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
uint256 ORACLE_PAYMENT = 1 * LINK;
constructor() public {
setPublicChainlinkToken();
manager = msg.sender;
}
function getWinnerAddress()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
// When the URL finishes, the response is routed to this function
function fulfill(bytes32 _requestId, uint256 _index)
public
recordChainlinkFulfillment(_requestId)
{
indexOfWinner = _index;
assert(msg.sender == manager);
players[indexOfWinner].transfer(address(this).balance);
players = new address payable[](0);
}
function enter() public payable{
assert(msg.value > MINIMUM);
players.push(msg.sender);
}
modifier onlyOwner() {
require(msg.sender == manager);
_;
}
// Allows the owner to withdraw their LINK on this contract
function withdrawLink() external onlyOwner() {
LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());
require(_link.transfer(msg.sender, _link.balanceOf(address(this))), "Unable to transfer");
}
}
This would do about everything you need.
If you can't adjust the API to return a uint, you can return a bytes32 and then convert it to an address or a string.
function bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
You cannot. The vm does not have any I/O outside of the blockchain itself. Instead you will need to tell your smart contract who the winner is and then the smart contract can just read the value of that variable.
This design pattern is also known as the "oracle". Google "Ethereum oracle" for more info.
Basically your web server can call your smart contract. Your smart contract cannot call your web server. If you need your smart contract to access a 3rd party service then your web server will need to make the request then forward the result to solidity by calling a function in your smart contract.
You didn't properly explain what you are trying to do. Are you having trouble with the solidity code? or rather with your server? Here is an edited version. See if it helps.
pragma solidity ^0.4.24;
contract LeagueWinners{
address public manager;
//address[] public players;
uint256 MINIMUM = 1000000000000000;
constructor() public{
manager = msg.sender;
}
struct Player {
address playerAddress;
uint score;
}
Player[] public players;
// i prefer passing arguments this way
function enter(uint value) public payable{
assert(msg.value > MINIMUM);
players.push(Player(msg.sender, value));
}
//call this to get the address of winner
function winningPlayer() public view
returns (address winner)
{
uint winningScore = 0;
for (uint p = 0; p < players.length; p++) {
if (players[p].score > winningScore) {
winningScore = players[p].score;
winner = players[p].playerAddress;
}
}
}
// call this to transfer fund
function getWinner() public{
require(msg.sender == manager, "Only a manager is allowed to perform this operation");
// TODO
address winner = winningPlayer();
// Get the winner from the API call
//uint result = 0; // the result of the API call
winner.transfer(address(this).balance);
// returns an adress object
// all units of transfer are in wei
delete players;
// this empties the dynamic array
}
}
At least that is what I understand by your question.