Blockchain name using ethers js - ethereum

Is there a way to check name of current blockchain using ethers js
For example
const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
const chainInfo = await providers.getNetwork()
gives chain Id and network name but not the blockchain name as etherum or polygon etc

you can use detectNetwork. You make request to RPC server, so the "name" property depends on the response of the RPC server. For example if you make request binance mainnet
const provider = new ethers.providers.JsonRpcProvider(
"https://bsc-dataseed.binance.org"
);
const a = provider.detectNetwork().then((x) => console.log(x));
you will get this:
{
"name": "bnb",
"chainId": 56,
"ensAddress": null,
"_defaultProvider": null
}
But if you make request to "avalance"
const provider = new ethers.providers.JsonRpcProvider(
"https://api.avax.network/ext/bc/C/rpc"
);
const a = provider.detectNetwork().then((x) => console.log(x));
you will get this:
{
"chainId": 43114,
"name": "unknown"
}
It really depends on how the RPC server response is configured. you can find rpc endpoints here
Or you can create a mapping for the most popular networks
const NETWORKS: { [k: string]: string } = {
1: "Ethereum Main Network",
5: "Goerli Test Network",
42: "Kovan Test Network",
56: "Binance Smart Chain",
1337: "Ganache",
};
once you get the chainId, you can return
NETWORKS[chainId]

Related

Reading smart contract function - what am I doing wrong?

I'm trying to read total supply from this smart contract, I have checked the ABI and the read does not require arguments. Why am I getting this error?
Imported the ABI from Etherscan with a valid API key
Connected Infura node with valid api.
Please help. I'm new!
Error:
Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="TOTAL_SUPPLY()", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)
reason: null,
code: 'CALL_EXCEPTION',
method: 'TOTAL_SUPPLY()',
data: '0x',
errorArgs: null,
errorName: null,
errorSignature: null,
address: '0xFc7a5BD22dFc48565D6f04698E566Dd0C71d3155',
args: [],
transaction: {
data: '0x902d55a5',
to: '0xFc7a5BD22dFc48565D6f04698E566Dd0C71d3155',
from: '0xa9519a76981489Cf44a6b1023C53EA674B9365fB'
}
}
CODE:
const ethers = require("ethers");
async function main() {
// make an API call to the ABIs endpoint
const response = await fetch('https://api.etherscan.io/api?module=contract&action=getabi&address=0x31Cd7378715174e2c5Bd7EDF9984c9bC2A9209Eb&apikey=xxx');
const data = await response.json();
let abi = data.result;
/*console.log(abi);*/
// creating a new Provider, and passing in our node URL
const node = "https://mainnet.infura.io/v3/xxx";
const provider = new ethers.providers.JsonRpcProvider(node);
// initiating a new Wallet, passing in our private key to sign transactions
let privatekey = "xxx";
let wallet = new ethers.Wallet(privatekey, provider);
// print the wallet address
console.log("Using wallet address " + wallet.address);
// specifying the deployed contract address
let contractaddress = "0xFc7a5BD22dFc48565D6f04698E566Dd0C71d3155";
// initiating a new Contract
let contract = new ethers.Contract(contractaddress, abi, wallet);
console.log("Using contract address " + contract.address);
// calling the "retrieve" function to read the stored value
let supply = await contract.TOTAL_SUPPLY();
console.log("Value stored in contract is " + supply.toString());
You're retrieving ABI of address 0x31Cd7378715174e2c5Bd7EDF9984c9bC2A9209Eb on the Ethereum mainnet.
Your ethers provider correctly connects to the Ethereum mainnet.
But then it's trying to interact (call function TOTAL_SUPPLY()) with contract on address 0xFc7a5BD22dFc48565D6f04698E566Dd0C71d3155.
Since there's no contract on the 0xFc... address on the Ethereum mainnet, the call fails.
Have u tried web3client.app.
You can test any abi methods across 500+ chains in any smart contracts.
Identify which network your contract resides and do test it out.
It has code generate feature that lets you to easily get a bug free high quality code

sending a transaction requires a signer

I have an NFT Contract and I need to mint NFTs. Also I have a second contract
for handling buying and selling NFTs into this contract.
I am using the ethers library.
this is my code for config:
static async Initial(): Promise<any> {
let provider = new ethers.providers.JsonRpcProvider(config.contractConfig.url);
const signer = provider.getSigner();
this.tokenContract = new ethers.Contract(config.contractConfig.nftAddress, NFT.abi, provider);
this.dNFT = new ethers.Contract(config.contractConfig.dortajNftAddress, DNFT.abi, signer);
}
config address:
export default {
nftAddress: '0x444F15B115ED9663DAE46786a34AA3F6E8c0B57D',
dortajNftAddress: '0x8e4bE2a3BD1169596c38952D8e837b20D419Bcd1',
url : 'HTTP://127.0.0.1:7545'
}
now i need to use this function for mint nft :
let transaction = await this.tokenContract.mintToken();
const tx = await transaction.wait();
but it show me this error:
Error: sending a transaction requires a signer (operation="sendTransaction", code=UNSUPPORTED_OPERATION, version=contracts/5.5.0)
How can I solve this problem?
In this line
this.tokenContract = new ethers.Contract(config.contractConfig.nftAddress, NFT.abi, provider);
try to pass signer instead of provider.

How to get access to specific metadata of a ERC721 token

I would like to get n ERC721 token with a specific "dna".
See the metadata below:
{
"dna": "602472F",
"name": "Test #1",
"description": "My Collectibles",
"image": "ipfs://QmasMm8v9WkU11BtnWsybDW6/1.png",
"edition": 1,
"attributes": [
{
"trait": "type",
"value": "Fire"
},
{
"trait_type": "Eyes",
"value": "Black"
}
]
}
I know how to access a token using tokenURI.
Here is my code:
string public uri;
string public uriSuffix = ".json";
function _baseURI() internal view virtual override returns (string memory) {
return uri;
}
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory){
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : "";
}
Now, how can I check if a token has the dna I am looking for? Should I get this info from Opensea API or from the solidity side?
Ps: All my .json and .png files are hosted in IPFS.
EVM contracts are not able to read offchain data (the JSON file) directly. You'd need to use an offchain app (or an oracle provider such as Chainlink) for that to feed the offchain data to the contract.
So it's much easier to just query the data from an offchain app.
Example using node.js and the web3 package for querying the contract:
const contract = new web3.eth.Contract(abiJson, contractAddress);
const tokenURI = await contract.methods.tokenURI(tokenId);
const contents = (await axios.get(tokenURI)).data;
return contents.dna;

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

Switch Metamask Network to chain 1 (Ethereum Mainnet)

This past week Metamask introduced a new function called "wallet_addEthereumChain" which allows the user to automatically add a new Etheruem RPC to their wallet when prompted. This function also allows the user to change the network they are connected to, for example, if I already have Binance Smart Chain connected to metamask, calling wallet_addEthereumChain changes the active network to BSC. However, when trying this for the Ethereum chain, it gives an error that you cannot add mainnet RPC.
I have used the following code to change to change from Ethereum Mainnet to Binance Smart Chain, and it works fine:
switchToBinance: async function () {
let ethereum = window.ethereum;
const data = [{
chainId: '0x38',
chainName: 'Binance Smart Chain',
nativeCurrency:
{
name: 'BNB',
symbol: 'BNB',
decimals: 18
},
rpcUrls: ['https://bsc-dataseed.binance.org/'],
blockExplorerUrls: ['https://bscscan.com/'],
}]
/* eslint-disable */
const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch()
if (tx) {
console.log(tx)
}
},
However when I try the Exact thing, metamask throws an exception saying I cannot add a mainnet RPC:
switchToEthereum: async function () {
let ethereum = window.ethereum;
const data = [{
chainId: '0x1',
chainName: 'Ethereum',
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: ['https://mainnet.infura.io/v3/undefined'],
blockExplorerUrls: ['https://etherscan.io'],
}]
/* eslint-disable */
const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch()
if (tx) {
console.log(tx)
}
},
However, the request for adding a new RPC connection, and changing the active RPC connection is the same. So is there a way to change the active Ethereum provider from a custom chain to Mainnet (chain ID-1)
as this issue comment point, for security reason wallet_addEthereumChain not support mainnet. But there a new EIP to resolve this issue, follow EIP-3326 to find release info, and this discuss to see draft progrss.
chainId: '0x38' // error because await not decimal
Number('0x38').toString(10) //56 - chain ID of BSC
Right:
chainId: `0x${Number(56).toString(16)}`
OR:
chainId: `0x86`
Simply you have to prefix 0x with the chainId.
Example:
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x1' }],
})