create-token.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 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. """
  19. scripts/create-token.py: Automated ERC20 token creation for the MMGen suite
  20. """
  21. import sys, json, re
  22. from subprocess import run, PIPE
  23. from collections import namedtuple
  24. import script_init
  25. from mmgen.main import launch
  26. from mmgen.cfg import Config
  27. from mmgen.util import Msg, msg, rmsg, ymsg, die
  28. ti = namedtuple('token_param_info', ['default', 'conversion', 'test'])
  29. class TokenData:
  30. fields = ('decimals', 'supply', 'name', 'symbol', 'owner_addr')
  31. decimals = ti('18', int, lambda s: s.isascii() and s.isdigit() and 0 < int(s) <= 36)
  32. name = ti(None, str, lambda s: s.isascii() and s.isprintable() and len(s) < 256)
  33. supply = ti(None, int, lambda s: s.isascii() and s.isdigit() and 0 < int(s) < 2**256)
  34. symbol = ti(None, str, lambda s: s.isascii() and s.isalnum() and len(s) <= 20)
  35. owner_addr = ti(None, str, lambda s: s.isascii() and s.isalnum() and len(s) == 40) # checked separately
  36. token_data = TokenData()
  37. req_solc_ver_pat = '^0.8.25'
  38. opts_data = {
  39. 'text': {
  40. 'desc': 'Create an ERC20 token contract',
  41. 'usage':'[opts] <owner address>',
  42. 'options': f"""
  43. -h, --help Print this help message
  44. -o, --outdir=D Specify output directory for *.bin files
  45. -d, --decimals=D Number of decimals for the token (default: {token_data.decimals.default})
  46. -n, --name=N Token name (REQUIRED)
  47. -p, --preprocess Print the preprocessed code to stdout
  48. -t, --supply=T Total supply of the token (REQUIRED)
  49. -s, --symbol=S Token symbol (REQUIRED)
  50. -S, --stdout Output JSON data to stdout instead of files
  51. -v, --verbose Produce more verbose output
  52. -c, --check-solc-version Check the installed solc version
  53. """,
  54. 'notes': """
  55. The owner address must be in checksummed format.
  56. Use ‘mmgen-tool eth_checksummed_addr’ to create it if necessary.
  57. """
  58. }
  59. }
  60. import os
  61. with open(os.path.join(os.path.dirname(__file__), 'ERC20.sol.in')) as fh:
  62. solidity_code_template = fh.read()
  63. def create_src(cfg, template, token_data):
  64. def gen():
  65. for k in token_data.fields:
  66. field = getattr(token_data, k)
  67. if k == 'owner_addr':
  68. owner_addr = cfg._args[0]
  69. from mmgen.addr import is_coin_addr
  70. if not is_coin_addr(cfg._proto, owner_addr.lower()):
  71. die(1, f'{owner_addr}: not a valid {cfg._proto.coin} coin address')
  72. val = '0x' + owner_addr
  73. else:
  74. val = (
  75. getattr(cfg, k)
  76. or getattr(field, 'default', None)
  77. or die(1, f'The --{k} option must be specified')
  78. )
  79. if not field.test(val):
  80. die(1, f'{val!r}: invalid parameter for option --{k}')
  81. yield (k, field.conversion(val))
  82. from string import Template
  83. return Template(template).substitute(**(dict(gen()) | {'solc_ver_pat': req_solc_ver_pat}))
  84. def check_solc_version():
  85. """
  86. The output is used by other programs, so write to stdout only
  87. """
  88. try:
  89. cp = run(['solc', '--version'], check=True, stdout=PIPE)
  90. except:
  91. msg('solc missing or could not be executed') # this must go to stderr
  92. return False
  93. if cp.returncode != 0:
  94. Msg('solc exited with error')
  95. return False
  96. line = cp.stdout.decode().splitlines()[1]
  97. version_str = re.sub(r'Version:\s*', '', line)
  98. m = re.match(r'(\d+)\.(\d+)\.(\d+)', version_str)
  99. if not m:
  100. Msg(f'Unrecognized solc version string: {version_str}')
  101. return False
  102. from semantic_version import Version, NpmSpec
  103. version = Version('{}.{}.{}'.format(*m.groups()))
  104. if version in NpmSpec(req_solc_ver_pat):
  105. Msg(str(version))
  106. return True
  107. else:
  108. Msg(f'solc version ({version_str}) does not match requirement ({req_solc_ver_pat})')
  109. return False
  110. def compile_code(cfg, code):
  111. cmd = ['solc', '--optimize', '--bin', '--overwrite', '--evm-version=constantinople']
  112. if not cfg.stdout:
  113. cmd += ['--output-dir', cfg.outdir or '.']
  114. cmd += ['-']
  115. msg(f"Executing: {' '.join(cmd)}")
  116. cp = run(cmd, input=code.encode(), stdout=PIPE, stderr=PIPE)
  117. out = cp.stdout.decode().replace('\r', '')
  118. err = cp.stderr.decode().replace('\r', '').strip()
  119. if cp.returncode != 0:
  120. rmsg('Solidity compiler produced the following error:')
  121. msg(err)
  122. die(4, f'Solidity compiler exited with error (return val: {cp.returncode})')
  123. if err:
  124. ymsg('Solidity compiler produced the following warning:')
  125. msg(err)
  126. if cfg.stdout:
  127. o = out.split('\n')
  128. return {k:o[i+2] for k in ('SafeMath', 'Owned', 'Token') for i in range(len(o)) if k in o[i]}
  129. else:
  130. cfg._util.vmsg(out)
  131. def main():
  132. cfg = Config(opts_data=opts_data)
  133. if cfg.check_solc_version:
  134. sys.exit(0 if check_solc_version() else 1)
  135. if not cfg._proto.coin in ('ETH', 'ETC'):
  136. die(1, '--coin option must be ETH or ETC')
  137. if not len(cfg._args) == 1:
  138. cfg._usage()
  139. code = create_src(cfg, solidity_code_template, token_data)
  140. if cfg.preprocess:
  141. Msg(code)
  142. sys.exit(0)
  143. out = compile_code(cfg, code)
  144. if cfg.stdout:
  145. print(json.dumps(out))
  146. msg('Contract successfully compiled')
  147. if __name__ == '__main__':
  148. launch(func=main)