Exemple #1
0
    def withdraw(self, account, amount):
        """Widthdraw STEEMP to account as STEEM.

            :param str account: account name
            :param float amount: Amount to withdraw

            Withdraw example:

            .. code-block:: python

                from steemengine.market import Market
                from beem import Steem
                active_wif = "5xxxx"
                stm = Steem(keys=[active_wif])
                market = Market(steem_instance=stm)
                market.withdraw("test", 1)
        """
        wallet = Wallet(account, api=self.api, steem_instance=self.steem)
        token_in_wallet = wallet.get_token("STEEMP")
        if token_in_wallet is None:
            raise TokenNotInWallet("%s is not in wallet." % "STEEMP")
        if float(token_in_wallet["balance"]) < float(amount):
            raise InsufficientTokenAmount("Only %.3f in wallet" % float(token_in_wallet["balance"]))
        token = Token("STEEMP", api=self.api)
        quant_amount = token.quantize(amount)
        if quant_amount <= decimal.Decimal("0"):
            raise InvalidTokenAmount("Amount to transfer is below token precision of %d" % token["precision"])        
        contract_payload = {"quantity":str(quant_amount)}
        json_data = {"contractName":"steempegged","contractAction":"withdraw",
                     "contractPayload":contract_payload}
        tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[account])
        return tx
Exemple #2
0
    def sell(self, account, amount, symbol, price):
        """Sell token for given price.

            :param str account: account name
            :param float amount: Amount to withdraw
            :param str symbol: symbol
            :param float price: price

            Sell example:

            .. code-block:: python

                from steemengine.market import Market
                from beem import Steem
                active_wif = "5xxxx"
                stm = Steem(keys=[active_wif])
                market = Market(steem_instance=stm)
                market.sell("test", 1, "ENG", 0.95)
        """
        wallet = Wallet(account, api=self.api, steem_instance=self.steem)
        token_in_wallet = wallet.get_token(symbol)
        if token_in_wallet is None:
            raise TokenNotInWallet("%s is not in wallet." % symbol)
        if float(token_in_wallet["balance"]) < float(amount):
            raise InsufficientTokenAmount("Only %.3f in wallet" % float(token_in_wallet["balance"]))
        
        token = Token(symbol, api=self.api)
        quant_amount = token.quantize(amount)
        if quant_amount <= decimal.Decimal("0"):
            raise InvalidTokenAmount("Amount to transfer is below token precision of %d" % token["precision"])        
        contract_payload = {"symbol": symbol.upper(), "quantity":str(quant_amount), "price": str(price)}
        json_data = {"contractName":"market","contractAction":"sell",
                     "contractPayload":contract_payload}
        tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[account])
        return tx
Exemple #3
0
    def __init__(self, config, steemd_instance):
        self.config = config
        self.stm = steemd_instance

        self.daily_inflation = self.config["yearly_inflation"] / 365
        if not self.config["no_broadcast"]:
            self.stm.wallet.unlock(self.config["wallet_password"])

        self.scot_token = Token(self.config["scot_token"])
        self.token_wallet = Wallet(self.config["scot_account"],
                                   steem_instance=self.stm)
Exemple #4
0
    def transfer(self, to, amount, symbol, memo=""):
        """Transfer a token to another account.

            :param str to: Recipient
            :param float amount: Amount to transfer
            :param str symbol: Token to transfer
            :param str memo: (optional) Memo


            Transfer example:

            .. code-block:: python

                from steemengine.wallet import Wallet
                from beem import Steem
                active_wif = "5xxxx"
                stm = Steem(keys=[active_wif])
                wallet = Wallet("test", steem_instance=stm)
                wallet.transfer("test1", 1, "ENG", "test")
        """
        token_in_wallet = self.get_token(symbol)
        if token_in_wallet is None:
            raise TokenNotInWallet("%s is not in wallet." % symbol)
        if float(token_in_wallet["balance"]) < float(amount):
            raise InsufficientTokenAmount("Only %.3f in wallet" %
                                          float(token_in_wallet["balance"]))
        token = Token(symbol, api=self.api)
        quant_amount = token.quantize(amount)
        if quant_amount <= decimal.Decimal("0"):
            raise InvalidTokenAmount(
                "Amount to transfer is below token precision of %d" %
                token["precision"])
        check_to = Account(to, steem_instance=self.steem)
        contract_payload = {
            "symbol": symbol.upper(),
            "to": to,
            "quantity": str(quant_amount),
            "memo": memo
        }
        json_data = {
            "contractName": "tokens",
            "contractAction": "transfer",
            "contractPayload": contract_payload
        }
        tx = self.steem.custom_json(self.ssc_id,
                                    json_data,
                                    required_auths=[self.account])
        return tx
Exemple #5
0
    def issue(self, to, amount, symbol):
        """Issues a specific token amount.

            :param str to: Recipient
            :param float amount: Amount to issue
            :param str symbol: Token to issue


            Issue example:

            .. code-block:: python

                from steemengine.wallet import Wallet
                from beem import Steem
                active_wif = "5xxxx"
                stm = Steem(keys=[active_wif])
                wallet = Wallet("test", steem_instance=stm)
                wallet.issue(1, "my_token")
        """
        token = Token(symbol, api=self.api)
        if token["issuer"] != self.account:
            raise TokenIssueNotPermitted("%s is not the issuer of token %s" %
                                         (self.account, symbol))

        if token["maxSupply"] == token["supply"]:
            raise MaxSupplyReached("%s has reached is maximum supply of %d" %
                                   (symbol, token["maxSupply"]))
        quant_amount = token.quantize(amount)
        if quant_amount <= decimal.Decimal("0"):
            raise InvalidTokenAmount(
                "Amount to issue is below token precision of %d" %
                token["precision"])
        check_to = Account(to, steem_instance=self.steem)
        contract_payload = {
            "symbol": symbol.upper(),
            "to": to,
            "quantity": str(quant_amount)
        }
        json_data = {
            "contractName": "tokens",
            "contractAction": "issue",
            "contractPayload": contract_payload
        }
        tx = self.steem.custom_json(self.ssc_id,
                                    json_data,
                                    required_auths=[self.account])
        return tx
Exemple #6
0
 def get_token(self, symbol):
     """Returns Token from given token symbol. Is None
         when token does not exists.
     """
     for t in self:
         if t["symbol"].lower() == symbol.lower():
             return Token(t, api=self.api)
     return None
Exemple #7
0
    def unstake(self, amount, symbol):
        """Unstake a token.

            :param float amount: Amount to unstake
            :param str symbol: Token to unstake

            Unstake example:

            .. code-block:: python

                from steemengine.wallet import Wallet
                from beem import Steem
                active_wif = "5xxxx"
                stm = Steem(keys=[active_wif])
                wallet = Wallet("test", steem_instance=stm)
                wallet.unstake(1, "ENG")
        """
        token_in_wallet = self.get_token(symbol)
        if token_in_wallet is None:
            raise TokenNotInWallet("%s is not in wallet." % symbol)
        if "stake" not in token_in_wallet:
            raise InsufficientTokenAmount("Token cannot be unstaked")
        if float(token_in_wallet["stake"]) < float(amount):
            raise InsufficientTokenAmount(
                "Only %.3f are staked in the wallet" %
                float(token_in_wallet["stake"]))
        token = Token(symbol, api=self.api)
        quant_amount = token.quantize(amount)
        if quant_amount <= decimal.Decimal("0"):
            raise InvalidTokenAmount(
                "Amount to stake is below token precision of %d" %
                token["precision"])
        contract_payload = {
            "symbol": symbol.upper(),
            "quantity": str(quant_amount)
        }
        json_data = {
            "contractName": "tokens",
            "contractAction": "unstake",
            "contractPayload": contract_payload
        }
        tx = self.steem.custom_json(self.ssc_id,
                                    json_data,
                                    required_auths=[self.account])
        return tx
Exemple #8
0
def richlist(symbol, top):
    """ Shows the richlist of a token

    """
    token = Token(symbol)
    holder = token.get_holder()
    market_info = token.get_market_info()
    last_price = float(market_info["lastPrice"])
    sorted_holder = sorted(holder,
                           key=lambda account: float(account["balance"]),
                           reverse=True)
    t = PrettyTable(["Balance", "Account", "Value [STEEM]"])
    t.align = "l"
    for balance in sorted_holder[:int(top)]:
        t.add_row([
            balance["balance"], balance["account"],
            "%.3f" % (float(balance["balance"]) * last_price)
        ])
    print(t.get_string())
Exemple #9
0
import random
import schedule
import json
from dhooks import Webhook
import math
from beem.nodelist import NodeList
import json
import six
import requests
import getpass

beem_pass = ""  # Password to unlock beem wallet

api = Api()
tokens = Tokens()
token = Token("TMPS")
stm = Steem()
market = Market(steem_instance=stm)
wallet = Wallet("tmps", steem_instance=stm)
wallet2 = Wallet("market", steem_instance=stm)
stm.wallet.unlock(pwd=beem_pass)
blacklist = ["market", "tokens", "null", "tmps"]
dragon_token = wallet.get_token("TMPS")
wallet.refresh()
upvote_account = "ufm.pay"
adjusted_dragon = float(dragon_token["balance"]) * 0.95
balances = token.get_holder()
info = token.get_info()
max_post_age_days = 6
min_post_age = 5
whitelist = []
 def test_token(self):
     eng = Token("ENG")
     self.assertTrue(eng is not None)
     self.assertTrue(eng["symbol"] == "ENG")
Exemple #11
0
class Scot:
    def __init__(self, config, steemd_instance):
        self.config = config
        self.stm = steemd_instance

        self.daily_inflation = self.config["yearly_inflation"] / 365
        if not self.config["no_broadcast"]:
            self.stm.wallet.unlock(self.config["wallet_password"])

        self.scot_token = Token(self.config["scot_token"])
        self.token_wallet = Wallet(self.config["scot_account"],
                                   steem_instance=self.stm)

    def get_token_holder(self):
        offset = 0
        get_holder = self.scot_token.get_holder()
        offset += 1000
        new_holder = self.scot_token.get_holder(offset=offset)
        while len(new_holder) > 0:
            get_holder.append(new_holder)
            offset += 1000
            new_holder = self.scot_token.get_holder(offset=offset)

        token_per_100_vote = {}
        token_sum = 0
        for item in get_holder:
            if item["account"] == self.config["scot_account"]:
                continue
            token_sum += float(item["balance"])

        for item in get_holder:
            if item["account"] == self.config["scot_account"]:
                continue
            token_sum += float(item["balance"])
            if float(item["balance"]) > 0:
                token_per_100_vote[item["account"]] = (float(
                    item["balance"]) / token_sum) * self.daily_inflation / 10
        return token_per_100_vote

    def get_token_to_sent(self, start_block, stop_block, token_per_100_vote):
        token_to_authors = {}
        b = Blockchain(steem_instance=self.stm)
        for op in b.stream(start=start_block,
                           stop=stop_block,
                           opNames=["vote"],
                           max_batch_size=50):
            if op["voter"] not in token_per_100_vote:
                continue
            if not self.config["downvotes"] and op["weight"] < 0:
                continue
            if not self.config["upvotes"] and op["weight"] > 0:
                continue
            comment = Comment(op, steem_instance=self.stm)
            try:
                comment.refresh()
            except:
                print("Could not fetch %s" % comment["authorperm"])
                continue
            json_metadata = comment["json_metadata"]
            app = None
            SETokensSupported = None
            if isinstance(json_metadata, str):
                json_metadata = json.loads(json_metadata)
            if "app" in json_metadata:
                app = json_metadata["app"]
                if isinstance(app, dict) and "name" in app:
                    app = app["name"]
                elif isinstance(app, dict):
                    app = ""
            if "SETokensSupported" in json_metadata:
                SETokensSupported = json_metadata["SETokensSupported"]

            app_or_symbol = False
            if app is not None and len(
                    self.config["included_apps"]
            ) > 0 and app != "" and app in self.config["included_apps"]:
                app_or_symbol = True
            elif self.config["include_token_as_tag"] and self.scot_token[
                    "symbol"] in comment["tags"]:
                app_or_symbol = True
            elif SETokensSupported is not None and len(
                    SETokensSupported
            ) > 0 and self.scot_token["symbol"] in SETokensSupported:
                app_or_symbol = True
            if not app_or_symbol and not self.config["include_all_posts"]:
                continue

            token_amount = abs(
                op["weight"]) / 10000 * token_per_100_vote[op["voter"]]
            if op["weight"] < 0:
                if op["voter"] not in token_to_authors:
                    token_to_authors[op["voter"]] = token_amount
                else:
                    token_to_authors[op["voter"]] += token_amount
            else:
                if op["author"] not in token_to_authors:
                    token_to_authors[op["author"]] = token_amount
                else:
                    token_to_authors[op["author"]] += token_amount
        return token_to_authors

    def get_token_transfer_last_24_h(self):
        yesterday = date.today() - timedelta(days=1)
        yesterday_0_0_0 = datetime(yesterday.year, yesterday.month,
                                   yesterday.day)
        yesterday_23_59_59 = datetime(yesterday.year, yesterday.month,
                                      yesterday.day, 23, 59, 59)
        token_sent_last_24_h = 0
        for hist in self.token_wallet.get_history(self.scot_token["symbol"]):
            timestamp = datetime.strptime(hist["timestamp"], timeFormatZ)
            if timestamp <= yesterday_23_59_59:
                continue
            print(hist)
            if hist["from"] != self.config["scot_account"]:
                continue
            token_sent_last_24_h = float(hist["quantity"])
        return token_sent_last_24_h

    def count_token(self, token_to_authors):
        token_amount_to_sent = 0
        for author in token_to_authors:
            token_amount_to_sent += token_to_authors[author]
        return token_amount_to_sent

    def adapt_to_precision(self, token_to_authors):
        token_amount_to_sent = self.count_token(token_to_authors)
        for author in token_to_authors:
            token_to_authors[author] = token_to_authors[
                author] * self.daily_inflation / token_amount_to_sent
            token_to_authors[author] = math.floor(
                token_to_authors[author] * 10**self.scot_token["precision"]
            ) / 10**self.scot_token["precision"]
        return token_to_authors

    def send_token(self, token_to_authors):

        for author in token_to_authors:
            if token_to_authors[author] < 10**(-self.scot_token["precision"]):
                continue
            if self.config["no_broadcast"]:
                logger.info("Sending %f %s to %s" %
                            (token_to_authors[author],
                             self.scot_token["symbol"], author))
            else:
                self.token_wallet.transfer(author,
                                           token_to_authors[author],
                                           self.scot_token["symbol"],
                                           memo=self.config["token_memo"])
                time.sleep(4)

    def run(self):
        b = Blockchain(steem_instance=self.stm)

        yesterday = date.today() - timedelta(days=1)
        yesterday_0_0_0 = datetime(yesterday.year, yesterday.month,
                                   yesterday.day)
        yesterday_23_59_59 = datetime(yesterday.year, yesterday.month,
                                      yesterday.day, 23, 59, 59)
        start_block = b.get_estimated_block_num(addTzInfo(yesterday_0_0_0))
        stop_block = b.get_estimated_block_num(addTzInfo(yesterday_23_59_59))
        logger.info("Check token transfer from %s..." %
                    self.config["scot_account"])
        token_sent_last_24_h = self.get_token_transfer_last_24_h()
        if token_sent_last_24_h > 0:
            logger.warning("Token were already sent today...")
            return
        logger.info("No token transfer were found, continue...")
        token_per_100_vote = self.get_token_holder()
        logger.info("%d token holder were found." % len(token_per_100_vote))
        token_to_authors = self.get_token_to_sent(start_block, stop_block,
                                                  token_per_100_vote)
        token_to_authors = self.adapt_to_precision(token_to_authors)
        token_amount_to_sent = self.count_token(token_to_authors)
        logger.info("Start to send %f token to %d accounts" %
                    (token_amount_to_sent, len(token_to_authors)))
        self.send_token(token_to_authors)