示例#1
0
class DexTokenPairDisabler(BaseChanger):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_dex/TokenPairDisabler.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_dex/TokenPairDisabler.bin'))

    contract_governor_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_dex/Governor.abi'))
    contract_governor_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_dex/Governor.bin'))

    mode = 'DEX'

    def constructor(self,
                    base_address,
                    secondary_address,
                    execute_change=False):

        network = self.connection_manager.network
        contract_address = Web3.toChecksumAddress(self.connection_manager.options['networks'][network]['addresses']['dex'])

        self.log.info("Deploying new contract...")

        tx_hash, tx_receipt = self.fnx_constructor(contract_address,
                                                   Web3.toChecksumAddress(base_address),
                                                   Web3.toChecksumAddress(secondary_address))

        self.log.info("Deployed contract done!")
        self.log.info(Web3.toHex(tx_hash))
        self.log.info(tx_receipt)

        self.log.info("Changer Contract Address: {address}".format(address=tx_receipt.contractAddress))

        if execute_change:
            self.log.info("Executing change....")
            governor = self.load_governor()
            tx_hash = self.connection_manager.fnx_transaction(governor, 'executeChange', tx_receipt.contractAddress)
            tx_receipt = self.connection_manager.wait_transaction_receipt(tx_hash)
            self.log.info(Web3.toHex(tx_hash))
            self.log.info(tx_receipt)
            self.log.info("Change successfull!")

        return tx_hash, tx_receipt
示例#2
0
class RDOCPriceProviderChanger(MoCPriceProviderChanger):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/PriceProviderChanger.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/PriceProviderChanger.bin'))

    contract_governor_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/Governor.abi'))
    contract_governor_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/Governor.bin'))

    mode = 'RDoC'
示例#3
0
class RDOCFeedFactory(FeedFactory):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/FeedFactory.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/FeedFactory.bin'))

    mode = 'RDoC'
    precision = 10 ** 18
示例#4
0
class RDOCMoCSettlement(MoCSettlement):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCSettlement.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCSettlement.bin'))

    precision = 10 ** 18
    mode = 'RDoC'
示例#5
0
class RDOCMoCMedianizer(MoCMedianizer):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCMedianizer.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCMedianizer.bin'))

    mode = 'RDoC'
    precision = 10 ** 18
示例#6
0
class MoCSetCommissionFinalAddressChanger(BaseChanger):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/SetCommissionFinalAddressChanger.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/SetCommissionFinalAddressChanger.bin'))

    contract_governor_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/Governor.abi'))
    contract_governor_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/Governor.bin'))

    mode = 'MoC'

    def constructor(self, commission_address, commission_splitter=None, execute_change=False):

        network = self.connection_manager.network
        if not commission_splitter:
            commission_splitter = self.connection_manager.options['networks'][network]['addresses']['CommissionSplitter']

        self.log.info("Deploying new contract...")

        tx_hash, tx_receipt = self.fnx_constructor(Web3.toChecksumAddress(commission_splitter),
                                                   Web3.toChecksumAddress(commission_address))

        self.log.info("Deployed contract done!")
        self.log.info(Web3.toHex(tx_hash))
        self.log.info(tx_receipt)

        self.log.info("Changer Contract Address: {address}".format(address=tx_receipt.contractAddress))

        if execute_change:
            self.log.info("Executing change....")
            governor = self.load_governor()
            tx_hash = self.connection_manager.fnx_transaction(governor, 'executeChange', tx_receipt.contractAddress)
            tx_receipt = self.connection_manager.wait_transaction_receipt(tx_hash)
            self.log.info(Web3.toHex(tx_hash))
            self.log.info(tx_receipt)
            self.log.info("Change successfull!")

        return tx_hash, tx_receipt
示例#7
0
class MocInrateBitProInterestChanger(BaseChanger):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/MocInrateBitProInterestChanger.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/MocInrateBitProInterestChanger.bin'))

    contract_governor_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/Governor.abi'))
    contract_governor_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/Governor.bin'))

    mode = 'MoC'

    def constructor(self, bitpro_blockspan, execute_change=False):

        network = self.connection_manager.network
        contract_address = self.connection_manager.options['networks'][network]['addresses']['MoCInrate']

        self.log.info("Deploying new contract...")

        tx_hash, tx_receipt = self.fnx_constructor(Web3.toChecksumAddress(contract_address),
                                                   bitpro_blockspan)

        self.log.info("Deployed contract done!")
        self.log.info(Web3.toHex(tx_hash))
        self.log.info(tx_receipt)

        self.log.info("Changer Contract Address: {address}".format(address=tx_receipt.contractAddress))

        if execute_change:
            self.log.info("Executing change....")
            governor = self.load_governor()
            tx_hash = self.connection_manager.fnx_transaction(governor, 'executeChange', tx_receipt.contractAddress)
            tx_receipt = self.connection_manager.wait_transaction_receipt(tx_hash)
            self.log.info(Web3.toHex(tx_hash))
            self.log.info(tx_receipt)
            self.log.info("Change successfull!")

        return tx_hash, tx_receipt
示例#8
0
class RDOCGoverned(Governed):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/Governed.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/Governed.bin'))

    mode = 'RDoC'
    precision = 10**18
示例#9
0
class DEXGovernor(Governor):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/Governor.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/Governor.bin'))

    mode = 'DEX'
    precision = 10**18
示例#10
0
class RDOCMoCBucketContainerChanger(BaseChanger):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCBucketContainerChanger.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCBucketContainerChanger.bin'))

    contract_governor_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/Governor.abi'))
    contract_governor_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/Governor.bin'))

    mode = 'RDoC'

    def constructor(self, cobj_c0, cobj_x2, execute_change=False):

        network = self.connection_manager.network
        contract_address = self.connection_manager.options['networks'][network]['addresses']['MoCBProxManager']

        self.log.info("Deploying new contract...")

        tx_hash, tx_receipt = self.fnx_constructor(contract_address, cobj_c0, cobj_x2)

        self.log.info("Deployed contract done!")
        self.log.info(tx_hash)
        self.log.info(tx_receipt)

        self.log.info("Changer Contract Address: {address}".format(address=tx_receipt.contractAddress))

        if execute_change:
            self.log.info("Executing change....")
            governor = self.load_governor()
            tx_hash = self.connection_manager.fnx_transaction(governor, 'executeChange', tx_receipt.contractAddress)
            tx_receipt = self.connection_manager.wait_transaction_receipt(tx_hash)
            self.log.info(tx_hash)
            self.log.info(tx_receipt)
            self.log.info("Change successfull!")

        return tx_hash, tx_receipt
示例#11
0
class RRC20PriceFeed(PriceFeed):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/PriceFeed.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/PriceFeed.bin'))

    mode = 'RRC20'
    project = 'RRC20'
    precision = 10**18
示例#12
0
class RRC20MoCConnector(MoCConnector):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/MoCConnector.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/MoCConnector.bin'))

    precision = 10**18
    mode = 'RRC20'
    project = 'RRC20'
示例#13
0
class RDOCMoCBProxManager(RRC20MoCBProxManager):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoCRiskProxManager.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoCRiskProxManager.bin'))

    precision = 10**18
    mode = 'RRC20'
    project = 'RDoC'
示例#14
0
class RDOCMoCState(RRC20MoCState):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoCState.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoCState.bin'))

    mode = 'RRC20'
    project = 'RDoC'
    precision = 10**18
示例#15
0
class CoinPairPrice(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/CoinPairPrice.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/CoinPairPrice.bin'))

    mode = 'MoC'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network][
                'addresses']['CoinPairPrice']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def price(self,
              formatted: bool = True,
              block_identifier: BlockIdentifier = 'latest'):
        """Get price"""

        result = self.sc.functions.peek().call(
            block_identifier=block_identifier)

        if not result[1]:
            raise Exception("No source value price")

        price = Web3.toInt(result[0])

        if formatted:
            price = Web3.fromWei(price, 'ether')

        return price
示例#16
0
class ProxyAdmin(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/ProxyAdmin.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/ProxyAdmin.bin'))

    mode = 'MoC'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network][
                'addresses']['admin']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def implementation(self,
                       contract_address,
                       block_identifier: BlockIdentifier = 'latest'):
        """Get proxy implementation"""

        result = self.sc.functions.getProxyImplementation(
            contract_address).call(block_identifier=block_identifier)

        return result
示例#17
0
class RDOCCommissionSplitter(CommissionSplitter):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/CommissionSplitter.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/CommissionSplitter.bin'))

    mode = 'RDoC'
    precision = 10**18

    def reserve_address(self, block_identifier: BlockIdentifier = 'latest'):
        """The reserve contract address"""

        result = self.sc.functions.reserveToken().call(
            block_identifier=block_identifier)

        return result
示例#18
0
class BProToken(ERC20Token):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/BProToken.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi/BProToken.bin'))

    def __init__(self, connection_manager, contract_address=None, contract_abi=None, contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network]['addresses']['BProToken']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()
示例#19
0
class RDOCMoCState(MoCState):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCState.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'abi_rdoc/MoCState.bin'))

    mode = 'RDoC'
    precision = 10 ** 18

    def collateral_reserves(self, formatted: bool = True,
                            block_identifier: BlockIdentifier = 'latest'):
        """RiskProx values and interests holdings"""

        result = self.sc.functions.collateralReserves().call(
            block_identifier=block_identifier)

        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result
示例#20
0
class MoCDecentralizedExchange(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/MoCDecentralizedExchange.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/MoCDecentralizedExchange.bin'))

    mode = 'DEX'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network][
                'addresses']['dex']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def implementation(self, block_identifier: BlockIdentifier = 'latest'):
        """Implementation of contract"""

        contract_admin = ProxyAdmin(self.connection_manager)
        contract_address = Web3.toChecksumAddress(self.contract_address)

        return contract_admin.implementation(contract_address,
                                             block_identifier=block_identifier)

    def token_pairs(self, block_identifier: BlockIdentifier = 'latest'):
        """ Get the token pairs"""

        result = self.sc.functions.getTokenPairs().call(
            block_identifier=block_identifier)

        return result

    def token_pairs_status(self,
                           base_address,
                           secondary_address,
                           block_identifier: BlockIdentifier = 'latest'):
        """ Get the token pairs"""

        base_address = Web3.toChecksumAddress(base_address)
        secondary_address = Web3.toChecksumAddress(secondary_address)

        result = self.sc.functions.getTokenPairStatus(
            base_address,
            secondary_address).call(block_identifier=block_identifier)

        if result:
            d_status = dict()
            d_status['emergentPrice'] = result[0]
            d_status['lastBuyMatchId'] = result[1]
            d_status['lastBuyMatchAmount'] = result[2]
            d_status['lastSellMatchId'] = result[3]
            d_status['tickNumber'] = result[4]
            d_status['nextTickBlock'] = result[5]
            d_status['lastTickBlock'] = result[6]
            d_status['lastClosingPrice'] = result[7]
            d_status['disabled'] = result[8]
            d_status['EMAPrice'] = result[9]
            d_status['smoothingFactor'] = result[10]
            d_status['marketPrice'] = result[11]

            return d_status

        return result

    def convert_token_to_common_base(
            self,
            token_address,
            amount,
            base_address,
            formatted: bool = True,
            block_identifier: BlockIdentifier = 'latest'):
        """
        @dev simple converter from the given token to a common base, in this case, Dollar on Chain
        @param token_address the token address of token to convert into the common base token
        @param amount the amount to convert
        @param base_address the address of the base of the pair in witch the token its going to operate.
        if the the token it is allready the base of the pair, this parameter it is unimportant
        @return convertedAmount the amount converted into the common base token
        """

        token_address = Web3.toChecksumAddress(token_address)
        base_address = Web3.toChecksumAddress(base_address)

        result = self.sc.functions.convertTokenToCommonBase(
            token_address, amount,
            base_address).call(block_identifier=block_identifier)

        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def get_price_provider(self,
                           base_address,
                           secondary_address,
                           block_identifier: BlockIdentifier = 'latest'):
        """Returns the price provider of a given pair """

        base_address = Web3.toChecksumAddress(base_address)
        secondary_address = Web3.toChecksumAddress(secondary_address)

        result = self.sc.functions.getPriceProvider(
            base_address,
            secondary_address).call(block_identifier=block_identifier)

        return result

    def next_tick(self, pair, block_identifier: BlockIdentifier = 'latest'):
        """ Next tick """

        result = self.sc.functions.getNextTick(
            pair[0], pair[1]).call(block_identifier=block_identifier)

        return result

    def run_tick_for_pair(self,
                          pair,
                          gas_limit=3500000,
                          wait_timeout=240,
                          matching_steps=70,
                          default_account=None,
                          wait_receipt=True):
        """Run tick for pair """

        tx_hash = None
        tx_receipt = None

        block_number = self.connection_manager.block_number
        self.log.info('About to run tick for pair {0}'.format(pair))
        next_tick_info = self.next_tick(pair)
        block_of_next_tick = next_tick_info[1]

        self.log.info('BlockOfNextTick {0}, currentBlockNumber {1}'.format(
            block_of_next_tick, block_number))
        self.log.info(
            'Is tick runnable? {0}'.format(block_of_next_tick <= block_number))
        if block_of_next_tick <= block_number:

            tx_hash = self.connection_manager.fnx_transaction(
                self.sc,
                'matchOrders',
                pair[0],
                pair[1],
                matching_steps,
                default_account=default_account,
                gas_limit=gas_limit)

            self.log.info('Transaction hash of tick run {0}'.format(
                tx_hash.hex()))

            if wait_receipt:
                # wait to transaction be mined
                tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                    tx_hash, timeout=wait_timeout, poll_latency=0.5)

                self.log.info(
                    "Tick runned correctly in Block  [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                    .format(tx_receipt['blockNumber'],
                            Web3.toHex(tx_receipt['transactionHash']),
                            tx_receipt['gasUsed'], tx_receipt['from']))

        else:
            self.log.info('Block of next tick has not been reached\n\n')

        return tx_hash, tx_receipt

    def run_orders_expiration_for_pair(self,
                                       pair,
                                       is_buy_order,
                                       order_type,
                                       hint=0,
                                       order_id=0,
                                       gas_limit=3500000,
                                       wait_timeout=240,
                                       matching_steps=70,
                                       default_account=None,
                                       wait_receipt=True):
        """Run order expiration """

        tx_hash = None
        tx_receipt = None

        block_number = self.connection_manager.block_number

        self.log.info(
            'About to expire {0} orders for pair {1} in blockNumber {2}'.
            format('buy' if is_buy_order else 'sell', pair, block_number))

        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'processExpired',
            pair[0],
            pair[1],
            is_buy_order,
            hint,
            order_id,
            matching_steps,
            order_type,
            default_account=default_account,
            gas_limit=gas_limit)

        self.log.info('Transaction hash of {0} orders expiration {1}'.format(
            'buy' if is_buy_order else 'sell', tx_hash.hex()))

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                tx_hash, timeout=wait_timeout, poll_latency=0.5)

            self.log.info(
                "Orders expiration job finished in block [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                .format(tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt
示例#21
0
class Governor(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/Governor.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/Governor.bin'))

    mode = 'MoC'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network][
                'addresses']['governor']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def owner(self, block_identifier: BlockIdentifier = 'latest'):
        """Owner"""

        result = self.sc.functions.owner().call(
            block_identifier=block_identifier)

        return result

    def transfer_ownership(self,
                           new_owner,
                           gas_limit=3500000,
                           wait_timeout=240,
                           default_account=None,
                           wait_receipt=True):
        """

        :param new_owner:
        :param gas_limit:
        :param wait_timeout:
        :param default_account:
        :param wait_receipt:
        :return:

        function transferOwnership(address newOwner) public onlyOwner {
            _transferOwnership(newOwner);
        }
        """

        tx_receipt = None
        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'transferOwnership',
            Web3.toChecksumAddress(new_owner),
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                tx_hash, timeout=wait_timeout)

            self.log.info(
                "Successfully transfer ownership to: {0} in Block [{1}] Hash: [{2}] Gas used: [{3}] From: [{4}]"
                .format(new_owner, tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt
示例#22
0
class Governed(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/Governed.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/Governed.bin'))

    mode = 'MoC'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        network = connection_manager.network
        if not contract_address:
            raise ValueError("You need to pass contract address")

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def governor(self, block_identifier: BlockIdentifier = 'latest'):
        """Contract address output"""

        result = self.sc.functions.governor().call(
            block_identifier=block_identifier)

        return result

    def initialize(self,
                   governor,
                   gas_limit=3500000,
                   wait_timeout=240,
                   default_account=None,
                   wait_receipt=True):
        """Initialize"""

        governor_address = Web3.toChecksumAddress(governor)

        tx_receipt = None
        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'initialize',
            governor_address,
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_transaction_receipt(
                tx_hash, timeout=wait_timeout)

            self.log.info(
                "Successfully initialized in Block [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                .format(tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt
示例#23
0
class MoCDecentralizedExchange(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/MoCDecentralizedExchange.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/MoCDecentralizedExchange.bin'))

    mode = 'DEX'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network][
                'addresses']['dex']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def implementation(self, block_identifier: BlockIdentifier = 'latest'):
        """Implementation of contract"""

        contract_admin = ProxyAdmin(self.connection_manager)
        contract_address = Web3.toChecksumAddress(self.contract_address)

        return contract_admin.implementation(contract_address,
                                             block_identifier=block_identifier)

    def paused(self, block_identifier: BlockIdentifier = 'latest'):
        """is Paused"""

        result = self.sc.functions.paused().call(
            block_identifier=block_identifier)

        return result

    def min_order_amount(self,
                         formatted: bool = True,
                         block_identifier: BlockIdentifier = 'latest'):
        """Gets min order amount"""

        result = self.sc.functions.minOrderAmount().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def token_pairs(self, block_identifier: BlockIdentifier = 'latest'):
        """ Get the token pairs"""

        result = self.sc.functions.getTokenPairs().call(
            block_identifier=block_identifier)

        return result

    def token_pairs_status(self,
                           base_address,
                           secondary_address,
                           block_identifier: BlockIdentifier = 'latest'):
        """ Get the token pairs"""

        base_address = Web3.toChecksumAddress(base_address)
        secondary_address = Web3.toChecksumAddress(secondary_address)

        result = self.sc.functions.getTokenPairStatus(
            base_address,
            secondary_address).call(block_identifier=block_identifier)

        if result:
            d_status = dict()
            d_status['emergentPrice'] = result[0]
            d_status['lastBuyMatchId'] = result[1]
            d_status['lastBuyMatchAmount'] = result[2]
            d_status['lastSellMatchId'] = result[3]
            d_status['tickNumber'] = result[4]
            d_status['nextTickBlock'] = result[5]
            d_status['lastTickBlock'] = result[6]
            d_status['lastClosingPrice'] = result[7]
            d_status['disabled'] = result[8]
            d_status['EMAPrice'] = result[9]
            d_status['smoothingFactor'] = result[10]
            d_status['marketPrice'] = result[11]

            return d_status

        return result

    def convert_token_to_common_base(
            self,
            token_address,
            amount,
            base_address,
            formatted: bool = True,
            block_identifier: BlockIdentifier = 'latest'):
        """
        @dev simple converter from the given token to a common base, in this case, Dollar on Chain
        @param token_address the token address of token to convert into the common base token
        @param amount the amount to convert
        @param base_address the address of the base of the pair in witch the token its going to operate.
        if the the token it is allready the base of the pair, this parameter it is unimportant
        @return convertedAmount the amount converted into the common base token
        """

        token_address = Web3.toChecksumAddress(token_address)
        base_address = Web3.toChecksumAddress(base_address)

        result = self.sc.functions.convertTokenToCommonBase(
            token_address, amount,
            base_address).call(block_identifier=block_identifier)

        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def get_price_provider(self,
                           base_address,
                           secondary_address,
                           block_identifier: BlockIdentifier = 'latest'):
        """Returns the price provider of a given pair """

        base_address = Web3.toChecksumAddress(base_address)
        secondary_address = Web3.toChecksumAddress(secondary_address)

        result = self.sc.functions.getPriceProvider(
            base_address,
            secondary_address).call(block_identifier=block_identifier)

        return result

    def next_tick(self, pair, block_identifier: BlockIdentifier = 'latest'):
        """ Next tick """

        result = self.sc.functions.getNextTick(
            pair[0], pair[1]).call(block_identifier=block_identifier)

        return result

    def are_orders_to_expire(self,
                             pair,
                             is_buy_order,
                             block_identifier: BlockIdentifier = 'latest'):
        """ Are orders to expire """

        result = self.sc.functions.areOrdersToExpire(
            pair[0], pair[1],
            is_buy_order).call(block_identifier=block_identifier)

        return result

    def emergent_price(self,
                       pair,
                       block_identifier: BlockIdentifier = 'latest'):
        """ Calculates closing price as if the tick closes at this moment.
            emergentPrice: AVG price of the last matched Orders

            return (emergentPrice, lastBuyMatch.id, lastBuyMatch.exchangeableAmount, lastSellMatch.id);
            """

        result = self.sc.functions.getEmergentPrice(
            pair[0], pair[1]).call(block_identifier=block_identifier)

        return result

    def market_price(self,
                     pair,
                     formatted: bool = True,
                     block_identifier: BlockIdentifier = 'latest'):
        """ Get the current market price """

        result = self.sc.functions.getMarketPrice(
            pair[0], pair[1]).call(block_identifier=block_identifier)

        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def run_tick_for_pair(self,
                          pair,
                          gas_limit=3500000,
                          wait_timeout=240,
                          matching_steps=70,
                          default_account=None,
                          wait_receipt=True):
        """Run tick for pair """

        tx_hash = None
        tx_receipt = None

        block_number = self.connection_manager.block_number
        self.log.info('About to run tick for pair {0}'.format(pair))
        next_tick_info = self.next_tick(pair)
        block_of_next_tick = next_tick_info[1]

        self.log.info('BlockOfNextTick {0}, currentBlockNumber {1}'.format(
            block_of_next_tick, block_number))
        self.log.info(
            'Is tick runnable? {0}'.format(block_of_next_tick <= block_number))
        if block_of_next_tick <= block_number:

            tx_hash = self.connection_manager.fnx_transaction(
                self.sc,
                'matchOrders',
                pair[0],
                pair[1],
                matching_steps,
                default_account=default_account,
                gas_limit=gas_limit)

            self.log.info('Transaction hash of tick run {0}'.format(
                tx_hash.hex()))

            if wait_receipt:
                # wait to transaction be mined
                tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                    tx_hash, timeout=wait_timeout, poll_latency=0.5)

                self.log.info(
                    "Tick runned correctly in Block  [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                    .format(tx_receipt['blockNumber'],
                            Web3.toHex(tx_receipt['transactionHash']),
                            tx_receipt['gasUsed'], tx_receipt['from']))

        else:
            self.log.info('Block of next tick has not been reached\n\n')

        return tx_hash, tx_receipt

    def run_orders_expiration_for_pair(self,
                                       pair,
                                       is_buy_order,
                                       order_type,
                                       hint=0,
                                       order_id=0,
                                       gas_limit=3500000,
                                       wait_timeout=240,
                                       matching_steps=70,
                                       default_account=None,
                                       wait_receipt=True):
        """Run order expiration """

        tx_hash = None
        tx_receipt = None

        block_number = self.connection_manager.block_number

        self.log.info(
            'About to expire {0} orders for pair {1} in blockNumber {2}'.
            format('buy' if is_buy_order else 'sell', pair, block_number))

        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'processExpired',
            pair[0],
            pair[1],
            is_buy_order,
            hint,
            order_id,
            matching_steps,
            order_type,
            default_account=default_account,
            gas_limit=gas_limit)

        self.log.info('Transaction hash of {0} orders expiration {1}'.format(
            'buy' if is_buy_order else 'sell', tx_hash.hex()))

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                tx_hash, timeout=wait_timeout, poll_latency=0.5)

            self.log.info(
                "Orders expiration job finished in block [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                .format(tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt

    def _insert_sell_limit_order(self,
                                 base_token,
                                 secondary_token,
                                 amount,
                                 price,
                                 lifespan,
                                 gas_limit=3500000,
                                 wait_timeout=240,
                                 default_account=None,
                                 wait_receipt=True,
                                 poll_latency=0.5):
        """ Inserts an order in the sell orderbook of a given pair without a hint
    the pair should not be disabled; the contract should not be paused. Takes the funds
    with a transferFrom """

        tx_hash = None
        tx_receipt = None

        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'insertSellLimitOrder',
            base_token,
            secondary_token,
            amount,
            price,
            lifespan,
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                tx_hash, timeout=wait_timeout, poll_latency=poll_latency)

            self.log.info(
                "Successfully inserted sell limit order in Block  [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                .format(tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt

    def insert_sell_limit_order(self,
                                base_token,
                                secondary_token,
                                amount,
                                price,
                                lifespan,
                                gas_limit=3500000,
                                wait_timeout=240,
                                default_account=None,
                                wait_receipt=True,
                                poll_latency=0.5):
        """ Inserts an order in the sell orderbook of a given pair without a hint
    the pair should not be disabled; the contract should not be paused. Takes the funds
    with a transferFrom """

        base_token = Web3.toChecksumAddress(base_token)
        secondary_token = Web3.toChecksumAddress(secondary_token)
        amount_sc = int(Decimal(amount) * self.precision)
        price_sc = int(Decimal(price) * self.precision)
        lifespan_sc = int(lifespan)

        if self.paused():
            raise Exception("Contract is paused you cannot operate!")

        tx_hash, tx_receipt = self._insert_sell_limit_order(
            base_token,
            secondary_token,
            amount_sc,
            price_sc,
            lifespan_sc,
            gas_limit=gas_limit,
            wait_timeout=wait_timeout,
            default_account=default_account,
            wait_receipt=wait_receipt,
            poll_latency=poll_latency)

        tx_logs = None
        tx_logs_formatted = None

        if tx_receipt:
            # receipt to logs
            tx_logs = {
                "NewOrderInserted":
                self.events.NewOrderInserted().processReceipt(tx_receipt)
            }
            tx_logs_formatted = {
                "NewOrderInserted":
                DEXNewOrderInserted(self.connection_manager,
                                    tx_logs["NewOrderInserted"][0])
            }

        return tx_hash, tx_receipt, tx_logs, tx_logs_formatted

    def _insert_buy_limit_order(self,
                                base_token,
                                secondary_token,
                                amount,
                                price,
                                lifespan,
                                gas_limit=3500000,
                                wait_timeout=240,
                                default_account=None,
                                wait_receipt=True,
                                poll_latency=0.5):
        """ @notice Inserts an order in the buy orderbook of a given pair without a hint
    the pair should not be disabled; the contract should not be paused. Takes the funds
    with a transferFrom """

        tx_hash = None
        tx_receipt = None

        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'insertBuyLimitOrder',
            base_token,
            secondary_token,
            amount,
            price,
            lifespan,
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                tx_hash, timeout=wait_timeout, poll_latency=poll_latency)

            self.log.info(
                "Successfully inserted buy limit order in Block  [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                .format(tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt

    def insert_buy_limit_order(self,
                               base_token,
                               secondary_token,
                               amount,
                               price,
                               lifespan,
                               gas_limit=3500000,
                               wait_timeout=240,
                               default_account=None,
                               wait_receipt=True,
                               poll_latency=0.5):
        """ Inserts an order in the buy orderbook of a given pair without a hint
    the pair should not be disabled; the contract should not be paused. Takes the funds
    with a transferFrom """

        base_token = Web3.toChecksumAddress(base_token)
        secondary_token = Web3.toChecksumAddress(secondary_token)
        amount_sc = int(Decimal(amount) * self.precision)
        price_sc = int(Decimal(price) * self.precision)
        lifespan_sc = int(lifespan)

        if self.paused():
            raise Exception("Contract is paused you cannot operate!")

        tx_hash, tx_receipt = self._insert_buy_limit_order(
            base_token,
            secondary_token,
            amount_sc,
            price_sc,
            lifespan_sc,
            gas_limit=gas_limit,
            wait_timeout=wait_timeout,
            default_account=default_account,
            wait_receipt=wait_receipt,
            poll_latency=poll_latency)

        tx_logs = None
        tx_logs_formatted = None

        if tx_receipt:
            # receipt to logs
            tx_logs = {
                "NewOrderInserted":
                self.events.NewOrderInserted().processReceipt(tx_receipt)
            }
            tx_logs_formatted = {
                "NewOrderInserted":
                DEXNewOrderInserted(self.connection_manager,
                                    tx_logs["NewOrderInserted"][0])
            }

        return tx_hash, tx_receipt, tx_logs, tx_logs_formatted
示例#24
0
class CommissionManager(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/CommissionManager.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_dex/CommissionManager.bin'))

    mode = 'DEX'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network][
                'addresses']['commissionManager']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def implementation(self, block_identifier: BlockIdentifier = 'latest'):
        """Implementation of contract"""

        contract_admin = ProxyAdmin(self.connection_manager)
        contract_address = Web3.toChecksumAddress(self.contract_address)

        return contract_admin.implementation(contract_address,
                                             block_identifier=block_identifier)

    def beneficiary_address(self,
                            block_identifier: BlockIdentifier = 'latest'):
        """Gets beneficiary destination address """

        result = self.sc.functions.beneficiaryAddress().call(
            block_identifier=block_identifier)

        return result

    def commision_rate(self,
                       formatted: bool = True,
                       block_identifier: BlockIdentifier = 'latest'):
        """Gets commision rate"""

        result = self.sc.functions.commissionRate().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def cancelation_penalty_rate(self,
                                 formatted: bool = True,
                                 block_identifier: BlockIdentifier = 'latest'):
        """Gets cancelationPenaltyRate"""

        result = self.sc.functions.cancelationPenaltyRate().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def expiration_penalty_rate(self,
                                formatted: bool = True,
                                block_identifier: BlockIdentifier = 'latest'):
        """Gets expirationPenaltyRate"""

        result = self.sc.functions.expirationPenaltyRate().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def calculate_initial_fee(self,
                              amount: int,
                              formatted: bool = True,
                              block_identifier: BlockIdentifier = 'latest'):
        """Calculate initial fee. Initial fee is the commission at insertion order"""

        result = self.sc.functions.calculateInitialFee(amount).call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def exchange_commissions(self,
                             address: str,
                             formatted: bool = True,
                             block_identifier: BlockIdentifier = 'latest'):
        """Gets exchangeCommissions"""

        result = self.sc.functions.exchangeCommissions(address).call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result
示例#25
0
class RDOCPriceFeederAdderChanger(BaseChanger):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/PriceFeederAdder.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/PriceFeederAdder.bin'))

    contract_medianizer_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoCMedianizer.abi'))
    contract_medianizer_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoCMedianizer.bin'))

    contract_feedfactory_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/FeedFactory.abi'))
    contract_feedfactory_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/FeedFactory.bin'))

    contract_governor_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/Governor.abi'))
    contract_governor_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/Governor.bin'))

    mode = 'RDoC'

    def constructor(self, account_owner, execute_change=False):

        network = self.connection_manager.network
        contract_address_medianizer = self.connection_manager.options[
            'networks'][network]['addresses']['oracle']
        contract_address_feedfactory = self.connection_manager.options[
            'networks'][network]['addresses']['FeedFactory']

        self.log.info("Deploying new contract...")

        tx_hash, tx_receipt = self.fnx_constructor(
            contract_address_feedfactory, contract_address_medianizer,
            Web3.toChecksumAddress(account_owner))

        self.log.info("Deployed contract done!")
        self.log.info(tx_hash)
        self.log.info(tx_receipt)

        self.log.info("Changer Contract Address: {address}".format(
            address=tx_receipt.contractAddress))

        if execute_change:
            self.log.info("Executing change....")
            governor = self.load_governor()
            tx_hash = self.connection_manager.fnx_transaction(
                governor, 'executeChange', tx_receipt.contractAddress)
            tx_receipt = self.connection_manager.wait_transaction_receipt(
                tx_hash)
            self.log.info(tx_hash)
            self.log.info(tx_receipt)
            self.log.info("Change successfull!")

        return tx_hash, tx_receipt
示例#26
0
class RRC20MoC(MoC):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/MoC.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/MoC.bin'))

    precision = 10**18
    mode = 'RRC20'
    project = 'RRC20'
    minimum_amount = Decimal(0.00000001)

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None,
                 contract_address_moc_state=None,
                 contract_address_moc_inrate=None,
                 contract_address_moc_exchange=None,
                 contract_address_moc_connector=None,
                 contract_address_moc_settlement=None,
                 contract_address_moc_bpro_token=None,
                 contract_address_moc_doc_token=None,
                 contract_address_reserve_token=None,
                 contracts_discovery=False):

        network = connection_manager.network
        if not contract_address:
            # load from connection manager
            contract_address = connection_manager.options['networks'][network][
                'addresses']['MoC']

        super().__init__(
            connection_manager,
            contract_address=contract_address,
            contract_abi=contract_abi,
            contract_bin=contract_bin,
            contract_address_moc_state=contract_address_moc_state,
            contract_address_moc_inrate=contract_address_moc_inrate,
            contract_address_moc_exchange=contract_address_moc_exchange,
            contract_address_moc_connector=contract_address_moc_connector,
            contract_address_moc_settlement=contract_address_moc_settlement,
            contract_address_moc_bpro_token=contract_address_moc_bpro_token,
            contract_address_moc_doc_token=contract_address_moc_doc_token,
            contracts_discovery=contracts_discovery)

        contract_addresses = dict()
        contract_addresses['ReserveToken'] = contract_address_reserve_token

        if contracts_discovery:
            connector_addresses = self.connector_addresses()
            contract_addresses['ReserveToken'] = connector_addresses[
                'ReserveToken']

        # load_reserve_token_contract
        self.sc_reserve_token = self.load_reserve_token_contract(
            contract_addresses['ReserveToken'])

    def load_moc_inrate_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCInrate']

        sc = RRC20MoCInrate(self.connection_manager,
                            contract_address=contract_address)

        return sc

    def load_moc_state_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCState']

        sc = RRC20MoCState(self.connection_manager,
                           contract_address=contract_address)

        return sc

    def load_moc_exchange_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCExchange']

        sc = RRC20MoCExchange(self.connection_manager,
                              contract_address=contract_address)

        return sc

    def load_moc_connector_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCConnector']

        sc = RRC20MoCConnector(self.connection_manager,
                               contract_address=contract_address)

        return sc

    def load_moc_settlement_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCSettlement']

        sc = RRC20MoCSettlement(self.connection_manager,
                                contract_address=contract_address)

        return sc

    def load_moc_bpro_token_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['BProToken']

        sc = RiskProToken(self.connection_manager,
                          contract_address=contract_address)

        return sc

    def load_moc_doc_token_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['DoCToken']

        sc = StableToken(self.connection_manager,
                         contract_address=contract_address)

        return sc

    def load_reserve_token_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['ReserveToken']

        sc = ReserveToken(self.connection_manager,
                          contract_address=contract_address)

        return sc

    def spendable_balance(self,
                          account_address,
                          formatted: bool = True,
                          block_identifier: BlockIdentifier = 'latest'):
        """ Spendable Balance """

        result = self.sc.functions.getAllowance(account_address).call(
            block_identifier=block_identifier)

        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def reserve_allowance(self,
                          account_address,
                          formatted: bool = True,
                          block_identifier: BlockIdentifier = 'latest'):
        """ Reserve allowance """

        result = self.sc_reserve_token.allowance(
            account_address,
            self.sc.address,
            formatted=formatted,
            block_identifier=block_identifier)

        return result
示例#27
0
class MoCStopper(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/Stopper.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/Stopper.bin'))

    mode = 'MoC'
    project = 'MoC'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        if not contract_address:
            # load from connection manager
            network = connection_manager.network
            contract_address = connection_manager.options['networks'][network][
                'addresses']['stopper']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def address_stopper(self, block_identifier: BlockIdentifier = 'latest'):
        """Contract address output"""

        result = self.sc.functions.stopper().call(
            block_identifier=block_identifier)

        return result

    def owner(self, block_identifier: BlockIdentifier = 'latest'):
        """Contract address output"""

        result = self.sc.functions.owner().call(
            block_identifier=block_identifier)

        return result

    def pause(self,
              contract_to_pause,
              gas_limit=3500000,
              wait_timeout=240,
              default_account=None,
              wait_receipt=True):
        """Initialize"""

        contract_to_pause = Web3.toChecksumAddress(contract_to_pause)

        tx_receipt = None
        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'pause',
            contract_to_pause,
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                tx_hash, timeout=wait_timeout)

            self.log.info(
                "Successfully paused contract {0} in Block [{1}] Hash: [{2}] Gas used: [{3}] From: [{4}]"
                .format(contract_to_pause, tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt

    def unpause(self,
                contract_to_pause,
                gas_limit=3500000,
                wait_timeout=240,
                default_account=None,
                wait_receipt=True):
        """Initialize"""

        contract_to_pause = Web3.toChecksumAddress(contract_to_pause)

        tx_receipt = None
        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'unpause',
            contract_to_pause,
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_for_transaction_receipt(
                tx_hash, timeout=wait_timeout)

            self.log.info(
                "Successfully paused contract {0} in Block [{1}] Hash: [{2}] Gas used: [{3}] From: [{4}]"
                .format(contract_to_pause, tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt
示例#28
0
class RRC20MoCInrate(MoCInrate):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/MoCInrate.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rrc20/MoCInrate.bin'))

    precision = 10**18
    mode = 'RRC20'
    project = 'RRC20'

    def stable_inrate(self,
                      formatted: bool = True,
                      block_identifier: BlockIdentifier = 'latest'):
        """Parameters inrate Stable"""

        info = dict()

        result = self.sc.functions.getStableTmax().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')
        info['StableTmax'] = result

        result = self.sc.functions.getStablePower().call(
            block_identifier=block_identifier)
        info['StablePower'] = result

        result = self.sc.functions.getStableTmin().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')
        info['StableTmin'] = result

        return info

    def riskprox_inrate(self,
                        formatted: bool = True,
                        block_identifier: BlockIdentifier = 'latest'):
        """Parameters inrate riskprox"""

        info = dict()

        result = self.sc.functions.getRiskProxTmax().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')
        info['RiskProxTmax'] = result

        result = self.sc.functions.getRiskProxPower().call(
            block_identifier=block_identifier)
        info['RiskProxPower'] = result

        result = self.sc.functions.getRiskProxTmin().call(
            block_identifier=block_identifier)
        if formatted:
            result = Web3.fromWei(result, 'ether')
        info['RiskProxTmin'] = result

        return info
示例#29
0
class CommissionSplitter(Contract):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/CommissionSplitter.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi/CommissionSplitter.bin'))

    mode = 'MoC'
    precision = 10**18

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None):

        network = connection_manager.network
        if not contract_address:
            # load from connection manager

            contract_address = connection_manager.options['networks'][network][
                'addresses']['CommissionSplitter']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # finally load the contract
        self.load_contract()

    def commission_address(self, block_identifier: BlockIdentifier = 'latest'):
        """Final receiver address"""

        result = self.sc.functions.commissionsAddress().call(
            block_identifier=block_identifier)

        return result

    def moc_address(self, block_identifier: BlockIdentifier = 'latest'):
        """The MOC contract address"""

        result = self.sc.functions.moc().call(
            block_identifier=block_identifier)

        return result

    def moc_proportion(self, block_identifier: BlockIdentifier = 'latest'):
        """ Proportion of the balance to send to moc """

        result = self.sc.functions.mocProportion().call(
            block_identifier=block_identifier)

        return result

    def balance(self,
                formatted: bool = True,
                block_identifier: BlockIdentifier = 'latest'):

        result = self.connection_manager.balance(self.address())

        if formatted:
            result = Web3.fromWei(result, 'ether')

        return result

    def initialize(self,
                   moc_address,
                   commission_address,
                   moc_proportion,
                   governor_address,
                   gas_limit=3500000,
                   wait_timeout=240,
                   default_account=None,
                   wait_receipt=True):
        """Init the contract"""

        moc_address = Web3.toChecksumAddress(moc_address)
        commission_address = Web3.toChecksumAddress(commission_address)
        governor_address = Web3.toChecksumAddress(governor_address)

        tx_receipt = None
        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'initialize',
            moc_address,
            commission_address,
            moc_proportion,
            governor_address,
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_transaction_receipt(
                tx_hash, timeout=wait_timeout)

            self.log.info(
                "Successfully initialized executed in Block [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                .format(tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt

    def split(self,
              gas_limit=3500000,
              wait_timeout=240,
              default_account=None,
              wait_receipt=True):
        """ split execute """

        tx_receipt = None
        tx_hash = self.connection_manager.fnx_transaction(
            self.sc,
            'split',
            default_account=default_account,
            gas_limit=gas_limit)

        if wait_receipt:
            # wait to transaction be mined
            tx_receipt = self.connection_manager.wait_transaction_receipt(
                tx_hash, timeout=wait_timeout)

            self.log.info(
                "Successfully split executed in Block [{0}] Hash: [{1}] Gas used: [{2}] From: [{3}]"
                .format(tx_receipt['blockNumber'],
                        Web3.toHex(tx_receipt['transactionHash']),
                        tx_receipt['gasUsed'], tx_receipt['from']))

        return tx_hash, tx_receipt
示例#30
0
class RDOCMoC(RRC20MoC):
    log = logging.getLogger()

    contract_abi = Contract.content_abi_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoC.abi'))
    contract_bin = Contract.content_bin_file(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     'abi_rdoc/MoC.bin'))

    precision = 10**18
    mode = 'RRC20'
    project = 'RDoC'
    minimum_amount = Decimal(0.00000001)

    def __init__(self,
                 connection_manager,
                 contract_address=None,
                 contract_abi=None,
                 contract_bin=None,
                 contract_address_moc_state=None,
                 contract_address_moc_inrate=None,
                 contract_address_moc_exchange=None,
                 contract_address_moc_connector=None,
                 contract_address_moc_settlement=None,
                 contract_address_moc_bpro_token=None,
                 contract_address_moc_doc_token=None,
                 contract_address_reserve_token=None):

        network = connection_manager.network
        if not contract_address:
            # load from connection manager
            contract_address = connection_manager.options['networks'][network][
                'addresses']['MoC']

        super().__init__(connection_manager,
                         contract_address=contract_address,
                         contract_abi=contract_abi,
                         contract_bin=contract_bin)

        # load main contract
        self.load_contract()

        # load contract moc connector
        self.sc_moc_connector = self.load_moc_connector_contract(
            contract_address_moc_connector)

        # load contract moc state
        self.sc_moc_state = self.load_moc_state_contract(
            contract_address_moc_state)

        # load contract moc inrate
        self.sc_moc_inrate = self.load_moc_inrate_contract(
            contract_address_moc_inrate)

        # load contract moc exchange
        self.sc_moc_exchange = self.load_moc_exchange_contract(
            contract_address_moc_exchange)

        # load contract moc settlement
        self.sc_moc_settlement = self.load_moc_settlement_contract(
            contract_address_moc_settlement)

        # load contract moc bpro_token
        self.sc_moc_bpro_token = self.load_moc_bpro_token_contract(
            contract_address_moc_bpro_token)

        # load contract moc doc_token
        self.sc_moc_doc_token = self.load_moc_bpro_token_contract(
            contract_address_moc_doc_token)

        # load_reserve_token_contract
        self.sc_reserve_token = self.load_reserve_token_contract(
            contract_address_reserve_token)

    def load_moc_inrate_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCInrate']

        sc = RDOCMoCInrate(self.connection_manager,
                           contract_address=contract_address)

        return sc

    def load_moc_state_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCState']

        sc = RDOCMoCState(self.connection_manager,
                          contract_address=contract_address)

        return sc

    def load_moc_exchange_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCExchange']

        sc = RDOCMoCExchange(self.connection_manager,
                             contract_address=contract_address)

        return sc

    def load_moc_connector_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCConnector']

        sc = RDOCMoCConnector(self.connection_manager,
                              contract_address=contract_address)

        return sc

    def load_moc_settlement_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['MoCSettlement']

        sc = RDOCMoCSettlement(self.connection_manager,
                               contract_address=contract_address)

        return sc

    def load_moc_bpro_token_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['BProToken']

        sc = RIFPro(self.connection_manager, contract_address=contract_address)

        return sc

    def load_moc_doc_token_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['DoCToken']

        sc = RIFDoC(self.connection_manager, contract_address=contract_address)

        return sc

    def load_reserve_token_contract(self, contract_address):

        network = self.connection_manager.network
        if not contract_address:
            contract_address = self.connection_manager.options['networks'][
                network]['addresses']['ReserveToken']

        sc = RIF(self.connection_manager, contract_address=contract_address)

        return sc