create-token.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 = {
  28. 'text': {
  29. 'desc': 'Create an ERC20 token contract',
  30. 'usage':'[opts] <owner address>',
  31. 'options': """
  32. -h, --help Print this help message
  33. -o, --outdir= d Specify output directory for *.bin files
  34. -d, --decimals=d Number of decimals for the token (default: {d})
  35. -n, --name=n Token name (default: {n})
  36. -t, --supply= t Total supply of the token (default: {t})
  37. -s, --symbol= s Token symbol (default: {s})
  38. -S, --stdout Output data in JSON format to stdout instead of files
  39. -v, --verbose Produce more verbose output
  40. """
  41. },
  42. 'code': {
  43. 'options': lambda s: s.format(
  44. d=decimals,
  45. n=name,
  46. s=symbol,
  47. t=supply)
  48. }
  49. }
  50. cmd_args = opts.init(opts_data)
  51. assert g.coin in ('ETH','ETC'),'--coin option must be set to ETH or ETC'
  52. if not len(cmd_args) == 1 or not is_coin_addr(cmd_args[0].lower()):
  53. opts.usage()
  54. owner_addr = '0x' + cmd_args[0]
  55. # ERC Token Standard #20 Interface
  56. # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
  57. code_in = """
  58. pragma solidity >0.5.0 <0.5.4;
  59. contract SafeMath {
  60. function safeAdd(uint a, uint b) public pure returns (uint c) {
  61. c = a + b;
  62. require(c >= a);
  63. }
  64. function safeSub(uint a, uint b) public pure returns (uint c) {
  65. require(b <= a);
  66. c = a - b;
  67. }
  68. function safeMul(uint a, uint b) public pure returns (uint c) {
  69. c = a * b;
  70. require(a == 0 || c / a == b);
  71. }
  72. function safeDiv(uint a, uint b) public pure returns (uint c) {
  73. require(b > 0);
  74. c = a / b;
  75. }
  76. }
  77. contract ERC20Interface {
  78. function totalSupply() public returns (uint);
  79. function balanceOf(address tokenOwner) public returns (uint balance);
  80. function allowance(address tokenOwner, address spender) public returns (uint remaining);
  81. function transfer(address to, uint tokens) public returns (bool success);
  82. function approve(address spender, uint tokens) public returns (bool success);
  83. function transferFrom(address from, address to, uint tokens) public returns (bool success);
  84. event Transfer(address indexed from, address indexed to, uint tokens);
  85. event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
  86. }
  87. contract Owned {
  88. address public owner;
  89. address public newOwner;
  90. event OwnershipTransferred(address indexed _from, address indexed _to);
  91. constructor() public {
  92. owner = msg.sender;
  93. }
  94. modifier onlyOwner {
  95. require(msg.sender == owner);
  96. _;
  97. }
  98. function transferOwnership(address _newOwner) public onlyOwner {
  99. newOwner = _newOwner;
  100. }
  101. function acceptOwnership() public {
  102. require(msg.sender == newOwner);
  103. emit OwnershipTransferred(owner, newOwner);
  104. owner = newOwner;
  105. newOwner = address(0);
  106. }
  107. }
  108. // ----------------------------------------------------------------------------
  109. // ERC20 Token, with the addition of symbol, name and decimals and assisted
  110. // token transfers
  111. // ----------------------------------------------------------------------------
  112. contract Token is ERC20Interface, Owned, SafeMath {
  113. string public symbol;
  114. string public name;
  115. uint8 public decimals;
  116. uint public _totalSupply;
  117. mapping(address => uint) balances;
  118. mapping(address => mapping(address => uint)) allowed;
  119. constructor() public {
  120. symbol = "<SYMBOL>";
  121. name = "<NAME>";
  122. decimals = <DECIMALS>;
  123. _totalSupply = <SUPPLY>;
  124. balances[<OWNER_ADDR>] = _totalSupply;
  125. emit Transfer(address(0), <OWNER_ADDR>, _totalSupply);
  126. }
  127. function totalSupply() public returns (uint) {
  128. return _totalSupply - balances[address(0)];
  129. }
  130. function balanceOf(address tokenOwner) public returns (uint balance) {
  131. return balances[tokenOwner];
  132. }
  133. function transfer(address to, uint tokens) public returns (bool success) {
  134. balances[msg.sender] = safeSub(balances[msg.sender], tokens);
  135. balances[to] = safeAdd(balances[to], tokens);
  136. emit Transfer(msg.sender, to, tokens);
  137. return true;
  138. }
  139. function approve(address spender, uint tokens) public returns (bool success) {
  140. allowed[msg.sender][spender] = tokens;
  141. emit Approval(msg.sender, spender, tokens);
  142. return true;
  143. }
  144. function transferFrom(address from, address to, uint tokens) public returns (bool success) {
  145. balances[from] = safeSub(balances[from], tokens);
  146. allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
  147. balances[to] = safeAdd(balances[to], tokens);
  148. emit Transfer(from, to, tokens);
  149. return true;
  150. }
  151. function allowance(address tokenOwner, address spender) public returns (uint remaining) {
  152. return allowed[tokenOwner][spender];
  153. }
  154. // Owner can transfer out any accidentally sent ERC20 tokens
  155. function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
  156. return ERC20Interface(tokenAddress).transfer(owner, tokens);
  157. }
  158. }
  159. """
  160. def create_src(code):
  161. for k in ('decimals','supply','name','symbol','owner_addr'):
  162. if hasattr(opt,k) and getattr(opt,k): globals()[k] = getattr(opt,k)
  163. code = code.replace('<{}>'.format(k.upper()),str(globals()[k]))
  164. return code
  165. def check_version():
  166. p = Popen(['solc','--version'],stdout=PIPE)
  167. res = p.stdout.read().decode()
  168. ver = re.search(r'Version:\s*(.*)',res).group(1)
  169. msg("Installed solc version: {}".format(ver))
  170. if not re.search(r'{}\b'.format(solc_version_pat),ver):
  171. ydie(1,'Incorrect Solidity compiler version (need version {})'.format(solc_version_pat))
  172. def compile_code(code):
  173. check_version()
  174. cmd = ['solc','--optimize','--bin','--overwrite']
  175. if not opt.stdout: cmd += ['--output-dir', opt.outdir or '.']
  176. cmd += ['-']
  177. msg('Executing: {}'.format(' '.join(cmd)))
  178. p = Popen(cmd,stdin=PIPE,stdout=PIPE,stderr=PIPE)
  179. res = p.communicate(code.encode())
  180. out = res[0].decode().replace('\r','')
  181. err = res[1].decode().replace('\r','').strip()
  182. rc = p.wait()
  183. if rc != 0:
  184. rmsg('Solidity compiler produced the following error:')
  185. msg(err)
  186. rdie(2,'Solidity compiler exited with error (return val: {})'.format(rc))
  187. if err:
  188. ymsg('Solidity compiler produced the following warning:')
  189. msg(err)
  190. if opt.stdout:
  191. o = out.split('\n')
  192. return {k:o[i+2] for k in ('SafeMath','Owned','Token') for i in range(len(o)) if k in o[i]}
  193. else:
  194. vmsg(out)
  195. src = create_src(code_in)
  196. out = compile_code(src)
  197. if opt.stdout:
  198. print(json.dumps(out))
  199. msg('Contract successfully compiled')