Move token index, accounts index out of repo

This commit is contained in:
nolash 2021-10-04 12:35:10 +02:00
parent 47f59735bd
commit c3c948e9e3
Signed by: lash
GPG Key ID: 21D2E7BB88C2A746
23 changed files with 11 additions and 995 deletions

View File

@ -1 +0,0 @@
from .accounts_index import *

View File

@ -1,54 +0,0 @@
# standard imports
import os
# external imports
from chainlib.eth.tx import (
TxFormat,
)
from chainlib.eth.contract import (
ABIContractEncoder,
ABIContractType,
)
from eth_accounts_index.interface import AccountsIndex
moddir = os.path.dirname(__file__)
datadir = os.path.join(moddir, '..', 'data')
class AccountsIndexAddressDeclarator(AccountsIndex):
__abi = None
__bytecode = None
@staticmethod
def abi():
if AccountsIndexAddressDeclarator.__abi == None:
f = open(os.path.join(datadir, 'AccountsIndexAddressDeclarator.json'), 'r')
AccountsIndexAddressDeclarator.__abi = json.load(f)
f.close()
return AccountsIndexAddressDeclarator.__abi
@staticmethod
def bytecode():
if AccountsIndexAddressDeclarator.__bytecode == None:
f = open(os.path.join(datadir, 'AccountsIndexAddressDeclarator.bin'))
AccountsIndexAddressDeclarator.__bytecode = f.read()
f.close()
return AccountsIndexAddressDeclarator.__bytecode
@staticmethod
def gas(code=None):
return 700000
def constructor(self, sender_address, context_address, address_declarator_address):
code = AccountsIndexAddressDeclarator.bytecode()
tx = self.template(sender_address, None, use_nonce=True)
enc = ABIContractEncoder()
enc.address(context_address)
enc.address(address_declarator_address)
code += enc.get()
tx = self.set_code(tx, code)
return self.build(tx)

View File

@ -1,85 +0,0 @@
"""Deploys accounts index, registering arbitrary number of writers
.. 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.connection import EthHTTPConnection
from chainlib.eth.tx import receipt
# local imports
from eth_address_declarator.accounts_index import AccountsIndexAddressDeclarator
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
arg_flags = chainlib.eth.cli.argflag_std_write
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
argparser.add_argument('--address-declarator', type=str, required=True, dest='address_declarator', help='address declarator backend address')
argparser.add_argument('--token-address', type=str, required=True, dest='token_address', help='token address context for accounts registry')
args = argparser.parse_args()
extra_args = {
'address_declarator': None,
'token_address': None,
}
config = chainlib.eth.cli.Config.from_args(args, arg_flags, extra_args=extra_args, default_fee_limit=AccountsIndexAddressDeclarator.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()
address_declarator = config.get('_ADDRESS_DECLARATOR')
if not config.true('_UNSAFE') and not is_checksum_address(address_declarator):
raise ValueError('address declarator {} is not a valid checksum address'.format(address_declarator))
token_address = config.get('_TOKEN_ADDRESS')
if not config.true('_UNSAFE') and not is_checksum_address(token_address):
raise ValueError('token {} is not a valid checksum address'.format(token_address))
c = AccountsIndexAddressDeclarator(chain_spec, signer=signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
(tx_hash_hex, o) = c.constructor(signer_address, token_address, address_declarator)
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

@ -1 +0,0 @@
from .interface import *

View File

@ -1,77 +0,0 @@
# 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 token index with address declarator backend
# 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,
)
# local imports
from .interface import (
TokenUniqueSymbolIndex,
to_identifier,
)
logg = logging.getLogger(__name__)
moddir = os.path.dirname(__file__)
datadir = os.path.join(moddir, '..', 'data')
class TokenUniqueSymbolIndexAddressDeclarator(TokenUniqueSymbolIndex):
__abi = None
__bytecode = None
@staticmethod
def abi():
if TokenUniqueSymbolIndexAddressDeclarator.__abi == None:
f = open(os.path.join(datadir, 'TokenUniqueSymbolIndexAddressDeclarator.json'), 'r')
TokenUniqueSymbolIndexAddressDeclarator.__abi = json.load(f)
f.close()
return TokenUniqueSymbolIndexAddressDeclarator.__abi
@staticmethod
def bytecode():
if TokenUniqueSymbolIndexAddressDeclarator.__bytecode == None:
f = open(os.path.join(datadir, 'TokenUniqueSymbolIndexAddressDeclarator.bin'))
TokenUniqueSymbolIndexAddressDeclarator.__bytecode = f.read()
f.close()
return TokenUniqueSymbolIndexAddressDeclarator.__bytecode
@staticmethod
def gas(code=None):
return 2000000
def constructor(self, sender_address, address_declarator_address):
code = TokenUniqueSymbolIndexAddressDeclarator.bytecode()
tx = self.template(sender_address, None, use_nonce=True)
enc = ABIContractEncoder()
enc.address(address_declarator_address)
code += enc.get()
tx = self.set_code(tx, code)
return self.build(tx)

View File

@ -1,113 +0,0 @@
# 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):
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

@ -1,78 +0,0 @@
"""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_address_declarator.token_index.index import TokenUniqueSymbolIndexAddressDeclarator
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
arg_flags = chainlib.eth.cli.argflag_std_write
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
argparser.add_argument('--address-declarator', type=str, required=True, dest='address_declarator', help='address declarator backend address')
args = argparser.parse_args()
extra_args = {
'address_declarator': None,
}
config = chainlib.eth.cli.Config.from_args(args, arg_flags, extra_args=extra_args, default_fee_limit=TokenUniqueSymbolIndexAddressDeclarator.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()
address_declarator = config.get('_ADDRESS_DECLARATOR')
if not config.true('_UNSAFE') and not is_checksum_address(address_declarator):
raise ValueError('address declarator {} is not a valid checksum address'.format(address_declarator))
c = TokenUniqueSymbolIndexAddressDeclarator(chain_spec, signer=signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
(tx_hash_hex, o) = c.constructor(signer_address, config.get('_ADDRESS_DECLARATOR'))
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 @@
from .addressdeclarator import *

View File

@ -17,10 +17,10 @@ logging.basicConfig(level=logging.DEBUG)
logg = logging.getLogger() logg = logging.getLogger()
class TestBase(EthTesterCase): class TestAddressDeclaratorBase(EthTesterCase):
def setUp(self): def setUp(self):
super(TestBase, self).setUp() super(TestAddressDeclaratorBase, self).setUp()
self.description = add_0x(os.urandom(32).hex()) self.description = add_0x(os.urandom(32).hex())
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc) nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = AddressDeclarator(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle) c = AddressDeclarator(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)

View File

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

View File

@ -1 +0,0 @@
[{"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

@ -1 +0,0 @@
[{"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"}]

View File

@ -1,147 +0,0 @@
# 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 TokenUniqueSymbolIndexAddressDeclarator(TxFactory):
__abi = None
__bytecode = None
@staticmethod
def abi():
if TokenUniqueSymbolIndexAddressDeclarator.__abi == None:
f = open(os.path.join(datadir, 'TokenUniqueSymbolIndexAddressDeclarator.json'), 'r')
TokenUniqueSymbolIndexAddressDeclarator.__abi = json.load(f)
f.close()
return TokenUniqueSymbolIndexAddressDeclarator.__abi
@staticmethod
def bytecode():
if TokenUniqueSymbolIndexAddressDeclarator.__bytecode == None:
f = open(os.path.join(datadir, 'TokenUniqueSymbolIndexAddressDeclarator.bin'))
TokenUniqueSymbolIndexAddressDeclarator.__bytecode = f.read()
f.close()
return TokenUniqueSymbolIndexAddressDeclarator.__bytecode
@staticmethod
def gas(code=None):
return 1200000
def constructor(self, sender_address):
code = TokenUniqueSymbolIndexAddressDeclarator.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

@ -1,89 +0,0 @@
"""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

@ -1,69 +0,0 @@
"""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

@ -1,100 +0,0 @@
"""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()

View File

@ -28,6 +28,7 @@ packages =
eth_address_declarator.runnable eth_address_declarator.runnable
eth_token_index eth_token_index
eth_token_index.runnable eth_token_index.runnable
eth_token_index.unittest
[options.extras_require] [options.extras_require]
testing = testing =

View File

@ -22,7 +22,7 @@ from hexathon import (
# local imports # local imports
from eth_address_declarator.declarator import AddressDeclarator from eth_address_declarator.declarator import AddressDeclarator
from eth_address_declarator import Declarator from eth_address_declarator import Declarator
from tests.test_addressdeclarator_base import TestBase from eth_address_declarator.unittest import TestAddressDeclaratorBase
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
logg = logging.getLogger() logg = logging.getLogger()
@ -32,7 +32,7 @@ testdir = os.path.dirname(__file__)
description = '0x{:<064s}'.format(b'foo'.hex()) description = '0x{:<064s}'.format(b'foo'.hex())
class TestAddressDeclarator(TestBase): class TestAddressDeclarator(TestAddressDeclaratorBase):
def setUp(self): def setUp(self):
super(TestAddressDeclarator, self).setUp() super(TestAddressDeclarator, self).setUp()
@ -145,15 +145,15 @@ class TestAddressDeclarator(TestBase):
o = c.declaration_address_at(self.address, self.accounts[1], 0, sender_address=self.accounts[0]) o = c.declaration_address_at(self.address, self.accounts[1], 0, sender_address=self.accounts[0])
r = self.rpc.do(o) r = self.rpc.do(o)
self.assertEqual(c.parse_declaration_address_at(r), self.foo_token_address) self.assertEqual(c.parse_declaration_address_at(r), strip_0x(self.foo_token_address))
o = c.declaration_address_at(self.address, self.accounts[2], 0, sender_address=self.accounts[0]) o = c.declaration_address_at(self.address, self.accounts[2], 0, sender_address=self.accounts[0])
r = self.rpc.do(o) r = self.rpc.do(o)
self.assertEqual(c.parse_declaration_address_at(r), self.foo_token_address) self.assertEqual(c.parse_declaration_address_at(r), strip_0x(self.foo_token_address))
o = c.declaration_address_at(self.address, self.accounts[1], 1, sender_address=self.accounts[0]) o = c.declaration_address_at(self.address, self.accounts[1], 1, sender_address=self.accounts[0])
r = self.rpc.do(o) r = self.rpc.do(o)
self.assertEqual(c.parse_declaration_address_at(r), self.bar_token_address) self.assertEqual(c.parse_declaration_address_at(r), strip_0x(self.bar_token_address))
def test_subject_to_declarator(self): def test_subject_to_declarator(self):
@ -176,11 +176,11 @@ class TestAddressDeclarator(TestBase):
o = c.declarator_address_at(self.address, self.foo_token_address, 0, sender_address=self.accounts[0]) o = c.declarator_address_at(self.address, self.foo_token_address, 0, sender_address=self.accounts[0])
r = self.rpc.do(o) r = self.rpc.do(o)
self.assertEqual(c.parse_declaration_address_at(r), self.accounts[1]) self.assertEqual(c.parse_declaration_address_at(r), strip_0x(self.accounts[1]))
o = c.declarator_address_at(self.address, self.foo_token_address, 1, sender_address=self.accounts[0]) o = c.declarator_address_at(self.address, self.foo_token_address, 1, sender_address=self.accounts[0])
r = self.rpc.do(o) r = self.rpc.do(o)
self.assertEqual(c.parse_declaration_address_at(r), self.accounts[2]) self.assertEqual(c.parse_declaration_address_at(r), strip_0x(self.accounts[2]))
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,50 +0,0 @@
pragma solidity >0.6.11;
// SPDX-License-Identifier: GPL-3.0-or-later
contract AccountsIndexAddressDeclarator {
address public tokenAddress;
bytes32 tokenAddressHash;
address public addressDeclaratorAddress;
mapping(address => uint256) entryIndex;
uint256 count;
address public owner;
address newOwner;
event AddressAdded(address indexed addedAccount, uint256 indexed accountIndex); // AccountsIndex
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // EIP173
constructor(address _tokenAddress, address _addressDeclaratorAddress) public {
bytes memory _tokenAddressPadded;
owner = msg.sender;
addressDeclaratorAddress = _addressDeclaratorAddress;
tokenAddress = _tokenAddress;
_tokenAddressPadded = abi.encode(tokenAddress);
tokenAddressHash = sha256(_tokenAddressPadded);
count = 1;
}
function add(address _account) external returns (bool) {
bool ok;
bytes memory r;
uint256 oldEntryIndex;
(ok, r) = addressDeclaratorAddress.call(abi.encodeWithSignature("addDeclaration(address,bytes32)", _account, tokenAddressHash));
require(ok);
require(r[31] == 0x01);
oldEntryIndex = count;
entryIndex[_account] = oldEntryIndex;
count++;
emit AddressAdded(_account, oldEntryIndex);
return true;
}
function have(address _account) external view returns (bool) {
return entryIndex[_account] > 0;
}
}

View File

@ -1,115 +0,0 @@
pragma solidity >0.6.11;
// SPDX-License-Identifier: GPL-3.0-or-later
contract TokenUniqueSymbolIndexAddressDeclarator {
// EIP 173
address public owner;
address newOwner;
address public addressDeclaratorAddress;
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(address _addressDeclaratorAddress) public {
owner = msg.sender;
addressDeclaratorAddress = _addressDeclaratorAddress;
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);
bool ok;
bytes memory r;
bytes memory token_symbol;
bytes32 token_symbol_key;
uint256 idx;
(ok, r) = _token.call(abi.encodeWithSignature('symbol()'));
require(ok);
token_symbol = abi.decode(r, (bytes));
token_symbol_key = sha256(token_symbol);
(ok, r) = addressDeclaratorAddress.call(abi.encodeWithSignature("addDeclaration(address,bytes32)", _token, token_symbol_key));
require(ok);
require(r[31] == 0x01);
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;
}
}