I am new to solidity.
This is my 1st simple project
when I do node compile.js & I am getting following error:
My Error :
{
contracts: {},
errors: [
":7:16: ParserError: Expected identifier, got 'LParen'\n" +
' constructor(string initialMessage) public{\r\n' +
' ^\n'
],
sourceList: [ '' ],
sources: {}
}
my compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const inboxPath = path.resolve(__dirname,'contracts','Inbox.sol');
const source = fs.readFileSync(inboxPath,'utf8');
console.log(solc.compile(source,1));
my Inbox.sol
pragma solidity ^0.4.17;
contract Inbox {
string public message;
constructor(string initialMessage) public{
message = initialMessage;
}
function setMessage(string newMessage) public{
message = newMessage;
}
}
I'm not sure why you are attempting to compile your smart contract natively using node. That is a fairly cumbersome approach (although it can be done, albeit with exponentially more work on your part), especially when tools already exist for this purpose.
The prefered method would be to use a tool such as the most recent build of truffle (which is a CLI tool available as a NodeJS package via NPM for compiling, deploying and testing smart contracts), instead of using NodeJS to compile.
Simply install truffle as a global package from a console using:
npm install -g truffle
Then navigate to your project root directory and run:
truffle init
This will generate a barebone project structure with everything that is required (such as directories for contracts and migrations).
After the project has been init'ed, open the truffle-config.js file and add the configurations required for your project:
module.exports = {
networks: {
//Configuration for localhost private dev network for testing code
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*" //Match any network id
}
//Connecting to the main, live ethereum network requires different config
//and should NOT be used for development purposes.
//Only after your contracts have been thoroughly tested and audited should you deploy a production ready project to the main net.
},
compilers: {
solc: {
version: "0.6.2"
}
}
};
You can specify whichever compiler version suites your needs, however, most contracts now a days should target version 0.6.0 and up for the most recent features.
Learn more about customizing Truffle's configuration here!
Now, this allows you to specify both the network to deploy to and the specific solidity compiler (which truffle will automatically download the correct version if it does not already exist on your system) to run when compiling your project.
After this is complete, your contracts can be compiled easily using:
truffle compile --all --network development
Note that the argument for --network must match an entry in truffle-config.js's networks object (although just for compiling, it should not be necessary to specify a network, only for deployment).
Then there you go! You have compiled your first smart contract.
However, there is one caveat.
At this point you do not have a local test network to deploy to.
When deploying the contract, it's important to be aware to not deploy untested code to the live main network until it has been tested and audited.
Since any changes to the blockchain are permanent, deploying buggy contracts to the live blockchain can't be undone and any bugs can and will be exploited by malicious agents indefinitely.
To solve this issue, the trufflesuite team also provides ganache-cli (alongside various other helpful tools) for running a private test network on localhost. This package is also available via NPM however, that goes beyond the scope of this answer and your question.
Hope that helps you get started, best of luck!
The problem you are facing is a result of the compiler version. with solidity compiler version 0.4.17 all you need to do is replace the constructor keyword with the name of the contract i.e implicitly creating the constructor function. That should do the trick and yes your code editor will most likely complain especially if you have linting enabled but your codes will still run
Related
I have a site running Gatsby and Gatsby-Source-Drupal7, it is a plugin that uses Graphql to make an axios get request to https://stagingsupply.htm-mbs.com/restws_resource.json and uses the json data to query. I am able to run it just fine on my computer by going to localhost:8000 and it creates over 200k nodes, but when I try to deploy on any cloud service provider like Gatsby Cloud or Netlify it doesn't fetch any nodes or data at all from the site.
Warning from console
Starting to fetch data from Drupal
warn The gatsby-source-drupal7 plugin has generated no Gatsby nodes. Do you need
it?
Code
code from gatsby config
module.exports = {
siteMetadata: {
title: `new`,
siteUrl: `https://www.yourdomain.tld`,
},
plugins: [
{
resolve: `gatsby-source-drupal7`,
options: {
baseUrl: `https://stagingsupply.htm-mbs.com/`,
apiBase: `restws_resource.json`, // optional, defaults to `restws_resource.json`
},
},
]
}
gatsby-config.js from node_modules/gatsby-source-drupal7
const createNode = actions.createNode; // Default apiBase to `jsonapi`
apiBase = apiBase || `restws_resource.json`; // Fetch articles.
// console.time(`fetch Drupal data`)
console.log(`Starting to fetch data from Drupal`);
const data = yield axios.get(`${baseUrl}/${apiBase}`, {
auth: basicAuth
});
const allData = yield Promise.all(_.map(data.data.list,
Link to repo that works on local computer https://github.com/nicholastorr/gatsby-d7
any and all help will be appreciated
As you pointed out, you've played around with the Node versions using NODE_ENV and engines workarounds. My guess also relies on a mismatching Node version between environments but as Netlify docs suggests, there are only two ways of customizing Node versions to manage dependencies.
Set a NODE_VERSION environment variable.
Add a .node-version or .nvmrc file to the site’s base directory in your repository. This will also tell any other developer using the
repository which version of Node.js it depends on.
Without seeing your Netlify build command (to see the NODE_VERSION) there's no .node-version nor .nvmrc in your repository. I'd try creating it at the root of the project with the v14.17.1 in it and trying a fresh install.
In addition, double-check other server-related conflicts like IP-blocking, etc.
Error was nothing Gatsby or Node related, my site was block the IP of the server :>
I am trying to deploy an AzureFunctions in NodeJs but it doesn't work on Azure.
My apllication is a v3 functions running on Linux.
When the deploy is completed, i get this 500 error:
Error:
/home/site/wwwroot/node_modules/canvas/build/Release/canvas.node:
invalid ELF header
Its happen only when I do this imports:
import ChartDataLabels from 'chartjs-plugin-datalabels';
const canvasRenderService = new CanvasRenderService(width, height, chartCallback);
const chartCallback = (ChartJS) => {
ChartJS.register(require('chartjs-plugin-datalabels'))
};
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;
Would someone help me please?
It works (only) on my machine :(
Edit: It works when I make the deploy by Linux Subsystem.
I hope this will help somebody.
Azure function will not include the Node_modules while deploying into azure. Because Node_modules directory contains very large file. You can include your package.json in you function directory and run npm install as you normally would with Node.js projects using Kudu (https://<function_app_name>.scm.azurewebsites.net )or the Console in the Azure portal.
Check Dependency management for more information.
Refer here Link 1 & Link 2
Any updates on this topic?
Doesn't seem like a valid option for me to manually run npm install via KUDU or some other terminal in a Cloud Function App - especially with Continoues Deployment etc.
Got the same problem while using canvas for barcode generation...
I'm using Nuxt & Axios but having trouble using environment variables when building the application from my local machine.
I have installed the #nuxtjs/dotenv module in an attempt to fix this issue but still having problems.
Note: The environment variables work fine when building the app within my hosting providers environment. It is only building from my local machine that gives me trouble. My IDE is VS Code.
Here is my axios setup inside nuxt.config.js:
module.exports = {
...
buildModules: [
'#nuxtjs/dotenv'
],
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios'
],
axios: {
baseURL: process.env.BASE_URL
},
...
}
My .env file has the following:
BASE_URL="https://some.api.com"
The .env variables are not being recognized when building the app:
nuxt build
Instead, it just sets the axios base url to the same host:port that the server runs on by default. Ex: localhost:4000
I found the following documentation from #nuxtjs/dotenv module: https://github.com/nuxt-community/dotenv-module#using-env-file-in-nuxtconfigjs. This instructs you to add the following to the top of nuxt.config.js:
require('dotenv').config()
This works for building locally; my variables from .env are recognized! However, because dotenv is a dev dependency, this causes the build to crash when deployed to my hosting provider because the module isn't recognized.
I know that I can define the environment variables directly in the build command as follows but I would prefer NOT to do so:
NUXT_ENV_BASE_URL=some.api.com nuxt build
Is there an easy way to get environment variables to work locally inside of nuxt.config.js during the build process that also works well when deploying to production??
Thank you!
Updated 2020-09-26
As of 2.13.0 I have removed #nuxtjs/dotenv. My nuxt.config.js now simply reads as below with the dotenv imports removed. I made no other code changes and the rest functions exactly the same for me.
env: {
DB_HOST: process.env.DB_HOST
},
My .env contains the following.
DB_HOST=http://localhost:5001/
Original answer
I installed the following as a dev dependency; #nuxtjs/dotenv. Then I added the following to my nuxt.config.js. I found this import statement in an article and tried it. Thankfully it worked for me.
import dotenv from "dotenv";
dotenv.config();
env: {
DB_HOST: process.env.DB_HOST
},
I created a file called .env with the following content
DB_HOST=http://localhost:5001/
In nuxt version v2.13.0, support for Runtime Config was added. This adds proper support to read environment variables at runtime. Previously they could be read but were compiled into the application.
The standard documentation is pretty good: https://nuxtjs.org/guide/runtime-config/ .
There is also a great blog post on how to migrate. You remove the use of #nuxtjs/dotenv.
https://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/
For example, in your nuxt.config.js, you define.
// Public env variables that are exposed on the frontend.
publicRuntimeConfig: {
someAccessKeyId: process.env.SOME_ACCESS_KEY_ID,
},
// Private env variables that are not be exposed on the frontend.
privateRuntimeConfig: {},
Then in your vue code, you access it via.
const { someAccessKeyId } = this.$config
I try to import a node module inside an Angular 8 web worker, but get an compile error 'Cannot find module'. Anyone know how to solve this?
I created a new worker inside my electron project with ng generate web-worker app, like described in the above mentioned ng documentation.
All works fine until i add some import like path or fs-extra e.g.:
/// <reference lib="webworker" />
import * as path from 'path';
addEventListener('message', ({ data }) => {
console.log(path.resolve('/'))
const response = `worker response to ${data}`;
postMessage(response);
});
This import works fine in any other ts component but inside the web worker i get a compile error with this message e.g.
Error: app/app.worker.ts:3:23 - error TS2307: Cannot find module 'path'.
How can i fix this? Maybe i need some additional parameter in the generated tsconfig.worker.json?
To reproduce the error, run:
$ git clone https://github.com/hoefling/stackoverflow-57774039
$ cd stackoverflow-57774039
$ yarn build
Or check out the project's build log on Travis.
Note:
1) I only found this as a similar problem, but the answer handles only custom modules.
2) I tested the same import with a minimal electron seed which uses web workers and it worked, but this example uses plain java script without angular.
1. TypeScript error
As you've noticed the first error is a TypeScript error. Looking at the tsconfig.worker.json I've found that it sets types to an empty array:
{
"compilerOptions": {
"types": [],
// ...
}
// ...
}
Specifying types turns off the automatic inclusion of #types packages. Which is a problem in this case because path has its type definitions in #types/node.
So let's fix that by explicitly adding node to the types array:
{
"compilerOptions": {
"types": [
"node"
],
// ...
}
// ...
}
This fixes the TypeScript error, however trying to build again we're greeted with a very similar error. This time from Webpack directly.
2. Webpack error
ERROR in ./src/app/app.worker.ts (./node_modules/worker-plugin/dist/loader.js!./src/app/app.worker.ts)
Module build failed (from ./node_modules/worker-plugin/dist/loader.js):
ModuleNotFoundError: Module not found: Error: Can't resolve 'path' in './src/app'
To figure this one out we need to dig quite a lot deeper...
Why it works everywhere else
First it's important to understand why importing path works in all the other modules. Webpack has the concept of targets (web, node, etc). Webpack uses this target to decide which default options and plugins to use.
Ordinarily the target of a Angular application using #angular-devkit/build-angular:browser would be web. However in your case, the postinstall:electron script actually patches node_modules to change that:
postinstall.js (parts omitted for brevity)
const f_angular = 'node_modules/#angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js';
fs.readFile(f_angular, 'utf8', function (err, data) {
var result = data.replace(/target: "electron-renderer",/g, '');
var result = result.replace(/target: "web",/g, '');
var result = result.replace(/return \{/g, 'return {target: "electron-renderer",');
fs.writeFile(f_angular, result, 'utf8');
});
The target electron-renderer is treated by Webpack similarily to node. Especially interesting for us: It adds the NodeTargetPlugin by default.
What does that plugin do, you wonder? It adds all known built in Node.js modules as externals. When building the application, Webpack will not attempt to bundle externals. Instead they are resolved using require at runtime. This is what makes importing path work, even though it's not installed as a module known to Webpack.
Why it doesn't work for the worker
The worker is compiled separately using the WorkerPlugin. In their documentation they state:
By default, WorkerPlugin doesn't run any of your configured Webpack plugins when bundling worker code - this avoids running things like html-webpack-plugin twice. For cases where it's necessary to apply a plugin to Worker code, use the plugins option.
Looking at the usage of WorkerPlugin deep within #angular-devkit we see the following:
#angular-devkit/src/angular-cli-files/models/webpack-configs/worker.js (simplified)
new WorkerPlugin({
globalObject: false,
plugins: [
getTypescriptWorkerPlugin(wco, workerTsConfigPath)
],
})
As we can see it uses the plugins option, but only for a single plugin which is responsible for the TypeScript compilation. This way the default plugins, configured by Webpack, including NodeTargetPlugin get lost and are not used for the worker.
Solution
To fix this we have to modify the Webpack config. And to do that we'll use #angular-builders/custom-webpack. Go ahead and install that package.
Next, open angular.json and update projects > angular-electron > architect > build:
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
}
// existing options
}
}
Repeat the same for serve.
Now, create extra-webpack.config.js in the same directory as angular.json:
const WorkerPlugin = require('worker-plugin');
const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin');
module.exports = (config, options) => {
let workerPlugin = config.plugins.find(p => p instanceof WorkerPlugin);
if (workerPlugin) {
workerPlugin.options.plugins.push(new NodeTargetPlugin());
}
return config;
};
The file exports a function which will be called by #angular-builders/custom-webpack with the existing Webpack config object. We can then search all plugins for an instance of the WorkerPlugin and patch its options adding the NodeTargetPlugin.
I'm attempting to set up unit testing on an Angular/Browserify project using Karma, Karma-Jasmine, and Karma-Browserify. I'm on a Windows machine, for reference. karma-cli is on my global npm path, and karma, karma-jasmine, karma-browserify, and browserify are all local npm installs, using -D.
I'm trying to pull in a single spec file, which looks like:
var PhoneListCtrl = require('../../../public/js/app/controllers/phone-list');
describe('PhoneListCtrl', function() {
var scope,
ctrl;
beforeEach(function() {
scope = {};
ctrl = new PhoneListCtrl(scope);
});
it('should create "phones" model with 3 phones', function() {
expect(scope).not.toBe(undefined);
});
});
And I get the following error every time:
Uncaught Error: Cannot find module 'Cc/gGH'
I get this exact same error after cloning the following repos, installing karma and all plugins, and attempting to run their example test suites:
https://github.com/xdissent/karma-browserify
https://github.com/waye929/angular-browserify
What on earth am I doing wrong? The test spec module is found correctly, and karma seems to be finding all necessary plugins/preprocessors, but it appears that karma-browserify is tripping on the require statement in a spec every time, for reasons I cannot fathom.
I've uninstalled and reinstalled karma and all related plugins numerous times now, to no avail.
I managed to find a solution. The issue was caused by karma-browserify's own module name hashing function, which is incompatible with newer versions of browserify. There's a fork that deals with it by using browserify's hashing function:
https://github.com/voidlock/karma-browserify/commit/3afe3b7485f2e4723bba5ad1c5a730d560b8c234
There's a pull request pending but in the meantime you can use the fork by placing
"karma-browserify": "https://github.com/voidlock/karma-browserify/tarball/use-browserify-hash-function"
in your package.json (dev)dependencies section.