Solidity TypeError: artifacts is not a function - typeerror

I am a student learning to write smart contracts using solidity. When running these codes using truffle(ganache):
Helloworld.sol
pragma solidity 0.5.12;
contract Helloworld {
string message = "Hello World";
function getMessage() public view returns (string memory) {
return message;
}
function setMessage(string memory newMessage) public payable {
message = newMessage;
}
}
Helloworld_migration.js
const Helloworld = artifacts.require("Helloworld");
module.exports = function(deployer, network, accounts){
deployer.deploy(Helloworld).then(function(instance){
instance.setMessage("Hello Again!", {value: 1000000, from: accounts[0]}).then(function(){
console.log("Success");
}).catch(function(err){
console.log("error: " + err);
});
}).catch(function(err){
console.log("Deploy failed " + err);
});
};
Helloworldtest.js
const Helloworld = artifacts().require("Helloworld");
contract("Helloworld", async function(){
it("should initialize correctly", async function(){
let instance = await Helloworld.deployed();
let message = await instance.getMessage();
assert(message === "Hello Again!");
});
});
I received this error msg:
TypeError: artifacts is not a function
at Object.<anonymous> (/Users/cherrybluemoon/projects/test/Helloworldtest.js:1:20)
at Module._compile (internal/modules/cjs/loader.js:1123:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
at Module.load (internal/modules/cjs/loader.js:972:32)
at Function.Module._load (internal/modules/cjs/loader.js:872:14)
at Module.require (internal/modules/cjs/loader.js:1012:19)
at require (internal/modules/cjs/helpers.js:72:18)
at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:231:27
at Array.forEach (<anonymous>)
at Mocha.loadFiles
(/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:228:14)
at Mocha.run
(/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:536:10)
at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-
core/lib/test.js:135:1
at processTicksAndRejections (internal/process/task_queues.js:97:5)

You have to remove "()" from artifacts.
const Helloworld = artifacts.require("Helloworld");

Helloworld_migration.js is an invalid file name for a migration file. It needs to start with a number such as 1_migration.js or 1_helloworld_migration.js

Related

Short stack trace with async await in protractor 7

I'm trying to automate some tests with protractor and jasmine and I'm using async/await to resolve the promises.
The issue is, when an error does happen, the stack trace is TOO short and thus, I can't seem to locate the source of the issue.
I did make sure to put SELENIUM_PROMISE_MANAGER to FALSE in the config file.
I'm using protractor 7 along with node 14.16.0
Does anyone know how to solve this ? There are not enough details
Here's a code snippet
const invoicesButton: Button = new Button("Invoices", LocatorType.Href, "#/Invoices");
describe("Kouka test", function () {
beforeEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000000;
});
it("Does a random test", async function () {
await browser.get("https://appdev.expensya.com/Portal/#/Login?lang=en");
await loginEmailInput.typeText("amr.refacto#yopmail.com")
await loginPasswordInput.typeText("a")
await loginButton.click(true);
await dashboardPage.invoicesButton.click().catch((e) => {
e.stackTraceLimit = Infinity;
throw e;
});
await userInvoicesPage.createManualInvoice(invoice).catch((e) => {
e.stackTraceLimit = Infinity;
console.error("TEST ERROR ", e);
throw e;
});
await browser.sleep(10000);
});
});
And here's the definition of the "Button" Class:
import { browser } from "protractor";
import { WebComponent } from "./webComponent";
export class Button extends WebComponent {
/**
* #param webElementText Text that the web element contains.
* #param locatorType Locator type of the web element to search for.
* #param locator Locator of the web element to search for.
* #param parentElement Parent Web Component if it exists.
*/
constructor(webElementText, locatorType, locator, parentElement: WebComponent = null) {
super(webElementText, locatorType, locator, parentElement);
}
async click(usingJavaScript = false) {
if (usingJavaScript) {
await this.isPresent();
await browser.executeScript("arguments[0].click();", await this.webElement)
}
else {
await this.isVisible();
await this.isClickable();
await this.webElement.click();
}
}
}
Finally, here's the stack trace
Started
Jasmine started
undefined
F
Kouka test
× Does a random test
- Failed: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
Failures:
1) Kouka test Does a random test
Message:
Failed: Wait timed out after 10012ms
Stack:
TimeoutError: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
1 spec, 1 failure
Finished in 19.461 seconds
I remember trying to solve this a while ago and I couldn't. But I implemented a bunch of workarounds and apparently this was enough
To begin, can you share what these are doing
await this.isPresent();
await this.isVisible();
await this.isClickable();
Having this function
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime
)
}
you can use an advantage of third argument of browser.wait as described here and include an optional message on failure like this
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Element ${this.webElement.locator().toString()} is not present after ${this._elapsedTime}ms`);
)
}
(I'm giving you all my secret sauce ingredients haha) If you add this to onPrepare in the config
/**
* Set global environment configuration
*/
Object.defineProperty(global, '__stack', {
get: function() {
let orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
let err = new Error();
Error.captureStackTrace(err, arguments.callee);
let stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
},
});
// returns name of the file from which is called
Object.defineProperty(global, '__file', {
get: function() {
let path = __stack[1].getFileName();
try {
//*nix OSes
return path.match(/[^\/]+\/[^\/]+$/)[0];
} catch (error) {
//Windows based OSes
return path.match(/[^\\]+\\[^\\]+$/)[0];
}
},
});
// returns function name from which is called
Object.defineProperty(global, '__function', {
get: function() {
return __stack[1].getFunctionName();
},
});
// returns line number of the position in code when called
Object.defineProperty(global, '__line', {
get: function() {
return __stack[1].getLineNumber();
},
});
then you can use it for logging the file name, function name, and the line where it's called
For example,
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Failed at ${__file} -> ${__function}() -> line ${__line}`
)
}
will result in this error
- Failed: Failed at common/index.js -> isVisible() -> line 82
Wait timed out after 1032ms
Wait timed out after 1032ms
So you can accommodate this to your needs
also I just realized you may want to play around with __stack variable itself

Test Smart Contract with arguments in constructor with truffle

I want to test smart contract with parameter in constructor but have error.
Here is my smart contract and test files:
pragma solidity >=0.4.25 <0.7.0;
contract Test {
string public test;
constructor(string memory _test) public {
test = _test;
}
}
const Test = artifacts.require("Test");
contract('Test', (accounts) => {
it('should init', async () => {
const instance = await Test.new("test");
const result = await instance.test;
assert.equal("test", result, "info is not equals");
});
});
And log:
Error: while migrating Test: Invalid number of parameters for "undefined". Got 0 expected 1!
at /usr/local/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:365:1
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at Migration._deploy (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:68:1)
at Migration._load (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:55:1)
at Migration.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:171:1)
at Object.runMigrations (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:150:1)
at Object.runFrom (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:110:1)
at Object.runAll (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:114:1)
at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:79:1)
at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/testing/Test.js:109:1)
at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/test/index.js:192:1)
at Command.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/command.js:136:1)
Truffle v5.1.64 (core: 5.1.64)
Node v12.16.3
How to solve it?
Your forgot to pass the transaction params including the sender (deployer) adddres.
const instance = await Test.new("test");
shoud be
const txParams = {
from: accounts[0]
};
const instance = await Test.new("test", txParams);
More info on the new() function: https://www.trufflesuite.com/docs/truffle/reference/contract-abstractions#-code-mycontract-new-arg1-arg2-tx-params-code-

Nodemailer: Cannot find module 'net' + nodemailer.createTransport is not a function

I am unable to understand why nodemailer is not working properly within a VUE.js app.
The code is from the nodemailer examples. Here is the method I call on form submit:
methods: {
submit() {
this.$refs.form.validate().then(() => {
"use strict";
const nodemailer = require("nodemailer");
async function main() {
let transporter = nodemailer.createTransport({
host:'mail.kakakakak',
port: 465,
secure: true,
auth: {
user: 'info#',
pass: '****'
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: "info#lopezi.com",
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>" // html body
});
console.log("Message sent: %s", info.messageId);
}
main().catch(console.error);
});
},
}
The first time I click the submit button I get the error:
Uncaught (in promise) Error: Cannot find module 'net'
at webpackEmptyContext (eval at ./node_modules/defaultable sync recursive (app.5176eebb0babf67e88fb.hot-update.js:22), <anonymous>:2:10)
at Object.workaround_require (defaultable.js?6987:49)
at require (defaultable.js?6987:77)
at eval (server.js?663d:9)
at defaulter (defaultable.js?6987:83)
at defaultable (defaultable.js?6987:63)
at good (defaultable.js?6987:174)
at Object.eval (server.js?663d:5)
at eval (server.js:242)
at Object../node_modules/hbo-dnsd/server.js (chunk-vendors.5176eebb0babf67e88fb.hot-update.js:2053)
The second time I click the submit button, still with the same content in there I get the error:
TypeError: nodemailer.createTransport is not a function
at _callee$ (ContactForm.vue?2be1:64)
at tryCatch (runtime.js?96cf:45)
at Generator.invoke [as _invoke] (runtime.js?96cf:271)
at Generator.prototype.<computed> [as next] (runtime.js?96cf:97)
at asyncGeneratorStep (asyncToGenerator.js?3b8d:5)
at _next (asyncToGenerator.js?3b8d:27)
at eval (asyncToGenerator.js?3b8d:34)
at new Promise (<anonymous>)
at new F (_export.js?63b6:36)
at eval (asyncToGenerator.js?3b8d:23)

missing db argument error when connecting gridfs multer and mongodb

I am using gridfs and mutler to upload files likes ppt pdf etc..to mongodb atlas. When setting up router its keeps saying db not found I have my uri in a config file.What am i missing here in mongodb atlas i have 3 collections in a database called 'test' do i have to create another db in the cluster? Please help
if (!db) throw new Error('missing db argument\nnew Grid(db, mongo)');
^
Error: missing db argument new Grid(db, mongo)
at new Grid (/Users/ezana/Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:25:18)
at Grid (/Users/ezana/Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:19:12)
at Object. (/Users/ezana/Desktop/Canvas/backend/api/routes/fileUploadRoutes.js:9:11)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (/Users/ezana/Desktop/Canvas/backend/app.js:7:21)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
const router = require('express').Router();
const multer = require('multer');
const db = require('./config/main').mongoURI;
const {
mongo,
connection
} = require('mongoose');
const Grid = require('gridfs-stream');
Grid.mongo = mongo;
const gfs = Grid(connection.db);
const storage = require('multer-gridfs-storage')({
db: connection.db,
file: (req, file) => {
return {
filename: file.originalname
}
}
});
const mongoose = require("mongoose");
const multer = require("multer");
const Grid = require("gridfs-stream");
const GridFsStorage = require("multer-gridfs-storage");
const db = mongoose.connection;
let gfs;
db.once("open", function() {
gfs = Grid(db.db, mongoose.mongo);
});
const storage = new GridFsStorage({
url:
url,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString("hex") + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: "uploads"
};
resolve(fileInfo);
});
});
}
});
This worked for me.

wit.ai quickstart.js error from node, unexpected token{

I am going through the wit.ai quickstart tutorial and get an error from node (version 4.5.0 LTS), but I don't see the error in the code and also, it is the example code downloaded directly from wit.ai:
examples\quickstart.js:39
const {sessionId, context, entities} = request;
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
Also, the code in the download from git is different than the code shown on the tutorial page:
Code from the git clone, example/quickstart.js is this:
'use strict';
let Wit = null;
let interactive = null;
try {
// if running from repo
Wit = require('../').Wit;
interactive = require('../').interactive;
} catch (e) {
Wit = require('node-wit').Wit;
interactive = require('node-wit').interactive;
}
const accessToken = (() => {
if (process.argv.length !== 3) {
console.log('usage: node examples/quickstart.js <wit-access-token>');
process.exit(1);
}
return process.argv[2];
})();
// Quickstart example
// See https://wit.ai/ar7hur/quickstart
const firstEntityValue = (entities, entity) => {
const val = entities && entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value
;
if (!val) {
return null;
}
return typeof val === 'object' ? val.value : val;
};
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
console.log('sending...', JSON.stringify(response));
},
getForecast({context, entities}) {
var location = firstEntityValue(entities, 'location');
if (location) {
context.forecast = 'sunny in ' + location; // we should call a weather API here
delete context.missingLocation;
} else {
context.missingLocation = true;
delete context.forecast;
}
return context;
},
};
const client = new Wit({accessToken, actions});
interactive(client);
but the tutorial says the const actions section should be this:
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
return new Promise(function(resolve, reject) {
console.log('sending...', JSON.stringify(response));
return resolve();
});
},
getForecast({context, entities}) {
return new Promise(function(resolve, reject) {
// Here should go the api call, e.g.:
// context.forecast = apiCall(context.loc)
context.forecast = 'sunny';
return resolve(context);
});
},
};
Regardless, both versions give the same error.
Turns out that, due to some ECMAScript 6 features in the code, if your node version <= 6.x.x, you have to add the flag harmony_destructuring to the node command line, as illustrated here:
node --harmony_destructuring examples/quickstart.js