Assert.equal is not available when running Truffle Tests - solidity

I have a simple contract and I am trying to write Solidity tests for that contract in Truffle. Below are the code samples -
File: dummycontract.sol
pragma solidity ^0.4.17;
contract DummyContract {
uint[] public elements;
function addElement(uint element) public {
elements.push(element);
}
function getNumberOfElements() public view returns(uint) {
uint numElements = uint(elements.length);
return numElements;
}
}
And the test file -
pragma solidity ^0.4.17;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/dummycontract.sol";
contract TestZombieFactory {
function testInitialState() public {
DummyContract dummyContract = DummyContract(DeployedAddresses.DummyContract());
uint numberOfElements = dummyContract.getNumberOfElements();
Assert.equal(numberOfElements == 0);
}
}
On running truffle test, I get the following error -
TypeError: Member "equal" is not available in type(library Assert) outside of storage.
Assert.equal(numberOfElements == 0);
Can someone please explain this to me?

Your usage of Assert.equal() is not correct. It expects two values and does the comparison within the function. The function signature is
function equal(uint A, uint B, string message) constant returns (bool result)
Change your test contract to the following and it will work.
pragma solidity ^0.4.17;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/dummycontract.sol";
contract TestZombieFactory {
function testInitialState() public {
DummyContract dummyContract = DummyContract(DeployedAddresses.DummyContract());
uint numberOfElements = dummyContract.getNumberOfElements();
Assert.equal(numberOfElements, 0, "Number of elements should be 0");
}
}

You should replace
Assert.equal(numberOfElements == 0);
with
Assert.equal(numberOfElements,0);

Related

Allow ERC20 token for minting ERC721 NFT

I'm new in Solidity and trying to allow purchasing using ETH and other token such as USDT but I keep getting this error no matter what I tried.
DeclarationError: Identifier already declared. --> contract-9b5b02c5de.sol:9:1:
|
9 | import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
This is my code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "#openzeppelin/contracts#4.8.0/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts#4.8.0/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts#4.8.0/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts#4.8.0/access/Ownable.sol";
import "#openzeppelin/contracts#4.8.0/utils/Counters.sol";
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Combat is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
ERC20 public tokenUsdt;
uint256 public ethPrice = 0;
uint256 public usdtPrice = 0;
uint256 public maxSupply; //Maximum amount token
bool public isMintEnabled; //default : false
mapping(address=>uint256) public mintedWallets;
constructor(address _tokenUsdt) ERC721("XXX", "QAZ") {
maxSupply = 100;
tokenUsdt = ERC20(_tokenUsdt);
}
function setToken(address _tokenUsdt) external onlyOwner {
tokenUsdt = _tokenUsdt;
}
function setPrice(uint256 _ethPrice, uint256 _usdtPrice) external onlyOwner {
ethPrice = _ethPrice;
usdtPrice = _usdtPrice;
}
function buyMembershipUsdt() external payable {
require(msg.value >= usdtPrice, "Price Error");
tokenUsdt.safeTransferFrom(msg.sender, owner(), _amount);
mintMembership();
}
function buyMembershipEth() external payable {
require(msg.value >= ethPrice, "Price Error");
mintMembership();
}
function mintMembership() internal {
require(isMintEnabled, "Not For Sale");
require(totalSupply() < maxSupply, "Sold Out");
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
function setMintEnabled(bool isMintEnabled_) external onlyOwner {
isMintEnabled = isMintEnabled_;
}
function _baseURI() internal pure override returns (string memory) {
return "ipfs://bafybeiebgbvibloa3p3vge7ecxobwxxnuyg4pdozbcfjigfglhz2ogidq4/";
}
function setMaxSupply(uint256 maxSupply_) external onlyOwner{
maxSupply = maxSupply_;
}
function withdraw() public onlyOwner {
require(address(this).balance > 0, "Balance is 0");
payable(owner()).transfer(address(this).balance);
}
function withdrawToken() external onlyOwner {
uint256 tokenBalance = tokenUsdt.balanceOf(address(this));
require(tokenBalance > 0, "Insufficient balance");
tokenUsdt.safeTransfer(msg.sender, tokenBalance);
}
// The following functions are overrides required by Solidity.
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
}
I seen some guides our there but none seems to help because it uses custom token which I'm not using it. Regardless whether I'm using IERC20 or ERC20, I will keep getting error above I mentioned. Am I missing something or what?
You import should be
import "#openzeppelin/contracts#4.8.0/token/ERC20/ERC20.sol";
instead of
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";

Hardhat Compiling Error (_safeMint 'Undeclared identifier')

hello I'm writing a contract and got this error in my function.
function mintCardNFT(uint _cardIndex) external {
uint256 newItemId = _tokenIds.current();
_safeMint(msg.sender, newItemId);
nftHolderAttributes[newItemId] = CardAttributes({
cardIndex: _cardIndex,
name: defaultCards[_cardIndex].name,
imageURI: defaultCards[_cardIndex].imageURI,
alignments: defaultCards[_cardIndex].alignments,
power: defaultCards[_cardIndex].power,
maxPower: defaultCards[_cardIndex].maxPower,
resistance: defaultCards[_cardIndex].resistance,
income: defaultCards[_cardIndex].income
});
console.log("Minted NFT w/ tokenId %s and cardIndex %s", newItemId, _cardIndex);
nftHolders[msg.sender] = newItemId;
_tokenIds.increment();}
solidity version is 0.8.1 in hardhat.config and ^0.8.1 in contract.
everything looks normal to me. Merci!
You're trying to invoke a function _safeMint() but this function is not declared.
Most likely you forgot to derive your contract from the OpenZeppelin ERC721.
pragma solidity ^0.8;
// import the OpenZeppelin `ERC721` contract
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
// derive your contract from the imported `ERC721` contract
contract MyCollection is ERC721 {
// call the parent constructor
constructor() ERC721("MyCollection", "MyC") {}
function mintCardNFT() external {
// now the `_safeMint()` function is available
_safeMint(msg.sender, 1);
}
}

Not able to purchase the NFT I've created on Rarible (ropsten testnet)

I have created a nft on Rarible ( ropsten test net) but looks like people are not able to buy it....can anyone help me with why this seems to be happenning ?
rarible NFT : nft-link
solidity contract:
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "./rarible/impl/RoyaltiesV2Impl.sol";
import "./rarible/royalties/contracts/LibPart.sol";
import "./rarible/royalties/contracts/LibRoyaltiesV2.sol";
contract RoyaltyNFT is ERC721, Ownable, RoyaltiesV2Impl {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
constructor() ERC721("RoyaltyNFT", "ROYA") {}
function mint(address _to) public onlyOwner {
super._mint(_to, _tokenIdTracker.current());
_tokenIdTracker.increment();
}
function _baseURI() internal view virtual override returns (string memory) {
return "https://gateway.pinata.cloud/ipfs/QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH";
}
function setRoyalties(uint _tokenId, address payable _royaltiesReceipientAddress, uint96 _percentageBasisPoints) public onlyOwner {
LibPart.Part[] memory _royalties = new LibPart.Part[](1);
_royalties[0].value = _percentageBasisPoints;
_royalties[0].account = _royaltiesReceipientAddress;
_saveRoyalties(_tokenId, _royalties);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) {
if(interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) {
return true;
}
return super.supportsInterface(interfaceId);
}
}
I had followed a blog to create rarible NFT and i was able to do so but i was unable to sell it to other people as transfer could not be initiated by others.

Truffle test in solidity with sending value

duplicating my question from SA:
I have a simple contract with public function, that can receive value and do something based on that value:
pragma solidity >= 0.8.0 < 0.9.0;
contract ContractA {
uint public boughtItems = 0;
uint price = 10;
address [] buyers;
function buySomething() public payable {
require(msg.value >= price, "Sent value is lower");
boughtItems++;
buyers.push(msg.sender);
}
}
and in test folder of my Truffle project I have test contract:
pragma solidity >=0.8.0 <0.9.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/TicketsRoutes.sol";
contract TestTicketsRoutes {
ContractA instance;
address account1 = 0xD8Ce37FA3A1A61623705dac5dCb708Bb5eb9a125;
function beforeAll() public {
instance = new ContractA();
}
function testBuying() public {
//Here I need to invoke buySomething with specific value from specific address
instance.buySomething();
Assert.equal(instance.boughtItems, 1, "Routes amount is not equal");
}
}
How do I invoke function of ContractA in my TestContractA with passing value and sender?
You can use the low-level call() Solidity function to pass a value.
(bool success, bytes memory returnedData) = address(instance).call{value: 1 ether}(
abi.encode(instance.buySomething.selector)
);
But, in order to execute the buySomething() function from a different sender, you need to send it from a different address than the TestTicketsRoutes deployed address.
So you'll need to change your approach and perform the test from an off-chain script (instead of the on-chain test contract) that allows you to sign the transaction from a different sender. Since you tagged the question truffle, here's an example of executing a contract function using the Truffle JS suite (docs).
const instance = await MyContract.at(contractAddress);
const tx = await instance.buySomething({
from: senderAddress,
value: web3.toWei(1, "ether")
});

Ethereum Pet Shop tutorial - ParserError: Expected pragma, import directive or contract/interface/library definition

I'm trying to follow the tutorial here to learn how to code a dapp. I put together this .sol code (well, copy/pasted...):
pragma solidity ^0.5.0;
contract Adoption {
address[16] public adopters;
}
// Adopting a pet
function adopt(uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}
// Retrieving the adopters
function getAdopters() public view returns (address[16] memory) {
return adopters;
}
and there's another file that was already there. When I run the truffle compile command I see the following:
ParserError: Expected pragma, import directive or contract/interface/library definition.
function adopt(uint petId) public returns (uint) {
^------^
Compilation failed. See above.
Truffle v5.1.34 (core: 5.1.34)
Node v12.18.2
Any idea what I might be missing?
Functions must be within the contract scope:
pragma solidity ^0.5.0;
contract Adoption {
address[16] public adopters;
// Adopting a pet
function adopt(uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}
// Retrieving the adopters
function getAdopters() public view returns (address[16] memory) {
return adopters;
}
} // <= closing brace