Truffle test fails with Error: Could not find artifacts - solidity

I learn the demo: Code is come from: https://truffleframework.com/tutorials/pet-shop, when I test:
$ truffle.cmd test
Using network 'development'.
Compiling .\test\TestAdoption.sol...
TestAdoption
1) "before all" hook: prepare suite
0 passing (30s)
1 failing
1) TestAdoption
"before all" hook: prepare suite:
Error: Could not find artifacts for /E/blockchain/pet-
shop/contracts/Adoption.sol from any sources
at Resolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-resolver\index.js:37:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at dependency_paths.forEach.dependency_path (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:203:1)
at Array.forEach (<anonymous>)
at deployer.deploy.then (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:202:1)
at D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-deployer\src\deferredchain.js:20:1
at process._tickCallback (internal/process/next_tick.js:68:7)
I updated my nodejs lastest, and installed window-build-tools,it does not work.
TestAdoption.sol:
pragma solidity ^0.5.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Adoption.sol";
contract TestAdoption {
Adoption adoption = Adoption(DeployedAddresses.Adoption());
function testUserCanAdoptPet() public {
uint returnedId = adoption.adopt(expectedPetId);
Assert.equal(returnedId, expectedPetId);
}
uint expectedPetId = 8;
address expectedAdopter = address(this);
function testGetAdopterAddressByPetId() public {
address adopter = adoption.adopters(expectedPetId);
Assert.equal(adopter, expectedAdopter, "Owner of the expected pet should be this contract");
}
function testGetAdopterAddressByPetIdInArray() public {
address[16] memory adopters = adoption.getAdopters();
Assert.equal(adopters[expectedPetId], expectedAdopter, "Owner of the expected pet should be this contract");
}
}
2_deploy_contracts.sol:
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
And import "truffle/Assert.sol"; vscode say: Source "truffle/Assert.sol" not found: File import callback not supported.My friend's version is 0.4.14 and work well, may be a version problem?
Here is project dir(just a demo from https://truffleframework.com/tutorials/pet-shop):

This error DOESN'T happen (currently) in the version v5.1.10 of truffle.
My full error was:
TypeError: Error parsing C:/Users/PATH/yourSmartContract.sol: Cannot destructure property 'body' of 'undefined' as it is undefined.
My solution is to downgrade the version like so:
$ npm uninstall -g truffle
$ npm install -g truffle#v5.1.10
(Developing in BC is hard because of version control and managment. Keep the good the work.)

The problem is the name of the artifact is defined according to the contract's name. This is your contract:
contract TestAdoption {
}
So;
2_deploy_contracts.sol:
// not artifactsrequire(Adoption)
var Adoption = artifacts.require("TestAdoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};

Try these files:
1_initial_migration.js:
const Migrations = artifacts.require("Migrations");
module.exports = function(deployer) {
deployer.deploy(Migrations);
};
2_deploy_contracts.js:
const YourContractName = artifacts.require("YourContractName");
module.exports = function(deployer) {
deployer.deploy(YourContractName);
};
Tips:
Do not change the name of the files (1_initial_migration.js and 2_deploy_contracts.js);
Use the exactly name of your contract in the "2_deploy_contracts" file (if it is called BatatinhaFrita123, you need to specify BatatinhaFrita123 inside the artifacts.require()).

Related

How to get web3 accounts in solc?

My blockchain project with solc version ^0.4.6 . Has been throwing errors when given the command of being web3.eth.accounts.
web3.eth.accounts
Uncaught Error: Invalid JSON RPC response: undefined
at Object.InvalidResponse (E:\techdot-master\node_modules\web3\lib\web3\errors.js:38:16)
at HttpProvider.send (E:\techdot-master\node_modules\web3\lib\web3\httpprovider.js:91:22)
at RequestManager.send (E:\techdot-master\node_modules\web3\lib\web3\requestmanager.js:58:32)
at Eth.get [as accounts] (E:\techdot-master\node_modules\web3\lib\web3\property.js:107:62).
I have tried reading the docs and tried other commands. Still unable to resolve the issue!
"Invalid JSON RPC response" means you are not connected to the node. In order to connect to a node, you need a provider. You can get an infura account and create a provider HdWalletProvider
const HDWalletProvider = require("#truffle/hdwallet-provider");
const provider = new HDWalletProvider({
mnemonic: {
phrase: metamask_mnemonic,
},
providerOrUrl: ropsten_network,//infura endpoint here
});
Or if you are using ganache-cli
const ganache = require('ganache-cli');
const provider = ganache.provider()
Then create web3
const web3 = new Web3(provider);
I think instead of accounts, should be getAccounts
const accounts = await web3.eth.getAccounts();
I recommend using ehtersjs, with it everything is a lot easier.

Unable to run ethers.getSigner() from the (nodeJS?) console

I am following a Hardhat intro tutorial by Reanblock https://www.youtube.com/watch?v=osHk0eEsjDM and I am stuck in the last few minutes of the video.
I have a simple hardhat.config.js file as follows:
require("#nomiclabs/hardhat-waffle");
require("#nomiclabs/hardhat-web3");
require('solidity-coverage');
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
task("azbalance", "-prints a/c balances- ")
.addParam("azaccount", "the accounts address")
.setAction(async (taskArgs) => {
const account = web3.utils.toChecksumAddress(taskArgs.azaccount);
const balance = await web3.eth.getBalance(account);
console.log(web3.utils.fromWei(balance, "ether"), "ETH");
})
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
};
I successfully created a node in another terminal using the command:
npx hardhat node
I am able to deploy the contract using the following command.
npx hardhat run scripts/sample-script.js --network localhost
on the console I type:
npx hardhat console --network localhost
so far it has been working as expected.
on the (NodeJS ? ) console when I type
acc = await ethers.getSigner()
I get the following error:
Uncaught TypeError: ethers.getSigner is not a function
at REPL1:1:47
my goal is to get the account address using the command:
acc.address
**** Apologies if used the terms Terminal and Console incorrectly. I'm yet to figure out its proper usage ***
Where do you run the command npx hardhat console --network localhost?
Make sure you run from the folder contained the hardhat.config.js file.
Please try with the simple config first:
require("#nomiclabs/hardhat-waffle");
module.exports = {
solidity: "0.8.4",
defaultNetwork: "localhost",
networks: {
localhost: {
url: "http://127.0.0.1:8545"
}
}
};
You should able to achieve

Can not call the function Aggregate - Multicall2.sol on BSC testnet

I already deployed the multicall2.sol smart contract on BSC Testnet
https://testnet.bscscan.com/address/0x8F3273Fb89B075b1645095ABaC6ed17B2d4Bc576#code
then call the contract by using the following typescript code:
try {
const multi = getMulticallContract(options.web3 || web3NoAccount)
const itf = new Interface(abi)
const calldata = calls.map((call) => [call.address.toLowerCase(), itf.encodeFunctionData(call.name, call.params)])
const { returnData } = await multi.methods.aggregate(calldata).call(undefined, options.blockNumber)
const res = returnData.map((call, i) => itf.decodeFunctionResult(calls[i].name, call))
return res
} catch (error) {
throw new Error(error)
}
}
I got the error
Uncaught (in promise) Error: Error: Returned error: execution reverted: Multicall aggregate: call failed
It's weird. Because the function works properly on Mainnet. Can anyone help me?
The author found his solution but just to complete the troubleshooting I suggest making sure you have:
Have the contract deployed on testnet
Switch your RPC Node Url to the correct network. For example: BSC testnet's is https://data-seed-prebsc-1-s2.binance.org:8545
in my case, i resolved the issue by simply switching the rpc from https://data-seed-prebsc-1-s3.binance.org:8545/ to https://data-seed-prebsc-1-s2.binance.org:8545/
looks like they have some substantial inconsistency between nodes

Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)

i have develop a simple smartContract. when i run truffle test it showed the following error:i am new in this so i cant figure it out.
PS F:\pracdap> truffle test
Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SimpleSmartContract.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Compilation warnings encountered:
Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "urce file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more informa
--> /F/pracdap/contracts/SimpleSmartContract.sol
> Artifacts written to C:\Users\HP\AppData\Local\Temp\test--1224-GWVOn3NGyps8
> Compiled successfully using:
- solc: 0.8.3+commit.8d00100c.Emscripten.clang
Contract: SimpleSmartContract
1) should be deployed
> No events were emitted
0 passing (128ms)
1 failing
1) Contract: SimpleSmartContract
should be deployed:
Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)
at Object.checkNetworkArtifactMatch (F:\node\node_modules\truffle\build\webpack:\packages\contract\lib\utils\index.js
at Function.deployed (F:\node\node_modules\truffle\build\webpack:\packages\contract\lib\contract\constructorMethods.j
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at Context.<anonymous> (test\simpleSmartContract.js:5:33)
Solidity code
pragma solidity >=0.4.22 <0.9.0;
contract SimpleSmartContract {
}
Node js. test code
const SimpleSmartContract = artifacts.require('SimpleSmartContract');
contract('SimpleSmartContract', () => {
it('should be deployed', async () => {
const simpleSmartContract = await SimpleSmartContract.deployed();
assert(simpleSmartContract.address !== '');
});
});
Looks like you have not added a Migration file for your SimpleSmartContract.
Create a file named 2_deploy_contracts.js in your Migrations directory. The add the following code in it :
const SimpleSmartContract = artifacts.require("SimpleSmartContract");
module.exports = function (deployer) {
deployer.deploy(SimpleSmartContract);
};
Then try running the test.
try using migration...if is shows any error let me know.
const SimpleSmartContract = artifacts.require("SimpleSmartContract");
module.exports = async function(deployer, _network, accounts) {
await deployer.deploy(SimpleSmartContract);
};
You should create a new 'migrations file' in the migration folder with a (possible) name of 2_deploy_contracts.js.
async function arguments:
deployer: deployment of the contract
_network: specified network (truffle-config.js)
accounts: to access the truffle accounts when deploying (I.E Solidity constructor arguments)
Ref: https://trufflesuite.com/docs/truffle/getting-started/running-migrations.html

Error parsing triggers: Cannot find module 'firebase/firestore'

I am trying to run a very basic code on google api using firebase.
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
//const {Card, Suggestion} = require('dialogflow-fulfillment');
var admin = require('firebase-admin');
require("firebase/firestore");
admin.initializeApp(functions.config().firebase);
//var firestore = admin.firestore();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
//firestore arguments defined
/* var addRef = firestore.collection('Admissions');
var feeRef = firestore.collection('Fees');
*/
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
console.log("request.body.queryResult.parameters: ", request.body.queryResult.parameters);
// Run the proper function handler based on the matched Dialogflow intent name
var intentMap = new Map();
});
It gives me a error that says
'Error parsing triggers: Cannot find module 'firebase/firestore'.Try running "npm install" in your functions directory before deploying.
When I run npm install inside the funtions directory, I get:
audited 9161 packages in 25.878s found 292 vulnerabilities (21 low,
207 moderate, 64 high) run npm audit fix to fix them, or npm
audit for details
Its been a week, I am stuck with these errors, these errors keep fluctuating based on the solution i find. But i am not able to overcome this error. Can you please check if there is something wrong I am doing, or anything else I need to try?
Just delete the node_modules folder and run npm install again. I was also stuck on this for a week. It is a corrupt file issue.