create-token.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. import sys,os,json,re
  19. from subprocess import Popen,PIPE
  20. from mmgen.common import *
  21. from mmgen.obj import CoinAddr,is_coin_addr
  22. decimals = 18
  23. supply = 10**26
  24. name = 'MMGen Token'
  25. symbol = 'MMT'
  26. solc_version_pat = r'0.5.[123]'
  27. opts_data = lambda: {
  28. 'desc': 'Create an ERC20 token contract',
  29. 'usage':'[opts] <owner address>',
  30. 'options': """
  31. -h, --help Print this help message
  32. -o, --outdir= d Specify output directory for *.bin files
  33. -d, --decimals=d Number of decimals for the token (default: {d})
  34. -n, --name=n Token name (default: {n})
  35. -t, --supply= t Total supply of the token (default: {t})
  36. -s, --symbol= s Token symbol (default: {s})
  37. -S, --stdout Output data in JSON format to stdout instead of files
  38. -v, --verbose Produce more verbose output
  39. """.format(d=decimals,n=name,s=symbol,t=supply)
  40. }
  41. cmd_args = opts.init(opts_data)
  42. assert g.coin in ('ETH','ETC'),'--coin option must be set to ETH or ETC'
  43. if not len(cmd_args) == 1 or not is_coin_addr(cmd_args[0].lower()):
  44. opts.usage()
  45. owner_addr = '0x' + cmd_args[0]
  46. # ERC Token Standard #20 Interface
  47. # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
  48. code_in = """
  49. pragma solidity >0.5.0 <0.5.4;
  50. contract SafeMath {
  51. function safeAdd(uint a, uint b) public pure returns (uint c) {
  52. c = a + b;
  53. require(c >= a);
  54. }
  55. function safeSub(uint a, uint b) public pure returns (uint c) {
  56. require(b <= a);
  57. c = a - b;
  58. }
  59. function safeMul(uint a, uint b) public pure returns (uint c) {
  60. c = a * b;
  61. require(a == 0 || c / a == b);
  62. }
  63. function safeDiv(uint a, uint b) public pure returns (uint c) {
  64. require(b > 0);
  65. c = a / b;
  66. }
  67. }
  68. contract ERC20Interface {
  69. function totalSupply() public returns (uint);
  70. function balanceOf(address tokenOwner) public returns (uint balance);
  71. function allowance(address tokenOwner, address spender) public returns (uint remaining);
  72. function transfer(address to, uint tokens) public returns (bool success);
  73. function approve(address spender, uint tokens) public returns (bool success);
  74. function transferFrom(address from, address to, uint tokens) public returns (bool success);
  75. event Transfer(address indexed from, address indexed to, uint tokens);
  76. event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
  77. }
  78. contract Owned {
  79. address public owner;
  80. address public newOwner;
  81. event OwnershipTransferred(address indexed _from, address indexed _to);
  82. constructor() public {
  83. owner = msg.sender;
  84. }
  85. modifier onlyOwner {
  86. require(msg.sender == owner);
  87. _;
  88. }
  89. function transferOwnership(address _newOwner) public onlyOwner {
  90. newOwner = _newOwner;
  91. }
  92. function acceptOwnership() public {
  93. require(msg.sender == newOwner);
  94. emit OwnershipTransferred(owner, newOwner);
  95. owner = newOwner;
  96. newOwner = address(0);
  97. }
  98. }
  99. // ----------------------------------------------------------------------------
  100. // ERC20 Token, with the addition of symbol, name and decimals and assisted
  101. // token transfers
  102. // ----------------------------------------------------------------------------
  103. contract Token is ERC20Interface, Owned, SafeMath {
  104. string public symbol;
  105. string public name;
  106. uint8 public decimals;
  107. uint public _totalSupply;
  108. mapping(address => uint) balances;
  109. mapping(address => mapping(address => uint)) allowed;
  110. constructor() public {
  111. symbol = "<SYMBOL>";
  112. name = "<NAME>";
  113. decimals = <DECIMALS>;
  114. _totalSupply = <SUPPLY>;
  115. balances[<OWNER_ADDR>] = _totalSupply;
  116. emit Transfer(address(0), <OWNER_ADDR>, _totalSupply);
  117. }
  118. function totalSupply() public returns (uint) {
  119. return _totalSupply - balances[address(0)];
  120. }
  121. function balanceOf(address tokenOwner) public returns (uint balance) {
  122. return balances[tokenOwner];
  123. }
  124. function transfer(address to, uint tokens) public returns (bool success) {
  125. balances[msg.sender] = safeSub(balances[msg.sender], tokens);
  126. balances[to] = safeAdd(balances[to], tokens);
  127. emit Transfer(msg.sender, to, tokens);
  128. return true;
  129. }
  130. function approve(address spender, uint tokens) public returns (bool success) {
  131. allowed[msg.sender][spender] = tokens;
  132. emit Approval(msg.sender, spender, tokens);
  133. return true;
  134. }
  135. function transferFrom(address from, address to, uint tokens) public returns (bool success) {
  136. balances[from] = safeSub(balances[from], tokens);
  137. allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
  138. balances[to] = safeAdd(balances[to], tokens);
  139. emit Transfer(from, to, tokens);
  140. return true;
  141. }
  142. function allowance(address tokenOwner, address spender) public returns (uint remaining) {
  143. return allowed[tokenOwner][spender];
  144. }
  145. // Owner can transfer out any accidentally sent ERC20 tokens
  146. function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
  147. return ERC20Interface(tokenAddress).transfer(owner, tokens);
  148. }
  149. }
  150. """
  151. def create_src(code):
  152. for k in ('decimals','supply','name','symbol','owner_addr'):
  153. if hasattr(opt,k) and getattr(opt,k): globals()[k] = getattr(opt,k)
  154. code = code.replace('<{}>'.format(k.upper()),str(globals()[k]))
  155. return code
  156. def check_version():
  157. p = Popen(['solc','--version'],stdout=PIPE)
  158. res = p.stdout.read().decode()
  159. ver = re.search(r'Version:\s*(.*)',res).group(1)
  160. msg("Installed solc version: {}".format(ver))
  161. if not re.search(r'{}\b'.format(solc_version_pat),ver):
  162. ydie(1,'Incorrect Solidity compiler version (need version {})'.format(solc_version_pat))
  163. def compile_code(code):
  164. check_version()
  165. cmd = ['solc','--optimize','--bin','--overwrite']
  166. if not opt.stdout: cmd += ['--output-dir', opt.outdir or '.']
  167. cmd += ['-']
  168. msg('Executing: {}'.format(' '.join(cmd)))
  169. p = Popen(cmd,stdin=PIPE,stdout=PIPE,stderr=PIPE)
  170. res = p.communicate(code.encode())
  171. out = res[0].decode().replace('\r','')
  172. err = res[1].decode().replace('\r','').strip()
  173. rc = p.wait()
  174. if rc != 0:
  175. rmsg('Solidity compiler produced the following error:')
  176. msg(err)
  177. rdie(2,'Solidity compiler exited with error (return val: {})'.format(rc))
  178. if err:
  179. ymsg('Solidity compiler produced the following warning:')
  180. msg(err)
  181. if opt.stdout:
  182. o = out.split('\n')
  183. return dict((k,o[i+2]) for k in ('SafeMath','Owned','Token') for i in range(len(o)) if k in o[i])
  184. else:
  185. vmsg(out)
  186. src = create_src(code_in)
  187. out = compile_code(src)
  188. if opt.stdout:
  189. print(json.dumps(out))
  190. msg('Contract successfully compiled')