interacting with ganache-cli fork through script - javascript

const {ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent} = require ('#uniswap/sdk');
const ethers = require('ethers');
const chainId = ChainId.MAINNET;
how would I specify it to be the locally forked ganache chain?
tried this:
const Web3 = require('web3');
const web3 = new Web3(`http://localhost:8545`);
const tokenAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
const init = async ()=> {
const chainId = await web3.eth.getChainId();
...
following error is shown:
/Users/GreyShadow/node_modules/#ethersproject/logger/lib/index.js:179
var error = new Error(message);
^
Error: unsupported getDefaultProvider network (operation="getDefaultProvider", network={"chainId":1337,"name":"unknown"}, code=NETWORK_ERROR, version=providers/5.0.17)
Help is much appreciated

Related

TypeError: vrfCoordinatorV2Mock.createSubscription is not a function

`
const { network, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../helper-hardhat.config")
const { verify } = require("../helper-hardhat.config")
const FUND_AMOUNT = "100000000000000000"
module.exports = async ({ getNamedAccounts, deployments }) => {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const chainId = network.config.chainId
let vrfCoordinatorV2Address, subsciptionId
if (developmentChains.includes(network.name)) {
const vrfCoordinatorV2Mock = await deployments.get("VRFCoordinatorV2Mock")
vrfCoordinatorV2Address = vrfCoordinatorV2Mock.address
const transactionResponse = await vrfCoordinatorV2Mock.createSubscription()
const transactionReceipt = await transactionResponse.wait(1)
subscriptionId = transactionReceipt.events[0].args.subId
await vrfCoordinatorV2Mock.fundSubscription(subscriptionId, FUND_AMOUNT)
} else {
vrfCoordinatorV2Address = networkConfig[chainId]["vrfCoordinatorV2"]
subscriptionId = networkConfig[chainId]["subscriptionId"]
}
const entranceFee = networkConfig[chainId]["entranceFee"]
const gasLane = networkConfig[chainId]["gasLane"]
const callbackGasLimit = networkConfig[chainId]["callbackGasLimit"]
const interval = networkConfig[chainId]["interval"]
const args = [
vrfCoordinatorV2Address,
entranceFee,
gasLane,
subscriptionId,
callbackGasLimit,
interval,
]
const raffle = await deploy("Raffle", {
from: deployer,
args: args,
log: true,
waitConfirmations: network.config.blockConfirmations || 1,
})
if (!developmentChains.includes(network.name) && process.env.ETHERSCAN_API_KEY) {
log("-------Verifying.... Please Wait !-------------")
await verify(raffle.address, args)
}
log("--------------------------------------------------------------------------------")
}
module.exports.tags = ["all", "raffle"]`
Hello, I am learning solidity, and in the middle of writing a script for a contract. So, i am getting error TypeError: vrfCoordinatorV2Mock.createSubsctiption is not a function with the code above. Now I had to make some adjustment as in another lesson we used
const vrfCoordinatorV2Mock = await deployments.get("VRFCoordinatorV2Mock")
"deployments.get" to get the latest deployements. If I use:
const vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock")
the "getContract" piece is giving me this error:
TypeError: Cannot read properties of undefined (reading 'getContract')
So I am stuck now, I had searched the discussions for "getContract" error, no luck, may be I am missing some "imports" as I cant use syntax ethers.utils.parseEther to input ETHER value as well. That thing is generating another error TypeError: Cannot read properties of undefined (reading 'utils'). Please Help me out I am stuck and have no clue whats going on.
Thank You in advance!
try adding hardhat-ethers using yarn this way:
yarn add --dev #nomiclabs/hardhat-ethers#npm:hardhat-deploy-ethers
and check your package.json file. this should fix the "calling from ethers" problem

Getting an ENS error when interacting with a Smart Contract using ethers library

I everyone, I'm trying to call a function called 'safeMint' on an ERC721 contract deployed on Rinkeby testnet but I'm getting this error:
Error: resolver or addr is not configured for ENS name (argument="name", value="", code=INVALID_ARGUMENT, version=contracts/5.5.0)
This is the code I'm using to call the function
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
setAccount(accounts[0]);
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner();
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(account, props.cidOfJsonInIpfs);
console.log(trx);
} catch(err) {
console.log(err);
}
}
}
I've tried to print the parameters passed but they seem to be right, what am I doing wrong?
I solved it with the following code
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner(accounts[0]);
console.log(signer._address)
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(accounts[0], `https://gateway.pinata.cloud/ipfs/${props.cidOfFile}`);
let receipt = await trx.wait();
console.log(receipt);
} catch(err) {
console.log(err);
}
}
What I was missing: I was using setState function to set the 'account' state variable with the first account of metamask, instead, I started using account[0] directly and it worked!
I will accept this as solution in 2 days

How can get json interface of the smart contract

I export JSON interface from compile.js file but deploy.js file not work
it shows error as
RuntimeError: abort(Error: You must provide the JSON interface of the contract when instantiating a contract object.). Build with -s ASSERTIONS=1 for more info.
here is compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const lotteryPath = path.resolve(__dirname, 'contracts', 'lottery.sol');
const source = fs.readFileSync(lotteryPath, 'utf-8');
//console.log(solc.compile(source,1));
var input = JSON.stringify({
language: 'Solidity',
sources: {
'lottery.sol': {
content: source
}
},
settings: {
outputSelection: {
// Enable the metadata and bytecode outputs of every single contract.
"*": {
"*": ["metadata", "evm.bytecode"]
},
// Enable the abi and opcodes output of MyContract defined in file def.
"def": {
"Lottery": ["abi"]
},
}
}
})
const output = JSON.parse(solc.compile(input));
const interface = output.contracts['lottery.sol'].Lottery.abi;
const bytecode = output.contracts['lottery.sol'].Lottery.evm.bytecode.object;
module.exports = {
interface,
bytecode,
};
after that export this to deploy.js file
const HDwalletProvider = require("truffle-hdwallet-provider");
const Web3 = require("web3");
const {interface,bytecode}= require('./compile.js');
const provider = new HDwalletProvider(
'',
'https://ropsten.infura.io/v3/9ba5113757f648aaaab4d53e65898119'
);
const web3 = new Web3(provider);
const deploy = async()=>{
const accounts = await web3.eth.getAccounts();
console.log(accounts);
console.log("contract is deployed by manager with address",accounts[0]);
const result = await new web3.eth.Contract(interface)
.deploy({data : '0x'+bytecode})
.send({gas : '2000000' , from : accounts[0]});
console.log('contract deployed to address ', result.options.address);
}
deploy();
finally, show error
JSON interface error
Please help me,I am just a beginner at web3.js.I follow old tutorial to know the workflow
But it does not match with updated versions
here is depend
"dependencies": {
"next": "^11.1.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"solc": "^0.8.6",
"truffle-hdwallet-provider": "^1.0.17",
"web3": "^1.5.2"
}
I need someone help to get deployed address to set here
lottery.js file
import web3 from './web3.js';
const address = '';
const abi = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"enterLottery","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"participants","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pickWinner","outputs":[],"stateMutability":"nonpayable","type":"function"}];
export default new web3.eth.Contract(abi,address);
in compile.js
var output = JSON.parse(solc.compile(JSON.stringify(input))); // an object
// it spits out bytecode and interface
module.exports = output.contracts["Lottery.sol"]["Lottery"];
in deploy.js
const { abi, evm } = require("./compile");
compile.js
const path = require("path");
const fs = require("fs");
const solc = require("solc");
const inboxPath = path.resolve(__dirname, "contracts", "Example.sol");
const source = fs.readFileSync(inboxPath, "utf8");
const input = {
language: "Solidity",
sources: {
"Example.sol": {
content: source,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
const output = JSON.parse(solc.compile(JSON.stringify(input)));
module.exports = output.contracts["Example.sol"]["Example"];
here is my mocha test file example.test.js:
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const web3 = new Web3(ganache.provider());
const { abi, evm } = require("../compile");
let accounts;
let exampleContract;
beforeEach(async () => {
// Get a list of all accounts
accounts = await web3.eth.getAccounts();
// Use one of those accounts to deploy the contract
exampleContract = await new web3.eth
.Contract(abi)
.deploy({
data: evm.bytecode.object,
arguments: ["Hi there"],
})
.send({ from: accounts[0], gas: 1000000 });
});
describe("Example", () => {
it("deploys a contract", () => {
console.log(exampleContract);
});
});

Connect to Google Spreadsheet doesn't work | Node.js

Okay so I have this code :
const GoogleSpreadsheet = require('google-spreadsheet');
const { promisify } = require('util');
const creds = require('./client_secret.json');
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('1HrQBQU-3DtMywH_qZASB8xiIj8Vb6AlI3k2LWDameE8');
await promisify(doc.useServiceAccountAuth)(creds);
const info = await promisify(doc.getInfo)();
const sheet = info.worksheets[0];
console.log(`Title: ${sheet.title}`);
}
accessSpreadsheet()
and the console return :
> (node:1596) UnhandledPromiseRejectionWarning: TypeError: GoogleSpreadsheet is not a constructor
Why ?
All the creds are correct and I still don't understant what is wrong...
Thank's for your help

Lowdb return undefined

I'm doing a Discord bot with command handling, but on a file, I can't get the content of my JSON file out with lowdb... I proceed exactly the same way with success in the other files, I don't understand... Here is my code:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
module.exports = {
name: 'rent',
description: 'Rent a number',
usage: '<country>',
guildOnly: true,
async execute(message, args) {
return console.log(db.get().value())
...
Here's my db.json:
{
"numbers": [
{
"test": "1234"
}
]
}
When I console.log db alone, it takes me out the object, but as soon as I try to console.log with lowdb like above it takes me out undefined ....
So I'm not sure why, but you have to remove a point on the road to lowdb files.
Code not working:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
Code after modification and functional:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('./db.json')
const db = low(adapter)
const adapter2 = new FileSync('./users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;

Categories