Node error when I deployed smart contract - ethereum

I get this error when I deployed smart contract to my private chain.
Error: Node error: {"code":-32000,"message":"unknown account"}
This is my web3.js code.
const bytecode = "0x608060405234801561001057600080fd5b506040516020806101018339810180604052602081101561003057600080fd5b8101908080519060200190929190505050806000819055505060aa806100576000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c8063c412eaba146037578063ca6158cb146053575b600080fd5b603d606f565b6040518082815260200191505060405180910390f35b60596078565b6040518082815260200191505060405180910390f35b60008054905090565b6000548156fea165627a7a7230582042b7071573f040950b28decc097069f3f208055692800cf2260019f40904af610029"
var itemContract = new this.props.web3.eth.Contract([{"constant":true,"inputs":[],"name":"getItem","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"itemId","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"id","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]);
itemContract.deploy({
data: bytecode,
arguments:[1]
})
.send({
from: decryptEtherAccount.address,
gas: 0,
gasPrice: '0',
}).on('error', (error) => {
console.log("Error: ", error);
}).on('transactionHash', (transactionHash) => {
console.log("TxHash: ", transactionHash);
}).on('receipt', (receipt) => {
console.log("Address: ", receipt.contractAddress)
}).then((newContractInstance) => {
console.log(newContractInstance);
}).catch(function(error) {
console.log(error);
});
Could you give me any advise why I am getting this error, please?

Before using an address to send a transaction, make sure you have added it to your web3 wallet.
Guide: https://web3js.readthedocs.io/en/v1.2.0/web3-eth-accounts.html#wallet-add

Related

window.ethereum.providers.find((provider) => provider.isMetamask) returns undefined

Metamask wallet will not connect if coinbase is installed.
This is a critical issue for anyone trying to execute transactions on their website. Asking users to remove their coinbase wallet is a major deterrent.
https://docs.metamask.io/guide/ethereum-provider.html#using-the-provider
This link on the metamask website demonstrates that they are aware of the issue but no documentation addresses it.
This issue can't be impossible to fix because sites like uniswap allow users to select which wallet. So I think it would be helpful if this was addressed in the documentation.
This is the original code for the connect function:
const connectMetamask = async (setAlert, setCurrentAccount) => {
const {ethereum} = window
const isInstalled = () => {
return Boolean(ethereum && ethereum.isMetaMask)
}
const isConnect = () => {
return Boolean(ethereum && ethereum.isConnected()) // <-- this is the issue
}
try {
if (!isInstalled()) {
console.log("No metamask!"); // <-- this works
setAlert(true);
return;
}
if (!isConnect()) {
console.log("Metamask not connected!");
setAlert(true)
return;
}
const chainId = await ethereum.request({ method: "eth_chainId" });
} catch (error) {
console.error(error);
}
};
This code works fine to connect metamask IF coinbase wallet is not installed.
https://docs.cloud.coinbase.com/wallet-sdk/docs/injected-provider-guidance
This link suggests what to do- but it doesn't work (for me at least).
if (window.ethereum.providers?.length) {
window.ethereum.providers.forEach(async (p) => {
if (p.isMetaMask) provider = p;
});
}
window.ethereum.providers returns an array, first element being the coinbase wallet which works fine, second being a proxy containing metamask. The properties of this proxy object are not accessible.
As per some answers I've written (which is the same as the code in the coinbase example):
const metamaskProvider = await window.ethereum.providers.find((provider) => provider.isMetaMask);
ethereum.setSelectedProvider(metamaskProvider)
Logging metamaskProvider returns undefined.
Logging window.ethereum.providers returns an array:
0: v {_events: {…}, _eventsCount: 0, _maxListeners: undefined, _filterPolyfill: e.FilterPolyfill, _subscriptionManager: e.SubscriptionManager, …}
1: Proxy {_events: {…}, _eventsCount: 0, _maxListeners: 100, _log: u, _state: {…}, …}
1 is the metamask provider.
It contains the following properties:
1: Proxy
[[Handler]]: Object
deleteProperty: ()=>!0
[[Prototype]]: Object
[[Target]]: l
chainId: "0x1"
enable: ƒ ()
isMetaMask: true
....
metamaskProvider returns undefined. How do I access the isMetaMask property, and set my selectedProvider to metamaskProvider ?
I think if you have multiple wallets are installed, you would not have window.ethereum.providers defined. I currently have only "metamask", I get this error: Uncaught TypeError: Cannot read properties of undefined (reading 'find')
if (typeof window.ethereum !== "undefined") {
let provider = window.ethereum;
// if multiple wallet are installed
if (window.ethereum.providers?.length) {
window.ethereum.providers.find(async (p) => {
if (p.isMetaMask) provider = p;
});
}
also you should not destructure
const metamaskProvider = await window.ethereum.providers.find((provider) => provider.isMetaMask);
My fix:
const connectMetamask = async (setAlert, setCurrentAccount) => {
let { ethereum } = window;
try {
if (!ethereum) {
console.log("No metamask!");
setAlert(true);
return;
}
try{
if (!ethereum.isConnected()) {
console.log("Metamask not connected!");
setAlert(true)
return;
}
} catch (error){
console.error(error)
try{
console.log('providers',window.ethereum.providers);
console.log('ethVar',ethereum)
ethereum = await window.ethereum.providers.find(
(provider) => provider.isMetaMask );
console.log('ethVarAfterFind', ethereum)
} catch (error){
console.error(error)
}
}
const chainId = await ethereum.request({ method: "eth_chainId" });
.....
} catch (error) {
console.log('error:')
console.error(error);
}
};
export default connectMetamask;
Basically just :
ethereum = await window.ethereum.providers.find( (provider) => provider.isMetaMask );
const chainId = await ethereum.request({ method: "eth_chainId" });
Honestly I'm pretty sure I tried this already and it wasn't working but, it is now ¯\_(ツ)_/¯

Getting an error when using methods.myMethod.call() with web3js

I am getting an error trying to call an existing smart contract function using call().
The error is "Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced." My code is below
let url = 'https://api.etherscan.io/api?module=contract&action=getabi&address=0x672C1f1C978b8FD1E9AE18e25D0E55176824989c&apikey=<api-key>';
request(url, (err, res, body) => {
if (err) {
console.log(err);
}
let data = JSON.parse(body);
let contract_abi = JSON.parse(data.result);
let contract_address = '0x672C1f1C978b8FD1E9AE18e25D0E55176824989c';
const contract = new web3.eth.Contract(contract_abi, contract_address);
contract.methods.totalSupply().call()
.then(result => {
console.log('result', result);
}).catch(err => {
console.log('error: ', err);
})
})
When I execute the same function using send() it works, however I need the return value of the function which is why I want to use call(). I am using ganache to set up a local test network which is working fine. Thanks!

Ionic gives error undefined is not an object (evaluating '_co.user.username') when decoding the login user token

This is part of the error message that I am getting:
[Error] ERROR – TypeError: undefined is not an object (evaluating '_co.user.username') TypeError: undefined is not an object (evaluating '_co.user.username')(anonymous function)checkAndUpdateView — core.js:44...
My login process works fine and data of the user is gotten fine, on ionic serve version of my app, but on ios I can see that error message, like json encoding doesn't work fine or something. Why is the JSON working fine on website, but not on the app? Here is content of TokenService :
constructor(private cookieService: CookieService) {}
setToken(token) {
this.cookieService.set("chat_token", token);
}
getToken() {
return this.cookieService.get("chat_token");
}
deleteToken() {
this.cookieService.delete("chat_token");
}
getPayload() {
const token = this.getToken();
let payload;
if (token) {
payload = token.split(".")[1];
payload = JSON.parse(window.atob(payload));
}
return payload.data;
}
and this is the loginUser function in LoginComponent , that is triggered on logging in:
loginUser() {
this.showSpinner = true;
this.authService.loginUser(this.loginForm.value).subscribe(
data => {
this.tokenService.setToken(data.token);
localStorage.setItem("currentUser", JSON.stringify(data));
this.loginForm.reset();
setTimeout(() => {
this.router.navigate(["/streams"]);
}, 200);
},
err => {
this.showSpinner = false;
if (err.error.message) {
this.errorMessage = err.error.message;
}
}
);
}
Now, the server side, I have this rout in routes/ directory, in node express in file authRoutes.js:
router.post('/login', AuthCtrl.LoginUser);
And then I have this in routes/ directory, in file userRoutes.js:
const express = require('express');
const router = express.Router();
const UserCtrl = require('../controllers/users');
const AuthHelper = require('../Helpers/AuthHelper');
router.get('/users', AuthHelper.VerifyToken, UserCtrl.GetAllUsers);
router.get('/user/:id', AuthHelper.VerifyToken, UserCtrl.GetUser);
router.get(
'/username/:username',
AuthHelper.VerifyToken,
UserCtrl.GetUserByName
);
router.post('/user/view-profile', AuthHelper.VerifyToken, UserCtrl.ProfileView);
router.post(
'/change-password',
AuthHelper.VerifyToken,
UserCtrl.ChangePassword
);
module.exports = router;
This is the part of controller auth.js on node server side:
async LoginUser(req, res) {
if (!req.body.username || !req.body.password) {
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "No empty fields allowed" });
}
await User.findOne({ username: Helpers.firstUpper(req.body.username) })
.then(user => {
if (!user) {
return res.status(HttpStatus.NOT_FOUND).json({ message: "Username not found" });
}
return bcrypt.compare(req.body.password, user.password).then(result => {
if (!result) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "Password is incorrect" });
}
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: "5h"
});
res.cookie("auth", token);
return res.status(HttpStatus.OK).json({ message: "Login successful", user, token });
});
})
.catch(err => {
console.log("Error is:");
console.log(err);
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "Error occured" });
});
}
I resolved the issue by transferring all the stored data from CookieService, which is the main culprit of the error, to a localStorage. Just instead of storing payload and that cookie in CookieService, just transferred it to localStorage, and I didn't have any more problems. Seems like, the simpler - the better.

UnhandledPromiseRejectionWarning, Express.js and Node.js

I am completely new to Node.js and Express.js and have been trying to work through some examples to integrate the Shippo API into my E-commerce web app but I'm getting some errors that I just can't solve despite reviewing my code several times.
I get the UnhandledPromiseRejectionWarning error, which, from I've read online, means that somewhere in my code there is something a .then() section which does not include a "catch" or a "what to-do" is the request returns an error. Any help would be greatly appreciated.
This is my code:
var express = require('express')
var app = express()
var http = require('http');
var Raven = require('raven');
var shippo = require('shippo')('ACCESS_TOKEN');
var engines = require('consolidate');
const bodyParser = require('body-parser');
const path = require('path');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.engine('html', engines.mustache);
app.set('view engine', 'html');
//app.use(express.static(path.join(_dirname,'/')));
app.get('/', function (req, res) {
res.render('Index.html');
})
app.post('/', function (req, res) {
var addressFrom = {
"object_purpose":"PURCHASE",
"name": "SENDER_NAME",
"company":"Shippo",
"street1":"215 Clayton St.",
"city":"San Francisco",
"state":"CA",
"zip":"94117",
"country":"US", //iso2 country code
"phone":"+1 555 341 9393",
"email":"SENDER_EMAIL",
};
// example address_to object dict
var addressTo = {
"object_purpose":"PURCHASE",
"name": req.body.fnames + ' ' + req.body.lnames,
"company": req.body.company,
"street1":req.body.street,
"city":req.body.city,
"state":req.body.state,
"zip":req.body.zipcode,
"country": req.body.country, //iso2 country code
"phone":"+1 555 341 9393",
"email":"support#goshippo.com",
};
// parcel object dict
var parcelOne = {
"length":"5",
"width":"5",
"height":"5",
"distance_unit":"in",
"weight":"2",
"mass_unit":"lb"
};
var shipment = {
"object_purpose": "PURCHASE",
"address_from": addressFrom,
"address_to": addressTo,
"parcels": [parcelOne],
"submission_type": "DROPOFF"
};
shippo.transaction.create({
"shipment": shipment,
"servicelevel_token": "ups_standard",
"carrier_account": 'CARRIER_TOKEN',
"label_file_type": "PDF"
})
.then(function(transaction) {
shippo.transaction.list({
"rate": transaction.rate
})
.then(function(mpsTransactions) {
mpsTransactions.results.forEach(function(mpsTransaction){
if(mpsTransaction.object_status == "SUCCESS") {
console.log("Label URL: %s", mpsTransaction.label_url);
console.log("Tracking Number: %s", mpsTransaction.tracking_number);
console.log("E-Mail: %s", mpsTransaction.object_owner);
console.log(mpsTransaction.object_status);
res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
} else {
// hanlde error transactions
console.log("Message: %s", mpsTransactions.messages);
}
});
})
}, function(err) {
// Deal with an error
console.log("There was an error creating transaction : %s", err.detail);
res.send("something happened :O")
});
})
app.post('/successp', function (req, res) {
var token = req.body.stripeToken; // Using Express
// Charge the user's card:
var charge = stripe.charges.create({
amount: 1000,
currency: "eur",
description: "Example charge",
source: token,
}, function(err, charge) {
// asynchronously called
});
res.send('Thanks!')
})
app.post('/successp', function (req, res) {
var token = req.body.stripeToken; // Using Express
// Charge the user's card:
var charge = stripe.charges.create({
amount: 1000,
currency: "eur",
description: "Example charge",
source: token,
}, function(err, charge) {
// asynchronously called
});
res.send('Thanks!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
And this is the Error I get:
Example app listening on port 3000!
(node:2378) UnhandledPromiseRejectionWarning
(node:2378) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2378) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm also not completely sure about the purpose for some of the lines (again, i'm very new to express and node.js). What is engine and mustache? also, I see that this sample code uses APP.POST('/succesp', function(req, res)...), what exactly is that '/succesp'? Another html file I need to create? Also, what is that "app.use(express.statc([ath.join(_dirnam,'/')));" at the beginning?
You need to be a little careful using the format then(FN, errorFn), because if there's an error inside the then, the errorFn won't catch it. It's better to use then(fn).catch(errorFn). This will allow all errors in any then above to filter down to the last catch for handling.
For example, the first call properly catches the error, the second doesn't:
function fn() {
return Promise.resolve("good")
}
fn()
.then(r => {
throw ("whoops")
})
.catch(err => console.log(err)) //<-- catch works here
fn()
.then(r => {
throw ("whoops")
},
err => console.log(err) // this can't catch the error above; it will only catch rejections on fn()
)
It doesn't show in the snippet but if you look at the console, you'll see an unhandled rejection error.
In your code, you can flatten out the promise chain by returning the promise from shippo.transaction.list. Then you can add a catch at the end to handle errors.
shippo.transaction.create({
"shipment": shipment,
"servicelevel_token": "ups_standard",
"carrier_account": 'CARRIER_TOKEN',
"label_file_type": "PDF"
})
.then(function(transaction) {
return shippo.transaction.list({ // return this promise
"rate": transaction.rate
})
.then(function(mpsTransactions) { // so this can flatten out
mpsTransactions.results.forEach(function(mpsTransaction){
if(mpsTransaction.object_status == "SUCCESS") {
console.log("Label URL: %s", mpsTransaction.label_url);
console.log("Tracking Number: %s", mpsTransaction.tracking_number);
console.log("E-Mail: %s", mpsTransaction.object_owner);
console.log(mpsTransaction.object_status);
res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
} else {
// hanlde error transactions
console.log("Message: %s", mpsTransactions.messages);
}
});
})
.catch(function(err) { // catch errors
// Deal with an error
console.log("There was an error creating transaction : %s", err.detail);
res.send("something happened :O")
});
})
Since this is hard to run locally without all the pieces, I'm not positive about the source of the error, but it looks like you are sending res.status(200).send() inside a loop, which might lead to an error if it gets called twice.
Without reading the full code, you shouldn't try to catch an error with a callback function when using Promises. You catch errors in Promises using a .catch block
And you should also return the first promise, so that it passes to the next .then function (if your intention is to return the shippo.transaction.list as mpsTransactions)
Something like this:
shippo.transaction.create({
"shipment": shipment,
"servicelevel_token": "ups_standard",
"carrier_account": 'CARRIER_TOKEN',
"label_file_type": "PDF"
})
.then(function(transaction) {
return shippo.transaction.list({
"rate": transaction.rate
})
})
.then(function(mpsTransactions) {
mpsTransactions.results.forEach(function(mpsTransaction){
if(mpsTransaction.object_status == "SUCCESS") {
console.log("Label URL: %s", mpsTransaction.label_url);
console.log("Tracking Number: %s", mpsTransaction.tracking_number);
console.log("E-Mail: %s", mpsTransaction.object_owner);
console.log(mpsTransaction.object_status);
res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
} else {
// hanlde error transactions
console.log("Message: %s", mpsTransactions.messages);
}
});
})
.catch(function (error) {
// Deal with an error
console.log("There was an error creating transaction : %s", err.detail);
res.send("something happened :O")
});

FeathersJS Error Handler Unexpected Token < Issue

I am working on an Express App with MongoDB and trying to utilize FeathersJS for all my services. Here I'm running a test try to get an error message from the server to the client, but I have an issue with the response from the error handler. My req headers have the correct application/json stuff, so I assumed the Error Handler should send valid json back.
I know I'm not using the next callback in my function, but when I try to do that it gives the same error, so I'm thinking it has to do with the Error Handler. Any direction here would be greatly appreciated!
The first error log is on the server, which is correct.
Bucket Services
error >>>>> Bucket validation failed
Possibly Unhandled Rejection: Bucket validation failed, Promise { <rejected> 'Bucket validation failed' }
>>>>>> Error: Unexpected token < in JSON at position 0
at convert (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/node_modules/feathers-errors/lib/index.js:365:79)
at toError (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/lib/client/base.js:24:37)
at process._tickCallback (internal/process/next_tick.js:103:7)
my create function within the BucketService class:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save((error) => {
console.log('error >>>>>', error.message);
if (error) { return Promise.reject(error.message); }
return Promise.resolve(new_bucket);
});
}
my router file:
const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const router = feathers();
const LoginService = require('../services/login_service');
const UserService = require('../services/user_service');
const BucketService = require('../services/bucket_service');
// Enable REST services
router.configure(rest());
router.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
router.use('/login', new LoginService());
router.use('/user', new UserService());
router.use('/bucket', new BucketService());
// Set up error handling
router.use(errorHandler());
module.exports = router;
I figured it out, the key was to correctly pass through a callback (next) function as the third parameter to handle errors. FeathersJS handles the Promise Rejections for you on errors. Then in my test I needed to convert the Feathers-Error to JSON before I could get the message.
I changed my test to:
it('can validate an incorrect bucket', (done) => {
const invalid_bucket = {
name: 'Invalid Bucket',
};
bucket_service.create(invalid_bucket, {}, (error) => {
error = error.toJSON();
assert(error.message.length > 0);
done();
});
});
and my create function to:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save()
.then(created_bucket => Promise.resolve(created_bucket))
.catch(next);
}