initial commit, factored out from eth-address-index

This commit is contained in:
nolash 2021-10-04 16:24:51 +02:00
commit f8466066f1
Signed by: lash
GPG Key ID: 21D2E7BB88C2A746
19 changed files with 690 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.egg-info
build
*.pyc
__pycache__

1
python/MANIFEST.in Normal file
View File

@ -0,0 +1 @@
include **/data/*.json **/data/*.bin *requirements.txt

View File

@ -0,0 +1,4 @@
from .index import (
TokenUniqueSymbolIndex,
to_identifier,
)

View File

@ -0,0 +1 @@
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
[{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint8","name":"_decimals","type":"uint8"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"TransferFrom","type":"event"},{"inputs":[{"internalType":"address","name":"_minter","type":"address"}],"name":"addMinter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"mint","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_minter","type":"address"}],"name":"removeMinter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"addedAccount","type":"address"},{"indexed":true,"internalType":"uint256","name":"accountIndex","type":"uint256"}],"name":"AddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"add","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_key","type":"bytes32"}],"name":"addressOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_idx","type":"uint256"}],"name":"entry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"entryCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"register","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"registry","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"_sum","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

View File

@ -0,0 +1,147 @@
# Author: Louis Holbrook <dev@holbrook.no> 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
# SPDX-License-Identifier: GPL-3.0-or-later
# File-version: 1
# Description: Python interface to abi and bin files for faucet contracts
# standard imports
import logging
import json
import os
import hashlib
# external imports
from chainlib.eth.contract import (
ABIContractEncoder,
ABIContractType,
abi_decode_single,
)
from chainlib.eth.tx import (
TxFactory,
TxFormat,
)
from chainlib.jsonrpc import JSONRPCRequest
from chainlib.eth.constant import ZERO_ADDRESS
from hexathon import (
add_0x,
)
logg = logging.getLogger(__name__)
moddir = os.path.dirname(__file__)
datadir = os.path.join(moddir, 'data')
def to_identifier(s):
h = hashlib.new('sha256')
h.update(s.encode('utf-8'))
return h.digest().hex()
class TokenUniqueSymbolIndex(TxFactory):
__abi = None
__bytecode = None
@staticmethod
def abi():
if TokenUniqueSymbolIndex.__abi == None:
f = open(os.path.join(datadir, 'TokenUniqueSymbolIndex.json'), 'r')
TokenUniqueSymbolIndex.__abi = json.load(f)
f.close()
return TokenUniqueSymbolIndex.__abi
@staticmethod
def bytecode():
if TokenUniqueSymbolIndex.__bytecode == None:
f = open(os.path.join(datadir, 'TokenUniqueSymbolIndex.bin'))
TokenUniqueSymbolIndex.__bytecode = f.read()
f.close()
return TokenUniqueSymbolIndex.__bytecode
@staticmethod
def gas(code=None):
return 1200000
def constructor(self, sender_address):
code = TokenUniqueSymbolIndex.bytecode()
tx = self.template(sender_address, None, use_nonce=True)
tx = self.set_code(tx, code)
return self.build(tx)
def register(self, contract_address, sender_address, address, tx_format=TxFormat.JSONRPC):
enc = ABIContractEncoder()
enc.method('register')
enc.typ(ABIContractType.ADDRESS)
enc.address(address)
data = enc.get()
tx = self.template(sender_address, contract_address, use_nonce=True)
tx = self.set_code(tx, data)
tx = self.finalize(tx, tx_format)
return tx
def address_of(self, contract_address, token_symbol, sender_address=ZERO_ADDRESS, id_generator=None):
j = JSONRPCRequest(id_generator)
o = j.template()
o['method'] = 'eth_call'
enc = ABIContractEncoder()
enc.method('addressOf')
enc.typ(ABIContractType.BYTES32)
token_symbol_digest = to_identifier(token_symbol)
enc.bytes32(token_symbol_digest)
data = add_0x(enc.get())
tx = self.template(sender_address, contract_address)
tx = self.set_code(tx, data)
o['params'].append(self.normalize(tx))
o = j.finalize(o)
return o
def entry(self, contract_address, idx, sender_address=ZERO_ADDRESS, id_generator=None):
j = JSONRPCRequest(id_generator)
o = j.template()
o['method'] = 'eth_call'
enc = ABIContractEncoder()
enc.method('entry')
enc.typ(ABIContractType.UINT256)
enc.uint256(idx)
data = add_0x(enc.get())
tx = self.template(sender_address, contract_address)
tx = self.set_code(tx, data)
o['params'].append(self.normalize(tx))
o = j.finalize(o)
return o
def entry_count(self, contract_address, sender_address=ZERO_ADDRESS, id_generator=None):
j = JSONRPCRequest(id_generator)
o = j.template()
o['method'] = 'eth_call'
enc = ABIContractEncoder()
enc.method('entryCount')
data = add_0x(enc.get())
tx = self.template(sender_address, contract_address)
tx = self.set_code(tx, data)
o['params'].append(self.normalize(tx))
o = j.finalize(o)
return o
@classmethod
def parse_address_of(self, v):
return abi_decode_single(ABIContractType.ADDRESS, v)
@classmethod
def parse_entry(self, v):
return abi_decode_single(ABIContractType.ADDRESS, v)
@classmethod
def parse_entry_count(self, v):
return abi_decode_single(ABIContractType.UINT256, v)

View File

@ -0,0 +1,89 @@
"""Adds a new token to the token symbol index
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# standard imports
import sys
import os
import json
import argparse
import logging
import hashlib
# external imports
import chainlib.eth.cli
from chainlib.chain import ChainSpec
from chainlib.eth.tx import receipt
from eth_erc20 import ERC20
from chainlib.eth.address import to_checksum_address
from hexathon import add_0x
# local imports
from eth_token_index import TokenUniqueSymbolIndex
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
arg_flags = chainlib.eth.cli.argflag_std_write | chainlib.eth.cli.Flag.EXEC
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
argparser.add_argument('token_address', type=str, help='Token address to add to index')
args = argparser.parse_args()
extra_args = {
'token_address': None,
}
config = chainlib.eth.cli.Config.from_args(args, arg_flags, extra_args=extra_args, default_fee_limit=TokenUniqueSymbolIndex.gas())
wallet = chainlib.eth.cli.Wallet()
wallet.from_config(config)
rpc = chainlib.eth.cli.Rpc(wallet=wallet)
conn = rpc.connect_by_config(config)
chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
def main():
signer = rpc.get_signer()
signer_address = rpc.get_sender_address()
gas_oracle = rpc.get_gas_oracle()
nonce_oracle = rpc.get_nonce_oracle()
c = TokenUniqueSymbolIndex(chain_spec, signer=signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
token_address = to_checksum_address(config.get('_TOKEN_ADDRESS'))
if not config.true('_UNSAFE') and token_address != add_0x(config.get('_TOKEN_ADDRESS')):
raise ValueError('invalid checksum address for token_address')
contract_address = to_checksum_address(config.get('_EXEC_ADDRESS'))
if not config.true('_UNSAFE') and contract_address != add_0x(config.get('_EXEC_ADDRESS')):
raise ValueError('invalid checksum address for contract')
(tx_hash_hex, o) = c.register(contract_address, signer_address, token_address)
if config.get('_RPC_SEND'):
conn.do(o)
if config.get('_WAIT'):
r = conn.wait(tx_hash_hex)
if r['status'] == 0:
sys.stderr.write('EVM revert while deploying contract. Wish I had more to tell you')
sys.exit(1)
c = ERC20(chain_spec)
o = c.symbol(token_address)
r = conn.do(o)
token_symbol = ERC20.parse_symbol(r)
logg.info('added token {} at {} to token index {}'.format(token_symbol, token_address, contract_address))
print(tx_hash_hex)
else:
print(o)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,69 @@
"""Deploys the token symbol index
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# standard imports
import sys
import os
import json
import argparse
import logging
# external imports
import chainlib.eth.cli
from chainlib.chain import ChainSpec
from chainlib.eth.tx import receipt
# local imports
from eth_token_index import TokenUniqueSymbolIndex
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
arg_flags = chainlib.eth.cli.argflag_std_write
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
args = argparser.parse_args()
config = chainlib.eth.cli.Config.from_args(args, arg_flags, default_fee_limit=TokenUniqueSymbolIndex.gas())
wallet = chainlib.eth.cli.Wallet()
wallet.from_config(config)
rpc = chainlib.eth.cli.Rpc(wallet=wallet)
conn = rpc.connect_by_config(config)
chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
def main():
signer = rpc.get_signer()
signer_address = rpc.get_sender_address()
gas_oracle = rpc.get_gas_oracle()
nonce_oracle = rpc.get_nonce_oracle()
c = TokenUniqueSymbolIndex(chain_spec, signer=signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
(tx_hash_hex, o) = c.constructor(signer_address)
if config.get('_RPC_SEND'):
conn.do(o)
if config.get('_WAIT'):
r = conn.wait(tx_hash_hex)
if r['status'] == 0:
sys.stderr.write('EVM revert while deploying contract. Wish I had more to tell you')
sys.exit(1)
# TODO: pass through translator for keys (evm tester uses underscore instead of camelcase)
address = r['contractAddress']
print(address)
else:
print(tx_hash_hex)
else:
print(o)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,100 @@
"""Adds a new token to the token symbol index
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# standard imports
import sys
import os
import json
import argparse
import logging
import hashlib
# external imports
import chainlib.eth.cli
from chainlib.chain import ChainSpec
from eth_erc20 import ERC20
from chainlib.eth.address import to_checksum_address
from hexathon import add_0x
# local imports
from eth_token_index import TokenUniqueSymbolIndex
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
default_format = 'terminal'
script_dir = os.path.dirname(__file__)
data_dir = os.path.join(script_dir, '..', 'data')
arg_flags = chainlib.eth.cli.argflag_std_write | chainlib.eth.cli.Flag.EXEC
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
argparser.add_argument('token_symbol', type=str, nargs='?', help='Token symbol to return address for')
args = argparser.parse_args()
extra_args = {
'token_symbol': None,
}
config = chainlib.eth.cli.Config.from_args(args, arg_flags, extra_args=extra_args, default_fee_limit=TokenUniqueSymbolIndex.gas())
#wallet = chainlib.eth.cli.Wallet()
#wallet.from_config(config)
rpc = chainlib.eth.cli.Rpc()
conn = rpc.connect_by_config(config)
chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
def out_element(e, w=sys.stdout):
if config.get('_RAW'):
w.write(e[1] + '\n')
else:
w.write(e[1] + '\t' + e[0] + '\n')
def element(ifc, conn, contract_address, token_symbol, w=sys.stdout):
o = ifc.address_of(contract_address, token_symbol)
r = conn.do(o)
a = ifc.parse_address_of(r)
out_element((token_symbol, a), w)
def ls(ifc, conn, contract_address, token_ifc, w=sys.stdout):
o = ifc.entry_count(contract_address)
r = conn.do(o)
count = ifc.parse_entry_count(r)
logg.debug('count {}'.format(count))
for i in range(count):
o = ifc.entry(contract_address, i)
r = conn.do(o)
token_address = ifc.parse_entry(r)
o = token_ifc.symbol(token_address)
r = conn.do(o)
token_symbol = token_ifc.parse_symbol(r)
element(ifc, conn, contract_address, token_symbol, w)
def main():
token_ifc = ERC20(chain_spec)
ifc = TokenUniqueSymbolIndex(chain_spec)
contract_address = to_checksum_address(config.get('_EXEC_ADDRESS'))
if not config.true('_UNSAFE') and contract_address != add_0x(config.get('_EXEC_ADDRESS')):
raise ValueError('invalid checksum address for contract')
token_symbol = config.get('_TOKEN_SYMBOL')
if token_symbol != None:
element(ifc, conn, contract_address, token_symbol, sys.stdout)
else:
ls(ifc, conn, contract_address, token_ifc, sys.stdout)
if __name__ == '__main__':
main()

5
python/requirements.txt Normal file
View File

@ -0,0 +1,5 @@
confini>=0.3.6rc3,<0.5.0
crypto-dev-signer>=0.4.15rc2,<=0.4.15
chainlib-eth>=0.0.9a13,<=0.1.0
eth_erc20>=0.1.2a3,<=0.2.0
eth-address-index>=0.2.4a1

45
python/setup.cfg Normal file
View File

@ -0,0 +1,45 @@
[metadata]
name = eth-token-index
version = 0.2.4a1
description = Token symbol to address unique index
author = Louis Holbrook
author_email = dev@holbrook.no
url = https://gitlab.com/cicnet/eth-address-index
keywords =
ethereum
classifiers =
Programming Language :: Python :: 3
Operating System :: OS Independent
Development Status :: 3 - Alpha
Environment :: No Input/Output (Daemon)
Intended Audience :: Developers
License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
Topic :: Internet
#Topic :: Blockchain :: EVM
license = GPL3
licence_files =
LICENSE
[options]
include_package_data = True
python_requires = >= 3.6
packages =
eth_token_index
eth_token_index.runnable
[options.extras_require]
testing =
eth-tester==0.5.0b2
py-evm==0.3.0a20
[options.package_data]
* =
data/TokenUniqueSymbolIndex.bin
data/TokenUniqueSymbolIndex.json
data/ERC20.json
[options.entry_points]
console_scripts =
eth-token-index-deploy = eth_token_index.runnable.deploy:main
eth-token-index-add = eth_token_index.runnable.add:main
eth-token-index-list = eth_token_index.runnable.list:main

25
python/setup.py Normal file
View File

@ -0,0 +1,25 @@
from setuptools import setup
requirements = []
f = open('requirements.txt', 'r')
while True:
l = f.readline()
if l == '':
break
requirements.append(l.rstrip())
f.close()
test_requirements = []
f = open('test_requirements.txt', 'r')
while True:
l = f.readline()
if l == '':
break
test_requirements.append(l.rstrip())
f.close()
setup(
install_requires=requirements,
tests_require=test_requirements,
)

View File

@ -0,0 +1,2 @@
eth-tester==0.5.0b3
py-evm==0.3.0a20

View File

@ -0,0 +1,78 @@
# standard imports
import os
import unittest
import json
import logging
import hashlib
# external imports
from chainlib.eth.unittest.ethtester import EthTesterCase
from chainlib.eth.nonce import RPCNonceOracle
from chainlib.eth.tx import receipt
from giftable_erc20_token import GiftableToken
from chainlib.eth.tx import unpack
from hexathon import strip_0x
from chainlib.eth.contract import ABIContractEncoder
# local imports
from eth_token_index.index import (
TokenUniqueSymbolIndex,
to_identifier,
)
# test imports
from eth_address_declarator.declarator import Declarator
from eth_address_declarator.unittest import TestAddressDeclaratorBase
logging.basicConfig(level=logging.DEBUG)
logg = logging.getLogger()
testdir = os.path.dirname(__file__)
class TestTokenUniqueSymbolIndex(TestAddressDeclaratorBase):
def setUp(self):
super(TestTokenUniqueSymbolIndex, self).setUp()
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = TokenUniqueSymbolIndex(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash_hex, o) = c.constructor(self.accounts[0])
self.rpc.do(o)
o = receipt(tx_hash_hex)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
self.token_index_address = r['contract_address']
def test_register(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = TokenUniqueSymbolIndex(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash_hex, o) = c.register(self.token_index_address, self.accounts[0], self.foo_token_address)
self.rpc.do(o)
e = unpack(bytes.fromhex(strip_0x(o['params'][0])), self.chain_spec)
o = receipt(tx_hash_hex)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.address_of(self.token_index_address, 'FOO', sender_address=self.accounts[0])
r = self.rpc.do(o)
address = c.parse_address_of(r)
self.assertEqual(address, strip_0x(self.foo_token_address))
o = c.entry(self.token_index_address, 0, sender_address=self.accounts[0])
r = self.rpc.do(o)
address = c.parse_entry(r)
self.assertEqual(address, strip_0x(self.foo_token_address))
o = c.entry_count(self.token_index_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
count = c.parse_entry_count(r)
self.assertEqual(count, 1)
if __name__ == '__main__':
unittest.main()

11
solidity/Makefile Normal file
View File

@ -0,0 +1,11 @@
SOLC = /usr/bin/solc
all:
$(SOLC) TokenUniqueSymbolIndex.sol --abi --evm-version byzantium | awk 'NR>3' > TokenUniqueSymbolIndex.json
$(SOLC) TokenUniqueSymbolIndex.sol --bin --evm-version byzantium | awk 'NR>3' > TokenUniqueSymbolIndex.bin
truncate -s -1 TokenUniqueSymbolIndex.bin
install: all
cp -v TokenUniqueSymbolIndex.{json,bin} ../python/eth_token_index/data/
.PHONY: install

View File

@ -0,0 +1,105 @@
pragma solidity >0.6.11;
// SPDX-License-Identifier: GPL-3.0-or-later
contract TokenUniqueSymbolIndex {
// EIP 173
address public owner;
address newOwner;
mapping ( bytes32 => uint256 ) public registry;
address[] tokens;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // EIP173
event AddressAdded(address indexed addedAccount, uint256 indexed accountIndex); // AccountsIndex
constructor() public {
owner = msg.sender;
tokens.push(address(0));
}
// Implements AccountsIndex
function entry(uint256 _idx) public view returns ( address ) {
return tokens[_idx + 1];
}
// Implements Registry
function addressOf(bytes32 _key) public view returns ( address ) {
uint256 idx;
idx = registry[_key];
return tokens[idx];
}
function register(address _token) public returns (bool) {
require(msg.sender == owner);
bytes memory token_symbol;
bytes32 token_symbol_key;
uint256 idx;
(bool _ok, bytes memory _r) = _token.call(abi.encodeWithSignature('symbol()'));
require(_ok);
token_symbol = abi.decode(_r, (bytes));
token_symbol_key = sha256(token_symbol);
idx = registry[token_symbol_key];
require(idx == 0);
registry[token_symbol_key] = tokens.length;
tokens.push(_token);
emit AddressAdded(_token, tokens.length - 1);
return true;
}
// Implements AccountsIndex
function add(address _token) public returns (bool) {
return register(_token);
}
// Implements AccountsIndex
function entryCount() public view returns ( uint256 ) {
return tokens.length - 1;
}
// Implements EIP173
function transferOwnership(address _newOwner) public returns (bool) {
require(msg.sender == owner);
newOwner = _newOwner;
}
// Implements OwnedAccepter
function acceptOwnership() public returns (bool) {
address oldOwner;
require(msg.sender == newOwner);
oldOwner = owner;
owner = newOwner;
newOwner = address(0);
emit OwnershipTransferred(oldOwner, owner);
}
// Implements EIP165
function supportsInterface(bytes4 _sum) public pure returns (bool) {
if (_sum == 0xcbdb05c7) { // AccountsIndex
return true;
}
if (_sum == 0xbb34534c) { // Registry
return true;
}
if (_sum == 0x01ffc9a7) { // EIP165
return true;
}
if (_sum == 0x9493f8b2) { // EIP173
return true;
}
if (_sum == 0x37a47be4) { // OwnedAccepter
return true;
}
return false;
}
}