84 lines
2.4 KiB
Python
84 lines
2.4 KiB
Python
# standard imports
|
|
import os
|
|
import stat
|
|
import logging
|
|
|
|
# external imports
|
|
from chainlib.eth.constant import ZERO_ADDRESS
|
|
from cic_eth_registry.erc20 import ERC20Token
|
|
|
|
# local imports
|
|
from clicada.store.mem import MemDictStore
|
|
from clicada.encode import tx_normalize
|
|
|
|
logg = logging.getLogger(__name__)
|
|
|
|
|
|
# TODO: merge into cic-eth-registry
|
|
class FileTokenStore:
|
|
|
|
def __init__(self, chain_spec, conn, label, store_base_path, caller_address=ZERO_ADDRESS):
|
|
self.label = label
|
|
self.store_path = os.path.join(store_base_path, self.label)
|
|
os.makedirs(self.store_path, exist_ok=True)
|
|
self.__validate_dir()
|
|
self.caller_address = caller_address
|
|
self.memstore_symbol = MemDictStore()
|
|
self.memstore_decimals = MemDictStore()
|
|
self.conn = conn
|
|
self.chain_spec = chain_spec
|
|
|
|
|
|
def __validate_dir(self):
|
|
st = os.stat(self.store_path)
|
|
if stat.S_ISDIR(st.st_mode):
|
|
logg.debug('using existing file store {} for {}'.format(self.store_path, self.label))
|
|
|
|
|
|
def __cache_token(self, address):
|
|
token = ERC20Token(self.chain_spec, self.conn, address)
|
|
logg.info('cached token symbol {} for address {}'.format(token.symbol, address))
|
|
|
|
p = os.path.join(self.store_path, address)
|
|
f = open(p, 'w')
|
|
f.write(token.symbol)
|
|
f.close()
|
|
|
|
p_decimals = os.path.join(self.store_path, token.symbol)
|
|
f = open(p_decimals, 'w')
|
|
f.write(str(token.decimals))
|
|
f.close()
|
|
|
|
return p
|
|
|
|
|
|
def by_address(self, address):
|
|
address = tx_normalize.executable_address(address)
|
|
|
|
token_symbol = self.memstore_symbol.get(address)
|
|
if token_symbol != None:
|
|
token_decimals = self.memstore_decimals.get(token_symbol)
|
|
return (token_symbol, token_decimals,)
|
|
|
|
p = os.path.join(self.store_path, address)
|
|
f = None
|
|
try:
|
|
f = open(p, 'r')
|
|
except FileNotFoundError:
|
|
p = self.__cache_token(address)
|
|
f = open(p, 'r')
|
|
|
|
token_symbol = f.read()
|
|
f.close()
|
|
|
|
p = os.path.join(self.store_path, token_symbol)
|
|
f = open(p, 'r')
|
|
r = f.read()
|
|
f.close()
|
|
token_decimals = int(r)
|
|
|
|
self.memstore_symbol.put(address, token_symbol)
|
|
self.memstore_decimals.put(token_symbol, token_decimals)
|
|
|
|
return (token_symbol, token_decimals,)
|