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

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

Related

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

Unable to verify the first certificate Next.js

I am trying to build a new application.
It accesses one API to get some data over HTTPS.
Status2.getInitialProps = async () => {
console.info('ENTERRRRRRRR')
const res = await fetch('https://test.com/api/v1/messages', {
method: 'get',
headers: {
'Authorization': 'Bearer ffhdfksdfsfsflksfgjflkjW50aXNocjEiLCJpYXQiOjE2MDc1ODIzODQsImF1ZCI6InJlY3J1aXRpbmdhcHAtMTAwMC5kZXZlbG9wLnVtYW50aXMuY29tIiwiaXNzIjoicmVjcnVpdGluZ2FwcC0xMDAwLmRldmVsb3AudW1hbnRpcy5jb20ifQ.0jqPutPOM5UC_HNbTxRiKZd7xVc3T5Mn3SjD8NfpEGE',
'Accept': 'application/vnd.api+json'
}
}
)
}
When the browser tries to access this API then it gives me the following error:
Server Error
FetchError: request to https://test.com/api/v1/messages failed, reason: unable to verify the first certificate
This error happened while generating the page. Any console logs will be displayed in the terminal window.
C
To solve this issue I followed this but when tried it, it gave me another error:
'NODE_TLS_REJECT_UNAUTHORIZED' is not recognized as an internal or external command,
operable program or batch file.
The NODE_TLS_REJECT_UNAUTHORIZED solution is a no-go as it is against the main purpose of having a trusted connection between your front-end and API. We run into this error message recently with a NextJS as the front-end, ExpressJS as the back-end, and Nginx as the webserver.
If you or your team are on implementing the API, I would suggest looking into your webserver config and how you are handling the path of the certificates as the problem might be related to a misconfiguration of the intermediate certificate. Combining the certificate + intermediate certificate like so did the trick for us:
# make command
cat {certificate file} {intermediate certificate file} > {new file}
# config file /etc/nginx/conf.d/xxx.conf
ssl_certificate {new file};
create a next.config.js file if you not already have one in your project and add the following to your webpack config:
const webpack = require("webpack");
module.exports = {
webpack: (config) => {
config.node = {
fs: "empty",
};
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const env = Object.keys(process.env).reduce((acc, curr) => {
acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
return acc;
}, {});
config.plugins.push(new webpack.DefinePlugin(env));
return config;
},
};
Do not use it like this in production. It should only be used in a dev environment.

TestCafe Authentication results in a 401 - Unauthorized: Access is denied.... error

Issue:
I am trying to get TestCafe to open an internal website that triggers a windows authentication pop up on opening, but the TestCafe built in Authentication feature doesn't work for some weird reason and the website complains with "401 - Unauthorized: Access is denied due to invalid credentials."
Note manually I can open the website with the same login credentials.
Also note the Authentication feature does work for other websites, and I am doing this at work, so there is a work proxy.
The site that TestCafe is failing to open up:
Is made up of a server name & port only & lives internally eg.
http://[ServerName]:[Port]
The Code:
Made up of 2 files....
The Test Script:
import {Selector} from 'testcafe';
fixture('My Test')
.page('http://[ServerIP]:[Port]/') // Also tried ('http://[ServerName]:[Port]')
.httpAuth({
username: 'domain\name',
password: 'password_here'
})
test ('Opening this internal site', async t => {
await t
.debug()
});
The Runner file:
const createTestCafe = require('testcafe');
let testcafe = null;
createTestCafe('localhost', '8081')
.then(tc => {
testcafe = tc;
const runner = testcafe.createRunner();
return runner
.src([
'My_Test.js'
])
.browsers('chrome')
.useProxy('webproxy01:8080', '[ServerIP]:[Port]') // I tried including the website that I want to test incase it needs to be ByPassed
.run({
skipJsErrors: true,
concurrency: 1
})
})
.then(failedCount => {
console.log(`Tests failed: ` + failedCount);
testcafe.close();
});
Just to add I've tried this too and it doesn't work either:
.httpAuth({
username: 'name',
password: 'password_here',
domain: 'domain_here',
workstation: 'computer_name'
})
Many thanks!

Truffle test fails with Error: Could not find artifacts

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()).

Unable to connect Ganache with Truffle/Npm Dev server

I am able to work with Truffle and Ganache-cli. Have deployed the contract and can play with that using truffle console
truffle(development)>
Voting.deployed().then(function(contractInstance)
{contractInstance.voteForCandidate('Rama').then(function(v)
{console.log(v)})})
undefined
truffle(development)> { tx:
'0xe4f8d00f7732c09df9e832bba0be9f37c3e2f594d3fbb8aba93fcb7faa0f441d',
receipt:
{ transactionHash:
'0xe4f8d00f7732c09df9e832bba0be9f37c3e2f594d3fbb8aba93fcb7faa0f441d',
transactionIndex: 0,
blockHash:
'0x639482c03dba071973c162668903ab98fb6ba4dbd8878e15ec7539b83f0e888f',
blockNumber: 10,
gasUsed: 28387,
cumulativeGasUsed: 28387,
contractAddress: null,
logs: [],
status: '0x01',
logsBloom: ... }
Now when i started a server using "npm run dev". Server started fine but is not connecting with the Blockchain
i am getting the error
Uncaught (in promise) Error: Contract has not been deployed to detected network (network/artifact mismatch)
This is my truffle.js
// Allows us to use ES6 in our migrations and tests.
require('babel-register')
module.exports = {
networks: {
development: {
host: '127.0.0.1',
port: 8545,
network_id: '*', // Match any network id
gas: 1470000
}
}
}
Can you please guide me how i can connect ?
Solve the issue.
issue was at currentProvider, i gave the url of ganache blockchain provider and it worked.
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source like Metamask")
// Use Mist/MetaMask's provider
// window.web3 = new Web3(web3.currentProvider);
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
} else {
console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
In your truffle.js, change 8545 to 7545.
Or, in Ganache (GUI), click the gear in the upper right corner and change the port number from 7545 to 8545, then restart. With ganache-cli use -p 8545 option on startup to set 8545 as the port to listen on.
Either way, the mismatch seems to be the issue; these numbers should match. This is a common issue.
Also feel free to check out ethereum.stackexchange.com. If you want your question moved there, you can flag it and leave a message for a moderator to do that.