From 9d9bf9eba44f66cf7236b6b744aa3aa57fc3d76f Mon Sep 17 00:00:00 2001 From: Mark Veidemanis Date: Tue, 25 Jan 2022 20:01:22 +0000 Subject: [PATCH] Implement converting all Revolut accounts to one currency --- handler/commands.py | 12 +++++++++++ handler/revolut.py | 52 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/handler/commands.py b/handler/commands.py index a2c8f60..638878b 100644 --- a/handler/commands.py +++ b/handler/commands.py @@ -408,3 +408,15 @@ class IRCCommands(object): @staticmethod def run(cmd, spl, length, authed, msg, agora, revolut, tx): agora.withdraw_funds() + + class shuffle(object): + name = "shuffle" + authed = True + helptext = "Convert all currencies in Revolut to supplied one. Usage: shuffle " + + @staticmethod + def run(cmd, spl, length, authed, msg, agora, revolut, tx): + if length == 2: + currency = spl[1] + rtrn = revolut.shuffle(currency) + msg(dumps(rtrn)) diff --git a/handler/revolut.py b/handler/revolut.py index 7614823..6233fb7 100644 --- a/handler/revolut.py +++ b/handler/revolut.py @@ -8,6 +8,8 @@ import requests from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend import jwt +from random import choices +from string import ascii_uppercase # Project imports from settings import settings @@ -199,3 +201,53 @@ class Revolut(object): else: total_usd += account["balance"] / rates[account["currency"]] return total_usd + + def convert(self, from_account_id, from_currency, to_account_id, to_currency, sell_amount): + """ + Convert currency. + :param sell_currency: currency to sell + :param buy_currency: currency to buy + :param sell_amount: amount of currency to sell + """ + reference = "".join(choices(ascii_uppercase, k=5)) + headers = {"Authorization": f"Bearer {self.token}"} + data = { + "from": { + "account_id": from_account_id, + "currency": from_currency, + "amount": sell_amount, + }, + "to": { + "account_id": to_account_id, + "currency": to_currency, + }, + "request_id": reference, + } + r = requests.post(f"{settings.Revolut.Base}/exchange", headers=headers, data=dumps(data)) + if r.status_code == 200: + return r.json() + else: + self.log.error("Error converting balance: {content}", content=r.content) + return False + + def shuffle(self, currency): + """ + Exchange money in all accounts to the given currency. + :param currency: the currency to convert all our funds to + """ + accounts = self.accounts() + + # Find given currency account + for account in accounts: + if account["currency"] == currency: + if account["state"] == "active" and account["public"] is True: + dest_account = account + # Remove this account + accounts.remove(dest_account) + break + + for account in accounts: + if account["balance"] > 0: + self.convert(account["id"], account["currency"], dest_account["id"], dest_account["currency"], account["balance"]) + + return True