From 82beae8c3056a29cb2900a92255dbb74add41164 Mon Sep 17 00:00:00 2001
From: Fabian Schuh <Fabian@chainsquad.com>
Date: Mon, 20 Feb 2017 10:51:26 +0100
Subject: [PATCH] [instance] use default_instances properly

---
 Makefile                        |   2 +-
 bitshares/account.py            |   7 +-
 bitshares/amount.py             |   6 +-
 bitshares/asset.py              |   6 +-
 bitshares/bitshares.py          | 181 +++++++++++++++-----------------
 bitshares/block.py              |   6 +-
 bitshares/blockchain.py         |   7 +-
 bitshares/dex.py                |   7 +-
 bitshares/instance.py           |  21 ++++
 bitshares/market.py             |   6 +-
 bitshares/memo.py               |   6 +-
 bitshares/price.py              |  74 +++++++------
 bitshares/transactionbuilder.py |   6 +-
 bitshares/wallet.py             |  20 ++--
 bitshares/witness.py            |   6 +-
 15 files changed, 180 insertions(+), 181 deletions(-)
 create mode 100644 bitshares/instance.py

diff --git a/Makefile b/Makefile
index 378a0772..03ce5de7 100644
--- a/Makefile
+++ b/Makefile
@@ -10,7 +10,7 @@ clean-build:
 	rm -fr build/
 	rm -fr dist/
 	rm -fr *.egg-info
-	rm -fr __pycache__/
+	rm -fr __pycache__/ .eggs/ .cache/
 
 clean-pyc:
 	find . -name '*.pyc' -exec rm -f {} +
diff --git a/bitshares/account.py b/bitshares/account.py
index aec04f60..7cd68e3f 100644
--- a/bitshares/account.py
+++ b/bitshares/account.py
@@ -1,4 +1,4 @@
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .amount import Amount
 from .exceptions import AccountDoesNotExistsException
 
@@ -16,10 +16,7 @@ class Account(dict):
     ):
         self.cached = False
         self.full = full
-
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         if isinstance(account, Account):
             super(Account, self).__init__(account)
diff --git a/bitshares/amount.py b/bitshares/amount.py
index 48678e7b..726213c0 100644
--- a/bitshares/amount.py
+++ b/bitshares/amount.py
@@ -1,4 +1,4 @@
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .asset import Asset
 
 
@@ -6,9 +6,7 @@ class Amount(dict):
     def __init__(self, *args, amount=None, asset=None, bitshares_instance=None):
         self["asset"] = {}
 
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         if len(args) == 1 and isinstance(args[0], Amount):
             # Copy Asset object
diff --git a/bitshares/asset.py b/bitshares/asset.py
index 0fa3c6cc..71fd5952 100644
--- a/bitshares/asset.py
+++ b/bitshares/asset.py
@@ -1,5 +1,5 @@
 import json
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .exceptions import AssetDoesNotExistsException
 
 
@@ -23,9 +23,7 @@ class Asset(dict):
         self.full = full
         self.asset = None
 
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         if isinstance(asset, Asset):
             self.asset = asset.get("symbol")
diff --git a/bitshares/bitshares.py b/bitshares/bitshares.py
index 05dbdad6..54c7a4fd 100644
--- a/bitshares/bitshares.py
+++ b/bitshares/bitshares.py
@@ -24,7 +24,44 @@ log = logging.getLogger(__name__)
 
 
 class BitShares(object):
-    """ The purpose of this class it to simplify interaction with
+    """ Connect to the BitShares network.
+
+        :param str node: Node to connect to *(optional)*
+        :param str rpcuser: RPC user *(optional)*
+        :param str rpcpassword: RPC password *(optional)*
+        :param bool nobroadcast: Do **not** broadcast a transaction! *(optional)*
+        :param bool debug: Enable Debugging *(optional)*
+        :param array,dict,string keys: Predefine the wif keys to shortcut the wallet database
+        :param bool offline: Boolean to prevent connecting to network (defaults to ``False``)
+
+        Three wallet operation modes are possible:
+
+        * **Wallet Database**: Here, the bitshareslibs load the keys from the
+          locally stored wallet SQLite database (see ``storage.py``).
+          To use this mode, simply call ``BitShares()`` without the
+          ``keys`` parameter
+        * **Providing Keys**: Here, you can provide the keys for
+          your accounts manually. All you need to do is add the wif
+          keys for the accounts you want to use as a simple array
+          using the ``keys`` parameter to ``BitShares()``.
+        * **Force keys**: This more is for advanced users and
+          requires that you know what you are doing. Here, the
+          ``keys`` parameter is a dictionary that overwrite the
+          ``active``, ``owner``, or ``memo`` keys for
+          any account. This mode is only used for *foreign*
+          signatures!
+
+        If no node is provided, it will connect to the node of
+        http://uptick.rocks. It is **highly** recommended that you pick your own
+        node instead. Default settings can be changed with:
+
+        .. code-block:: python
+
+            uptick set node <host>
+
+        where ``<host>`` starts with ``ws://`` or ``wss://``.
+
+        The purpose of this class it to simplify interaction with
         BitShares.
 
         The idea is to have a class that allows to do this:
@@ -50,107 +87,61 @@ class BitShares(object):
         This class also deals with edits, votes and reading content.
     """
 
-    wallet = None
-    config = None
-    rpc = None
-    debug = None
-    nobroadcast = None
-    unsigned = None
-    expiration = None
-
     def __init__(self,
                  node="",
                  rpcuser="",
                  rpcpassword="",
                  debug=False,
                  **kwargs):
-        """ Connect to the BitShares network.
-
-            :param str node: Node to connect to *(optional)*
-            :param str rpcuser: RPC user *(optional)*
-            :param str rpcpassword: RPC password *(optional)*
-            :param bool nobroadcast: Do **not** broadcast a transaction! *(optional)*
-            :param bool debug: Enable Debugging *(optional)*
-            :param array,dict,string keys: Predefine the wif keys to shortcut the wallet database
-            :param bool skipcreatewallet: Skip creation of a wallet
-
-            Three wallet operation modes are possible:
-
-            * **Wallet Database**: Here, the bitshareslibs load the keys from the
-              locally stored wallet SQLite database (see ``storage.py``).
-              To use this mode, simply call ``BitShares()`` without the
-              ``keys`` parameter
-            * **Providing Keys**: Here, you can provide the keys for
-              your accounts manually. All you need to do is add the wif
-              keys for the accounts you want to use as a simple array
-              using the ``keys`` parameter to ``BitShares()``.
-            * **Force keys**: This more is for advanced users and
-              requires that you know what you are doing. Here, the
-              ``keys`` parameter is a dictionary that overwrite the
-              ``active``, ``owner``, or ``memo`` keys for
-              any account. This mode is only used for *foreign*
-              signatures!
-
-            If no node is provided, it will connect to the node of
-            http://uptick.rocks. It is **highly** recommended that you pick your own
-            node instead. Default settings can be changed with:
-
-            .. code-block:: python
-
-                uptick set node <host>
-
-            where ``<host>`` starts with ``ws://`` or ``wss://``.
-        """
+
         # More specific set of APIs to register to
         if "apis" not in kwargs:
             kwargs["apis"] = [
                 "database",
                 "network_broadcast",
-                "account_by_key",
-                "follow",
             ]
 
-        if not BitShares.rpc:
-            """ Connect to BitShares network
-            """
-            if not node:
-                if "node" in config:
-                    node = config["node"]
-                else:
-                    raise ValueError("A BitShares node needs to be provided!")
-            if not rpcuser and "rpcuser" in config:
-                rpcuser = config["rpcuser"]
-            if not rpcpassword and "rpcpassword" in config:
-                rpcpassword = config["rpcpassword"]
-            BitShares.rpc = BitSharesNodeRPC(node, rpcuser, rpcpassword, **kwargs)
-
-        if BitShares.config is None:
-            BitShares.config = config
-        if BitShares.debug is None:
-            BitShares.debug = debug
-        if BitShares.nobroadcast is None:
-            BitShares.nobroadcast = kwargs.get("nobroadcast", False)
-        if BitShares.unsigned is None:
-            BitShares.unsigned = kwargs.pop("unsigned", False)
-        if BitShares.expiration is None:
-            BitShares.expiration = int(kwargs.pop("expires", 30))
-
-        self.rpc = BitShares.rpc
-
-        # Compatibility after name change from wif->keys
-        if "wif" in kwargs and "keys" not in kwargs:
-            kwargs["keys"] = kwargs["wif"]
-
-        if self.wallet is None:
-            if "keys" in kwargs:
-                BitShares.wallet = Wallet(self.rpc, keys=kwargs["keys"])
+        self.rpc = None
+        self.debug = debug
+
+        self.offline = kwargs.get("offline", False)
+        self.nobroadcast = kwargs.get("nobroadcast", False)
+        self.unsigned = kwargs.get("unsigned", False)
+        self.expiration = int(kwargs.get("expiration", 30))
+
+        if not self.offline:
+            self._connect(node=node,
+                          rpcuser=rpcuser,
+                          rpcpassword=rpcpassword,
+                          **kwargs)
+
+        self.wallet = Wallet(self.rpc, **kwargs)
+
+    def _connect(self,
+                 node="",
+                 rpcuser="",
+                 rpcpassword="",
+                 **kwargs):
+        """ Connect to Steem network (internal use only)
+        """
+        if not node:
+            if "node" in config:
+                node = config["node"]
             else:
-                BitShares.wallet = Wallet(self.rpc)
+                raise ValueError("A Steem node needs to be provided!")
+
+        if not rpcuser and "rpcuser" in config:
+            rpcuser = config["rpcuser"]
+
+        if not rpcpassword and "rpcpassword" in config:
+            rpcpassword = config["rpcpassword"]
+
+        self.rpc = BitSharesNodeRPC(node, rpcuser, rpcpassword, **kwargs)
 
     def newWallet(self):
         self.wallet.newWallet()
 
-    def finalizeOp(self, op, account, permission):
+    def finalizeOp(self, ops, account, permission):
         """ This method obtains the required private keys if present in
             the wallet, finalizes the transaction, signs it and
             broadacasts it
@@ -169,8 +160,8 @@ class BitShares(object):
                 posting permission. Neither can you use different
                 accounts for different operations!
         """
-        tx = TransactionBuilder()
-        tx.appendOps(op)
+        tx = TransactionBuilder(bitshares_instance=self)
+        tx.appendOps(ops)
 
         if self.unsigned:
             tx.addSigningInformation(account, permission)
@@ -190,7 +181,7 @@ class BitShares(object):
                 from the wallet as defined in "missing_signatures" key
                 of the transactions.
         """
-        tx = TransactionBuilder(tx)
+        tx = TransactionBuilder(tx, bitshares_instance=self)
         tx.appendMissingSignatures(wifs)
         tx.sign()
         return tx.json()
@@ -278,13 +269,13 @@ class BitShares(object):
             )
 
         try:
-            Account(account_name)
+            Account(account_name, bitshares_instance=self)
             raise AccountExistsException
         except:
             pass
 
-        referrer = Account(referrer)
-        registrar = Account(registrar)
+        referrer = Account(referrer, bitshares_instance=self)
+        registrar = Account(registrar, bitshares_instance=self)
 
         " Generate new keys from password"
         from bitsharesbase.account import PasswordKey, PublicKey
@@ -434,7 +425,7 @@ class BitShares(object):
             raise ValueError(
                 "Permission needs to be either 'owner', or 'active"
             )
-        account = Account(account)
+        account = Account(account, bitshares_instance=self)
 
         if not weight:
             weight = account[permission]["weight_threshold"]
@@ -448,7 +439,7 @@ class BitShares(object):
             ])
         except:
             try:
-                foreign_account = Account(foreign)
+                foreign_account = Account(foreign, bitshares_instance=self)
                 authority["account_auths"].append([
                     foreign_account["id"],
                     weight
@@ -495,7 +486,7 @@ class BitShares(object):
             raise ValueError(
                 "Permission needs to be either 'owner', or 'active"
             )
-        account = Account(account)
+        account = Account(account, bitshares_instance=self)
         authority = account[permission]
 
         try:
@@ -509,7 +500,7 @@ class BitShares(object):
             ))
         except:
             try:
-                foreign_account = Account(foreign)
+                foreign_account = Account(foreign, bitshares_instance=self)
                 affected_items = list(
                     filter(lambda x: x[0] == foreign_account["id"],
                            authority["account_auths"]))
@@ -569,7 +560,7 @@ class BitShares(object):
 
         PublicKey(key)  # raises exception if invalid
 
-        account = Account(account)
+        account = Account(account, bitshares_instance=self)
         account["options"].update({
             "memo_key": "BTS5TPTziKkLexhVKsQKtSpo4bAv5RnB8oXcG4sMHEwCcTf3r7dqE"}
         )
diff --git a/bitshares/block.py b/bitshares/block.py
index dff533da..67a57a96 100644
--- a/bitshares/block.py
+++ b/bitshares/block.py
@@ -1,4 +1,4 @@
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .exceptions import BlockDoesNotExistsException
 
 
@@ -7,9 +7,7 @@ class Block(dict):
         self.cached = False
         self.block = block
 
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         if isinstance(block, Block):
             super(Block, self).__init__(block)
diff --git a/bitshares/blockchain.py b/bitshares/blockchain.py
index dbd7e182..e5008f7f 100644
--- a/bitshares/blockchain.py
+++ b/bitshares/blockchain.py
@@ -1,6 +1,6 @@
 import time
 from .block import Block
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .utils import parse_time
 from bitsharesbase.operationids import operations, getOperationNameForId
 
@@ -18,9 +18,8 @@ class Blockchain(object):
             :param str mode: (default) Irreversible block
                     (``irreversible``) or actual head block (``head``)
         """
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
+
         if mode == "irreversible":
             self.mode = 'last_irreversible_block_num'
         elif mode == "head":
diff --git a/bitshares/dex.py b/bitshares/dex.py
index 5a0cc7b3..ee7c79bc 100644
--- a/bitshares/dex.py
+++ b/bitshares/dex.py
@@ -1,5 +1,5 @@
 # from .storage import config
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .account import Account
 from .asset import Asset
 from .amount import Amount
@@ -17,10 +17,7 @@ from bitsharesbase.objects import Operation
 
 class Dex():
     def __init__(self, bitshares_instance=None, **kwargs):
-
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
     def returnFees(self):
         """ Returns a dictionary of all fees that apply through the
diff --git a/bitshares/instance.py b/bitshares/instance.py
new file mode 100644
index 00000000..924df68e
--- /dev/null
+++ b/bitshares/instance.py
@@ -0,0 +1,21 @@
+import bitshares as bts
+
+_shared_bitshares_instance = None
+
+
+def shared_bitshares_instance():
+    """ This method will initialize _shared_bitshares_instance and return it.
+    The purpose of this method is to have offer single default bitshares instance that can be reused by multiple classes.
+    """
+    global _shared_bitshares_instance
+    if not _shared_bitshares_instance:
+        _shared_bitshares_instance = bts.BitShares()
+    return _shared_bitshares_instance
+
+
+def set_shared_bitshares_instance(bitshares_instance):
+    """ This method allows us to override default bitshares instance for all users of
+    _shared_bitshares_instance.
+    """
+    global _shared_bitshares_instance
+    _shared_bitshares_instance = bitshares_instance
diff --git a/bitshares/market.py b/bitshares/market.py
index 7a8f3209..5ed097f2 100644
--- a/bitshares/market.py
+++ b/bitshares/market.py
@@ -1,4 +1,4 @@
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from datetime import datetime, timedelta
 from .utils import formatTimeFromNow, formatTime, formatTimeString
 from .asset import Asset
@@ -19,9 +19,7 @@ class Market(dict):
         bitshares_instance=None,
         **kwargs
     ):
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         if len(args) == 1 and isinstance(args[0], str):
             import re
diff --git a/bitshares/memo.py b/bitshares/memo.py
index 38e6e801..1515f92e 100644
--- a/bitshares/memo.py
+++ b/bitshares/memo.py
@@ -1,4 +1,4 @@
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 import random
 from bitsharesbase import memo as BtsMemo
 from bitsharesbase.account import PrivateKey, PublicKey
@@ -9,9 +9,7 @@ from .exceptions import MissingKeyError
 class Memo(object):
     def __init__(self, from_account, to_account, memo, bitshares_instance=None):
 
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         memo_wif = self.bitshares.wallet.getPrivateKeyForPublicKey(
             from_account["options"]["memo_key"]
diff --git a/bitshares/price.py b/bitshares/price.py
index cb9f6806..bd033643 100644
--- a/bitshares/price.py
+++ b/bitshares/price.py
@@ -1,11 +1,13 @@
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .amount import Amount
 from .asset import Asset
 from .utils import formatTimeString
 
 
 class Price(dict):
-    def __init__(self, *args, base=None, quote=None):
+    def __init__(self, *args, base=None, quote=None, bitshares_instance=None):
+
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         if len(args) == 1:
             obj = args[0]
@@ -22,11 +24,11 @@ class Price(dict):
                 elif "base" in obj and "quote" in obj:
                     base_id = obj["base"]["asset_id"]
                     if obj["base"]["asset_id"] == base_id:
-                        self["base"] = Amount(obj["base"])
-                        self["quote"] = Amount(obj["quote"])
+                        self["base"] = Amount(obj["base"], bitshares_instance=self.bitshares)
+                        self["quote"] = Amount(obj["quote"], bitshares_instance=self.bitshares)
                     else:
-                        self["quote"] = Amount(obj["base"])
-                        self["base"] = Amount(obj["quote"])
+                        self["quote"] = Amount(obj["base"], bitshares_instance=self.bitshares)
+                        self["base"] = Amount(obj["quote"], bitshares_instance=self.bitshares)
 
                 # Filled order
                 elif "op" in obj:
@@ -35,12 +37,12 @@ class Price(dict):
                     if obj["op"]["receives"]["asset_id"] == base["id"]:
                         # If the seller received "base" in a quote_base market, than
                         # it has been a sell order of quote
-                        self["base"] = Amount(obj["op"]["receives"])
-                        self["quote"] = Amount(obj["op"]["pays"])
+                        self["base"] = Amount(obj["op"]["receives"], bitshares_instance=self.bitshares)
+                        self["quote"] = Amount(obj["op"]["pays"], bitshares_instance=self.bitshares)
                     else:
                         # buy order
-                        self["base"] = Amount(obj["op"]["pays"])
-                        self["quote"] = Amount(obj["op"]["receives"])
+                        self["base"] = Amount(obj["op"]["pays"], bitshares_instance=self.bitshares)
+                        self["quote"] = Amount(obj["op"]["receives"], bitshares_instance=self.bitshares)
 
                 else:
                     raise ValueError("Invalid json format for Price()")
@@ -51,11 +53,11 @@ class Price(dict):
                     self["quote"] = Amount({
                         "amount": 10 ** qp,
                         "asset": quote
-                    })
+                    }, bitshares_instance=self.bitshares)
                     self["base"] = Amount({
                         "amount": float(obj) * 10 ** bp,
                         "asset": base
-                    })
+                    }, bitshares_instance=self.bitshares)
 
             elif (isinstance(base, str) and isinstance(quote, str)):
                     self["base"] = Asset(base)
@@ -66,8 +68,8 @@ class Price(dict):
         elif len(args) == 2:
             if isinstance(args[0], str) and isinstance(args[1], str):
                 self["quote"], self["base"] = args[0], args[1]
-                self["base"] = Amount(base)
-                self["quote"] = Amount(quote)
+                self["base"] = Amount(base, bitshares_instance=self.bitshares)
+                self["quote"] = Amount(quote, bitshares_instance=self.bitshares)
 
             if isinstance(args[0], Amount) and isinstance(args[1], Amount):
                 self["quote"], self["base"] = args[0], args[1]
@@ -272,7 +274,10 @@ class Price(dict):
 
 class Order(Price):
 
-    def __init__(self, *args, **kwargs):
+    def __init__(self, *args, bitshares_instance=None, **kwargs):
+
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
+
         if (
             isinstance(args[0], dict) and
             "sell_price" in args[0]
@@ -281,8 +286,8 @@ class Order(Price):
             for k, v in args[0].items():
                 self[k] = v
             self["price"] = Price(args[0]["sell_price"])
-            self["quote"] = Amount(args[0]["sell_price"]["quote"])
-            self["base"] = Amount(args[0]["sell_price"]["base"])
+            self["quote"] = Amount(args[0]["sell_price"]["quote"], bitshares_instance=self.bitshares)
+            self["base"] = Amount(args[0]["sell_price"]["base"], bitshares_instance=self.bitshares)
 
         elif (
             isinstance(args[0], dict) and
@@ -290,17 +295,17 @@ class Order(Price):
             "amount_to_sell" in args[0]
         ):
             super(Order, self).__init__(
-                Amount(args[0]["min_to_receive"]),
-                Amount(args[0]["amount_to_sell"]),
+                Amount(args[0]["min_to_receive"], bitshares_instance=self.bitshares),
+                Amount(args[0]["amount_to_sell"], bitshares_instance=self.bitshares),
             )
             for k, v in args[0].items():
                 self[k] = v
             self["price"] = Price(
-                Amount(args[0]["min_to_receive"]),
-                Amount(args[0]["amount_to_sell"])
+                Amount(args[0]["min_to_receive"], bitshares_instance=self.bitshares),
+                Amount(args[0]["amount_to_sell"], bitshares_instance=self.bitshares)
             )
-            self["quote"] = Amount(args[0]["min_to_receive"])
-            self["base"] = Amount(args[0]["amount_to_sell"])
+            self["quote"] = Amount(args[0]["min_to_receive"], bitshares_instance=self.bitshares)
+            self["base"] = Amount(args[0]["amount_to_sell"], bitshares_instance=self.bitshares)
 
         elif isinstance(args[0], Amount) and isinstance(args[1], Amount):
             self["price"] = Price(*args, **kwargs)
@@ -312,7 +317,10 @@ class Order(Price):
 
 class FilledOrder(Price):
 
-    def __init__(self, order, **kwargs):
+    def __init__(self, order, bitshares_instance=None, **kwargs):
+
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
+
         if isinstance(order, dict) and "price" in order:
             super(FilledOrder, self).__init__(
                 order.get("price"),
@@ -321,11 +329,13 @@ class FilledOrder(Price):
             )
             self["quote"] = Amount(
                 order.get("amount"),
-                kwargs.get("quote")
+                kwargs.get("quote"),
+                bitshares_instance=self.bitshares
             )
             self["base"] = Amount(
                 order.get("value"),
-                kwargs.get("base")
+                kwargs.get("base"),
+                bitshares_instance=self.bitshares
             )
             self["time"] = formatTimeString(order["date"])
             self["price"] = Price(
@@ -344,12 +354,12 @@ class FilledOrder(Price):
             for k, v in order.items():
                 self[k] = v
             if base["id"] == order["op"]["receives"]["asset_id"]:
-                self["quote"] = Amount(order["op"]["receives"])
-                self["base"] = Amount(order["op"]["pays"])
+                self["quote"] = Amount(order["op"]["receives"], bitshares_instance=self.bitshares)
+                self["base"] = Amount(order["op"]["pays"], bitshares_instance=self.bitshares)
                 self["type"] = "buy"
             else:
-                self["quote"] = Amount(order["op"]["pays"])
-                self["base"] = Amount(order["op"]["receives"])
+                self["quote"] = Amount(order["op"]["pays"], bitshares_instance=self.bitshares)
+                self["base"] = Amount(order["op"]["receives"], bitshares_instance=self.bitshares)
                 self["type"] = "sell"
 
             self["time"] = formatTimeString(self["time"])
@@ -363,8 +373,8 @@ class FilledOrder(Price):
             "receives" in order and
             "pays" in order
         ):
-            self["quote"] = Amount(order["pays"])
-            self["base"] = Amount(order["receives"])
+            self["quote"] = Amount(order["pays"], bitshares_instance=self.bitshares)
+            self["base"] = Amount(order["receives"], bitshares_instance=self.bitshares)
             self["time"] = None
             self["price"] = Price(
                 self["base"],
diff --git a/bitshares/transactionbuilder.py b/bitshares/transactionbuilder.py
index c629e5f2..d647c127 100644
--- a/bitshares/transactionbuilder.py
+++ b/bitshares/transactionbuilder.py
@@ -8,7 +8,7 @@ from .exceptions import (
     MissingKeyError,
     InvalidWifError
 )
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 import logging
 log = logging.getLogger(__name__)
 
@@ -19,9 +19,7 @@ class TransactionBuilder(dict):
     """
 
     def __init__(self, tx={}, bitshares_instance=None):
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         self.op = []
         self.wifs = []
diff --git a/bitshares/wallet.py b/bitshares/wallet.py
index 87f64493..d6454d7e 100644
--- a/bitshares/wallet.py
+++ b/bitshares/wallet.py
@@ -1,16 +1,14 @@
+import logging
+import os
+
+from graphenebase import bip38
 from bitsharesbase.account import PrivateKey, GPHPrivateKey
-import bitshares as bts
-from bitsharesbase import bip38
+
+from .account import Account
 from .exceptions import (
-    NoWallet,
     InvalidWifError,
     WalletExists
 )
-import os
-import json
-from appdirs import user_data_dir
-import logging
-from .account import Account
 
 log = logging.getLogger(__name__)
 
@@ -53,12 +51,12 @@ class Wallet():
     keys = {}  # struct with pubkey as key and wif as value
     keyMap = {}  # type:wif pairs to force certain keys
 
-    def __init__(self, *args, **kwargs):
+    def __init__(self, rpc, *args, **kwargs):
         from .storage import configStorage
         self.configStorage = configStorage
 
         # RPC
-        Wallet.rpc = bts.BitShares.rpc
+        Wallet.rpc = rpc
 
         # Prefix?
         if Wallet.rpc:
@@ -98,7 +96,7 @@ class Wallet():
                 key = PrivateKey(wif)
             except:
                 raise InvalidWifError
-            self.keys[format(key.pubkey, self.prefix)] = str(key)
+            Wallet.keys[format(key.pubkey, self.prefix)] = str(key)
 
     def unlock(self, pwd=None):
         """ Unlock the wallet database
diff --git a/bitshares/witness.py b/bitshares/witness.py
index 1f29153f..e951819c 100644
--- a/bitshares/witness.py
+++ b/bitshares/witness.py
@@ -1,4 +1,4 @@
-import bitshares as bts
+from bitshares.instance import shared_bitshares_instance
 from .account import Account
 from .exceptions import WitnessDoesNotExistsException
 
@@ -20,9 +20,7 @@ class Witness(dict):
         self.cached = False
         self.witness = witness
 
-        if not bitshares_instance:
-            bitshares_instance = bts.BitShares()
-        self.bitshares = bitshares_instance
+        self.bitshares = bitshares_instance or shared_bitshares_instance()
 
         if not lazy:
             self.refresh()
-- 
GitLab