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).
I've got a Chainlink client contract which makes a DirectRequest to an oracle. The oracle does its thing and then returns the answer via the typical callback selector passed in via the ChainlinkRequest. It all works well, but I'd like to write some tests that test the callback implementation
My client contract is as follows:
contract PriceFeed is Ownable, ChainlinkClient {
function updatePrice() onlyOwner returns (bytes32 requestId) {
// makes Chainlink request specifying callback via this.requestCallback.selector
}
function requestCallback(bytes32 _requestId, uint256 _newPrice) public
recordChainlinkFulfillment(_requestId) {
price = _newPrice;
}
}
The problem arises when the test code calls requestCallback(...) and the code hits the recordChainlinkFulfillment(...) modifier. The ChainlinkClient complains that the requestId being passed in by the test below isn't in the underling private pendingRequests mapping maintained by the ChainlinkClient.
The simplified version of ChainlinkClient looks like this:
contract ChainlinkClient {
mapping(bytes32 => address) private pendingRequests;
modifier recordChainlinkFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit ChainlinkFulfilled(_requestId);
_;
}
}
My Foundry/Solidity test is as follows:
contract PriceFeedTest is Test {
function testInitialCallback() public {
priceFeed.requestCallback("abc123", 1000000); // fails on this line
assertEq(1000000, priceFeed.price(), "Expecting price to be 1000000");
}
}
The code fails on first line of the testInitialCallback() line with: Source must be the oracle of the request
How can I trick the ChainklinkClient into allowing my callback to get past the modifier check? AFAIK I can't access and pre-populate the private pendingRequests mapping. Is there another way?
I know that Foundry provides Cheatcodes to help in testing and there's a stdstorage cheatcode, but I'm not familiar on how to construct a call to stdstorage to override pendingRequests if thats even possible with a cheatcode.
contract PriceFeedTest is Test {
function testInitialCallback2() public {
stdstore
.target(address(priceFeed))
.sig("pendingRequests()")
.with_key("abc123")
.checked_write(address(this));
priceFeed.requestCallback("abc123", 1000000);
assertEq(1000000, priceFeed.price(), "Expecting price to be 1000000");
}
}
The above code throws the following error: No storage use detected for target
Any help would be greatly appreciated. Many thanks.
When you execute the updatePrice function in your test, you should be able to strip out the requestId from the transaction receipt event. Once you have that, you can then use it in your call to requestCallback. Check out this example unit test from the hardhat starter kit for an example of this
i'm writing simple smart contract for learning.
I wrote a contract as
contract A {
mapping(address => mapping(uint32 => uint32)) data;
..
function getData(address addr, index id) public view {
return data[addr][id];
}
}
And it returns compile error
TypeError: Different number of arguments in return statement than in returns declaration
In right that line.
Maybe there is miswriting in my code data[addr][index] , which one should be fixed,
or just a bug of Solidity?
Weirdly, i found answer right after posting..
Simply added returns keywords like
function getData(address addr, index id) public view returns(uint32) {
...
then works fine.
For others, i'll leave this question as is.
I want to use Oraclize in Remix, to test it. I'm too stupid to use their examples.
How can I make this work?
From their Github I took the YouTube-Views code and copied it into Remix
pragma solidity >= 0.5.0 < 0.6.0;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
contract YoutubeViews is usingOraclize {
string public viewsCount;
event LogYoutubeViewCount(string views);
event LogNewOraclizeQuery(string description);
constructor()
public
{
update(); // Update views on contract creation...
}
function __callback(
bytes32 _myid,
string memory _result
)
public
{
require(msg.sender == oraclize_cbAddress());
viewsCount = _result;
emit LogYoutubeViewCount(viewsCount);
// Do something with viewsCount, like tipping the author if viewsCount > X?
}
function update()
public
payable
{
emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer...");
oraclize_query("URL", 'html(https://www.youtube.com/watch?v=9bZkp7q19f0).xpath(//*[contains(#class, "watch-view-count")]/text())');
}
}
When I use the viewCount it returns:
0: string:
This happens with all the other examples aswell.
With WolframAlpha eg. I also get the following error:
transact to WolframAlpha.update errored: VM error: revert.
revert The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value. Debug the transaction to get more information.
Ok you don't see the answer like a normal result in Remix:
You have to go under settings and open the Oraclize plug in.
If you then deploy the contract and or click update, you get the result shown in the plug in.
I'm trying to change the state variable value of solidity, and test on the geth console, but the value of state variable is not changed.
The steps are as below:
1: Write a simple smart contract code by solidity as below
pragma solidity ^0.4.0;
contract SimpleStorage {
uint public storedData=99;
mapping(string => uint) balances;
function set(uint x) public returns (uint){
storedData = x;
return storedData;
}
function get() public constant returns (uint) {
return storedData;
}
function multiply(uint a) returns(uint d) {
return a * 7;
}
function setmapping(string key,uint value) returns(uint v)
{
balances[key] = value;
return balances[key];
}
function getmapping(string key) returns(uint v)
{
return balances[key];
}
function kill()
{
}
}
2: compile the code by the truffle, use command
truffle compile
3:start the geth, unlock account, and start the minner
4:deploy the smart contract
truffle migration --reset
and then I see the console output as below
Using network 'development'.
Running migration: 1_initial_migration.js
Replacing Migrations...
... 0x8ccf9e1599c2760ff3eed993be10929403e1faa05489a247a067f4f06536c74c
Migrations: 0xec08113a9e810e527d99a1aafa8376425c4a75ed
Saving successful migration to network...
... 0xedbf12715b736759e9d9297cbaaeb3151d95f478c2f1ee71bff4819d2dbb47e5
Saving artifacts...
Running migration: 2_deploy_contracts.js
Replacing SimpleStorage...
... 0xff5b00f9b14d8ecea4828c3ad8e9dbfa9d685bc0b81530fc346759d7998b060f
SimpleStorage: 0x96cf1e076f4d99a5d0823bd76c8de6a3a209d125
Saving successful migration to network...
... 0x3452a9e76b73e250de80874ebc3fd454724ebf6a15563bee0d5ba89b7b41909f
Saving artifacts...
which means the smart contract deployed to geth successfully
5: Then in the geth console, I set abi variable as below:
abi=[{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"changeStorage","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"kill","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"getAll","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"key","type":"string"},{"name":"value","type":"uint256"}],"name":"setmapping","outputs":[{"name":"v","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"refrenceType","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"changeMemory","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"key","type":"string"}],"name":"getmapping","outputs":[{"name":"v","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"payable":false,"type":"function"}]
6: Get an contract instant as below:
test=eth.contract(abi).at("0x2f3970e8e4e2f5ed4ccb37b0f79fe5598700e2f0")
7: Run the set()
test.set.call(22);
The out put is 22, which I think the state variable storedData was successfully set to the new value 22, but when I run below code to read the storedData,
test4.get()
the return value is still 99, which mean the value of storedData was not changed, beside use the uint to do the testing, I also tried the mapping, but the answer is as same as uint, I don't know if I was wrong in somewhere or the state variable is not allowed to be modified, could anyone help me?
Thanks.
From the question, this is the call that is not changing state:
test.set.call(22)
In order to change state, you must issue a transaction. A call(...) only tells you what would happen if you were to send a transaction. For more background, see: What is the difference between a transaction and a call?
So you can replace the above line with:
test.set.sendTransaction(22)
Alternatively, web3.js will automatically attempt to decide whether to use a transaction or a call. So in this case you can use simply:
test.set(22)
For more background on how web3.js decides, see: How does web3.js decide to run a call() or sendTransaction() on a method call?