create-token.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 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 run,PIPE
  20. from mmgen.common import *
  21. class TokenData:
  22. attrs = ('decimals','supply','name','symbol','owner_addr')
  23. decimals = 18
  24. supply = 10**26
  25. name = 'MMGen Token'
  26. symbol = 'MMT'
  27. owner_addr = None
  28. token_data = TokenData()
  29. req_solc_ver_pat = '^0.8.6'
  30. opts_data = {
  31. 'text': {
  32. 'desc': 'Create an ERC20 token contract',
  33. 'usage':'[opts] <owner address>',
  34. 'options': f"""
  35. -h, --help Print this help message
  36. -o, --outdir=D Specify output directory for *.bin files
  37. -d, --decimals=D Number of decimals for the token (default: {token_data.decimals})
  38. -n, --name=N Token name (default: {token_data.name!r})
  39. -t, --supply=T Total supply of the token (default: {token_data.supply})
  40. -s, --symbol=S Token symbol (default: {token_data.symbol!r})
  41. -S, --stdout Output JSON data to stdout instead of files
  42. -v, --verbose Produce more verbose output
  43. -c, --check-solc-version Check the installed solc version
  44. """,
  45. 'notes': """
  46. The owner address must be in checksummed format
  47. """
  48. }
  49. }
  50. # ERC Token Standard #20 Interface
  51. # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
  52. solidity_code_template = """
  53. pragma solidity %s;
  54. contract SafeMath {
  55. function safeAdd(uint a, uint b) public pure returns (uint c) {
  56. c = a + b;
  57. require(c >= a);
  58. }
  59. function safeSub(uint a, uint b) public pure returns (uint c) {
  60. require(b <= a);
  61. c = a - b;
  62. }
  63. function safeMul(uint a, uint b) public pure returns (uint c) {
  64. c = a * b;
  65. require(a == 0 || c / a == b);
  66. }
  67. function safeDiv(uint a, uint b) public pure returns (uint c) {
  68. require(b > 0);
  69. c = a / b;
  70. }
  71. }
  72. abstract contract ERC20Interface {
  73. function totalSupply() public virtual returns (uint);
  74. function balanceOf(address tokenOwner) public virtual returns (uint balance);
  75. function allowance(address tokenOwner, address spender) public virtual returns (uint remaining);
  76. function transfer(address to, uint tokens) public virtual returns (bool success);
  77. function approve(address spender, uint tokens) public virtual returns (bool success);
  78. function transferFrom(address from, address to, uint tokens) public virtual returns (bool success);
  79. event Transfer(address indexed from, address indexed to, uint tokens);
  80. event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
  81. }
  82. contract Owned {
  83. address public owner;
  84. address public newOwner;
  85. event OwnershipTransferred(address indexed _from, address indexed _to);
  86. constructor() public {
  87. owner = msg.sender;
  88. }
  89. modifier onlyOwner {
  90. require(msg.sender == owner);
  91. _;
  92. }
  93. function transferOwnership(address _newOwner) public onlyOwner {
  94. newOwner = _newOwner;
  95. }
  96. function acceptOwnership() public {
  97. require(msg.sender == newOwner);
  98. emit OwnershipTransferred(owner, newOwner);
  99. owner = newOwner;
  100. newOwner = address(0);
  101. }
  102. }
  103. // ----------------------------------------------------------------------------
  104. // ERC20 Token, with the addition of symbol, name and decimals and assisted
  105. // token transfers
  106. // ----------------------------------------------------------------------------
  107. contract Token is ERC20Interface, Owned, SafeMath {
  108. string public symbol;
  109. string public name;
  110. uint8 public decimals;
  111. uint public _totalSupply;
  112. mapping(address => uint) balances;
  113. mapping(address => mapping(address => uint)) allowed;
  114. constructor() public {
  115. symbol = "<SYMBOL>";
  116. name = "<NAME>";
  117. decimals = <DECIMALS>;
  118. _totalSupply = <SUPPLY>;
  119. balances[<OWNER_ADDR>] = _totalSupply;
  120. emit Transfer(address(0), <OWNER_ADDR>, _totalSupply);
  121. }
  122. function totalSupply() public override returns (uint) {
  123. return _totalSupply - balances[address(0)];
  124. }
  125. function balanceOf(address tokenOwner) public override returns (uint balance) {
  126. return balances[tokenOwner];
  127. }
  128. function transfer(address to, uint tokens) public override returns (bool success) {
  129. balances[msg.sender] = safeSub(balances[msg.sender], tokens);
  130. balances[to] = safeAdd(balances[to], tokens);
  131. emit Transfer(msg.sender, to, tokens);
  132. return true;
  133. }
  134. function approve(address spender, uint tokens) public override returns (bool success) {
  135. allowed[msg.sender][spender] = tokens;
  136. emit Approval(msg.sender, spender, tokens);
  137. return true;
  138. }
  139. function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
  140. balances[from] = safeSub(balances[from], tokens);
  141. allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
  142. balances[to] = safeAdd(balances[to], tokens);
  143. emit Transfer(from, to, tokens);
  144. return true;
  145. }
  146. function allowance(address tokenOwner, address spender) public override returns (uint remaining) {
  147. return allowed[tokenOwner][spender];
  148. }
  149. // Owner can transfer out any accidentally sent ERC20 tokens
  150. function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
  151. return ERC20Interface(tokenAddress).transfer(owner, tokens);
  152. }
  153. }
  154. """ % req_solc_ver_pat
  155. def create_src(code,token_data,owner_addr):
  156. token_data.owner_addr = '0x' + owner_addr
  157. for k in token_data.attrs:
  158. if getattr(opt,k,None):
  159. setattr( token_data, k, getattr(opt,k) )
  160. code = code.replace( f'<{k.upper()}>', str(getattr(token_data,k)) )
  161. return code
  162. def check_solc_version():
  163. """
  164. The output is used by other programs, so write to stdout only
  165. """
  166. try:
  167. cp = run(['solc','--version'],check=True,stdout=PIPE)
  168. except:
  169. msg('solc missing or could not be executed') # this must go to stderr
  170. return False
  171. if cp.returncode != 0:
  172. Msg('solc exited with error')
  173. return False
  174. line = cp.stdout.decode().splitlines()[1]
  175. version_str = re.sub(r'Version:\s*','',line)
  176. m = re.match(r'(\d+)\.(\d+)\.(\d+)',version_str)
  177. if not m:
  178. Msg(f'Unrecognized solc version string: {version_str}')
  179. return False
  180. from semantic_version import Version,NpmSpec
  181. version = Version('{}.{}.{}'.format(*m.groups()))
  182. if version in NpmSpec(req_solc_ver_pat):
  183. Msg(str(version))
  184. return True
  185. else:
  186. Msg(f'solc version ({version_str}) does not match requirement ({req_solc_ver_pat})')
  187. return False
  188. def compile_code(code):
  189. cmd = ['solc','--optimize','--bin','--overwrite']
  190. if not opt.stdout:
  191. cmd += ['--output-dir', opt.outdir or '.']
  192. cmd += ['-']
  193. msg(f"Executing: {' '.join(cmd)}")
  194. cp = run(cmd,input=code.encode(),stdout=PIPE,stderr=PIPE)
  195. out = cp.stdout.decode().replace('\r','')
  196. err = cp.stderr.decode().replace('\r','').strip()
  197. if cp.returncode != 0:
  198. rmsg('Solidity compiler produced the following error:')
  199. msg(err)
  200. rdie(2,f'Solidity compiler exited with error (return val: {cp.returncode})')
  201. if err:
  202. ymsg('Solidity compiler produced the following warning:')
  203. msg(err)
  204. if opt.stdout:
  205. o = out.split('\n')
  206. return {k:o[i+2] for k in ('SafeMath','Owned','Token') for i in range(len(o)) if k in o[i]}
  207. else:
  208. vmsg(out)
  209. if __name__ == '__main__':
  210. cmd_args = opts.init(opts_data)
  211. if opt.check_solc_version:
  212. sys.exit(0 if check_solc_version() else 1)
  213. from mmgen.protocol import init_proto_from_opts
  214. proto = init_proto_from_opts()
  215. if not proto.coin in ('ETH','ETC'):
  216. die(1,'--coin option must be ETH or ETC')
  217. if not len(cmd_args) == 1:
  218. opts.usage()
  219. owner_addr = cmd_args[0]
  220. from mmgen.obj import is_coin_addr
  221. if not is_coin_addr( proto, owner_addr.lower() ):
  222. die(1,f'{owner_addr}: not a valid {proto.coin} coin address')
  223. out = compile_code(
  224. create_src( solidity_code_template, token_data, owner_addr )
  225. )
  226. if opt.stdout:
  227. print(json.dumps(out))
  228. msg('Contract successfully compiled')