MaxOS Monterey 12.3.1 nodejs v16.14.0
Solidityのコードの中でconsole.log()
を使うことでログを取ることができる
console.log()
を使うにはインポートする必要がある
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract Token {
//...
}
JavaScriptで使用するように使うことができる
function transfer(address to, uint256 amount) external {
console.log("Sender balance is %s tokens", balances[msg.sender]);
console.log("Trying to send %s tokens to %s", amount, to);
require(balances[msg.sender] >= amount, "Not enough tokens");
balances[msg.sender] -= amount;
balances[to] += amount;
}
テストでログが出力されているか確認
% npx hardhat test
Compiled 2 Solidity files successfully
Token contract
✔ Deployment should assign the total supply of tokens to the owner (465ms)
Transactions
Sender balance is 1000000000 tokens
Trying to send 50 tokens to 0x70997970c51812dc3a010c7d01b50e0d17dc79c8
Sender balance is 50 tokens
Trying to send 50 tokens to 0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc
✔ Should transfer tokens between accounts (72ms)
...
新しくscriptsフォルダを作りその中にdeploy.jsファイルを入れる
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);
});
networkのパラメーターを指定することで特定のイーサリアムネットワークに接続することができる
npx hardhat run scripts/deploy.js --network <network-name>
networkのパラメーターをつけずに実行するとデプロイは出来ないがコードが機能するかのテストには有用。
npx hardhat run scripts/deploy.js
Deploying contracts with the account: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
Account balance: 10000000000000000000000
Token address: 0x5FbDB2315678afecb367f032d93F642f64180aa3
リモートネットワークにデプロイするためには
require("@nomiclabs/hardhat-waffle");
// Go to https://www.alchemyapi.io, sign up, create
// a new App in its dashboard, and replace "KEY" with its key
const ALCHEMY_API_KEY = "KEY";
// Replace this private key with your Ropsten account private key
// To export your private key from Metamask, open Metamask and
// go to Account Details > Export Private Key
// Be aware of NEVER putting real Ether into testing accounts
const ROPSTEN_PRIVATE_KEY = "YOUR ROPSTEN PRIVATE KEY";
module.exports = {
solidity: "0.8.13",
networks: {
ropsten: {
url: `https://eth-ropsten.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
accounts: [`${ROPSTEN_PRIVATE_KEY}`]
}
}
};
ロプステンネットワークにデプロイする
npx hardhat run scripts/deploy.js --network ropsten
Compiled 1 Solidity file successfully
Deploying contracts with the account: 0x2ea1ABCf8D4f439F03c335acfF61AA02f090b4f1
Account balance: 1100000000000000000
Token address: 0x5D0EDe1E7454f8ce488a61926251da361e22b7e0
--