Invalid character when try to deploy or use a function from my contract using Web3Js - solidity

I keep trying to deploy to a contract or use a contract, but every time I deploy or use a function, I only get this error
error Error: Magic RPC Error: [-32603] Internal error: Invalid character
at sdk:11:8488
My contract is correct, I also deployed using a hardhat tool and everything was ok, but if I give them via web3.js I only have problems
const fromAddress = (await web3.eth.getAccounts())[0];
console.log(fromAddress);
console.log(contractAbi);
const contract = new web3.eth.Contract(JSON.parse(contractAbi));
console.log(contract);
// Deploy contract with "Hello World!" in the constructor and wait to finish
const contractInstance = await contract
.deploy({
data: contractByteCode
})
.send({
from: fromAddress,
gas: 200000
})
.on('error', (error) => {
console.log("error", error);
});
console.log(contractInstance);
The Abi and the byte code have no problems.. what could it be?
let contractAbi = '[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"string","name":"_promocode","type":"string"},{"internalType":"uint256","name":"_expirationDatetime","type":"uint256"}],"name":"addPromocode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_identifier","type":"string"}],"name":"addWallet","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"string","name":"_identifier","type":"string"}],"name":"addWalletOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"checkWallet","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"string","name":"_promocode","type":"string"}],"name":"getPromocode","outputs":[{"components":[{"internalType":"string","name":"promocode","type":"string"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"generationDatetime","type":"uint256"},{"internalType":"uint256","name":"expirationDatetime","type":"uint256"},{"internalType":"bool","name":"status","type":"bool"}],"internalType":"structEWalletContract.Promocode","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_userAddress","type":"address"}],"name":"getUserBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"getUserPromocodes","outputs":[{"components":[{"internalType":"string","name":"promocode","type":"string"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"generationDatetime","type":"uint256"},{"internalType":"uint256","name":"expirationDatetime","type":"uint256"},{"internalType":"bool","name":"status","type":"bool"}],"internalType":"structEWalletContract.Promocode[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"string","name":"_promocode","type":"string"}],"name":"sendPromocode","outputs":[{"components":[{"internalType":"string","name":"promocode","type":"string"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"generationDatetime","type":"uint256"},{"internalType":"uint256","name":"expirationDatetime","type":"uint256"},{"internalType":"bool","name":"status","type":"bool"}],"internalType":"structEWalletContract.Promocode","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"testContract","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"transaction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_promocode","type":"string"}],"name":"usePromocode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"userTransactions","outputs":[{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"}],"internalType":"structEWalletContract.Transaction[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"usersCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]';

Related

Can not deploy my contract when i use estimateGas()

I can not deploy my contract when I use estimateGas() actually estimateGas() and the gasUsed in error is the same. Why does this happen? How to fix this problem?
my code:
const deployedContract = await deployTx.send({
from: signer.address,
gas: await deployTx.estimateGas(),
}).once("transactionHash", (txhash) => {
console.log(`Mining deployment transaction ...`);
console.log(txhash);
});
error:
receipt: {
blockHash: '0x6330753afbeae8ac63fc4056d9f26ea8eec15cfcf6a4cfcf34f4fd2ada55620c',
blockNumber: 10781483,
contractAddress: '0x2801e146eB41339F060BbF2b2dd87cE970e5cAec',
cumulativeGasUsed: 5421372,
effectiveGasPrice: 4154546093,
from: '0xa458b7e161aa47c268053004fd0b25b7a2fa66f0',
gasUsed: 2442757,
logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
status: false,
to: null,
transactionHash: '0x9e5f0d788ce28e3f5d35ee80e911d3f23f984d3d7d98271e82582b6045534acc',
transactionIndex: 11,
type: '0x2',
events: {}
}
}
There is no error in your code.
The contract has been successfully deployed to the address 0x2801... shown in the contractAddress property of the transaction receipt.
estimateGas() just asks the node that you're connected to (in your case most likely a local emulator) to estimate how much gas is the transaction going to cost.

Can not call the function Aggregate - Multicall2.sol on BSC testnet

I already deployed the multicall2.sol smart contract on BSC Testnet
https://testnet.bscscan.com/address/0x8F3273Fb89B075b1645095ABaC6ed17B2d4Bc576#code
then call the contract by using the following typescript code:
try {
const multi = getMulticallContract(options.web3 || web3NoAccount)
const itf = new Interface(abi)
const calldata = calls.map((call) => [call.address.toLowerCase(), itf.encodeFunctionData(call.name, call.params)])
const { returnData } = await multi.methods.aggregate(calldata).call(undefined, options.blockNumber)
const res = returnData.map((call, i) => itf.decodeFunctionResult(calls[i].name, call))
return res
} catch (error) {
throw new Error(error)
}
}
I got the error
Uncaught (in promise) Error: Error: Returned error: execution reverted: Multicall aggregate: call failed
It's weird. Because the function works properly on Mainnet. Can anyone help me?
The author found his solution but just to complete the troubleshooting I suggest making sure you have:
Have the contract deployed on testnet
Switch your RPC Node Url to the correct network. For example: BSC testnet's is https://data-seed-prebsc-1-s2.binance.org:8545
in my case, i resolved the issue by simply switching the rpc from https://data-seed-prebsc-1-s3.binance.org:8545/ to https://data-seed-prebsc-1-s2.binance.org:8545/
looks like they have some substantial inconsistency between nodes

Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)

i have develop a simple smartContract. when i run truffle test it showed the following error:i am new in this so i cant figure it out.
PS F:\pracdap> truffle test
Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SimpleSmartContract.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Compilation warnings encountered:
Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "urce file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more informa
--> /F/pracdap/contracts/SimpleSmartContract.sol
> Artifacts written to C:\Users\HP\AppData\Local\Temp\test--1224-GWVOn3NGyps8
> Compiled successfully using:
- solc: 0.8.3+commit.8d00100c.Emscripten.clang
Contract: SimpleSmartContract
1) should be deployed
> No events were emitted
0 passing (128ms)
1 failing
1) Contract: SimpleSmartContract
should be deployed:
Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)
at Object.checkNetworkArtifactMatch (F:\node\node_modules\truffle\build\webpack:\packages\contract\lib\utils\index.js
at Function.deployed (F:\node\node_modules\truffle\build\webpack:\packages\contract\lib\contract\constructorMethods.j
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at Context.<anonymous> (test\simpleSmartContract.js:5:33)
Solidity code
pragma solidity >=0.4.22 <0.9.0;
contract SimpleSmartContract {
}
Node js. test code
const SimpleSmartContract = artifacts.require('SimpleSmartContract');
contract('SimpleSmartContract', () => {
it('should be deployed', async () => {
const simpleSmartContract = await SimpleSmartContract.deployed();
assert(simpleSmartContract.address !== '');
});
});
Looks like you have not added a Migration file for your SimpleSmartContract.
Create a file named 2_deploy_contracts.js in your Migrations directory. The add the following code in it :
const SimpleSmartContract = artifacts.require("SimpleSmartContract");
module.exports = function (deployer) {
deployer.deploy(SimpleSmartContract);
};
Then try running the test.
try using migration...if is shows any error let me know.
const SimpleSmartContract = artifacts.require("SimpleSmartContract");
module.exports = async function(deployer, _network, accounts) {
await deployer.deploy(SimpleSmartContract);
};
You should create a new 'migrations file' in the migration folder with a (possible) name of 2_deploy_contracts.js.
async function arguments:
deployer: deployment of the contract
_network: specified network (truffle-config.js)
accounts: to access the truffle accounts when deploying (I.E Solidity constructor arguments)
Ref: https://trufflesuite.com/docs/truffle/getting-started/running-migrations.html

getaddrinfo ENOTFOUND API Google Cloud

I'm trying to execute API.AI tutorial for building a weather bot for Google Assistant (the one here: https://dialogflow.com/docs/getting-started/basic-fulfillment-conversation)
I made everything successfully, created the bot within API, created the Fulfillments, installed NodeJS on my pc, connected Google Cloud Platform, etc.
Then I created the index.js file by copying it exactly how it's stated on API.ai tutorial with my API key from World Weather Organisation (see below).
But when I use the bot, it doesn't work. On the Google Cloud Platform the error is always the same:
Error: getaddrinfo ENOTFOUND api.worldweatheronline.com
api.worldweatheronline.com:80
at errnoException (dns.js:28)
at GetAddrInfoReqWrap.onlookup (dns.js:76)
No matter how often I do it I get the same error. So I don't actually reach the API. I tried to see if anything changed from WWO side (URL, etc.) but apparently no. I updated NodeJS and still same issue. I refreshed the Google Cloud platform completely and didn't help.
That one I really can't debug. Could anyone help?
Here's the code from API.ai:
'use strict';
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = '[YOUR_API_KEY]';
exports.weatherWebhook = (req, res) => {
// Get the city and date from the request
let city = req.body.result.parameters['geo-city']; // city is a required param
// Get the date for the weather forecast (if present)
let date = '';
if (req.body.result.parameters['date']) {
date = req.body.result.parameters['date'];
console.log('Date: ' + date);
}
// Call the weather API
callWeatherApi(city, date).then((output) => {
// Return the results of the weather API to Dialogflow
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
});
};
function callWeatherApi (city, date) {
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the weather
let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' +
'&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date;
console.log('API Request: ' + host + path);
// Make the HTTP request to get the weather
http.get({host: host, path: path}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
let response = JSON.parse(body);
let forecast = response['data']['weather'][0];
let location = response['data']['request'][0];
let conditions = response['data']['current_condition'][0];
let currentConditions = conditions['weatherDesc'][0]['value'];
// Create response
let output = `Current conditions in the ${location['type']}
${location['query']} are ${currentConditions} with a projected high of
${forecast['maxtempC']}°C or ${forecast['maxtempF']}°F and a low of
${forecast['mintempC']}°C or ${forecast['mintempF']}°F on
${forecast['date']}.`;
// Resolve the promise with the output text
console.log(output);
resolve(output);
});
res.on('error', (error) => {
reject(error);
});
});
});
}
Oh boy, in fact the reason was most stupid ever. I didn't enable "billing" on Google Cloud Platform and that's why it blocked everything (even though I'm using a free test of the API). They just wanted my credit card number. It works now
I had the same issue trying to hit my db. Billing wasn't the fix as I had billing enabled already.
For me it was knexfile.js setup for MySql - specifically the connection object. In that object, you should replace the host key with socketPath; and prepend /cloudsql/ to the value. Here's an example:
connection: {
// host: process.env.APP_DB_HOST, // The problem
socketPath: `/cloudsql/${process.env.APP_DB_HOST}`, // The fix
database: process.env.APP_DB_NAME,
user: process.env.APP_DB_USR,
password: process.env.APP_DB_PWD
}
Where process.env.APP_DB_HOST is your Instance connection name.
PS: I imagine that even if you're not using Knex, the host or server parameter of a typical DB connectionstring will have to be called socketPath when connecting to Google Cloud SQL.

Hello world contract method call returns Unhandled rejection Error

This is my package.json:
{
"dependencies": {
"solc": "^0.4.16",
"web3": "^1.0.0-beta.20"
}
}
This is my smart contract code:
contract HelloWorld {
function displayMessage() constant returns (string) {
return "Hello from a smart contract";
}
}
I've compiled this contract on the node repl with testprc running, and I'm trying to call the displayMessage method like so:
myContract.methods.displayMessage().call()
or
myContract.methods.displayMessage.call()
but I'm just getting this error:
> Unhandled rejection Error: ERROR: The returned value is not a convertible string:
at SolidityTypeString.formatOutputString [as _outputFormatter] (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/formatters.js:245:15)
at /Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/type.js:246:25
at SolidityTypeString.SolidityType.decode (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/type.js:247:11)
at /Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/index.js:327:49
at Array.forEach (<anonymous>)
at ABICoder.decodeParameters (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/index.js:326:13)
at Contract._decodeMethodReturn (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-contract/src/index.js:490:22)
at Method._parent._ethereumCall.call.method.outputFormatter (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-contract/src/index.js:820:42)
at Method.formatOutput (/Users/alberthu/Documents/solidity-intro/node_modules/web3-core-method/src/index.js:179:54)
at sendTxCallback (/Users/alberthu/Documents/solidity-intro/node_modules/web3-core-method/src/index.js:446:33)
at /Users/alberthu/Documents/solidity-intro/node_modules/web3-core-requestmanager/src/index.js:144:9
at XMLHttpRequest.request.onreadystatechange (/Users/alberthu/Documents/solidity-intro/node_modules/web3-providers-http/src/index.js:64:13)
at XMLHttpRequestEventTarget.dispatchEvent (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:110:20)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
I've tried reading through the web3 api docs but I'm new to this and haven't found anything useful. Anyone know how I can get "Hello from a smart contract" to show on the server?
Thanks!
I have the same problem. And insert correct contract address.
My contract (example from documentation web3js) I use web3.1.0.0-beta.23.
pragma solidity ^0.4.18;
contract MyContract {
function myFunction() returns(uint256 myNumber, string myString) {
return (23456, "Hello!%");
}
}
code
const contract = new web3.eth.Contract(abi, contractAddress);
contract.methods.myFunction().call()
.then(res => console.log(res))
.catch(e => console.log(e.message))
contract creating and send from test net good. But if I tried call methods - have the same error:
ERROR: The returned value is not a convertible string:
I am also learning how to code smart contracts and came across this error earlier today. I found what was causing it was that I had the wrong address tied to my smart contract.
Contract objects in web3 have an address property which represents the address used for that contract instance. In my case this address was incorrect and was causing me to have the same error. The contract address should have been returned to you after your deployment.
The correct contract address should have been returned to you in a callback function after you deployed it.
You can set and check your contract address as follows:
myContract.options.address // returns the current address you have set for this contract instance
myContract.options.address = "the correct contract address"
I would have left this as a comment but unfortunately I do not have enough reputation. Let me know if you need some more help or want to get together to learn.
Here is the web3js documentation on contract address property: https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#options-address