I have the following smart contract function:
function safeMint(address to, uint256 tokenId) public onlyOwner payable {
require(msg.value >= mintPrice, "Not enough ETH to purchase NFT; check price!");
_safeMint(to, tokenId);
}
and the following test function in chai to test it.
describe("mint", () => {
it("should return true when 0.5 ethers are sent with transaction", async function () {
await contract.deployed();
const cost = ethers.utils.parseEther("0.1");
await contract.safeMint("0x65.....",1,cost
});
However the test function is not working and gives me an error on cost.
Error: "Type 'BigNumber' has no properties in common with type 'Overrides & { from?: PromiseOrValue; }'." I fail to understand where the error lies.
Try this, it's the valid syntax to send value with the call:
await contract.safeMint("0x65.....", 1, {value: cost});
I had a similar problem while testing a payable function, it kept saying 'object is not an instanceof of BigInt'. How I solved this problem and ensured testing ran smoothly was to test the balance of the receiver (in your case, the 'to' address), to make sure the balance has been updated. That is, if the safeMint function was successful during test, the 'to' address should be increased by 1.
You can test by:
const balOfToAdress = await contract.balanceOf(to.address)
expect(balOfToAddress).to.equal(1)
Note: the 'expect' above is gotten by requiring chai at the top of your code i.e.
const {expect} = require('chai')
and, you have to test specifically for the balance of 'to' address (Here, I just assumed the initial balance of mints on 'to' address is 0).
Related
Total beginner here apologies in advance.
I'm learning Solidity and using Hardhat and trying to figure out how to return the value of the Chainlink price feed in this tutorial contract after deployment. I know how to return the function output in remix but having trouble figuring out how to use console.log or another method in Hardhat. I am able to use console.log for built in functions like token address but can't figure out how to apply to other functions. This is using the Goerli Testnet btw.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract TestChainlink {
AggregatorV3Interface internal priceFeed;
constructor() {
// ETH / USD
priceFeed = AggregatorV3Interface(0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e);
}
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
// for ETH / USD price is scaled up by 10 ** 8
return price;
}
}
I tried emulating console.log usage that work for built in functions like token address to apply them to the Chainlink getLatestPrice() function.
const Token = await ethers.getContractFactory("TestChainlink");
const token = await Token.deploy();
console.log("Token address:", token.address);
i.e.
I tried a ton of different combinations this was the last one I will spare all the error messages since it probably isn't a complex solve for a non novice.
console.log("ETH Price:", getLatestPrice());
try
let price = await token.getLatestPrice();
console.log(`Eth price is: ${price}`);
In card.sol contract, I have a function 'add' which allows a user to create a poker card with any number. To use this 'add' function, it requires at least 0.01 eth.
I have written the following truffle test scripts to ensure that at least 0.01 eth is used to create a card in the smart contract above.
var Web3 = require('web3');
const card = artifacts.require("card");
contract('card Test', async accounts => {
it("ensure > 0.01 eth is needed to create a card", async () => {
const instance = await Card.deployed();
const cardInstance = instance;
await cardInstance.add(5, 10, {from: accounts[0], value: Web3.utils.toWei('0.02')});
assert.isAbove(____________, 0.01, "> 0.01 eth is needed to create the card");
});
What is the correct code for ____________?
For the usual solidity test scripts, it will be 'msg.value'. What is the equivalence of 'msg.value' for the _________ above?
you have to send amount that less than 0.01 Assuming that created the instance correctly
try {
// this will throw error and you will catch it catch statement
await cardInstance.add(5, 10, {from: accounts[0], value:Web3.utils.toWei('0.00001')})
// if this line executed, your test will fail.
assert(false);
} catch (e) {
// to test this part of your code executed
console.log("errror is caught")
// this will confirm that we get an error object
assert(e);
}
If you send less than minimum requirement, if we are successfully catching the error in catch statement, test case will pass. If there was an error with require statement assert(false) would run and test case would fail
I have such function to transfer tokens from contract and i get error where shoudl i add payable and i dont really understand if withdraw will withdraw ethers or tokens?
function withdrawBalances() public nonReentrant {
uint share = _Balances[msg.sender];
_Balances[msg.sender] = 0;
msg.sender.transfer(share);
}
.withdrawBalances errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
This error occurs when you try to send some Ether when calling a function that isn't payable. Set Ether value to 0 to avoid this. You can also allow a function to accept Ether by using the payable keyword.
function withdrawBalances() public payable {
...
}
I am getting an error in metamask "the MetaMask Web3 object does not support synchronous methods like eth_sendTransaction without a callback parameter".
I am trying to pass three parameters to a solidity function, but the callbacks I've tried to insert don't seem to work?
Below is the js code, just a button and 3 labels for the variables in the HTML
$('#proposalbutton').click(function() {
log("Calling add proposals...");
community.newProposal($("#address").text(), $("#coinAmount").val(),
$("#jobDescription").text()), (err, res) =>{
if (!err) {
log("Proposals call executed successfully.");;
}
}
});
Can anyone point out what I'm doing wrong? I can't figure out the callbacks.
Below is the solidity function header
function newProposal(
address beneficiary,
uint coinAmount,
string jobDescription
)
onlyMembers public
returns (uint proposalID)
Callbacks are the last parameter sent after your Solidity contract parameters. It looks like you're closing newProposal after just the function parameter list.
community.newProposal($("#address").text(), $("#coinAmount").val(),
$("#jobDescription").text(), (err, res) => {
if (!err) {
log("Proposals call executed successfully.");;
}
});
Additional note: Transaction methods won't return a value. You won't get proposalID in your response. Use either an event or store the result in your contract state and then use a view function to return it.
I want to send some ETH to smart contract address
Test.deployed().then(function(instance) {return instance.contribute("0x1e0c326f4f24b5e9f5d42d695f48983d0a72b240", {from:web3.eth.accounts[0],value:10});})
but I always get
truffle(development)> Test.deployed().then(function(instance) {return instance.contribute("0x1e0c326f4f24b5e9f5d42d695f48983d0a72b240", {from:web3.eth.accounts[0],value:10});})
TypeError: instance.contribute is not a function
at evalmachine.<anonymous>:1:61
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
truffle(development)> truffle(development)>
I am using last version of truffle, so version 4.x
Same problem with
Test.deployed().then(function(instance) {return instance.getElements.call();})
Updated
contract MyContract Common {
function setMultisigWallet(address newMultisigWallet) public onlyOwner {
multisigWallet = newMultisigWallet;
}
function() external payable {
executeSale();
}
}
Send a transaction directly to a contract via instance.sendTransaction(). This is promisified like all available contract instance functions, and has the same API as web3.eth.sendTransaction but without the callback. The to value will be automatically filled in for you if not specified.