本文由以太坊官方文档翻译
有不正之处欢迎指正。可留言或者发送我的邮箱:i@tangc.me
转载此翻译需要注明来源本站。
代币
我们将要创建一个数字代币(Token). 在以太坊生态中的代币可以象征任何可替代的、可买卖的行为:货币,可信任节点,黄金凭证,各种借据凭证,游戏道具等等。由于所有的代币都通过通用的标准实现基本特点,这也就意味着你按此标准创造出来的代币就可以立马和以太坊钱包、其它轻钱包或者同样标准的合约相兼容。
最小可行代币
标准优秀的代币合约可能是相当复杂的,但是实质上一个很基础的代币可以浓缩成如下代码所示:
contract MyToken {
mapping (address => uint256) public balanceOf;
function MyToken(
uint256 initialSupply
) {
balanceOf[msg.sender] = initialSupply;
}
function transfer(address _to, uint256 _value) {
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
}
代码THE CODE
当然,如果你只是想要复制粘贴一段完整的代码,那么你就用这个:
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
理解代码
这样,让我们从最基本的开始。打开以太坊钱包,到 合约(CONTRACTS) 选项,然后在下面选择 部署新合约(DEPLOY NEW CONTRACT) ,在合约原始代码文本框里编写如下代码:
contract MyToken {
mapping (address => uint256) public balanceOf;
}
一个 mapping 表示一个关联数组,一个拥有余额的地址。这个地址是一个基本十六进制的以太坊形态,当地址里的余额是整数时,可从0到115 quattuorvigintillion. 如果你不知道一个 quattuorvigintillion 是多少, 是很多个 vigintillions(译者:1后面跟63个0) 反正超过你想发行的代币数量。 关键词 public , 意思是这个变量是公开的,可以被区块链上的任何人访问,这就意味着所有的余额都是公开的。(其它应用客户端都可以显示这个余额了)
如何你现在立刻发布你的这个合约,它可以工作但是好像并不是那么有用:它将会是一个可以查询任何地址上你发行代币余额的合约。但是你永远不会创建一个这么单一的代币,每个拥有它的人余额永远是0. 因此我们将要在启动处创建一些代码。 在最后大括号前,mapping下面一行加上如下代码:
function MyToken() {
balanceOf[msg.sender] = 21000000;
}
注意 MyToken 这个方法必须和 contract MyToken 同名。这是非常重要的,并且如果你要重名一个,那个也要跟着变。这是一个很特别的方法,这个启动函数仅只执行一次,且在合约首次部署到以太坊主网络上。这个方法将设置合约的创建者拥有代币的全部,即拥有2100万个代币余额。
2100万这个选择我们更希望它是可任意设置的,你可以在代码里随意修改这个值。但是我们一个更好的方法,将这个数设置成一个变量参数。像这样:
function MyToken(uint256 initialSupply) {
balanceOf[msg.sender] = initialSupply;
}
看一眼合约右边的列,你会看见 选择合约 一个下拉选择,选择 “MyToken” 你会看见一个 Constructor parameters 区域,这些都是代币合约的可改变参数,你可以在将来用同样的代码重复使用只需要改变几个值就可以。
现在你已经拥有一个有余额的功能性的合约,但是你好像还是没有办法去转移这个余额,它只能始终在创建者一个账户里。因此,我们现在将要实现这个功能,在最后大括号前加上如下代码:
function transfer(address _to, uint256 _value) {
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
这是一个很直接明了的方法:它有一个 接受者 和 数量 作为参数,不管何时有人调用它,它将从调用者余额里扣除 _value 并在 _to 增加同样的余额数 _value . 可是立马有个显而易见的问题出现了: 当一个人想发送超过他账户里余额的数量时会发生什么?因为我们不想在这个特别的合约里去处理负债问题,我们将简单快速地做一个校验:如果发送者没有足够的资金那合约就停止执行。这也同样可以校验溢出问题从而避免大额再变成0.
为了阻止合约的执行,你可以用 return or throw 这种形式会花费很少的GAS 但这可能会让你更头疼,你对合约做的任何改变都会被记录保存. 另一方面“throw”将取消所有的合约执行,交易已经回滚但是发送者为GAS发送的以太币将失去. 但是由于钱包可以检测一个合约 抛出异常,所以它总是会显示一条警告 防止你的以太币被浪费掉。
function transfer(address _to, uint256 _value) {
require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
现在确实的是关于合同的一些基本信息。在不久的将来,这可以由一个代币注册处来实现,但是现在我们将直接把它们加入到合约中:
string public name;
string public symbol;
uint8 public decimals;
现在我们更新构造函数,以允许在开始时设置所有这些变量:
function MyToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) {
balanceOf[msg.sender] = initialSupply;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
}
最后,我们需要一些所谓的事件。这些特殊、空的函数,您可以调用它们来帮助像以太坊钱包这样的客户端去跟踪合约中发送的活动。事件应该以大写字母开头。在合约的开头我们需要提前声明事件:
event Transfer(address indexed from, address indexed to, uint256 value);
然后你只需要在 “transfer” 这个方法中增加下面两行:
Transfer(msg.sender, _to, _value);
至此,你的代币已经准备好了!
你可能会问那些 @notice 和 @param 那些注释是什么? 那是 Natspec 一个自然语言规法的新兴标准, 它允许钱包向用户展示合约要做的语言描述。虽然目前很多钱包目前还不支持,但是这在将来会改变的。提前做好准备是个好事。
如何部署
如果你已经准备好了,打开以太坊钱包,到合约选项页。然后点击 部署新合约。
现在从上面的代码我们粘贴到 Solidity源码编辑器中,如果代码编译没有任何错误,你可以看到 选择一个合约 的下拉选择。我们点击下拉 选择 “MyToken” 这个合约. 在右侧列表的下面你会看到所有的关于你代币的个人定制化参数。你可以按你要求进行调整,但是为了这个教程我们建议您选择这些参数 :
supply:10000
name :随便起一个
symbol: %
decimal:2
你的软件应该是像这样的:
滚动到页面的末尾,你会看到创建这个合约所需要的成本估计,你可以选择你愿意支付多少以太坊作为费用。超额的以太坊会返回给你,你可以保留默认的设置,点击发送部署。输入你的密码并等待几秒钟以便你的交易被记录。
你将会被重定向到前端页面,这里你可以看到你创建合约的交易正在等待确认。点击被命名为 “Etherbase” 的账户(你的主账户)你会发现你的账户将显示你已经拥有了你刚刚创建的 100%股份。发送一些给你的一些朋友:
选择 发送
选择你想发送的货币(以太或者你刚创建的份额),将你朋友的地址粘贴到 To 下面文本框 并按下 发送。
如果你把代币发送给一个朋友,他的钱包里是看不到任何东西的。这样因为以太坊钱包只追踪它所知道的代币。所以你必须手动添加这些。现在切换到 合约 界面 ,你会看到一个 你刚部署合约 链接。点击跳转页面,因为这是一个很简单的合约没有什么太多可做的,你只需要点击 复制地址,然后找个文本编辑器保存好地址,因为我们一会会用到它。
添加一个代币进行查看,到合约页面 然后点击 查看代币(Watch Token). 一个弹出窗口会出现,你需要粘贴刚才的合约地址到第一行。然后 token name, symbol and decimal number 这些会自动显示出来。但是如果不是,你可以设置你想要的 (它仅仅只影响在你当前钱包里的显示). 一旦做好这,你的钱包就会自动显示这个代币的余额,你就可以把它发送给其他人。
现在你有了属于自己的加密代币!代币可以作为价值交换 在你的社区,可以支付工作小时和其它绩效考核。但是,我们能否让代币具有内在价值,让它更有用呢?
提高代币价值
你可以在不触及一行代码的情况下部署整个加密代币,但是当你开始定制时真正的神奇正在发生。接下来的章节里功能建议,你可以加到你的代币里让它更适合你的需要。
更多的基础功能
你将注意到,在你基本代币合约中有一些更多的函数,像 approve, sendFrom 和其它函数. 这些函数用户您的代币和其它合约进行交互:如果你想卖一些代币给一个去中心化的交易所,只发送给他们一个地址是不够的。因为合约不能通过订阅时间来调用函数 。因此,对于合约,你首先应该批准他们可以从你的账户中移动的数量,然后通知他们让他们知道应该做的事 或者 做的动作 用 approveAndCall
因为许多这样的函数都不得不重新实现代币的传输,让它们转换一个内置函数是有意义的,让只能由合约自身调用。
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
现在你代币转让的所有功能可以自己做检查,然后用正确的参数调用 transfer . 注意,该方法把代币从任何其它账户转到另一个账户,不需要任何人权限的原因在于:它是一个内部函数,只有合同本身可以调用。 如果你添加任何函数调用它,要确保调用者有授权。
集中管理
所有 dapps 默认都是去中心化的,但这并不意味着他们不可以拥有某种集中管理。如果你想要,这完全可以。也许你想铸造更多的货币,也许你想禁止一些人使用你的货币,你可以添加任何这些特性. 但是,关键是你必须在开始就加上这些功能,所以所有代币持有者在决定拥有一个代币前已经知道这个代币所有的规则。
要实现这一点,你需要一个货币的中央控制者。这可以是一个简单的账户,但也可以是一个合约, 因此决定创造更多代币将取决于合约:如一个自治组织通过投票或者限制代币拥有者的权力。
为了实现那样的功能,我们将学习一个非常有用的合约属性:继承 。继承允许一个合约继承父合约的所有属性。而不需要再重新定义它们。这使得代码更简洁更重复易用。加上这些代码在第一行 在 contract MyToken {. 前面
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
这就创建了一个基本合约,除了定义一些通用函数外没有做任何事。现在,下一步我们将文本 is owned 加到我们的合约中:
contract MyToken is owned {
这意味着在 MyToken 中的所有方法都可以访问 owner 和modifier onlyOwner. 这个合约还具有转移所有权的功能. 因为在启动时直接设置所有者可能会很有趣,你也可以将这些加入到构造函数里:
function MyToken(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
address centralMinter
) {
if(centralMinter != 0 ) owner = centralMinter;
}
中央铸币厂
假设你想要改变正在流通中代币数量。举个例子:当你的代币已经代表了一个区块链资产(黄金凭证、法币)时,你希望虚拟库存反映真实库存。这也可能是另一个案例:当货币持有者期望对代币进行价格控制,增发或者废除一些流通中的代币。
首先我们要加一个变量 totalSupply 来存储总数,并在构造函数里进行赋值。
contract MyToken {
uint256 public totalSupply;
function MyToken(...) {
totalSupply = initialSupply;
...
}
...
}
现在让我们添加一个新的功能,它将使所有者能够创建新的代币:
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
请注意,在函数名的末尾有一个 onlyOwner 。这意味着该函数将在编译时重写,以从我们之前定义的 modifier onlyOwner 中继承代码。该函数的代码将插入到 modifier 函数 并有一个下划线,这意味着该函数只能由设置为所有者的帐户调用。只需将其添加到与所有者修改器的合约中,您就可以创建更多的货币。
冻结资产
根据您的用例,您可能有对谁使用,谁不使用您的代币进行一些管理上的障碍。为此,您可以添加一个参数,使合同所有者可以冻结或解冻资产。
在合约中添加这个变量和函数。您可以将它们放到任何地方,但是我们建议您将映射与其他映射 和事件与其他事件放在一起。
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
有了这个代码,所有帐户默认都是未冻结的,但是所有者可以通过调用冻结帐户将任何帐户设置为冻结状态。不幸的是,冻结没有实际效果,因为我们没有给传递函数添加任何东西。我们现在就可以改变这点了:
function transfer(address _to, uint256 _value) {
require(!frozenAccount[msg.sender]);
现在任何冻结的账户都将保留其资金,但无法移动它们。默认情况下,所有帐户都是未冻结的,除非您冻结它们,但是您可以很容易地将该行为转换为白名单,您需要手动审批每个帐户。将frozenAccount重新命名为approvedAccount并更改最后一行:
require(approvedAccount[msg.sender]);
自动买卖
到目前为止,您已经依赖于实用程序和信任来评估您的代币。但是,如果你想让这个代币的价值得到以太(或其他代币)的支持,就会创建一个基金,它可以以市场价自动买卖。
首先,让我们设置买卖的价格:
uint256 public sellPrice;
uint256 public buyPrice;
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
这是可以接受的价格,不会经常改变,因为每一个新的价格变化将要求你执行一个交易和花费一点以太。如果你想要一个恒定的浮动价格,我们建议你调查标准的数据输入(standard data feeds)
下一步实现买卖功能:
function buy() payable returns (uint amount){
amount = msg.value / buyPrice;
require(balanceOf[this] >= amount);
balanceOf[msg.sender] += amount;
balanceOf[this] -= amount;
Transfer(this, msg.sender, amount);
return amount;
}
function sell(uint amount) returns (uint revenue){
require(balanceOf[msg.sender] >= amount);
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
revenue = amount * sellPrice;
require(msg.sender.send(revenue));
Transfer(msg.sender, this, amount);
return revenue;
}
注意这不会创建新的代币,而是更改合约的余额。合约可以同时拥有自己的代币和以太币以及合同所有者,当它可以设置价格,或者在某些情况下创建新的代币(如果可以的),它不能触及本来存储的代币和以太币。这个合约转移资金的唯一方式就是出售和购买。
备注:买卖的价格不是用 以太币 为单位的,而是用以太生态系统里的最小计量单位: wei (相当于欧元和美元的分,或者比特币的 satoshi)。一个ETH = 1000000000000000000 wei. 所以在设定价格的时候你要在结尾加18个0。
当创建合约时,要发送足够的ETH,这样它就可以在市场上买回所有的代币,否则你的合同就会破产,你的用户将无法出售他们的代币。
当然前面的例子描述的是一个单一集中的买家和卖家的合约。一个更有趣的合约会允许一个任何人出不同价格,或者从外部直接报价的市场。
AUTOREFILL
每次你在以太坊上发起一个交易时,你都需要给区块记账的矿工一笔费用,那样才能创建你的智能合约。虽然这可能在将来会改变,不过目前你还是要用ETH去支付,所有持有你代币的用户也同样需要。合约的代币持有者如果没有ETH会被卡住直到有足够的费用。但在一些情况下,你可能不想让用户考虑以太坊,区块链或者如何支付多少ETH,你可以让以太坊自动填充用户的余额。
为了做到这点,你需要创建一个变量,该变量有个阈值并且有个函数可以更改。如果你不知道任何值,将它设置成 5 finney (0.005 ether).
uint minBalanceForAccounts;
function setMinBalance(uint minimumBalanceInFinney) onlyOwner {
minBalanceForAccounts = minimumBalanceInFinney * 1 finney;
}
然后,把这行加到 transfer 函数中,这样发送者就能得到退款:
function transfer(address _to, uint256 _value) {
...
if(msg.sender.balance < minBalanceForAccounts)
sell((minBalanceForAccounts - msg.sender.balance) / sellPrice);
}
你也可以更改它让这笔费用由发送方支付给接收者:
function transfer(address _to, uint256 _value) {
...
if(_to.balance<minBalanceForAccounts)
_to.send(sell((minBalanceForAccounts - _to.balance) / sellPrice));
}
这会确保任何接收代币的用户没必要支付费用。
PROOF OF WORK
There are some ways to tie your coin supply to a mathematical formula. One of the simplest ways would be to make it a “merged mining” with ether, meaning that anyone who finds a block on ethereum would also get a reward from your coin, given that anyone calls the reward function on that block. You can do it using the special keyword coinbase that refers to the miner who finds the block.
function giveBlockReward() {
balanceOf[block.coinbase] += 1;
}
It’s also possible to add a mathematical formula, so that anyone who can do math can win a reward. On this next example you have to calculate the cubic root of the current challenge gets a point and the right to set the next challenge:
uint currentChallenge = 1;
function rewardMathGeniuses(uint answerToCurrentReward, uint nextChallenge) {
require(answerToCurrentReward**3 == currentChallenge);
balanceOf[msg.sender] += 1;
currentChallenge = nextChallenge;
}
Of course while calculating cubic roots can be hard for someone to do on their heads, they are very easy with a calculator, so this game could be easily broken by a computer. Also since the last winner can choose the next challenge, they could pick something they know and therefore would not be a very fair game to other players. There are tasks that are easy for humans but hard for computers but they are usually very hard to code in simple scripts like these. Instead a fairer system should be one that is very hard for a computer to do, but isn’t very hard for a computer to verify. A great candidate would be to create a hash challenge where the challenger has to generate hashes from multiple numbers until they find one that is lower than a given difficulty.
This process was first proposed by Adam Back in 1997 as Hashcash and then was implemented in Bitcoin by Satoshi Nakamoto as Proof of work in 2008. Ethereum was launched using such system for its security model, but is planning to move from a Proof of Work security model into a mixed proof of stake and betting system called Casper.
But if you like Hashing as a form of random issuance of coins, you can still create your own ethereum based currency that has a proof of work issuance:
bytes32 public currentChallenge;
uint public timeOfLastProof;
uint public difficulty = 10**32;
function proofOfWork(uint nonce){
bytes8 n = bytes8(sha3(nonce, currentChallenge));
require(n >= bytes8(difficulty));
uint timeSinceLastProof = (now - timeOfLastProof);
require(timeSinceLastProof >= 5 seconds);
balanceOf[msg.sender] += timeSinceLastProof / 60 seconds;
difficulty = difficulty * 10 minutes / timeSinceLastProof + 1;
timeOfLastProof = now;
currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1));
}
Also change the Constructor function (the one that has the same name as the contract, which is called at first upload) to add this line, so the difficulty adjustment will not go crazy:
timeOfLastProof = now;
Once the contract is online, select the function “Proof of work”, add your favorite number on the nonce field and try to execute it. If the confirmation window gives a red warning saying “Data can’t be execute” go back and pick another number until you find one that allows the transaction to go forward: this process is random. If you find one you will be awarded 1 token for every minute that has passed since the last reward was given, and then the challenge difficulty will be adjusted up or down to target an average of 10 minutes per reward.
This process of trying to find the number that will give you a reward is what is called mining: if difficulty rises it can be very hard to find a lucky number, but it will always be easy to verify that you found one.
Improved Coin
FULL COIN CODE
If you add all the advanced options, this is how the final code should look like:
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract MyAdvancedToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
}
部署
Scroll down and you’ll see an estimated cost for deployment. If you want you can change the slider to set a smaller fee, but if the price is too below the average market rate your transaction might take longer to pick up. Click Deploy and type your password. After a few seconds you’ll be redirected to the dashboard and under Latest transactions you’ll see a line saying “creating contract”. Wait for a few seconds for someone to pick your transaction and then you’ll see a slow blue rectangle representing how many other nodes have seen your transaction and confirmed them. The more confirmations you have, the more assurance you have that your code has been deployed.
点击 管理页面 你会的得到世界上最简单的中央银行仪表台,在这你可以用创建的货币做任何你想做的事。
在合同的左边,你有所有的选项和功能,你可以免费阅读合约的信息,如果您的代币拥有一个所有者,它将在这里显示它的地址。复制该地址并将其粘贴到余额中,它将显示任何帐户的余额(余额也会自动显示在任何有代币的帐户页面上)。
在右边,在Write to Contract下,你将看到所有可以用来改变或改变区块链的函数。这些操作会花费gas 。如果你创造了一个允许你铸造新硬币的合同,你应该有一个叫做“mint Token”的功能。选择它。
Select the address where those new currencies will be created and then the amount (if you have decimals set at 2, then add 2 zeros after the amount, to create the correct quantity). On Execute from select the account that set as owner, leave the ether amount at zero and then press execute.
After a few confirmations, the recipient balance will be updated to reflect the new amount. But your recipient wallet might not show it automatically: in order to be aware of custom tokens, the wallet must add them manually to a watch list. Copy your token address (at the admin page, press copy address) and send that to your recipient. If they haven’t already they should go to the contracts tab, press Watch Token and then add the address there. Name, symbols and decimal amounts displayed can be customized by the end user, especially if they have other tokens with similar (or the same) name. The main icon is not changeable and users should pay attention to them when sending and receiving tokens to ensure they are dealing with the real deal and not some copycat token.
Using your coin
Once you’ve deployed your tokens, they will be added to your list of watched tokens, and the total balance will be shown on your account. In order to send tokens, just go to the Send tab and select an account that contains tokens. The tokens the account has will be listed just under Ether. Select them and then type the amount of tokens you want to send.
If you want to add someone else’s token, just go to the Contracts tab and click Watch token. For example, to add the Unicorn (🦄) token to your watch list, just add the address 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 and the remaining information will be loaded automatically. Click Ok and your token will be added.
Unicorn tokens are memorabilia created exclusively for those who have donated to the address 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359 that is controlled by the Ethereum Foundation. For more information about them read it here
原文地址:https://www.ethereum.org/token