running zeppelin-solidity demos shows undefined return message - truffle

I'm studying deploying smart contract following the steps on this article.
I used absolute path for import instead of relative path because compiler was not able to look into import files in node_modules so it compiles
the truffle migrate seems good because when I input JCoinCrowdsale.deployed() it returns full info (I named JCoin for this example)
but when I input JCoinCrowdsale.deployed().then(inst => { crowdsale = inst }) , it returns undefined
Any clue on this?

You did it correctly! And I see that you assign the result of the promise JCoinCrowdsale.deployed() to the variable crowdsale.
The reason it shows undefined is due to the fact that this function inst => { crowdsale = inst } does not explicitly return anything.
If you type crowdsale on to the truffle console you will be able to see the same JavaScript object you get when you just type JCoinCrowdsale.deployed().
Hope it helps and wish you all the best in your learning :-)

Try below:
var crowdsale = JCoinCrowdsale.deployed().then(function(inst) { crowdsale = inst })

Related

Cypress: Cannot use cy.task() to load dataset to Mongo before tests

I'm trying to use cy.taks() to load certain datasets to mongo before a test is run. But I'm getting errors. I've got a module where I export 2 functions, one from dropping a collection, and the other to load an object to a collection. Here is my cypress/plugins/index.js:
module.exports = (on, config) => {
on("task", {
"defaults:db": () => {
const {dropCollection, createUser } = require("../../lib/connectDB");
dropCollection("users");
createUser(userData)
},
});
};
Here is my /lib/connecDB.js:
export function dropCollection(collection) {
return mongoose.connection.dropCollection(collection);
}
export async function createUserInDB(userData) {
await User.create(userData);
}
So when I run the test, I'm getting:
cy.task('defaults:db') failed with the following error:
Unexpected token 'export'
Tried as well importing these function outside the index.js export, but getting same result.
I'd say it is something about export/import. The functions are exported as ES6, and imported as ES5.
I've tried to import the function the ES6 like:
import { dropCollection, createUser } from '../lib/connectDB'
And then export the plugin function also as ES6, but then I get:
Error: The plugins file is missing or invalid.
Your `pluginsFile` is set to `C:\Users\someRoute\cypress\plugins\index.js`, but either the file is missing, it contains a syntax error, or threw an error when required. The `pluginsFile` must be a `.js`, `.ts`, or `.coffee` file.
I've also tried to import required modules outside the function like:
const globalDbUtils = require('../lib/connectDB')
And then use the functions as
globalDbUtils.dropCollection("collectionName")
globalDbUtils.createUser(userData)
But I'm getting last error. I've tried pretty much everything, I tried to import Mongoose models straight, mongo client etc...Also I tried to import just one function and return it (just copy/pasting official doc...) but cannot make it work. I researched for a couple of days getting nothing, I found there is a npm package that helps u doing this, but since cypress allows you to do this by using no more plugins, I'd like to do it with no more tools than cypress itself.
Anyone knows what I am doing wrong?
Thanks in advance!
You need to use require instead of import at the top of your file and when exporting at the bottom use
module.exports = { createUserInDB }
Instead of exporting as you are currently doing.

In Electron, using "typeof" causes TypeError: Cannot assign to read only property

I got a doozie here. In Electron's main process, I require in the function below to setup event handlers with ipcMain. This keeps the main.js file a little more streamlined. All went swimmingly until I wrote some validation code to ensure that the user passes in an object. I use typeof all the time for this purpose, and never have I had an issue. But in Electron I am getting:
A JavaScript error occurred in the main process - TypeError: Cannot
assign to read only property 'exports' of object '# '
The code:
const {ipcMain} = require('electron');
function ipcSetup() {
ipcMain.on('123', function(event, arg) {
// this blows chunks...
if(arg && typeof arg === 'object') {
console.log(`All good....`);
}
// and if you comment that out, this use of "typeof" does the same thing
console.log(typeof arg);
// and to eliminate 'arg' as the issue...
let a = 1;
console.log(typeof a); // expect 'number', get Exception
});
}
module.exports = ipcSetup;
I didn't know if Electron is using Object.defineProperty to make arg read only, but typeof is not making an assignment here anyway, and I eliminated arg so this error makes no sense. Environment is Electron 1.8.4 on Node 8.2.1 using electron-vue
If you're importing that module in another module that uses ES6 import/export syntax, using typeof apparently causes this. I think this is because webpack doesn't support mixing the two syntaxes. But it is quite funny that it would work fine if you didn't use the typeof operator...

How to use a pig latin translator npm module inside my React app

I need to write a React/Redux app to translate an English sentence into Pig Latin. I found that there are some already existing npm modules for this purpose, hence thought of reusing them. I wrote a simple functional component for this translation as below.
import _ from 'lodash';
import React from 'react';
import piglatin from 'piglatin';
function convertToPigLatin(data){
// https://www.npmjs.com/package/piglatin
// return pigLatin(data);
}
export default (props) => {
console.log(props.data);
console.log(piglatin('hello there')); // Works fine
console.log(piglatin(props.data)); // gives an ERROR
return (
<label>Hello !</label>
)
}
Simply I just wanted to log the translated text into the console.But when I try that out it works for a hard coded text after changing it as per the answer below.
console.log(piglatin('hello there')); // Works fine
But when I pass real data it fails giving me this ERROR.
console.log(piglatin(props.data)); // gives an ERROR
Uncaught TypeError: Cannot read property 'split' of null at piglatin
I think this error occurs because we are missing '' around the text.Finally I was able to solve the issue by using the ES6 back-tick operator as below.
console.log(piglatin(`${props.data}`)); // This solved the issue
You may find my code here in github. How can I sort this out. Any help is really appreciated.
Later, I found that there's another npm module for the same purpose which is also a cool one. Both gives you identical results hence you may use either of them. There's a slight difference in code and I have posted it below.
import pigLatin from 'piglatin';
export const PIG_LATIN = 'PIG_LATIN';
export function pigLatinConvert(input){
console.log(input);
const output = pigLatin(`${input.inputtext}`);
console.log(output);
return {
type: PIG_LATIN,
payload: output
};
}
Looking at that module's docs is looks like it should be
console.log(piglatin(props.data));
NOT
console.log(piglatin.piglatin(props.data));

Electron app: Reference mainWindow object in another module?

I am building an electron app, where the mainWindow object is created following the quick start: http://electron.atom.io/docs/tutorial/quick-start/.
As per this quick start, it is created asynchronously. The problem that I run into, is that for instance when I want to send messages from main to renderer process, I need to reference the mainWindow object. If this happens to be in a module that I require, then I need a means to make this module know of the mainWindow object.
I could of course prepend it with global., but I know that this is very much advised against. So I wish to do it more elegantly.
I came across this post: Asynchronous nodejs module exports; which appears to offer a solution. Taking the main.js file from the quick start (see above link, it's explicitly shown there), it appears I would add to the createWindow function
if( typeof callback === 'function' ){
callback(mainWindow);
}
and export the main.js module as
module.exports = function(cb){
if(typeof mainWindow !== 'undefined'){
cb(mainWindow);
} else {
callback = cb;
}
}
Then, in a higher-level script, I would require as follows:
let main = require('./main.js');
let lib = require('./lib.js'); // Library where I need a mainWindow reference
main(function(window) {
lib.doSomething(window);
});
where lib.js looks like
module.exports.doSomething = function(window) {
// Do something with window object, like sending ipc messages to it
window.webContents.send('hello-from-main', "hi!");
}
Although the simple case in the original post 'Asynchronous nodejs module exports' works fine, I cannot get it to work like described above; running the app it complains Uncaught Exception: TypeError: Cannot read property 'webContents' of null. This is also the case if I directly require lib.js within main()'s callback (which I know is also advised against).
I confess that I do not fully understand the simple case of the post, as I am rather new to node. This prevents me from fixing my own implementation of it, which I agree is blunt copy/pasting which reasonably should be expected to fail. Could somebody help me with how to correct above method, or advise me of a different approach to make it work? Thank you!
I have created the npm package electron-main-window for the same.
Install:
$ npm install electron-main-window
or
$ yarn add electron-main-window
Usage:
// Import ES6 way
import { getMainWindow } from 'electron-main-window';
const mainWindow = getMainWindow();
// Import ES5 way
const mainWindow = require('electron-main-window').getMainWindow();
// e.g:
if(mainWindow !== null ){
mainWindow.webContents.send('mainWindowCommunication', "This is a test message");
}
Whooops! The devil is in the details... I had defined on top of main.js
let mainWindow = null, callback;
which caused the error! Should be
let mainWindow, callback;
then it works perfectly!
P.s. Instead of deleting my post, I opted for keeping it and answering myself for future reference of other people who need asynchronous exporting.

RequireJS Dependancies Fail Randomly: "Module has not been loaded yet for context", Puzzling

I've run into a problem with RequireJS that pops up randomly in different areas over and over, after a long period (about a year) of working fine.
I declare my requireJS file like this:
define(['TestController'], function (TestController)
{
return {
oneFunction: function(callback)
{
//When I try to use "TestController" here, I get the
//"Error: Module name "TestController" has not been
//loaded yet for context" error...
TestController.test(); //ERROR
//I had been using the above for years, without changes,
//and it worked great. then out of the blue started not
// working. Ok, let's try something else:
if(typeof TestController == "undefined")
{
var TestController = require('TestController'); //ERROR
}
//The above method worked for a few months, then broke AGAIN
// out of the blue, with the same error. My last resort is one
// that always works, however it makes my code have about 20+
//layers of callbacks:
require(['TestController'], function(TestController){
TestController.test();
//WORKS, but what's the point of declaring it as a
//requirement at the top if it doesn't work and I have to
//wrap my code every time? :(
});
},
anotherFunction: function()
{
console.log("hello");
}
}
});
I am getting the "Error: Module name "TestController" has not been loaded yet for context" error over and over until I re-declare the dependency... My question is, what's the point of declaring 'TestController' at the top as a dependency if I have to keep re-declaring it as if I never listed it? What am I doing wrong here?
I declare 'TestController' in other files and it works great, but every once and a while, ONE of the declarations will fail...and it's always a different file (there are about 200-300)... I never know which one, and the only way to fix it is to re-declare it and wrap it.
Anyone see anything I'm doing wrong that could be causing this? I keep updating RequireJS to see if it fixes it and it doesn't :/
Version
RequireJS 2.1.22
jquery-1.12.1
node 4.2.6
As #Louis pointed out, it was circular dependencies that was causing the problem.
Circular Dependency Solution #1: 'exports'
Here's the solution straight from RequireJS's documentation:
If you define a circular dependency ("a" needs "b" and "b" needs "a"), then in this case when "b"'s module function is called, it will get an undefined value for "a". "b" can fetch "a" later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up "a"):
//Inside b.js:
define(["require", "a"],
function(require, a) {
//"a" in this case will be null if "a" also asked for "b",
//a circular dependency.
return function(title) {
return require("a").doSomething();
}
}
);
If you are familiar with CommonJS modules, you could instead use exports to create an empty object for the module that is available immediately for reference by other modules.
//Inside b.js:
define(function(require, exports, module) {
//If "a" has used exports, then we have a real
//object reference here. However, we cannot use
//any of "a"'s properties until after "b" returns a value.
var a = require("a");
exports.foo = function () {
return a.bar();
};
});
Circular Dependency Solution #2: Visualize with madge
I came accross this npm module that will create a dependency graph for you : https://github.com/pahen/madge
I've decided to analyze my code with madge and remove the circular dependencies.
Here is how I used the tool:
cd <Client-Code-Location>
madge --image dep.png .
This gave me an image of the dependencies, however there were no circular dependencies found. So I decided to try another way:
cd <Client-Code-Location>
madge --image dep.png --format amd .
This way I was able to see where I had the circular dependency. :)

Resources