Example #1
0
 def _check_redeeming_accounts(self):
     fund_state = self.fund.state()
     if fund_state == State.Normal:
         try:
             fundMarginAccount = self.perp.getMarginAccount(Address(config.FUND_ADDRESS))
             redeeming_accounts = self._get_redeeming_accounts()
             for account in redeeming_accounts:
                 price_limit = self._get_redeem_trade_price(fundMarginAccount.side)
                 share_amount = self.fund.redeemingBalance(account)
                 if share_amount > Wad(0):
                     side = 2 if fundMarginAccount.side == PositionSide.LONG else 1
                     tx_hash = self.fund.bidRedeemingShare(account, share_amount, price_limit, side , self.keeper_account, self.gas_price)
                     transaction_status = self._wait_transaction_receipt(tx_hash, 10)
                     if transaction_status:
                         self.logger.info(f"bidRedeemingShare success. amount:{share_amount}")
                     else:
                         self.logger.info(f"bidRedeemingShare fail. amount:{share_amount}")
         except Exception as e:
             self.logger.fatal(f"_check_redeeming_accounts bidRedeemingShare fail. error:{e}")
     elif fund_state == State.Emergency:
         try:
             fundMarginAccount = self.perp.getMarginAccount(Address(config.FUND_ADDRESS))
             # price_limit = self._get_redeem_trade_price(fundMarginAccount.side)
             price_limit = self.perp.markPrice()
             total_supply = self.fund.total_supply()
             self.get_gas_price()
             side = 2 if fundMarginAccount.side == PositionSide.LONG else 1
             tx_hash = self.fund.bidSettledShare(total_supply, price_limit, side, self.keeper_account, self.gas_price)
             transaction_status = self._wait_transaction_receipt(tx_hash, 10)
             if transaction_status:
                 self.logger.info(f"bidSettledShare success. amount:{total_supply}")
             else:
                 self.logger.info(f"bidSettledShare fail. amount:{total_supply}")
         except Exception as e:
             self.logger.fatal(f"_check_redeeming_accounts emergency fail. error:{e}")
Example #2
0
 def createTransaction(self, password, destList):
     """Create a new transaction and send it to the RelayNode
        destList is a list of tuples
        Each tuples is like : (str_address, value)
        The last transaction is the rest of the wallet send to the new user address
     """
     self.checkUpdate()
     newAddr = Address()
     newAddr.encryptPrivateKey(password)
     total = sum([i[1] for i in destList])
     if total <= self.count:
         destList.append((str(newAddr), (self.count - total)))
         transac = Transaction(self.addr.public(), destList)
         self.addr.decryptPrivateKey(password)
         transac.sign(self.addr)
         debug('valid: ' + ('True' if transac.is_signed() else 'False'))
         self.addr.encryptPrivateKey(password)
         if not self.relay.submit_transaction(transac):
             return False
         self.addrList.append(newAddr)
         self.addr = newAddr
         add_address(self.user_ID, self.addr, len(self.addrList) - 1)
         return True
     else:
         return False
Example #3
0
def transfer(bc, relay, from_addr, to_addr, amount):
    f = get_address(from_addr)
    if f is None:
        exit('no address '+str(from_addr)+' in database')
    
    total = bc.get_amount_of_address(f)
    if total < amount:
        exit('not enough money for this transfer')
    
    pwd = getpass.getpass()
    while not f.decryptPrivateKey(pwd):
        print('Invalid password')
        pwd = getpass.getpass()
    
    receivers = [(to_addr, amount)]
    if total > amount:
        new = Address()
        new.encryptPrivateKey(pwd)
        db.add_address('client', new, 0)
        print('created new address '+str(new)+' to receive remaining funds')
        receivers.append((str(new), total - amount))
    t = Transaction(f, receivers)
    if relay.submit_transaction(t):
        print('transaction sent to the network')
    else:
        print('error sending transaction')
Example #4
0
    def __init__(self):
        self._logger = logging.getLogger()
        config.LOG_CONFIG["handlers"]["file_handler"]["filename"] = config.PAYER_LOGPATH
        logging.config.dictConfig(config.LOG_CONFIG)

        self._web3 = Web3(HTTPProvider(endpoint_uri=config.ETH_RPC_URL,
                        request_kwargs={"timeout": config.ETH_RPC_TIMEOUT}))
        self._web3.middleware_onion.inject(geth_poa_middleware, layer=0)
        self._gas_price = self._web3.toWei(50, "gwei")
        self._get_gas_price()
        self._payer_account = None

        # contract
        self._disperse = Disperse(
            web3=self._web3, address=Address(config.DISPERSE_ADDRESS))
        self._MCBToken = ERC20Token(
            web3=self._web3, address=Address(config.MCB_TOKEN_ADDRESS))
Example #5
0
 def __init__(self, token_address, web3, end_block):
     self._token_address = token_address.lower()
     self._end_block = end_block
     # contract
     self._erc20_token = ERC20Token(web3=web3,
                                    address=Address(token_address))
     self._erc20_decimals = self._erc20_token.decimals
     self._logger = logging.getLogger()
Example #6
0
 def __init__(self, perpetual_address, inverse, web3):
     
     self._perpetual_address = web3.toChecksumAddress(perpetual_address)
     self._inverse = inverse
     # contract
     self._perpetual = Perpetual(
         web3=web3, address=Address(self._perpetual_address))
     self._logger = logging.getLogger()
Example #7
0
    def __init__(self, args: list, **kwargs):
        logging.config.dictConfig(config.LOG_CONFIG)
        self.keeper_account = None
        self.keeper_account_key = ""
        self.web3 = Web3(HTTPProvider(endpoint_uri=config.ETH_RPC_URL))
        self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)
        self.gas_price = self.web3.toWei(10, "gwei")

        # contract 
        self.perp = Perpetual(web3=self.web3, address=Address(config.PERP_ADDRESS))
        self.token = ERC20Token(web3=self.web3, address=Address(config.COLLATERAL_TOKEN))
        self.AMM = AMM(web3=self.web3, address=Address(config.AMM_ADDRESS))
        self.fund = Fund(web3=self.web3, address=Address(config.FUND_ADDRESS))

        # mcdex for orderbook
        self.mcdex = Mcdex(config.MCDEX_URL, config.MARKET_ID)

        # watcher
        self.watcher = Watcher(self.web3)
Example #8
0
 def __init__(self, perpetual_address, inverse, perpetual_position_topic, web3, end_block):
     
     self._perpetual_address = web3.toChecksumAddress(perpetual_address)
     self._inverse = inverse
     self._perpetual_position_topic = perpetual_position_topic
     self._end_block = end_block
     # contract
     self._perpetual = Perpetual(
         web3=web3, address=Address(self._perpetual_address))
     self._logger = logging.getLogger()
Example #9
0
 def _check_account_from_key(self):
     try:
         account = Account()
         acct = account.from_key(config.PAYER_KEY)
         self._web3.middleware_onion.add(
             construct_sign_and_send_raw_middleware(acct))
         self._payer_account = Address(acct.address)
     except:
         self._logger.fatal(f"Account {config.PAYER_ADDRESS} register key error")
         return False
     return True
Example #10
0
    def _check_keeper_account(self):
        with open(config.KEEPER_KEY_FILE) as f:
            read_key = f.read().replace("\n","")

        # check account with key
        try:
            account = Account()
            acct = account.from_key(read_key)
            self.web3.middleware_onion.add(construct_sign_and_send_raw_middleware(acct))
            self.keeper_account = Address(acct.address)
            self.keeper_account_key = read_key
        except Exception as e:
            self.logger.warning(f"check private key error: {e}")
            return False
            
        return True
Example #11
0
 def _get_redeeming_accounts(self):
     user_list = []
     query = '''
         {
             userInFunds(where: {fund: "%s", redeemingShareAmount_gt: 0}) {
                 redeemingShareAmount
                 user{
                     id
                 }
             }
         }
     ''' % (config.FUND_ADDRESS.lower())
     res = requests.post(config.FUND_GRAPH_URL, json={'query': query}, timeout=10)
     if res.status_code == 200:
         user_in_funds = res.json()['data']['userInFunds']
         for user_in_fund in user_in_funds:
             user_list.append(Address(user_in_fund['user']['id']))
     return user_list
Example #12
0
    def __init__(self, user_ID, password):
        """Create a new wallet

        user_ID  : The ID of the user to select it's own address on the DB
        password : The password is used to generate a AES_Key to ecrypt / decrypt the private key on DB
                   Here, we used it to load all the address or write the new address
        """
        self.blockChain = Blockchain('client')
        self.relay = RelayClient()
        self.updater = Updater(self.blockChain, self.relay)
        self.updater.update()
        self.user_ID = user_ID
        self.addrList = loadAddressList(self.user_ID)  # list of address
        self.last = len(self.addrList) - 1  #index of the actual address
        if self.addrList == []:  #New Wallet : Create the first Address
            self.addr = Address()
            self.addr.encryptPrivateKey(password)
            add_address(self.user_ID, self.addr, 0)
            self.addrList.append(self.addr)
        else:
            self.addr = self.addrList[len(self.addrList) - 1]
        self.count = self.blockChain.get_amount_of_address(self.addr)
Example #13
0
    def _check_account_balance(self):
        self.get_gas_price()
        if self.token.address != Address('0x0000000000000000000000000000000000000000'):
            allowance = self.token.allowance(self.keeper_account, self.perp.address)
            self.logger.info(f"address:{self.keeper_account} allowance:{allowance}")

            if allowance.value == 0:
                self.token.approve(self.perp.address, self.keeper_account)
            margin_account = self.perp.getMarginAccount(self.keeper_account)
            self.logger.info(f"address:{self.keeper_account} cash_balance:{margin_account.cash_balance}")
            if margin_account.cash_balance.value == 0:
                self.logger.error(f"your cash balance is {margin_account.cash_balance}, please deposit enough balance in perpetual contract {self.perp.address}")
                return False
        else:
            eth_balance = self.web3.eth.getBalance(self.keeper_account.address)
            self.logger.info(f"address:{self.keeper_account} eth_balance:{eth_balance}")
            margin_account = self.perp.getMarginAccount(self.keeper_account)
            self.logger.info(f"address:{self.keeper_account} cash_balance:{margin_account.cash_balance}")
            if margin_account.cash_balance.value == 0:
                #self.perp.depositEther(100, address, self.gas_price)
                self.logger.error(f"your cash balance is {margin_account.cash_balance}, please deposit enough balance in perpetual contract {self.perp.address}")
                return False

        return True
Example #14
0
 def test_json(self):
     a = Address()
     b = Address.fromJson(a.toJson())
     self.assertTrue(self.equalAddresses(a, b))
Example #15
0
 def test_json_equal(self):
     a = Address()
     b = Address.fromJson(a.toJson())
     self.assertEqual(a.toJson(), b.toJson())
Example #16
0
 def test_encrypted_json(self):
     a = Address()
     a.encryptPrivateKey('pwd')
     b = Address.fromJson(a.toJson())
     self.assertTrue(self.equalAddresses(a, b, False, True))
Example #17
0
def create_address():
    pwd = getpass.getpass()
    addr = Address()
    addr.encryptPrivateKey(pwd)
    db.add_address('client', addr, 0)
    print('created new address '+str(addr))
Example #18
0
 def test_public_json(self):
     a = Address().public()
     b = Address.fromJson(a.toJson())
     self.assertTrue(self.equalAddresses(a, b, False))
Example #19
0
 def test_public_address(self):
     a = Address()
     b = a.public()
     self.assertEqual(str(a), str(b))
     self.assertNotEqual(a.toJson(), b.toJson())
Example #20
0
 def test_encrypted(self):
     a = Address()
     b = Address(a.dsa)
     b.encryptPrivateKey('pwd')
     b.decryptPrivateKey('pwd')
     self.assertTrue(self.equalAddresses(a, b))
Example #21
0
 def perpetualProxy(self, user: Address) -> Address:
     return Address(self.contract.functions.perpetualProxy().call({'from': user.address}))
Example #22
0
    """
     the next lines are some tests of our functions
    """

    print("NEW TEST:\n")
    blockchain = Blockchain("blockchain")
    print("empty blockchain")
    print(blockchain)
    db = blockchain.db
    previousHash = blockchain.get_last_hash()
    print("previousHash")
    print(previousHash)

    print("TESTING Blocks DB")

    sender_address = Address()
    receiver1_address = Address()
    receiver2_address = Address()
    miner_address = Address()
    transaction = Transaction(sender_address.public(),
                              [(str(receiver1_address), 123),
                               (str(receiver2_address), 321)])
    print("transaction")
    print(str(transaction.toJson()))
    block = Block(previousHash, str(miner_address), [transaction])
    block.set_proof("43334")
    print("block")
    print(str(block.toJson()))
    json_block = block.toJson()
    print("json_block")
    print(str(json_block))
Example #23
0
 def accounts(self, account_id: int) -> Address:
     return Address(self.contract.functions.accountList(account_id).call())
Example #24
0
 def test_init(self):
     a = Address()
     b = Address(a.dsa)
     self.assertTrue(self.equalAddresses(a, b))