Error while deploying a smart contract to a local hardhat node - next.js

Getting the following two errors when I deploy my contract to my local hardhat node:
Error: network does not support ENS (operation="getAvatar", network="unknown", code=UNSUPPORTED_OPERATION, version=providers/5.6.5)
Error: network does not support ENS (operation="lookupAddress", network="unknown", code=UNSUPPORTED_OPERATION, version=providers/5.6.5)
I'm using ethers, hardhat, and rainbow kit wallet in a next.js app. The rest of my code appears to be working, but I'm still getting these errors in the console on the initial load. Here is my deploy script that I'm running on hardhat:
const fs = require("fs");
async function main() {
const NFTMarketplace = await hre.ethers.getContractFactory("NFTMarketplace");
const nftMarketplace = await NFTMarketplace.deploy();
await nftMarketplace.deployed();
console.log("nftMarketplace deployed to:", nftMarketplace.address);
fs.writeFileSync(
"./config.js",
`
export const marketplaceAddress = "${nftMarketplace.address}"
`
);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

network does not support ENS
ENS stands for Ethereum Name Service. It's a decentralized alternative to DNS (Domain Name Service) on the Ethereum network.
The rainbowkit wallet is trying to query Hardhat for an ENS name of an address and its avatar, however Hardhat emulator does not support ENS.

Related

When deploying contract using hardhat to Mumbai (Polygon) the address already exists

Contract deploys to address 0x47c5e40890bcE4a473A49D7501808b9633F29782
It looks like many other contracts were deployed to the same address by other people.
Should the address of the contract not be unique or is it deterministically generated or cached somehow by hardhat?
Why would other people have deployed to the same address?
I am wondering if this is some bug with Polygon/Mumbai testnet
const { ethers } = require("hardhat");
async function main() {
const SuperMarioWorld = await ethers.getContractFactory("Rilu");
const superMarioWorld = await SuperMarioWorld.deploy("Rilu", "RILU");
await superMarioWorld.deployed();
console.log("Success contract was deployed to: ", superMarioWorld.address)
await superMarioWorld.mint("https://ipfs.io/ipfs/QmZkUCDt5CVRWQjLDyRS4c8kU6UxRNdpsjMf6vomDcd7ep")
}
// 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);
});
Hardhat
module.exports = {
solidity: '0.8.4',
networks: {
mumbai: {
url: process.env.MUMBAI_RPC,
accounts: [process.env.PRIVATE_KEY],
},
},
};
.env file (no problem with sharing the private key, just one I got from vanity-eth.tk and used for testing)
PRIVATE_KEY=84874e85685c95440e51d5edacf767f952f596cca6fd3da19b90035a20f57e37
MUMBAI_RPC=https://rpc-mumbai.maticvigil.com
Output
~/g/s/b/r/nft ❯❯❯ npx hardhat run scripts/deploy.js --network mumbai ✘ 1
Compiling 12 files with 0.8.4
Compilation finished successfully
Success contract was deployed to: 0x47c5e40890bcE4a473A49D7501808b9633F29782

Web Scraping in React & MongoDB Stitch App

I'm moving a MERN project into React + MongoDB Stitch after seeing it allows for easy user authentication, quick deployment, etc.
However, I am having a hard time understanding where and how can I call a site scraping function. Previously, I web scraped in Express.js with cheerio like:
app.post("/api/getTitleAtURL", (req, res) => {
if (req.body.url) {
request(req.body.url, function(error, response, body) {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(body);
const webpageTitle = $("title").text();
const metaDescription = $("meta[name=description]").attr("content");
const webpage = {
title: webpageTitle,
metaDescription: metaDescription
};
res.send(webpage);
} else {
res.status(400).send({ message: "THIS IS AN ERROR" });
}
});
}
});
But obviously with Stitch no Node & Express is needed. Is there a way to fetch another site's content without having to host a node.js application just serving that one function?
Thanks
Turns out you can build Functions in MongoDB Stitch that allows you to upload external dependencies.
However, there're limitation, for example, cheerio didn't work as an uploaded external dependency while request worked. A solution, therefore, would be to create a serverless function in AWS's lambda, and then connect mongoDB stitch to AWS lambda (mongoDB stitch can connect to many third party services, including many AWS lambda cloud services like lambda, s3, kinesis, etc).
AWS lambda allows you to upload any external dependencies, if mongoDB stitch allowed for any, we wouldn't need lambda, but stitch still needs many support. In my case, I had a node function with cheerio & request as external dependencies, to upload this to lambda: make an account, create new lambda function, and pack your node modules & code into a zip file to upload it. Your zip should look like this:
and your file containing the function should look like:
const cheerio = require("cheerio");
const request = require("request");
exports.rss = function(event, context, callback) {
request(event.requestURL, function(error, response, body) {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(body);
const webpageTitle = $("title").text();
const metaDescription = $("meta[name=description]").attr("content");
const webpage = {
title: webpageTitle,
metaDescription: metaDescription
};
callback(null, webpage);
return webpage;
} else {
callback(null, {message: "THIS IS AN ERROR"})
return {message: "THIS IS AN ERROR"};
}
});
};
and in mongoDB, connect to a third party service, choose AWS, enter the secret keys you got from making an IAM amazon user. In rules -> actions, choose lambda as your API, and allow for all actions. Now, in your mongoDB stitch functions, you can connect to Lambda, and that function should look like this in my case:
exports = async function(requestURL) {
const lambda = context.services.get('getTitleAtURL').lambda("us-east-1");
const result = await lambda.Invoke({
FunctionName: "getTitleAtURL",
Payload: JSON.stringify({requestURL: requestURL})
});
console.log(result.Payload.text());
return EJSON.parse(result.Payload.text());
};
Note: this slowed down performances big time though, generally, it took twice extra time for the call to finish.

How to fix the error : your application id may be incorrect. If the error persists, contact support#algolia.com

I want to send cloud firestore data to algolia to enable full-text search. Firebase cloud function log is showing an error about application id. I am not able to understand this error and how to fix this.
name: 'RetryError',
message: 'Unreachable hosts - your application id may be incorrect. If the error persists, contact support#algolia.com.'
This is my index.js file
exports.addFirestoreDataToAlgolia =
functions.https.onRequest((req, res) => {
var arr = [];
admin.firestore().collection("tags").get()
.then((docs) => {
docs.forEach((doc) => {
let user = doc.data();
user.objectID = doc.id;
arr.push(user);
})
const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY);
const index = client.initIndex(ALGOLIA_INDEX_NAME);
return index.saveObjects(arr, (err, content) => {
if (err) {
res.status(500);
}
else {
res.status(200).send(content);
}
})
})
.catch( err => {
console.log(err);
})
})
Outbound requests (outside of Google services) can only be made from functions on a paid plan (https://firebase.google.com/pricing).
Reason for the wrong appID error is that the Algolia is trying to resolve a dns using your appID, which fails. See https://github.com/algolia/algoliasearch-client-javascript/issues/587#issuecomment-407397688
You have to move off of the free Spark plan in order to call out to Algolia from your function..
I also got this error with NextJS, it was working fine with react but then when I moved to NextJs I got the error.
Turns out it was my .env variables that were not being passed correctly to the client/browser. Renaming the variables from REACT_APP_<variable name> to NEXT_PUBLIC_<variable name> to make them available to the browser as per the NextJs documentation fixed the issue.
NEXT_PUBLIC_ALGOLIA_APP_ID=xxxxxx
NEXT_PUBLIC_ALGOLIA_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
NEXT_PUBLIC_ALGOLIA_ADMIN_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxx

Google Cloud Functions Datastore Emulator local connection with functions

I've launched the local Datastore emulator and although wrote and test GCF with the remote Datastore instance (not emulated one). Now I'm trying to use the locally launched Datastore instance for testing purposes, but all requests still going to the cloud instance of Datastore.
Here is the code.
const db = require("#google-cloud/datastore")();
exports.signUp = (req, res) => {
if(!req.body.firstName || !req.body.lastName || !req.body.email) {
res.status(400).send("Incorrect user data passed");
} else {
let key = db.key("User");
console.log("KEY: ", key);
db.insert({
key: key,
data: {
firsName: req.body.firsName,
lastName: req.body.lastName,
email: req.body.email
}
}, (err, apiResponse) => {
console.log(apiResponse);
if(err) {
res.status(400).json({
message: "Error occured during creation"
});
} else {
res.status(200).json({
message: `Created under ${apiResponse}`
});
}
});
}
};
I know about the apiEndpoint (link on documentation) parameter in the Datastore instance configuration object. But should it actually be passed explicitly in the code? I though that there should be some environment variable that will tell default configuration to search for the Datastore emulator first, and then try to use the cloud one.

Firebase - create user on Node.js server

We have a large SPA using Firebase v2. We would like to upgrade to the new API, but we experience the following problem:
As the app is quite large, we have developed many integration tests, and for these tests we always need to reset the database and initialize it to a state, where some users exist. However, we found out there really is no such thing as creating a user on server anymore ( Firebase createUserWithEmailAndPassword method is undefined in node.js ), and we are quite unsure, how to upgrade the API and yet be able to reset and initialize the database from server.
Moreover, we are quite forced to do this upgrade, because we noticed that the Firebase v2, is still using the deprecated Graph API v2.0 for Facebook OAuth, and is not recommended for use after 8.8.2016. We understand that the Firebase v2 will probably not upgrade the calls to the Graph API, as the v2 is legacy. This, however, leaves us quite cornered for now.
Any help on this topic, please?
As of Firebase v3.3.0 you are able to create user accounts using Node, but the documentation isn't great on how to expose these methods.
In order to use the user management methods, you need to initialize an application in node using your Web API key, and not the Service Account config that is walked through in the setup guide.
// The Usual Service Account Init
// This will not contain any user management methods on firebase.auth()
this.app = firebase.initializeApp(
{
serviceAccount: 'path/to/serviceaccount/file.json',
databaseURL: 'https://mydbfb.firebaseio.com'
},
'MyAppName');
// Web Client Init in Node.js
// firebase.auth() will now contain user management methods
this.app = firebase.initializeApp(
{
"apiKey": "my-api-key",
"authDomain": "somedomain.firebaseapp.com",
"databaseURL": "https://mydbfb.firebaseio.com",
"storageBucket": "myfbdb.appspot.com",
"messagingSenderId": "SomeId"
},
'MyAppName');
You can grab your client api key from your Firebase console from the Web Setup guide
https://firebase.google.com/docs/web/setup
This is the only reference I could find that explicitly referenced the need to init with api key to get this to work.
https://groups.google.com/forum/#!msg/firebase-talk/_6Rhro3zBbk/u8hB1oVRCgAJ
Given below is a working example of creating Firebase user through Node.js
exports.addUser = function(req, res) {
var wine = req.body;
var email = req.body.email;
console.log(req.body);
var password = req.body.password;
var name = req.body.name;
console.log(“Creating user for -“+email+”-“+password);
var defaultAuth = admin.auth();
admin.auth().createUser({
email: email,
emailVerified: false,
password: password,
displayName: name,
disabled: false
})
.then(function(userRecord) {
console.log(“Created Firebase User successfully with id :”, userRecord.uid);
var wine = req.body;
wine.userId = userRecord.uid;
wine.timestamp = Date.now();
delete wine.password;
status = “201”;
var reply = JSON.stringify(wine);
db.collection(‘collname’, function(err, collection) {
collection.insert(wine, {safe:true}, function(err, result) {
if (err) {
wine.status = “200”;
wine.message = “An error occured”;
reply.set(‘status’,”201″);
res.status(201).send(wine);
} else {
console.log(‘Success: ‘ + JSON.stringify(result[0]));
status= “200”;
wine.status = “200”;
wine.message = “Account created Successfully”;
res.status(200).send(wine);
}
});
});
})
.catch(function(error) {
wine.message = “An error occured—“;
wine.status = “201”;
console.log(“User Creation onf Firebase failed:”, error);
res.status(201).send(wine);
});
}
For details you can see the following blog post
http://navraj.net/?p=53
Thanks

Resources