Automatically pointing contract address to solidity interface - ethereum

I'm trying to use a interface on remix IDE and my only issue is that I have to copy and paste the contract's address.
Is there a way that I can point it automatically?
ty.

In Remix IDE, you need to copy and paste the newly deployed address manually.
With frameworks, such as Hardhat, you can retrieve the address of the deployed contract in the code and then pass it to the other contract.
In the example below, we're passing the address of First instance to Second's constructor, using the Hardhat JS framework.
const firstFactory = await ethers.getContractFactory("First");
const first = await firstFactory.deploy();
await first.deployed();
const secondFactory = await ethers.getContractFactory("Second");
const second = await secondFactory.deploy(first.address);
await second.deployed();
pragma solidity ^0.8;
contract First {}
contract Second {
constructor(address firstAddress) {}
}

Related

How to get the address of a contract deployed by another contract

-----START EDIT-----
I don't know what I was doing wrong before, but the code below was somehow not working for me, and now is working, and it's exactly the same. I don't know how or what I was missing before, but both this minimal example and the real project I am working on is working now. Obviously I changed something, but I can't figure out what. I just know it's working now. Sorry for the confusion and thanks to everyone for helping.
-----END EDIT-----
I am new to Solidity and am using the Factory pattern for deploying a contract from another contract. I am trying to get the contract address of the deployed contract, but I am running into errors.
I already tried the solution in this question, but I'm getting the following error: Return argument type struct StorageFactory.ContractData storage ref is not implicitly convertible to expected type (type of first return variable) address.
Here is my code:
// START EDIT (adding version)
pragma solidity ^0.8.0;
// END EDIT
contract StorageFactory {
struct ContractData {
address contractAddress; // I want to save the deployed contract address in a mapping that includes this struct
bool exists;
}
// mapping from address of user who deployed new Storage contract => ContractData struct (which includes the contract address)
mapping(address => ContractData) public userAddressToStruct;
function createStorageContract(address _userAddress) public {
// require that the user has not previously deployed a storage contract
require(!userAddressToStruct[_userAddress].exists, "Account already exists");
// TRYING TO GET THE ADDRESS OF THE NEWLY CREATED CONTRACT HERE, BUT GETTING AN ERROR
address contractAddress = address(new StorageContract(_userAddress));
// trying to save the contractAddress here but unable to isolate the contract address
userAddressToStruct[_userAddress].contractAddress = contractAddress;
userAddressToStruct[_userAddress].exists = true;
}
}
// arbitrary StorageContract being deployed
contract StorageContract {
address immutable deployedBy;
constructor(address _deployedBy) {
deployedBy = _deployedBy;
}
}
How can I get this contract address, so I can store it in the ContractData struct? Thanks.
I compiled your contract, deployed it on Remix, and interacted without issue with this setting
pragma solidity >=0.7.0 <0.9.0;
I think you had this in your contract before
userAddressToStruct[_userAddress] = contractAddress;
instead of this
userAddressToStruct[_userAddress].contractAddress = contractAddress;
You can use the following code to get the address of the deployed contract:
address contractAddress;
(contractAddress,) = new StorageContract(_userAddress);
userAddressToStruct[_userAddress].contractAddress = contractAddress;

How to call functions of a contract deployed on hardhat forking mainnet

I am trying to use my own contract's functions deployed to hardhat forking mainnet. To do that I have some steps like this:
I added the forking configuration in hardhat.config.js
networks: {
hardhat: {
forking: {
url: "https://eth-mainnet.alchemyapi.io/v2/<key>",
}
}
}
I ran npx hardhat node in a terminal to start rpc server.
I deployed the contract by using hardhat forking as network. So I took the deployed contract address. I used the network parameter as --network hardhat Then it gave me deployed contract address. This address I guess is in the mainnet forking.
I wrote a js file to interact with this contract and call its functions.(For testing I added a simple pure function in contract, returning a uint256)
const { ethers } = require('ethers');
const provider2 = new ethers.providers.getDefaultProvider('http://127.0.0.1:8545/')
const hrdhatAccountPrivate = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"//owner
const hrdhatAccountPublic = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"//owner
const ERC_20_ABI = require("./erc20_abi.json")
const FORK_MAIN_ABI = [
"function myTestFunction() pure returns (uint256)",
]
const walletFork = new ethers.Wallet(hrdhatAccountPrivate, provider2)
async function main() {
const fundxPoolAddr = '0xBbc18b580256A82dC0F9A86152b8B22E7C1C8005'//forking
const fundxPoolContract = new ethers.Contract(fundxPoolAddr, FORK_MAIN_ABI, provider2)
const fundxPoolContractWithWallet = fundxPoolContract.connect(hrdhatAccountPublic)//walletFork
const tx = await fundxPoolContractWithWallet.myTestFunction()//{gasLimit:300000}
console.log(tx);
}
main()
.catch((error) => {
console.error(error);
process.exitCode = 1;
});
But when I try to run this script (to call contract function), it throws an error.
Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="myTestFunction()", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.6.3)
at Logger.makeError (C:\Users\***\node_modules\#ethersproject\logger\lib\index.js:233:21)
at Logger.throwError (C:\Users\***\node_modules\#ethersproject\logger\lib\index.js:242:20)
at Interface.decodeFunctionResult (C:\Users\***\node_modules\#ethersproject\abi\lib\interface.js:388:23)
at Contract.<anonymous> (C:\Users\***\node_modules\#ethersproject\contracts\lib\index.js:395:56)
at step (C:\Users\***\node_modules\#ethersproject\contracts\lib\index.js:48:23)
at Object.next (C:\Users\***\node_modules\#ethersproject\contracts\lib\index.js:29:53)
at fulfilled (C:\Users\***\node_modules\#ethersproject\contracts\lib\index.js:20:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
reason: null,
code: 'CALL_EXCEPTION',
method: 'myTestFunction()',
data: '0x',
errorArgs: null,
errorName: null,
errorSignature: null,
address: '0xB9d9e972100a1dD01cd441774b45b5821e136043',
args: [],
transaction: {
data: '0xd100387c',
to: '0xB9d9e972100a1dD01cd441774b45b5821e136043',
from: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266'
}
}
When I deploy to --network goerli, it works well. But in --network hardhat it occurs an error. How can I solve this?
I tried to deploy my contract into the goerli testnet, then I called this contract's function and it worked. But for hardhat forking mainnet, it isn't deployed properly or I am doing something wrong during calling the contract's function. Otherwise it wouldn't work in goerli.
When I comment/remove the networks parameters in hardhat.config.js and then start the hardhat forking sw with command line just like this: npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/<key>, it works well. The problem was about network. I had started the forking network and deployed the contract into it. But in my script I was trying to interact with this contract in the local network.
I very thank nick.tran in KyberNetwork Team for his help.

How to inject Binance Wallet into Web3 instead of Metamask?

I started using Binance Chain Wallet in my dapp, so I can now use:
import { BscConnector } from '#binance-chain/bsc-connector'
export const bsc = new BscConnector({
supportedChainIds: [56, 97] // later on 1 ethereum mainnet and 3 ethereum ropsten will be supported
})
// invoke method on bsc e.g.
await bsc.activate();
await bsc.getAccount();
await bsc.getChainId();
but in API docs it says to do some chain operations I need to iject :
The biggest difference between Binance Chain Wallet and MetaMask is we inject BinanceChain rather than ethereum (or web3) to the web page. So user could keep two extensions at the same time.
BinanceChain.request({method: "eth_sign", params: ["address", "message"])
with metamsk I use
ethereum.request(...)
can you explain to me how to do this?
BinanceChain obj is not declared :)
So I figured out that these steps are necessarily :
// create instance of bsc wallet
const bsc = new BscConnector({
supportedChainIds: [56, 97, 1] // later on 1 ethereum mainnet and 3 ethereum ropsten will be supported
})
// get provider out of this instance:
const bsc_provider = await bsc.getProvider()
provider = new ethers.providers.Web3Provider(bsc_provider)
// from here u can use all binance wallet functions:
provider.provider.switchNetwork('eth-mainnet')
see docs:
binance wallet docs

How do I solve the Smart Contract error "returned values aren't valid"?

I am trying to read basic information from a smart contract using web3.js (GRAPH Token):
https://etherscan.io/address/0xc944e90c64b2c07662a292be6244bdf05cda44a7#code
This is my super simple react web3.js setup:
import Web3 from 'web3';
...
useEffect(() => {
const start = async () => {
const web3 = new Web3('https://bsc-dataseed1.binance.org:443')
const abi = [{"inputs":[{"internalType":"uint256","name":"_initialSupply","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"MinterAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"MinterRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"NewOwnership","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"NewPendingOwnership","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"addMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"governor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"isMinter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingGovernor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"uint256","name":"_deadline","type":"uint256"},{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"removeMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newGovernor","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]
const address = '0xc944E90C64B2c07662A292be6244BDf05Cda44a7'
const contract = new web3.eth.Contract(abi, address)
console.log(contract);
const i = await contract.methods.getName().call()
console.log(i); // => ERROR
}
start()
}, [])
And it throws error:
Error: 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.
This is a known and misleading error which usually means that the address or the contract abi is invalid but I verified it is correct.
I researched this error for two days but didn't manage to solve this issue... any suggestions?
You're trying to interact with an Ethereum contract, using a BSC (Binance Smart Chain) Web3 provider (in your case https://bsc-dataseed1.binance.org:443). This results in trying to call the getName() function on the BSC address (which doesn't contain any contract).
Ethereum and BSC are different networks, unrelated to each other.
Solution: Use an Ethereum mainnet provider (for example Infura is widely used).

Truffle migrate success but contract address is not displayed

I am using testrpc to deploy my contracts. Contract deployment is successful and it also displays the contract address in console when it is deployed.
But when I try to query from truffle console it throws this error: Contract has no network configuration for its current network id (5777).
I am clueless. Any help would be much appreciated. I am using Truffle v4.1.0-beta.0 (core: 4.1.0).
Solidity v0.4.19 (solc-js)
You need to return the the deployed contract from the Promise to have the contract object be injected by Truffle. Example:
var Caller = artifacts.require("Caller");
var Callee = artifacts.require("Callee");
module.exports = function(deployer) {
deployer.deploy(Callee).then(function() {
return deployer.deploy(Caller, Callee.address);
});
};