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"
Related
I am doing a mern project but at begin I got an error .
const express=require("express");
const mongoose= require("mongoose");
const app=express();
const dotenv=require("dotenv")
dotenv.config()
//connect router
const route=require("./routes/User");
const authRoute=require("./routes/Auth");
mongoose
.connect(
process.env.local
)
.then(()=>console.log("MongoDB connected")).catch((err)=>{
console.log(err)
});
//accept json
app.use(express.json())
app.use("/authData",authRoute)
app.listen(process.env.PORT || 5000,()=>{
console.log("Backend server is running ")
});
the error is
internal/modules/cjs/loader.js:888
throw err;
^
Error: Cannot find module './routes/Auth'
Require stack:
C:\Users\me\Desktop\E-commerce_Web\backendnode\index.js
I have read MANY docs/blogs/SO articles on using the Firebase Emulator Suite trying a simple pubsub setup, but can't seem to get the Emulator to receive messages.
I have 2 functions in my functions/index.js:
const functions = require('firebase-functions');
const PROJECT_ID = 'my-example-pubsub-project';
const TOPIC_NAME = 'MY_TEST_TOPIC';
// receive messages to topic
export default functions.pubsub
.topic(TOPIC_NAME)
.onPublish((message, context) => {
console.log(`got new message!!! ${JSON.stringify(message, null, 2)}`);
return true;
});
// publish message to topic
export default functions.https.onRequest(async (req, res) => {
const { v1 } = require('#google-cloud/pubsub');
const publisherClient = new v1.PublisherClient({
projectId: process.env.GCLOUD_PROJECT,
});
const formattedTopic = publisherClient.projectTopicPath(PROJECT_ID, TOPIC_NAME);
const data = JSON.stringify({ hello: 'world!' });
// Publishes the message as JSON object
const dataBuffer = Buffer.from(data);
const messagesElement = {
data: dataBuffer,
};
const messages = [messagesElement];
// Build the request
const request = {
topic: formattedTopic,
messages: messages,
};
return publisherClient
.publish(request)
.then(([responses]) => {
console.log(`published(${responses.messageIds}) `);
res.send(200);
})
.catch((ex) => {
console.error(`ERROR: ${ex.message}`);
res.send(555);
throw ex; // be sure to fail the function
});
});
When I run firebase emulators:start --only functions,firestore,pubsub and then run the HTTP method with wget -Sv -Ooutput.txt --method=GET http://localhost:5001/my-example-pubsub-project/us-central1/httpTestPublish, the HTTP function runs and I see its console output, but I can't seem to ever get the .onPublish() to run.
I notice that if I mess around with the values for v1.PublisherClient({projectId: PROJECT_ID}), then I will get a message showing up in the GCP cloud instance of the Subscription...but that's exactly what I don't want happening :)
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)
});
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).
For the following truffle-config.js file, which has 2 networks listed in module.exports (development and ropsten), if I use the command truffle migrate in the terminal without explicitly saying --network development or --network ropsten, which network will the contract deploy to? Both?
require('dotenv').config();
const Web3 = require("web3");
const web3 = new Web3();
const WalletProvider = require("truffle-wallet-provider");
const Wallet = require('ethereumjs-wallet');
const ropstenPrivateKey = new Buffer(process.env.ROPSTEN_PRIVATE_KEY, "hex")
const ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey);
const ropstenProvider = new WalletProvider(ropstenWallet, `https://ropsten.infura.io/${process.env.INFURA_ROPSTEN_ID}`);
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
ropsten: {
provider: ropstenProvider,
gas: 4600000,
gasPrice: web3.utils.toWei('55', 'gwei'),
network_id: "3"
}
}
};
If --network is unspecified, it deploys to only development. You can confirm this by just running a migrate:
$ truffle migrate
Compiling .\contracts\SimpleContract.sol...
Writing artifacts to .\build\contracts
Using network 'development'.
Network up to date.