Testing contracts using time from OpenZepplin library: Error: Invalid JSON RPC response: "" - ethereum

I increase time the same way as described in OpenZepplin samples in the test below:
it("should revert claim drawing with 'Android: bad state'", async () => {
const [owner, signer1] = await ethers.getSigners();
let duration = time.duration.seconds(3);
await time.increase(duration);
await truffleAssert.reverts(
android.claimPainting(1),
'Android: bad state'
);
});
And it fails with Error: Invalid JSON RPC response: "". How can i fix it?
time is imported as const { time } = require("#openzeppelin/test-helpers"); + "#openzeppelin/test-helpers": "0.5.15" in package.json.
I also use ethers from hardhat, don't know if this could cause the problem.

You will need to execute Hardhat local node server and try again.
"npx hardhat node"
Hope this works on your side.

Install web3 and the hardhat-web3 plugin.
npm install --save-dev #nomiclabs/hardhat-web3 web3
Then add the following line to your hardhat config
import "#nomiclabs/hardhat-web3";

Related

I want to run hardhat tests for local network not on testnet, how to configure it?

So the problem is I have defined a hardhat config like this
import { HardhatUserConfig, task } from "hardhat/config";
import "#nomicfoundation/hardhat-toolbox";
import * as dotenv from "dotenv";
dotenv.config();
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
})
const config: HardhatUserConfig = {
solidity: "0.8.17",
networks: {
// defined defaultNetwork as hardhat so it would use it for testing.
defaultNetwork: {
url: 'hardhat',
},
hardhat: {},
goerli: {
url: process.env.STAGING_QUICKNODE_KEY,
accounts: [process.env.PRIVATE_KEY!]
}
}
};
export default config;
when I run this command on my local machine npx hardhat test it works fine because I guess maybe I have a .env file, but if I remove this .env file or run this command on GitHub workflow it would give me this error.
Error HH8: There are one or more errors in your config file:
* Invalid value undefined for HardhatConfig.networks.goerli.url - Expected a value of type string.
* Invalid account: #0 for the network: goerli - Expected string, received undefined
now the problem is I don't want to upload my .env file on GitHub because it contains my secret key information. I have seen this answer as well and tried it also How do I use different config for testing vs. deployment hardhat solidity?
so I tried to run this command npx hardhat test --network hardhat but it would the same error as above.
I want to know if there is any way to change this config object at runtime in *.spec.ts files, then I can try that way or if you know of any other hacks, please let me know.
The errors mentioned in your question are related to the fact that the config values are invalid. Hardhat expects the accounts items to be of type string (and in the format of "0x followed by 64 hex characters") but they are undefined.
I'm not sure about the proper solution (anyone else feel free to provide a better answer), but you can use a dummy key as a workaround.
goerli: {
url: process.env.STAGING_QUICKNODE_KEY || "https://dummy.url.com",
accounts: [process.env.PRIVATE_KEY || "0x1234567890123456789012345678901234567890123456789012345678901234"]
}
This validation happens before running the tests. So even if you use the hardhat network for tests, it won't allow you to run them if another part of the config is invalid.
npx hardhat test and npx hardhat test --network hardhat is effectively the same command, as hardhat is the default network.

How to run Amazon polly on Firebase Functions?

I got working code on local NodeJs server, then I tried to run same code on Firebase Function and failed.
Here is my code split into 2 files:
// index.js
const functions = require("firebase-functions");
const polly = require("./polly");
exports.pollySynth = functions.https.onCall((req, res) => {
return polly.speak()
});
// polly.js
const AWS = require("aws-sdk");
// Create an Polly client
const Polly = new AWS.Polly({
signatureVersion: "v4",
region: "my-region",
accessKeyId: "keyId,
secretAccessKey: "access key",
});
// Params
const params = {
Text: "Hello world. This is the word of speech!",
OutputFormat: "json",
};
// prettier-ignore
const synthSpeech = function() {
Polly.synthesizeSpeech(params, function(err, res) {
if (err) {
console.log("err", err);
return err;
} else if (res && res.AudioStream instanceof Buffer) {
return res.AudioStream;
}
});
};
module.exports = {speak: synthSpeech};
When trying to deploy this function, I'm getting this error:
Functions deploy had errors with the following functions: pollySynth(us-central1)
I'm not pro coder, so maybe it's just some dumb error in my code.. Please help me :)
That took around half day to solve this issue. The root of the problem was that for some reason, firebase didn't provide detailed error logs. It just said that there is some error in the code.
Only running this command through the command line helped me to understand what's wrong:
firebase functions:log --only pollySynth
I found that command only at StackOverflow, and official documentation didn't mention it.
Log looked this way:
Did you list all required modules in the package.json dependencies?
2021-08-20T12:04:51.823Z ? speechSynth:
Detailed stack trace: Error: Cannot find module 'aws-sdk'
Now I understand that problem is that npm modules was not installed. It worked locally with an emulator, but deploy was throwing an error 🤯
I tried to install aws sdk using commands like this again and again. Tried to add module into package.json manually as well, but nothing worked...
npm install aws-sdk
npm install --save
Then I looked into "node_modules" folder inside the "functions" folder and didn't find that package!
Then I looked at the folder structure installed by default:
- root
- functions
- node modules
- public
It seems like the terminal is running the command on the root folder, and "node_modules" is placed inside the "functions" folder.
So I opened the terminal, moved to the "functions" folder, and installed aws sdk.
cd functions
npm install aws-sdk
And successfully deployed the function!
The next problem was that the function return null. I needed to use a promise to wait for aws server response.
And that code worked for me:
const createSpeech = function() {
return Polly.synthesizeSpeech(params)
.promise()
.then((audio) => {
if (audio.AudioStream instanceof Buffer) {
return audio.AudioStream;
} else {
throw new Error("AudioStream is not a Buffer.");
}
});
};
Now everything works correctly, and I can move to the next steps.

blockchain tutorial Error: The send transactions "from" field must be defined

I am following a blockchain tutorial from dappuniversity.
When I create the task in the line
await App.todoList.createTask(content)
from line
https://github.com/dappuniversity/eth-todo-list/blob/e3ed9a2cefb581c09730250c56c9d30a19cc63c8/src/app.js#L115
I get the following error :
Uncaught (in promise) Error: The send transactions "from" field must be defined!
at Method.inputTransactionFormatter (truffle-contract.js:50747)
at truffle-contract.js:51228
at Array.map (<anonymous>)
at Method.formatInput (truffle-contract.js:51226)
at Method.toPayload (truffle-contract.js:51261)
at Eth.send [as sendTransaction] (truffle-contract.js:51551)
Do I need to define a 'from' field somewhere?
With the latest dependencies, none of the above answers were working for me.
I had to edit the loadAccount method:
loadAccount: async () => {
// Set the current blockchain account
const accounts = await web3.eth.getAccounts();
App.account = accounts[0];
},
then pass the App's account to the createTask method: await App.todoList.createTask(content, { from: App.account })
I was running into issues with the above answer which appears due to recent Metamask updates and that moving from web3.currentProvider to window.ethereum
I was able to make this work using
await App.todoList.createTask(content, {from: App.account})
I am using the latest truffle/contract. I needed to specify the from account in my createTask method like the following:
await App.todoList.createTask(content, { from: web3.eth.defaultAccount})
This worked.
Same happened to me on Remix while interacting with the contract deployed on Rinkeby. I chose injected web3 for the environment, But account field was empty.
It happended because I rejected the connection to metamask first and then did not get any other request to connect with metamask. So I refreshed remix, locked and unlocked metamask. It sent request to connect to metamask

#feathersjs/socketio-client connection timeout. Why?

I maked follow:
feathers g app # with socket and rest
feathers g service # todos & NeDB
npm start
and simple client for this. I copy code from documentation
https://docs.feathersjs.com/api/client/socketio.
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const io = require('socket.io-client');
const socket = io('http://localhost:3030');
const app = feathers();
app.configure(socketio(socket));
app.service('todos')
.on('created', message => console.log('New message created', message));
app.service('todos').find().then(r => {
console.log(r)
}).catch(e => console.log('error',e))
app.service('todos').create({
title: 'A message from a REST client'
});
this client code get me timeout errors for find() and create() methods
But if I make POST request by CURL, I have onCreated message in console
Why I got errors on create() and find() calls?
UPDATE:
I maked git repo for easy reproduce this problem
https://github.com/tolyanor/feathersjs-error
UPDATE2:
I change autogenerated file src/app.js like in feathers example chat application https://github.com/feathersjs/feathers-chat/blob/master/src/app.js
Now I CAN call service method create on client, but CAN NOT receive onCreated message. So, this code
app.service('/todos')
.on('created', message => console.log('New todos created', message));
never calling
You are using a Feathers v3 client with a Feathers v2 server. Old clients will be backwards compatible with new servers but not the other way around. Follow the migration guide to upgrade your server or generate a new application using #feathersjs/cli (feathers --version on the command line should show v3.5.0 or later).

express send incomplete response json data

The version info:
"express": "~4.15.2",
"express-session": "^1.15.5",
I use this code send large json data to client:
router.get('/exportAllData',function(req,res,next){
async function getData(){
let sql="SELECT * FROM int_information "
let rows=await query(sql);
let data=await JSON.stringify(rows);
return JSON.parse(data);
}
getData().then(data=>res.send({flag:1,data:data})).catch(error=>{
res.send({flag:0,err:error});
});
})
I tried wget localhost on server and can get full data,
But the remote client got broken json data and different each time refresh.
Where is the problem? Seems response closed before get all data.
This is an open bug in node js 8.x, I use 7.10 solved this problem.
Or you can set server.keepAliveTimeout=30000 in app.js to extend timeout setting