Issue with Contract Deployment Script
I’m working on a blockchain project and having trouble with my deployment script. When I execute the command npx hardhat run scripts/deploy.js --network localhost, the contract address comes back as undefined instead of showing the actual deployed address.
Expected output:
Deploying contracts with account: [address]
Account balance: [balance]
TOKEN CONTRACT ADDRESS: [actual address]
Actual output:
Deploying contracts with account: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
Account balance: 9999992459571303767619n
TOKEN CONTRACT ADDRESS: undefined
My deployment script:
async function deploy() {
const [signer] = await ethers.getSigners();
console.log("Deploying contracts with account:", signer.address);
console.log("Account balance:", await signer.provider.getBalance(signer.address));
const TokenFactory = await ethers.getContractFactory("MyToken");
const token = await TokenFactory.deploy();
console.log("TOKEN CONTRACT ADDRESS", token.address);
saveContractData(token, "MyToken");
}
function saveContractData(contractInstance, contractName) {
const fs = require("fs");
const dataDir = __dirname + "/../../client/contracts";
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir);
}
fs.writeFileSync(
dataDir + `/${contractName}-address.json`,
JSON.stringify({ address: contractInstance.address }, undefined, 2)
);
const artifact = artifacts.readArtifactSync(contractName);
fs.writeFileSync(
dataDir + `/${contractName}.json`,
JSON.stringify(artifact, null, 2)
);
}
deploy()
.then(() => process.exit(0))
.catch(err => {
console.error(err);
process.exit(1);
});
I tried adding await token.deployed() but got errors saying that method doesn’t exist. How can I properly get the deployed contract address?