コード例 #1
0
 def cdcTakeAction(self, arg):
     logging.debug(arg)
     cdcOp = CDCOperation(self.accountList.currentText(), self.collateral_contract, self.api)
     ret = ''
     if arg['action'] == 'Payback':
         ret = cdcOp.pay_back(arg['cdc_id'], arg['amount'])
     elif arg['action'] == 'Generate':
         ret = cdcOp.generate_stable_coin(arg['cdc_id'], arg['amount'])
     elif arg['action'] == 'AddCollateral':
         ret = cdcOp.add_collateral(arg['cdc_id'], arg['amount'])
     elif arg['action'] == 'Withdraw':
         ret = cdcOp.withdraw_collateral(arg['cdc_id'], arg['amount'])
     elif arg['action'] == 'Close':
         ret = cdcOp.close_cdc(arg['cdc_id'])
     elif arg['action'] == 'Liquidate':
         if arg['amount'] == '' or arg['amount2'] == '':
             QMessageBox.information(self, 'Info', \
                     'The CDC (ID: %s) cannot be liquidated.' % arg['cdc_id'])
             return
         self.cdcOp.liquidate(arg['cdc_id'], arg['amount'], arg['amount2'])
     else:
         pass
     if ret is None:
         retMessage = 'Fail to %s' % arg['action']
     else:
         retMessage = 'Success to %s' % arg['action']
     QMessageBox.information(self, 'Info', retMessage)
     logging.debug(ret)
コード例 #2
0
def closeAllUsersCdcs(usersNum,account_name_prefix,filepath,mainAccount):
    global cdcs
    if(len(cdcs) == 0):
        try:
            with open(filepath, 'r') as load_f:
                cdcs = json.load(load_f)
        except BaseException as e:
            logging.error(str(e))

    cdcUsers = []
    if(len(cdcs)==0):
        print("closeAllUsersCdcs , no cdcs!!!!")
        #return
    else:
        for i in range(0, usersNum):
            user = account_name_prefix + str(i)
            cdcUsers.append(CDCOperation(user, cdc_address, wallet_api))

    get_my_accounts()

    contract_info = json.loads(CDCOperation(mainAccount, cdc_address, wallet_api).get_contract_info())

    cdc_admin_addr = contract_info['admin']
    priceFeederAddr = contract_info['priceFeederAddr']
    stableTokenAddr = contract_info['stableTokenAddr']
    collateralAsset = contract_info['collateralAsset']
    liquidationRatio = float(contract_info['liquidationRatio'])
    annualStabilityFee = float(contract_info['annualStabilityFee'])

    YEARSECS = 31536000

    cdc_admin = accounts[cdc_admin_addr]
    cdcAdmin = CDCOperation(cdc_admin, cdc_address, wallet_api)
    priceFeederUser = PriceFeeder(cdc_admin, priceFeederAddr, wallet_api)
    feeders = json.loads(priceFeederUser.get_feeders())
    price_feeder = accounts[feeders[0]]
    priceFeeder = PriceFeeder(price_feeder, priceFeederAddr, wallet_api)


    fromuser = cdc_admin
    cdcFromUser = cdcAdmin

    origStableTokenSupply = token_supply(stableTokenAddr,mainAccount)

    totalDestoryedStableTokenAmount = 0
    lenPrefix = len(account_name_prefix)
    origcdcs = copy.deepcopy(cdcs)
    time.sleep(5)
    for user in origcdcs.keys():
        if(user.startswith(account_name_prefix)):
            i = int(user[lenPrefix:])
            cdcUser = cdcUsers[i]
            trxid = origcdcs[user]['trxid']
            result = cdcUser.get_cdc(trxid)
            if (result is not None):
                cdcinfo = json.loads(result)
                if(len(cdcinfo)==0):
                    continue
                collateralAmount = int(cdcinfo['collateralAmount'])
                stabilityFee = int(cdcinfo['stabilityFee'])
                stableTokenAmount = int(cdcinfo['stableTokenAmount'])
                isNeedLiquidation = cdcinfo['isNeedLiquidation']
                totalNeedPayAmount = stableTokenAmount + stabilityFee
                if (totalNeedPayAmount > 0):
                    tokenbalance = token_balanceOf(stableTokenAddr, user)
                    if (totalNeedPayAmount > tokenbalance):
                        fromusertokenbalance = token_balanceOf(stableTokenAddr, fromuser)
                        if(fromusertokenbalance <= (totalNeedPayAmount - tokenbalance)):
                            price = float(priceFeeder.get_price())
                            addCollateral(fromuser,cdcFromUser,collateralAsset)
                            #time.sleep(5)
                            expandLoan(fromuser,cdcFromUser,price,liquidationRatio)
                            #time.sleep(5)
                        r = token_transfer(stableTokenAddr, fromuser, user, (totalNeedPayAmount - tokenbalance + int(stableTokenAmount*20/YEARSECS*annualStabilityFee) ))
                        #if r is not None:
                            #time.sleep(5)
                        result = cdcUser.close_cdc(trxid)
                        if result is not None:
                            print("close_cdc txid:" + trxid + " user:"******" totalNeedPayAmount:" + str(
                                    totalNeedPayAmount)+" stableTokenAmount:"+str(stableTokenAmount))
                            totalDestoryedStableTokenAmount = totalDestoryedStableTokenAmount+stableTokenAmount
                            del cdcs[user]
                            with open(filepath, 'w') as f:
                                json.dump(cdcs, f)
                        else:
                            print("close_cdc fail !!! txid:" + trxid + " user:"******" totalNeedPayAmount:" + str(
                                totalNeedPayAmount) + " stableTokenAmount:" + str(stableTokenAmount))




    if (cdc_admin in cdcs.keys() and "trxid" in cdcs[cdc_admin].keys()):
        trxid = cdcs[cdc_admin]['trxid']
        result = cdcAdmin.get_cdc(trxid)
        if (result is not None):
            cdcinfo = json.loads(result)
            #collateralAmount = cdcinfo['collateralAmount']
            stabilityFee = int(cdcinfo['stabilityFee'])
            stableTokenAmount = int(cdcinfo['stableTokenAmount'])
            #isNeedLiquidation = cdcinfo['isNeedLiquidation']
            totalNeedPayAmount = stableTokenAmount + stabilityFee
            result = cdcAdmin.close_cdc(trxid)
            if result is not None:
                print("close_cdc admin txid:" + trxid + " user:"******" totalNeedPayAmount:" + str(
                    totalNeedPayAmount)+" stableTokenAmount:"+str(stableTokenAmount))
                totalDestoryedStableTokenAmount = totalDestoryedStableTokenAmount + stableTokenAmount
                del cdcs[cdc_admin]
                with open(filepath, 'w') as f:
                    json.dump(cdcs, f)
            else:
                print("close_cdc fail !!! txid:" + trxid + " user:"******" totalNeedPayAmount:" + str(
                    totalNeedPayAmount) + " stableTokenAmount:" + str(stableTokenAmount))


    time.sleep(5)
    for i in range(0,usersnum):
        user = account_name_prefix + str(i)
        tokenbalance = token_balanceOf(stableTokenAddr, user)
        if(tokenbalance > 0):
            r = token_transfer(stableTokenAddr, user, fromuser, tokenbalance)

    currentStableTokenSupply = token_supply(stableTokenAddr, mainAccount)
    totalCdcStableTokenAmount = 0
    for user, cdc in cdcs.items():
        result = cdcAdmin.get_cdc(cdc['trxid'])
        if result is not None:
            cdcinfo = json.loads(result)
            if(len(cdcinfo)==0):
                continue
            stableTokenAmount = int(cdcinfo['stableTokenAmount'])
            totalCdcStableTokenAmount = totalCdcStableTokenAmount + stableTokenAmount

    print(cdcs)
    print("totalDestoryedStableTokenAmount:"+str(totalDestoryedStableTokenAmount))
    print("origStableTokenSupply:" + str(origStableTokenSupply))
    print("now totalCdcStableTokenAmount:" + str(totalCdcStableTokenAmount))
    print("currentStableTokenSupply:" + str(currentStableTokenSupply))
    if ((origStableTokenSupply - totalDestoryedStableTokenAmount) != currentStableTokenSupply):
        raise RuntimeError("error !!!!! (origStableTokenSupply - totalDestoryedStableTokenAmount) != currentStableTokenSupply")
    if(totalCdcStableTokenAmount > 0):
        raise RuntimeError("error!!! close all cdcs fail!!!")

    cdcAdmin.set_annual_stability_fee("0.15")

    ###################### transfer all users HX,BTC to mainAccount  ##################################################################
    print("transfer all users HX,BTC to mainAccount")
    mainAccountAddr = accountNames[mainAccount]
    for i in range(0, usersNum):
        user = account_name_prefix + str(i)
        #userAddr = accountNames[user]
        userBalances = get_account_balances(user,wallet_api)
        if (collateralAsset in userBalances.keys()):
            amount = userBalances[collateralAsset]
            if (amount > 0):
                wallet_api.rpc_request('transfer_to_address',
                                       [user, mainAccountAddr, convertCoinWithPrecision(amount), collateralAsset, "",
                                        0.0001, 100000,
                                        True])

        if(("HX" in userBalances.keys()) and userBalances["HX"] > HXPRECISION):
            dhxAmount = (userBalances["HX"]-HXPRECISION)/HXPRECISION
            wallet_api.rpc_request('transfer_to_address',
                                   [user, mainAccountAddr, dhxAmount, "HX", "", 0.0001, 100000, True])

    adminBalances = get_account_balances(cdc_admin, wallet_api)
    if (collateralAsset in adminBalances.keys()):
        amount = adminBalances[collateralAsset]
        if (amount > 0):
            wallet_api.rpc_request('transfer_to_address',
                                   [cdc_admin, mainAccountAddr, convertCoinWithPrecision(amount), collateralAsset, "",
                                    0.0001, 100000,
                                    True])

    if (("HX" in adminBalances.keys()) and userBalances["HX"] > HXPRECISION):
        dhxAmount = (adminBalances["HX"] - HXPRECISION) / HXPRECISION
        wallet_api.rpc_request('transfer_to_address',
                               [cdc_admin, mainAccountAddr, dhxAmount, "HX", "", 0.0001, 100000, True])
コード例 #3
0
class TestHdaoEvents():
    @classmethod
    def setup_class(cls):
        pass

    @classmethod
    def teardown_class(cls):
        pass

    def setup_method(self, function):
        self.api = HXWalletApi(name="TestHdaoEvents", rpc_url=HX_TESTNET_RPC)
        self.cdcOp = CDCOperation(USER1['account'], CDC_CONTRACT_ID, self.api)
        self.collector = EventsCollector(USER1['account'], CDC_CONTRACT_ID,
                                         self.api)

    def teardown_function(self):
        self.api = None
        self.collector = None
        self.cdc = None

    # def test_collect(self):
    #     self.collector.collect_event(969234)

    def test_cdc_query(self):
        cdcs = self.collector.query_cdc_by_address(
            'HXNUeoaUVkUg9q2uokDwzdrxp1uE4L9VhTSs')
        assert (len(cdcs) >= 1)
        assert (cdcs[0].cdc_id == '0694d145b7000d8d5b13f9f4c4acbee3533ca14a')

    def test_cdc_op_query(self):
        cdcs = self.collector.query_cdc_op_by_id(
            'ee80006bb468a434af71c38cb62e1afac6a51c52')
        assert (len(cdcs) == 2)
        assert (cdcs[0].cdc_id == 'ee80006bb468a434af71c38cb62e1afac6a51c52')

    def test_cdc_normal_operations(self):
        info = self.api.rpc_request("info", [])
        block_num = info['head_block_num']
        result = self.cdcOp.open_cdc(0.001, 0.001)
        assert ("trxid" in result and result["trxid"] != "")
        confirmed = False
        cdc = None
        while not confirmed:
            time.sleep(3)
            self.collector.collect_event(block_num)
            cdcs = self.collector.query_cdc_by_address(USER1['address'])
            for c in cdcs:
                if c.block_number > block_num:
                    confirmed = True
                    cdc = c
                    break
        assert (cdc.collateral_amount == '100000'
                and cdc.collateral_amount == '100000')
        previousCdcId = cdc.cdc_id
        self.cdcOp.close_cdc(cdc.cdc_id)
        confirmed = False
        waitTimes = 0
        with pytest.raises(AssertionError):
            while waitTimes < 10:
                time.sleep(3)
                self.collector.collect_event(block_num)
                cdcs = self.collector.query_cdc_by_address(USER1['address'])
                for c in cdcs:
                    if c.cdc_id == previousCdcId:
                        if c.state == 3:
                            raise AssertionError
                        break