Encountering BAD_DATA when interacting with smart contract

I have an ERC-20 smart contract that I've created. I'm trying to deploy and interact with it locally using hardhat and ethers. Deployment is successful, however, I keep getting an error when interacting with it (scripts/interact.ts).

contracts/MyToken.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyToken is ERC20, Ownable {

    constructor(
        string memory _name, 
        string memory _symbol,
        address _new_owner
    ) ERC20(_name, _symbol) {
        _transferOwnership(_new_owner);
    }
    // rest of the code

scripts/interact.ts

import { ethers } from "hardhat";
import contractBuild from "../artifacts/contracts/MyToken.sol/MyToken.json";
import * as dotenv from "dotenv";
dotenv.config({ path: __dirname+'/.env' });

async function main() {
  const CONTRACT_ADDRESS: string = process.env.CONTRACT_ADDRESS ?? 'contract-address';
  const ALCHEMY_API_KEY: string = process.env.ALCHEMY_API_KEY ?? 'api-key';
  const PRIVATE_KEY: string = process.env.PRIVATE_KEY ?? 'private-key';

  // Provider
  // const provider = new ethers.AlchemyProvider("goerli", ALCHEMY_API_KEY);
  const provider = ethers.provider;

  // Signer
  const signer = new ethers.Wallet(PRIVATE_KEY, provider);

  // Contract
  const contract = new ethers.Contract(CONTRACT_ADDRESS, contractBuild.abi, signer);

  // Get contract name
  console.log(await contract.name());
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

An alternative version of the main function above that I used is:

  const contractAddress = ...
  const token = await ethers.getContractAt("MyToken", contractAddress);
  console.log(await token.name());

However, both return the error:

Error: could not decode result data (value="0x", info={ "method": "name", "signature": "name()" }, code=BAD_DATA, version=6.5.1)
    ...
  code: 'BAD_DATA',
  value: '0x',
  info: { method: 'name', signature: 'name()' }
}

This also occurs in the hardhat console. What could the problem and solution be?

Sounds like the problem is that there is no contract deployed at the given address.

Or perhaps there is, but it doesn't implement a public or external function name().

2 Likes

Thanks! The first suggestion made me re-think the network I'm using. I thought dev network was called with --network hardhat. Turns out default is --network localhost, which isn't in the hardhat config. New to hardhat :sweat_smile: