I have smartcontract from HardHat tutorial https://hardhat.org/tutorial/writing-and-compiling-contracts.html
and I successfully deployed it.
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const Token = await ethers.getContractFactory("Token");
const token = await Token.deploy();
console.log("Token address:", token.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
But only the address of the contact is returned to me and its private key is not.
console.log("Deploying contracts with the account:", deployer.address);
How can I get the private key in this way? I need it for the method
web3.eth.accounts.wallet.add('0x<private_key>');
Because otherwise I can't call the transfer method on the smart contract.
Not possible by design.
A contract address is determined from the deployment transaction params. Specifically, the ethers
deploy()
function is using the CREATE
opcode by default, so the contract address is determined from the deployer address and the deploying transaction nonce
param.
But the private key to the contract address is never generated during the deployment - so it can't be returned. Just the address.
Because otherwise I can't call the transfer method on the smart contract.
Correct. If you want to transfer funds out of the contract, you need to implement a function to be able to do that.
pragma solidity ^0.8;
contract MyContract {
// transfers the entire balance of this contract to the `msg.sender`
function widthdraw() external {
require(msg.sender == address(0x123), "Not authorized");
payable(msg.sender).transfer(address(this).balance);
}
}