Compilation warnings encountered(truffle test) - solidity

When I run truffle test,
I get the following statement.
Is it an error?
Compilation warnings encountered:
project:/contracts/Fundraiser.sol:18:5: Warning: This declaration
shadows an existing declaration.
address payable _beneficiary,
^--------------------------^
project:/contracts/Fundraiser.sol:8:5: The shadowed declaration is
here:
address payable _beneficiary;
^--------------------------^
,project:/contracts/Fundraiser.sol:19:5: Warning: This declaration
shadows an existing declaration.
address _custodian
^----------------^
project:/contracts/Fundraiser.sol:9:5: The shadowed declaration is
here:
address _custodian;
^----------------^
CompileError: project:/contracts/Fundraiser.sol:27:9:
DeclarationError: Undeclared identifier. Did you mean "_beneficiary"
or "_beneficiary"?
beneficiary = _beneficiary;
^---------^
,project:/contracts/Fundraiser.sol:28:9: DeclarationError: Undeclared
identifier. Did you mean "_custodian" or "_custodian"?
custodian = _custodian;
^-------^
The code for the smart contract is as follows.
#Fundraiser.sol
pragma solidity >0.4.23 <0.7.0;
contract Fundraiser{
string public name;
string public url;
string public imageURL;
string public description;
address payable _beneficiary;
address _custodian;
constructor(
string memory _name,
string memory _url,
string memory _imageURL,
string memory _description,
address payable _beneficiary,
address _custodian
)
public{
name = _name;
url = _url;
imageURL = _imageURL;
description = _description;
beneficiary = _beneficiary;
custodian = _custodian;
}
 }
The code for the test is as follows.
#test/fundraiser_test.js
const FundraiserContract = artifacts.require("Fundraiser");
contract("Fundraiser", accounts => {
let fundraiser;
const name = "Beneficiary Name";
const url = "[beneficiaryname.org](http://beneficiaryname.org/)";
const imageURL="[https://placeKitten.com/600/350](https://placekitten.com/600/350)";
const description = "Beneficiary description";
const beneficiary = accounts[1];
const cunstodian = accounts[0];
beforeEach(async () => {
fundraiser = await FundraiserContract.new(
name,
url,
imageURL,
description,
beneficiary,
cunstodian
)
});
describe("initialization", () => {
it("gets the beneficiary name", async () => {
const actual = await [fundraiser.name](http://fundraiser.name/)();
assert.equal(actual, name, "names should match");
});
it("gets the beneficiary url", async () => {
const actual = await fundraiser.imageURL();
assert.equal(actual, imageURL, "imageURL should match");
});
it("gets the beneficiary image url", async () => {
const actual = await [fundraiser.name](http://fundraiser.name/)();
assert.equal(actual, name, "names should match");
});
it("gets the beneficiary description", async () => {
const actual = await fundraiser.description();
assert.equal(actual, description, "description should match");
});
it("gets the beneficiary", async () => {
const actual = await fundraiser.beneficiary();
assert.equal(actual, beneficiary, "beneficiary should match");
});
it("gets the cunstodian", async () => {
const actual = await fundraiser.cunstodian();
assert.equal(actual, cunstodian, "cunstodian should match");
});
});
});;

You can't name state variables and input argument Variables the same, it will confuse the compiler on which one to use.
You first defined _beneficiary and _custodian as a state variables on
project:/contracts/Fundraiser.sol:8:5
and
project:/contracts/Fundraiser.sol:9:5
respectively. and then later on in the constructor input you named the variable same, at line number
project:/contracts/Fundraiser.sol:18:5
project:/contracts/Fundraiser.sol:19:5
You have to change the naming and differentiate it so that compiler can understand, what you are trying to do.
For instance, normally when we add an underscore before the variable name in the temp variable (input arguments), not with state variables unless they are private.
in short your code shold look like this.
pragma solidity >0.4.23 <0.7.0;
contract Fundraiser{
string public name;
string public url;
string public imageURL;
string public description;
address payable beneficiary; //removed underscore
address custodian; //removed underscore
constructor(
string memory _name,
string memory _url,
string memory _imageURL,
string memory _description,
address payable _beneficiary,
address _custodian
)
public{
name = _name;
url = _url;
imageURL = _imageURL;
description = _description;
beneficiary = _beneficiary;
custodian = _custodian;
}
 }
Don't forget to accept the answer.

Related

NomicLabsHardhatPluginError: The constructor for contracts/FundMe.sol:FundMe has 1 parameters but 0 arguments were provided instead

I'm trying to verify and submit my contract source code to etherscan using a headset, but I'm getting the following error and I don't understand how to solve it. I've read through the code and can't figure out what I'm doing wrong. Please can anyone advise?
The error that I am getting when I run:
NomicLabsHardhatPluginError: The constructor for contracts/FundMe.sol:FundMe has 1 parameters
but 0 arguments were provided instead.
heres all the code FundMe.sol code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "./PriceConverter.sol";
error NotOwner();
contract FundMe {
using PriceConverter for uint256;
mapping(address => uint256) public addressToAmountFunded;
address[] public funders;
address public /* immutable */ i_owner;
uint256 public constant MINIMUM_USD = 50 * 10 ** 18;
AggregatorV3Interface public priceFeed;
constructor(address priceFeedAddress) {
i_owner = msg.sender;
priceFeed = AggregatorV3Interface(priceFeedAddress);
}
function fund() public payable {
require(msg.value.getConversionRate(priceFeed) >= MINIMUM_USD, "You need to spend more ETH!");
addressToAmountFunded[msg.sender] += msg.value;
funders.push(msg.sender);
}
modifier onlyOwner {
if (msg.sender != i_owner) revert NotOwner();
_;
}
function withdraw() payable onlyOwner public {
for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++){
address funder = funders[funderIndex];
addressToAmountFunded[funder] = 0;
}
funders = new address[](0);
(bool callSuccess, ) = payable(msg.sender).call{value: address(this).balance}("");
require(callSuccess, "Call failed");
}
fallback() external payable {
fund();
}
receive() external payable {
fund();
}
}
and also the 01-deploy-fund-me.js to see the code of verify
const { getNamedAccounts, deployments, network } = require("hardhat")
const { networkConfig, developmentChains } = require("../helper-hardhat-config")
const { verify } = require("../utils/verify")
module.exports = async ({ getNamedAccounts, deployments }) => {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const chainId = network.config.chainId
let ethUsdPriceFeedAddress
if (chainId == 31337) {
const ethUsdAggregator = await deployments.get("MockV3Aggregator")
ethUsdPriceFeedAddress = ethUsdAggregator.address
} else {
ethUsdPriceFeedAddress = networkConfig[chainId]["ethUsdPriceFeed"]
}
log("----------------------------------------------------")
log("Deploying FundMe and waiting for confirmations...")
const fundMe = await deploy("FundMe", {
from: deployer,
args: [ethUsdPriceFeedAddress],
log: true,
// we need to wait if on a live network so we can verify properly
waitConfirmations: network.config.blockConfirmations || 1,
})
//log("----------------------------------------------------")
log(`FundMe deployed at ${fundMe.address}`)
if (
!developmentChains.includes(network.name) &&
process.env.ETHERSCAN_API_KEY
) {
await verify(fundMe.address, [ethUsdPriceFeedAddress])
}
log("----------------------------------------------------")
}
module.exports.tags = ["all", "fundme"]
Please help me!

contracts/3_Ballot.sol:33:37: TypeError: Named argument does not match function declaration

from solidity:
contracts/3_Ballot.sol:33:37: TypeError: Named argument does not match function declaration.
Request memory newRequest = Request({
^ (Relevant source part starts here and spans across multiple lines).
I get this error every time. What should i do for the solve it?
pragma solidity ^0.4.17;
contract Campaign {
struct Request {
string description;
uint value;
address recipient;
bool complete;
}
Request[] public requests;
address public manager;
uint public minimumContirbution;
address[] public approvers;
modifier restricted() {
require (msg.sender == manager);
_;
}
function Campaign (uint minimum) public {
manager = msg.sender;
minimumContirbution = minimum;
}
function contribute () public payable {
require(msg.value > minimumContirbution);
approvers.push(msg.sender);
}
function createRequest(string description, uint value, address recipient) restricted public {
Request memory newRequest = Request({
description: description,
value: value,
restricted: restricted,
complete: false
});
requests.push(newRequest);
}
}
You can define the Request struct in this way and push it into requests array:
function createRequest(string description, uint value, address recipient) restricted public {
Request memory newRequest = Request(description, value, recipient, false);
requests.push(newRequest);
}
In this way, you can add the struct into your array and can retrieve with all parameters setted previously.
Because you're are using wrong argument(restricted) inside you Request type
try this:
Request memory newRequest = Request({
descritption: descritpion,
value: value,
recipient: recipient,
complete: false
});

Error in plugin #nomiclabs/hardhat-etherscan: The contract verification failed. Reason: Fail - Unable to verify - with arguments

I am trying to verify my contract with arguments and I am getting this error:
Error in plugin #nomiclabs/hardhat-etherscan: The contract verification failed.
Reason: Fail - Unable to verify
I am also importing Open Zeppelin contracts ERC721Enumerable and Ownable.
Here's my NFTCollectible.sol
pragma solidity 0.8.10;
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "hardhat/console.sol";
contract NFTCollectible is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.08 ether;
uint256 public maxSupply = 5000;
uint256 public maxMintAmount = 25;
mapping(address => uint256) public addressMintedBalance;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function withdraw() public payable onlyOwner {
(bool me, ) = payable(owner())
.call{value: address(this).balance}("");
require(me);
}
}
Here's my deploy.js
const main = async () => {
const nftContractFactory = await hre.ethers.getContractFactory('NFTCollectible');
const nftContract = await nftContractFactory.deploy(
"NFTCollectible",
"NFTC",
"ipfs://CID",
"https://www.example.com"
);
await nftContract.deployed();
console.log("Contract deployed to:", nftContract.address);
};
const runMain = async () => {
try {
await main();
process.exit(0);
} catch (error) {
console.log(error);
process.exit(1);
}
};
runMain();
Here's my hardhat.config
require('#nomiclabs/hardhat-waffle');
require('#nomiclabs/hardhat-etherscan');
require('dotenv').config();
module.exports = {
solidity: '0.8.10',
networks: {
rinkeby: {
url: process.env.STAGING_ALCHEMY_KEY,
accounts: [process.env.PRIVATE_KEY],
},
mainnet: {
chainId: 1,
url: process.env.PROD_ALCHEMY_KEY,
accounts: [process.env.PRIVATE_KEY],
gasPrice: 3000000
},
},
etherscan: {
apiKey: process.env.ETHERSCAN_KEY
}
};
I realize Hardhat does not support 0.8.10+ compiler version, but no other versions work either. Same error.
You need to pass in the constructor into the command line.
hh verify --network mainnet DEPLOYED_CONTRACT_ADDRESS "Constructor argument 1"
Here's the documentation.
https://hardhat.org/plugins/nomiclabs-hardhat-etherscan.html
You have this error because you are not using the same arguments that you used during the deployment, be sure to use the same arguments at deployment as at verification
What worked for me is changing:
etherscan: {
apiKey: process.env.ETHERSCAN_KEY
}
to:
etherscan: {
apiKey: {
rinkeby:"ETHERSCAN API KEY HERE",
}
}
SOLVED
This isn't really an answer, but my solve was to use both Remix and Hardhat, the latter via VSCode. Basically, deploy via Remix and verify through Hardhat.
Because I'm using libraries, I need to verify every file, obviously. The degen way of pasting every Open Zeppelin file...I don't recommend it. I tried and still got it wrong.
Suspicion: I was not creating a transaction in my deploy script, which is weird because my params seem correct. In any event...
My issue is resolved by simply adding my own proxy config in the "hardhat.config.js" file:
// set proxy
const { ProxyAgent, setGlobalDispatcher } = require("undici");
const proxyAgent = new ProxyAgent('http://127.0.0.1:7890'); // change to yours
setGlobalDispatcher(proxyAgent);
I got success finally:
I just used the docs here and using the npx hardhat --network xxxx verify xxxx worked for me. One more thing is be patient maybe you need to execute this after a few block since the Smart contract deployment.

_signTypedData method on ethers does not match with ERC712 solidity code

I've faced an ethers signature unmatched problem.
Everything is normal.
Already compared domainData, types, message variable in the js code with contract.
Below is the JS Code to generate signature and call contract.
const contractAddress = await contract.address;
domainData.chainId = 31337;
domainData.verifyingContract = contractAddress;
const signature = await signer._signTypedData(domainData, types, message);
const { r, s, v } = ethers.utils.splitSignature(signature);
const result = await contract.recoverAddressFromTypedData(
message,
v,
r,
s
);
expect(result).to.equal(signer.address);
Below is the solidity code which use "#openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"
function recoverAddressFromTypedData(
Bid memory bid,
uint8 v,
bytes32 r,
bytes32 s
) public view returns (address) {
bytes32 digest = _hashTypedDataV4(hashBid(bid));
address signer = ecrecover(digest, v, r, s);
return signer;
}
But I got following error on the last line of JS code.
AssertionError: expected '0x7Da34C07B95dB4A1c85fe4C5d313F4860E85e340' to equal '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266'
+ expected - actual
-0x7Da34C07B95dB4A1c85fe4C5d313F4860E85e340
+0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
Is there anything wrong with my code?
I don't know if I have the same reason as you, in my case I had a struct member containing a string type which needed to be converted to bytes32.
contract MyContract is Ownable, AccessControl, EIP712 {
struct Action {
address initiator;
string name;
}
bytes32 public constant ACTION_TYPE_HASH = keccak256("Action(address initiator,string name)");
function _hashStruct(Action memory action) private pure returns (bytes32) {
// If your struct member has string type,
// you need to use keccak256(abi.encodePacked(string))
// convert it to bytes32
return keccak256(abi.encode(ACTION_TYPE_HASH, action.initiator, keccak256(abi.encodePacked(action.name))));
}
function _hashTypedDataV4(Action memory action) private view returns (bytes32) {
bytes32 structHash = _hashStruct(action);
return EIP712._hashTypedDataV4(structHash);
}
// more...
}

Metamask error: Transaction error. exception thrown in contract code

I've been successfully compiled and deployed my smart contract Campaign.sol. All the functions in my contract can run successfully but as I use my javascript file RequestRow.js to call my function finalizeRequest Metamask pops up the error Transaction error. Exception thrown in contract code
I've googled this error and tried to solve my question by this and this. However, they aren't helpful for my error.
Can anyone tells me where did I do wrong in my smart contract. I don't know how to solve it. Please help!
My Campaign.sol file
pragma solidity ^0.4.17;
contract CampaignFactory{
address[] public deployedCampaigns;
function createCampaign(uint minimum)public{
address newCampaign = new Campaign(minimum, msg.sender);
deployedCampaigns.push(newCampaign);
}
function getDeployedCampaign() public view returns(address[]){
return deployedCampaigns;
}
}
contract Campaign{
struct Request {
string description;
uint value;
address recipient;
bool complete;
uint approvalCount;
mapping(address => bool) approvals;
}
Request[] public requests;
address public manager;
uint public minimumContribution;
mapping (address => bool) public approvers;
uint public approversCount;
modifier restricted(){
require(msg.sender == manager);
_;
}
function Campaign (uint minimum, address creator)public{
manager = creator;
minimumContribution = minimum;
}
function contribue()public payable{
require(msg.value > minimumContribution);
approvers[msg.sender] = true;
approversCount++;
}
function createRequest(string description, uint value, address recipient)public restricted{
Request memory newRequest = Request({
description: description,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
requests.push(newRequest);
}
function approveRequest(uint index)public{
Request storage request = requests[index];
require(approvers[msg.sender]);
require(!request.approvals[msg.sender]);
request.approvals[msg.sender] = true;
request.approvalCount++;
}
function finalizeRequest(uint index)public restricted{
Request storage request = requests[index];
require(request.approvalCount > (approversCount/2));
require(!request.complete);
request.recipient.transfer(request.value);
request.complete = true;
}
function getSummary() public view returns (
uint, uint, uint, uint, address
){
return (
minimumContribution,
this.balance,
requests.length,
approversCount,
manager
);
}
function getRequestsCount() public view returns (uint){
return requests.length;
}
}
My RequestRow.js file
import React, {Component} from 'react';
import {Table, Button} from 'semantic-ui-react';
import web3 from '../ethereum/web3';
import Campaign from '../ethereum/campaign';
class RequestRow extends Component{
onApprove = async() => {
const campaign = Campaign(this.props.address);
const accounts = await web3.eth.getAccounts();
await campaign.methods.approveRequest(this.props.id).send({
from: accounts[0]
});
};
onFinalize = async() => {
const campaign = Campaign(this.props.address);
const accounts = await web3.eth.getAccounts();
await campaign.methods.finalizeRequest(this.props.id).send({
from: accounts[0]
});
};
render(){
const {Row, Cell} = Table;
const {id, request, approversCount} = this.props;
return (
<Row>
<Cell>{id}</Cell>
<Cell>{request.description}</Cell>
<Cell>{web3.utils.fromWei(request.value,'ether')}</Cell>
<Cell>{request.recipient}</Cell>
<Cell>{request.approvalCount}/{approversCount}</Cell>
<Cell>
<Button color="green" basic onClick={this.onApprove}>
Approve
</Button>
</Cell>
<Cell>
<Button color="teal" basic onClick={this.onFinalize}>
Finalize
</Button>
</Cell>
</Row>
)
}
}
export default RequestRow;
The full error message that I got in the deveoper console
Uncaught (in promise) Error: Transaction has been reverted by the EVM:
{
"blockHash": "0xcca9f6dac8c99c2ecc1f9314661399bda3a6096bf0f36d1c1724d84dcece42b2",
"blockNumber": 5145820,
"contractAddress": null,
"cumulativeGasUsed": 270372,
"from": "0x284aea2dca83c9c6247907554cb27120f7ce1892",
"gasUsed": 55899,
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"status": false,
"to": "0x6ff70b2a9c30909431714902581539087fe25a3b",
"transactionHash": "0x24b15e5db8bb673375409327cdde0fba98844126f5909ed7681845ee3bccce84",
"transactionIndex": 2,
"events": {}
}
at index.js?959bf61:366
This error is due to the rather complicated account switching required.
First, you need to create a campaign with one of your MetaMask accounts,
Then you need to create a request while in this same account as 'manager'. When you copy and paste the address of the recipient make sure to switch back to the right account after, before submitting the request.
Then you need to contribute to the campaign with another MetaMask account, and approve the request while making sure you are still in the account that you contributed the funds with.
Normally this account switching would not be an issue but it is simulating multiple different users interacting with the contract.
Regards
Mark
you need use truffle/HDwallet and set provider.