Skip to content
Snippets Groups Projects
Commit e29f27c5 authored by Fabian Schuh's avatar Fabian Schuh
Browse files

[minor] modifications and fixes as well as 'blocking' attribute

parent 7a8b8f4a
No related branches found
No related tags found
No related merge requests found
...@@ -117,10 +117,14 @@ class Account(dict): ...@@ -117,10 +117,14 @@ class Account(dict):
""" Obtain the balance of a specific Asset. This call returns instances of """ Obtain the balance of a specific Asset. This call returns instances of
:class:`bitshares.amount.Amount`. :class:`bitshares.amount.Amount`.
""" """
from .amount import Amount
if isinstance(symbol, dict) and "symbol" in symbol:
symbol = symbol["symbol"]
balances = self.balances balances = self.balances
for b in balances: for b in balances:
if b["symbol"] == symbol: if b["symbol"] == symbol:
return b return b
return Amount(0, symbol)
@property @property
def call_positions(self): def call_positions(self):
......
...@@ -42,6 +42,7 @@ class BitShares(object): ...@@ -42,6 +42,7 @@ class BitShares(object):
:param int proposal_expiration: Expiration time (in seconds) for the proposal *(optional)* :param int proposal_expiration: Expiration time (in seconds) for the proposal *(optional)*
:param int proposal_review: Review period (in seconds) for the proposal *(optional)* :param int proposal_review: Review period (in seconds) for the proposal *(optional)*
:param int expiration: Delay in seconds until transactions are supposed to expire *(optional)* :param int expiration: Delay in seconds until transactions are supposed to expire *(optional)*
:param str blocking: Wait for broadcasted transactions to be included in a block and return full transaction (can be "head" or "irrversible")
:param bool bundle: Do not broadcast transactions right away, but allow to bundle operations *(optional)* :param bool bundle: Do not broadcast transactions right away, but allow to bundle operations *(optional)*
Three wallet operation modes are possible: Three wallet operation modes are possible:
...@@ -122,6 +123,7 @@ class BitShares(object): ...@@ -122,6 +123,7 @@ class BitShares(object):
self.proposal_expiration = int(kwargs.get("proposal_expiration", 60 * 60 * 24)) self.proposal_expiration = int(kwargs.get("proposal_expiration", 60 * 60 * 24))
self.proposal_review = int(kwargs.get("proposal_review", 0)) self.proposal_review = int(kwargs.get("proposal_review", 0))
self.bundle = bool(kwargs.get("bundle", False)) self.bundle = bool(kwargs.get("bundle", False))
self.blocking = kwargs.get("blocking", False)
# Store config for access through other Classes # Store config for access through other Classes
self.config = config self.config = config
......
...@@ -175,7 +175,7 @@ class Blockchain(object): ...@@ -175,7 +175,7 @@ class Blockchain(object):
r.update(op["op"][1]) r.update(op["op"][1])
yield r yield r
def awaitTxConfirmation(self, transaction, limit=50): def awaitTxConfirmation(self, transaction, limit=10):
""" Returns the transaction as seen by the blockchain after being included into a block """ Returns the transaction as seen by the blockchain after being included into a block
.. note:: If you want instant confirmation, you need to instantiate .. note:: If you want instant confirmation, you need to instantiate
...@@ -190,8 +190,9 @@ class Blockchain(object): ...@@ -190,8 +190,9 @@ class Blockchain(object):
transaction contented and thus identifies a transaction transaction contented and thus identifies a transaction
uniquely. uniquely.
""" """
counter = 10 counter = 0
for block in self.blocks(): start = self.get_current_block_num() - 2
for block in self.blocks(start=start):
counter += 1 counter += 1
for tx in block["transactions"]: for tx in block["transactions"]:
if sorted(tx["signatures"]) == sorted(transaction["signatures"]): if sorted(tx["signatures"]) == sorted(transaction["signatures"]):
......
...@@ -123,20 +123,27 @@ class Market(dict): ...@@ -123,20 +123,27 @@ class Market(dict):
""" """
data = {} data = {}
# Core Exchange rate # Core Exchange rate
cer = self["quote"]["options"]["core_exchange_rate"]
data["core_exchange_rate"] = Price( data["core_exchange_rate"] = Price(
self["quote"]["options"]["core_exchange_rate"], cer,
bitshares_instance=self.bitshares bitshares_instance=self.bitshares
) )
if cer["base"]["asset_id"] == self["quote"]["id"]:
data["core_exchange_rate"] = data["core_exchange_rate"].invert()
# smartcoin stuff # smartcoin stuff
if "bitasset_data_id" in self["quote"]: if "bitasset_data_id" in self["quote"]:
bitasset = self.bitshares.rpc.get_object(self["quote"]["bitasset_data_id"]) bitasset = self.bitshares.rpc.get_object(self["quote"]["bitasset_data_id"])
backing_asset_id = bitasset["options"]["short_backing_asset"] backing_asset_id = bitasset["options"]["short_backing_asset"]
if backing_asset_id == self["base"]["id"]: if backing_asset_id == self["base"]["id"]:
sp = bitasset["current_feed"]["settlement_price"]
data["quoteSettlement_price"] = Price( data["quoteSettlement_price"] = Price(
bitasset["current_feed"]["settlement_price"], sp,
bitshares_instance=self.bitshares bitshares_instance=self.bitshares
) )
if sp["base"]["asset_id"] == self["quote"]["id"]:
data["quoteSettlement_price"] = data["quoteSettlement_price"].invert()
elif "bitasset_data_id" in self["base"]: elif "bitasset_data_id" in self["base"]:
bitasset = self.bitshares.rpc.get_object(self["base"]["bitasset_data_id"]) bitasset = self.bitshares.rpc.get_object(self["base"]["bitasset_data_id"])
backing_asset_id = bitasset["options"]["short_backing_asset"] backing_asset_id = bitasset["options"]["short_backing_asset"]
...@@ -428,14 +435,18 @@ class Market(dict): ...@@ -428,14 +435,18 @@ class Market(dict):
"expiration": formatTimeFromNow(expiration), "expiration": formatTimeFromNow(expiration),
"fill_or_kill": killfill, "fill_or_kill": killfill,
}) })
if returnOrderId:
# Make blocking broadcasts
prevblocking = self.bitshares.blocking
self.bitshares.blocking = returnOrderId
tx = self.bitshares.finalizeOp(order, account["name"], "active") tx = self.bitshares.finalizeOp(order, account["name"], "active")
if returnOrderId: if returnOrderId:
chain = Blockchain(
mode=("head" if returnOrderId == "head" else "irreversible"),
bitshares_instance=self.bitshares
)
tx = chain.awaitTxConfirmation(tx)
tx["orderid"] = tx["operation_results"][0][1] tx["orderid"] = tx["operation_results"][0][1]
self.bitshares.blocking = prevblocking
return tx return tx
def sell( def sell(
...@@ -509,15 +520,17 @@ class Market(dict): ...@@ -509,15 +520,17 @@ class Market(dict):
"expiration": formatTimeFromNow(expiration), "expiration": formatTimeFromNow(expiration),
"fill_or_kill": killfill, "fill_or_kill": killfill,
}) })
if returnOrderId:
# Make blocking broadcasts
prevblocking = self.bitshares.blocking
self.bitshares.blocking = returnOrderId
tx = self.bitshares.finalizeOp(order, account["name"], "active") tx = self.bitshares.finalizeOp(order, account["name"], "active")
if returnOrderId: if returnOrderId:
chain = Blockchain(
mode=("head" if returnOrderId == "head" else "irreversible"),
bitshares_instance=self.bitshares
)
tx = chain.awaitTxConfirmation(tx)
tx["orderid"] = tx["operation_results"][0][1] tx["orderid"] = tx["operation_results"][0][1]
return tx self.bitshares.blocking = prevblocking
def cancel(self, orderNumber, account=None): def cancel(self, orderNumber, account=None):
""" Cancels an order you have placed in a given market. Requires """ Cancels an order you have placed in a given market. Requires
......
...@@ -132,7 +132,7 @@ class Notify(Events): ...@@ -132,7 +132,7 @@ class Notify(Events):
continue continue
if isinstance(d, str): if isinstance(d, str):
# Single order has been placed # Single order has been placed
log.info("Calling on_market with Order()") log.debug("Calling on_market with Order()")
self.on_market(Order(d)) self.on_market(Order(d))
continue continue
elif isinstance(d, dict): elif isinstance(d, dict):
......
from .account import Account from .account import Account
from .blockchain import Blockchain
from bitsharesbase.objects import Operation from bitsharesbase.objects import Operation
from bitsharesbase.account import PrivateKey, PublicKey from bitsharesbase.account import PrivateKey, PublicKey
from bitsharesbase.signedtransactions import Signed_Transaction from bitsharesbase.signedtransactions import Signed_Transaction
...@@ -176,14 +177,23 @@ class TransactionBuilder(dict): ...@@ -176,14 +177,23 @@ class TransactionBuilder(dict):
log.warning("Not broadcasting anything!") log.warning("Not broadcasting anything!")
return self return self
tx = self.json()
# Broadcast # Broadcast
try: try:
self.bitshares.rpc.broadcast_transaction(self.json(), api="network_broadcast") self.bitshares.rpc.broadcast_transaction(tx, api="network_broadcast")
except Exception as e: except Exception as e:
raise e raise e
self.clear() self.clear()
if self.bitshares.blocking:
chain = Blockchain(
mode=("head" if self.bitshares.blocking == "head" else "irreversible"),
bitshares_instance=self.bitshares
)
tx = chain.awaitTxConfirmation(tx)
return tx
return self return self
def clear(self): def clear(self):
...@@ -191,6 +201,7 @@ class TransactionBuilder(dict): ...@@ -191,6 +201,7 @@ class TransactionBuilder(dict):
""" """
self.ops = [] self.ops = []
self.wifs = [] self.wifs = []
self.pop("signatures", None)
super(TransactionBuilder, self).__init__({}) super(TransactionBuilder, self).__init__({})
def addSigningInformation(self, account, permission): def addSigningInformation(self, account, permission):
......
...@@ -264,7 +264,7 @@ class BitSharesWebsocket(Events): ...@@ -264,7 +264,7 @@ class BitSharesWebsocket(Events):
else: else:
try: try:
callbackname = self.__events__[id] callbackname = self.__events__[id]
log.info("Patching through to call %s" % callbackname) log.debug("Patching through to call %s" % callbackname)
[getattr(self.events, callbackname)(x) for x in data["params"][1]] [getattr(self.events, callbackname)(x) for x in data["params"][1]]
except Exception as e: except Exception as e:
log.critical("Error in {}: {}\n\n{}".format( log.critical("Error in {}: {}\n\n{}".format(
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment