Giaosucan's blog - Chia sẻ kiến thức theo cách bá đạo

Ticker

20/recent/ticker-posts

Tạo tiền ảo trong vòng 1 nốt nhạc

Tạo tiền ảo trong vòng 1 nốt nhạc


Image result for cryptocurrency ethereum


Cùng với việc phát triển mạnh mẽ của các đồng tiền số như Bitcoin và Ethereum trong thời gian gần đây, các bạn sẽ khá quen thuộc với cụm từ ICO (Initial Coin Offering). một hình thức kêu gọi vốn đầu tư khá phổ biến trong các dự án tiền điện tử kỹ thuật số (Cryptocurrency). Khi một công ty hay nhóm phát hành ra cryptocurrency của riêng họ, họ thường tạo ra một số lượng Token nhất định và bán ra những mã token này cho các nhà đầu tư trong nhiều đợt Crowdsale khác nhau
Vậy bạn có muốn tạo ra một đồng tiền ảo cho riêng mình? Bài viết này sẽ hướng dẫn các bạn cách tạo 1 đồng tiền ảo chỉ trong vòng 1 nốt nhạc
Công nghệ đằng sau tiền ảo là Blockchain, platform blockchain mình sử dụng trong bài viết này là Ethereum. Môt platform blockchain khá thông dụng

Image result for ethereumImage result for ethereumImage result for ethereum

Chuẩn bị đồ nghề

Dưới đây là 1 số “đồ nghề” cần chuẩn bị
  • Visual Studio Code, cài thêm plugin solidity
  • Install plugin MetaMask for Chrome (Xem hướng dẫn ở bài trước)
  • Solidity Compiler. (Có thể cài solc compiler hoặc mì ăn liền thì dùng bộ compiler online Solidity Remix Compiler)
  • Môi trường Windows, Linux ok tuốt. Nhưng làm blockchain thì nên xài Linux

Lựa chọn Token bạn muốn tạo

Ethereum cung cấp 1 loại Token tiêu chuẩn gọi là ERC20 token. ERC là viết tắt của Ethereum Request for Comments. Đây là một giao thức chính thức để đề xuất các cải tiến cho mạng Ethereum. '20' là số ID đề xuất duy nhất
ERC20 định nghĩa một tập hợp các quy tắc cần được đáp ứng để cho một token được chấp nhận và được gọi là 'ERC20 Token’. Các Token này là các tài sản blockchain có giá trị và có thể được gửi và nhận giống như Bitcoin, Litecoin, Ethereum.
Sự khác biệt giữa các Token này và các loại tiền tệ độc lập khác là Token ERC20 trên mạng Ethereum được lưu trữ bởi các địa chỉ Ethereum và được gửi bằng các giao dịch Ethereum
Để tạo một ERC20 Token, bạn cần những thông tin sau

  • Tên Token
  • Ký hiệu của Token (giống kiểu $ là kí hiệu của USD)
  • The Token’s Decimal Places (Vị trị thập phân). Nếu set là 1, mọi người có thể có một số thập phân Token, kiểu như 0.5 Token, còn 0 nghĩa là có 1 số nguyên token
  • Số lượng Token được lưu thông

Code Smart Contract

Trong Ethereum, Token thực chất là một smart contract. Bạn có thể sử dụng đoạn code standard của Ethereum về chỉnh sửa cho phù hợp
SmartContract trong Ethereum được viết bằng ngôn ngữ solidity, một ngôn ngữ gần giống JavaScript


pragma solidity ^0.4.4;

contract Token {

   /// @return total amount of tokens
   function totalSupply() constant returns (uint256 supply) {}

   /// @param _owner The address from which the balance will be retrieved
   /// @return The balance
   function balanceOf(address _owner) constant returns (uint256 balance) {}

   /// @notice send `_value` token to `_to` from `msg.sender`
   /// @param _to The address of the recipient
   /// @param _value The amount of token to be transferred
   /// @return Whether the transfer was successful or not
   function transfer(address _to, uint256 _value) returns (bool success) {}

   /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
   /// @param _from The address of the sender
   /// @param _to The address of the recipient
   /// @param _value The amount of token to be transferred
   /// @return Whether the transfer was successful or not
   function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}

   /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
   /// @param _spender The address of the account able to transfer the tokens
   /// @param _value The amount of wei to be approved for transfer
   /// @return Whether the approval was successful or not
   function approve(address _spender, uint256 _value) returns (bool success) {}

   /// @param _owner The address of the account owning tokens
   /// @param _spender The address of the account able to transfer the tokens
   /// @return Amount of remaining tokens allowed to spent
   function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}

   event Transfer(address indexed _from, address indexed _to, uint256 _value);
   event Approval(address indexed _owner, address indexed _spender, uint256 _value);
   
}
contract StandardToken is Token {
   function transfer(address _to, uint256 _value) returns (bool success) {
       //Default assumes totalSupply can't be over max (2^256 - 1).
       //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
       //Replace the if with this one instead.
       //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
       if (balances[msg.sender] >= _value && _value > 0) {
           balances[msg.sender] -= _value;
           balances[_to] += _value;
           Transfer(msg.sender, _to, _value);
           return true;
       } else { return false; }
   }
   function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
       //same as above. Replace this line with the following if you want to protect against wrapping uints.
       //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
       if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
           balances[_to] += _value;
           balances[_from] -= _value;
           allowed[_from][msg.sender] -= _value;
           Transfer(_from, _to, _value);
           return true;
       } else { return false; }
   }

   function balanceOf(address _owner) constant returns (uint256 balance) {
       return balances[_owner];
   }

   function approve(address _spender, uint256 _value) returns (bool success) {
       allowed[msg.sender][_spender] = _value;
       Approval(msg.sender, _spender, _value);
       return true;
   }

   function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
     return allowed[_owner][_spender];
   }

   mapping (address => uint256) balances;
   mapping (address => mapping (address => uint256)) allowed;
   uint256 public totalSupply;
}

//name this contract whatever you'd like
contract ERC20Token is StandardToken {

   function () {
       //if ether is sent to this address, send it back.
       throw;
   }

   /* Public variables of the token */

   /*
   NOTE:
   The following variables are OPTIONAL vanities. One does not have to include them.
   They allow one to customise the token contract & in no way influences the core functionality.
   Some wallets/interfaces might not even bother to look at this information.
   */
   string public name;                   //fancy name: eg Simon Bucks
   uint8 public decimals;                //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
   string public symbol;                 //An identifier: eg SBX
   string public version = 'H1.0';       //human 0.1 standard. Just an arbitrary versioning scheme.

//
// CHANGE THESE VALUES FOR YOUR TOKEN
//

//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token

   function ERC20Token(
       ) {
       balances[msg.sender] = 100000;               // Give the creator all initial tokens (100000 for example)
       totalSupply = 100000;                        // Update total supply (100000 for example)
       name = "Giaosucan's Token";            // Set the name for display purposes
       decimals = 0;                                // Amount of decimals for display purposes
       symbol = "SYM";                              // Set the symbol for display purposes
   }

   /* Approves and then calls the receiving contract */
   function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
       allowed[msg.sender][_spender] = _value;
       Approval(msg.sender, _spender, _value);

       //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
       //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
       //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
       if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
       return true;
   }
}


Đây là thông tin cần chú ý




Symbol của Token (SYM), số lượng Token cung cấp ra thị trường, chú ý số lượng này tỉ lệ với decimals
Ví dụ: nếu bạn muốn một Token có 0 chữ số thập phân có 10 token, thì nguồn cung cấp sẽ là 10.
Nhưng nếu bạn có một Token với 18 chữ số thập phân và bạn muốn 10 của họ, nguồn cung cấp sẽ là 10^18.
balances[msg.sender] = 100000


Khi deploy contract, người tạo contract sẽ nhận được số Token là 100000

Deploy contract

Ethereum cung cấp 1 online compiler dùng để compile và deploy contract
Chọn compiler


Sau đó thì compile


Nếu không có lỗi gì thì sẽ compile thành công
Bật MetaMask, connect với Ropsten Test net. Mạng Ropsten được sử dụng như là một môi trường test trước khi bạn đưa Token của bạn vào mạng chính
Tạo 1 account trên MetaMask (tham khảo hướng dẫn của bài trước)
Bạn cần cung cấp 1 khoản ETH cho account này để thực hiện các giao dịch. Do trong mạng Ropsten bạn có thể dùng link dưới để send ETH
Nhập public address vào để send ETH, giao dịch mất khoảng vài second để hoàn thành
Bạn sẽ thấy account được cập nhật giá trị
Trên Remix compiler, bấm create, MetaMask sẽ hiện thị popup để thực hiên deploy contract. Chọn Submit để thực hiện deploy. Quá trình Deploy sẽ mất khoảng vài chục seconds.


Khi Contract được deploy thành công, Ethereum sẽ tạo ra một address cho contract đó. Trong trường hợp này, contract khi deploy có địa chỉ như dưới
0x743ce9d1c6ed5aa23f4fc811823e716728e5b0e2.
Add Token, bạn sẽ thấy Token của mình được hiện ra trên MetaMask


Truy cập vào trang sau, nhập địa chỉ address vào rồi search
Bạn sẽ Contract của mình đã được deploy trên mạng Ropsten như hình dưới




Chọn Contract Code, nhập thông tin rồi chọn Verify and Publish. Chúc mừng! Bây giờ mọi người có thể ghé thăm Token address của bạn.

Như vậy bạn đã tạo thành công 1 Loại tiền ảo cho trên mạng Ethereum

Đăng nhận xét

1 Nhận xét

  1. Anh ơi, anh hướng dẫn lại được bằng các bước được không ạ? Em làm theo mà không thành công.

    Trả lờiXóa