hardhat getNamedAccounts() does not work properly - javascript

I'm following the course of 32 hours Learn Blockchain, Solidity, .. in Javascript and I'm stucked with an error that others have but they solve because typos ecc.
I'm pretty sure at this point that the problem is not there but so what is the problem? I have my configuration file:
namedAccounts: {
deployer: {
default: 0,
1:0, // I even with this but nothing change
},
},
And I'm running everything in the hardhat default network, and when from the 00-deploy-mock.js the script calls the function getNamedAccounts():
module.exports = async function ({getNamedAccounts,deployments}){
const {deploy,log} = deployments
const {deployer} = await getNamedAccounts()
log(deployer)
if(developmentChains.includes(network.name)){
log("Local network " + network.name +" deploying mocks....")
await deploy("VRFCoordinatorV2Mock",{
from: deployer,
log: true,
args: [BASE_FEE,GAS_PRICE_LINK]
})
log("Mocks deployed !")
log("--------------------------------------------------")
}
}
log(deployer) prints undefined. and It returns the error:
TypeError: Cannot read properties of undefined (reading 'length')
The same process but using ganache instead run fine.
I have the hardhat-deploy plugin installed and i'm using the command hardhat deploy.
Any ideas ?

const { ethers } = require("hardhat");
async function main() {
const AMOUNT = ethers.utils.parseEther("0.1"); //bignumber
const [deployer] = await ethers.getSigners();
const iWTH = await ethers.getContractAt(
"IWeth",
"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
deployer
);
const tx = await iWTH.deposit({ value: AMOUNT });
await tx.wait(1);
const wethBalance = await iWTH.balanceOf(deployer.address);
console.log(`WETH OF ${deployer.address}:= WETH ${wethBalance / 10 ** 18} `);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Try this this worked for me .instead of getNamedAccounts use
const [deployer] = await ethers.getSigners();

It's clear that deployer is not loaded properly.
This usually happens when you have not set up your module.exports in the file where you wrote the "getNamedAccounts()" function

in your hardhat-config.js file under the module.exports section please include the following feilds
namedAccounts: {
deployer: {
default: 0,
1: 0,
} } ,
also please ensure that the following imports are there
require("#nomiclabs/hardhat-waffle")
require("hardhat-gas-reporter")
require("#nomiclabs/hardhat-etherscan")
require("dotenv").config()
require("solidity-coverage")
require("hardhat-deploy")
although gas-reports and all are not necessary since you are fallowing the 31-hours course ....sooner or later you will be needing it
I guess it should work now

In Hardhat.config.js file
change getNamedAccounts to namedAccounts
namedAccounts: {
deployer: {
default: 0,
},
users: {
default: 1,
},
},
Also,
in deploy.js Make getNamedAccounts a function by adding
"()"
const { deployer } = await getNamedAccounts;
to
const { deployer } = await getNamedAccounts();

Related

NodeJS: My jest spyOn function is not being called

I don't understand why my spy is not being used. I have used this code elsewhere and it has worked fine.
Here is my test:
const {DocumentEngine} = require('../documentEngine')
const fileUtils = require('../utils/fileUtils')
const request = {...}
const fieldConfig = {...}
test('If the Carbone addons file is not found, context is built with the carboneAddons property as an empty object', async () => {
const expectedResult = {
carboneAddons: {},
}
const fileExistSpy = jest
.spyOn(fileUtils, 'checkFileExists')
.mockResolvedValue(false)
const result = await docEngine.buildContext(request, fieldConfig)
expect(fileExistSpy).toHaveBeenCalledTimes(1)
})
Here is the code that it is being tested:
async function buildContextForLocalResources(request, fieldConfig) {
/* other code */
const addonFormatters = await getCarboneAddonFormatters()
const context = {
sourceJson,
addonFormatters,
documentFormat,
documentTemplateId,
documentTemplateFile,
responseType,
jsonTransformContext
}
return context
}
async function getCarboneAddonFormatters() {
const addOnPath = path.resolve(
docConfig.DOC_GEN_RESOURCE_LOCATION,
'library/addon-formatters.js'
)
if (await checkFileExists(addOnPath)) {
logger.info('Formatters found and are being used')
const {formatters} = require(addOnPath)
return formatters
}
logger.info('No formatters were found')
return {}
}
This is the code from my fileUtils file:
const fs = require('fs/promises')
async function checkFileExists(filePath) {
try {
await fs.stat(filePath)
return true
} catch (e) {
return false
}
}
My DocumentEngine class calls the buildContext function which in turn calls the its method getCarboneAddonFormatters. The fileUtils is outside of DocumentEngine class in a utilities folder. The original code I had this working on was TypeScript as opposed to this which is just NodeJS Javascript. The config files for both are the same. When I try to step through the code (VSCode debugger), as soon as I hit the line with await fs.stat(filePath) in the checkFileExists function, it kicks me out of the test and moves on to the next test - no error messages or warnings.
I've spent most of the day trying to figure this out. I don't think I need to do an instance wrapper for the documentEngine, because checkFileExists is not a class member, and that looks like a React thing...
Any help in getting this to work would be appreciated.

js imported function error "getUser not a function"

I have three files
BotJobActions.js
TestDate.js
CreateCron.js
The BotJobActions file creates a function called getUser that returns the user connected to a specific job, then exports the getUser along with a bunch of other functions.
const getUser = async (jobId) =>{
await mongoConnect(process.env.DB_PWORD)
try {
const user = await User.findOne({pendingJobs:jobId})
return user
} catch (err) {
console.log(err)
}
}
module.exports = { newJob, getUserJobs, getUser, updateUserJob, destroyUserPendingJob, destroyUserCompletedJob, activateJob, deactivateJob, endJob }
TestDate defines a function called runBot which runs a bot Job. In runBot it also calls the getUser function, so I can make changes to a specific user. Then exports the function because it will be used in other files.
const { getUser } = require("../bot/botJobActions");
const runBot = async (todayJobs) =>{
// await mongoConnect(process.env.DB_PWORD)
for(const job of todayJobs){
const clubPassword = decryptToken(job.clubPassword.token, job.clubPassword.iv)
const user = await getUser(job.id)
if(job.proxy){
const proxyConfig = await getProxyConfig(user)
if(proxyConfig.status === "no proxy") console.log("[-] Proxy Config Retrival Error/Running Without Proxy")
// await startBot(member=job.member?job.member : null, proxy=proxyConfig.status === 'success'?proxyConfig:null, job.clubUsername, clubPassword, job.startTime, job.endTime, job.courseList, job.id)
await console.log(member=job.member?job.member : null, proxy=proxyConfig.status === 'success'?proxyConfig:null, job.clubUsername, clubPassword, job.startTime, job.endTime, job.courseList, job.id)
}else{
// await startBot(member=job.member?job.member : null, proxy=null, job.clubUsername, clubPassword, job.startTime, job.endTime, job.courseList, job.id)
await console.log(member=job.member?job.member : null, proxy=null, job.clubUsername, clubPassword, job.startTime, job.endTime, job.courseList, job.id)
}
}
return
}
module.exports = { runBot, getJobs }
CreateCron is a function that runs whenever a job is created with a specific start time. This function will create a cron job for that specified time to run the bot.
const schedule = require('node-schedule');
const { runBot } = require('./testDate');
const createCron = (job) =>{
const startDate = new Date(job.botStartDate)
const startTime = new Date(`09/19/2000 ${job.botStartTime}`)
startDate.setHours(startTime.getHours())
startDate.setMinutes(startTime.getMinutes())
console.log(startDate.toUTCString())
schedule.scheduleJob(startDate, async function(){
console.log('run job')
await runBot([job])
})
}
My problem thought is that whenever I run the createCron function, I get an error saying that the getUser is not a function. Even thought it is.
Any help is appreciated!!
I was able to fix the problem. All I had to do was use the absolute path to the function instead of the relative path. Then the functions worked. Hope this can help somebody!

Manually resolve promise for getPromiseFinishAllItems

I'm using a combination of protractor, selenium, jasmine and report portal for automated testing. The tests all run fine but when it comes to the last test it always hangs and it eventually fails, looking into it, it seems to come down to what is used in the afterAll function in my protractor.conf.js file.
jasmineEnv.afterAll(async (done) => {
await agent.getPromiseFinishAllItems(agent.tempLaunchId);
done();
});
Now the function it calls comes from the node modules reportportal-agent.js :
getPromiseFinishAllItems(launchTempId){
return this.client.getPromiseFinishAllItems(launchTempId)
}
I've noticed that written above this function is the comment
/*
* This method is used for frameworks as Jasmine and other. There is problems when
* it doesn't wait for promise resolve and stop the process. So it better to call
* this method at the spec's function as #afterAll() and manually resolve this promise.
*
* #return a promise
*/
I'm wondering is there a solution for how to properly resolve this promise? I have tried looking online but not found anything of any significance
EDIT -
protractor.conf.js
const ReportportalAgent = require('agent-js-jasmine');
const { SpecReporter } = require('jasmine-spec-reporter');
const suiteSettings = require('./suiteSettings');
const settings = require('./settings');
const logger = require('./tests/helpers/logger');
// This is a temporary solution because we have issues if instances=nodes. For now balance between nodes and instances that instances < 3
const nodeReduceCount = 5;
let isBrowserOpen = false;
exports.config = {
framework: 'jasmine',
seleniumAddress: settings.seleniumHubHost,
capabilities: {
'shardTestFiles': true,
'maxInstances': Math.max(settings.countOfStreams - nodeReduceCount, 1),
'browserName': settings.browser,
'loggingPrefs': {
performance: 'INFO',
},
'moz:firefoxOptions': getFirefoxOptions(),
'goog:chromeOptions': getChromeOptions(),
},
suites: [
suiteSettings.suite,
],
jasmineNodeOpts: {
defaultTimeoutInterval: settings.jasmineTimeout,
isVerbose: false,
includeStackTrace: true,
realtimeFailure: false,
},
onPrepare: async () => {
const jasmineEnv = jasmine.getEnv();
const capabilities = await browser.getCapabilities();
const config = await browser.getProcessedConfig();
global.consoleReporter = [];
console.log(capabilities);
if (!settings.useReportPortal) {
registerReporter(jasmineEnv);
} else {
registerConsoleReporter(jasmineEnv);
}
jasmineEnv.beforeEach(async () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = settings.jasmineTimeout;
const criticalCheck = String(config.specs);
if (criticalCheck.includes('critical')) {
process.env.RUN_WITH_SERVICE_WORKER = 'true';
} else {
process.env.RUN_WITH_SERVICE_WORKER = '';
}
if (isBrowserOpen) {
browser.restart();
}
await browser.driver.manage().window().setSize(settings.viewPort.width, settings.viewPort.height);
isBrowserOpen = true;
await logger.logMessage(`Opening Link ${settings.newPlanUrl()}`);
await browser.waitForAngularEnabled(false);
await browser.get(settings.newPlanUrl());
});
},
};
function registerReporter(jasmineEnv) {
jasmineEnv.addReporter(new SpecReporter({
spec: {
displayStacktrace: true,
},
}));
const config = {
id: browser.params.id,
...settings.reportPortal,
};
const agent = new ReportportalAgent(config);
const reporter = agent.getJasmineReporter();
jasmineEnv.afterAll(async (done) => {
await agent.getPromiseFinishAllItems(agent.tempLaunchId);
done();
});
global.reporter = reporter;
jasmineEnv.addReporter(reporter);
return agent;
}
function registerConsoleReporter(jasmineEnv) {
jasmineEnv.afterEach(async () => {
await browser.takeScreenshot().then((png) => {
const testSuite = settings.currentSuite;
const date = new Date();
const currentDay = `(Time-${date.getHours()}-${date.getMinutes()}-${date.getSeconds()})`;
logger.writeScreenShot(png, `screenshots/${currentDay}_${testSuite}.png`);
});
});
jasmineEnv.afterAll(async () => {
await console.log('\n---------------------------------');
await console.log('Test Results');
await global.consoleReporter.forEach((testResult) => {
console.log(testResult);
});
await console.log('---------------------------------');
});
}
function getFirefoxOptions() {
const options = {};
if (settings.headless) {
options.args = ['--headless'];
}
return options;
}
function getChromeOptions() {
const options = {
args: [
'--disable-gpu',
'--no-sandbox',
'--disable-extensions',
'--disable-dev-shm-usage',
'--disable-infobars',
],
};
if (settings.headless) {
options.args.push('--headless');
options.perfLoggingPrefs = {
enableNetwork: true,
};
}
return options;
}
Edit:
So the error I had before was due to adding:
agent.getExitPromise.
But I've noticed after removing that and running my test suite again to see if jenkins would log anything useful when it comes to the test that gets interrupted, it says:
13:43:26 Cancelling nested steps due to timeout
13:43:26 ...Sending interrupt signal to process
13:43:31 npm ERR! path /app
13:43:31 npm ERR! command failed
13:43:31 npm ERR! signal SIGTERM
13:43:31 npm ERR! command sh -c node generateTests.js && node start.js
does anyone have any idea what the cause of this could be?
So after comments with Sergey which helped massively. I realised I was looking in the wrong area and tried to think more of what is happening. Looking at the test runs I noticed that the last test was cut off so I figured I must be closing the connection somewhere before the last test has a chance to finish.
What I've done, which seems to work is do:
jasmineEnv.afterAll(async (done) => {
await agent.getPromiseFinishAllItems(agent.tempLaunchId);
await agent.getExitPromise();
done();
});
Getting the exit promise appears to have solved the issue
Okay so I finally found out what the issue was, we had files that were in the incorrect directory. That was it, once these were moved to the correct place, the issue stopped happening and the last test no longer gets hung up. So for anyone else that comes across this issue, this is something to check

Example script provided by neo4j for JavaScript won't run

I am very new to the graph database ecosystem and for start I am experimenting with the neo4j. I would very much like to work with node and neo4j. So after a quick search I found neo4j-driver that is an officially supported driver for JavaScript and an example provided which is:
const neo4j = require('neo4j-driver')
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session()
const personName = 'Alice'
try {
const result = await session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{ name: personName }
)
const singleRecord = result.records[0]
const node = singleRecord.get(0)
console.log(node.properties.name)
} finally {
await session.close()
}
// on application exit:
await driver.close()
now when I run this code, I immediately get the following error:
SyntaxError: await is only valid in async function
Now I thought I understood the error that I would have to wrap the try-catch block with anonymous async function to get rid of the error. The changed code body is:
const config = {
"neo4j": {
"url": "neo4j://localhost",
"authUser": "neo4j",
"authKey": "adminPassword"
}
}
const neo4j = require("neo4j-driver");
const driver = neo4j.driver(
config.neo4j.url,
neo4j.auth.basic(config.neo4j.authUser, config.neo4j.authKey)
);
const session = driver.session();
(async () => {
try {
const result = await session.run('CREATE (a:Person {name: $name}) RETURN a', { name: 'Alice' });
const singleRecord = result.records[0];
const node = singleRecord.get(0);
console.log(node.properties.name);
} catch (error) {
console.log("Error Body: ", error);
} finally {
await session.close();
}
})();
await driver.close();
But to my dismay, I have run into another error that is very cryptic:
{ Neo4jError: Could not perform discovery. No routing servers available. Known routing table: RoutingTable[database=Sample database, expirationTime=0, currentTime=1592397056399, routers=[], readers=[], writers=[]]
at captureStacktrace (/Users/pc/node_modules/neo4j-driver/lib/result.js:263:15)
at new Result (/Users/pc/node_modules/neo4j-driver/lib/result.js:68:19)
at Session._run (/Users/pc/node_modules/neo4j-driver/lib/session.js:174:14)
at Session.run (/Users/pc/node_modules/neo4j-driver/lib/session.js:135:19)
at /Users/pc/neoNode.js:20:38
at Object.<anonymous> (/Users/pc/neoNode.js:31:3)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12) code: 'ServiceUnavailable', name: 'Neo4jError' }
I also had some problems with this.
First off, Natam Oliveira is correct. You need to use the bolt protocol, and await promises needs to be within an async function. For some reason the neo4j protocol is used in some examples in the docs. Additionally it would seem both examples currently provided by Neo4j—in the driver-manual and javascript-driver section—causes errors if you use them outside of some kind of unspecified environment.
There were some clues on the npmjs pagckage page, though, so by working them into the existing code, I was at least able to spit out some data. However I'm also wondering on how you could make this work inside the async function, so an explanation to how that could work with this driver would be very welcome.
Here's what worked for me:
const neo4j = require('neo4j-driver')
const cnx = {
user: 'neo4j',
password: 'some passphrase',
uri: 'bolt://localhost:7687'
}
const driver = neo4j.driver(cnx.uri, neo4j.auth.basic(cnx.user, cnx.password))
driver.verifyConnectivity()
.then((cnxMsg) => {
console.log(cnxMsg)
})
const session = driver.session({ database: 'neo4j' })
session.run('MATCH (n:Movie) RETURN n LIMIT 5')
.subscribe({
onKeys: keys => {
console.log(keys)
},
onNext: record => {
console.log(record.get('n').properties.title)
},
onCompleted: () => {
session.close()
},
onError: error => {
console.error(error)
}
})
This spits out some movies using the streaming API as seen in the NPM documentation. (Note: It will only work if you started/installed the Movie database, so double check that you didn't delete it, as its deletion is also part of the Neo4j tutorial.) Now just change the MATCH Cypher query to whatever you like, and play around with the output, for instance by piping it to Express.
Sources:
https://neo4j.com/docs/driver-manual/current/client-applications/
https://neo4j.com/developer/javascript/#javascript-driver
https://www.npmjs.com/package/neo4j-driver
https://neo4j.com/docs/api/javascript-driver/current/
first of all, I think your URL should be "url": "bolt://localhost:7687"
And you still with await driver.close() outside an async function
If you are starting to use neo4j, look for an OGM (Object Graph Model) to help you.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object

I am using the source code from a security rules tutorial to attempt to do integration testing with Jest for my Javascript async function async_create_post, used for my firebase HTTP function create_post The files involved has a directory structure of the following:
Testing file: root/tests/handlers/posts.test.js
File to be tested: root/functions/handlers/posts.js
Helper code from the tutorial: root/tests/rules/helpers.js
And here is the source code that is involved:
posts.test.js
const { setup, teardown} = require("../rules/helpers");
const {
async_get_all_undeleted_posts,
async_get_post,
async_delete_post,
async_create_post
} = require("../../functions/handlers/posts");
describe("Post Creation", () => {
afterEach(async () => {
await teardown();
});
test("should create a post", async () => {
const db = await setup();
const malloryUID = "non-existent uid";
const firstPost = {
body: "First post from Mallory",
author_id: malloryUID,
images: ["url1", "url2"]
}
const before_post_snapshot = await db.collection("posts").get();
expect(before_post_snapshot.docs.length).toBe(0);
await async_create_post(firstPost); //fails at this point, expected to create a new post, but instead threw an error
const after_post_snapshot = await db.collection("posts").get();
expect(after_post_snapshot.docs.length).toBe(1);
});
});
posts.js
const {admin, db } = require('../util/admin');
//admin.initializeApp(config); //my credentials
//const db = admin.firestore();
const { uuid } = require("uuidv4");
const {
success_response,
error_response
} = require("../util/validators");
exports.async_create_post = async (data, context) => {
try {
const images = [];
data.images.forEach((url) => {
images.push({
uid: uuid(),
url: url
});
})
const postRecord = {
body: data.body,
images: images,
last_updated: admin.firestore.FieldValue.serverTimestamp(),
like_count: 0,
comment_count: 0,
deleted: false,
author_id: data.author_id
};
const generatedToken = uuid();
await db
.collection("posts")
.doc(generatedToken)
.set(postRecord);
// return success_response();
return success_response(generatedToken);
} catch (error) {
console.log("Error in creation of post", error);
return error_response(error);
}
}
When I run the test in Webstorm IDE, with 1 terminal running Firebase emulators:start , I get the following error message.
console.log
Error in creation of post TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object
at validateString (internal/validators.js:120:11)
at Object.basename (path.js:1156:5)
at GrpcClient.loadProto (/Users/isaac/Desktop/project/functions/node_modules/google-gax/src/grpc.ts:166:23)
at new FirestoreClient (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/v1/firestore_client.js:118:38)
at ClientPool.clientFactory (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/index.js:330:26)
at ClientPool.acquire (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/pool.js:87:35)
at ClientPool.run (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/pool.js:164:29)
at Firestore.request (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/index.js:961:33)
at WriteBatch.commit_ (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/write-batch.js:485:48)
at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:36:5) {
code: 'ERR_INVALID_ARG_TYPE'
}
at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:44:13)
Error: expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0
<Click to see difference>
at Object.<anonymous> (/Users/isaac/Desktop/project/tests/handlers/posts.test.js:59:45)
Error in creation of post comes from the console.log("Error in creation of post", error); in posts.js, so the error is shown in the title of this post.
I want to know why calling the async_create_post from posts.test.js will cause this error and does not populate my database with an additional record as expected behaviour. Do inform me if more information is required to solve the problem.
Here are some code snippets that may give more context.
helpers.js [Copied from the repository]
const firebase = require("#firebase/testing");
const fs = require("fs");
module.exports.setup = async (auth, data) => {
const projectId = `rules-spec-${Date.now()}`;
const app = firebase.initializeTestApp({
projectId,
auth
});
const db = app.firestore();
// Apply the test rules so we can write documents
await firebase.loadFirestoreRules({
projectId,
rules: fs.readFileSync("firestore-test.rules", "utf8")
});
// write mock documents if any
if (data) {
for (const key in data) {
const ref = db.doc(key); // This means the key should point directly to a document
await ref.set(data[key]);
}
}
// Apply the actual rules for the project
await firebase.loadFirestoreRules({
projectId,
rules: fs.readFileSync("firestore.rules", "utf8")
});
return db;
// return firebase;
};
module.exports.teardown = async () => {
// Delete all apps currently running in the firebase simulated environment
Promise.all(firebase.apps().map(app => app.delete()));
};
// Add extensions onto the expect method
expect.extend({
async toAllow(testPromise) {
let pass = false;
try {
await firebase.assertSucceeds(testPromise);
pass = true;
} catch (error) {
// log error to see which rules caused the test to fail
console.log(error);
}
return {
pass,
message: () =>
"Expected Firebase operation to be allowed, but it was denied"
};
}
});
expect.extend({
async toDeny(testPromise) {
let pass = false;
try {
await firebase.assertFails(testPromise);
pass = true;
} catch (error) {
// log error to see which rules caused the test to fail
console.log(error);
}
return {
pass,
message: () =>
"Expected Firebase operation to be denied, but it was allowed"
};
}
});
index.js
const functions = require('firebase-functions');
const {
async_get_all_undeleted_posts,
async_get_post,
async_delete_post,
async_create_post
} = require('./handlers/posts');
exports.create_post = functions.https.onCall(async_create_post);
The error message means that a method of the path module (like path.join) expects one of its arguments to be a string but got something else.
I found the offending line by binary search commenting the program until the error was gone.
Maybe one of your modules uses path and you supply the wrong arguments.

Categories

Resources