Solidity Tokens Ethers.js Hardhat Hardhat-Deploy – How to Get Address of Deployed Smart Contract in Hardhat

ethers.jshardhathardhat-deploysoliditytokens

I have two files, Token.sol and Token.js for Testing:-

Token.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;
import "hardhat/console.sol";


contract Token{
     string public name ;
     string public symbol ;
     uint256 public decimals = 18;
     uint256 public totalSupply ;

     mapping(address => uint256) public balanceOf;
    
     constructor(string memory _name, string memory _symbol, uint256 _totalSupply){
          name = _name;
          symbol = _symbol;
          totalSupply = _totalSupply * (10 ** decimals);
          balanceOf[msg.sender] = totalSupply; 

     }
}

Token.js

const { ethers } = require("hardhat")
const { expect } = require("chai")


function tokens (n){
    return ethers.parseUnits(n.toString(),'ether')
}


describe('Token', ()=>{

    let token;
    let deployer;
    let accounts;


    beforeEach(async () => {
        const Token = await ethers.getContractFactory('Token');
        token = await Token.deploy('Demo Coin', 'DC', 1000000);
        await token.waitForDeployment();
        accounts = await ethers.getSigners()
        deployer = accounts[0]; 
    });

    describe('Deployment', ()=>{

        console.log('Token Address', token.address)

        it('has correct name', async() =>{
            expect(await token.name()).to.equal('Demo Coin')
        })
    
        it('has correct symbol', async() =>{
            expect(await token.symbol()).to.equal('DC')
        })  
    
        it('has correct decimal', async() =>{
            expect(await token.decimals()).to.equal(18)
        }) 
    
        it('has correct totalSupply', async() =>{
            expect(await token.totalSupply() ).to.equal(tokens(1000000))
        }) 

        it('assigns total supply to deployer', async() =>{
           expect(await token.balanceOf(deployer.address)).to.equal(tokens(1000000))
        }) 
        
    })    
})

To get know the address of deployed smart contract, i am using console.log("Address of Deployed Contract", token.address)

But after running npx hardhat test got the error as :–

TypeError: Cannot read properties of undefined (reading 'address')

What's the reason for this error? Any help genuinely appreciated, thanks!

Best Answer

If you are using ethers version 6 or higher, then you may want to try changing

console.log('Token Address', token.address)

to

console.log('Token Address', token.target)
Related Topic