error in depolying contract >> Error: could not detect network (event="noNetwork", code=NETWORK_ERROR, version=providers/5.7.2) - deployment

im trying the depoy my contract using npx hardhat run scripts/deploy.js --network goerli and i keep geeting the above error
//this is the error
omota#DESKTOP-3T9OR5N MINGW32 ~/web3-projects/tinder-blockchain/smart-contract (main)
$ npx hardhat run scripts/deploy.js --network goerli
Compiled 1 Solidity file successfully
error in depolying contract >> Error: could not detect network (event="noNetwork", code=NETWORK_ERROR, version=providers/5.7.2)
at Logger.makeError (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\logger\src.ts\index.ts:269:28)
at Logger.throwError (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\logger\src.ts\index.ts:281:20)
at EthersProviderWrapper.<anonymous> (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\src.ts\json-rpc-provider.ts:483:23)
at step (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\lib\json-rpc-provider.js:48:23)
at Object.throw (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\lib\json-rpc-provider.js:29:53)
at rejected (C:\Users\omota\web3-projects\tinder-blockchain\smart-contract\node_modules\#ethersproject\providers\lib\json-rpc-provider.js:21:65)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
reason: 'could not detect network',
code: 'NETWORK_ERROR',
event: 'noNetwork'
}
//here is my depoy.js file
const { ethers } = require('hardhat')
const main = async () => {
const tinderFactory = await ethers.getContractFactory('TinderERC721')
const tinderContract = await tinderFactory.deploy()
console.log('TINDER CONTRACT ADDRESS:', tinderContract.address)
};
main()
.then(() => process.exit(0))
.catch(error => {
console.log('error in depolying contract >>', error);
process.exit(1);
})
//here is my hardhat-config.js
require("#nomicfoundation/hardhat-toolbox");
require('dotenv').config({path: '.env'})
const ALCHEMY_API_URL = process.env.ALCHEMY_API_URL
const GOERLI_PRIVATE_KEY = process.env.GOERLI_PRIVATE_KEY
/** #type import('hardhat/config').HardhatUserConfig */
module.exports = {
defaultNetwork: 'goerli',
networks: {
goerli: {
url: ALCHEMY_API_URL,
accounts: [`0x${GOERLI_PRIVATE_KEY}`],
},
},
solidity: '0.8.17',
}
any help will be appreciated
i have done anything i can but still the same

I had the same error. Since you are using .env to store the private keys, if the value is being stored as:
"https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}" within the .env file itself, change it to the full link instead:
"https://eth-goerli.alchemyapi.io/v2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
I was also getting a "private key too long" error as well because of using semi-colons to separate statements within the .env file... Hope this helps!

Maybe you have some problems with the ALCHEMY_API_URL. It should be in the form:
https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}
Or for sure, you can use public RPC nodes:
https://goerli.infura.io/v3/ //default on metamask
https://rpc.ankr.com/eth_goerli //I tried and it worked
https://eth-goerli.public.blastapi.io
https://rpc.goerli.mudit.blog

Related

Minimal Sveltekit + pg integration fails with "status" error

I'm trying to get Postgres working with sveltekit and a very minimal example is giving me issues. This is probably a configuration thing but the error I'm getting back from sveltekit makes no sense to me.
I start by installing a new project:
npm create svelte#latest my-testapp
Then I install "pg" to get Postgres pooling:
npm i pg
Then I add a page under src/lib/db.js:
import { Client, Pool } from 'pg';
const pool = new Pool({
user: 'xxx',
host: 'xxx',
database: 'xxx',
password: 'xxx',
port: 5432,
})
export const connectToDB = async () => await pool.connect();
Finally I add src/hooks.server.js to give me access to the pool within routes:
import { connectToDB } from '$lib/db';
export const handle = async ({event, resolve}) => {
const dbconn = await connectToDB();
event.locals = { dbconn };
const response = await resolve(event);
dbconn.release();
}
The server fails to compile with a couple of these errors:
Cannot read properties of undefined (reading 'status')
TypeError: Cannot read properties of undefined (reading 'status')
at respond (file:///C:/Users/user/code/svelte/my-testapp/node_modules/#sveltejs/kit/src/runtime/server/index.js:314:16)
at async file:///C:/Users/user/code/svelte/my-testapp/node_modules/#sveltejs/kit/src/exports/vite/dev/index.js:406:22
Not sure where "status" is coming from, seems to be part of the initial scaffolding. Any help appreciated.
Also - if there is a more straightforward way to integrate pg with sveltekit then I'm happy to hear about it. Thanks
My bad - the hooks function wasn't returning the response.
Hooks.server.js should read:
import { connectToDB } from '$lib/db';
export const handle = async ({event, resolve}) => {
const dbconn = await connectToDB();
event.locals = { dbconn };
const response = await resolve(event);
dbconn.release();
return response
}

How to solve Vercel 500 Internal Server Error?

I have created a project that uses MongoDB to store user info and Next-Auth to authenticate users. On local host this is all working seamlessly. Previously I had a couple errors with my next-auth config, but that seems to be working fine now on Vercel live site. Once the user logs in they are redirected to "my-project/suggestions". On this page I am using getServerSideProps to identify if there is a valid session token. If so, data is pulled from a local json file.
On the live site, when the user logs in, the page is redirected to "/suggestions", yet I am receiving an 500 Internal Server Error page. On the function logs I am getting this error message:
[GET] /_next/data/KpsnuV9k44lUAhQ-0rK-B/suggestions.json
10:10:57:12
2022-05-05T14:10:59.270Z 5b7a7375-045f-4518-864b-7968c3c9385f ERROR [Error: ENOENT: no such file or directory, open '/var/task/public/data/data.json'] {
errno: -2,
syscall: 'open',
path: '/var/task/public/data/data.json',
page: '/suggestions'
}
RequestId: 5b7a7375-045f-4518-864b-7968c3c9385f Error: Runtime exited with error: exit status 1
Runtime.ExitError
This is my first project using MongoDB and Next-Auth.. not so sure what the issue is in this case. In my .env.local file I only have these two variables:
NEXTAUTH_SECRET="MUNKNATION"
NEXTAUTH_URL=http://localhost:3000
How I am pulling the data on local host:
export const getServerSideProps = async (context) => {
const session = await getSession({ req: context.req });
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
} else {
let filePath = path.join(process.cwd(), "public", "data", "data.json");
let jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
const inProgressStatusData = data.productRequests.filter(
(item) => item.status == "in-progress"
);
const liveStatusData = data.productRequests.filter(
(item) => item.status == "live"
);
const plannedStatusData = data.productRequests.filter(
(item) => item.status == "planned"
);
let filterData = filteredData(data, "suggestion");
let feedbackData = {
suggestions: filterData,
progress: inProgressStatusData,
planned: plannedStatusData,
live: liveStatusData,
};
return {
props: { session, feedbackData },
};
}
};
Folder structure:
A simple solution to this problem would be to, inside of your getServerSideProps, instead of calling readFile use readFileSync as follows:
export const getServerSideProps = async (context) => {
...
const file = readFileSync(
join(process.cwd(), "public", "data", "data.json"),
"utf8"
);
const data = JSON.parse(fileData);
...
I have tested this solution with Vercel and it works correctly, in development and production mode.

How to fix the error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>')

I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.
Code
const addChoice = async (e) => {
try {
e.preventDefault();
const res = await fetch("/api/sendChoice", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
choiceSeq: choice,
checkSubmit: true,
}),
});
console.log(res);
router.push("/home");
} catch (error) {
console.log(error);
}
};
The error is happening at const res = await fetch("/api/sendChoice" ,{
In terminal server the error
error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'
In the inspect element the error is as
I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.
Some other related code from my project:
api/sendChoice
import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";
export default async function sendChoice(req, res) {
try {
const session = await getSession({ req });
await dbConnect();
if (!session) {
res.status(401).send("You are not signed in");
return;
}
if (req.method === "POST") {
console.log(req.body);
const { choiceSeq, checkSubmit } = req.body;
console.log(choiceSeq, checkSubmit);
const userId = session.user.id;
const nameP = session.user.name;
const choice = new Choice({
user: userId,
name: nameP,
choiceSeq,
checkSubmit,
});
await choice.save();
res.status(200).send("Choice saved");
} else {
res.status(400).send("Bad request");
}
}
catch (error) {
console.log(error);
}
}
The MongoDB schema
import mongoose, { Schema } from 'mongoose';
const ChoiceSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User',
},
name: {
type: String,
},
choiceSeq: {
type: Array,
default: [],
},
checkSubmit: {
type: Boolean,
}
});
mongoose.models = {};
export default mongoose.model('Choice', ChoiceSchema);
the latest update to version 17.5.0 is the one causing this error. You must reinstall node js to version 16.14.0 LTS. You should always work with LTS versions
This issue occured recently and apparently its happening with latest version of node.
issue link
So you can change the version of node to older version and it will be fixed. I am using node version v14.19.0
if you are using Docker then, giving a version will solve the problem.
before:
FROM node:alpine
now
FROM node:16.5.0-alpine
WORKDIR /app
COPY package.json .
RUN npm install --only=prod
COPY . .
CMD ["npm", "start"]
The latest release of Node.JS is what is causing this issue. In your package.json, make sure to set your engine to"engines": { "node": ">=0.12 < 17.5.0" } and you should be fine.
Also if you are using docker for deployment, make sure to change the version number in your dockerfile to be less that 17.5.0
Solution which worked well for me:)
Step 01: Open your terminal and copy paste below command.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | zsh
Wait patiently until its done.
Step 02: sudo vim ./zshrc
Step 03: Press I for Insert Mode and copy paste below command. Must be same in three lines.
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion"
then press ESC key :wq (write and quite).
Step 04: brew install nvm
step 05: nvm install node (which will download latest version node)
step 06: nvm ls-remote (which make all the version available)
step 07: nvm install 14 (An Example)
step 08: nvm use 14 (this make it as default version)
source: https://github.com/nvm-sh/nvm
Try upgrading to v17.6.0. It solved the issue for me.
In My case eslint 8.9.0 was the culprit. Rollback fixed it.

My 'deployed' contract still won't show up on Etherscan. Been about 1.5 hours

need help figuring out why my supposedly 'deployed' contract will still not appear in Etherscan.
Overview:
I used hardhat with following code and got back confirmation:
$ npx hardhat run scripts/deployRoboPunksNFT.js --network rinkeby
RoboPunksNFT deployed to: 0xaBDe0c1A9F7589f21818287287885a2Fef32E3f0
Clearly, it confirms as fully deployed but when I check this contract address at Etherscan (Rinkeby)...nothing: https://rinkeby.etherscan.io/address/0xaBDe0c1A9F7589f21818287287885a2Fef32E3f0
The deployment script used:
const hre = require("hardhat");
async function main() {
const RoboPunksNFT = await hre.ethers.getContractFactory("RoboPunksNFT");
const roboPunksNFT = await RoboPunksNFT.deploy();
await roboPunksNFT.deployed();
console.log("RoboPunksNFT deployed to:", roboPunksNFT.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
My hardhat.config.js
require("#nomiclabs/hardhat-waffle");
const dotenv = require("dotenv");
require("#nomiclabs/hardhat-etherscan");
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);
}
});
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
networks: {
rinkeby: {
url: process.env.REACT_APP_RINKEBY_RPC_URL,
accounts: [process.env.REACT_APP_PRIVATE_KEY]
},
},
etherscan: {
apiKey: process.env.REACT_APP_ETHERSCAN_KEY,
}
};
I got so frustrated that I deployed it again (Code above is 2nd attempt/2nd deployed contract. The first deployed contract address was at 0x9F6040234728493121BCB9A1EaFDBa5E494bB3ed.
Please let me know if anyone sees something that I missed. Hopefully there's enuf info I've submitted here to determine...
Thanks very much!
Problem solved. Rinkeby happened to be down for 6 whole hours. But once it came back up, had 2 freshly deployed contracts on Rinkeby ready to go...

StitchServiceError "aws: "aws_service" is a required string", errorCodeName: InvalidParameter

I'm setting up AWS S3 bucket to upload audio files to using MongoDB Stitch (here are the docs mongo s3 docs . After following the instructions and authenticating my user I keep geting this error when trying to upload the selected file: error image from console
On line 119 where the error is coming from I'm just catching the error after running AWS build:
const aws = stitchClient.getServiceClient(AwsServiceClient.factory, "AWS");
convertAudioToBSONBinaryObject(file).then((result) => {
const audiofile = mongodb.db("data").collection("audiofile");
//now we need an instance of AWS service client
const key = `${stitchClient.auth.user.id}-${file.name}`;
// const key = `${stitchClient.auth.user.id}-${file.name}`;
const bucket = "myBucketName";
const url =
"http://" + bucket + ".s3.amazonaws.com/" + encodeURIComponent(key);
const args = {
ACL: "public-read",
Bucket: bucket,
ContentType: file.type,
Key: key,
Body: result,
// aws_service: "s3",
};
// building the request
const request = new AwsRequest.Builder()
.withService("s3")
.withAction("PutObject")
.withRegion("us-east-1")
.withArgs(args);
aws
.execute(request.build)
.then((result) => {
console.log(result);
console.log(url);
return audiofile.insertOne({
owner_id: stitchClient.auth.user.id,
url,
file: {
name: file.name,
type: file.type,
},
Etag: result.Etag,
ts: new Date(),
});
})
.then((result) => {
console.log("last result", result);
})
.catch((err) => {
console.log(err);
});
});
My Stitch rule for s3 looks like this: Stitch rule for AWS s3
So it seems to me that everything is set up the way it's inteded to, but the error tells me I'm not passing all the needed args. I'd really appreciate any thoughts on how to fix this error.
P.S. If I change "AWS" to "AWS_S3" in this line :
const aws = stitchClient.getServiceClient(AwsServiceClient.factory, "AWS");
The error message changes to this:
StitchServiceError {message: "service not found: 'AWS_S3'", name: "StitchServiceError", errorCode: 18, errorCodeName: "ServiceNotFound",
And the log in Stitch shows this for information for both errors: Stitch Logs
The answer to this is a simple typo in this line:
aws
.execute(request.build)
.then((result)
build is a function so I just needed to call it - (request.build()).then((result).
Issue solved, thanks all!