Can't deploy smart contract to hardhat network - solidity

I set up a project with hardhat for an NFT app. I modify hardhat.config.js like this:
const { ALCHEMY_KEY, ACCOUNT_PRIVATE_KEY } = process.env;
module.exports = {
solidity: "0.8.0",
defaultNetwork: "hardhat",
networks: {
hardhat: {},
rinkeby: {
url: `https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_KEY}`,
accounts: [`0x${ACCOUNT_PRIVATE_KEY}`]
},
// ethereum: {
// chainId: 1,
// url: `https://eth-mainnet.alchemyapi.io/v2/${ALCHEMY_KEY}`,
// accounts: [`0x${ACCOUNT_PRIVATE_KEY}`]
// },
},
}
then I created a deploy script in the scripts folder with the deploy task
// scripts/deploy.js
const { task } = require("hardhat/config");
const { getAccount } = require("./helpers");
task("deploy", "Deploys the TokenV2.sol contract").setAction(async function (taskArguments, hre) {
const tokenFactory = await hre.ethers.getContractFactory("TokenV2", getAccount());
const token = await tokenFactory.deploy();
await token.deployed()
console.log(`Contract deployed to address: ${token.address}`);
});
The problem it's when I run npx hardhat deploy it's shows this error in terminal: Error: unsupported getDefaultProvider network (operation="getDefaultProvider", network="hardhat", code=NETWORK_ERROR, version=providers/5.5.3) What I missed? I will appreciate any help.

I never used defaultNetwork in my works so I just had the following hardhat.config File and had no issues at all:
{
"solidity":"0.8.4",
"networks":{
"rinkeby":{
"url":"`https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_KEY}`",
"accounts":[
"`0x${ACCOUNT_PRIVATE_KEY}`"
]
}
}
}

Related

Etherscan has no support for network sepolia with chain id 11155111

I am trying to verify my deployed contract from truffle and getting "Etherscan has no support for network sepolia with chain id 11155111" error. So I am working with Etherscan and I deployed my contract on sepolia testnet.
How can I solve this problem?
My truffle-config.js
const apikeys = require("./chains/apikeys");
const keys = require("./keys.json");
module.exports = {
plugins: ["truffle-plugin-verify"],
api_keys:{
etherscan: "myApiEtherScan"
},
contracts_build_directory: "./public/contracts",
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*",
},
sepolia: {
provider: () =>
new HDWalletProvider(
keys.PRIVATE_KEY,
keys.INFURA_SEPOLIA_URL,
),
network_id: 11155111,
gas:5221975,
gasPrice:20000000000,
confirmations: 3,
timeoutBlocks:200,
skipDryRun: true
}
},
compilers: {
solc: {
version: "0.8.16",
settings: {
optimizer: {
enabled: true, // Default: false
runs: 1000 // Default: 200
}
}
}
},
};
Plugin truffle-plugin-verify doesn't have Sepolia chain support
I added the sepolia api url and etherscan url to constants and it works
const API_URLS = {
...
11155111: 'https://api-sepolia.etherscan.io/api',
...
}
const EXPLORER_URLS = {
...
11155111: 'https://sepolia.etherscan.io/address',
...
}
https://github.com/tafonina/truffle-plugin-verify

Error deploying smart contract using hardhat -- Cannot read property 'sendTransaction' of null

Getting the below error while trying to deploy a smart contract from hardhat. Error details
TypeError: Cannot read property 'sendTransaction' of null
at ContractFactory.<anonymous> (C:\Collection\node_modules\#ethersproject\contracts\src.ts\index.ts:1249:38)
at step (C:\Collection\node_modules\#ethersproject\contracts\lib\index.js:48:23)
at Object.next (C:\Collection\node_modules\#ethersproject\contracts\lib\index.js:29:53)
at fulfilled (C:\Collection\node_modules\#ethersproject\contracts\lib\index.js:20:58)
Here are the config files
hardhat.config.js
require('#nomiclabs/hardhat-waffle');
require("#nomiclabs/hardhat-ethers");
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 (taskArgs, hre) => {
const accounts = await hre.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 = {
solidity: "0.8.2",
networks: {
mumbai: {
url: process.env.MUMBAI_URL,
account: process.env.PRIVATE_KEY
}
}
};
deploy.js
const {ethers} = require("hardhat");
async function main() {
const SuperMario = await ethers.getContractFactory("SuperMario");
const superInstance = await SuperMario.deploy("SuperMarioCollection", "SMC");
await superInstance.deployed();
console.log("contract was deployed to:", superInstance.address());
await superInstance.mint("https://ipfs.io/ipfs/XXXXXXX");
}
// 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 am trying to deploy it using the following command
npx hardhat run scripts/deploy.js --network mumbai
thanks
Change account to accounts in the network config
found the fix. There was an error in the hardhat.config file
instead of account:, it should have been
accounts:[process.env.PRIVATE_KEY]

How to parse serverless.yml file in script

I need to read the serverless.yml config for use in some test mocks.
The following worked until a recent change:
const serverless = new Serverless()
await serverless.init()
const service = await serverless.variables.populateService()
How does one read the file now? There is an astounding lack of documentation in regards to using serverless progamically.
Well I ended up taking some code from the AppSync emulator package. I am not sure it covers it does a full parsing but it does the job for me.
import Serverless from 'serverless'
import path from 'path'
import fs from 'fs'
class ConfigServerless extends Serverless {
async getConfig(servicePath) {
this.processedInput = {
commands: [],
options: { stage: 'dev' }
}
this.config.servicePath = servicePath
this.pluginManager.setCliOptions(this.processedInput.options)
this.pluginManager.setCliCommands(this.processedInput.commands)
await this.service.load(this.processedInput)
this.pluginManager.validateCommand(this.processedInput.commands)
return this.variables
.populateService(this.pluginManager.cliOptions)
.then(() => {
this.service.mergeArrays()
this.service.setFunctionNames(this.processedInput.options)
this.service.validate()
})
}
}
const normalizeResources = config => {
if (!config.resources) {
return config.resources
}
if (!config.resources.Resources) {
return {}
}
if (!Array.isArray(config.resources.Resources)) {
return config.resources
}
const newResources = config.resources.Resources.reduce(
(sum, { Resources, Outputs = {} }) => ({
...sum,
...Resources,
Outputs: {
...(sum.Outputs || {}),
...Outputs
}
}),
{}
)
return {
Resources: newResources
}
}
export async function loadServerlessConfig(cwd = process.cwd()) {
const stat = fs.statSync(cwd)
if (!stat.isDirectory()) {
cwd = path.dirname(cwd)
}
const serverless = new ConfigServerless()
await serverless.getConfig(cwd)
const { service: config } = serverless
const { custom = {} } = config
const output = {
...config,
custom: {
...custom
},
resources: normalizeResources(config)
}
return output
}

Solidity issue passing parameters to a function

I have a Smart Contract with the function:
contract Example {
event claimed(address owner);
function claimStar() public {
owner = msg.sender;
emit claimed(msg.sender);
}
}
I'm using Truffle V5.0 and the Webpack box as a boiler plate code.
In my truffle-config.js file I have the in the networks configuration:
development:{
host:"127.0.0.1",
port: 9545,
network_id:"*"
}
Everything compile fine using:
- truffle develop
- compile
- migrate --reset
It says Truffle Develop started at http://127.0.0.1:9545
In my index.js file I have the following code:
import Web3 from "web3";
import starNotaryArtifact from "../../build/contracts/StarNotary.json";
const App = {
web3: null,
account: null,
meta: null,
start: async function() {
const { web3 } = this;
try {
// get contract instance
const networkId = await web3.eth.net.getId();
const deployedNetwork = starNotaryArtifact.networks[networkId];
this.meta = new web3.eth.Contract(
starNotaryArtifact.abi,
deployedNetwork.address,
);
// get accounts
const accounts = await web3.eth.getAccounts();
this.account = accounts[0];
} catch (error) {
console.error("Could not connect to contract or chain.");
}
},
setStatus: function(message) {
const status = document.getElementById("status");
status.innerHTML = message;
},
claimStarFunc: async function(){
const { claimStar } = this.meta.methods;
await claimStar();
App.setStatus("New Star Owner is " + this.account + ".");
}
};
window.App = App;
window.addEventListener("load", async function() {
if (window.ethereum) {
// use MetaMask's provider
App.web3 = new Web3(window.ethereum);
await window.ethereum.enable(); // get permission to access accounts
} else {
console.warn("No web3 detected. Falling back to http://127.0.0.1:9545. You should remove this fallback when you deploy live",);
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
App.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:9545"),);
}
App.start();
});
In my browser I have Metamask installed and I added a Private Network with the same URL and also imported two accounts.
When I start the application and opened in the browser it opens Metamask to request permission because I'm using window.ethereum.enable();.
But when I click on the button to claim it doesn't do anything.
The normal behavior is to Metamask open a prompt to ask for confirmation but it never happen.
I created also a new property in the contract for test and it works fine showing me the value assigned in the contract constructor.
My question is, Am I missing something?
I also tried to change the functionawait claimStar(); to await claimStar({from: this.account}); but in this case I got an error saying that claimStar doesn't expect parameters.
I would appreciate any help. Thanks
I solved the issue, the problem was in the function claimStarFunc
It should be in this way:
claimStarFunc: async function(){
const { claimStar } = this.meta.methods;
await claimStar().send({from:this.account});
App.setStatus("New Star Owner is " + this.account + ".");
}
Because I'm sending a transaction.
Thanks

What is the best approach to test a HapiJS plugin, with Lab?

What is the best way to test a HapiJS plugin, for example one plugin that add routes and handlers.
Since I have to create an instance of Hapi.Server to run the plugins, should I define all the tests from the app's root, for all the plugins ?
or
should I manage to get THE instance of Hapi.Server in my plugin's local tests ?
If I go for the second option, my server will have registered all the plugins, including those that the plugin to be tested doesn't depends on.
What is the best way to approach this ?
Thanks in advance.
If you're using Glue (and I highly recommend it), you can create a manifest variable for each test (or group of tests) you want to execute. The manifest only needs to include plugins required for that test to execute properly.
And expose some sort of init function to actually start your server. Small example:
import Lab = require("lab");
import Code = require('code');
import Path = require('path');
import Server = require('../path/to/init/server');
export const lab = Lab.script();
const it = lab.it;
const describe = lab.describe;
const config = {...};
const internals = {
manifest: {
connections: [
{
host: 'localhost',
port: 0
}
],
registrations: [
{
plugin: {
register: '../http_routes',
options: config
}
},
{
plugin: {
register: '../business_plugin',
options: config
}
}
]
},
composeOptions: {
relativeTo: 'some_path'
}
};
describe('business plugin', function () {
it('should do some business', function (done) {
Server.init(internals.manifest, internals.composeOptions, function (err, server) {
// run your tests here
});
});
});
init function:
export const init = function (manifest: any, composeOptions: any, next: (err?: any, server?: Hapi.Server) => void) {
Glue.compose(manifest, composeOptions, function (err: any, server: Hapi.Server) {
if (err) {
return next(err);
}
server.start(function (err: any) {
return next(err, server);
});
});
};