How to correctly pass --network parameter to Hardhat scripts? - ethereum

I'm trying to deploy to Goerli, but my deploy script seems to ignore the --network parameter.
Here is my hardhat.config.ts:
import { HardhatUserConfig } from "hardhat/config";
import "#nomicfoundation/hardhat-toolbox";
import "hardhat-gas-reporter"
import "#nomiclabs/hardhat-ethers";
import * as dotenv from 'dotenv'
dotenv.config();
const env:any = process.env;
const config: HardhatUserConfig = {
solidity: {
[...]
},
networks: {
hardhat: {
[...]
},
goerli: {
url: 'https://goerli.infura.io/v3/',
accounts: [env['DEPLOYER_PRIVATE_KEY']]
},
},
[...]
};
export default config;
Then I run:
npx hardhat run scripts/deploy.ts --network goerli
And in my deploy.ts:
async function main() {
const [deployer] = await ethers.getSigners();
console.log('Using RPC ', ethers.provider.connection.url);
console.log('Deploying from address', deployer.address);
[...] // contract deployment code
}
However it fails with error "could not detect network". It makes sense because it also logs (from my code):
Using RPC http://localhost:8545
Deploying from address 0x3a5Bd3fBc2a17f2eECf2Cff44aef38bd7dc4fd7c
My address is correct, the address logged indeed corresponds to the account that I provided with the private key from dotenv, so it's being read from the config correctly. However, the RPC URL is incorrect: it seems that it's trying to connect to my local RPC and failing.
Why isn't Hardhat respecting the url property in the config, and still trying to connect to my local instance?

Change
const config: HardhatUserConfig = {
solidity: {
[...]
},
to
module.exports = {
solidity: "0.8.4",
networks: {
goerli: {
url: 'https://goerli.infura.io/v3/',
accounts: [env['DEPLOYER_PRIVATE_KEY']]
}
}
};
If you want to deploy on Hardhat you can run npx hardhat node and remove goerli and const env:any = process.env;.

Related

Firebase Cloud Function with Swagger: Error: could not handle the request

I have this code in a function called docs:
const functions = require("firebase-functions");
const express = require("express");
const swaggerUi = require("swagger-ui-express");
const swaggerJsdoc = require("swagger-jsdoc");
const options = {
definition: {
openapi: "3.0.0",
info: {
title: "API",
version: "1.0.0",
},
},
apis: ["../**/*.function.js"],
};
const openapiSpecification = swaggerJsdoc(options);
console.log("🚀 ", openapiSpecification);
const app = express();
app.use(
"/",
swaggerUi.serve,
swaggerUi.setup(openapiSpecification, {
swaggerOptions: {
supportedSubmitMethods: [], //to disable the "Try it out" button
},
})
);
module.exports = functions.https.onRequest(app);
But every time I hit the URL, this error gets returned:
Error: could not handle the request
URL:
https://REGION-PROJECT.cloudfunctions.net/docs
The deps above are all installed.
Any idea what is causing this issue?
Or better yet, how can I serve an endpoint for Swagger docs?
Please keep in mind that all other functions don't use express; most are callable. Just this one function uses it, so not sure if the mixing not supported.
Here's the folder structure:
package.json
index.js
app
auth
login.function.js
users
createUser.function.js
Inside index.js, the functions get loaded and added to the exports dynamically. This setup works fine and deploys well, so no issues there.

HardHat and Rinkeby ProviderError: Must be authenticated Error

When I run
npx hardhat console --network rinkeby
accounts = await ethers.provider.listAccounts();
I get
Uncaught ProviderError: Must be authenticated!
with below rinkeby network config in hardhat.config.js
rinkeby: {
url: "ALCHEMY_URL",
accounts:["YOUR_PRIVATE_KEY"],
}
Solution: update config file with below lines:
rinkeby: {
url: "ALCHEMY_URL",
accounts: ["YOUR_PRIVATE_KEY"],
gas: 2100000,
gasPrice: 8000000000,
saveDeployments: true,
}
This works like a charm. Hope this helped in saving some of your time.
Finally, your hardhat.config.js should look like this
require('#nomiclabs/hardhat-waffle');
module.exports = {
solidity: '0.8.0',
networks: {
ropsten: {
url: `${ARCHEM_APP_URL}`,
accounts: [`${ACCOUNT_KEY}`],
gas: 2100000,
gasPrice: 8000000000,
saveDeployments: true,
}
}
}

React, Hardhat frontend smart contract method calling, how to do so?

I'm using hardhat locally and have a react frontend up and running but I can't call the methods without errors.
I've tried both ethers.js and web3.
Here's my code and attempts. Please let me know if you see what I'm doing wrong.
I'm trying to interact with contracts that are deployed in the local hardhat env through web3
I'm unable to get back the data from the contract, here's the info
I have:
var list = await contract.methods.getList();
console.log("list ", list );
which gets me
list {arguments: Array(0), call: ƒ, send: ƒ, encodeABI: ƒ, estimateGas: ƒ, …}
When I do
var list = await contract.methods.getList().call();
console.log("list ", list );
I get this error in the browser:
Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
I do:
Setup in console:
npx hardhat node
>Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/
>Accounts
>========
>...
npx hardhat compile
> Nothing to compile
npx hardhat run scripts/deploy.js --network hardhat
Note: In the deploy.js file, I do a
const list = await contract.getList();
console.log("list", list ); // correctly outputs ["string", "string"]
The method:
mapping(uint256 => address) internal list;
uint256 internal listCount;
function getList() public override view returns (address[] memory) {
address[] memory assets = new address[](listCount);
for (uint256 i = 0; i < listCount; i++) {
assets[i] = list[i];
}
return assets;
}
In react App.js:
import Contract_from './data/abi/Contract_.json'; // Contract_ is a placer
var contract = new web3.eth.Contract(Contract_, address_given_on_deploy);
var contractAddress = await contract .options.address; // correctly outputs
var list= await contract.methods.getList().call();
console.log("list", list);
As you see, this doesn't return the values from the method. What am I doing wrong here?
For any reason and may be likely the issue, here's my config:
require("#nomiclabs/hardhat-waffle");
// openzeppelin adds
require("#nomiclabs/hardhat-ethers");
require('#openzeppelin/hardhat-upgrades');
//abi
require('hardhat-abi-exporter');
// 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 = {
networks: {
hardhat: {
gas: 12000000,
blockGasLimit: 0x1fffffffffffff,
allowUnlimitedContractSize: true,
timeout: 1800000,
chainId: 1337
}
},
solidity: {
compilers: [
{
version: "0.8.0",
settings: {
optimizer: {
enabled: true,
runs: 1000
}
}
},
{
version: "0.8.2",
settings: {
optimizer: {
enabled: true,
runs: 1000
}
}
},
],
},
abiExporter: {
path: './frontend/src/data/abi',
clear: true,
flat: true,
only: [],
spacing: 2
}
}
__
I thought maybe i would try ethers.js since that is what i do my testing in but same issue.
For whatever reason, I can "get" the contracts, print the methods that belong to them, but I can't actually call the methods.
Here's my ethers.js brevity:
provider = new ethers.providers.Web3Provider(window.ethereum);
if(provider != null){
const _contract = new ethers.Contract(address, _Contract, provider);
var list= await _contract.getList().call();
console.log("list", list);
}
The error i get from this is:
Error: call revert exception (method="getList()", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.4.0)
I've tried numerous contracts in the protocol and same thing for each

Deploy contract to local hardhat node with forked Kovan chain

I am trying to write tests for my contract on Kovan network. In order to do so I am using the fork feature of hardhat and added the following to the hardhat.config.js file:
module.exports = {
solidity: "0.8.0",
defaultNetwork: "hardhat",
networks: {
hardhat: {
forking: {
url: INFURA_URL,
accounts: [`0x${PRIVATE_KEY}`]
}
}
}
};
INFURA_URL points to node on Kovan. PRIVATE_KEY is the key of an account on Kovan I would like to deploy with. This variables work well when I deploy to Kovan directly but not to forked node.
In my deployment script I do the following:
const [deployer] = await ethers.getSigners();
But my deployer is not the account that corresponds to the private key from config. It is a correct account when I deploy directly to Kovan.
Not sure why does this happen are forks of Kovan not supported on hardhat?
The way it worked for me was to forget Hardhat and rely entirely on ethers, for that I created a Signer specifying a private key and a provider like:
import { providers, Wallet } from 'ethers';
require('dotenv').config();
const main = async() => {
const providerLocal = new
providers.JsonRpcProvider("http://127.0.0.1:8545");
const owner = new Wallet(process.env.DEPLOYER_PRIVATE_KEY as string, providerLocal);
console.log(`The wallet ${owner.address} will deploy this contract`)
const MyContract = await ethers.getContractFactory('MyContract');
const mycontract = await MayContract.connect(owner).deploy();
}
main();

"Web3ProviderEngine does not support synchronous requests" when running truffle migrate

I wanted to config my truffle-config.js with provider. When I run command "truffle migrate --network ropsten", it throws this error:
Error: Web3ProviderEngine does not support synchronous requests.
And the error details told
at Object.run (C:\Users\Bruce\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-migrate\index.js:92:1)
I have no idea about this. I look for the file
"C:\Users\Bruce\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-migrate\index.js:92:1", but I cannot find the path webpack under the "build/". Is it somethind wrong? I install truffle with global and it runs well with default network ganache.
ropsten: {
provider: () => new HDWalletProvider(
privateKeys.split(','),
`https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`
),
network_id: 3, // Ropsten's id, mainnet is 1
gas: 5500000, // Ropsten has a lower block limit than mainnet
gasPrice: 2500000000, //2.5 gwei
confirmations: 2, // # of confs to wait between deployments. (default: 0)
timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
},
My HDWalletProvider dependency version:
"dependencies": {
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"dotenv": "^8.1.0",
"eslint": "^6.4.0",
"openzeppelin-solidity": "^2.3.0",
"truffle-hdwallet-provider": "^1.0.17",
"truffle-hdwallet-provider-privkey": "^0.3.0",
"web3": "^1.2.1"
},
And the migrations:
1_initial_migration.js
const Migrations = artifacts.require("Migrations");
module.exports = function(deployer) {
deployer.deploy(Migrations);
};
2_deploy_contract.js
const Token = artifacts.require("TokenInstance");
const DeleToken = artifacts.require("DelegateToken")
module.exports = async function(deployer) {
deployer.deploy(Token);
deployer.deploy(DeleToken);
};
It just cannot compile successfully. But I use the default network with ganache is OK!
You are still using the old repository that has been deprecated.
You should use truffle monorepo instead
npm install #truffle/hdwallet-provider
and replace
const HDWalletProvider = require("#truffle/hdwallet-provider");
also you don't need to use truffle-hdwallet-provider-privkey