AuthenticatedClient.unbond_tokens()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 17
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 3
dl 0
loc 17
rs 10
c 0
b 0
f 0
1
"""
2
Description:
3
4
    Authenticated Client Class for interacting with the Tradehub network.
5
    This client performs the actions on the tradehub network by submitting transaction on-chain.
6
    This class is designed to use public nodes for the API and WS clients to use.
7
8
Usage::
9
10
    from tradehub.authenticated_client import AuthenticatedClient
11
"""
12
13
from tradehub.transactions import Transactions as TradehubTransactions
14
import tradehub.types as types
15
from tradehub.utils import to_tradehub_asset_amount, format_withdraw_address
16
from tradehub.wallet import Wallet
17
18
19
class AuthenticatedClient(TradehubTransactions):
20
    """
21
    This class uses a private key to interact with the Tradehub network of validators.
22
23
    Execution of this function is as follows::
24
25
        AuthenticatedClient(network='mainnet',
26
                            wallet=Wallet(mnemonic='', network='mainnet')
27
                            trusted_ips=None,
28
                            trusted_uris=None)
29
    """
30
31
    '''
32
    TODO
33
    # AMM reward % -> /get_amm_reward_percentage
34
    # Vault types -> /get_vault_types
35
    # Vaults by address -> /get_vaults?address=${address}
36
    '''
37
38
    def __init__(self, wallet: Wallet, trusted_ips: list = None, trusted_uris: list = None, network: str = "testnet"):
39
        """
40
        :param wallet: Wallet Client that contains the attributes necessary for submitting on-chain transactions.
41
        :type wallet: Wallet
42
        :param network: The network you want to interact with. Accepts "testnet" or "mainnet".
43
        :type network: str
44
        :param trusted_ips: Known and trusted IPs to connect to for your API requests.
45
        :type trusted_ips: list
46
        :param trusted_uris: Known and trusted URIs to connect to for your API requests.
47
        :type trusted_uris: list
48
        """
49
        TradehubTransactions.__init__(self, wallet=wallet, trusted_ips=trusted_ips, trusted_uris=trusted_uris, network=network)
50
        self.wallet = wallet
51
52
    # Authenticated Client Functions
53
    '''
54
        The way each of these functions work follow a similar pattern.
55
        (1) The function is passed a message that matches a class from the type file.
56
        (2) That message and matching transaction type are sent to a function that standardizes builds of transaction sent to the blockchain.
57
        (3) Inside that standardization are the:
58
            (3a) - Determination of fees
59
            (3b) - Transformation of the message class to a Python dictionary/JSON object to facilitate signing and broadcast to the network.
60
            (3c) - Determination of account details
61
        (4) With everything standardized, each of the objects are then sent off to be signed and broadcast to the Tradehub blockchain.
62
    '''
63
    def update_profile(self, message: types.UpdateProfileMessage, fee: dict = None):
64
        """
65
        Function that makes the network requests to the Tradehub validators across the network.
66
67
        Execution of this function is as follows::
68
69
            update_profile(message=types.UpdateProfileMessage(username='PythonCICD', twitter='PythonCICD'))
70
71
        The expected return result for this function is as follows::
72
73
            {
74
                'height': '1927295',
75
                'txhash': 'C6AF947EE35EE5282BD140F9F51614FA1C7ACADAB263B921621097C786C06977',
76
                'raw_log': ...,
77
                'logs': ...,
78
                'gas_wanted': '100000000000',
79
                'gas_used': '68345'
80
            }
81
82
        :param message: UpdateProfileMessage Type that is a class of attributes required to make this on-chain action.
83
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
84
        :return: Dictionary of the transaction response sent on-chain.
85
        """
86
        transaction_type = "UPDATE_PROFILE_MSG_TYPE"
87
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
88
89
    def send_tokens(self, message: types.SendTokensMessage, fee: dict = None):
90
        """
91
        Function to send tokens from your wallet to a recipient.
92
93
        Execution of this function is as follows::
94
95
            sent_tokens(message=types.SendTokensMessage(to_address=send_address,
96
                                                        amount=types.SendTokensAmount(amount='10.1', denom='swth')))
97
98
        :param message: SendTokensMessage Type that is a class of attributes required to make this on-chain action.
99
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
100
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
101
        """
102
        transaction_type = "SEND_TOKENS_TYPE"
103
        if hasattr(message, 'from_address') and message.from_address in [None, ""]:
104
            message.from_address = self.wallet.address
105
        amounts = []
106
        for amount in message.amount:
107
            formatted_amount = to_tradehub_asset_amount(amount=float(amount.amount), decimals=self.tokens[amount.denom]["decimals"])
108
            amounts.append(types.SendTokensAmount(amount=formatted_amount, denom=amount.denom))
109
        message.amount = sorted(amounts, key=lambda x: x.denom.lower())  # When dealing with coin lists in Cosmos it is a requirement that they be ordered by name - https://github.com/cosmos/cosmos-sdk/blob/master/types/coin.go#L215
110
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
111
112
    def create_order(self, message: types.CreateOrderMessage, fee: dict = None):
113
        """
114
        Function to create an order on the Tradehub network.
115
116
        Execution of this function is as follows::
117
118
            create_order(message=types.CreateOrderMessage(market="swth_eth1",
119
                                                          side="sell",
120
                                                          quantity="200",
121
                                                          price="0.00002",
122
                                                          type="limit"))
123
124
        :param message: CreateOrderMessage Type that is a class of attributes required to make this on-chain action.
125
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
126
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
127
        """
128
        return self.create_orders(messages=[message], fee=fee)
129
130
    def create_orders(self, messages: [types.CreateOrderMessage], fee: dict = None):
131
        """
132
        Function to create multiple orders on the Tradehub network.
133
134
        Execution of this function is as follows::
135
136
            create_orders([message=types.CreateOrderMessage(market="swth_eth1",
137
                                                            side="sell",
138
                                                            quantity="200",
139
                                                            price="0.00002",
140
                                                            type="limit")])
141
142
        :param message: List of CreateOrderMessage Type that is a class of attributes required to make this on-chain action.
143
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
144
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
145
        """
146
        transaction_type = "CREATE_ORDER_MSG_TYPE"
147
        return self.submit_transaction_on_chain(messages=messages, transaction_type=transaction_type, fee=fee)
148
149
    def cancel_order(self, message: types.CancelOrderMessage, fee: dict = None):
150
        """
151
        Function to cancel an order on the Tradehub network.
152
153
        Execution of this function is as follows::
154
155
            cancel_order(message=types.CancelOrderMessage(id="D3F370A91D260DB3B1112757D8F9B66EEA1B7887FB4B247872D367F04A4C56EB"))
156
157
        :param message: CancelOrderMessage Type that is a class of attributes required to make this on-chain action.
158
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
159
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
160
        """
161
        return self.cancel_orders(messages=[message], fee=fee)
162
163
    def cancel_orders(self, messages: [types.CancelOrderMessage], fee: dict = None):
164
        """
165
        Function to cancel multiple order on the Tradehub network.
166
167
        Execution of this function is as follows::
168
169
            cancel_orders(message=[types.CancelOrderMessage(id="D3F370A91D260DB3B1112757D8F9B66EEA1B7887FB4B247872D367F04A4C56EB")])
170
171
        :param message: List of CancelOrderMessage Type that is a class of attributes required to make this on-chain action.
172
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
173
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
174
        """
175
        transaction_type = "CANCEL_ORDER_MSG_TYPE"
176
        return self.submit_transaction_on_chain(messages=messages, transaction_type=transaction_type, fee=fee)
177
178
    def cancel_all(self, message: types.CancelAllMessage, fee: dict = None):
179
        """
180
        Function to cancel all orders for a specific market on the Tradehub network.
181
182
        Execution of this function is as follows::
183
184
            cancel_all(message=types.CancelAllMessage(market='swth_eth1'))
185
186
        :param message: CancelAllMessage Type that is a class of attributes required to make this on-chain action.
187
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
188
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
189
        """
190
        transaction_type = "CANCEL_ALL_MSG_TYPE"
191
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
192
193
    def edit_order(self, message: types.EditOrderMessage, fee: dict = None):
194
        """
195
        Function to edit an open order on the Tradehub network.
196
197
        Execution of this function is as follows::
198
199
            edit_order(message=types.EditOrderMessage(id="816F6D321F696EA81EB9961BE51DB5CB31520217DAF75FA569446BDD85A21E96",
200
                                                      quantity="220",
201
                                                      stop_price="0.0000175"))
202
203
204
        :param message: EditOrderMessage Type that is a class of attributes required to make this on-chain action.
205
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
206
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
207
        """
208
        return self.edit_orders(messages=[message], fee=fee)
209
210
    def edit_orders(self, messages: [types.EditOrderMessage], fee: dict = None):
211
        """
212
        Function to edit open orders on the Tradehub network.
213
214
        Execution of this function is as follows::
215
216
            edit_orders(message=[types.EditOrderMessage(id="816F6D321F696EA81EB9961BE51DB5CB31520217DAF75FA569446BDD85A21E96",
217
                                                        quantity="220",
218
                                                        stop_price="0.0000175")])
219
220
        :param message: List of EditOrderMessage Type that is a class of attributes required to make this on-chain action.
221
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
222
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
223
        """
224
        transaction_type = "EDIT_ORDER_MSG_TYPE"
225
        return self.submit_transaction_on_chain(messages=messages, transaction_type=transaction_type, fee=fee)
226
227
    # def set_leverage(self, message: types.SetLeverageMessage, fee: dict = None):
228
    #     return self.set_leverages(messages=[message], fee=fee)
229
230
    # def set_leverages(self, messages: [types.SetLeverageMessage], fee: dict = None):
231
    #     transaction_type = "SET_LEVERAGE_MSG_TYPE"
232
    #     return self.submit_transaction_on_chain(messages=messages, transaction_type=transaction_type, fee=fee)
233
234
    # def edit_margin(self, message: types.EditMarginMessage, fee: dict = None):
235
    #     return self.edit_margins(messages=[message], fee=fee)
236
237
    # def edit_margins(self, messages: [types.EditMarginMessage], fee: dict = None):
238
    #     transaction_type = "EDIT_MARGIN_MSG_TYPE"
239
    #     return self.submit_transaction_on_chain(messages=messages, transaction_type=transaction_type, fee=fee)
240
241
    def stake_switcheo(self, message=types.DelegateTokensMessage, fee: dict = None):
242
        """
243
        Function to stake (or delegate) Switcheo to validators on the Tradehub network.
244
245
        Execution of this function is as follows::
246
247
            stake_switcheo(message=types.DelegateTokensMessage(delegator_address=self._wallet.address,
248
                                                               validator_address='tswthvaloper1hn0spc9plh5ker8lrtzyz9uqfe3xk2yn0c6nyf',
249
                                                               amount=types.DelegateTokensAmount(amount = '10.1', denom = 'swth')))
250
251
        :param message: DelegateTokensMessage Type that is a class of attributes required to make this on-chain action.
252
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
253
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
254
        """
255
        transaction_type = "DELEGATE_TOKENS_MSG_TYPE"
256
        message.amount.amount = to_tradehub_asset_amount(amount=float(message.amount.amount), decimals=self.tokens["swth"]["decimals"])
257
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
258
259
    def claim_staking_rewards(self, message=types.WithdrawDelegatorRewardsMessage, fee: dict = None):
260
        """
261
        Function to claim rewards generated from staking with a Switcheo validator on the Tradehub network.
262
263
        Execution of this function is as follows::
264
265
            claim_staking_rewards(message=types.WithdrawDelegatorRewardsMessage(delegator_address=self._wallet.address,
266
                                                                                validator_address='tswthvaloper10229tj7kh2mzwsn9cnfxuq3sqjuph860dlezpr'))
267
268
        :param message: WithdrawDelegatorRewardsMessage Type that is a class of attributes required to make this on-chain action.
269
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
270
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
271
        """
272
        transaction_type = "WITHDRAW_DELEGATOR_REWARDS_MSG_TYPE"
273
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
274
275
    def claim_all_staking_rewards(self, message=types.WithdrawAllDelegatorRewardsParams, fee: dict = None):
276
        """
277
        Function to claim rewards generated from all validators a wallet is staking with on the Tradehub network.
278
279
        Execution of this function is as follows::
280
281
            claim_all_staking_rewards(message=types.WithdrawAllDelegatorRewardsParams(delegator_address=self._wallet.address,
282
                                                                                      validator_addresses=['tswthvaloper1hn0spc9plh5ker8lrtzyz9uqfe3xk2yn0c6nyf', 'tswthvaloper10229tj7kh2mzwsn9cnfxuq3sqjuph860dlezpr']))
283
284
        :param message: WithdrawAllDelegatorRewardsMessage Type that is a class of attributes required to make this on-chain action.
285
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
286
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
287
        """
288
        transaction_type = "WITHDRAW_DELEGATOR_REWARDS_MSG_TYPE"
289
        messages = []
290
        for validator_address in message.validator_addresses:
291
            messages.append(types.WithdrawDelegatorRewardsMessage(delegator_address=message.delegator_address, validator_address=validator_address))
292
        return self.submit_transaction_on_chain(messages=messages, transaction_type=transaction_type, fee=fee)
293
294
    def unbond_tokens(self, message: types.BeginUnbondingTokensMessage, fee: dict = None):
295
        """
296
        Function to unbond tokens a validator on the Tradehub network.
297
298
        Execution of this function is as follows::
299
300
            unbond_tokens(message=types.BeginUnbondingTokensMessage(delegator_address=self._wallet.address,
301
                                                                    validator_address='tswthvaloper1hn0spc9plh5ker8lrtzyz9uqfe3xk2yn0c6nyf',
302
                                                                    amount=types.AmountMessage(amount='0.1', denom='swth')))
303
304
        :param message: BeginUnbondingTokensMessage Type that is a class of attributes required to make this on-chain action.
305
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
306
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
307
        """
308
        transaction_type = "BEGIN_UNBONDING_TOKENS_MSG_TYPE"
309
        message.amount.amount = to_tradehub_asset_amount(amount=float(message.amount.amount), decimals=self.tokens["swth"]["decimals"])
310
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
311
312
    def redelegate_tokens(self, message: types.BeginRedelegatingTokensMessage, fee: dict = None):
313
        """
314
        Function to move tokens from one validator to another on the Tradehub network.
315
316
        Execution of this function is as follows::
317
318
            redelegate_tokens(message=types.BeginRedelegatingTokensMessage(delegator_address=self._wallet.address,
319
                                                                           validator_src_address='tswthvaloper1hn0spc9plh5ker8lrtzyz9uqfe3xk2yn0c6nyf',
320
                                                                           validator_dst_address='tswthvaloper10229tj7kh2mzwsn9cnfxuq3sqjuph860dlezpr',
321
                                                                           amount=types.AmountMessage(amount='0.1', denom='swth'))
322
323
        :param message: BeginRedelegatingTokensMessage Type that is a class of attributes required to make this on-chain action.
324
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
325
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
326
        """
327
        transaction_type = "BEGIN_REDELEGATING_TOKENS_MSG_TYPE"
328
        message.amount.amount = to_tradehub_asset_amount(amount=float(message.amount.amount), decimals=self.tokens["swth"]["decimals"])
329
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
330
331
    def create_withdraw(self, message: types.CreateWithdrawMessage, blockchain: str, fee: dict = None):
332
        """
333
        Function to withdraw tokens from the Tradehub network onto the desired blockchain.
334
335
        Execution of this function is as follows::
336
337
            create_withdraw(message=types.CreateWithdrawMessage(to_address=NEO_ADDRESS,
338
                                                                denom='swth-n',
339
                                                                amount='87',
340
                                                                fee_amount="1"),
341
                            blockchain='NEO')
342
343
        :param message: CreateWithdrawMessage Type that is a class of attributes required to make this on-chain action.
344
        :param blockchain: String to specify if the withdraw is going to the NEO or Ethereum network.
345
        :param fee: Dict of the fee type, generally this can be left blank and allow the API to handle this.
346
        :return: Dictionary of the transaction response sent on-chain, look in the logs to be sure it matches what was sent.
347
        """
348
        message.fee_address = 'swth1prv0t8j8tqcdngdmjlt59pwy6dxxmtqgycy2h7'
349
        message.to_address = format_withdraw_address(address=message.to_address, blockchain=blockchain)
350
        transaction_type = "CREATE_WITHDRAWAL_TYPE"
351
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
352
353
    def create_validator(self, message: types.CreateValidatorMessage, fee: dict = None):
354
        transaction_type = "CREATE_VALIDATOR_MSG_TYPE"
355
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
356
357
    def create_sub_account(self, message: types.CreateSubAccountMessage, fee: dict = None):
358
        transaction_type = "CREATE_SUB_ACCOUNT_MSG_TYPE"
359
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
360
361
    def activate_sub_account(self, message: types.ActivateSubAccountMessage, fee: dict = None):
362
        transaction_type = "ACTIVATE_SUB_ACCOUNT_MSG_TYPE"
363
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
364
365
    def add_liquidity(self, message: types.AddLiquidityMessage, fee: dict = None):
366
        transaction_type = "ADD_LIQUIDITY_MSG_TYPE"
367
        if not hasattr(message, 'min_shares'):
368
            message.min_shares = '0'
369
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
370
371
    def remove_liquidity(self, message: types.RemoveLiquidityMessage, fee: dict = None):
372
        transaction_type = "REMOVE_LIQUIDITY_MSG_TYPE"
373
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
374
375
    def stake_pool_token(self, message: types.StakePoolTokenMessage, fee: dict = None):
376
        transaction_type = "STAKE_POOL_TOKEN_MSG_TYPE"
377
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
378
379
    def unstake_pool_token(self, message: types.UnstakePoolTokenMessage, fee: dict = None):
380
        transaction_type = "UNSTAKE_POOL_TOKEN_MSG_TYPE"
381
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
382
383
    def claim_pool_rewards(self, message: types.ClaimPoolRewardsMessage, fee: dict = None):
384
        transaction_type = "CLAIM_POOL_REWARDS_MSG_TYPE"
385
        return self.submit_transaction_on_chain(messages=[message], transaction_type=transaction_type, fee=fee)
386