Exemplo n.º 1
0
 def token_get(fundId):
   request = app.current_request
   fund = Database.find_one("Fund", {"id": int(fundId)})
   if not fund: raise NotFoundError("fund not found with id {}".format(fundId))
   tokens = Database.find("Token", {"fundId": fund["id"]})
   fund["tokens"] = toObject(tokens)
   for token in fund["tokens"]:
     tokenHoldings = Database.find_one("TokenHoldings", {"tokenId": token["id"]})
     tokenHoldingsList = Database.find("TokenHolding", {"tokenHoldingsId": tokenHoldings["id"]})
     for tokenHolding in tokenHoldingsList:
       tokenHolding['security'] = toObject(Database.find_one('Security', {'id': tokenHolding["securityId"]}))
       tokenHolding['securityTimestamp'] = toObject(Database.find_one('SecurityTimestamp', {'securityId': tokenHolding["securityId"]}, order_by='-createdAt'))
     token['holdings'] = toObject(tokenHoldingsList)
   return toObject(fund)
Exemplo n.º 2
0
  def orders_show(orderId):
    order = Database.find_one("Order", {"id": orderId})

    order["broker"] = Database.find_one("User", {"id": order["brokerId"]}, ['id','name','email','address'])
    order["token"] = toObject(Database.find_one("Token", {"id": order["tokenId"]}))
    order["orderHoldings"] = Database.find("OrderHolding", {"orderId": order["id"]})

    for orderHolding in order["orderHoldings"]:
      orderHolding["security"] = toObject(Database.find_one("Security", {"id": orderHolding["securityId"]}))

    order["orderTrades"] = Database.find("OrderTrade", {"orderId": order["id"]})
    for orderTrade in order["orderTrades"]:
      orderTrade["trade"] = toObject(Database.find_one("Trade", {"id": orderTrade["tradeId"]}))

    return toObject(order)
Exemplo n.º 3
0
 def users_get():
     request = app.current_request
     users = None
     query_params = request.query_params or {}
     if 'role' in query_params:
         role = query_params['role']
         users = Database.find("User", {'role': role})
         users = [u for u in users if u['ik']]
     else:
         users = Database.find("User")
     users = [
         toObject(
             u, ['id', 'name', 'address', 'role', 'ik', 'spk', 'signature'])
         for u in users
     ]
     return users
Exemplo n.º 4
0
    def test_find(self):
        with patch.dict('os.environ', env):
            Database.insert("User", {'name': 'tom'})

            users = Database.find("User", {'name': 'tom'})
            
            self.assertEqual(len(users), 1)
            self.assertEqual(users[0]['name'], 'tom')
Exemplo n.º 5
0
  def orders_complete():
    request = app.current_request
    data = request.json_body
    order = Database.find_one("Order", {"hash": data["orderHash"]})

    # set order state to complete
    Database.update("Order", {"id": order["id"]}, {"state": 1})

    # set state to all trade as verified
    orderTrades = Database.find("OrderTrade", {"orderId": order["id"]})
    tradeIds = [o['tradeId'] for o in orderTrades]
    tradeQuery = [[('id','=',tradeId)] for tradeId in tradeIds]
    Database.update("Trade", tradeQuery, {'state': 2})

    # Here I need to check if all orders are complete for the day
    executionDate = order["executionDate"]
    incompleteOrders = Database.find("Order", {"state": 0, "executionDate": executionDate, "tokenId": order["tokenId"]})
    if len(incompleteOrders):
      # There are still orders waiting to complete
      print("There are still orders waiting to complete")
      return {"message": "Order completed"}

    # Here I need to calculate the AUM
    # find the token
    token = Database.find_one("Token", {"id": order["tokenId"]})
    print(token['address'])
    tokenContract = Web3Helper.getContract("ETT.json", token['address'])

    tokenHoldingsObject = Database.find_one("TokenHoldings", {"tokenId": token["id"]})
    tokenHoldings = Database.find("TokenHolding", {"tokenHoldingsId": tokenHoldingsObject["id"]})

    newAUM = 0
    for tokenHolding in tokenHoldings:
      securityTimestamp = Database.find_one('SecurityTimestamp', {'securityId': tokenHolding["securityId"]}, order_by='-createdAt')
      newAUM += securityTimestamp['price'] * tokenHolding['securityAmount']

    executionDateString = arrow.get(executionDate).format('YYYY-MM-DD')

    tx = Web3Helper.transact(tokenContract, 'endOfDay', executionDateString)
    # tx = b''
    print({"message": "AUM updated", "AUM": newAUM, "hash": tx.hex()})
    return {"message": "AUM updated", "AUM": newAUM, "hash": tx.hex()}
Exemplo n.º 6
0
  def orders_get():
    request = app.current_request
    query = request.query_params or {}
    single = False
    orders = []
    total = None

    if 'page' in query:
      page = int(query['page'])
      del query['page']
    if 'page_count' in query:
      page_count = int(query['page_count'])
      del query['page_count']

    if 'single' in query:
      del query['single']
      single = True
      order = Database.find_one("Order", query)
      if not order: raise NotFoundError("No order found")
      orders = [order]
    else:
      dbRes = Database.find("Order", query, page=page, page_count=page_count)
      orders = dbRes['data']
      total = dbRes['total']


    for order in orders:
      order["broker"] = Database.find_one("User", {"id": order["brokerId"]}, ['id','name','email','address'])
      order["token"] = toObject(Database.find_one("Token", {"id": order["tokenId"]}))
      order["orderHoldings"] = Database.find("OrderHolding", {"orderId": order["id"]})

      for orderHolding in order["orderHoldings"]:
        orderHolding["security"] = toObject(Database.find_one("Security", {"id": orderHolding["securityId"]}))

      order["orderTrades"] = Database.find("OrderTrade", {"orderId": order["id"]})
      for orderTrade in order["orderTrades"]:
        orderTrade["trade"] = toObject(Database.find_one("Trade", {"id": orderTrade["tradeId"]}))

    if single:
      return toObject(orders[0])

    return {"data": toObject(orders), "total": total}
Exemplo n.º 7
0
    def tokens_nav_update():
        print('\n\n\n\n')
        request = app.current_request
        data = request.json_body
        token = Database.find_one("Token", {"address": data["token"]})
        time = data["time"]
        executionDate = arrow.get(time).format('YYYY-MM-DD')
        nav = Database.insert("NAVTimestamp", {
            "tokenId": token['id'],
            "price": data['value'],
            "executionDate": executionDate
        },
                              return_inserted=True)

        # First need to collect the trades
        print(token['id'])
        trades = Database.find("Trade", {"state": 1, "tokenId": token["id"]})
        print(trades)
        # Need to go through each trade and get the NAV+price
        supplyUpdate = 0
        for trade in trades:
            decryptedNominalAmount = Cryptor.decryptInput(
                trade['nominalAmount'], trade['sk'])
            amountInvested = int(decryptedNominalAmount.split(':')[1])
            price = Cryptor.decryptInput(trade['price'], trade['sk'])
            price = float(price)
            print("amountInvested: ", amountInvested)
            print("price: ", price)
            effectiveNAV = (1.0 + float(price) / 100) * nav['price']
            print("supplyUpdate", int(amountInvested * 1.0 / effectiveNAV))
            # supplyUpdate += int(amountInvested * math.pow(10, token['decimals']) / nav['price'])
            supplyUpdate += int(amountInvested *
                                math.pow(10, token['decimals']) / effectiveNAV)

        tokenContract = Web3Helper.getContract("ETT.json", token['address'])

        # Update trades to be ready for claiming
        tradeQuery = [[('id', '=', t['id'])] for t in trades]
        trades = Database.update("Trade",
                                 tradeQuery, {'state': 4},
                                 return_updated=True)
        for trade in trades:
            # Take funds
            takeFunds(trade)
        tx = Web3Helper.transact(
            tokenContract,
            'updateTotalSupply',
            supplyUpdate,
            '',  # we are ignoring this for now
            executionDate)
        # tx = b''
        print(tx.hex())

        return toObject(nav)
Exemplo n.º 8
0
def getBalances(tokenId):
    token = Database.find_one("Token", {"id": int(tokenId)})
    if not token:
        raise NotFoundError("token not found with id {}".format(tokenId))
    tokenBalances = Database.find("TokenBalance", {"tokenId": token["id"]})
    for tokenBalance in tokenBalances:
        investor = Database.find_one(
            "User", {"id": tokenBalance["userId"]},
            ["id", "name", "type", "juristiction", "address"])
        tokenBalance["investor"] = investor
        tokenBalance["token"] = toObject(token)
    return tokenBalances
Exemplo n.º 9
0
    def test_update_multiple(self):
        with patch.dict('os.environ', env):
            Database.insert("User", {'name': 'tom'})
            Database.insert("User", {'name': 'tom'})

            Database.update("User", [[('name','=','tom')]], {'name': 'tom2'})

            user = Database.find_one("User", {'name': 'tom'})
            self.assertEqual(user, None)

            users = Database.find("User", {'name': 'tom2'})
            self.assertEqual(len(users), 2)
            self.assertEqual(users[0]['name'], 'tom2')
            self.assertEqual(users[1]['name'], 'tom2')
Exemplo n.º 10
0
def getTokenHoldings(tokenId):
    token = Database.find_one("Token", {"id": int(tokenId)})
    if not token:
        raise NotFoundError("token not found with id {}".format(tokenId))
    tokenHoldings = Database.find_one("TokenHoldings",
                                      {"tokenId": token["id"]},
                                      order_by='-createdAt')
    tokenHoldingsList = Database.find("TokenHolding",
                                      {"tokenHoldingsId": tokenHoldings["id"]})
    for tokenHolding in tokenHoldingsList:
        tokenHolding['security'] = toObject(
            Database.find_one('Security', {'id': tokenHolding["securityId"]}))
        tokenHolding['securityTimestamp'] = toObject(
            Database.find_one('SecurityTimestamp',
                              {'securityId': tokenHolding["securityId"]},
                              order_by='-createdAt'))
    return tokenHoldingsList
Exemplo n.º 11
0
  def trades_show(tradeId):
    request = app.current_request
    trade = Database.find_one("Trade", {"id": int(tradeId)})
    if not trade: raise NotFoundError("trade not found with id {}".format(tradeId))
    investor = Database.find_one("User", {"id": trade["investorId"]}, ["address", "id","name"])
    trade["investor"] = investor
    if trade['brokerId']:
      broker = Database.find_one("User", {"id": trade["brokerId"]}, ["address", "id","name"])
      trade["broker"] = broker

    token = Database.find_one("Token", {"id": trade["tokenId"]}, ["id","address","cutoffTime","symbol","decimals"])
    trade["token"] = token

    tradeBrokers = Database.find("TradeBroker", {"tradeId": trade["id"]})
    for ob in tradeBrokers: ob["broker"] = Database.find_one("User", {"id": ob["brokerId"]}, ["address", "id","name"])
    trade["tradeBrokers"] = tradeBrokers
    return toObject(trade)
Exemplo n.º 12
0
def getInvested(tokenId, user):
    token = Database.find_one("Token", {"id": int(tokenId)})
    if not token:
        raise NotFoundError("token not found with id {}".format(tokenId))

    # Need to find all the trades this investor invested in
    claimedTrades = Database.find("Trade", {
        "tokenId": token["id"],
        "investorId": user["id"],
        "state": 6
    })

    totalAmount = 0
    for trade in claimedTrades:
        decrypted = Cryptor.decryptInput(trade['nominalAmount'], trade['sk'])
        # I'll need to include the currency here
        amountInvested = int(decrypted.split(':')[1])
        print(amountInvested)
        totalAmount += amountInvested
    return totalAmount
Exemplo n.º 13
0
  def fund_balances(fundId):
    request = app.current_request
    fund = Database.find_one("Fund", {"id": int(fundId)})
    if not fund: raise NotFoundError("fund not found with id {}".format(fundId))
    tokens = Database.find("Token", {"fundId": fund["id"]})
    token_balances = []
    for token in tokens:
      token_balances += getBalances(token["id"])
    user_hash = {}
    total_balance = []
    for token_balance in token_balances:
      if not token_balance['balance']: continue
      id = token_balance['investor']['id']
      if id in user_hash:
        total_balance[user_hash[id]]['balance'] = int(total_balance[user_hash[id]]['balance'])
        total_balance[user_hash[id]]['balance'] += int(token_balance['balance'])
        total_balance[user_hash[id]]['balance'] = str(total_balance[user_hash[id]]['balance'])
      else:
        index = len(total_balance)
        user_hash[id] = index
        total_balance.append(token_balance)

    return toObject(total_balance)
Exemplo n.º 14
0
  def trades_get():
    request = app.current_request
    trades = []
    tradeBrokers = []
    query = request.query_params or {}
    if 'state' in query:
      query['state'] = int(query['state'])

    page = 0
    page_count = None
    total = None

    if 'page' in query:
      page = int(query['page'])
      del query['page']
    if 'page_count' in query:
      page_count = int(query['page_count'])
      del query['page_count']

    if 'confirmed' in query:
      query['state'] = ('>', 0)
      del query['confirmed']

    if request.user["role"] == "investor":
      query["investorId"] = request.user["id"]
      dbRes = Database.find("Trade", query, page=page, page_count=page_count)
      trades = dbRes['data']
      total = dbRes['total']

    elif request.user["role"] == "broker":
      dbRes = Database.find("TradeBroker", {"brokerId": request.user["id"]}, page=0, page_count=500000000000)
      tradeBrokers = dbRes['data']
      total = dbRes["total"]
      tradeIds = [tradeBroker["tradeId"] for tradeBroker in tradeBrokers]
      for i, tradeId in enumerate(tradeIds):
        _query = copy.copy(query)
        _query["id"] = tradeId
        trade = Database.find_one("Trade", _query)
        if trade:
          if trade["brokerId"] and trade["brokerId"] != request.user["id"]: continue
          trade["tradeBrokers"] = [tradeBrokers[i]]
          trades += [trade]
      if page_count:
        trades = trades[page*page_count: (page+1)*page_count]

    elif request.user["role"] == "issuer":
      # first find all the funds the issuer owns
      funds = Database.find("Fund")
      fundIds = [o['id'] for o in funds]
      tokenQuery = [[('fundId','=',fundId)] for fundId in fundIds]
      tokens = Database.find("Token", tokenQuery)
      tokenIds = [o['id'] for o in tokens]
      tradeQuery = []
      if 'tokenId' in query:
        tokenIds = [t for t in tokenIds if t == int(query['tokenId'])]
      if 'investorId' in query:
        tradeQuery = [[
          ('tokenId','=',tokenId),
          ('investorId','=',query['investorId'])
        ] for tokenId in tokenIds]
      else:
        tradeQuery = [[('tokenId','=',tokenId)] for tokenId in tokenIds]
      print(tradeQuery)
      trades = None

      if page_count:
        dbRes = Database.find("Trade", tradeQuery, page=page, page_count=page_count)
        trades = dbRes['data']
        total = dbRes['total']
      else:
        trades = Database.find("Trade", tradeQuery)

      for trade in trades:
        tradeBrokers = Database.find("TradeBroker", {"tradeId": trade["id"]})
        trade['tradeBrokers'] = tradeBrokers

    tokenIds = list(set([o["tokenId"] for o in trades]))
    tokens = [Database.find_one("Token", {"id": t}) for t in tokenIds]
    tokens = [toObject(t, ["id","address","cutoffTime","symbol","decimals"]) for t in tokens]
    tokens_hash = {token["id"]: token for token in tokens}
    for trade in trades:
      investor = Database.find_one("User", {"id": trade["investorId"]}, ["address", "id","name"])
      trade["investor"] = investor
      trade["token"] = tokens_hash[trade["tokenId"]]
      if request.user["role"] == "investor":
        tradeBrokers = Database.find("TradeBroker", {"tradeId": trade["id"]})
        for tradeBroker in tradeBrokers:
          tradeBroker["broker"] = Database.find_one("User", {"id": tradeBroker["brokerId"]}, ["address", "id","name"])
        trade["tradeBrokers"] = tradeBrokers

    return {"total": total, "data": toObject(trades), "page": page, "page_count": page_count}
Exemplo n.º 15
0
def getTokens():
    return Database.find("Token")
Exemplo n.º 16
0
 def token_get_dividends(tokenId):
     request = app.current_request
     user = request.user
     data = request.json_body
     dividends = Database.find("Dividend", {"tokenId": tokenId})
     return toObject(dividends)
Exemplo n.º 17
0
 def funds_get():
   request = app.current_request
   funds = Database.find("Fund")
   funds = [toObject(u) for u in funds]
   return funds