I have deployed a smart contract on a public testnet and now I am trying to connect to it from the front end using ethers js. But when I try to fetch the value it gives the following errors in the console:
I am using Angular for the front end and here's the code I wrote:
declare let window: any;
import { Component, OnInit } from '@angular/core';
import { ethers } from 'ethers';
import addresses from '../../environment/contract-address.json'
import Election from '../../blockchain/artifacts/blockchain/contracts/Election.sol/Election.json'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'angvote';
public signer: any;
public electionContract: any;
public candidate : any;
public candidatesList:string[] | undefined;
constructor(){}
async ngOnInit(){
const provider = new ethers.providers.Web3Provider(window.ethereum);
window.ethereum.enable()
provider.on("network",(newNetwork: any, oldNetwork: any)=>{
if (oldNetwork){
window.location.reload();
}
});
this.signer = provider.getSigner();
if(await this.signer.getChainId() !== 4){
alert("Please change your network to Rinkeby!")
}
this.electionContract = new ethers.Contract(addresses.electioncontract,Election.abi,this.signer);
this.candidate = await this.electionContract.candidatesCount();
}
}
I have encountered the same error. I had not changed the contract address once I deployed it to the testnet(Previously I deployed to localhost). Just check if the contract address you are using is of the contract you deployed to the testnet.