I am using Ganache and Ethereum Remix
Here is my solidity smart contract function:
function sendEth(string memory url) public payable{
require(msg.value >= minLimit, "Pay more than the minimum limit");
}
And I am calling it with react code, here is my react code:
return erc20Contract.methods
.sendEth(url)
.send({
from: walletAddress,
value: 120000000 // Hardcoded value for testing
}).then((res) => {
console.log("Success", res)
}).catch(err => console.log(err)) ;
I am getting this error when I try to sign using metamask:
Metamask Screenshot
Error
Getting same error on Remix too
Remix Error
What is the reason of this error?
Related
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!
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 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
I'm building an api with nodejs to interact with both the client(android) and the admin(web).
When the api is started, it works fine for the admin and the views are rendered properly but when I connect the client to the api, I get an error/warning in server console like:
App at port 4003
db connection opened successfully
Categroies Count: 2
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)
at ServerResponse.setHeader (_http_outgoing.js:501:3)
at ServerResponse.header
(E:\nodeCMSApp\node_modules\express\lib\response.js:767:10)
at ServerResponse.json
(E:\nodeCMSApp\node_modules\express\lib\response.js:264:10)
at Categories.find.select.exec.then.data
(E:\nodeCMSApp\routes\admin_categories.js:20:22)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:13880) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): Error: Can't set headers after they are
sent.
(node:13880) [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.
Here's my api code snippet:
router.get('/', (req, res) => {
Categories.find({})
.select('title slug image _id')
.exec()
.then(data => {
if (data) {
res.status(200)
.json({
success: true,
count: data.length,
categories: data
})
// I understand that the problem lies here
res.render('admin/all_categories', {
categories: data
});
} else {
res.render('all_categories', {
categories: null
});
}
})
.catch(error => {
console.error(error);
res.send('Error 404');
});
});
I understand that it's because I have already rendered a view with the response object and I'm calling it again to return some json for the client.
My question is how do I render the view and return json data for the client concurrently withoutany errors?
Thanks.
In your code, you are sending two responses to user if all goes well:
if (data) {
res.status(200).json({
success: true,
count: data.length,
categories: data
});
// I understand that the problem lies here
res.render('admin/all_categories', {
categories: data
});
}
In the moment you perform some call to res.json, res.send, res.redirect, res.render, etc, you are sending the proper headers to user (browser) so, in your case, after res.status(200).json you are trying to send res.render and is not possible because first res.json started sending the result to the user. I guess you want to render all_categories with "data" so you should render the template in backend (compile) before send it to the user.
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);
}