在終端輸入
truffle create contract MyToken
創建

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract MyToken {
uint INITIAL_SUPPLY = 10000;
mapping(address => uint) balances;
constructor() {
balances[msg.sender] = INITIAL_SUPPLY;
}
// transfer token for a specified address
function transfer(address _to, uint _amount) public {
require(balances[msg.sender] > _amount);
balances[msg.sender] -= _amount;
balances[_to] += _amount;
}
// Get the balance of the specified address
// Constant and Immutable State Variables. See https://docs.soliditylang.org/en/v0.8.10/contracts.html#modifiers
function balanceOf(address _owner) public view returns (uint) {
return balances[_owner];
}
}
在migrations資料夾新增
var HelloWorld = artifacts.require("HelloWorld");
var MyToken = artifacts.require("MyToken");
module.exports = function(deployer) {
deployer.deploy(HelloWorld);
deployer.deploy(MyToken);
};
編譯
truffle compile

開始部署,Run
truffle migrate


Test
開啟console
truffle console
let contract
MyToken.deployed().then(instance => contract = instance)

contract.balanceOf(accounts[0])
contract.balanceOf(accounts[1])

contract.transfer(accounts[1], 123)
contract.balanceOf(accounts[0])
contract.balanceOf.call(accounts[1])

---
使用Remix測試:
(可以參考前面: {% post_link Remix-On-Vscode '在VSCode上使用Remix' %})
1.啟動ganache-cli

2.使用remix連接local測試網

3.編譯並部屬

4.測試
先呼叫部屬者,並從output中觀察結果

接著轉5000,測試轉帳功能


再看一次部屬者的Balance


最後看轉Token過去的account

完成,簡單的token生成與轉移token已經實現,但一般的Token我們會使用**ERC20**,而不會像這樣實現陽春的功能,會使用更嚴謹的方式來防止漏洞。
歡迎大家來我的Blog看:
1.Blog: 文章連結