// Token.sol // SPDX-License-Identifier: MIT // The line above is recommended and let you define the license of your contract // Solidity files have to start with this pragma. // It will be used by the Solidity compiler to validate its version. pragma solidity ^0.7.0;
// This is the main building block for smart contracts. contract Token { // Some string type variables to identify the token. // The `public` modifier makes a variable readable from outside the contract. string public name = "My Hardhat Token"; string public symbol = "MBT";
// The fixed amount of tokens stored in an unsigned integer type variable. uint256 public totalSupply = 1000000;
// An address type variable is used to store ethereum accounts. address public owner;
// A mapping is a key/value map. Here we store each account balance. mapping(address => uint256) balances;
/** * Contract initialization. * * The `constructor` is executed only once when the contract is created. */ constructor(address _owner) { // The totalSupply is assigned to transaction sender, which is the account // that is deploying the contract. balances[_owner] = totalSupply; owner = _owner; }
/** * A function to transfer tokens. * * The `external` modifier makes a function *only* callable from outside * the contract. */ functiontransfer(address to, uint256 amount) external { // Check if the transaction sender has enough tokens. // If `require`'s first argument evaluates to `false` then the // transaction will revert. require(balances[msg.sender] >= amount, "Not enough tokens");
// Transfer the amount. balances[msg.sender] -= amount; balances[to] += amount; }
/** * Read only function to retrieve the token balance of a given account. * * The `view` modifier indicates that it doesn't modify the contract's * state, which allows us to call it without executing a transaction. */ functionbalanceOf(address account) external view returns (uint256) { return balances[account]; } }
编译:
终端运行
1
yarn hardhat compile
输出
1 2 3 4
yarn run v1.22.10 $ /Users/cool-erc20/demo/node_modules/.bin/hardhat compile Compiled 1 Solidity file successfully ✨ Done in 5.25s.
$ yarn hardhat deploy yarn run v1.22.10 $ /Users/cool-erc20/demo/node_modules/.bin/hardhat deploy Nothing to compile deploying "Token" (tx: 0x453cf83db75329816a62d6079aa22f694036d339106344b7e1864bcb344aa49d)...: deployed at 0x5FbDB2315678afecb367f032d93F642f64180aa3 with 483242 gas ✨ Done in 5.60s.