IPFS is not a constructor: Nodejs - IPFS/OrbitDB chatroom - javascript

I'm trying to build a Dapp with Nodejs and IPFS/OrbitDB every time, I try to start my App I get the error:
this.node = new IPFS({
^
TypeError: IPFS is not a constructor
This is my basic code without a specific Swarm:
const Ipfs = require('ipfs');
const OrbitDB = require('orbit-db');
class chatroom {
constructor(IPFS, OrbitDB) {
this.OrbitDB = OrbitDB;
this.node = new IPFS({
preload: {enable: false},
repo: "./ipfs",
EXPERIMENTAL: {pubsub: true},
config: {
Bootstrap: [],
Addresses: {Swarm: []}
}
});
this.node.on("error", (e) => {throw (e)});
this.node.on("ready", this._init.bind(this));
}
async _init(){
this.orbitdb = await this.OrbitDB.createInstance(this.node);
this.onready();
}
}
module.exports = exports = new chatroom(Ipfs, OrbitDB);
I'm running on the following version of IPFS: ipfs#0.42.0
I tried it also on an empty Nodejs App and there I had the same error also when I added a specific Swarm to connect to.
I would really appreciate your help, thx for your time in advance.
Kind regards
beni

I did it now like that:
const IPFS = require('ipfs');
async function createNode() {
let node = await IPFS.create(
{
repo: (() => `repo-${Math.random()}`)(),
"Addresses": {
"Swarm": [
"/ip4/0.0.0.0/tcp/4001"
],
"API": "/ip4/127.0.0.1/tcp/5001",
"Gateway": "/ip4/127.0.0.1/tcp/8080"
}
}
);
try {
await node.start();
console.log('Node started!');
} catch (error) {
console.error('Node failed to start!', error);
}
}
(thx #Eugene)

Related

How to connect any server using ssh in Cypress.io to run a command?

I know that this probably is not the best way to do this. I read the question with the same title here, but it not solve my problem.
The question is: I have a server that only will achieve a result that I wanna if I run a command line in the server. So I wanna write a test to check the state of one page before and after I run that command. How I do that?
I tried to use the simple-ssh package, but I keep getting this error while trying to read the ssh key file:
fs.readFileSync is not a function
Actually my code looks like this:
import * as fs from 'fs';
let sshConfig = Cypress.config('ssh')
sshConfig.key = fs.readFileSync('path/to/key/file')
let SSH = require('simple-ssh');
Cypress.Commands.add('teste', () => {
let ssh = new SSH(sshConfig)
ssh.exec('echo', {
args: ['$PATH'],
out: function(stdout) {
console.log(stdout);
}
}).start();
})
Other possibility's are welcome.
As Fody mentioned, there are node.js functions present inside simple-ssh so a task is needed.
This is the basic configuration.
It's a direct translation of what you have, but you would want to return something from the task. As it is, the console.log() goes to the terminal console not the browser console.
cypress.config.js
const { defineConfig } = require('cypress')
const fs = require('fs')
const SSH = require('simple-ssh');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
ssh() {
const sshConfig = config.ssh
sshConfig.key = fs.readFileSync('path/to/key/file')
const ssh = new SSH(sshConfig)
ssh.exec('echo', {
args: ['$PATH'],
out: function(stdout) {
console.log(stdout);
}
}).start();
return null
},
})
}
}
})
test
Cypress.Commands.add('ssh', () => {
cy.task('ssh')
})
cy.ssh()
Try it with cy.readFile().
const SSH = require('simple-ssh');
Cypress.Commands.add('testSSH', () => {
cy.readFile('path/to/key/file').then(key
const sshConfig = Cypress.config('ssh')
sshConfig.key = key
const ssh = new SSH(sshConfig)
ssh.exec('echo', {
args: ['$PATH'],
out: function(stdout) {
console.log(stdout);
}
}).start()
})
})
The problem is fs is a node.js library, and it cannot be used in the browser.
But you may find the same thing applies to simple-ssh, If so, you will have to shift the code into a task where you can use any node.js functions.

Not able register hapi-cron-job plugin

I am trying to schedule cronjobs which will run at specified time, i am using hapi-cron-job of hapi, when i try to register the plugin, i am getting below error.
[1] "plugin.register" must be of type function
at Object.exports.apply (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\config.js:19:15)
at internals.Server.register (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\server.js:454:31)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Please find the configuration while registering the plugin.
server.js
const { plugins } = require('./register/index');
await server
.register(plugins)
.then(() => {})
.catch(err => {
console.error('Plugin registeration failed!');
console.error(err);
});
index.js
module.exports.plugins = [
// I have here other pluguns, passing this array for registration in server.js
require("./hapi-cron-job-plugin")
];
hapi-cron-job-plugin.js
const hapiCronJob = require('hapi-cron-job')
const plugin = {
register: require('hapi-cron-job'),
options: {
jobs: [
{
name: "diplay time",
enabled: true,
immediate: true,
schedule: "every 1 s",
execute: alertSystemAdminAndDispatcher,
environments: ['development', 'staging']
}
],
}
}
module.exports = plugin;
nodeJS version: v14.17.3
Hapi-cron-job: "hapi-cron-job": "^2.0.1"

Got the error code "TypeError: Cannot read properties of null (reading 'sendTransaction')" while trying to deploy to the goerli test network

Here is my hardhat.config.js code
// hardhat.config.js
require("#nomiclabs/hardhat-ethers");
require("#nomiclabs/hardhat-waffle");
require("dotenv").config()
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
const GOERLI_URL = process.env.GOERLI_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
networks: {
goerli: {
url: process.env.GOERLI_URL || "https://eth-goerli.alchemyapi.io/v2/PT8BEXCUKwsfvcBz8y3g7A2V7LdhUKQA",
accounts: process.env.PRIVATE_KEY
}
}
};
And my deploy.js script:
// scripts/deploy.js
const hre = require("hardhat");
async function main() {
// We get the contract to deploy.
const BuyMeACoffee = await hre.ethers.getContractFactory("BuyMeACoffee");
const buyMeACoffee = await BuyMeACoffee.deploy();
await buyMeACoffee.deployed();
console.log("BuyMeACoffee deployed to:", buyMeACoffee.address);
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
I really do not know how to get it sorted and it pretty much has left me in a loop.
Please help. Thank You
I am pretty much new to using hardhat and npm. My current node v16.13.1 (npm v8.1.2)
There was an error in the hardhat.config file instead of accounts:process.env.PRIVATE_KEY, it should have been accounts:[process.env.PRIVATE_KEY]

How do I listen to events from a smart contract using ethers.js contract.on() in a node.js application?

I'm trying to listen to events emitted from the USDT contract Transfer function using ethers.js (not web3) in a node.js application.
When I run the script, the code runs with no errors and then quickly exits. I'd expect to get the event logs. I'm not sure what step I'm missing.
I've tested this script by calling the getOwner() method and console logging that result, this works fine, so my connection to mainnet is ok.
I'm using alchemy websocket.
My index.js file
const hre = require("hardhat");
const ethers = require('ethers');
const USDT_ABI = require('../abis/USDT_ABI.json')
async function main() {
const usdt = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
const provider = new ethers.providers.WebSocketProvider("wss://eth-mainnet.ws.alchemyapi.io/v2/MY_API");
const contract = new ethers.Contract(usdt, USDT_ABI, provider)
contract.on('Transfer', (from, to, value) => console.log(from, to, value))
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
My hardhat.config.js file
require("#nomiclabs/hardhat-waffle");
require('dotenv').config()
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async () => {
const accounts = await ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
paths: {
artifacts: './src/artifacts',
},
networks: {
mainnet: {
url: "wss://eth-mainnet.ws.alchemyapi.io/v2/MY_API",
accounts: [`0x${process.env.PRIVATE_KEY}`]
},
hardhat: {
chainId: 1337
},
},
solidity: "0.4.8"
};`
I solved this by removing
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
and just calling main. It's recommended in the hardhat docs to use the .then and .catch code but when running a long running process like this script does with contract.on(), it causes the script to exit.
I do this:
const ethers = require('ethers');
const abi = [{...}]
const contractAddress = '0x000...'
const webSocketProvider = new ethers.providers.WebSocketProvider(process.env.ETHEREUM_NODE_URL, process.env.NETWORK_NAME);
const contract = new ethers.Contract(contractAddress, abi, webSocketProvider);
contract.on("Transfer", (from, to, value, event) => {
console.log({
from: from,
to: to,
value: value.toString(),
data: event
});
});
The event return all data related to event and transaction.

Module not found: Can't resolve 'child_process' - google-spreadsheet

I am trying to save form data to a spreadsheet in Next.js but I keep getting this error which appears as soon as I import google-spreadsheet
Error
./node_modules/google-spreadsheet/node_modules/google-auth-library/build/src/auth/googleauth.js:17:0
Module not found: Can't resolve 'child_process'
Bellow is what I have that is causing the error.
// The error appears when I do this import
import { GoogleSpreadsheet } from "google-spreadsheet";
const SPREADSHEET_ID = process.env.NEXT_PUBLIC_SPREADSHEET_ID;
const SHEET_ID = process.env.NEXT_PUBLIC_SHEET_ID;
const CLIENT_EMAIL = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL;
const PRIVATE_KEY = process.env.NEXT_PUBLIC_GOOGLE_SERVICE_PRIVATE_KEY;
const doc = new GoogleSpreadsheet(SPREADSHEET_ID);
const appendSpreadsheet = async (row) => {
try {
await doc.useServiceAccountAuth({
client_email: CLIENT_EMAIL,
private_key: PRIVATE_KEY,
});
// loads document properties and worksheets
await doc.loadInfo();
const sheet = doc.sheetsById[SHEET_ID];
const result = await sheet.addRow(row);
return result;
} catch (e) {
console.error("Error: ", e);
}
};
I just solve it.
Please create next.config.js file in your root.
And fill it below.
module.exports = {
webpack: config => {
config.node = {
fs: 'empty',
child_process: 'empty',
net: 'empty',
dns: 'empty',
tls: 'empty',
};
return config;
},
};
Hoorai!
I was having this problem with nextjs 12. Here's what fixed it for me:
My code:
const doc = new GoogleSpreadsheet(SPREADSHEET_ID);
await doc.useServiceAccountAuth({
client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY,
});
await doc.loadInfo();
console.log('title', doc.title);
My next.config.js:
const nextConfig = {
reactStrictMode: true,
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback.fs = false
config.resolve.fallback.tls = false
config.resolve.fallback.net = false
config.resolve.fallback.child_process = false
}
return config
},
future: {
webpack5: true,
},
fallback: {
fs: false,
tls: false,
net: false,
child_process: false
},
}
module.exports = nextConfig;
Took inspiration/fix from here
Found this answer due to a similar issue. I later learned for next.js, with some of these api libraries, you must call call this type of code (serverside) in two contexts getStaticProps or getServerSideProps. See this and this for more details.
Try changing the import statement to:
const { GoogleSpreadsheet } = require('google-spreadsheet');
Source: https://www.npmjs.com/package/google-spreadsheet
The reason is that the library you require uses some nodejs native modules, like path, fs or child_process.
As part of the build process nextjs will create js bundles for your client and server separately. The issue is that your client build cannot resolve those nodejs modules. As a workaround you can tell nextjs to ignore these modules for the client build only.
next.config.js
const nextConfig = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback = {
fs: false,
path: false,
}
}
return config
}
}
module.exports = nextConfig;
the library does not support ES6 feature yet
if you look to the module export you will find somthing like this :
module.exports = {
GoogleSpreadsheet,
GoogleSpreadsheetWorksheet,
GoogleSpreadsheetRow,
GoogleSpreadsheetFormulaError,
};
https://github.com/theoephraim/node-google-spreadsheet/blob/master/index.js
change the import statement to commonjs modules like this :
const { GoogleSpreadsheet } = require('google-spreadsheet');

Categories