const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
const { interface, bytecode } = require('../compile');
let accounts;
let inbox;
beforeEach(async () => {
// Get a list of all accounts
accounts = await web3.eth.getAccounts();
// Use one of those accounts to deploy
// the contract
inbox = await new web3.eth.Contract(JSON.parse(interface))
.deploy({
data: bytecode,
arguments: ['Hi there!']
})
.send({ from: accounts[0], gas: '1000000' });
});
describe('Inbox', () => {
it('deploys a contract', () => {
assert.ok(inbox.options.address);
});
it('has a default message', async () => {
const message = await inbox.methods.message().call();
assert.equal(message, 'Hi there!');
});
it('can change the message', async () => {
await inbox.methods.setMessage('bye').send({ from: accounts[0] });
const message = await inbox.methods.message().call();
assert.equal(message, 'bye');
});
});
after running the above code i keep getting the following error
inbox#1.0.0 test C:\Users\user\Documents\inbox
mocha
Inbox
1) "before each" hook for "deploys a contract"
0 passing (98ms)
1 failing
1) "before each" hook for "deploys a contract":
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at Context.beforeEach (test\inbox.test.js:16:44)
at
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! inbox#1.0.0 test: mocha
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the inbox#1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\user\AppData\Roaming\npm-cache_logs\2018-07-03T13_17_54_895Z-debug.log
C:\Users\user\Documents\inbox\test>
When I changed my encoding from 'UTF-8' to 'utf8' in my compile.js file it worked.
My compile.js file looks like this
const path = require('path'); //for crossplatform
const fs = require('fs'); //file system
const solc = require('solc');
const inboxPath = path.resolve(__dirname, 'contracts', 'Inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8'); //change to utf8 to UTF-8
module.exports = solc.compile(source, 1).contracts[':Inbox'];
Hi guys I am also face this issue before.
There is nothing need to change in complie.js file.
Just we need to dot the change in declaration part
like in your case :
instead of writing this
const {interface, bytecode} = require("../compile")
we can write like
const {interface} = require("../compile")
const {bytecode} = require("../compile")
In this case we get the both interface and bytecode value which is exported form compile.js file.
uninstall your current version of solidity compiler and install solidity#0.4.17 (npm install --save solc#0.4.17) and make sure in your source code you have mentioned the correct version (pragma solidity ^0.4.17).
Related
I'm attempting to upgrade to Gulp 4 in an existing project. I have created a task called vendor with the intent of concatenating and minifying global javascript packages. Unfortunately I'm receiving an error when compiling with the following code:
function vendor() {
const source = [
'./node_modules/#popperjs/core/dist/umd/popper.js',
'./node_modules/bootstrap/dist/js/bootstrap.js',
'./node_modules/slick-carousel/slick/slick.js'
];
return src(source)
.pipe(changed(source))
.pipe(concat('vendor.js'))
.pipe(uglify())
.pipe(rename({
extname: '.min.js'
}))
.pipe(dest('./dist/js/'))
}
exports.build = series(parallel(vendor, js));
The error that I'm receiving is TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object.
This on my side functional (with path that I had on my project). Can you try this task and see if it works well ?
const {src, dest, task} = require("gulp");
const stripDebug = require('gulp-strip-debug');
const logger = require('node-color-log');
const uglify = require('gulp-uglify');
const source = [
'./node_modules/#popperjs/core/dist/umd/popper.js',
'./node_modules/bootstrap/dist/js/bootstrap.js',
'./node_modules/slick-carousel/slick/slick.js'
];
const jsDest = "./dist/js/";
function compressJs(callback) {
logger.color('yellow').log(`Removing console.log() and uglifying js from ${source} to: ${jsDest}`);
src(source)
.pipe(stripDebug())
.pipe(uglify())
.pipe(dest(`${jsDest}`))
.on('end', function () {
callback();
});
}
const Js = task('compress:js', compressJs);
exports.Js = Js;
My code keeps returning SyntaxError: Unexpected token u in JSON at position 0.
It deploys from accounts[0] but it does not return a "deployed to" address.
I've tried stringify as well.
I'm new to JS and I'm taking first steps in building my own project.
I had the same problem at my compile.js file but solved it with JSON.parse(solc.compile(JSON.stringify(input). It doesn't seem to work here.
Can someone help?
Here's my deploy.js:
const HDWalletProvider = require("#truffle/hdwallet-provider");
const Web3 = require("web3");
const { interface, bytecode } = require("./compile");
const compiledPurchase = require("./build/Purchase.json");
const provider = new HDWalletProvider(
"12 words",
"testnet"
);
const web3 = new Web3(provider);
const deploy = async() => {
const accounts = await web3.eth.getAccounts();
console.log("Attempting to deploy from account", accounts[0]);
// #####Deploy script#####
const result = await new web3.eth.Contract(
JSON.parse(compiledPurchase.interface)
)
.deploy({ data: compiledPurchase.bytecode })
.send({ gas: "1000000", from: accounts[0] });
console.log("Contract deployed to", result.options.address);
};
deploy();
Confirm that the path you are giving is correct and complete in this line:
const compiledPurchase = require("./build/Purchase.json");
Path to the folder could be different. That depends on your Project directory structure. But when you compile with truffle, it generates a json file in build/contracts folder.
Then change your deployment script like this:
const contract = new web3.eth.Contract(compiledPurchase.abi)
contract.deploy({ data: compiledPurchase.bytecode })
.send({ gas: "1000000", from: accounts[0] })
.then(function(result){
console.log("Contract deployed to", result.options.address)
});
I am trying to learn how to deploy a code on Ropsten network which worked fine on ganache but it keeps throwing an error and I am not able to figure it out. Below is the code
const fs = require('fs');
const HDWalletProvider = require("#truffle/hdwallet-provider");
const gitignore = JSON.parse (
fs.readFileSync('.gitignore').toString().trim()
);
module.exports = {
networks: {
ropsten: {
provider: () =>
new HDWalletProvider(
gitignore.seed,
'https://ropsten.infura.io/v3/${gitignore.projectID}'
),
network_id: 3
}
}
};
below are the dependency version
Truffle v5.3.9 (core: 5.3.9)
Node v14.17.0
#truffle/hdwallet-provider: "^1.4.1"
For better or worse, I'm following a tutorial from late 2018 to help me understand how to deploy a smart contract on Kovan testnet. I'm aware versioning might be an issue, so before I show the deploy.js here is my package.json:
"dependencies": {
"ganache-cli": "^6.10.2",
"mocha": "^4.1.0",
"solc": "^0.4.25",
"truffle-hdwallet-provider": "0.0.3",
"web3": "^1.0.0-beta.26"
},
My .env:
WALLET_SEED="some 12 word seed phrase"
INFURA_ENDPOINT="https://kovan.infura.io/v3/PROJECT_ID"
The deploy.js:
const dotenv = require("dotenv").config();
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface, bytecode } = require('./compile');
const provider = new HDWalletProvider(
process.env.WALLET_SEED,
process.env.INFURA_ENDPOINT
);
const web3 = new Web3(provider);
const deploy = async () => {
const accounts = await web3.eth.getAccounts();
console.log('Attempting to deploy from account', accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['Hi there!']})
.send({ gas: '1000000', from: accounts[0] });
console.log('Contract deployed to: ', result.options.address);
}
deploy();
The compile works correctly, but when I deploy I get the following error:
UnhandledPromiseRejectionWarning: Error: Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 10000000000000000 and got: 0.
at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/web3.js:15:44
at XMLHttpRequest.request.onreadystatechange (/Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/truffle-hdwallet-provider/node_modules/web3/lib/web3/httpprovider.js:118:13)
I definitely have 1 ETH in my Kovan wallet. The interesting thing is this: When I query my wallet in the following code I get the following output:
const balance = await web3.eth.getBalance('0x...............actualaccount');
console.log(balance)
// => 1000000000000 etc.
But when i query the accounts variable generated by the Web3 provider from my mnemonic phrase I get a completely different account:
const provider = new HDWalletProvider(
process.env.WALLET_SEED,
process.env.INFURA_ENDPOINT
);
const web3 = new Web3(provider);
const accounts = await web3.eth.getAccounts();
console.log(accounts)
// [ '0x..............XYZ']
When I check the funds in the account that web3 constructs for me, I confirm that the balance is indeed 0:
const balance = await web3.eth.getBalance('0x...............XYZ');
console.log(balance)
// => 0
But when I hard-code my actual wallet address into the deploy script as such, it tells me the account does not exist!
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['Hi there!']})
.send({ gas: '1000000', from: '0x.................actualaccount' });
(node:93528) UnhandledPromiseRejectionWarning: Error: Unknown address - unable to sign transaction for this address: "0x.....................actualaddress"
at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/hooked-wallet.js:185:35
at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/hooked-wallet.js:207:5
In your truffle-config.js where you define the networks to use add 'from: '0x...', ensuring that the contract deploys from the account that you know has the balance.
I decided to use vinyl-ftp for my deployment process in gulp. One thing I would like to do is to have a separate file with my ftp credentials:
host
user
password
and put that file in my .gitignore. And then I want those credentials in that file be read by my connection variable in my gulp file. My deploy code is the following:
gulp.task( 'deploy', function () {
var conn = ftp.create( {
host: 'yourdomain.com',
user: 'ftpusername',
password: 'ftpuserpassword',
parallel: 10,
log: gutil.log
} );
var globs = [
'dist/**'
];
return gulp.src( globs, { base: './dist/', buffer: false } )
.pipe( conn.newer( 'yourdomain.com' ) )
.pipe( conn.dest( 'yourdomain.com' ) );
} );//end deploy
So I want the values of the variables yourdomain.com for the host, ftpusername for user and ftpuserpassword for password be read in from a separate file so my credentials show up when I do git push. How do I accomplish this?
Thanks
You can pass them as run args:
var
gulp = require('gulp'),
args = require('yargs').argv;
const distDir = "./dist";
gulp.task('deploy', function() {
var conn = ftp.create({
host: args.host,
user: args.user,
password: args.password,
parallel: 10,
log: flog // .log
});
var globs = [
distDir + '/**',
distDir + '/.htaccess',
];
return gulp.src(globs, {buffer: false})
.pipe(conn.dest(args.remotedir));
});
Then call it from command line or put the line in a batch file: npm run gulp deploy -- --host=hostname --user=username --password=password --remotedir=/path/to/folder/on/server. Use gulp instead of npm run gulp if gulp is installed global.
This is a good practice to pass credentials trough args at a program start.