diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e3b9b8e6..a1388bd3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -22,3 +22,7 @@ repos: hooks: - id: isort name: isort (python) +- repo: https://github.com/psf/black-pre-commit-mirror + rev: 23.9.1 + hooks: + - id: black diff --git a/compatibility-tests/tests.py b/compatibility-tests/tests.py index 7e01fbcf..c1872378 100644 --- a/compatibility-tests/tests.py +++ b/compatibility-tests/tests.py @@ -16,7 +16,6 @@ class Transaction: - def __init__( self, *, @@ -94,17 +93,14 @@ def get_signed(self) -> str: return json.dumps(signed_tx, separators=(",", ":")) def _sign(self) -> str: - message_str = json.dumps( - self._get_sign_message(), separators=(",", ":"), sort_keys=True) + message_str = json.dumps(self._get_sign_message(), separators=(",", ":"), sort_keys=True) message_bytes = message_str.encode("utf-8") - privkey = ecdsa.SigningKey.from_string( - self._privkey, curve=ecdsa.SECP256k1) + privkey = ecdsa.SigningKey.from_string(self._privkey, curve=ecdsa.SECP256k1) signature_compact_keccak = privkey.sign_deterministic( message_bytes, hashfunc=sha3.keccak_256, sigencode=ecdsa.util.sigencode_string_canonize ) - signature_base64_str = base64.b64encode( - signature_compact_keccak).decode("utf-8") + signature_base64_str = base64.b64encode(signature_compact_keccak).decode("utf-8") return signature_base64_str def _get_sign_message(self) -> Dict[str, Any]: @@ -122,15 +118,13 @@ def _get_sign_message(self) -> Dict[str, Any]: async def main() -> None: - sender_pk = seed_to_privkey( - "physical page glare junk return scale subject river token door mirror title" - ) + sender_pk = seed_to_privkey("physical page glare junk return scale subject river token door mirror title") sender_acc_addr = privkey_to_address(sender_pk) print("Sender Account:", sender_acc_addr) acc_num, acc_seq = await get_account_num_seq(sender_acc_addr) - async with grpc.aio.insecure_channel('testnet-sentry0.injective.network:9910') as channel: + async with grpc.aio.insecure_channel("testnet-sentry0.injective.network:9910") as channel: accounts_rpc = accounts_rpc_grpc.InjectiveAccountsRPCStub(channel) account_addr = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku" @@ -169,34 +163,38 @@ async def main() -> None: async def get_account_num_seq(address: str) -> (int, int): async with aiohttp.ClientSession() as session: async with session.request( - 'GET', 'http://staking-lcd-testnet.injective.network/cosmos/auth/v1beta1/accounts/' + address, - headers={'Accept-Encoding': 'application/json'}, + "GET", + "http://staking-lcd-testnet.injective.network/cosmos/auth/v1beta1/accounts/" + address, + headers={"Accept-Encoding": "application/json"}, ) as response: if response.status != 200: print(await response.text()) raise ValueError("HTTP response status", response.status) resp = json.loads(await response.text()) - acc = resp['account']['base_account'] - return acc['account_number'], acc['sequence'] + acc = resp["account"]["base_account"] + return acc["account_number"], acc["sequence"] async def post_tx(tx_json: str): async with aiohttp.ClientSession() as session: async with session.request( - 'POST', 'http://staking-lcd-testnet.injective.network/txs', data=tx_json, - headers={'Content-Type': 'application/json'}, + "POST", + "http://staking-lcd-testnet.injective.network/txs", + data=tx_json, + headers={"Content-Type": "application/json"}, ) as response: if response.status != 200: print(await response.text()) raise ValueError("HTTP response status", response.status) resp = json.loads(await response.text()) - if 'code' in resp: + if "code" in resp: print("Response:", resp) - raise ValueError('sdk error %d: %s' % (resp['code'], resp['raw_log'])) + raise ValueError("sdk error %d: %s" % (resp["code"], resp["raw_log"])) + + return resp["txhash"] - return resp['txhash'] if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/compatibility-tests/unit_tests.py b/compatibility-tests/unit_tests.py index a2a4a7ae..7c19a28c 100644 --- a/compatibility-tests/unit_tests.py +++ b/compatibility-tests/unit_tests.py @@ -16,7 +16,6 @@ class Transaction: - def __init__( self, *, @@ -92,17 +91,14 @@ def get_signed(self) -> str: return json.dumps(signed_tx, separators=(",", ":")) def _sign(self) -> str: - message_str = json.dumps( - self._get_sign_message(), separators=(",", ":"), sort_keys=True) + message_str = json.dumps(self._get_sign_message(), separators=(",", ":"), sort_keys=True) message_bytes = message_str.encode("utf-8") - privkey = ecdsa.SigningKey.from_string( - self._privkey, curve=ecdsa.SECP256k1) + privkey = ecdsa.SigningKey.from_string(self._privkey, curve=ecdsa.SECP256k1) signature_compact_keccak = privkey.sign_deterministic( message_bytes, hashfunc=sha3.keccak_256, sigencode=ecdsa.util.sigencode_string_canonize ) - signature_base64_str = base64.b64encode( - signature_compact_keccak).decode("utf-8") + signature_base64_str = base64.b64encode(signature_compact_keccak).decode("utf-8") return signature_base64_str def _get_sign_message(self) -> Dict[str, Any]: @@ -122,47 +118,48 @@ def _get_sign_message(self) -> Dict[str, Any]: async def get_account_num_seq(address: str) -> (int, int): async with aiohttp.ClientSession() as session: async with session.request( - 'GET', 'http://staking-lcd-testnet.injective.network/cosmos/auth/v1beta1/accounts/' + address, - headers={'Accept-Encoding': 'application/json'}, + "GET", + "http://staking-lcd-testnet.injective.network/cosmos/auth/v1beta1/accounts/" + address, + headers={"Accept-Encoding": "application/json"}, ) as response: if response.status != 200: print(await response.text()) raise ValueError("HTTP response status", response.status) resp = json.loads(await response.text()) - acc = resp['account']['base_account'] - return acc['account_number'], acc['sequence'] + acc = resp["account"]["base_account"] + return acc["account_number"], acc["sequence"] async def post_tx(tx_json: str): async with aiohttp.ClientSession() as session: async with session.request( - 'POST', 'http://staking-lcd-testnet.injective.network/txs', data=tx_json, - headers={'Content-Type': 'application/json'}, + "POST", + "http://staking-lcd-testnet.injective.network/txs", + data=tx_json, + headers={"Content-Type": "application/json"}, ) as response: if response.status != 200: print(await response.text()) raise ValueError("HTTP response status", response.status) resp = json.loads(await response.text()) - if 'code' in resp: + if "code" in resp: print("Response:", resp) - raise ValueError('sdk error %d: %s' % (resp['code'], resp['raw_log'])) + raise ValueError("sdk error %d: %s" % (resp["code"], resp["raw_log"])) - return resp['txhash'] + return resp["txhash"] @pytest.fixture async def msg_send(): - sender_pk = seed_to_privkey( - "physical page glare junk return scale subject river token door mirror title" - ) + sender_pk = seed_to_privkey("physical page glare junk return scale subject river token door mirror title") sender_acc_addr = privkey_to_address(sender_pk) print("Sender Account:", sender_acc_addr) acc_num, acc_seq = await get_account_num_seq(sender_acc_addr) - async with grpc.aio.insecure_channel('testnet-sentry0.injective.network:9910') as channel: + async with grpc.aio.insecure_channel("testnet-sentry0.injective.network:9910") as channel: accounts_rpc = accounts_rpc_grpc.InjectiveAccountsRPCStub(channel) account_addr = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku" diff --git a/examples/SendToInjective.py b/examples/SendToInjective.py index 4563a145..b03988b4 100644 --- a/examples/SendToInjective.py +++ b/examples/SendToInjective.py @@ -20,11 +20,12 @@ async def main() -> None: receiver = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku" amount = 1 - data = ('{"@type": "/injective.exchange.v1beta1.MsgDeposit",' - '"sender": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",' - '"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",' - '"amount": {"denom": "inj","amount": "1000000000000000000"}}' - ) + data = ( + '{"@type": "/injective.exchange.v1beta1.MsgDeposit",' + '"sender": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",' + '"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",' + '"amount": {"denom": "inj","amount": "1000000000000000000"}}' + ) with open("../pyinjective/Peggo_ABI.json") as pego_file: peggo_data = pego_file.read() @@ -39,8 +40,9 @@ async def main() -> None: maxFeePerGas=maxFeePerGas_Gwei, maxPriorityFeePerGas=maxPriorityFeePerGas_Gwei, data=data, - peggo_abi=peggo_abi + peggo_abi=peggo_abi, ) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/0_LocalOrderHash.py b/examples/chain_client/0_LocalOrderHash.py index 1eef1af7..e25d695c 100644 --- a/examples/chain_client/0_LocalOrderHash.py +++ b/examples/chain_client/0_LocalOrderHash.py @@ -24,11 +24,7 @@ async def main() -> None: subaccount_id = address.get_subaccount_id(index=0) subaccount_id_2 = address.get_subaccount_id(index=1) - order_hash_manager = OrderHashManager( - address=address, - network=network, - subaccount_indexes=[0, 1, 2, 7] - ) + order_hash_manager = OrderHashManager(address=address, network=network, subaccount_indexes=[0, 1, 2, 7]) # prepare trade info spot_market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -43,7 +39,7 @@ async def main() -> None: price=0.524, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ), composer.SpotOrder( market_id=spot_market_id, @@ -52,7 +48,7 @@ async def main() -> None: price=27.92, quantity=0.01, is_buy=False, - is_po=False + is_po=False, ), ] @@ -65,7 +61,7 @@ async def main() -> None: quantity=0.01, leverage=1.5, is_buy=True, - is_po=False + is_po=False, ), composer.DerivativeOrder( market_id=deriv_market_id, @@ -75,20 +71,14 @@ async def main() -> None: quantity=0.01, leverage=2, is_buy=False, - is_reduce_only=False + is_reduce_only=False, ), ] # prepare tx msg - spot_msg = composer.MsgBatchCreateSpotLimitOrders( - sender=address.to_acc_bech32(), - orders=spot_orders - ) + spot_msg = composer.MsgBatchCreateSpotLimitOrders(sender=address.to_acc_bech32(), orders=spot_orders) - deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders( - sender=address.to_acc_bech32(), - orders=derivative_orders - ) + deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders(sender=address.to_acc_bech32(), orders=derivative_orders) # compute order hashes order_hashes = order_hash_manager.compute_order_hashes( @@ -109,12 +99,14 @@ async def main() -> None: gas_price = 500000000 base_gas = 85000 gas_limit = base_gas + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -144,12 +136,14 @@ async def main() -> None: gas_price = 500000000 base_gas = 85000 gas_limit = base_gas + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -168,7 +162,7 @@ async def main() -> None: price=1.524, quantity=0.01, is_buy=True, - is_po=True + is_po=True, ), composer.SpotOrder( market_id=spot_market_id, @@ -177,7 +171,7 @@ async def main() -> None: price=27.92, quantity=0.01, is_buy=False, - is_po=False + is_po=False, ), ] @@ -190,7 +184,7 @@ async def main() -> None: quantity=0.01, leverage=1.5, is_buy=True, - is_po=False + is_po=False, ), composer.DerivativeOrder( market_id=deriv_market_id, @@ -200,20 +194,14 @@ async def main() -> None: quantity=0.01, leverage=2, is_buy=False, - is_reduce_only=False + is_reduce_only=False, ), ] # prepare tx msg - spot_msg = composer.MsgBatchCreateSpotLimitOrders( - sender=address.to_acc_bech32(), - orders=spot_orders - ) + spot_msg = composer.MsgBatchCreateSpotLimitOrders(sender=address.to_acc_bech32(), orders=spot_orders) - deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders( - sender=address.to_acc_bech32(), - orders=derivative_orders - ) + deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders(sender=address.to_acc_bech32(), orders=derivative_orders) # compute order hashes order_hashes = order_hash_manager.compute_order_hashes( @@ -234,12 +222,14 @@ async def main() -> None: gas_price = 500000000 base_gas = 85000 gas_limit = base_gas + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -250,5 +240,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/13_MsgIncreasePositionMargin.py b/examples/chain_client/13_MsgIncreasePositionMargin.py index ddab6e91..a2556f78 100644 --- a/examples/chain_client/13_MsgIncreasePositionMargin.py +++ b/examples/chain_client/13_MsgIncreasePositionMargin.py @@ -31,7 +31,7 @@ async def main() -> None: market_id=market_id, source_subaccount_id=subaccount_id, destination_subaccount_id=subaccount_id, - amount=2 + amount=2, ) # build sim tx @@ -55,12 +55,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -71,5 +73,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/15_MsgWithdraw.py b/examples/chain_client/15_MsgWithdraw.py index a8d987e9..437d0037 100644 --- a/examples/chain_client/15_MsgWithdraw.py +++ b/examples/chain_client/15_MsgWithdraw.py @@ -37,12 +37,7 @@ async def main() -> None: subaccount_id = address.get_subaccount_id(index=0) # prepare tx msg - msg = composer.MsgWithdraw( - sender=address.to_acc_bech32(), - subaccount_id=subaccount_id, - amount=1, - denom="USDT" - ) + msg = composer.MsgWithdraw(sender=address.to_acc_bech32(), subaccount_id=subaccount_id, amount=1, denom="USDT") # build sim tx tx = ( @@ -65,12 +60,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -81,5 +78,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/16_MsgSubaccountTransfer.py b/examples/chain_client/16_MsgSubaccountTransfer.py index d97d112e..bc2e5baf 100644 --- a/examples/chain_client/16_MsgSubaccountTransfer.py +++ b/examples/chain_client/16_MsgSubaccountTransfer.py @@ -29,7 +29,7 @@ async def main() -> None: source_subaccount_id=subaccount_id, destination_subaccount_id=dest_subaccount_id, amount=100, - denom="INJ" + denom="INJ", ) # build sim tx @@ -53,12 +53,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -69,5 +71,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/17_MsgBatchUpdateOrders.py b/examples/chain_client/17_MsgBatchUpdateOrders.py index 1617e65b..3b3e7f77 100644 --- a/examples/chain_client/17_MsgBatchUpdateOrders.py +++ b/examples/chain_client/17_MsgBatchUpdateOrders.py @@ -37,26 +37,26 @@ async def main() -> None: composer.OrderData( market_id=derivative_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103" + order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103", ), composer.OrderData( market_id=derivative_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] spot_orders_to_cancel = [ composer.OrderData( market_id=spot_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d", ), composer.OrderData( market_id=spot_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" - ) + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", + ), ] derivative_orders_to_create = [ @@ -68,7 +68,7 @@ async def main() -> None: quantity=0.1, leverage=1, is_buy=True, - is_po=False + is_po=False, ), composer.DerivativeOrder( market_id=derivative_market_id_create, @@ -78,7 +78,7 @@ async def main() -> None: quantity=0.01, leverage=1, is_buy=False, - is_po=False + is_po=False, ), ] @@ -90,7 +90,7 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, ), composer.SpotOrder( market_id=spot_market_id_create, @@ -99,7 +99,7 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, ), ] @@ -109,7 +109,7 @@ async def main() -> None: derivative_orders_to_create=derivative_orders_to_create, spot_orders_to_create=spot_orders_to_create, derivative_orders_to_cancel=derivative_orders_to_cancel, - spot_orders_to_cancel=spot_orders_to_cancel + spot_orders_to_cancel=spot_orders_to_cancel, ) # build sim tx @@ -137,12 +137,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -154,5 +156,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/18_MsgBid.py b/examples/chain_client/18_MsgBid.py index a0a0cc60..5a23f172 100644 --- a/examples/chain_client/18_MsgBid.py +++ b/examples/chain_client/18_MsgBid.py @@ -22,11 +22,7 @@ async def main() -> None: await client.get_account(address.to_acc_bech32()) # prepare tx msg - msg = composer.MsgBid( - sender=address.to_acc_bech32(), - round=16250, - bid_amount=1 - ) + msg = composer.MsgBid(sender=address.to_acc_bech32(), round=16250, bid_amount=1) # build sim tx tx = ( @@ -49,12 +45,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -65,5 +63,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/19_MsgGrant.py b/examples/chain_client/19_MsgGrant.py index 2dc6a88b..548af1a5 100644 --- a/examples/chain_client/19_MsgGrant.py +++ b/examples/chain_client/19_MsgGrant.py @@ -30,7 +30,7 @@ async def main() -> None: granter="inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", grantee="inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", msg_type="/injective.exchange.v1beta1.MsgCreateSpotLimitOrder", - expire_in=31536000 # 1 year + expire_in=31536000, # 1 year ) # TYPED AUTHZ @@ -64,12 +64,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) diff --git a/examples/chain_client/1_MsgSend.py b/examples/chain_client/1_MsgSend.py index 390349fc..1d3c28a6 100644 --- a/examples/chain_client/1_MsgSend.py +++ b/examples/chain_client/1_MsgSend.py @@ -24,9 +24,9 @@ async def main() -> None: # prepare tx msg msg = composer.MsgSend( from_address=address.to_acc_bech32(), - to_address='inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r', + to_address="inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", amount=0.000000000000000001, - denom='INJ' + denom="INJ", ) # build sim tx @@ -50,12 +50,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -66,5 +68,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/20_MsgExec.py b/examples/chain_client/20_MsgExec.py index 52dae6f7..c940523c 100644 --- a/examples/chain_client/20_MsgExec.py +++ b/examples/chain_client/20_MsgExec.py @@ -35,13 +35,10 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ) - msg = composer.MsgExec( - grantee=grantee, - msgs=[msg0] - ) + msg = composer.MsgExec(grantee=grantee, msgs=[msg0]) # build sim tx tx = ( @@ -63,22 +60,21 @@ async def main() -> None: sim_res_msg = composer.MsgResponses(sim_res, simulation=True) data = sim_res_msg[0] - unpacked_msg_res = composer.UnpackMsgExecResponse( - msg_type=msg0.__class__.__name__, - data=data - ) + unpacked_msg_res = composer.UnpackMsgExecResponse(msg_type=msg0.__class__.__name__, data=data) print("simulation msg response") print(unpacked_msg_res) # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -89,5 +85,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/21_MsgRevoke.py b/examples/chain_client/21_MsgRevoke.py index 2e10e52b..7c040810 100644 --- a/examples/chain_client/21_MsgRevoke.py +++ b/examples/chain_client/21_MsgRevoke.py @@ -25,7 +25,7 @@ async def main() -> None: msg = composer.MsgRevoke( granter="inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", grantee="inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", - msg_type="/injective.exchange.v1beta1.MsgCreateSpotLimitOrder" + msg_type="/injective.exchange.v1beta1.MsgCreateSpotLimitOrder", ) # build sim tx @@ -49,12 +49,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -65,5 +67,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/22_MsgSendToEth.py b/examples/chain_client/22_MsgSendToEth.py index d4ee9e97..96f6e435 100644 --- a/examples/chain_client/22_MsgSendToEth.py +++ b/examples/chain_client/22_MsgSendToEth.py @@ -36,7 +36,7 @@ async def main() -> None: denom="INJ", eth_dest="0xaf79152ac5df276d9a8e1e2e22822f9713474902", amount=23, - bridge_fee=bridge_fee + bridge_fee=bridge_fee, ) # build sim tx @@ -60,12 +60,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -76,5 +78,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/23_MsgRelayPriceFeedPrice.py b/examples/chain_client/23_MsgRelayPriceFeedPrice.py index c7b742fd..f55c8c72 100644 --- a/examples/chain_client/23_MsgRelayPriceFeedPrice.py +++ b/examples/chain_client/23_MsgRelayPriceFeedPrice.py @@ -22,17 +22,12 @@ async def main() -> None: await client.get_account(address.to_acc_bech32()) price = 100 - price_to_send = [str(int(price * 10 ** 18))] + price_to_send = [str(int(price * 10**18))] base = ["BAYC"] quote = ["WETH"] # prepare tx msg - msg = composer.MsgRelayPriceFeedPrice( - sender=address.to_acc_bech32(), - price=price_to_send, - base=base, - quote=quote - ) + msg = composer.MsgRelayPriceFeedPrice(sender=address.to_acc_bech32(), price=price_to_send, base=base, quote=quote) # build sim tx tx = ( @@ -55,12 +50,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -71,5 +68,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/24_MsgRewardsOptOut.py b/examples/chain_client/24_MsgRewardsOptOut.py index 55e02103..abf63829 100644 --- a/examples/chain_client/24_MsgRewardsOptOut.py +++ b/examples/chain_client/24_MsgRewardsOptOut.py @@ -22,9 +22,7 @@ async def main() -> None: await client.get_account(address.to_acc_bech32()) # prepare tx msg - msg = composer.MsgRewardsOptOut( - sender=address.to_acc_bech32() - ) + msg = composer.MsgRewardsOptOut(sender=address.to_acc_bech32()) # build sim tx tx = ( @@ -47,12 +45,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -63,5 +63,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/25_MsgDelegate.py b/examples/chain_client/25_MsgDelegate.py index 6d432c4c..9243b6d4 100644 --- a/examples/chain_client/25_MsgDelegate.py +++ b/examples/chain_client/25_MsgDelegate.py @@ -26,9 +26,7 @@ async def main() -> None: amount = 100 msg = composer.MsgDelegate( - delegator_address=address.to_acc_bech32(), - validator_address=validator_address, - amount=amount + delegator_address=address.to_acc_bech32(), validator_address=validator_address, amount=amount ) # build sim tx @@ -52,12 +50,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -68,5 +68,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/26_MsgWithdrawDelegatorReward.py b/examples/chain_client/26_MsgWithdrawDelegatorReward.py index 9eb8e636..61b9fbef 100644 --- a/examples/chain_client/26_MsgWithdrawDelegatorReward.py +++ b/examples/chain_client/26_MsgWithdrawDelegatorReward.py @@ -25,8 +25,7 @@ async def main() -> None: validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" msg = composer.MsgWithdrawDelegatorReward( - delegator_address=address.to_acc_bech32(), - validator_address=validator_address + delegator_address=address.to_acc_bech32(), validator_address=validator_address ) # build sim tx @@ -50,12 +49,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -66,5 +67,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/27_Grants.py b/examples/chain_client/27_Grants.py index 8a63c6d1..dca8ea42 100644 --- a/examples/chain_client/27_Grants.py +++ b/examples/chain_client/27_Grants.py @@ -13,5 +13,6 @@ async def main() -> None: authorizations = await client.get_grants(granter=granter, grantee=grantee, msg_type_url=msg_type_url) print(authorizations) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/28_BankBalances.py b/examples/chain_client/28_BankBalances.py index ba9864ac..4e6ec895 100644 --- a/examples/chain_client/28_BankBalances.py +++ b/examples/chain_client/28_BankBalances.py @@ -11,5 +11,6 @@ async def main() -> None: all_bank_balances = await client.get_bank_balances(address=address) print(all_bank_balances) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/29_BankBalance.py b/examples/chain_client/29_BankBalance.py index e9a3907e..959d1c72 100644 --- a/examples/chain_client/29_BankBalance.py +++ b/examples/chain_client/29_BankBalance.py @@ -12,5 +12,6 @@ async def main() -> None: bank_balance = await client.get_bank_balance(address=address, denom=denom) print(bank_balance) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/2_MsgDeposit.py b/examples/chain_client/2_MsgDeposit.py index 0d5c5754..13febc04 100644 --- a/examples/chain_client/2_MsgDeposit.py +++ b/examples/chain_client/2_MsgDeposit.py @@ -23,12 +23,7 @@ async def main() -> None: subaccount_id = address.get_subaccount_id(index=0) # prepare tx msg - msg = composer.MsgDeposit( - sender=address.to_acc_bech32(), - subaccount_id=subaccount_id, - amount=0.000001, - denom='INJ' - ) + msg = composer.MsgDeposit(sender=address.to_acc_bech32(), subaccount_id=subaccount_id, amount=0.000001, denom="INJ") # build sim tx tx = ( @@ -51,12 +46,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -67,5 +64,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/30_ExternalTransfer.py b/examples/chain_client/30_ExternalTransfer.py index 7661e7f7..c5dbcc53 100644 --- a/examples/chain_client/30_ExternalTransfer.py +++ b/examples/chain_client/30_ExternalTransfer.py @@ -29,7 +29,7 @@ async def main() -> None: source_subaccount_id=subaccount_id, destination_subaccount_id=dest_subaccount_id, amount=100, - denom="INJ" + denom="INJ", ) # build sim tx @@ -53,12 +53,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -69,5 +71,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/31_MsgCreateBinaryOptionsLimitOrder.py b/examples/chain_client/31_MsgCreateBinaryOptionsLimitOrder.py index 8e94abf4..fb2a9d24 100644 --- a/examples/chain_client/31_MsgCreateBinaryOptionsLimitOrder.py +++ b/examples/chain_client/31_MsgCreateBinaryOptionsLimitOrder.py @@ -28,8 +28,7 @@ async def main() -> None: fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" # set custom denom to bypass ini file load (optional) - denom = Denom(description="desc", base=0, quote=6, - min_price_tick_size=1000, min_quantity_tick_size=0.0001) + denom = Denom(description="desc", base=0, quote=6, min_price_tick_size=1000, min_quantity_tick_size=0.0001) # prepare tx msg msg = composer.MsgCreateBinaryOptionsLimitOrder( @@ -41,7 +40,7 @@ async def main() -> None: quantity=1, is_buy=False, is_reduce_only=False, - denom=denom + denom=denom, ) # build sim tx @@ -69,12 +68,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -86,5 +87,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/32_MsgCreateBinaryOptionsMarketOrder.py b/examples/chain_client/32_MsgCreateBinaryOptionsMarketOrder.py index dadbdb6c..2408b865 100644 --- a/examples/chain_client/32_MsgCreateBinaryOptionsMarketOrder.py +++ b/examples/chain_client/32_MsgCreateBinaryOptionsMarketOrder.py @@ -35,7 +35,7 @@ async def main() -> None: price=0.5, quantity=1, is_buy=True, - is_reduce_only=False + is_reduce_only=False, ) # build sim tx tx = ( @@ -62,12 +62,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -79,5 +81,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/33_MsgCancelBinaryOptionsOrder.py b/examples/chain_client/33_MsgCancelBinaryOptionsOrder.py index 7a4a4cdf..9daaf419 100644 --- a/examples/chain_client/33_MsgCancelBinaryOptionsOrder.py +++ b/examples/chain_client/33_MsgCancelBinaryOptionsOrder.py @@ -28,10 +28,7 @@ async def main() -> None: # prepare tx msg msg = composer.MsgCancelBinaryOptionsOrder( - sender=address.to_acc_bech32(), - market_id=market_id, - subaccount_id=subaccount_id, - order_hash=order_hash + sender=address.to_acc_bech32(), market_id=market_id, subaccount_id=subaccount_id, order_hash=order_hash ) # build sim tx tx = ( @@ -58,12 +55,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -75,5 +74,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/34_MsgAdminUpdateBinaryOptionsMarket.py b/examples/chain_client/34_MsgAdminUpdateBinaryOptionsMarket.py index f155dcbb..da3966e0 100644 --- a/examples/chain_client/34_MsgAdminUpdateBinaryOptionsMarket.py +++ b/examples/chain_client/34_MsgAdminUpdateBinaryOptionsMarket.py @@ -35,7 +35,7 @@ async def main() -> None: settlement_price=settlement_price, expiration_timestamp=expiration_timestamp, settlement_timestamp=settlement_timestamp, - status=status + status=status, ) # build sim tx @@ -63,12 +63,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -80,5 +82,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/35_MsgInstantBinaryOptionsMarketLaunch.py b/examples/chain_client/35_MsgInstantBinaryOptionsMarketLaunch.py index 91b59392..1116a669 100644 --- a/examples/chain_client/35_MsgInstantBinaryOptionsMarketLaunch.py +++ b/examples/chain_client/35_MsgInstantBinaryOptionsMarketLaunch.py @@ -37,7 +37,7 @@ async def main() -> None: expiration_timestamp=1680730982, settlement_timestamp=1690730982, min_price_tick_size=0.01, - min_quantity_tick_size=0.01 + min_quantity_tick_size=0.01, ) # build sim tx @@ -65,12 +65,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -82,5 +84,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/36_MsgRelayProviderPrices.py b/examples/chain_client/36_MsgRelayProviderPrices.py index 374d6c50..2068c572 100644 --- a/examples/chain_client/36_MsgRelayProviderPrices.py +++ b/examples/chain_client/36_MsgRelayProviderPrices.py @@ -27,10 +27,7 @@ async def main() -> None: # prepare tx msg msg = composer.MsgRelayProviderPrices( - sender=address.to_acc_bech32(), - provider=provider, - symbols=symbols, - prices=prices + sender=address.to_acc_bech32(), provider=provider, symbols=symbols, prices=prices ) # build sim tx @@ -58,12 +55,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -75,5 +74,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/37_GetTx.py b/examples/chain_client/37_GetTx.py index 2ee14f19..ece40b65 100644 --- a/examples/chain_client/37_GetTx.py +++ b/examples/chain_client/37_GetTx.py @@ -11,5 +11,6 @@ async def main() -> None: tx_logs = await client.get_tx(tx_hash=tx_hash) print(tx_logs) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/38_StreamEventOrderFail.py b/examples/chain_client/38_StreamEventOrderFail.py index dc767268..62aed601 100644 --- a/examples/chain_client/38_StreamEventOrderFail.py +++ b/examples/chain_client/38_StreamEventOrderFail.py @@ -9,17 +9,19 @@ async def main() -> None: network = Network.mainnet() - event_filter = ("tm.event='Tx' AND message.sender='inj1rwv4zn3jptsqs7l8lpa3uvzhs57y8duemete9e' " - "AND message.action='/injective.exchange.v1beta1.MsgBatchUpdateOrders' " - "AND injective.exchange.v1beta1.EventOrderFail.flags EXISTS") - query = json.dumps({ - "jsonrpc": "2.0", - "method": "subscribe", - "id": "0", - "params": { - "query": event_filter - }, - }) + event_filter = ( + "tm.event='Tx' AND message.sender='inj1rwv4zn3jptsqs7l8lpa3uvzhs57y8duemete9e' " + "AND message.action='/injective.exchange.v1beta1.MsgBatchUpdateOrders' " + "AND injective.exchange.v1beta1.EventOrderFail.flags EXISTS" + ) + query = json.dumps( + { + "jsonrpc": "2.0", + "method": "subscribe", + "id": "0", + "params": {"query": event_filter}, + } + ) async with websockets.connect(network.tm_websocket_endpoint) as ws: await ws.send(query) @@ -40,5 +42,6 @@ async def main() -> None: print(dict) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/39_Account.py b/examples/chain_client/39_Account.py index c7b76e2a..43692ba2 100644 --- a/examples/chain_client/39_Account.py +++ b/examples/chain_client/39_Account.py @@ -11,5 +11,6 @@ async def main() -> None: acc = await client.get_account(address=address) print(acc) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/3_MsgCreateSpotLimitOrder.py b/examples/chain_client/3_MsgCreateSpotLimitOrder.py index ca48b45c..a480e817 100644 --- a/examples/chain_client/3_MsgCreateSpotLimitOrder.py +++ b/examples/chain_client/3_MsgCreateSpotLimitOrder.py @@ -35,7 +35,7 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ) # build sim tx @@ -63,12 +63,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -80,5 +82,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/40_MsgExecuteContract.py b/examples/chain_client/40_MsgExecuteContract.py index 387d152e..3d92b825 100644 --- a/examples/chain_client/40_MsgExecuteContract.py +++ b/examples/chain_client/40_MsgExecuteContract.py @@ -27,16 +27,16 @@ async def main() -> None: funds = [ composer.Coin( amount=69, - denom='factory/inj1hdvy6tl89llqy3ze8lv6mz5qh66sx9enn0jxg6/inj12ngevx045zpvacus9s6anr258gkwpmthnz80e9' + denom="factory/inj1hdvy6tl89llqy3ze8lv6mz5qh66sx9enn0jxg6/inj12ngevx045zpvacus9s6anr258gkwpmthnz80e9", ), - composer.Coin(amount=420, denom='peggy0x44C21afAaF20c270EBbF5914Cfc3b5022173FEB7'), - composer.Coin(amount=1, denom='peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5'), + composer.Coin(amount=420, denom="peggy0x44C21afAaF20c270EBbF5914Cfc3b5022173FEB7"), + composer.Coin(amount=1, denom="peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5"), ] msg = composer.MsgExecuteContract( sender=address.to_acc_bech32(), contract="inj1ady3s7whq30l4fx8sj3x6muv5mx4dfdlcpv8n7", msg='{"increment":{}}', - funds=funds + funds=funds, ) # build sim tx @@ -60,12 +60,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -76,5 +78,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/41_MsgCreateInsuranceFund.py b/examples/chain_client/41_MsgCreateInsuranceFund.py index 7afdee76..86f7b0b6 100644 --- a/examples/chain_client/41_MsgCreateInsuranceFund.py +++ b/examples/chain_client/41_MsgCreateInsuranceFund.py @@ -30,7 +30,7 @@ async def main() -> None: oracle_quote="Frontrunner", oracle_type=11, expiry=-2, - initial_deposit=1000 + initial_deposit=1000, ) # build sim tx @@ -54,12 +54,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -70,5 +72,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/42_MsgUnderwrite.py b/examples/chain_client/42_MsgUnderwrite.py index 11c4443c..087aae33 100644 --- a/examples/chain_client/42_MsgUnderwrite.py +++ b/examples/chain_client/42_MsgUnderwrite.py @@ -26,7 +26,7 @@ async def main() -> None: sender=address.to_acc_bech32(), market_id="0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74", quote_denom="USDT", - amount=100 + amount=100, ) # build sim tx @@ -50,12 +50,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -66,5 +68,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/43_MsgRequestRedemption.py b/examples/chain_client/43_MsgRequestRedemption.py index 801bedcd..7379f055 100644 --- a/examples/chain_client/43_MsgRequestRedemption.py +++ b/examples/chain_client/43_MsgRequestRedemption.py @@ -26,7 +26,7 @@ async def main() -> None: sender=address.to_acc_bech32(), market_id="0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74", share_denom="share15", - amount=100 # raw chain value + amount=100, # raw chain value ) # build sim tx @@ -50,12 +50,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -66,5 +68,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/44_MessageBroadcaster.py b/examples/chain_client/44_MessageBroadcaster.py index 4fbeb719..6b948578 100644 --- a/examples/chain_client/44_MessageBroadcaster.py +++ b/examples/chain_client/44_MessageBroadcaster.py @@ -35,7 +35,7 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, ), composer.SpotOrder( market_id=spot_market_id_create, @@ -44,7 +44,7 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, ), ] @@ -59,5 +59,6 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/45_MessageBroadcasterWithGranteeAccount.py b/examples/chain_client/45_MessageBroadcasterWithGranteeAccount.py index 61b9ebd3..860b91e0 100644 --- a/examples/chain_client/45_MessageBroadcasterWithGranteeAccount.py +++ b/examples/chain_client/45_MessageBroadcasterWithGranteeAccount.py @@ -41,7 +41,7 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ) # broadcast the transaction @@ -49,5 +49,6 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/46_MessageBroadcasterWithoutSimulation.py b/examples/chain_client/46_MessageBroadcasterWithoutSimulation.py index dc804b24..1aa19990 100644 --- a/examples/chain_client/46_MessageBroadcasterWithoutSimulation.py +++ b/examples/chain_client/46_MessageBroadcasterWithoutSimulation.py @@ -35,7 +35,7 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, ), composer.SpotOrder( market_id=spot_market_id_create, @@ -44,7 +44,7 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, ), ] @@ -59,5 +59,6 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/47_MessageBroadcasterWithGranteeAccountWithoutSimulation.py b/examples/chain_client/47_MessageBroadcasterWithGranteeAccountWithoutSimulation.py index 5539c112..ccb41de5 100644 --- a/examples/chain_client/47_MessageBroadcasterWithGranteeAccountWithoutSimulation.py +++ b/examples/chain_client/47_MessageBroadcasterWithGranteeAccountWithoutSimulation.py @@ -41,7 +41,7 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ) # broadcast the transaction @@ -49,5 +49,6 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/48_WithdrawValidatorCommissionAndRewards.py b/examples/chain_client/48_WithdrawValidatorCommissionAndRewards.py index 1a05868f..4ab89394 100644 --- a/examples/chain_client/48_WithdrawValidatorCommissionAndRewards.py +++ b/examples/chain_client/48_WithdrawValidatorCommissionAndRewards.py @@ -1,4 +1,3 @@ - import asyncio from pyinjective.async_client import AsyncClient @@ -29,13 +28,10 @@ async def main() -> None: validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" msg0 = composer.MsgWithdrawDelegatorReward( - delegator_address=address.to_acc_bech32(), - validator_address=validator_address + delegator_address=address.to_acc_bech32(), validator_address=validator_address ) - msg1 = composer.MsgWithdrawValidatorCommission( - validator_address=validator_address - ) + msg1 = composer.MsgWithdrawValidatorCommission(validator_address=validator_address) # build sim tx tx = ( @@ -58,12 +54,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -74,5 +72,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/4_MsgCreateSpotMarketOrder.py b/examples/chain_client/4_MsgCreateSpotMarketOrder.py index c93d1cf5..293b5145 100644 --- a/examples/chain_client/4_MsgCreateSpotMarketOrder.py +++ b/examples/chain_client/4_MsgCreateSpotMarketOrder.py @@ -34,7 +34,7 @@ async def main() -> None: fee_recipient=fee_recipient, price=10.522, quantity=0.01, - is_buy=True + is_buy=True, ) # build sim tx @@ -62,12 +62,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -79,5 +81,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/5_MsgCancelSpotOrder.py b/examples/chain_client/5_MsgCancelSpotOrder.py index ee6ca060..f94638bd 100644 --- a/examples/chain_client/5_MsgCancelSpotOrder.py +++ b/examples/chain_client/5_MsgCancelSpotOrder.py @@ -28,10 +28,7 @@ async def main() -> None: # prepare tx msg msg = composer.MsgCancelSpotOrder( - sender=address.to_acc_bech32(), - market_id=market_id, - subaccount_id=subaccount_id, - order_hash=order_hash + sender=address.to_acc_bech32(), market_id=market_id, subaccount_id=subaccount_id, order_hash=order_hash ) # build sim tx @@ -55,12 +52,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -71,5 +70,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/6_MsgCreateDerivativeLimitOrder.py b/examples/chain_client/6_MsgCreateDerivativeLimitOrder.py index f5b8e28b..865400b4 100644 --- a/examples/chain_client/6_MsgCreateDerivativeLimitOrder.py +++ b/examples/chain_client/6_MsgCreateDerivativeLimitOrder.py @@ -36,7 +36,7 @@ async def main() -> None: quantity=0.1, leverage=1, is_buy=False, - is_reduce_only=False + is_reduce_only=False, ) # build sim tx @@ -64,12 +64,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -81,5 +83,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/7_MsgCreateDerivativeMarketOrder.py b/examples/chain_client/7_MsgCreateDerivativeMarketOrder.py index dd8da09e..db69d7c1 100644 --- a/examples/chain_client/7_MsgCreateDerivativeMarketOrder.py +++ b/examples/chain_client/7_MsgCreateDerivativeMarketOrder.py @@ -35,7 +35,7 @@ async def main() -> None: price=50000, quantity=0.01, leverage=3, - is_buy=True + is_buy=True, ) # build sim tx @@ -63,12 +63,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -80,5 +82,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/8_MsgCancelDerivativeOrder.py b/examples/chain_client/8_MsgCancelDerivativeOrder.py index 61fd1d82..f2cda909 100644 --- a/examples/chain_client/8_MsgCancelDerivativeOrder.py +++ b/examples/chain_client/8_MsgCancelDerivativeOrder.py @@ -28,10 +28,7 @@ async def main() -> None: # prepare tx msg msg = composer.MsgCancelDerivativeOrder( - sender=address.to_acc_bech32(), - market_id=market_id, - subaccount_id=subaccount_id, - order_hash=order_hash + sender=address.to_acc_bech32(), market_id=market_id, subaccount_id=subaccount_id, order_hash=order_hash ) # build sim tx @@ -55,12 +52,14 @@ async def main() -> None: # build tx gas_price = 500000000 gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_fee = "{:.18f}".format((gas_price * gas_limit) / pow(10, 18)).rstrip("0") + fee = [ + composer.Coin( + amount=gas_price * gas_limit, + denom=network.fee_denom, + ) + ] + tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(client.timeout_height) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -71,5 +70,6 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/1_StreamSubaccountBalance.py b/examples/exchange_client/accounts_rpc/1_StreamSubaccountBalance.py index 33973715..9a0364eb 100644 --- a/examples/exchange_client/accounts_rpc/1_StreamSubaccountBalance.py +++ b/examples/exchange_client/accounts_rpc/1_StreamSubaccountBalance.py @@ -9,13 +9,11 @@ async def main() -> None: client = AsyncClient(network) subaccount_id = "0xc7dca7c15c364865f77a4fb67ab11dc95502e6fe000000000000000000000001" denoms = ["inj", "peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5"] - subaccount = await client.stream_subaccount_balance( - subaccount_id=subaccount_id, - denoms=denoms - ) + subaccount = await client.stream_subaccount_balance(subaccount_id=subaccount_id, denoms=denoms) async for balance in subaccount: print("Subaccount balance Update:\n") print(balance) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/2_SubaccountBalance.py b/examples/exchange_client/accounts_rpc/2_SubaccountBalance.py index d9a5f424..dd48b9f3 100644 --- a/examples/exchange_client/accounts_rpc/2_SubaccountBalance.py +++ b/examples/exchange_client/accounts_rpc/2_SubaccountBalance.py @@ -9,11 +9,9 @@ async def main() -> None: client = AsyncClient(network) subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000" denom = "inj" - balance = await client.get_subaccount_balance( - subaccount_id=subaccount_id, - denom=denom - ) + balance = await client.get_subaccount_balance(subaccount_id=subaccount_id, denom=denom) print(balance) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/3_SubaccountsList.py b/examples/exchange_client/accounts_rpc/3_SubaccountsList.py index 835f20e5..af523e2d 100644 --- a/examples/exchange_client/accounts_rpc/3_SubaccountsList.py +++ b/examples/exchange_client/accounts_rpc/3_SubaccountsList.py @@ -11,5 +11,6 @@ async def main() -> None: subacc_list = await client.get_subaccount_list(account_address) print(subacc_list) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/4_SubaccountBalancesList.py b/examples/exchange_client/accounts_rpc/4_SubaccountBalancesList.py index 0cbe952c..501d327e 100644 --- a/examples/exchange_client/accounts_rpc/4_SubaccountBalancesList.py +++ b/examples/exchange_client/accounts_rpc/4_SubaccountBalancesList.py @@ -9,11 +9,9 @@ async def main() -> None: client = AsyncClient(network) subaccount = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000" denoms = ["inj", "peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5"] - subacc_balances_list = await client.get_subaccount_balances_list( - subaccount_id=subaccount, - denoms=denoms - ) + subacc_balances_list = await client.get_subaccount_balances_list(subaccount_id=subaccount, denoms=denoms) print(subacc_balances_list) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/5_SubaccountHistory.py b/examples/exchange_client/accounts_rpc/5_SubaccountHistory.py index 2aa8ea4e..e67d2ab6 100644 --- a/examples/exchange_client/accounts_rpc/5_SubaccountHistory.py +++ b/examples/exchange_client/accounts_rpc/5_SubaccountHistory.py @@ -14,14 +14,10 @@ async def main() -> None: limit = 15 end_time = 1665118340224 subacc_history = await client.get_subaccount_history( - subaccount_id=subaccount, - denom=denom, - transfer_types=transfer_types, - skip=skip, - limit=limit, - end_time=end_time + subaccount_id=subaccount, denom=denom, transfer_types=transfer_types, skip=skip, limit=limit, end_time=end_time ) print(subacc_history) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/6_SubaccountOrderSummary.py b/examples/exchange_client/accounts_rpc/6_SubaccountOrderSummary.py index a6db421f..9026e4e1 100644 --- a/examples/exchange_client/accounts_rpc/6_SubaccountOrderSummary.py +++ b/examples/exchange_client/accounts_rpc/6_SubaccountOrderSummary.py @@ -11,11 +11,10 @@ async def main() -> None: order_direction = "buy" market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" subacc_order_summary = await client.get_subaccount_order_summary( - subaccount_id=subaccount, - order_direction=order_direction, - market_id=market_id + subaccount_id=subaccount, order_direction=order_direction, market_id=market_id ) print(subacc_order_summary) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/7_OrderStates.py b/examples/exchange_client/accounts_rpc/7_OrderStates.py index 1da25533..e78dc842 100644 --- a/examples/exchange_client/accounts_rpc/7_OrderStates.py +++ b/examples/exchange_client/accounts_rpc/7_OrderStates.py @@ -9,16 +9,17 @@ async def main() -> None: client = AsyncClient(network) spot_order_hashes = [ "0xce0d9b701f77cd6ddfda5dd3a4fe7b2d53ba83e5d6c054fb2e9e886200b7b7bb", - "0x2e2245b5431638d76c6e0cc6268970418a1b1b7df60a8e94b8cf37eae6105542" + "0x2e2245b5431638d76c6e0cc6268970418a1b1b7df60a8e94b8cf37eae6105542", ] derivative_order_hashes = [ "0x82113f3998999bdc3892feaab2c4e53ba06c5fe887a2d5f9763397240f24da50", - "0xbb1f036001378cecb5fff1cc69303919985b5bf058c32f37d5aaf9b804c07a06" + "0xbb1f036001378cecb5fff1cc69303919985b5bf058c32f37d5aaf9b804c07a06", ] orders = await client.get_order_states( spot_order_hashes=spot_order_hashes, derivative_order_hashes=derivative_order_hashes ) print(orders) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/8_Portfolio.py b/examples/exchange_client/accounts_rpc/8_Portfolio.py index c074c2a9..0a922054 100644 --- a/examples/exchange_client/accounts_rpc/8_Portfolio.py +++ b/examples/exchange_client/accounts_rpc/8_Portfolio.py @@ -11,5 +11,6 @@ async def main() -> None: portfolio = await client.get_portfolio(account_address=account_address) print(portfolio) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/accounts_rpc/9_Rewards.py b/examples/exchange_client/accounts_rpc/9_Rewards.py index f96f0882..b3a486cf 100644 --- a/examples/exchange_client/accounts_rpc/9_Rewards.py +++ b/examples/exchange_client/accounts_rpc/9_Rewards.py @@ -11,8 +11,10 @@ async def main() -> None: epoch = -1 rewards = await client.get_rewards( # account_address=account_address, - epoch=epoch) + epoch=epoch + ) print(rewards) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/auctions_rpc/1_Auction.py b/examples/exchange_client/auctions_rpc/1_Auction.py index 8a813b51..94f73e16 100644 --- a/examples/exchange_client/auctions_rpc/1_Auction.py +++ b/examples/exchange_client/auctions_rpc/1_Auction.py @@ -12,5 +12,6 @@ async def main() -> None: auction = await client.get_auction(bid_round=bid_round) print(auction) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/auctions_rpc/2_Auctions.py b/examples/exchange_client/auctions_rpc/2_Auctions.py index 1bc0f8dc..30576a89 100644 --- a/examples/exchange_client/auctions_rpc/2_Auctions.py +++ b/examples/exchange_client/auctions_rpc/2_Auctions.py @@ -11,5 +11,6 @@ async def main() -> None: auctions = await client.get_auctions() print(auctions) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/auctions_rpc/3_StreamBids.py b/examples/exchange_client/auctions_rpc/3_StreamBids.py index 4540fa09..8306becb 100644 --- a/examples/exchange_client/auctions_rpc/3_StreamBids.py +++ b/examples/exchange_client/auctions_rpc/3_StreamBids.py @@ -12,5 +12,6 @@ async def main() -> None: async for bid in bids: print(bid) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/10_StreamHistoricalOrders.py b/examples/exchange_client/derivative_exchange_rpc/10_StreamHistoricalOrders.py index 2b962102..b58448d2 100644 --- a/examples/exchange_client/derivative_exchange_rpc/10_StreamHistoricalOrders.py +++ b/examples/exchange_client/derivative_exchange_rpc/10_StreamHistoricalOrders.py @@ -9,11 +9,10 @@ async def main() -> None: network = Network.testnet() client = AsyncClient(network) market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" - orders = await client.stream_historical_derivative_orders( - market_id=market_id - ) + orders = await client.stream_historical_derivative_orders(market_id=market_id) async for order in orders: print(order) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/11_Trades.py b/examples/exchange_client/derivative_exchange_rpc/11_Trades.py index 72dee870..5ae822a9 100644 --- a/examples/exchange_client/derivative_exchange_rpc/11_Trades.py +++ b/examples/exchange_client/derivative_exchange_rpc/11_Trades.py @@ -10,11 +10,9 @@ async def main() -> None: client = AsyncClient(network) market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000" - trades = await client.get_derivative_trades( - market_id=market_id, - subaccount_id=subaccount_id - ) + trades = await client.get_derivative_trades(market_id=market_id, subaccount_id=subaccount_id) print(trades) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/12_StreamTrades.py b/examples/exchange_client/derivative_exchange_rpc/12_StreamTrades.py index 0eb0d259..8d6246bb 100644 --- a/examples/exchange_client/derivative_exchange_rpc/12_StreamTrades.py +++ b/examples/exchange_client/derivative_exchange_rpc/12_StreamTrades.py @@ -10,15 +10,13 @@ async def main() -> None: client = AsyncClient(network) market_ids = [ "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6", - "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff" + "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff", ] subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000" - trades = await client.stream_derivative_trades( - market_id=market_ids[0], - subaccount_id=subaccount_id - ) + trades = await client.stream_derivative_trades(market_id=market_ids[0], subaccount_id=subaccount_id) async for trade in trades: print(trade) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/13_SubaccountOrdersList.py b/examples/exchange_client/derivative_exchange_rpc/13_SubaccountOrdersList.py index c12425e5..a7f06db7 100644 --- a/examples/exchange_client/derivative_exchange_rpc/13_SubaccountOrdersList.py +++ b/examples/exchange_client/derivative_exchange_rpc/13_SubaccountOrdersList.py @@ -13,13 +13,10 @@ async def main() -> None: skip = 1 limit = 2 orders = await client.get_derivative_subaccount_orders( - subaccount_id=subaccount_id, - market_id=market_id, - skip=skip, - limit=limit + subaccount_id=subaccount_id, market_id=market_id, skip=skip, limit=limit ) print(orders) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/14_SubaccountTradesList.py b/examples/exchange_client/derivative_exchange_rpc/14_SubaccountTradesList.py index f89eb7fa..4cd55f06 100644 --- a/examples/exchange_client/derivative_exchange_rpc/14_SubaccountTradesList.py +++ b/examples/exchange_client/derivative_exchange_rpc/14_SubaccountTradesList.py @@ -20,10 +20,10 @@ async def main() -> None: execution_type=execution_type, direction=direction, skip=skip, - limit=limit + limit=limit, ) print(trades) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/15_FundingPayments.py b/examples/exchange_client/derivative_exchange_rpc/15_FundingPayments.py index 8cc637a0..8f352c9e 100644 --- a/examples/exchange_client/derivative_exchange_rpc/15_FundingPayments.py +++ b/examples/exchange_client/derivative_exchange_rpc/15_FundingPayments.py @@ -14,13 +14,10 @@ async def main() -> None: limit = 3 end_time = 1676426400125 funding = await client.get_funding_payments( - market_id=market_id, - subaccount_id=subaccount_id, - skip=skip, - limit=limit, - end_time=end_time + market_id=market_id, subaccount_id=subaccount_id, skip=skip, limit=limit, end_time=end_time ) print(funding) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/17_FundingRates.py b/examples/exchange_client/derivative_exchange_rpc/17_FundingRates.py index c00a35b9..2a8cbcd1 100644 --- a/examples/exchange_client/derivative_exchange_rpc/17_FundingRates.py +++ b/examples/exchange_client/derivative_exchange_rpc/17_FundingRates.py @@ -12,13 +12,9 @@ async def main() -> None: skip = 0 limit = 3 end_time = 1675717201465 - funding_rates = await client.get_funding_rates( - market_id=market_id, - skip=skip, - limit=limit, - end_time=end_time - ) + funding_rates = await client.get_funding_rates(market_id=market_id, skip=skip, limit=limit, end_time=end_time) print(funding_rates) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/18_Orderbooks.py b/examples/exchange_client/derivative_exchange_rpc/18_Orderbooks.py index 2709814e..49b00e02 100644 --- a/examples/exchange_client/derivative_exchange_rpc/18_Orderbooks.py +++ b/examples/exchange_client/derivative_exchange_rpc/18_Orderbooks.py @@ -10,10 +10,11 @@ async def main() -> None: client = AsyncClient(network) market_ids = [ "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6", - "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff" + "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff", ] markets = await client.get_derivative_orderbooks(market_ids=market_ids) print(markets) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/19_Binary_Options_Markets.py b/examples/exchange_client/derivative_exchange_rpc/19_Binary_Options_Markets.py index 773b363c..9ed36e38 100644 --- a/examples/exchange_client/derivative_exchange_rpc/19_Binary_Options_Markets.py +++ b/examples/exchange_client/derivative_exchange_rpc/19_Binary_Options_Markets.py @@ -9,12 +9,10 @@ async def main() -> None: client = AsyncClient(network) market_status = "active" quote_denom = "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7" - market = await client.get_binary_options_markets( - market_status=market_status, - quote_denom=quote_denom - ) + market = await client.get_binary_options_markets(market_status=market_status, quote_denom=quote_denom) print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/1_Market.py b/examples/exchange_client/derivative_exchange_rpc/1_Market.py index 52a75e98..f0cdf499 100644 --- a/examples/exchange_client/derivative_exchange_rpc/1_Market.py +++ b/examples/exchange_client/derivative_exchange_rpc/1_Market.py @@ -12,5 +12,6 @@ async def main() -> None: market = await client.get_derivative_market(market_id=market_id) print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/20_Binary_Options_Market.py b/examples/exchange_client/derivative_exchange_rpc/20_Binary_Options_Market.py index 2f448439..6c14d93a 100644 --- a/examples/exchange_client/derivative_exchange_rpc/20_Binary_Options_Market.py +++ b/examples/exchange_client/derivative_exchange_rpc/20_Binary_Options_Market.py @@ -11,5 +11,6 @@ async def main() -> None: market = await client.get_binary_options_market(market_id=market_id) print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/21_Historical_Orders.py b/examples/exchange_client/derivative_exchange_rpc/21_Historical_Orders.py index 8bca13c8..9dc22f6f 100644 --- a/examples/exchange_client/derivative_exchange_rpc/21_Historical_Orders.py +++ b/examples/exchange_client/derivative_exchange_rpc/21_Historical_Orders.py @@ -22,5 +22,6 @@ async def main() -> None: ) print(orders) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/22_OrderbooksV2.py b/examples/exchange_client/derivative_exchange_rpc/22_OrderbooksV2.py index 43ed58f3..40ae4598 100644 --- a/examples/exchange_client/derivative_exchange_rpc/22_OrderbooksV2.py +++ b/examples/exchange_client/derivative_exchange_rpc/22_OrderbooksV2.py @@ -10,10 +10,11 @@ async def main() -> None: client = AsyncClient(network) market_ids = [ "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6", - "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff" + "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff", ] orderbooks = await client.get_derivative_orderbooksV2(market_ids=market_ids) print(orderbooks) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/2_Markets.py b/examples/exchange_client/derivative_exchange_rpc/2_Markets.py index ed0850fb..949695e1 100644 --- a/examples/exchange_client/derivative_exchange_rpc/2_Markets.py +++ b/examples/exchange_client/derivative_exchange_rpc/2_Markets.py @@ -10,11 +10,9 @@ async def main() -> None: client = AsyncClient(network) market_status = "active" quote_denom = "peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5" - market = await client.get_derivative_markets( - market_status=market_status, - quote_denom=quote_denom - ) + market = await client.get_derivative_markets(market_status=market_status, quote_denom=quote_denom) print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/3_StreamMarket.py b/examples/exchange_client/derivative_exchange_rpc/3_StreamMarket.py index 4f9a8a32..b5b7cbb0 100644 --- a/examples/exchange_client/derivative_exchange_rpc/3_StreamMarket.py +++ b/examples/exchange_client/derivative_exchange_rpc/3_StreamMarket.py @@ -12,5 +12,6 @@ async def main() -> None: async for market in markets: print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/4_Orderbook.py b/examples/exchange_client/derivative_exchange_rpc/4_Orderbook.py index aaf92213..49602701 100644 --- a/examples/exchange_client/derivative_exchange_rpc/4_Orderbook.py +++ b/examples/exchange_client/derivative_exchange_rpc/4_Orderbook.py @@ -12,5 +12,6 @@ async def main() -> None: market = await client.get_derivative_orderbook(market_id=market_id) print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/5_StreamOrderbooks.py b/examples/exchange_client/derivative_exchange_rpc/5_StreamOrderbooks.py index f1da521f..ab9c5927 100644 --- a/examples/exchange_client/derivative_exchange_rpc/5_StreamOrderbooks.py +++ b/examples/exchange_client/derivative_exchange_rpc/5_StreamOrderbooks.py @@ -13,5 +13,6 @@ async def main() -> None: async for market in markets: print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/6_StreamOrderbookUpdate.py b/examples/exchange_client/derivative_exchange_rpc/6_StreamOrderbookUpdate.py index e3375223..235e75d2 100644 --- a/examples/exchange_client/derivative_exchange_rpc/6_StreamOrderbookUpdate.py +++ b/examples/exchange_client/derivative_exchange_rpc/6_StreamOrderbookUpdate.py @@ -79,8 +79,11 @@ def apply_orderbook_update(orderbook: Orderbook, updates): # ensure we have not missed any update if updates.sequence > (orderbook.sequence + 1): - raise Exception("missing orderbook update events from stream, must restart: {} vs {}".format( - updates.sequence, (orderbook.sequence + 1))) + raise Exception( + "missing orderbook update events from stream, must restart: {} vs {}".format( + updates.sequence, (orderbook.sequence + 1) + ) + ) print("updating orderbook with updates at sequence {}".format(updates.sequence)) @@ -91,9 +94,8 @@ def apply_orderbook_update(orderbook: Orderbook, updates): if level.is_active: # upsert level orderbook.levels[direction][level.price] = PriceLevel( - price=Decimal(level.price), - quantity=Decimal(level.quantity), - timestamp=level.timestamp) + price=Decimal(level.price), quantity=Decimal(level.quantity), timestamp=level.timestamp + ) else: if level.price in orderbook.levels[direction]: del orderbook.levels[direction][level.price] @@ -121,5 +123,5 @@ def apply_orderbook_update(orderbook: Orderbook, updates): print("====================================") -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/7_Positions.py b/examples/exchange_client/derivative_exchange_rpc/7_Positions.py index fcd5814e..fddd7b3a 100644 --- a/examples/exchange_client/derivative_exchange_rpc/7_Positions.py +++ b/examples/exchange_client/derivative_exchange_rpc/7_Positions.py @@ -10,7 +10,7 @@ async def main() -> None: client = AsyncClient(network) market_ids = [ "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6", - "0xd97d0da6f6c11710ef06315971250e4e9aed4b7d4cd02059c9477ec8cf243782" + "0xd97d0da6f6c11710ef06315971250e4e9aed4b7d4cd02059c9477ec8cf243782", ] subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000" direction = "short" @@ -23,9 +23,10 @@ async def main() -> None: direction=direction, subaccount_total_positions=subaccount_total_positions, skip=skip, - limit=limit + limit=limit, ) print(positions) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/derivative_exchange_rpc/9_StreamPositions.py b/examples/exchange_client/derivative_exchange_rpc/9_StreamPositions.py index 05b5a484..cc808a7e 100644 --- a/examples/exchange_client/derivative_exchange_rpc/9_StreamPositions.py +++ b/examples/exchange_client/derivative_exchange_rpc/9_StreamPositions.py @@ -10,12 +10,10 @@ async def main() -> None: client = AsyncClient(network) market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" subaccount_id = "0xea98e3aa091a6676194df40ac089e40ab4604bf9000000000000000000000000" - positions = await client.stream_derivative_positions( - market_id=market_id, - subaccount_id=subaccount_id - ) + positions = await client.stream_derivative_positions(market_id=market_id, subaccount_id=subaccount_id) async for position in positions: print(position) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/10_GetIBCTransfers.py b/examples/exchange_client/explorer_rpc/10_GetIBCTransfers.py index 33114f4f..62ca0c24 100644 --- a/examples/exchange_client/explorer_rpc/10_GetIBCTransfers.py +++ b/examples/exchange_client/explorer_rpc/10_GetIBCTransfers.py @@ -24,9 +24,10 @@ async def main() -> None: destination_channel=destination_channel, dest_port=dest_port, limit=limit, - skip=skip + skip=skip, ) print(ibc_transfers) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/1_GetTxByHash.py b/examples/exchange_client/explorer_rpc/1_GetTxByHash.py index 84096641..33e6abe4 100644 --- a/examples/exchange_client/explorer_rpc/1_GetTxByHash.py +++ b/examples/exchange_client/explorer_rpc/1_GetTxByHash.py @@ -19,5 +19,6 @@ async def main() -> None: first_message = transaction_messages[0] print(first_message) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/2_AccountTxs.py b/examples/exchange_client/explorer_rpc/2_AccountTxs.py index ca4957a2..b1e39445 100644 --- a/examples/exchange_client/explorer_rpc/2_AccountTxs.py +++ b/examples/exchange_client/explorer_rpc/2_AccountTxs.py @@ -20,5 +20,6 @@ async def main() -> None: first_message = first_transaction_messages[0] print(first_message) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/3_Blocks.py b/examples/exchange_client/explorer_rpc/3_Blocks.py index 072403d1..72739096 100644 --- a/examples/exchange_client/explorer_rpc/3_Blocks.py +++ b/examples/exchange_client/explorer_rpc/3_Blocks.py @@ -12,5 +12,6 @@ async def main() -> None: block = await client.get_blocks(limit=limit) print(block) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/4_Block.py b/examples/exchange_client/explorer_rpc/4_Block.py index 433a4071..e043bdcd 100644 --- a/examples/exchange_client/explorer_rpc/4_Block.py +++ b/examples/exchange_client/explorer_rpc/4_Block.py @@ -12,5 +12,6 @@ async def main() -> None: block = await client.get_block(block_height=block_height) print(block) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/5_TxsRequest.py b/examples/exchange_client/explorer_rpc/5_TxsRequest.py index 57803f50..8282816b 100644 --- a/examples/exchange_client/explorer_rpc/5_TxsRequest.py +++ b/examples/exchange_client/explorer_rpc/5_TxsRequest.py @@ -12,5 +12,6 @@ async def main() -> None: txs = await client.get_txs(limit=limit) print(txs) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/6_StreamTxs.py b/examples/exchange_client/explorer_rpc/6_StreamTxs.py index 1d3b9597..f96a595e 100644 --- a/examples/exchange_client/explorer_rpc/6_StreamTxs.py +++ b/examples/exchange_client/explorer_rpc/6_StreamTxs.py @@ -8,10 +8,10 @@ async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() client = AsyncClient(network) - stream_txs = await client.stream_txs( - ) + stream_txs = await client.stream_txs() async for tx in stream_txs: print(tx) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/7_StreamBlocks.py b/examples/exchange_client/explorer_rpc/7_StreamBlocks.py index e167db2a..f5169511 100644 --- a/examples/exchange_client/explorer_rpc/7_StreamBlocks.py +++ b/examples/exchange_client/explorer_rpc/7_StreamBlocks.py @@ -8,10 +8,10 @@ async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() client = AsyncClient(network) - stream_blocks = await client.stream_blocks( - ) + stream_blocks = await client.stream_blocks() async for block in stream_blocks: print(block) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/8_GetPeggyDeposits.py b/examples/exchange_client/explorer_rpc/8_GetPeggyDeposits.py index 7c18dd38..4fde668f 100644 --- a/examples/exchange_client/explorer_rpc/8_GetPeggyDeposits.py +++ b/examples/exchange_client/explorer_rpc/8_GetPeggyDeposits.py @@ -12,5 +12,6 @@ async def main() -> None: peggy_deposits = await client.get_peggy_deposits(receiver=receiver) print(peggy_deposits) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/explorer_rpc/9_GetPeggyWithdrawals.py b/examples/exchange_client/explorer_rpc/9_GetPeggyWithdrawals.py index 67859c62..def1fedf 100644 --- a/examples/exchange_client/explorer_rpc/9_GetPeggyWithdrawals.py +++ b/examples/exchange_client/explorer_rpc/9_GetPeggyWithdrawals.py @@ -10,11 +10,9 @@ async def main() -> None: client = AsyncClient(network) sender = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku" limit = 2 - peggy_deposits = await client.get_peggy_withdrawals( - sender=sender, - limit=limit - ) + peggy_deposits = await client.get_peggy_withdrawals(sender=sender, limit=limit) print(peggy_deposits) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/insurance_rpc/1_InsuranceFunds.py b/examples/exchange_client/insurance_rpc/1_InsuranceFunds.py index 32a52818..167cae93 100644 --- a/examples/exchange_client/insurance_rpc/1_InsuranceFunds.py +++ b/examples/exchange_client/insurance_rpc/1_InsuranceFunds.py @@ -11,5 +11,6 @@ async def main() -> None: insurance_funds = await client.get_insurance_funds() print(insurance_funds) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/insurance_rpc/2_Redemptions.py b/examples/exchange_client/insurance_rpc/2_Redemptions.py index 5b5c0399..794e4b02 100644 --- a/examples/exchange_client/insurance_rpc/2_Redemptions.py +++ b/examples/exchange_client/insurance_rpc/2_Redemptions.py @@ -12,11 +12,10 @@ async def main() -> None: redemption_denom = "share4" status = "disbursed" insurance_redemptions = await client.get_redemptions( - redeemer=redeemer, - redemption_denom=redemption_denom, - status=status + redeemer=redeemer, redemption_denom=redemption_denom, status=status ) print(insurance_redemptions) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/meta_rpc/1_Ping.py b/examples/exchange_client/meta_rpc/1_Ping.py index f342297e..3b75cbae 100644 --- a/examples/exchange_client/meta_rpc/1_Ping.py +++ b/examples/exchange_client/meta_rpc/1_Ping.py @@ -9,7 +9,8 @@ async def main() -> None: network = Network.testnet() client = AsyncClient(network) resp = await client.ping() - print('Health OK?', resp) + print("Health OK?", resp) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/meta_rpc/2_Version.py b/examples/exchange_client/meta_rpc/2_Version.py index 0493c67c..025a931b 100644 --- a/examples/exchange_client/meta_rpc/2_Version.py +++ b/examples/exchange_client/meta_rpc/2_Version.py @@ -9,7 +9,8 @@ async def main() -> None: network = Network.testnet() client = AsyncClient(network) resp = await client.version() - print('Version:', resp) + print("Version:", resp) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/meta_rpc/3_Info.py b/examples/exchange_client/meta_rpc/3_Info.py index 33d45d41..8f799da7 100644 --- a/examples/exchange_client/meta_rpc/3_Info.py +++ b/examples/exchange_client/meta_rpc/3_Info.py @@ -10,11 +10,11 @@ async def main() -> None: network = Network.testnet() client = AsyncClient(network) resp = await client.info() - print('[!] Info:') + print("[!] Info:") print(resp) latency = int(round(time.time() * 1000)) - resp.timestamp - print(f'Server Latency: {latency}ms') + print(f"Server Latency: {latency}ms") -if __name__ == '__main__': +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/meta_rpc/4_StreamKeepAlive.py b/examples/exchange_client/meta_rpc/4_StreamKeepAlive.py index 2c5686a5..789cabc7 100644 --- a/examples/exchange_client/meta_rpc/4_StreamKeepAlive.py +++ b/examples/exchange_client/meta_rpc/4_StreamKeepAlive.py @@ -30,11 +30,11 @@ async def get_markets(client): async def keepalive(client, tasks: list): stream = await client.stream_keepalive() async for announce in stream: - print('Server announce:', announce) + print("Server announce:", announce) async for task in tasks: task.cancel() - print('Cancelled all tasks') + print("Cancelled all tasks") -if __name__ == '__main__': +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/oracle_rpc/1_StreamPrices.py b/examples/exchange_client/oracle_rpc/1_StreamPrices.py index 360c02ee..ca7f9de5 100644 --- a/examples/exchange_client/oracle_rpc/1_StreamPrices.py +++ b/examples/exchange_client/oracle_rpc/1_StreamPrices.py @@ -8,16 +8,15 @@ async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() client = AsyncClient(network) - base_symbol = 'BTC' - quote_symbol = 'USDT' - oracle_type = 'bandibc' + base_symbol = "BTC" + quote_symbol = "USDT" + oracle_type = "bandibc" oracle_prices = await client.stream_oracle_prices( - base_symbol=base_symbol, - quote_symbol=quote_symbol, - oracle_type=oracle_type + base_symbol=base_symbol, quote_symbol=quote_symbol, oracle_type=oracle_type ) async for oracle in oracle_prices: print(oracle) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/oracle_rpc/2_Price.py b/examples/exchange_client/oracle_rpc/2_Price.py index 48b4c703..f3a5921e 100644 --- a/examples/exchange_client/oracle_rpc/2_Price.py +++ b/examples/exchange_client/oracle_rpc/2_Price.py @@ -8,17 +8,18 @@ async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() client = AsyncClient(network) - base_symbol = 'BTC' - quote_symbol = 'USDT' - oracle_type = 'bandibc' + base_symbol = "BTC" + quote_symbol = "USDT" + oracle_type = "bandibc" oracle_scale_factor = 6 oracle_prices = await client.get_oracle_prices( base_symbol=base_symbol, quote_symbol=quote_symbol, oracle_type=oracle_type, - oracle_scale_factor=oracle_scale_factor + oracle_scale_factor=oracle_scale_factor, ) print(oracle_prices) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/oracle_rpc/3_OracleList.py b/examples/exchange_client/oracle_rpc/3_OracleList.py index 69fa1789..558ac66d 100644 --- a/examples/exchange_client/oracle_rpc/3_OracleList.py +++ b/examples/exchange_client/oracle_rpc/3_OracleList.py @@ -11,5 +11,6 @@ async def main() -> None: oracle_list = await client.get_oracle_list() print(oracle_list) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/portfolio_rpc/1_AccountPortfolio.py b/examples/exchange_client/portfolio_rpc/1_AccountPortfolio.py index 396adce4..965d40c7 100644 --- a/examples/exchange_client/portfolio_rpc/1_AccountPortfolio.py +++ b/examples/exchange_client/portfolio_rpc/1_AccountPortfolio.py @@ -9,10 +9,9 @@ async def main() -> None: network = Network.testnet() client = AsyncClient(network) account_address = "inj1clw20s2uxeyxtam6f7m84vgae92s9eh7vygagt" - portfolio = await client.get_account_portfolio( - account_address=account_address - ) + portfolio = await client.get_account_portfolio(account_address=account_address) print(portfolio) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/portfolio_rpc/2_StreamAccountPortfolio.py b/examples/exchange_client/portfolio_rpc/2_StreamAccountPortfolio.py index 7b06037c..53d7c4da 100644 --- a/examples/exchange_client/portfolio_rpc/2_StreamAccountPortfolio.py +++ b/examples/exchange_client/portfolio_rpc/2_StreamAccountPortfolio.py @@ -14,5 +14,5 @@ async def main() -> None: print(update) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/10_StreamTrades.py b/examples/exchange_client/spot_exchange_rpc/10_StreamTrades.py index 053b2e61..8bf4a82a 100644 --- a/examples/exchange_client/spot_exchange_rpc/10_StreamTrades.py +++ b/examples/exchange_client/spot_exchange_rpc/10_StreamTrades.py @@ -9,7 +9,7 @@ async def main() -> None: client = AsyncClient(network) market_ids = [ "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe", - "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0" + "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0", ] execution_side = "maker" direction = "sell" @@ -20,11 +20,11 @@ async def main() -> None: execution_side=execution_side, direction=direction, subaccount_id=subaccount_id, - execution_types=execution_types + execution_types=execution_types, ) async for trade in trades: print(trade) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/11_SubaccountOrdersList.py b/examples/exchange_client/spot_exchange_rpc/11_SubaccountOrdersList.py index abd20bef..03e901e9 100644 --- a/examples/exchange_client/spot_exchange_rpc/11_SubaccountOrdersList.py +++ b/examples/exchange_client/spot_exchange_rpc/11_SubaccountOrdersList.py @@ -13,12 +13,10 @@ async def main() -> None: skip = 10 limit = 10 orders = await client.get_spot_subaccount_orders( - subaccount_id=subaccount_id, - market_id=market_id, - skip=skip, - limit=limit + subaccount_id=subaccount_id, market_id=market_id, skip=skip, limit=limit ) print(orders) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/12_SubaccountTradesList.py b/examples/exchange_client/spot_exchange_rpc/12_SubaccountTradesList.py index ae71af7f..a9670e58 100644 --- a/examples/exchange_client/spot_exchange_rpc/12_SubaccountTradesList.py +++ b/examples/exchange_client/spot_exchange_rpc/12_SubaccountTradesList.py @@ -20,9 +20,10 @@ async def main() -> None: execution_type=execution_type, direction=direction, skip=skip, - limit=limit + limit=limit, ) print(trades) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/13_StreamOrderbooks.py b/examples/exchange_client/spot_exchange_rpc/13_StreamOrderbooks.py index 18b6f70f..82fe35e7 100644 --- a/examples/exchange_client/spot_exchange_rpc/13_StreamOrderbooks.py +++ b/examples/exchange_client/spot_exchange_rpc/13_StreamOrderbooks.py @@ -9,11 +9,12 @@ async def main() -> None: client = AsyncClient(network) market_ids = [ "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe", - "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0" + "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0", ] orderbook = await client.stream_spot_orderbook_snapshot(market_ids=market_ids) async for orders in orderbook: print(orders) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/14_Orderbooks.py b/examples/exchange_client/spot_exchange_rpc/14_Orderbooks.py index 34b898e2..2a99f818 100644 --- a/examples/exchange_client/spot_exchange_rpc/14_Orderbooks.py +++ b/examples/exchange_client/spot_exchange_rpc/14_Orderbooks.py @@ -9,10 +9,11 @@ async def main() -> None: client = AsyncClient(network) market_ids = [ "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe", - "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0" + "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0", ] orderbooks = await client.get_spot_orderbooksV2(market_ids=market_ids) print(orderbooks) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/15_HistoricalOrders.py b/examples/exchange_client/spot_exchange_rpc/15_HistoricalOrders.py index aa63f432..0a39f80d 100644 --- a/examples/exchange_client/spot_exchange_rpc/15_HistoricalOrders.py +++ b/examples/exchange_client/spot_exchange_rpc/15_HistoricalOrders.py @@ -13,13 +13,10 @@ async def main() -> None: limit = 3 order_types = ["buy_po"] orders = await client.get_historical_spot_orders( - market_id=market_id, - subaccount_id=subaccount_id, - skip=skip, - limit=limit, - order_types=order_types + market_id=market_id, subaccount_id=subaccount_id, skip=skip, limit=limit, order_types=order_types ) print(orders) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/1_Market.py b/examples/exchange_client/spot_exchange_rpc/1_Market.py index 95152295..d926e97c 100644 --- a/examples/exchange_client/spot_exchange_rpc/1_Market.py +++ b/examples/exchange_client/spot_exchange_rpc/1_Market.py @@ -11,5 +11,6 @@ async def main() -> None: market = await client.get_spot_market(market_id=market_id) print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/2_Markets.py b/examples/exchange_client/spot_exchange_rpc/2_Markets.py index 926f8290..dc37d25f 100644 --- a/examples/exchange_client/spot_exchange_rpc/2_Markets.py +++ b/examples/exchange_client/spot_exchange_rpc/2_Markets.py @@ -10,13 +10,9 @@ async def main() -> None: market_status = "active" base_denom = "inj" quote_denom = "peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5" - market = await client.get_spot_markets( - market_status=market_status, - base_denom=base_denom, - quote_denom=quote_denom - ) + market = await client.get_spot_markets(market_status=market_status, base_denom=base_denom, quote_denom=quote_denom) print(market) -if __name__ == '__main__': +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/3_StreamMarkets.py b/examples/exchange_client/spot_exchange_rpc/3_StreamMarkets.py index 25ea9b15..16633271 100644 --- a/examples/exchange_client/spot_exchange_rpc/3_StreamMarkets.py +++ b/examples/exchange_client/spot_exchange_rpc/3_StreamMarkets.py @@ -12,5 +12,6 @@ async def main() -> None: async for market in markets: print(market) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/4_Orderbook.py b/examples/exchange_client/spot_exchange_rpc/4_Orderbook.py index 03112299..1de0c539 100644 --- a/examples/exchange_client/spot_exchange_rpc/4_Orderbook.py +++ b/examples/exchange_client/spot_exchange_rpc/4_Orderbook.py @@ -11,5 +11,6 @@ async def main() -> None: orderbook = await client.get_spot_orderbookV2(market_id=market_id) print(orderbook) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/6_Trades.py b/examples/exchange_client/spot_exchange_rpc/6_Trades.py index d8acaf66..6c035553 100644 --- a/examples/exchange_client/spot_exchange_rpc/6_Trades.py +++ b/examples/exchange_client/spot_exchange_rpc/6_Trades.py @@ -17,9 +17,10 @@ async def main() -> None: execution_side=execution_side, direction=direction, subaccount_id=subaccount_id, - execution_types=execution_types + execution_types=execution_types, ) print(orders) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/7_StreamOrderbookSnapshot.py b/examples/exchange_client/spot_exchange_rpc/7_StreamOrderbookSnapshot.py index e522cf22..5c4ed593 100644 --- a/examples/exchange_client/spot_exchange_rpc/7_StreamOrderbookSnapshot.py +++ b/examples/exchange_client/spot_exchange_rpc/7_StreamOrderbookSnapshot.py @@ -13,5 +13,6 @@ async def main() -> None: async for orderbook in orderbooks: print(orderbook) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/8_StreamOrderbookUpdate.py b/examples/exchange_client/spot_exchange_rpc/8_StreamOrderbookUpdate.py index e24cd79f..13a789fd 100644 --- a/examples/exchange_client/spot_exchange_rpc/8_StreamOrderbookUpdate.py +++ b/examples/exchange_client/spot_exchange_rpc/8_StreamOrderbookUpdate.py @@ -79,8 +79,11 @@ def apply_orderbook_update(orderbook: Orderbook, updates): # ensure we have not missed any update if updates.sequence > (orderbook.sequence + 1): - raise Exception("missing orderbook update events from stream, must restart: {} vs {}".format( - updates.sequence, (orderbook.sequence + 1))) + raise Exception( + "missing orderbook update events from stream, must restart: {} vs {}".format( + updates.sequence, (orderbook.sequence + 1) + ) + ) print("updating orderbook with updates at sequence {}".format(updates.sequence)) @@ -91,9 +94,8 @@ def apply_orderbook_update(orderbook: Orderbook, updates): if level.is_active: # upsert level orderbook.levels[direction][level.price] = PriceLevel( - price=Decimal(level.price), - quantity=Decimal(level.quantity), - timestamp=level.timestamp) + price=Decimal(level.price), quantity=Decimal(level.quantity), timestamp=level.timestamp + ) else: if level.price in orderbook.levels[direction]: del orderbook.levels[direction][level.price] @@ -121,5 +123,5 @@ def apply_orderbook_update(orderbook: Orderbook, updates): print("====================================") -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(main()) diff --git a/examples/exchange_client/spot_exchange_rpc/9_StreamHistoricalOrders.py b/examples/exchange_client/spot_exchange_rpc/9_StreamHistoricalOrders.py index 75a12a3e..95dcdb43 100644 --- a/examples/exchange_client/spot_exchange_rpc/9_StreamHistoricalOrders.py +++ b/examples/exchange_client/spot_exchange_rpc/9_StreamHistoricalOrders.py @@ -9,12 +9,10 @@ async def main() -> None: client = AsyncClient(network) market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" order_side = "buy" - orders = await client.stream_historical_spot_orders( - market_id=market_id, - order_side=order_side - ) + orders = await client.stream_historical_spot_orders(market_id=market_id, order_side=order_side) async for order in orders: print(order) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/poetry.lock b/poetry.lock index 65d65b81..7f7f64cc 100644 --- a/poetry.lock +++ b/poetry.lock @@ -344,6 +344,52 @@ files = [ {file = "bitarray-2.8.1.tar.gz", hash = "sha256:e68ceef35a88625d16169550768fcc8d3894913e363c24ecbf6b8c07eb02c8f3"}, ] +[[package]] +name = "black" +version = "23.9.1" +description = "The uncompromising code formatter." +optional = false +python-versions = ">=3.8" +files = [ + {file = "black-23.9.1-cp310-cp310-macosx_10_16_arm64.whl", hash = "sha256:d6bc09188020c9ac2555a498949401ab35bb6bf76d4e0f8ee251694664df6301"}, + {file = "black-23.9.1-cp310-cp310-macosx_10_16_universal2.whl", hash = "sha256:13ef033794029b85dfea8032c9d3b92b42b526f1ff4bf13b2182ce4e917f5100"}, + {file = "black-23.9.1-cp310-cp310-macosx_10_16_x86_64.whl", hash = "sha256:75a2dc41b183d4872d3a500d2b9c9016e67ed95738a3624f4751a0cb4818fe71"}, + {file = "black-23.9.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:13a2e4a93bb8ca74a749b6974925c27219bb3df4d42fc45e948a5d9feb5122b7"}, + {file = "black-23.9.1-cp310-cp310-win_amd64.whl", hash = "sha256:adc3e4442eef57f99b5590b245a328aad19c99552e0bdc7f0b04db6656debd80"}, + {file = "black-23.9.1-cp311-cp311-macosx_10_16_arm64.whl", hash = "sha256:8431445bf62d2a914b541da7ab3e2b4f3bc052d2ccbf157ebad18ea126efb91f"}, + {file = "black-23.9.1-cp311-cp311-macosx_10_16_universal2.whl", hash = "sha256:8fc1ddcf83f996247505db6b715294eba56ea9372e107fd54963c7553f2b6dfe"}, + {file = "black-23.9.1-cp311-cp311-macosx_10_16_x86_64.whl", hash = "sha256:7d30ec46de88091e4316b17ae58bbbfc12b2de05e069030f6b747dfc649ad186"}, + {file = "black-23.9.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:031e8c69f3d3b09e1aa471a926a1eeb0b9071f80b17689a655f7885ac9325a6f"}, + {file = "black-23.9.1-cp311-cp311-win_amd64.whl", hash = "sha256:538efb451cd50f43aba394e9ec7ad55a37598faae3348d723b59ea8e91616300"}, + {file = "black-23.9.1-cp38-cp38-macosx_10_16_arm64.whl", hash = "sha256:638619a559280de0c2aa4d76f504891c9860bb8fa214267358f0a20f27c12948"}, + {file = "black-23.9.1-cp38-cp38-macosx_10_16_universal2.whl", hash = "sha256:a732b82747235e0542c03bf352c126052c0fbc458d8a239a94701175b17d4855"}, + {file = "black-23.9.1-cp38-cp38-macosx_10_16_x86_64.whl", hash = "sha256:cf3a4d00e4cdb6734b64bf23cd4341421e8953615cba6b3670453737a72ec204"}, + {file = "black-23.9.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cf99f3de8b3273a8317681d8194ea222f10e0133a24a7548c73ce44ea1679377"}, + {file = "black-23.9.1-cp38-cp38-win_amd64.whl", hash = "sha256:14f04c990259576acd093871e7e9b14918eb28f1866f91968ff5524293f9c573"}, + {file = "black-23.9.1-cp39-cp39-macosx_10_16_arm64.whl", hash = "sha256:c619f063c2d68f19b2d7270f4cf3192cb81c9ec5bc5ba02df91471d0b88c4c5c"}, + {file = "black-23.9.1-cp39-cp39-macosx_10_16_universal2.whl", hash = "sha256:6a3b50e4b93f43b34a9d3ef00d9b6728b4a722c997c99ab09102fd5efdb88325"}, + {file = "black-23.9.1-cp39-cp39-macosx_10_16_x86_64.whl", hash = "sha256:c46767e8df1b7beefb0899c4a95fb43058fa8500b6db144f4ff3ca38eb2f6393"}, + {file = "black-23.9.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:50254ebfa56aa46a9fdd5d651f9637485068a1adf42270148cd101cdf56e0ad9"}, + {file = "black-23.9.1-cp39-cp39-win_amd64.whl", hash = "sha256:403397c033adbc45c2bd41747da1f7fc7eaa44efbee256b53842470d4ac5a70f"}, + {file = "black-23.9.1-py3-none-any.whl", hash = "sha256:6ccd59584cc834b6d127628713e4b6b968e5f79572da66284532525a042549f9"}, + {file = "black-23.9.1.tar.gz", hash = "sha256:24b6b3ff5c6d9ea08a8888f6977eae858e1f340d7260cf56d70a49823236b62d"}, +] + +[package.dependencies] +click = ">=8.0.0" +mypy-extensions = ">=0.4.3" +packaging = ">=22.0" +pathspec = ">=0.9.0" +platformdirs = ">=2" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""} + +[package.extras] +colorama = ["colorama (>=0.4.3)"] +d = ["aiohttp (>=3.7.4)"] +jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] +uvloop = ["uvloop (>=0.15.2)"] + [[package]] name = "certifi" version = "2023.7.22" @@ -526,6 +572,20 @@ files = [ {file = "charset_normalizer-3.2.0-py3-none-any.whl", hash = "sha256:8e098148dd37b4ce3baca71fb394c81dc5d9c7728c95df695d2dca218edf40e6"}, ] +[[package]] +name = "click" +version = "8.1.7" +description = "Composable command line interface toolkit" +optional = false +python-versions = ">=3.7" +files = [ + {file = "click-8.1.7-py3-none-any.whl", hash = "sha256:ae74fb96c20a0277a1d615f1e4d73c8414f5a98db8b799a7931d1582f3390c28"}, + {file = "click-8.1.7.tar.gz", hash = "sha256:ca9853ad459e787e2192211578cc907e7594e294c7ccc834310722b41b9ca6de"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} + [[package]] name = "coincurve" version = "18.0.0" @@ -1542,6 +1602,17 @@ files = [ {file = "multidict-6.0.4.tar.gz", hash = "sha256:3666906492efb76453c0e7b97f2cf459b0682e7402c0489a95484965dbc1da49"}, ] +[[package]] +name = "mypy-extensions" +version = "1.0.0" +description = "Type system extensions for programs checked with the mypy type checker." +optional = false +python-versions = ">=3.5" +files = [ + {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, + {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, +] + [[package]] name = "nodeenv" version = "1.8.0" @@ -1580,6 +1651,17 @@ files = [ [package.dependencies] regex = ">=2022.3.15" +[[package]] +name = "pathspec" +version = "0.11.2" +description = "Utility library for gitignore style pattern matching of file paths." +optional = false +python-versions = ">=3.7" +files = [ + {file = "pathspec-0.11.2-py3-none-any.whl", hash = "sha256:1d6ed233af05e679efb96b1851550ea95bbb64b7c490b0f5aa52996c11e92a20"}, + {file = "pathspec-0.11.2.tar.gz", hash = "sha256:e0d8d0ac2f12da61956eb2306b69f9469b42f4deb0f3cb6ed47b9cce9996ced3"}, +] + [[package]] name = "platformdirs" version = "3.10.0" @@ -2526,4 +2608,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.9" -content-hash = "9910d20ce606278058ffa00c27ab4b42abb06da9278623cc014c0b7076f13503" +content-hash = "fcf0115df57cae7065cda119c217acb85cc70d086b05538537df91ef261002bb" diff --git a/pyinjective/async_client.py b/pyinjective/async_client.py index 1e90a4e6..f279b45f 100644 --- a/pyinjective/async_client.py +++ b/pyinjective/async_client.py @@ -54,10 +54,10 @@ class AsyncClient: def __init__( - self, - network: Network, - insecure: bool = False, - credentials=grpc.ssl_channel_credentials(), + self, + network: Network, + insecure: bool = False, + credentials=grpc.ssl_channel_credentials(), ): # the `insecure` parameter is ignored and will be deprecated soon. The value is taken directly from `network` @@ -74,9 +74,7 @@ def __init__( else grpc.aio.insecure_channel(network.grpc_endpoint) ) - self.stubCosmosTendermint = tendermint_query_grpc.ServiceStub( - self.chain_channel - ) + self.stubCosmosTendermint = tendermint_query_grpc.ServiceStub(self.chain_channel) self.stubAuth = auth_query_grpc.QueryStub(self.chain_channel) self.stubAuthz = authz_query_grpc.QueryStub(self.chain_channel) self.stubBank = bank_query_grpc.QueryStub(self.chain_channel) @@ -91,30 +89,16 @@ def __init__( if (network.use_secure_connection and credentials is not None) else grpc.aio.insecure_channel(network.grpc_exchange_endpoint) ) - self.stubMeta = exchange_meta_rpc_grpc.InjectiveMetaRPCStub( - self.exchange_channel - ) - self.stubExchangeAccount = exchange_accounts_rpc_grpc.InjectiveAccountsRPCStub( - self.exchange_channel - ) + self.stubMeta = exchange_meta_rpc_grpc.InjectiveMetaRPCStub(self.exchange_channel) + self.stubExchangeAccount = exchange_accounts_rpc_grpc.InjectiveAccountsRPCStub(self.exchange_channel) self.stubOracle = oracle_rpc_grpc.InjectiveOracleRPCStub(self.exchange_channel) - self.stubInsurance = insurance_rpc_grpc.InjectiveInsuranceRPCStub( - self.exchange_channel - ) - self.stubSpotExchange = spot_exchange_rpc_grpc.InjectiveSpotExchangeRPCStub( - self.exchange_channel - ) - self.stubDerivativeExchange = ( - derivative_exchange_rpc_grpc.InjectiveDerivativeExchangeRPCStub( - self.exchange_channel - ) - ) - self.stubAuction = auction_rpc_grpc.InjectiveAuctionRPCStub( - self.exchange_channel - ) - self.stubPortfolio = portfolio_rpc_grpc.InjectivePortfolioRPCStub( + self.stubInsurance = insurance_rpc_grpc.InjectiveInsuranceRPCStub(self.exchange_channel) + self.stubSpotExchange = spot_exchange_rpc_grpc.InjectiveSpotExchangeRPCStub(self.exchange_channel) + self.stubDerivativeExchange = derivative_exchange_rpc_grpc.InjectiveDerivativeExchangeRPCStub( self.exchange_channel ) + self.stubAuction = auction_rpc_grpc.InjectiveAuctionRPCStub(self.exchange_channel) + self.stubPortfolio = portfolio_rpc_grpc.InjectivePortfolioRPCStub(self.exchange_channel) # explorer stubs self.explorer_channel = ( @@ -122,9 +106,7 @@ def __init__( if (network.use_secure_connection and credentials is not None) else grpc.aio.insecure_channel(network.grpc_explorer_endpoint) ) - self.stubExplorer = explorer_rpc_grpc.InjectiveExplorerRPCStub( - self.explorer_channel - ) + self.stubExplorer = explorer_rpc_grpc.InjectiveExplorerRPCStub(self.explorer_channel) # timeout height update routine self.cron = aiocron.crontab( @@ -204,11 +186,10 @@ async def get_latest_block(self) -> tendermint_query.GetLatestBlockResponse: async def get_account(self, address: str) -> Optional[account_pb2.EthAccount]: try: - metadata = await self.network.chain_metadata( - metadata_query_provider=self._chain_cookie_metadata_requestor) - account_any = (await self.stubAuth.Account( - auth_query.QueryAccountRequest(address=address), metadata=metadata - )).account + metadata = await self.network.chain_metadata(metadata_query_provider=self._chain_cookie_metadata_requestor) + account_any = ( + await self.stubAuth.Account(auth_query.QueryAccountRequest(address=address), metadata=metadata) + ).account account = account_pb2.EthAccount() if account_any.Is(account.DESCRIPTOR): account_any.Unpack(account) @@ -216,18 +197,15 @@ async def get_account(self, address: str) -> Optional[account_pb2.EthAccount]: self.sequence = int(account.base_account.sequence) except Exception as e: LoggerProvider().logger_for_class(logging_class=self.__class__).debug( - f"error while fetching sequence and number {e}") + f"error while fetching sequence and number {e}" + ) return None async def get_request_id_by_tx_hash(self, tx_hash: bytes) -> List[int]: tx = await self.stubTx.GetTx(tx_service.GetTxRequest(hash=tx_hash)) request_ids = [] for tx in tx.tx_response.logs: - request_event = [ - event - for event in tx.events - if event.type == "request" or event.type == "report" - ] + request_event = [event for event in tx.events if event.type == "request" or event.type == "report"] if len(request_event) == 1: attrs = request_event[0].attributes attr_id = [attr for attr in attrs if attr.key == "id"] @@ -238,37 +216,28 @@ async def get_request_id_by_tx_hash(self, tx_hash: bytes) -> List[int]: raise NotFoundError("Request Id is not found") return request_ids - async def simulate_tx( - self, tx_byte: bytes - ) -> Tuple[Union[abci_type.SimulationResponse, grpc.RpcError], bool]: + async def simulate_tx(self, tx_byte: bytes) -> Tuple[Union[abci_type.SimulationResponse, grpc.RpcError], bool]: try: req = tx_service.SimulateRequest(tx_bytes=tx_byte) - metadata = await self.network.chain_metadata( - metadata_query_provider=self._chain_cookie_metadata_requestor) + metadata = await self.network.chain_metadata(metadata_query_provider=self._chain_cookie_metadata_requestor) return await self.stubTx.Simulate(request=req, metadata=metadata), True except grpc.RpcError as err: return err, False async def send_tx_sync_mode(self, tx_byte: bytes) -> abci_type.TxResponse: - req = tx_service.BroadcastTxRequest( - tx_bytes=tx_byte, mode=tx_service.BroadcastMode.BROADCAST_MODE_SYNC - ) + req = tx_service.BroadcastTxRequest(tx_bytes=tx_byte, mode=tx_service.BroadcastMode.BROADCAST_MODE_SYNC) metadata = await self.network.chain_metadata(metadata_query_provider=self._chain_cookie_metadata_requestor) result = await self.stubTx.BroadcastTx(request=req, metadata=metadata) return result.tx_response async def send_tx_async_mode(self, tx_byte: bytes) -> abci_type.TxResponse: - req = tx_service.BroadcastTxRequest( - tx_bytes=tx_byte, mode=tx_service.BroadcastMode.BROADCAST_MODE_ASYNC - ) + req = tx_service.BroadcastTxRequest(tx_bytes=tx_byte, mode=tx_service.BroadcastMode.BROADCAST_MODE_ASYNC) metadata = await self.network.chain_metadata(metadata_query_provider=self._chain_cookie_metadata_requestor) result = await self.stubTx.BroadcastTx(request=req, metadata=metadata) return result.tx_response async def send_tx_block_mode(self, tx_byte: bytes) -> abci_type.TxResponse: - req = tx_service.BroadcastTxRequest( - tx_bytes=tx_byte, mode=tx_service.BroadcastMode.BROADCAST_MODE_BLOCK - ) + req = tx_service.BroadcastTxRequest(tx_bytes=tx_byte, mode=tx_service.BroadcastMode.BROADCAST_MODE_BLOCK) metadata = await self.network.chain_metadata(metadata_query_provider=self._chain_cookie_metadata_requestor) result = await self.stubTx.BroadcastTx(request=req, metadata=metadata) return result.tx_response @@ -287,14 +256,10 @@ async def get_grants(self, granter: str, grantee: str, **kwargs): ) async def get_bank_balances(self, address: str): - return await self.stubBank.AllBalances( - bank_query.QueryAllBalancesRequest(address=address) - ) + return await self.stubBank.AllBalances(bank_query.QueryAllBalancesRequest(address=address)) async def get_bank_balance(self, address: str, denom: str): - return await self.stubBank.Balance( - bank_query.QueryBalanceRequest(address=address, denom=denom) - ) + return await self.stubBank.Balance(bank_query.QueryBalanceRequest(address=address, denom=denom)) # Injective Exchange client methods @@ -416,27 +381,21 @@ async def get_ibc_transfers(self, **kwargs): async def stream_subaccount_balance(self, subaccount_id: str, **kwargs): req = exchange_accounts_rpc_pb.StreamSubaccountBalanceRequest( - subaccount_id=subaccount_id, - denoms=kwargs.get("denoms") + subaccount_id=subaccount_id, denoms=kwargs.get("denoms") ) return self.stubExchangeAccount.StreamSubaccountBalance(req) async def get_subaccount_balance(self, subaccount_id: str, denom: str): - req = exchange_accounts_rpc_pb.SubaccountBalanceEndpointRequest( - subaccount_id=subaccount_id, denom=denom - ) + req = exchange_accounts_rpc_pb.SubaccountBalanceEndpointRequest(subaccount_id=subaccount_id, denom=denom) return await self.stubExchangeAccount.SubaccountBalanceEndpoint(req) async def get_subaccount_list(self, account_address: str): - req = exchange_accounts_rpc_pb.SubaccountsListRequest( - account_address=account_address - ) + req = exchange_accounts_rpc_pb.SubaccountsListRequest(account_address=account_address) return await self.stubExchangeAccount.SubaccountsList(req) async def get_subaccount_balances_list(self, subaccount_id: str, **kwargs): req = exchange_accounts_rpc_pb.SubaccountBalancesListRequest( - subaccount_id=subaccount_id, - denoms=kwargs.get("denoms") + subaccount_id=subaccount_id, denoms=kwargs.get("denoms") ) return await self.stubExchangeAccount.SubaccountBalancesList(req) @@ -447,7 +406,7 @@ async def get_subaccount_history(self, subaccount_id: str, **kwargs): transfer_types=kwargs.get("transfer_types"), skip=kwargs.get("skip"), limit=kwargs.get("limit"), - end_time=kwargs.get("end_time") + end_time=kwargs.get("end_time"), ) return await self.stubExchangeAccount.SubaccountHistory(req) @@ -478,20 +437,18 @@ async def get_rewards(self, **kwargs): # OracleRPC - async def stream_oracle_prices( - self, base_symbol: str, quote_symbol: str, oracle_type: str - ): + async def stream_oracle_prices(self, base_symbol: str, quote_symbol: str, oracle_type: str): req = oracle_rpc_pb.StreamPricesRequest( base_symbol=base_symbol, quote_symbol=quote_symbol, oracle_type=oracle_type ) return self.stubOracle.StreamPrices(req) async def get_oracle_prices( - self, - base_symbol: str, - quote_symbol: str, - oracle_type: str, - oracle_scale_factor: int, + self, + base_symbol: str, + quote_symbol: str, + oracle_type: str, + oracle_scale_factor: int, ): req = oracle_rpc_pb.PriceRequest( base_symbol=base_symbol, @@ -534,9 +491,7 @@ async def get_spot_markets(self, **kwargs): return await self.stubSpotExchange.Markets(req) async def stream_spot_markets(self, **kwargs): - req = spot_exchange_rpc_pb.StreamMarketsRequest( - market_ids=kwargs.get("market_ids") - ) + req = spot_exchange_rpc_pb.StreamMarketsRequest(market_ids=kwargs.get("market_ids")) metadata = await self.network.exchange_metadata( metadata_query_provider=self._exchange_cookie_metadata_requestor ) @@ -626,7 +581,7 @@ async def stream_historical_spot_orders(self, market_id: str, **kwargs): subaccount_id=kwargs.get("subaccount_id"), order_types=kwargs.get("order_types"), state=kwargs.get("state"), - execution_types=kwargs.get("execution_types") + execution_types=kwargs.get("execution_types"), ) metadata = await self.network.exchange_metadata( metadata_query_provider=self._exchange_cookie_metadata_requestor @@ -640,7 +595,7 @@ async def stream_historical_derivative_orders(self, market_id: str, **kwargs): subaccount_id=kwargs.get("subaccount_id"), order_types=kwargs.get("order_types"), state=kwargs.get("state"), - execution_types=kwargs.get("execution_types") + execution_types=kwargs.get("execution_types"), ) metadata = await self.network.exchange_metadata( metadata_query_provider=self._exchange_cookie_metadata_requestor @@ -696,9 +651,7 @@ async def get_derivative_markets(self, **kwargs): return await self.stubDerivativeExchange.Markets(req) async def stream_derivative_markets(self, **kwargs): - req = derivative_exchange_rpc_pb.StreamMarketRequest( - market_ids=kwargs.get("market_ids") - ) + req = derivative_exchange_rpc_pb.StreamMarketRequest(market_ids=kwargs.get("market_ids")) metadata = await self.network.exchange_metadata( metadata_query_provider=self._exchange_cookie_metadata_requestor ) @@ -900,9 +853,7 @@ async def get_account_portfolio(self, account_address: str): async def stream_account_portfolio(self, account_address: str, **kwargs): req = portfolio_rpc_pb.StreamAccountPortfolioRequest( - account_address=account_address, - subaccount_id=kwargs.get("subaccount_id"), - type=kwargs.get("type") + account_address=account_address, subaccount_id=kwargs.get("subaccount_id"), type=kwargs.get("type") ) metadata = await self.network.exchange_metadata( metadata_query_provider=self._exchange_cookie_metadata_requestor diff --git a/pyinjective/composer.py b/pyinjective/composer.py index 29752b63..b543b077 100644 --- a/pyinjective/composer.py +++ b/pyinjective/composer.py @@ -32,13 +32,14 @@ class Composer: def __init__( - self, - network: str, - spot_markets: Optional[Dict[str, SpotMarket]] = None, - derivative_markets: Optional[Dict[str, DerivativeMarket]] = None, - binary_option_markets: Optional[Dict[str, BinaryOptionMarket]] = None, - tokens: Optional[Dict[str, Token]] = None): - """ Composer is used to create the requests to send to the nodes using the Client + self, + network: str, + spot_markets: Optional[Dict[str, SpotMarket]] = None, + derivative_markets: Optional[Dict[str, DerivativeMarket]] = None, + binary_option_markets: Optional[Dict[str, BinaryOptionMarket]] = None, + tokens: Optional[Dict[str, Token]] = None, + ): + """Composer is used to create the requests to send to the nodes using the Client :param network: the name of the network to use (mainnet, testnet, devnet) :type network: str @@ -99,7 +100,6 @@ def get_order_mask(self, **kwargs): return order_mask def OrderData(self, market_id: str, subaccount_id: str, order_hash: str, **kwargs): - order_mask = self.get_order_mask(**kwargs) return injective_exchange_tx_pb.OrderData( @@ -221,7 +221,6 @@ def BinaryOptionsOrder( quantity: float, **kwargs, ): - market = self.binary_option_markets[market_id] denom = kwargs.get("denom", None) @@ -280,8 +279,8 @@ def MsgExecuteContract(self, sender: str, contract: str, msg: str, **kwargs): sender=sender, contract=contract, msg=bytes(msg, "utf-8"), - funds=kwargs.get('funds') # funds is a list of cosmos_dot_base_dot_v1beta1_dot_coin__pb2.Coin. - # The coins in the list must be sorted in alphabetical order by denoms. + funds=kwargs.get("funds") # funds is a list of cosmos_dot_base_dot_v1beta1_dot_coin__pb2.Coin. + # The coins in the list must be sorted in alphabetical order by denoms. ) def MsgDeposit(self, sender: str, subaccount_id: str, amount: float, denom: str): @@ -338,9 +337,7 @@ def MsgCreateSpotMarketOrder( ), ) - def MsgCancelSpotOrder( - self, market_id: str, sender: str, subaccount_id: str, order_hash: str - ): + def MsgCancelSpotOrder(self, market_id: str, sender: str, subaccount_id: str, order_hash: str): return injective_exchange_tx_pb.MsgCancelSpotOrder( sender=sender, market_id=market_id, @@ -349,19 +346,13 @@ def MsgCancelSpotOrder( ) def MsgBatchCreateSpotLimitOrders(self, sender: str, orders: List): - return injective_exchange_tx_pb.MsgBatchCreateSpotLimitOrders( - sender=sender, orders=orders - ) + return injective_exchange_tx_pb.MsgBatchCreateSpotLimitOrders(sender=sender, orders=orders) def MsgBatchCancelSpotOrders(self, sender: str, data: List): - return injective_exchange_tx_pb.MsgBatchCancelSpotOrders( - sender=sender, data=data - ) + return injective_exchange_tx_pb.MsgBatchCancelSpotOrders(sender=sender, data=data) def MsgRewardsOptOut(self, sender: str): - return injective_exchange_tx_pb.MsgRewardsOptOut( - sender=sender - ) + return injective_exchange_tx_pb.MsgRewardsOptOut(sender=sender) def MsgCreateDerivativeLimitOrder( self, @@ -419,7 +410,6 @@ def MsgCreateBinaryOptionsLimitOrder( quantity: float, **kwargs, ): - return injective_exchange_tx_pb.MsgCreateBinaryOptionsLimitOrder( sender=sender, order=self.BinaryOptionsOrder( @@ -454,10 +444,7 @@ def MsgCreateBinaryOptionsMarketOrder( ), ) - def MsgCancelBinaryOptionsOrder( - self, sender: str, market_id: str, subaccount_id: str, order_hash: str - ): - + def MsgCancelBinaryOptionsOrder(self, sender: str, market_id: str, subaccount_id: str, order_hash: str): return injective_exchange_tx_pb.MsgCancelBinaryOptionsOrder( sender=sender, market_id=market_id, @@ -472,7 +459,6 @@ def MsgAdminUpdateBinaryOptionsMarket( status: str, **kwargs, ): - price_to_bytes = None if kwargs.get("settlement_price") is not None: @@ -491,9 +477,7 @@ def MsgAdminUpdateBinaryOptionsMarket( status=status, ) - def MsgRelayProviderPrices( - self, sender: str, provider: str, symbols: list, prices: list - ): + def MsgRelayProviderPrices(self, sender: str, provider: str, symbols: list, prices: list): oracle_prices = [] for price in prices: @@ -523,16 +507,13 @@ def MsgInstantBinaryOptionsMarketLaunch( min_quantity_tick_size: float, **kwargs, ): - scaled_maker_fee_rate = Decimal((maker_fee_rate * pow(10, 18))) maker_fee_to_bytes = bytes(str(scaled_maker_fee_rate), "utf-8") scaled_taker_fee_rate = Decimal((taker_fee_rate * pow(10, 18))) taker_fee_to_bytes = bytes(str(scaled_taker_fee_rate), "utf-8") - scaled_min_price_tick_size = Decimal( - (min_price_tick_size * pow(10, quote_decimals + 18)) - ) + scaled_min_price_tick_size = Decimal((min_price_tick_size * pow(10, quote_decimals + 18))) min_price_to_bytes = bytes(str(scaled_min_price_tick_size), "utf-8") scaled_min_quantity_tick_size = Decimal((min_quantity_tick_size * pow(10, 18))) @@ -555,9 +536,7 @@ def MsgInstantBinaryOptionsMarketLaunch( admin=kwargs.get("admin"), ) - def MsgCancelDerivativeOrder( - self, market_id: str, sender: str, subaccount_id: str, order_hash: str, **kwargs - ): + def MsgCancelDerivativeOrder(self, market_id: str, sender: str, subaccount_id: str, order_hash: str, **kwargs): order_mask = self.get_order_mask(**kwargs) return injective_exchange_tx_pb.MsgCancelDerivativeOrder( @@ -569,36 +548,24 @@ def MsgCancelDerivativeOrder( ) def MsgBatchCreateDerivativeLimitOrders(self, sender: str, orders: List): - return injective_exchange_tx_pb.MsgBatchCreateDerivativeLimitOrders( - sender=sender, orders=orders - ) + return injective_exchange_tx_pb.MsgBatchCreateDerivativeLimitOrders(sender=sender, orders=orders) def MsgBatchCancelDerivativeOrders(self, sender: str, data: List): - return injective_exchange_tx_pb.MsgBatchCancelDerivativeOrders( - sender=sender, data=data - ) + return injective_exchange_tx_pb.MsgBatchCancelDerivativeOrders(sender=sender, data=data) def MsgBatchUpdateOrders(self, sender: str, **kwargs): return injective_exchange_tx_pb.MsgBatchUpdateOrders( sender=sender, subaccount_id=kwargs.get("subaccount_id"), spot_market_ids_to_cancel_all=kwargs.get("spot_market_ids_to_cancel_all"), - derivative_market_ids_to_cancel_all=kwargs.get( - "derivative_market_ids_to_cancel_all" - ), + derivative_market_ids_to_cancel_all=kwargs.get("derivative_market_ids_to_cancel_all"), spot_orders_to_cancel=kwargs.get("spot_orders_to_cancel"), derivative_orders_to_cancel=kwargs.get("derivative_orders_to_cancel"), spot_orders_to_create=kwargs.get("spot_orders_to_create"), derivative_orders_to_create=kwargs.get("derivative_orders_to_create"), - binary_options_orders_to_cancel=kwargs.get( - "binary_options_orders_to_cancel" - ), - binary_options_market_ids_to_cancel_all=kwargs.get( - "binary_options_market_ids_to_cancel_all" - ), - binary_options_orders_to_create=kwargs.get( - "binary_options_orders_to_create" - ), + binary_options_orders_to_cancel=kwargs.get("binary_options_orders_to_cancel"), + binary_options_market_ids_to_cancel_all=kwargs.get("binary_options_market_ids_to_cancel_all"), + binary_options_orders_to_create=kwargs.get("binary_options_orders_to_create"), ) def MsgLiquidatePosition(self, sender: str, subaccount_id: str, market_id: str): @@ -672,7 +639,6 @@ def MsgExternalTransfer( ) def MsgBid(self, sender: str, bid_amount: float, round: float): - be_amount = Decimal(str(bid_amount)) * Decimal(f"1e{ADDITIONAL_CHAIN_FORMAT_DECIMALS}") return injective_auction_tx_pb.MsgBid( @@ -681,9 +647,7 @@ def MsgBid(self, sender: str, bid_amount: float, round: float): bid_amount=self.Coin(amount=int(be_amount), denom=INJ_DENOM), ) - def MsgGrantGeneric( - self, granter: str, grantee: str, msg_type: str, expire_in: int - ): + def MsgGrantGeneric(self, granter: str, grantee: str, msg_type: str, expire_in: int): auth = cosmos_authz_pb.GenericAuthorization(msg=msg_type) any_auth = any_pb2.Any() any_auth.Pack(auth, type_url_prefix="") @@ -693,9 +657,7 @@ def MsgGrantGeneric( expiration=timestamp_pb2.Timestamp(seconds=(int(time()) + expire_in)), ) - return cosmos_authz_tx_pb.MsgGrant( - granter=granter, grantee=grantee, grant=grant - ) + return cosmos_authz_tx_pb.MsgGrant(granter=granter, grantee=grantee, grant=grant) def MsgGrantTyped( self, @@ -762,9 +724,7 @@ def MsgGrantTyped( expiration=timestamp_pb2.Timestamp(seconds=(int(time()) + expire_in)), ) - return cosmos_authz_tx_pb.MsgGrant( - granter=granter, grantee=grantee, grant=grant - ) + return cosmos_authz_tx_pb.MsgGrant(granter=granter, grantee=grantee, grant=grant) def MsgExec(self, grantee: str, msgs: List): any_msgs: List[any_pb2.Any] = [] @@ -776,21 +736,12 @@ def MsgExec(self, grantee: str, msgs: List): return cosmos_authz_tx_pb.MsgExec(grantee=grantee, msgs=any_msgs) def MsgRevoke(self, granter: str, grantee: str, msg_type: str): - return cosmos_authz_tx_pb.MsgRevoke( - granter=granter, grantee=grantee, msg_type_url=msg_type - ) - - def MsgRelayPriceFeedPrice( - self, sender: list, base: list, quote: list, price: list - ): + return cosmos_authz_tx_pb.MsgRevoke(granter=granter, grantee=grantee, msg_type_url=msg_type) - return injective_oracle_tx_pb.MsgRelayPriceFeedPrice( - sender=sender, base=base, quote=quote, price=price - ) + def MsgRelayPriceFeedPrice(self, sender: list, base: list, quote: list, price: list): + return injective_oracle_tx_pb.MsgRelayPriceFeedPrice(sender=sender, base=base, quote=quote, price=price) - def MsgSendToEth( - self, denom: str, sender: str, eth_dest: str, amount: float, bridge_fee: float - ): + def MsgSendToEth(self, denom: str, sender: str, eth_dest: str, amount: float, bridge_fee: float): token = self.tokens[denom] be_amount = token.chain_formatted_value(human_readable_value=Decimal(str(amount))) be_bridge_fee = token.chain_formatted_value(human_readable_value=Decimal(str(bridge_fee))) @@ -802,10 +753,7 @@ def MsgSendToEth( bridge_fee=self.Coin(amount=int(be_bridge_fee), denom=token.denom), ) - def MsgDelegate( - self, delegator_address: str, validator_address: str, amount: float - ): - + def MsgDelegate(self, delegator_address: str, validator_address: str, amount: float): be_amount = Decimal(str(amount)) * Decimal(f"1e{ADDITIONAL_CHAIN_FORMAT_DECIMALS}") return cosmos_staking_tx_pb.MsgDelegate( @@ -823,7 +771,7 @@ def MsgCreateInsuranceFund( oracle_quote: str, oracle_type: int, expiry: int, - initial_deposit: int + initial_deposit: int, ): token = self.tokens[quote_denom] be_amount = token.chain_formatted_value(human_readable_value=Decimal(str(initial_deposit))) @@ -850,7 +798,9 @@ def MsgUnderwrite( be_amount = token.chain_formatted_value(human_readable_value=Decimal(str(amount))) return injective_insurance_tx_pb.MsgUnderwrite( - sender=sender, market_id=market_id, deposit=self.Coin(amount=int(be_amount), denom=token.denom), + sender=sender, + market_id=market_id, + deposit=self.Coin(amount=int(be_amount), denom=token.denom), ) def MsgRequestRedemption( @@ -860,26 +810,19 @@ def MsgRequestRedemption( share_denom: str, amount: int, ): - return injective_insurance_tx_pb.MsgRequestRedemption( - sender=sender, market_id=market_id, amount=self.Coin(amount=amount, denom=share_denom), + sender=sender, + market_id=market_id, + amount=self.Coin(amount=amount, denom=share_denom), ) - def MsgWithdrawDelegatorReward( - self, delegator_address: str, validator_address: str - ): - + def MsgWithdrawDelegatorReward(self, delegator_address: str, validator_address: str): return cosmos_distribution_tx_pb.MsgWithdrawDelegatorReward( delegator_address=delegator_address, validator_address=validator_address ) - def MsgWithdrawValidatorCommission( - self, validator_address: str - ): - - return cosmos_distribution_tx_pb.MsgWithdrawValidatorCommission( - validator_address=validator_address - ) + def MsgWithdrawValidatorCommission(self, validator_address: str): + return cosmos_distribution_tx_pb.MsgWithdrawValidatorCommission(validator_address=validator_address) def MsgVote( self, @@ -887,24 +830,21 @@ def MsgVote( voter: str, option: int, ): - - return cosmos_gov_tx_pb.MsgVote( - proposal_id=proposal_id, voter=voter, option=option - ) + return cosmos_gov_tx_pb.MsgVote(proposal_id=proposal_id, voter=voter, option=option) def MsgPrivilegedExecuteContract( - self, sender: str, contract: str, msg: str, **kwargs + self, sender: str, contract: str, msg: str, **kwargs ) -> injective_exchange_tx_pb.MsgPrivilegedExecuteContract: return injective_exchange_tx_pb.MsgPrivilegedExecuteContract( sender=sender, contract_address=contract, data=msg, - funds=kwargs.get('funds') # funds is a string of Coin strings, comma separated, - # e.g. 100000inj,20000000000usdt + funds=kwargs.get("funds") # funds is a string of Coin strings, comma separated, + # e.g. 100000inj,20000000000usdt ) def MsgInstantiateContract( - self, sender: str, admin: str, code_id: int, label: str, message: bytes, **kwargs + self, sender: str, admin: str, code_id: int, label: str, message: bytes, **kwargs ) -> wasm_tx_pb.MsgInstantiateContract: return wasm_tx_pb.MsgInstantiateContract( sender=sender, @@ -912,8 +852,8 @@ def MsgInstantiateContract( code_id=code_id, label=label, msg=message, - funds=kwargs.get('funds'), # funds is a list of cosmos_dot_base_dot_v1beta1_dot_coin__pb2.Coin. - # The coins in the list must be sorted in alphabetical order by denoms. + funds=kwargs.get("funds"), # funds is a list of cosmos_dot_base_dot_v1beta1_dot_coin__pb2.Coin. + # The coins in the list must be sorted in alphabetical order by denoms. ) # data field format: [request-msg-header][raw-byte-msg-response] @@ -924,6 +864,7 @@ def MsgResponses(response, simulation=False): data = response.result if not simulation: data = bytes.fromhex(data) + # fmt: off header_map = { "/injective.exchange.v1beta1.MsgCreateSpotLimitOrderResponse": injective_exchange_tx_pb.MsgCreateSpotLimitOrderResponse, @@ -982,7 +923,7 @@ def MsgResponses(response, simulation=False): "/injective.oracle.v1beta1.MsgRelayProviderPricesResponse": injective_oracle_tx_pb.MsgRelayProviderPrices, } - + # fmt: on msgs = [] for msg in data.msg_responses: msgs.append(header_map[msg.type_url].FromString(msg.value)) @@ -991,6 +932,7 @@ def MsgResponses(response, simulation=False): @staticmethod def UnpackMsgExecResponse(msg_type, data): + # fmt: off header_map = { "MsgCreateSpotLimitOrder": injective_exchange_tx_pb.MsgCreateSpotLimitOrderResponse, @@ -1035,6 +977,7 @@ def UnpackMsgExecResponse(msg_type, data): "MsgInstantBinaryOptionsMarketLaunch": injective_exchange_tx_pb.MsgInstantBinaryOptionsMarketLaunchResponse, } + # fmt: on responses = [header_map[msg_type].FromString(result) for result in data.results] return responses @@ -1042,7 +985,7 @@ def UnpackMsgExecResponse(msg_type, data): @staticmethod def UnpackTransactionMessages(transaction): meta_messages = json.loads(transaction.messages.decode()) - + # fmt: off header_map = { "/injective.exchange.v1beta1.MsgCreateSpotLimitOrder": injective_exchange_tx_pb.MsgCreateSpotLimitOrder, @@ -1101,7 +1044,7 @@ def UnpackTransactionMessages(transaction): "/injective.oracle.v1beta1.MsgRelayProviderPrices": injective_oracle_tx_pb.MsgRelayProviderPrices, } - + # fmt: on msgs = [] for msg in meta_messages: msg_as_string_dict = json.dumps(msg["value"]) @@ -1150,7 +1093,7 @@ def _initialize_markets_and_tokens_from_files(self): taker_fee_rate=None, service_provider_fee=None, min_price_tick_size=Decimal(str(configuration_section["min_price_tick_size"])), - min_quantity_tick_size=Decimal(str(configuration_section["min_quantity_tick_size"])) + min_quantity_tick_size=Decimal(str(configuration_section["min_quantity_tick_size"])), ) spot_markets[market.id] = market else: diff --git a/pyinjective/constant.py b/pyinjective/constant.py index 5e04c269..3e8d0d40 100644 --- a/pyinjective/constant.py +++ b/pyinjective/constant.py @@ -26,14 +26,8 @@ class Denom: def __init__( - self, - description: str, - base: int, - quote: int, - min_price_tick_size: float, - min_quantity_tick_size: float + self, description: str, base: int, quote: int, min_price_tick_size: float, min_quantity_tick_size: float ): - self.description = description self.base = base self.quote = quote diff --git a/pyinjective/core/broadcaster.py b/pyinjective/core/broadcaster.py index 2c6f6557..a84b38dd 100644 --- a/pyinjective/core/broadcaster.py +++ b/pyinjective/core/broadcaster.py @@ -13,7 +13,6 @@ class BroadcasterAccountConfig(ABC): - @property @abstractmethod def trading_injective_address(self) -> str: @@ -34,28 +33,28 @@ def messages_prepared_for_transaction(self, messages: List[any_pb2.Any]) -> List ... -class TransactionFeeCalculator (ABC): +class TransactionFeeCalculator(ABC): DEFAULT_GAS_PRICE = 500_000_000 @abstractmethod async def configure_gas_fee_for_transaction( - self, - transaction: Transaction, - private_key: PrivateKey, - public_key: PublicKey, + self, + transaction: Transaction, + private_key: PrivateKey, + public_key: PublicKey, ): ... class MsgBroadcasterWithPk: - def __init__( - self, - network: Network, - account_config: BroadcasterAccountConfig, - client: AsyncClient, - composer: Composer, - fee_calculator: TransactionFeeCalculator): + self, + network: Network, + account_config: BroadcasterAccountConfig, + client: AsyncClient, + composer: Composer, + fee_calculator: TransactionFeeCalculator, + ): self._network = network self._account_config = account_config self._client = client @@ -64,19 +63,16 @@ def __init__( @classmethod def new_using_simulation( - cls, - network: Network, - private_key: str, - client: Optional[AsyncClient] = None, - composer: Optional[Composer] = None, + cls, + network: Network, + private_key: str, + client: Optional[AsyncClient] = None, + composer: Optional[Composer] = None, ): client = client or AsyncClient(network=network) composer = composer or Composer(network=client.network.string()) account_config = StandardAccountBroadcasterConfig(private_key=private_key) - fee_calculator = SimulatedTransactionFeeCalculator( - client=client, - composer=composer - ) + fee_calculator = SimulatedTransactionFeeCalculator(client=client, composer=composer) instance = cls( network=network, account_config=account_config, @@ -88,19 +84,16 @@ def new_using_simulation( @classmethod def new_without_simulation( - cls, - network: Network, - private_key: str, - client: Optional[AsyncClient] = None, - composer: Optional[Composer] = None, + cls, + network: Network, + private_key: str, + client: Optional[AsyncClient] = None, + composer: Optional[Composer] = None, ): client = client or AsyncClient(network=network) composer = composer or Composer(network=client.network.string()) account_config = StandardAccountBroadcasterConfig(private_key=private_key) - fee_calculator = MessageBasedTransactionFeeCalculator( - client=client, - composer=composer - ) + fee_calculator = MessageBasedTransactionFeeCalculator(client=client, composer=composer) instance = cls( network=network, account_config=account_config, @@ -112,19 +105,16 @@ def new_without_simulation( @classmethod def new_for_grantee_account_using_simulation( - cls, - network: Network, - grantee_private_key: str, - client: Optional[AsyncClient] = None, - composer: Optional[Composer] = None, + cls, + network: Network, + grantee_private_key: str, + client: Optional[AsyncClient] = None, + composer: Optional[Composer] = None, ): client = client or AsyncClient(network=network) composer = composer or Composer(network=client.network.string()) account_config = GranteeAccountBroadcasterConfig(grantee_private_key=grantee_private_key, composer=composer) - fee_calculator = SimulatedTransactionFeeCalculator( - client=client, - composer=composer - ) + fee_calculator = SimulatedTransactionFeeCalculator(client=client, composer=composer) instance = cls( network=network, account_config=account_config, @@ -136,19 +126,16 @@ def new_for_grantee_account_using_simulation( @classmethod def new_for_grantee_account_without_simulation( - cls, - network: Network, - grantee_private_key: str, - client: Optional[AsyncClient] = None, - composer: Optional[Composer] = None, + cls, + network: Network, + grantee_private_key: str, + client: Optional[AsyncClient] = None, + composer: Optional[Composer] = None, ): client = client or AsyncClient(network=network) composer = composer or Composer(network=client.network.string()) account_config = GranteeAccountBroadcasterConfig(grantee_private_key=grantee_private_key, composer=composer) - fee_calculator = MessageBasedTransactionFeeCalculator( - client=client, - composer=composer - ) + fee_calculator = MessageBasedTransactionFeeCalculator(client=client, composer=composer) instance = cls( network=network, account_config=account_config, @@ -189,7 +176,6 @@ async def broadcast(self, messages: List[any_pb2.Any]): class StandardAccountBroadcasterConfig(BroadcasterAccountConfig): - def __init__(self, private_key: str): self._private_key = PrivateKey.from_hex(private_key) self._public_key = self._private_key.to_public_key() @@ -213,7 +199,6 @@ def messages_prepared_for_transaction(self, messages: List[any_pb2.Any]) -> List class GranteeAccountBroadcasterConfig(BroadcasterAccountConfig): - def __init__(self, grantee_private_key: str, composer: Composer): self._grantee_private_key = PrivateKey.from_hex(grantee_private_key) self._grantee_public_key = self._grantee_private_key.to_public_key() @@ -242,23 +227,23 @@ def messages_prepared_for_transaction(self, messages: List[any_pb2.Any]) -> List class SimulatedTransactionFeeCalculator(TransactionFeeCalculator): - def __init__( - self, - client: AsyncClient, - composer: Composer, - gas_price: Optional[int] = None, - gas_limit_adjustment_multiplier: Optional[Decimal] = None): + self, + client: AsyncClient, + composer: Composer, + gas_price: Optional[int] = None, + gas_limit_adjustment_multiplier: Optional[Decimal] = None, + ): self._client = client self._composer = composer self._gas_price = gas_price or self.DEFAULT_GAS_PRICE self._gas_limit_adjustment_multiplier = gas_limit_adjustment_multiplier or Decimal("1.3") async def configure_gas_fee_for_transaction( - self, - transaction: Transaction, - private_key: PrivateKey, - public_key: PublicKey, + self, + transaction: Transaction, + private_key: PrivateKey, + public_key: PublicKey, ): sim_sign_doc = transaction.get_sign_doc(public_key) sim_sig = private_key.sign(sim_sign_doc.SerializeToString()) @@ -285,20 +270,16 @@ async def configure_gas_fee_for_transaction( class MessageBasedTransactionFeeCalculator(TransactionFeeCalculator): TRANSACTION_GAS_LIMIT = 60_000 - def __init__( - self, - client: AsyncClient, - composer: Composer, - gas_price: Optional[int] = None): + def __init__(self, client: AsyncClient, composer: Composer, gas_price: Optional[int] = None): self._client = client self._composer = composer self._gas_price = gas_price or self.DEFAULT_GAS_PRICE async def configure_gas_fee_for_transaction( - self, - transaction: Transaction, - private_key: PrivateKey, - public_key: PublicKey, + self, + transaction: Transaction, + private_key: PrivateKey, + public_key: PublicKey, ): messages_gas_limit = math.ceil(self._calculate_gas_limit(messages=transaction.msgs)) transaction_gas_limit = messages_gas_limit + self.TRANSACTION_GAS_LIMIT diff --git a/pyinjective/core/gas_limit_estimator.py b/pyinjective/core/gas_limit_estimator.py index 8ec54acc..2bc5656c 100644 --- a/pyinjective/core/gas_limit_estimator.py +++ b/pyinjective/core/gas_limit_estimator.py @@ -19,9 +19,14 @@ def applies_to(cls, message: any_pb2.Any) -> bool: @classmethod def for_message(cls, message: any_pb2.Any): - estimator_class = next((estimator_subclass for estimator_subclass in cls.__subclasses__() - if estimator_subclass.applies_to(message=message)), - None) + estimator_class = next( + ( + estimator_subclass + for estimator_subclass in cls.__subclasses__() + if estimator_subclass.applies_to(message=message) + ), + None, + ) if estimator_class is None: estimator = DefaultGasLimitEstimator() else: @@ -180,15 +185,21 @@ def gas_limit(self) -> int: total += len(self._message.derivative_orders_to_cancel) * self.DERIVATIVE_ORDER_CANCELATION_GAS_LIMIT total += len(self._message.binary_options_orders_to_cancel) * self.DERIVATIVE_ORDER_CANCELATION_GAS_LIMIT - total += (len(self._message.spot_market_ids_to_cancel_all) - * self.CANCEL_ALL_SPOT_MARKET_GAS_LIMIT - * self.AVERAGE_CANCEL_ALL_AFFECTED_ORDERS) - total += (len(self._message.derivative_market_ids_to_cancel_all) - * self.CANCEL_ALL_DERIVATIVE_MARKET_GAS_LIMIT - * self.AVERAGE_CANCEL_ALL_AFFECTED_ORDERS) - total += (len(self._message.binary_options_market_ids_to_cancel_all) - * self.CANCEL_ALL_DERIVATIVE_MARKET_GAS_LIMIT - * self.AVERAGE_CANCEL_ALL_AFFECTED_ORDERS) + total += ( + len(self._message.spot_market_ids_to_cancel_all) + * self.CANCEL_ALL_SPOT_MARKET_GAS_LIMIT + * self.AVERAGE_CANCEL_ALL_AFFECTED_ORDERS + ) + total += ( + len(self._message.derivative_market_ids_to_cancel_all) + * self.CANCEL_ALL_DERIVATIVE_MARKET_GAS_LIMIT + * self.AVERAGE_CANCEL_ALL_AFFECTED_ORDERS + ) + total += ( + len(self._message.binary_options_market_ids_to_cancel_all) + * self.CANCEL_ALL_DERIVATIVE_MARKET_GAS_LIMIT + * self.AVERAGE_CANCEL_ALL_AFFECTED_ORDERS + ) return total @@ -207,8 +218,9 @@ def applies_to(cls, message: any_pb2.Any) -> bool: return cls.message_type(message=message).endswith("MsgExec") def gas_limit(self) -> int: - total = sum([GasLimitEstimator.for_message(message=inner_message).gas_limit() - for inner_message in self._message.msgs]) + total = sum( + [GasLimitEstimator.for_message(message=inner_message).gas_limit() for inner_message in self._message.msgs] + ) total += self.DEFAULT_GAS_LIMIT return total @@ -218,7 +230,6 @@ def _message_class(self, message: any_pb2.Any): class PrivilegedExecuteContractGasLimitEstimator(GasLimitEstimator): - def __init__(self, message: any_pb2.Any): self._message = self._parsed_message(message=message) @@ -234,7 +245,6 @@ def _message_class(self, message: any_pb2.Any): class ExecuteContractGasLimitEstimator(GasLimitEstimator): - def __init__(self, message: any_pb2.Any): self._message = self._parsed_message(message=message) @@ -250,7 +260,6 @@ def _message_class(self, message: any_pb2.Any): class GeneralWasmGasLimitEstimator(GasLimitEstimator): - def __init__(self, message: any_pb2.Any): self._message = self._parsed_message(message=message) @@ -266,7 +275,6 @@ def _message_class(self, message: any_pb2.Any): class GovernanceGasLimitEstimator(GasLimitEstimator): - def __init__(self, message: any_pb2.Any): self._message = self._parsed_message(message=message) diff --git a/pyinjective/core/market.py b/pyinjective/core/market.py index a544880b..58e648bb 100644 --- a/pyinjective/core/market.py +++ b/pyinjective/core/market.py @@ -85,10 +85,7 @@ def margin_to_chain_format(self, human_readable_value: Decimal) -> Decimal: return extended_chain_formatted_value def calculate_margin_in_chain_format( - self, - human_readable_quantity: Decimal, - human_readable_price: Decimal, - leverage: Decimal + self, human_readable_quantity: Decimal, human_readable_price: Decimal, leverage: Decimal ) -> Decimal: chain_formatted_quantity = human_readable_quantity chain_formatted_price = human_readable_price * Decimal(f"1e{self.quote_token.decimals}") @@ -131,9 +128,9 @@ class BinaryOptionMarket: def quantity_to_chain_format(self, human_readable_value: Decimal, special_denom: Optional[Denom] = None) -> Decimal: # Binary option markets do not have a base market to provide the number of decimals decimals = 0 if special_denom is None else special_denom.base - min_quantity_tick_size = (self.min_quantity_tick_size - if special_denom is None - else special_denom.min_quantity_tick_size) + min_quantity_tick_size = ( + self.min_quantity_tick_size if special_denom is None else special_denom.min_quantity_tick_size + ) chain_formatted_value = human_readable_value * Decimal(f"1e{decimals}") quantized_value = chain_formatted_value // min_quantity_tick_size * min_quantity_tick_size extended_chain_formatted_value = quantized_value * Decimal(f"1e{ADDITIONAL_CHAIN_FORMAT_DECIMALS}") @@ -150,21 +147,21 @@ def price_to_chain_format(self, human_readable_value: Decimal, special_denom: Op return extended_chain_formatted_value def calculate_margin_in_chain_format( - self, - human_readable_quantity: Decimal, - human_readable_price: Decimal, - is_buy: bool, - special_denom: Optional[Denom] = None, + self, + human_readable_quantity: Decimal, + human_readable_price: Decimal, + is_buy: bool, + special_denom: Optional[Denom] = None, ) -> Decimal: quantity_decimals = 0 if special_denom is None else special_denom.base price_decimals = self.quote_token.decimals if special_denom is None else special_denom.quote - min_quantity_tick_size = (self.min_quantity_tick_size - if special_denom is None - else special_denom.min_quantity_tick_size) + min_quantity_tick_size = ( + self.min_quantity_tick_size if special_denom is None else special_denom.min_quantity_tick_size + ) price = human_readable_price if is_buy else 1 - human_readable_price chain_formatted_quantity = human_readable_quantity * Decimal(f"1e{quantity_decimals}") chain_formatted_price = price * Decimal(f"1e{price_decimals}") - margin = (chain_formatted_price * chain_formatted_quantity) + margin = chain_formatted_price * chain_formatted_quantity # We are using the min_quantity_tick_size to quantize the margin because that is the way margin is validated # in the chain (it might be changed to a min_notional in the future) quantized_margin = (margin // min_quantity_tick_size) * min_quantity_tick_size diff --git a/pyinjective/core/network.py b/pyinjective/core/network.py index 6b70fca6..930fafe0 100644 --- a/pyinjective/core/network.py +++ b/pyinjective/core/network.py @@ -27,7 +27,6 @@ async def exchange_metadata(self, metadata_query_provider: Callable) -> Tuple[Tu class KubernetesLoadBalancedCookieAssistant(CookieAssistant): - def __init__(self): self._chain_cookie: Optional[str] = None self._exchange_cookie: Optional[str] = None @@ -84,15 +83,13 @@ def _is_cookie_expired(self, cookie_data: str) -> bool: cookie = SimpleCookie() cookie.load(cookie_data) - expiration_time = datetime.datetime.strptime(cookie["GCLB"]["expires"], - "%a, %d-%b-%Y %H:%M:%S %Z").timestamp() + expiration_time = datetime.datetime.strptime(cookie["GCLB"]["expires"], "%a, %d-%b-%Y %H:%M:%S %Z").timestamp() timestamp_diff = expiration_time - time.time() return timestamp_diff < self.SESSION_RENEWAL_OFFSET class BareMetalLoadBalancedCookieAssistant(CookieAssistant): - def __init__(self): self._chain_cookie: Optional[str] = None self._exchange_cookie: Optional[str] = None @@ -239,7 +236,7 @@ def testnet(cls, node="lb"): fee_denom="inj", env="testnet", cookie_assistant=cookie_assistant, - use_secure_connection=use_secure_connection + use_secure_connection=use_secure_connection, ) @classmethod @@ -309,16 +306,16 @@ def local(cls): @classmethod def custom( - cls, - lcd_endpoint, - tm_websocket_endpoint, - grpc_endpoint, - grpc_exchange_endpoint, - grpc_explorer_endpoint, - chain_id, - env, - cookie_assistant: Optional[CookieAssistant] = None, - use_secure_connection: bool = False, + cls, + lcd_endpoint, + tm_websocket_endpoint, + grpc_endpoint, + grpc_exchange_endpoint, + grpc_explorer_endpoint, + chain_id, + env, + cookie_assistant: Optional[CookieAssistant] = None, + use_secure_connection: bool = False, ): assistant = cookie_assistant or DisabledCookieAssistant() return cls( @@ -331,7 +328,7 @@ def custom( fee_denom="inj", env=env, cookie_assistant=assistant, - use_secure_connection=use_secure_connection + use_secure_connection=use_secure_connection, ) def string(self): diff --git a/pyinjective/orderhash.py b/pyinjective/orderhash.py index 9fc850e6..dd6a43c6 100644 --- a/pyinjective/orderhash.py +++ b/pyinjective/orderhash.py @@ -43,14 +43,14 @@ class DerivativeOrder(EIP712Message): # domain_separator = EIP712_domain.hash_struct() -order_type_dict = {0: '\x00', 1: '\x01', 2: '\x02', 3: '\x03', 4: '\x04', 5: '\x05', 6: '\x06', 7: '\x07', 8: '\x08'} +order_type_dict = {0: "\x00", 1: "\x01", 2: "\x02", 3: "\x03", 4: "\x04", 5: "\x05", 6: "\x06", 7: "\x07", 8: "\x08"} class OrderHashResponse: def __init__( - self, - spot: [str] = None, - derivative: [str] = None, + self, + spot: [str] = None, + derivative: [str] = None, ): self.spot = spot self.derivative = derivative @@ -58,17 +58,17 @@ def __init__( class OrderHashManager: def __init__( - self, - address, - network, - subaccount_indexes: [int] = None, + self, + address, + network, + subaccount_indexes: [int] = None, ): self.address = address self.subacc_nonces = dict() for i in subaccount_indexes: subaccount_id = address.get_subaccount_id(index=i) - url = network.lcd_endpoint + '/injective/exchange/v1beta1/exchange/' + subaccount_id + url = network.lcd_endpoint + "/injective/exchange/v1beta1/exchange/" + subaccount_id res = requests.get(url=url) nonce = res.json()["nonce"] self.subacc_nonces[i] = [subaccount_id, nonce + 1] @@ -96,7 +96,7 @@ def compute_order_hashes(self, spot_orders, derivative_orders, subaccount_index) def param_to_backend_go(param) -> int: go_param = Decimal(param) / pow(10, 18) - return format(go_param, '.18f') + return format(go_param, ".18f") def parse_order_type(order): @@ -104,7 +104,7 @@ def parse_order_type(order): def build_eip712_msg(order, nonce): - if order.__class__.__name__ == 'SpotOrder': + if order.__class__.__name__ == "SpotOrder": go_price = param_to_backend_go(order.order_info.price) go_trigger_price = param_to_backend_go(order.trigger_price) go_quantity = param_to_backend_go(order.order_info.quantity) @@ -115,13 +115,13 @@ def build_eip712_msg(order, nonce): SubaccountId=order.order_info.subaccount_id, FeeRecipient=order.order_info.fee_recipient, Price=go_price, - Quantity=go_quantity + Quantity=go_quantity, ), Salt=str(nonce), OrderType=go_order_type, - TriggerPrice=go_trigger_price + TriggerPrice=go_trigger_price, ) - if order.__class__.__name__ == 'DerivativeOrder': + if order.__class__.__name__ == "DerivativeOrder": go_price = param_to_backend_go(order.order_info.price) go_trigger_price = param_to_backend_go(order.trigger_price) go_quantity = param_to_backend_go(order.order_info.quantity) @@ -133,12 +133,12 @@ def build_eip712_msg(order, nonce): SubaccountId=order.order_info.subaccount_id, FeeRecipient=order.order_info.fee_recipient, Price=go_price, - Quantity=go_quantity + Quantity=go_quantity, ), Salt=str(nonce), OrderType=go_order_type, TriggerPrice=go_trigger_price, - Margin=go_margin + Margin=go_margin, ) diff --git a/pyinjective/sendtocosmos.py b/pyinjective/sendtocosmos.py index 208dd078..043910b6 100644 --- a/pyinjective/sendtocosmos.py +++ b/pyinjective/sendtocosmos.py @@ -9,23 +9,23 @@ def __init__(self, network: str): self.network = network def sendToInjective( - self, - ethereum_endpoint: str, - private_key: str, - token_contract: str, - receiver: str, - amount: float, - maxFeePerGas: int, - maxPriorityFeePerGas: int, - peggo_abi: str, - data: str, - decimals=18 + self, + ethereum_endpoint: str, + private_key: str, + token_contract: str, + receiver: str, + amount: float, + maxFeePerGas: int, + maxPriorityFeePerGas: int, + peggo_abi: str, + data: str, + decimals=18, ): - if self.network == 'testnet': + if self.network == "testnet": peggy_proxy_address = "0xd2C6753F6B1783EF0a3857275e16e79D91b539a3" - elif self.network == 'mainnet': + elif self.network == "mainnet": peggy_proxy_address = "0xF955C57f9EA9Dc8781965FEaE0b6A2acE2BAD6f3" - elif self.network == 'devnet': + elif self.network == "devnet": peggy_proxy_address = "0x4F38F75606d046819638f909b66B112aF1095e8d" else: LoggerProvider().logger_for_class(logging_class=self.__class__).info("Network is not supported") @@ -39,7 +39,7 @@ def sendToInjective( receiver_ethereum_address = Address.get_ethereum_address(receiver_address) receiver_address_checksum = web3.to_checksum_address(receiver_ethereum_address) receiver_slice = receiver_address_checksum[2:] - receiver_padded_address = '0x' + receiver_slice.zfill(64) + receiver_padded_address = "0x" + receiver_slice.zfill(64) destination = web3.to_bytes(hexstr=receiver_padded_address) @@ -50,24 +50,18 @@ def sendToInjective( amount_to_send = int(amount * pow(10, decimals)) gas = contract.functions.sendToInjective( - token_contract_address, - destination, - amount_to_send, - data - ).estimate_gas({'from': sender_address_checksum}) + token_contract_address, destination, amount_to_send, data + ).estimate_gas({"from": sender_address_checksum}) transaction_body = { - 'nonce': nonce, - 'gas': gas, - 'maxFeePerGas': web3.to_wei(maxFeePerGas, 'gwei'), - 'maxPriorityFeePerGas': web3.to_wei(maxPriorityFeePerGas, 'gwei'), + "nonce": nonce, + "gas": gas, + "maxFeePerGas": web3.to_wei(maxFeePerGas, "gwei"), + "maxPriorityFeePerGas": web3.to_wei(maxPriorityFeePerGas, "gwei"), } tx = contract.functions.sendToInjective( - token_contract_address, - destination, - amount_to_send, - data + token_contract_address, destination, amount_to_send, data ).buildTransaction(transaction_body) signed_tx = web3.eth.account.signTransaction(tx, private_key=private_key) @@ -75,8 +69,10 @@ def sendToInjective( try: tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction) LoggerProvider().logger_for_class(logging_class=self.__class__).info( - f"Transferred {amount} {token_contract} from {sender_ethereum_address} to {receiver}") + f"Transferred {amount} {token_contract} from {sender_ethereum_address} to {receiver}" + ) LoggerProvider().logger_for_class(logging_class=self.__class__).info( - "Transaction hash: {}".format(Web3.to_hex(tx_hash))) + "Transaction hash: {}".format(Web3.to_hex(tx_hash)) + ) except Exception as e: LoggerProvider().logger_for_class(logging_class=self.__class__).info("Transaction failed {}".format(e)) diff --git a/pyinjective/transaction.py b/pyinjective/transaction.py index 58348771..f54d5649 100644 --- a/pyinjective/transaction.py +++ b/pyinjective/transaction.py @@ -20,7 +20,7 @@ def __init__( fee: List[Coin] = None, gas: int = 0, memo: str = "", - timeout_height: int = 0 + timeout_height: int = 0, ): self.msgs = self.__convert_msgs(msgs) if msgs is not None else [] self.account_num = account_num @@ -75,11 +75,7 @@ def with_timeout_height(self, timeout_height: int) -> "Transaction": return self def __generate_info(self, public_key: PublicKey = None) -> Tuple[str, str]: - body = cosmos_tx_type.TxBody( - messages=self.msgs, - memo=self.memo, - timeout_height=self.timeout_height - ) + body = cosmos_tx_type.TxBody(messages=self.msgs, memo=self.memo, timeout_height=self.timeout_height) body_bytes = body.SerializeToString() mode_info = cosmos_tx_type.ModeInfo(single=cosmos_tx_type.ModeInfo.Single(mode=tx_sign.SIGN_MODE_DIRECT)) diff --git a/pyinjective/utils/fetch_metadata.py b/pyinjective/utils/fetch_metadata.py index 71d008a8..715e43c5 100644 --- a/pyinjective/utils/fetch_metadata.py +++ b/pyinjective/utils/fetch_metadata.py @@ -20,62 +20,67 @@ """ -testnet_denom_output = '' -mainnet_denom_output = '' +testnet_denom_output = "" +mainnet_denom_output = "" async def fetch_denom(network) -> str: - denom_output = '' + denom_output = "" symbols = {} # fetch meta data for spot markets client = AsyncClient(network) - status = 'active' + status = "active" mresp = await client.get_spot_markets(market_status=status) for market in mresp.markets: # append symbols to dict - if market.base_token_meta.SerializeToString() != '': + if market.base_token_meta.SerializeToString() != "": symbols[market.base_token_meta.symbol] = (market.base_denom, market.base_token_meta.decimals) - if market.quote_token_meta.SerializeToString() != '': + if market.quote_token_meta.SerializeToString() != "": symbols[market.quote_token_meta.symbol] = (market.base_denom, market.quote_token_meta.decimals) # format into ini entry - min_display_price_tick_size = (float(market.min_price_tick_size) - / pow(10, market.quote_token_meta.decimals - market.base_token_meta.decimals)) + min_display_price_tick_size = float(market.min_price_tick_size) / pow( + 10, market.quote_token_meta.decimals - market.base_token_meta.decimals + ) min_display_quantity_tick_size = float(market.min_quantity_tick_size) / pow(10, market.base_token_meta.decimals) config = metadata_template.format( market.market_id, - network.string().capitalize(), 'Spot', market.ticker, + network.string().capitalize(), + "Spot", + market.ticker, market.base_token_meta.decimals, market.quote_token_meta.decimals, market.min_price_tick_size, min_display_price_tick_size, market.min_quantity_tick_size, - min_display_quantity_tick_size + min_display_quantity_tick_size, ) denom_output += config # fetch meta data for derivative markets client = AsyncClient(network) - status = 'active' + status = "active" mresp = await client.get_derivative_markets(market_status=status) for market in mresp.markets: # append symbols to dict - if market.quote_token_meta.SerializeToString() != '': + if market.quote_token_meta.SerializeToString() != "": symbols[market.quote_token_meta.symbol] = (market.quote_denom, market.quote_token_meta.decimals) # format into ini entry min_display_price_tick_size = float(market.min_price_tick_size) / pow(10, market.quote_token_meta.decimals) config = metadata_template.format( market.market_id, - network.string().capitalize(), 'Derivative', market.ticker, + network.string().capitalize(), + "Derivative", + market.ticker, 0, market.quote_token_meta.decimals, market.min_price_tick_size, min_display_price_tick_size, market.min_quantity_tick_size, - market.min_quantity_tick_size + market.min_quantity_tick_size, ) denom_output += config @@ -99,5 +104,6 @@ async def main() -> None: with open("../denoms_mainnet.ini", "w") as text_file: text_file.write(data) -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/pyinjective/utils/logger.py b/pyinjective/utils/logger.py index 7562e95d..01f1dd09 100644 --- a/pyinjective/utils/logger.py +++ b/pyinjective/utils/logger.py @@ -8,7 +8,6 @@ class LoggerProvider: - def logger(self) -> Logger: return logging.getLogger(__name__) diff --git a/pyinjective/utils/metadata_validation.py b/pyinjective/utils/metadata_validation.py index ef357114..892ef8d5 100644 --- a/pyinjective/utils/metadata_validation.py +++ b/pyinjective/utils/metadata_validation.py @@ -27,45 +27,79 @@ def find_metadata_inconsistencies(network: Network) -> Tuple[List[Any]]: denom = constant.Denom.load_market(network=network.string(), market_id=config_key) if config_key in spot_markets: market: SpotMarket = spot_markets[config_key] - if (market.base_token.decimals != denom.base - or market.quote_token.decimals != denom.quote - or market.min_price_tick_size != Decimal(str(denom.min_price_tick_size)) - or market.min_quantity_tick_size != Decimal(str(denom.min_quantity_tick_size))): - markets_with_diffs.append([ - {"denom-market": config_key, "base_decimals": denom.base, "quote_decimals": denom.quote, - "min_quantity_tick_size": denom.min_quantity_tick_size, - "min_price_tick_size": denom.min_price_tick_size}, - {"newer-market": market.id, "base_decimals": market.base_token.decimals, - "quote_decimals": market.quote_token.decimals, - "min_quantity_tick_size": float(market.min_quantity_tick_size), - "min_price_tick_size": float(market.min_price_tick_size), "ticker": market.ticker}, - ]) + if ( + market.base_token.decimals != denom.base + or market.quote_token.decimals != denom.quote + or market.min_price_tick_size != Decimal(str(denom.min_price_tick_size)) + or market.min_quantity_tick_size != Decimal(str(denom.min_quantity_tick_size)) + ): + markets_with_diffs.append( + [ + { + "denom-market": config_key, + "base_decimals": denom.base, + "quote_decimals": denom.quote, + "min_quantity_tick_size": denom.min_quantity_tick_size, + "min_price_tick_size": denom.min_price_tick_size, + }, + { + "newer-market": market.id, + "base_decimals": market.base_token.decimals, + "quote_decimals": market.quote_token.decimals, + "min_quantity_tick_size": float(market.min_quantity_tick_size), + "min_price_tick_size": float(market.min_price_tick_size), + "ticker": market.ticker, + }, + ] + ) elif config_key in derivative_markets: market: DerivativeMarket = derivative_markets[config_key] - if (market.quote_token.decimals != denom.quote - or market.min_price_tick_size != Decimal(str(denom.min_price_tick_size)) - or market.min_quantity_tick_size != Decimal(str(denom.min_quantity_tick_size))): - markets_with_diffs.append([ - {"denom-market": config_key, "quote_decimals": denom.quote, - "min_quantity_tick_size": denom.min_quantity_tick_size, - "min_price_tick_size": denom.min_price_tick_size}, - {"newer-market": market.id, "quote_decimals": market.quote_token.decimals, - "min_quantity_tick_size": float(market.min_quantity_tick_size), - "min_price_tick_size": float(market.min_price_tick_size), "ticker": market.ticker}, - ]) + if ( + market.quote_token.decimals != denom.quote + or market.min_price_tick_size != Decimal(str(denom.min_price_tick_size)) + or market.min_quantity_tick_size != Decimal(str(denom.min_quantity_tick_size)) + ): + markets_with_diffs.append( + [ + { + "denom-market": config_key, + "quote_decimals": denom.quote, + "min_quantity_tick_size": denom.min_quantity_tick_size, + "min_price_tick_size": denom.min_price_tick_size, + }, + { + "newer-market": market.id, + "quote_decimals": market.quote_token.decimals, + "min_quantity_tick_size": float(market.min_quantity_tick_size), + "min_price_tick_size": float(market.min_price_tick_size), + "ticker": market.ticker, + }, + ] + ) elif config_key in binary_option_markets: market: BinaryOptionMarket = binary_option_markets[config_key] - if (market.quote_token.decimals != denom.quote - or market.min_price_tick_size != Decimal(str(denom.min_price_tick_size)) - or market.min_quantity_tick_size != Decimal(str(denom.min_quantity_tick_size))): - markets_with_diffs.append([ - {"denom-market": config_key, "quote_decimals": denom.quote, - "min_quantity_tick_size": denom.min_quantity_tick_size, - "min_price_tick_size": denom.min_price_tick_size}, - {"newer-market": market.id, "quote_decimals": market.quote_token.decimals, - "min_quantity_tick_size": float(market.min_quantity_tick_size), - "min_price_tick_size": float(market.min_price_tick_size), "ticker": market.ticker}, - ]) + if ( + market.quote_token.decimals != denom.quote + or market.min_price_tick_size != Decimal(str(denom.min_price_tick_size)) + or market.min_quantity_tick_size != Decimal(str(denom.min_quantity_tick_size)) + ): + markets_with_diffs.append( + [ + { + "denom-market": config_key, + "quote_decimals": denom.quote, + "min_quantity_tick_size": denom.min_quantity_tick_size, + "min_price_tick_size": denom.min_price_tick_size, + }, + { + "newer-market": market.id, + "quote_decimals": market.quote_token.decimals, + "min_quantity_tick_size": float(market.min_quantity_tick_size), + "min_price_tick_size": float(market.min_price_tick_size), + "ticker": market.ticker, + }, + ] + ) else: markets_not_found.append({"denom-market": config_key, "description": denom.description}) @@ -76,24 +110,28 @@ def find_metadata_inconsistencies(network: Network) -> Tuple[List[Any]]: peggy_denom, decimals = constant.Denom.load_peggy_denom(network=network.string(), symbol=config_key) if config_key in all_tokens: token = all_tokens[config_key] - if (token.denom != peggy_denom - or token.decimals != decimals): - peggy_denoms_with_diffs.append([ - {"denom_token": config_key, "peggy_denom": peggy_denom, "decimals": decimals}, - {"newer_token": token.symbol, "peggy_denom": token.denom, "decimals": token.decimals} - ]) + if token.denom != peggy_denom or token.decimals != decimals: + peggy_denoms_with_diffs.append( + [ + {"denom_token": config_key, "peggy_denom": peggy_denom, "decimals": decimals}, + {"newer_token": token.symbol, "peggy_denom": token.denom, "decimals": token.decimals}, + ] + ) else: peggy_denoms_not_found.append( - {"denom_token": config_key, "peggy_denom": peggy_denom, "decimals": decimals}) + {"denom_token": config_key, "peggy_denom": peggy_denom, "decimals": decimals} + ) return markets_with_diffs, markets_not_found, peggy_denoms_with_diffs, peggy_denoms_not_found def print_metadata_mismatches(network: Network): - (markets_with_diffs, - markets_not_found, - peggy_denoms_with_diffs, - peggy_denoms_not_found) = find_metadata_inconsistencies(network=network) + ( + markets_with_diffs, + markets_not_found, + peggy_denoms_with_diffs, + peggy_denoms_not_found, + ) = find_metadata_inconsistencies(network=network) for diff_pair in markets_with_diffs: print(f"{diff_pair[0]}\n{diff_pair[1]}") diff --git a/pyinjective/wallet.py b/pyinjective/wallet.py index 06e3f02f..991ba744 100644 --- a/pyinjective/wallet.py +++ b/pyinjective/wallet.py @@ -255,39 +255,40 @@ def to_hex(self) -> str: def get_subaccount_id(self, index: int) -> str: """Return a hex representation of address""" - id = index.to_bytes(12, byteorder='big').hex() - return '0x' + self.addr.hex() + id + id = index.to_bytes(12, byteorder="big").hex() + return "0x" + self.addr.hex() + id def get_ethereum_address(self) -> str: - return '0x' + self.addr.hex() + return "0x" + self.addr.hex() async def async_init_num_seq(self, lcd_endpoint: str) -> "Address": async with aiohttp.ClientSession() as session: async with session.request( - 'GET', lcd_endpoint + '/cosmos/auth/v1beta1/accounts/' + self.to_acc_bech32(), - headers={'Accept-Encoding': 'application/json'}, + "GET", + lcd_endpoint + "/cosmos/auth/v1beta1/accounts/" + self.to_acc_bech32(), + headers={"Accept-Encoding": "application/json"}, ) as response: if response.status != 200: print(await response.text()) raise ValueError("HTTP response status", response.status) resp = json.loads(await response.text()) - acc = resp['account']['base_account'] - self.number = int(acc['account_number']) - self.sequence = int(acc['sequence']) + acc = resp["account"]["base_account"] + self.number = int(acc["account_number"]) + self.sequence = int(acc["sequence"]) return self def init_num_seq(self, lcd_endpoint: str) -> "Address": response = requests.get( url=f"{lcd_endpoint}/cosmos/auth/v1beta1/accounts/{self.to_acc_bech32()}", - headers={'Accept-Encoding': 'application/json'} + headers={"Accept-Encoding": "application/json"}, ) if response.status_code != 200: raise ValueError("HTTP response status", response.status_code) resp = json.loads(response.text) - acc = resp['account']['base_account'] - self.number = int(acc['account_number']) - self.sequence = int(acc['sequence']) + acc = resp["account"]["base_account"] + self.number = int(acc["account_number"]) + self.sequence = int(acc["sequence"]) return self def get_sequence(self): diff --git a/pyproject.toml b/pyproject.toml index 06697c52..67d925f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,7 @@ requests-mock = "*" pre-commit = "^3.4.0" flakeheaven = "^3.3.0" isort = "^5.12.0" +black = "^23.9.1" [tool.flakeheaven] @@ -67,6 +68,20 @@ line_length = 120 skip_glob = ["pyinjective/proto/*", ".idea/*"] +[tool.black] +line-length = 120 +target-version = ["py39", "py310", "py311"] +# 'extend-exclude' excludes files or directories in addition to the defaults +extend-exclude = ''' +# A regex preceded with ^/ will apply only to files and directories +# in the root of the project. +( + ^pyinjective/proto/.* + | \.idea/.* +) +''' + + [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" diff --git a/tests/core/test_gas_limit_estimator.py b/tests/core/test_gas_limit_estimator.py index da043c2a..a2838f0b 100644 --- a/tests/core/test_gas_limit_estimator.py +++ b/tests/core/test_gas_limit_estimator.py @@ -10,21 +10,15 @@ class TestGasLimitEstimator: - def test_estimation_for_message_without_applying_rule(self): composer = Composer(network="testnet") - message = composer.MsgSend( - from_address="from_address", - to_address="to_address", - amount=1, - denom='INJ' - ) + message = composer.MsgSend(from_address="from_address", to_address="to_address", amount=1, denom="INJ") estimator = GasLimitEstimator.for_message(message=message) expected_message_gas_limit = 150_000 - assert(expected_message_gas_limit == estimator.gas_limit()) + assert expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_create_spot_limit_orders(self): spot_market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -37,7 +31,7 @@ def test_estimation_for_batch_create_spot_limit_orders(self): price=5, quantity=1, is_buy=True, - is_po=False + is_po=False, ), composer.SpotOrder( market_id=spot_market_id, @@ -46,19 +40,16 @@ def test_estimation_for_batch_create_spot_limit_orders(self): price=4, quantity=1, is_buy=True, - is_po=False + is_po=False, ), ] - message = composer.MsgBatchCreateSpotLimitOrders( - sender="sender", - orders=orders - ) + message = composer.MsgBatchCreateSpotLimitOrders(sender="sender", orders=orders) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 45000 expected_message_gas_limit = 5000 - assert((expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_cancel_spot_orders(self): spot_market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -67,29 +58,26 @@ def test_estimation_for_batch_cancel_spot_orders(self): composer.OrderData( market_id=spot_market_id, subaccount_id="subaccount_id", - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d", ), composer.OrderData( market_id=spot_market_id, subaccount_id="subaccount_id", - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", ), composer.OrderData( market_id=spot_market_id, subaccount_id="subaccount_id", - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] - message = composer.MsgBatchCancelSpotOrders( - sender="sender", - data=orders - ) + message = composer.MsgBatchCancelSpotOrders(sender="sender", data=orders) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 45000 expected_message_gas_limit = 5000 - assert((expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_create_derivative_limit_orders(self): market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" @@ -103,7 +91,7 @@ def test_estimation_for_batch_create_derivative_limit_orders(self): quantity=1, leverage=1, is_buy=True, - is_po=False + is_po=False, ), composer.DerivativeOrder( market_id=market_id, @@ -113,19 +101,16 @@ def test_estimation_for_batch_create_derivative_limit_orders(self): quantity=1, leverage=1, is_buy=False, - is_reduce_only=False + is_reduce_only=False, ), ] - message = composer.MsgBatchCreateDerivativeLimitOrders( - sender="sender", - orders=orders - ) + message = composer.MsgBatchCreateDerivativeLimitOrders(sender="sender", orders=orders) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 60_000 expected_message_gas_limit = 5000 - assert((expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_cancel_derivative_orders(self): spot_market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -134,29 +119,26 @@ def test_estimation_for_batch_cancel_derivative_orders(self): composer.OrderData( market_id=spot_market_id, subaccount_id="subaccount_id", - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d", ), composer.OrderData( market_id=spot_market_id, subaccount_id="subaccount_id", - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", ), composer.OrderData( market_id=spot_market_id, subaccount_id="subaccount_id", - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] - message = composer.MsgBatchCancelDerivativeOrders( - sender="sender", - data=orders - ) + message = composer.MsgBatchCancelDerivativeOrders(sender="sender", data=orders) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 55_000 expected_message_gas_limit = 5000 - assert((expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_create_spot_orders(self): market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -169,7 +151,7 @@ def test_estimation_for_batch_update_orders_to_create_spot_orders(self): price=5, quantity=1, is_buy=True, - is_po=False + is_po=False, ), composer.SpotOrder( market_id=market_id, @@ -178,7 +160,7 @@ def test_estimation_for_batch_update_orders_to_create_spot_orders(self): price=4, quantity=1, is_buy=True, - is_po=False + is_po=False, ), ] message = composer.MsgBatchUpdateOrders( @@ -186,14 +168,14 @@ def test_estimation_for_batch_update_orders_to_create_spot_orders(self): derivative_orders_to_create=[], spot_orders_to_create=orders, derivative_orders_to_cancel=[], - spot_orders_to_cancel=[] + spot_orders_to_cancel=[], ) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 40_000 expected_message_gas_limit = 10_000 - assert((expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_create_derivative_orders(self): market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" @@ -207,7 +189,7 @@ def test_estimation_for_batch_update_orders_to_create_derivative_orders(self): quantity=1, leverage=1, is_buy=True, - is_po=False + is_po=False, ), composer.DerivativeOrder( market_id=market_id, @@ -217,7 +199,7 @@ def test_estimation_for_batch_update_orders_to_create_derivative_orders(self): quantity=1, leverage=1, is_buy=False, - is_reduce_only=False + is_reduce_only=False, ), ] message = composer.MsgBatchUpdateOrders( @@ -225,14 +207,14 @@ def test_estimation_for_batch_update_orders_to_create_derivative_orders(self): derivative_orders_to_create=orders, spot_orders_to_create=[], derivative_orders_to_cancel=[], - spot_orders_to_cancel=[] + spot_orders_to_cancel=[], ) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 60_000 expected_message_gas_limit = 10_000 - assert((expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_create_binary_orders(self, usdt_token): market_id = "0x230dcce315364ff6360097838701b14713e2f4007d704df20ed3d81d09eec957" @@ -264,7 +246,7 @@ def test_estimation_for_batch_update_orders_to_create_binary_orders(self, usdt_t quantity=1, leverage=1, is_buy=True, - is_po=False + is_po=False, ), composer.BinaryOptionsOrder( market_id=market_id, @@ -274,7 +256,7 @@ def test_estimation_for_batch_update_orders_to_create_binary_orders(self, usdt_t quantity=1, leverage=1, is_buy=False, - is_reduce_only=False + is_reduce_only=False, ), ] message = composer.MsgBatchUpdateOrders( @@ -283,14 +265,14 @@ def test_estimation_for_batch_update_orders_to_create_binary_orders(self, usdt_t spot_orders_to_create=[], binary_options_orders_to_create=orders, derivative_orders_to_cancel=[], - spot_orders_to_cancel=[] + spot_orders_to_cancel=[], ) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 60_000 expected_message_gas_limit = 10_000 - assert((expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 2) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_cancel_spot_orders(self): market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -299,32 +281,32 @@ def test_estimation_for_batch_update_orders_to_cancel_spot_orders(self): composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d", ), composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", ), composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] message = composer.MsgBatchUpdateOrders( sender="senders", derivative_orders_to_create=[], spot_orders_to_create=[], derivative_orders_to_cancel=[], - spot_orders_to_cancel=orders + spot_orders_to_cancel=orders, ) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 45_000 expected_message_gas_limit = 10_000 - assert((expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_cancel_derivative_orders(self): market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" @@ -333,32 +315,32 @@ def test_estimation_for_batch_update_orders_to_cancel_derivative_orders(self): composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d", ), composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", ), composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] message = composer.MsgBatchUpdateOrders( sender="senders", derivative_orders_to_create=[], spot_orders_to_create=[], derivative_orders_to_cancel=orders, - spot_orders_to_cancel=[] + spot_orders_to_cancel=[], ) estimator = GasLimitEstimator.for_message(message=message) expected_order_gas_limit = 55_000 expected_message_gas_limit = 10_000 - assert((expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_cancel_binary_orders(self): market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" @@ -367,18 +349,18 @@ def test_estimation_for_batch_update_orders_to_cancel_binary_orders(self): composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d", ), composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", ), composer.OrderData( market_id=market_id, subaccount_id="subaccount_id", - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] message = composer.MsgBatchUpdateOrders( sender="senders", @@ -393,7 +375,7 @@ def test_estimation_for_batch_update_orders_to_cancel_binary_orders(self): expected_order_gas_limit = 55_000 expected_message_gas_limit = 10_000 - assert((expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit()) + assert (expected_order_gas_limit * 3) + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_cancel_all_for_spot_market(self): market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -406,14 +388,14 @@ def test_estimation_for_batch_update_orders_to_cancel_all_for_spot_market(self): derivative_orders_to_create=[], spot_orders_to_create=[], derivative_orders_to_cancel=[], - spot_orders_to_cancel=[] + spot_orders_to_cancel=[], ) estimator = GasLimitEstimator.for_message(message=message) expected_gas_limit = 35_000 * 20 expected_message_gas_limit = 10_000 - assert(expected_gas_limit + expected_message_gas_limit == estimator.gas_limit()) + assert expected_gas_limit + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_cancel_all_for_derivative_market(self): market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -426,14 +408,14 @@ def test_estimation_for_batch_update_orders_to_cancel_all_for_derivative_market( derivative_orders_to_create=[], spot_orders_to_create=[], derivative_orders_to_cancel=[], - spot_orders_to_cancel=[] + spot_orders_to_cancel=[], ) estimator = GasLimitEstimator.for_message(message=message) expected_gas_limit = 45_000 * 20 expected_message_gas_limit = 10_000 - assert(expected_gas_limit + expected_message_gas_limit == estimator.gas_limit()) + assert expected_gas_limit + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_batch_update_orders_to_cancel_all_for_binary_options_market(self): market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -446,14 +428,14 @@ def test_estimation_for_batch_update_orders_to_cancel_all_for_binary_options_mar derivative_orders_to_create=[], spot_orders_to_create=[], derivative_orders_to_cancel=[], - spot_orders_to_cancel=[] + spot_orders_to_cancel=[], ) estimator = GasLimitEstimator.for_message(message=message) expected_gas_limit = 45_000 * 20 expected_message_gas_limit = 10_000 - assert(expected_gas_limit + expected_message_gas_limit == estimator.gas_limit()) + assert expected_gas_limit + expected_message_gas_limit == estimator.gas_limit() def test_estimation_for_exec_message(self): market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -466,7 +448,7 @@ def test_estimation_for_exec_message(self): price=5, quantity=1, is_buy=True, - is_po=False + is_po=False, ), ] inner_message = composer.MsgBatchUpdateOrders( @@ -474,12 +456,9 @@ def test_estimation_for_exec_message(self): derivative_orders_to_create=[], spot_orders_to_create=orders, derivative_orders_to_cancel=[], - spot_orders_to_cancel=[] - ) - message = composer.MsgExec( - grantee="grantee", - msgs=[inner_message] + spot_orders_to_cancel=[], ) + message = composer.MsgExec(grantee="grantee", msgs=[inner_message]) estimator = GasLimitEstimator.for_message(message=message) @@ -487,10 +466,10 @@ def test_estimation_for_exec_message(self): expected_inner_message_gas_limit = 10_000 expected_exec_message_gas_limit = 5_000 - assert(expected_order_gas_limit - + expected_inner_message_gas_limit - + expected_exec_message_gas_limit - == estimator.gas_limit()) + assert ( + expected_order_gas_limit + expected_inner_message_gas_limit + expected_exec_message_gas_limit + == estimator.gas_limit() + ) def test_estimation_for_privileged_execute_contract_message(self): message = injective_exchange_tx_pb.MsgPrivilegedExecuteContract() @@ -498,7 +477,7 @@ def test_estimation_for_privileged_execute_contract_message(self): expected_gas_limit = 900_000 - assert(expected_gas_limit == estimator.gas_limit()) + assert expected_gas_limit == estimator.gas_limit() def test_estimation_for_execute_contract_message(self): composer = Composer(network="testnet") @@ -511,7 +490,7 @@ def test_estimation_for_execute_contract_message(self): expected_gas_limit = 375_000 - assert(expected_gas_limit == estimator.gas_limit()) + assert expected_gas_limit == estimator.gas_limit() def test_estimation_for_wasm_message(self): message = wasm_tx_pb.MsgInstantiateContract2() @@ -519,7 +498,7 @@ def test_estimation_for_wasm_message(self): expected_gas_limit = 225_000 - assert(expected_gas_limit == estimator.gas_limit()) + assert expected_gas_limit == estimator.gas_limit() def test_estimation_for_governance_message(self): message = gov_tx_pb.MsgDeposit() @@ -527,7 +506,7 @@ def test_estimation_for_governance_message(self): expected_gas_limit = 2_250_000 - assert(expected_gas_limit == estimator.gas_limit()) + assert expected_gas_limit == estimator.gas_limit() def test_estimation_for_generic_exchange_message(self): composer = Composer(network="testnet") @@ -539,10 +518,10 @@ def test_estimation_for_generic_exchange_message(self): price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ) estimator = GasLimitEstimator.for_message(message=message) expected_gas_limit = 100_000 - assert(expected_gas_limit == estimator.gas_limit()) + assert expected_gas_limit == estimator.gas_limit() diff --git a/tests/core/test_market.py b/tests/core/test_market.py index 68216823..003f39a2 100644 --- a/tests/core/test_market.py +++ b/tests/core/test_market.py @@ -11,17 +11,17 @@ class TestSpotMarket: - def test_convert_quantity_to_chain_format(self, inj_usdt_spot_market: SpotMarket): original_quantity = Decimal("123.456789") chain_value = inj_usdt_spot_market.quantity_to_chain_format(human_readable_value=original_quantity) expected_value = original_quantity * Decimal(f"1e{inj_usdt_spot_market.base_token.decimals}") - quantized_value = ((expected_value // inj_usdt_spot_market.min_quantity_tick_size) - * inj_usdt_spot_market.min_quantity_tick_size) + quantized_value = ( + expected_value // inj_usdt_spot_market.min_quantity_tick_size + ) * inj_usdt_spot_market.min_quantity_tick_size quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_price_to_chain_format(self, inj_usdt_spot_market: SpotMarket): original_quantity = Decimal("123.456789") @@ -29,11 +29,12 @@ def test_convert_price_to_chain_format(self, inj_usdt_spot_market: SpotMarket): chain_value = inj_usdt_spot_market.price_to_chain_format(human_readable_value=original_quantity) price_decimals = inj_usdt_spot_market.quote_token.decimals - inj_usdt_spot_market.base_token.decimals expected_value = original_quantity * Decimal(f"1e{price_decimals}") - quantized_value = ((expected_value // inj_usdt_spot_market.min_price_tick_size) - * inj_usdt_spot_market.min_price_tick_size) + quantized_value = ( + expected_value // inj_usdt_spot_market.min_price_tick_size + ) * inj_usdt_spot_market.min_price_tick_size quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_quantity_from_chain_format(self, inj_usdt_spot_market: SpotMarket): expected_quantity = Decimal("123.456") @@ -41,7 +42,7 @@ def test_convert_quantity_from_chain_format(self, inj_usdt_spot_market: SpotMark chain_format_quantity = expected_quantity * Decimal(f"1e{inj_usdt_spot_market.base_token.decimals}") human_readable_quantity = inj_usdt_spot_market.quantity_from_chain_format(chain_value=chain_format_quantity) - assert (expected_quantity == human_readable_quantity) + assert expected_quantity == human_readable_quantity def test_convert_price_from_chain_format(self, inj_usdt_spot_market: SpotMarket): expected_price = Decimal("123.456") @@ -50,20 +51,20 @@ def test_convert_price_from_chain_format(self, inj_usdt_spot_market: SpotMarket) chain_format_price = expected_price * Decimal(f"1e{price_decimals}") human_readable_price = inj_usdt_spot_market.price_from_chain_format(chain_value=chain_format_price) - assert (expected_price == human_readable_price) + assert expected_price == human_readable_price class TestDerivativeMarket: - def test_convert_quantity_to_chain_format(self, btc_usdt_perp_market: DerivativeMarket): original_quantity = Decimal("123.456789") chain_value = btc_usdt_perp_market.quantity_to_chain_format(human_readable_value=original_quantity) - quantized_value = ((original_quantity // btc_usdt_perp_market.min_quantity_tick_size) - * btc_usdt_perp_market.min_quantity_tick_size) + quantized_value = ( + original_quantity // btc_usdt_perp_market.min_quantity_tick_size + ) * btc_usdt_perp_market.min_quantity_tick_size quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_price_to_chain_format(self, btc_usdt_perp_market: DerivativeMarket): original_quantity = Decimal("123.456789") @@ -71,11 +72,12 @@ def test_convert_price_to_chain_format(self, btc_usdt_perp_market: DerivativeMar chain_value = btc_usdt_perp_market.price_to_chain_format(human_readable_value=original_quantity) price_decimals = btc_usdt_perp_market.quote_token.decimals expected_value = original_quantity * Decimal(f"1e{price_decimals}") - quantized_value = ((expected_value // btc_usdt_perp_market.min_price_tick_size) - * btc_usdt_perp_market.min_price_tick_size) + quantized_value = ( + expected_value // btc_usdt_perp_market.min_price_tick_size + ) * btc_usdt_perp_market.min_price_tick_size quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_margin_to_chain_format(self, btc_usdt_perp_market: DerivativeMarket): original_quantity = Decimal("123.456789") @@ -83,11 +85,12 @@ def test_convert_margin_to_chain_format(self, btc_usdt_perp_market: DerivativeMa chain_value = btc_usdt_perp_market.margin_to_chain_format(human_readable_value=original_quantity) margin_decimals = btc_usdt_perp_market.quote_token.decimals expected_value = original_quantity * Decimal(f"1e{margin_decimals}") - quantized_value = ((expected_value // btc_usdt_perp_market.min_quantity_tick_size) - * btc_usdt_perp_market.min_quantity_tick_size) + quantized_value = ( + expected_value // btc_usdt_perp_market.min_quantity_tick_size + ) * btc_usdt_perp_market.min_quantity_tick_size quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_quantity_from_chain_format(self, btc_usdt_perp_market: DerivativeMarket): expected_quantity = Decimal("123.456") @@ -95,7 +98,7 @@ def test_convert_quantity_from_chain_format(self, btc_usdt_perp_market: Derivati chain_format_quantity = expected_quantity human_readable_quantity = btc_usdt_perp_market.quantity_from_chain_format(chain_value=chain_format_quantity) - assert (expected_quantity == human_readable_quantity) + assert expected_quantity == human_readable_quantity def test_convert_price_from_chain_format(self, btc_usdt_perp_market: DerivativeMarket): expected_price = Decimal("123.456") @@ -104,7 +107,7 @@ def test_convert_price_from_chain_format(self, btc_usdt_perp_market: DerivativeM chain_format_price = expected_price * Decimal(f"1e{price_decimals}") human_readable_price = btc_usdt_perp_market.price_from_chain_format(chain_value=chain_format_price) - assert (expected_price == human_readable_price) + assert expected_price == human_readable_price def test_convert_margin_from_chain_format(self, btc_usdt_perp_market: DerivativeMarket): expected_margin = Decimal("123.456") @@ -113,11 +116,10 @@ def test_convert_margin_from_chain_format(self, btc_usdt_perp_market: Derivative chain_format_margin = expected_margin * Decimal(f"1e{price_decimals}") human_readable_margin = btc_usdt_perp_market.margin_from_chain_format(chain_value=chain_format_margin) - assert (expected_margin == human_readable_margin) + assert expected_margin == human_readable_margin class TestBinaryOptionMarket: - def test_convert_quantity_to_chain_format_with_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") fixed_denom = Denom( @@ -129,15 +131,15 @@ def test_convert_quantity_to_chain_format_with_fixed_denom(self, first_match_bet ) chain_value = first_match_bet_market.quantity_to_chain_format( - human_readable_value=original_quantity, - special_denom=fixed_denom + human_readable_value=original_quantity, special_denom=fixed_denom ) chain_formatted_quantity = original_quantity * Decimal(f"1e{fixed_denom.base}") - quantized_value = ((chain_formatted_quantity // Decimal(str(fixed_denom.min_quantity_tick_size))) - * Decimal(str(fixed_denom.min_quantity_tick_size))) + quantized_value = (chain_formatted_quantity // Decimal(str(fixed_denom.min_quantity_tick_size))) * Decimal( + str(fixed_denom.min_quantity_tick_size) + ) quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_quantity_to_chain_format_without_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -145,11 +147,12 @@ def test_convert_quantity_to_chain_format_without_fixed_denom(self, first_match_ chain_value = first_match_bet_market.quantity_to_chain_format( human_readable_value=original_quantity, ) - quantized_value = ((original_quantity // first_match_bet_market.min_quantity_tick_size) - * first_match_bet_market.min_quantity_tick_size) + quantized_value = ( + original_quantity // first_match_bet_market.min_quantity_tick_size + ) * first_match_bet_market.min_quantity_tick_size quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_price_to_chain_format_with_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -167,11 +170,12 @@ def test_convert_price_to_chain_format_with_fixed_denom(self, first_match_bet_ma ) price_decimals = fixed_denom.quote expected_value = original_quantity * Decimal(f"1e{price_decimals}") - quantized_value = ((expected_value // Decimal(str(fixed_denom.min_price_tick_size))) - * Decimal(str(fixed_denom.min_price_tick_size))) + quantized_value = (expected_value // Decimal(str(fixed_denom.min_price_tick_size))) * Decimal( + str(fixed_denom.min_price_tick_size) + ) quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_convert_price_to_chain_format_without_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -179,11 +183,12 @@ def test_convert_price_to_chain_format_without_fixed_denom(self, first_match_bet chain_value = first_match_bet_market.price_to_chain_format(human_readable_value=original_quantity) price_decimals = first_match_bet_market.quote_token.decimals expected_value = original_quantity * Decimal(f"1e{price_decimals}") - quantized_value = ((expected_value // first_match_bet_market.min_price_tick_size) - * first_match_bet_market.min_price_tick_size) + quantized_value = ( + expected_value // first_match_bet_market.min_price_tick_size + ) * first_match_bet_market.min_price_tick_size quantized_chain_format_value = quantized_value * Decimal("1e18") - assert (quantized_chain_format_value == chain_value) + assert quantized_chain_format_value == chain_value def test_calculate_margin_for_buy_with_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -208,13 +213,12 @@ def test_calculate_margin_for_buy_with_fixed_denom(self, first_match_bet_market: expected_quantity = original_quantity * Decimal(f"1e{quantity_decimals}") expected_price = original_price * Decimal(f"1e{price_decimals}") expected_margin = expected_quantity * expected_price - quantized_margin = ( - (expected_margin // Decimal(str(fixed_denom.min_quantity_tick_size))) - * Decimal(str(fixed_denom.min_quantity_tick_size)) + quantized_margin = (expected_margin // Decimal(str(fixed_denom.min_quantity_tick_size))) * Decimal( + str(fixed_denom.min_quantity_tick_size) ) quantized_chain_format_margin = quantized_margin * Decimal("1e18") - assert (quantized_chain_format_margin == chain_value) + assert quantized_chain_format_margin == chain_value def test_calculate_margin_for_buy_without_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -229,13 +233,12 @@ def test_calculate_margin_for_buy_without_fixed_denom(self, first_match_bet_mark price_decimals = first_match_bet_market.quote_token.decimals expected_price = original_price * Decimal(f"1e{price_decimals}") expected_margin = original_quantity * expected_price - quantized_margin = ( - (expected_margin // Decimal(str(first_match_bet_market.min_quantity_tick_size))) - * Decimal(str(first_match_bet_market.min_quantity_tick_size)) + quantized_margin = (expected_margin // Decimal(str(first_match_bet_market.min_quantity_tick_size))) * Decimal( + str(first_match_bet_market.min_quantity_tick_size) ) quantized_chain_format_margin = quantized_margin * Decimal("1e18") - assert (quantized_chain_format_margin == chain_value) + assert quantized_chain_format_margin == chain_value def test_calculate_margin_for_sell_without_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -250,13 +253,12 @@ def test_calculate_margin_for_sell_without_fixed_denom(self, first_match_bet_mar price_decimals = first_match_bet_market.quote_token.decimals expected_price = (Decimal(1) - original_price) * Decimal(f"1e{price_decimals}") expected_margin = original_quantity * expected_price - quantized_margin = ( - (expected_margin // Decimal(str(first_match_bet_market.min_quantity_tick_size))) - * Decimal(str(first_match_bet_market.min_quantity_tick_size)) + quantized_margin = (expected_margin // Decimal(str(first_match_bet_market.min_quantity_tick_size))) * Decimal( + str(first_match_bet_market.min_quantity_tick_size) ) quantized_chain_format_margin = quantized_margin * Decimal("1e18") - assert (quantized_chain_format_margin == chain_value) + assert quantized_chain_format_margin == chain_value def test_convert_quantity_from_chain_format_with_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -274,7 +276,7 @@ def test_convert_quantity_from_chain_format_with_fixed_denom(self, first_match_b chain_value=chain_formatted_quantity, special_denom=fixed_denom ) - assert (original_quantity == human_readable_quantity) + assert original_quantity == human_readable_quantity def test_convert_quantity_from_chain_format_without_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_quantity = Decimal("123.456789") @@ -285,7 +287,7 @@ def test_convert_quantity_from_chain_format_without_fixed_denom(self, first_matc chain_value=chain_formatted_quantity ) - assert (original_quantity == human_readable_quantity) + assert original_quantity == human_readable_quantity def test_convert_price_from_chain_format_with_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_price = Decimal("123.456789") @@ -303,7 +305,7 @@ def test_convert_price_from_chain_format_with_fixed_denom(self, first_match_bet_ chain_value=chain_formatted_price, special_denom=fixed_denom ) - assert (original_price == human_readable_price) + assert original_price == human_readable_price def test_convert_price_from_chain_format_without_fixed_denom(self, first_match_bet_market: BinaryOptionMarket): original_price = Decimal("123.456789") @@ -311,4 +313,4 @@ def test_convert_price_from_chain_format_without_fixed_denom(self, first_match_b human_readable_price = first_match_bet_market.price_from_chain_format(chain_value=chain_formatted_price) - assert (original_price == human_readable_price) + assert original_price == human_readable_price diff --git a/tests/core/test_message_based_transaction_fee_calculator.py b/tests/core/test_message_based_transaction_fee_calculator.py index eff3ea6e..f4c3a8d8 100644 --- a/tests/core/test_message_based_transaction_fee_calculator.py +++ b/tests/core/test_message_based_transaction_fee_calculator.py @@ -14,7 +14,6 @@ class TestMessageBasedTransactionFeeCalculator: - @pytest.mark.asyncio async def test_gas_fee_for_privileged_execute_contract_message(self): network = Network.testnet(node="sentry") @@ -34,8 +33,8 @@ async def test_gas_fee_for_privileged_execute_contract_message(self): expected_transaction_gas_limit = 60_000 expected_gas_limit = math.ceil(Decimal(6) * 150_000 + expected_transaction_gas_limit) - assert(expected_gas_limit == transaction.fee.gas_limit) - assert(str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount) + assert expected_gas_limit == transaction.fee.gas_limit + assert str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount @pytest.mark.asyncio async def test_gas_fee_for_execute_contract_message(self): @@ -60,8 +59,8 @@ async def test_gas_fee_for_execute_contract_message(self): expected_transaction_gas_limit = 60_000 expected_gas_limit = math.ceil(Decimal(2.5) * 150_000 + expected_transaction_gas_limit) - assert (expected_gas_limit == transaction.fee.gas_limit) - assert (str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount) + assert expected_gas_limit == transaction.fee.gas_limit + assert str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount @pytest.mark.asyncio async def test_gas_fee_for_wasm_message(self): @@ -82,8 +81,8 @@ async def test_gas_fee_for_wasm_message(self): expected_transaction_gas_limit = 60_000 expected_gas_limit = math.ceil(Decimal(1.5) * 150_000 + expected_transaction_gas_limit) - assert (expected_gas_limit == transaction.fee.gas_limit) - assert (str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount) + assert expected_gas_limit == transaction.fee.gas_limit + assert str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount @pytest.mark.asyncio async def test_gas_fee_for_governance_message(self): @@ -104,8 +103,8 @@ async def test_gas_fee_for_governance_message(self): expected_transaction_gas_limit = 60_000 expected_gas_limit = math.ceil(Decimal(15) * 150_000 + expected_transaction_gas_limit) - assert (expected_gas_limit == transaction.fee.gas_limit) - assert (str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount) + assert expected_gas_limit == transaction.fee.gas_limit + assert str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount @pytest.mark.asyncio async def test_gas_fee_for_exchange_message(self): @@ -126,7 +125,7 @@ async def test_gas_fee_for_exchange_message(self): price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ) transaction = Transaction() transaction.with_messages(message) @@ -135,8 +134,8 @@ async def test_gas_fee_for_exchange_message(self): expected_transaction_gas_limit = 60_000 expected_gas_limit = math.ceil(Decimal(1) * 100_000 + expected_transaction_gas_limit) - assert (expected_gas_limit == transaction.fee.gas_limit) - assert (str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount) + assert expected_gas_limit == transaction.fee.gas_limit + assert str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount @pytest.mark.asyncio async def test_gas_fee_for_msg_exec_message(self): @@ -157,12 +156,9 @@ async def test_gas_fee_for_msg_exec_message(self): price=7.523, quantity=0.01, is_buy=True, - is_po=False - ) - message = composer.MsgExec( - grantee="grantee", - msgs=[inner_message] + is_po=False, ) + message = composer.MsgExec(grantee="grantee", msgs=[inner_message]) transaction = Transaction() transaction.with_messages(message) @@ -174,8 +170,8 @@ async def test_gas_fee_for_msg_exec_message(self): expected_gas_limit = math.ceil( expected_exec_message_gas_limit + expected_inner_message_gas_limit + expected_transaction_gas_limit ) - assert (expected_gas_limit == transaction.fee.gas_limit) - assert (str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount) + assert expected_gas_limit == transaction.fee.gas_limit + assert str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount @pytest.mark.asyncio async def test_gas_fee_for_two_messages_in_one_transaction(self): @@ -196,19 +192,11 @@ async def test_gas_fee_for_two_messages_in_one_transaction(self): price=7.523, quantity=0.01, is_buy=True, - is_po=False - ) - message = composer.MsgExec( - grantee="grantee", - msgs=[inner_message] + is_po=False, ) + message = composer.MsgExec(grantee="grantee", msgs=[inner_message]) - send_message = composer.MsgSend( - from_address="address", - to_address='to_address', - amount=1, - denom='INJ' - ) + send_message = composer.MsgSend(from_address="address", to_address="to_address", amount=1, denom="INJ") transaction = Transaction() transaction.with_messages(message, send_message) @@ -225,5 +213,5 @@ async def test_gas_fee_for_two_messages_in_one_transaction(self): + expected_send_message_gas_limit + expected_transaction_gas_limit ) - assert (expected_gas_limit == transaction.fee.gas_limit) - assert (str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount) + assert expected_gas_limit == transaction.fee.gas_limit + assert str(expected_gas_limit * 5_000_000) == transaction.fee.amount[0].amount diff --git a/tests/core/test_token.py b/tests/core/test_token.py index 478bf906..6c649f06 100644 --- a/tests/core/test_token.py +++ b/tests/core/test_token.py @@ -4,11 +4,10 @@ class TestToken: - def test_chain_formatted_value(self, inj_token): value = Decimal("1.3456") chain_formatted_value = inj_token.chain_formatted_value(human_readable_value=value) expected_value = value * Decimal(f"1e{inj_token.decimals}") - assert (chain_formatted_value == expected_value) + assert chain_formatted_value == expected_value diff --git a/tests/rpc_fixtures/configurable_servicers.py b/tests/rpc_fixtures/configurable_servicers.py index bf32d9ba..8c46dd2d 100644 --- a/tests/rpc_fixtures/configurable_servicers.py +++ b/tests/rpc_fixtures/configurable_servicers.py @@ -6,7 +6,6 @@ class ConfigurableInjectiveSpotExchangeRPCServicer(InjectiveSpotExchangeRPCServicer): - def __init__(self): super().__init__() self.markets_queue = deque() @@ -16,7 +15,6 @@ async def Markets(self, request: injective_spot_exchange_rpc_pb2.MarketsRequest, class ConfigurableInjectiveDerivativeExchangeRPCServicer(InjectiveDerivativeExchangeRPCServicer): - def __init__(self): super().__init__() self.markets_queue = deque() @@ -26,8 +24,6 @@ async def Markets(self, request: injective_derivative_exchange_rpc_pb2.MarketsRe return self.markets_queue.pop() async def BinaryOptionsMarkets( - self, - request: injective_derivative_exchange_rpc_pb2.BinaryOptionsMarketsRequest, - context=None + self, request: injective_derivative_exchange_rpc_pb2.BinaryOptionsMarketsRequest, context=None ): return self.binary_option_markets_queue.pop() diff --git a/tests/rpc_fixtures/markets_fixtures.py b/tests/rpc_fixtures/markets_fixtures.py index 4ff72c4c..534ec8d7 100644 --- a/tests/rpc_fixtures/markets_fixtures.py +++ b/tests/rpc_fixtures/markets_fixtures.py @@ -11,7 +11,7 @@ def inj_token_meta(): symbol="INJ", logo="https://static.alchemyapi.io/images/assets/7226.png", decimals=18, - updated_at=1681739137644 + updated_at=1681739137644, ) return token @@ -27,7 +27,7 @@ def ape_token_meta(): symbol="APE", logo="https://assets.coingecko.com/coins/images/24383/small/apecoin.jpg?1647476455", decimals=18, - updated_at=1681739137646 + updated_at=1681739137646, ) return token @@ -43,7 +43,7 @@ def usdt_token_meta(): symbol="USDT", logo="https://static.alchemyapi.io/images/assets/825.png", decimals=6, - updated_at=1681739137645 + updated_at=1681739137645, ) return token @@ -59,7 +59,7 @@ def usdt_token_meta_second_denom(): symbol="USDT", logo="https://static.alchemyapi.io/images/assets/826.png", decimals=6, - updated_at=1691739137645 + updated_at=1691739137645, ) return token @@ -75,7 +75,7 @@ def usdt_perp_token_meta(): symbol="USDTPerp", logo="https://static.alchemyapi.io/images/assets/825.png", decimals=6, - updated_at=1683929869866 + updated_at=1683929869866, ) return token diff --git a/tests/test_async_client.py b/tests/test_async_client.py index ffd78cd3..c2bc2335 100644 --- a/tests/test_async_client.py +++ b/tests/test_async_client.py @@ -33,7 +33,6 @@ def derivative_servicer(): class TestAsyncClient: - @pytest.mark.asyncio async def test_sync_timeout_height_logs_exception(self, caplog): client = AsyncClient( @@ -49,9 +48,9 @@ async def test_sync_timeout_height_logs_exception(self, caplog): (record for record in caplog.record_tuples if record[2].startswith(expected_log_message_prefix)), None, ) - assert (found_log is not None) - assert (found_log[0] == "pyinjective.async_client.AsyncClient") - assert (found_log[1] == logging.DEBUG) + assert found_log is not None + assert found_log[0] == "pyinjective.async_client.AsyncClient" + assert found_log[1] == logging.DEBUG @pytest.mark.asyncio async def test_get_account_logs_exception(self, caplog): @@ -68,31 +67,31 @@ async def test_get_account_logs_exception(self, caplog): (record for record in caplog.record_tuples if record[2].startswith(expected_log_message_prefix)), None, ) - assert (found_log is not None) - assert (found_log[0] == "pyinjective.async_client.AsyncClient") - assert (found_log[1] == logging.DEBUG) + assert found_log is not None + assert found_log[0] == "pyinjective.async_client.AsyncClient" + assert found_log[1] == logging.DEBUG @pytest.mark.asyncio async def test_initialize_tokens_and_markets( - self, - spot_servicer, - derivative_servicer, - inj_usdt_spot_market_meta, - ape_usdt_spot_market_meta, - btc_usdt_perp_market_meta, - first_match_bet_market_meta, + self, + spot_servicer, + derivative_servicer, + inj_usdt_spot_market_meta, + ape_usdt_spot_market_meta, + btc_usdt_perp_market_meta, + first_match_bet_market_meta, ): - spot_servicer.markets_queue.append(injective_spot_exchange_rpc_pb2.MarketsResponse( - markets=[inj_usdt_spot_market_meta, ape_usdt_spot_market_meta] - )) - derivative_servicer.markets_queue.append(injective_derivative_exchange_rpc_pb2.MarketsResponse( - markets=[btc_usdt_perp_market_meta] - )) - derivative_servicer.binary_option_markets_queue.append( - injective_derivative_exchange_rpc_pb2.BinaryOptionsMarketsResponse( - markets=[first_match_bet_market_meta] + spot_servicer.markets_queue.append( + injective_spot_exchange_rpc_pb2.MarketsResponse( + markets=[inj_usdt_spot_market_meta, ape_usdt_spot_market_meta] ) ) + derivative_servicer.markets_queue.append( + injective_derivative_exchange_rpc_pb2.MarketsResponse(markets=[btc_usdt_perp_market_meta]) + ) + derivative_servicer.binary_option_markets_queue.append( + injective_derivative_exchange_rpc_pb2.BinaryOptionsMarketsResponse(markets=[first_match_bet_market_meta]) + ) client = AsyncClient( network=Network.local(), @@ -105,30 +104,28 @@ async def test_initialize_tokens_and_markets( await client._initialize_tokens_and_markets() all_tokens = await client.all_tokens() - assert(5 == len(all_tokens)) + assert 5 == len(all_tokens) inj_symbol, usdt_symbol = inj_usdt_spot_market_meta.ticker.split("/") ape_symbol, _ = ape_usdt_spot_market_meta.ticker.split("/") alternative_usdt_name = ape_usdt_spot_market_meta.quote_token_meta.name usdt_perp_symbol = btc_usdt_perp_market_meta.quote_token_meta.symbol - assert(inj_symbol in all_tokens) - assert(usdt_symbol in all_tokens) - assert(alternative_usdt_name in all_tokens) - assert(ape_symbol in all_tokens) - assert(usdt_perp_symbol in all_tokens) + assert inj_symbol in all_tokens + assert usdt_symbol in all_tokens + assert alternative_usdt_name in all_tokens + assert ape_symbol in all_tokens + assert usdt_perp_symbol in all_tokens all_spot_markets = await client.all_spot_markets() - assert (2 == len(all_spot_markets)) - assert (any((inj_usdt_spot_market_meta.market_id == market.id for market in all_spot_markets.values()))) - assert (any((ape_usdt_spot_market_meta.market_id == market.id for market in all_spot_markets.values()))) + assert 2 == len(all_spot_markets) + assert any((inj_usdt_spot_market_meta.market_id == market.id for market in all_spot_markets.values())) + assert any((ape_usdt_spot_market_meta.market_id == market.id for market in all_spot_markets.values())) all_derivative_markets = await client.all_derivative_markets() - assert (1 == len(all_derivative_markets)) - assert (any((btc_usdt_perp_market_meta.market_id == market.id for market in all_derivative_markets.values()))) + assert 1 == len(all_derivative_markets) + assert any((btc_usdt_perp_market_meta.market_id == market.id for market in all_derivative_markets.values())) all_binary_option_markets = await client.all_binary_option_markets() - assert (1 == len(all_binary_option_markets)) - assert ( - any( - (first_match_bet_market_meta.market_id == market.id for market in all_binary_option_markets.values()) - ) + assert 1 == len(all_binary_option_markets) + assert any( + (first_match_bet_market_meta.market_id == market.id for market in all_binary_option_markets.values()) ) diff --git a/tests/test_composer.py b/tests/test_composer.py index d8812580..c36eb5c5 100644 --- a/tests/test_composer.py +++ b/tests/test_composer.py @@ -16,7 +16,6 @@ class TestComposer: - @pytest.fixture def inj_usdt_market_id(self): return "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0" @@ -32,7 +31,7 @@ def basic_composer(self, inj_usdt_spot_market, btc_usdt_perp_market, first_match inj_usdt_spot_market.base_token.symbol: inj_usdt_spot_market.base_token, inj_usdt_spot_market.quote_token.symbol: inj_usdt_spot_market.quote_token, btc_usdt_perp_market.quote_token.symbol: btc_usdt_perp_market.quote_token, - } + }, ) return composer @@ -42,18 +41,20 @@ def test_composer_initialization_from_ini_files(self): inj_token = composer.tokens["INJ"] inj_usdt_spot_market = next( - (market for market in composer.spot_markets.values() - if market.ticker == "'Devnet Spot INJ/USDT'") + (market for market in composer.spot_markets.values() if market.ticker == "'Devnet Spot INJ/USDT'") ) inj_usdt_perp_market = next( - (market for market in composer.derivative_markets.values() - if market.ticker == "'Devnet Derivative INJ/USDT PERP'") + ( + market + for market in composer.derivative_markets.values() + if market.ticker == "'Devnet Derivative INJ/USDT PERP'" + ) ) - assert (18 == inj_token.decimals) - assert (18 == inj_usdt_spot_market.base_token.decimals) - assert (6 == inj_usdt_spot_market.quote_token.decimals) - assert (6 == inj_usdt_perp_market.quote_token.decimals) + assert 18 == inj_token.decimals + assert 18 == inj_usdt_spot_market.base_token.decimals + assert 6 == inj_usdt_spot_market.quote_token.decimals + assert 6 == inj_usdt_perp_market.quote_token.decimals def test_buy_spot_order_creation(self, basic_composer: Composer, inj_usdt_spot_market: SpotMarket): fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" @@ -70,21 +71,25 @@ def test_buy_spot_order_creation(self, basic_composer: Composer, inj_usdt_spot_m price_decimals = inj_usdt_spot_market.quote_token.decimals - inj_usdt_spot_market.base_token.decimals chain_format_price = Decimal(str(price)) * Decimal(f"1e{price_decimals}") - expected_price = ((chain_format_price // inj_usdt_spot_market.min_price_tick_size) - * inj_usdt_spot_market.min_price_tick_size - * Decimal("1e18")) + expected_price = ( + (chain_format_price // inj_usdt_spot_market.min_price_tick_size) + * inj_usdt_spot_market.min_price_tick_size + * Decimal("1e18") + ) chain_format_quantity = Decimal(str(quantity)) * Decimal(f"1e{inj_usdt_spot_market.base_token.decimals}") - expected_quantity = ((chain_format_quantity // inj_usdt_spot_market.min_quantity_tick_size) - * inj_usdt_spot_market.min_quantity_tick_size - * Decimal("1e18")) - - assert (order.market_id == inj_usdt_spot_market.id) - assert (order.order_info.subaccount_id == "1") - assert (order.order_info.fee_recipient == fee_recipient) - assert (order.order_info.price == str(int(expected_price))) - assert (order.order_info.quantity == str(int(expected_quantity))) - assert (order.order_type == exchange_pb2.OrderType.BUY) - assert (order.trigger_price == "0") + expected_quantity = ( + (chain_format_quantity // inj_usdt_spot_market.min_quantity_tick_size) + * inj_usdt_spot_market.min_quantity_tick_size + * Decimal("1e18") + ) + + assert order.market_id == inj_usdt_spot_market.id + assert order.order_info.subaccount_id == "1" + assert order.order_info.fee_recipient == fee_recipient + assert order.order_info.price == str(int(expected_price)) + assert order.order_info.quantity == str(int(expected_quantity)) + assert order.order_type == exchange_pb2.OrderType.BUY + assert order.trigger_price == "0" def test_buy_derivative_order_creation(self, basic_composer: Composer, btc_usdt_perp_market: DerivativeMarket): fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" @@ -121,14 +126,14 @@ def test_buy_derivative_order_creation(self, basic_composer: Composer, btc_usdt_ * Decimal("1e18") ) - assert (order.market_id == btc_usdt_perp_market.id) - assert (order.order_info.subaccount_id == "1") - assert (order.order_info.fee_recipient == fee_recipient) - assert (order.order_info.price == str(int(expected_price))) - assert (order.order_info.quantity == str(int(expected_quantity))) - assert (order.order_type == exchange_pb2.OrderType.BUY) - assert (order.margin == str(int(expected_margin))) - assert (order.trigger_price == "0") + assert order.market_id == btc_usdt_perp_market.id + assert order.order_info.subaccount_id == "1" + assert order.order_info.fee_recipient == fee_recipient + assert order.order_info.price == str(int(expected_price)) + assert order.order_info.quantity == str(int(expected_quantity)) + assert order.order_type == exchange_pb2.OrderType.BUY + assert order.margin == str(int(expected_margin)) + assert order.trigger_price == "0" def test_increase_position_margin(self, basic_composer: Composer, btc_usdt_perp_market: DerivativeMarket): sender = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" @@ -149,16 +154,14 @@ def test_increase_position_margin(self, basic_composer: Composer, btc_usdt_perp_ * Decimal("1e18") ) - assert (message.market_id == btc_usdt_perp_market.id) - assert (message.sender == sender) - assert (message.source_subaccount_id == "1") - assert (message.destination_subaccount_id == "2") - assert (message.amount == str(int(expected_margin))) + assert message.market_id == btc_usdt_perp_market.id + assert message.sender == sender + assert message.source_subaccount_id == "1" + assert message.destination_subaccount_id == "2" + assert message.amount == str(int(expected_margin)) def test_buy_binary_option_order_creation_with_fixed_denom( - self, - basic_composer: Composer, - first_match_bet_market: BinaryOptionMarket + self, basic_composer: Composer, first_match_bet_market: BinaryOptionMarket ): fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" price = 6.869 @@ -202,19 +205,19 @@ def test_buy_binary_option_order_creation_with_fixed_denom( * Decimal("1e18") ) - assert (order.market_id == first_match_bet_market.id) - assert (order.order_info.subaccount_id == "1") - assert (order.order_info.fee_recipient == fee_recipient) - assert (order.order_info.price == str(int(expected_price))) - assert (order.order_info.quantity == str(int(expected_quantity))) - assert (order.order_type == exchange_pb2.OrderType.BUY) - assert (order.margin == str(int(expected_margin))) - assert (order.trigger_price == "0") + assert order.market_id == first_match_bet_market.id + assert order.order_info.subaccount_id == "1" + assert order.order_info.fee_recipient == fee_recipient + assert order.order_info.price == str(int(expected_price)) + assert order.order_info.quantity == str(int(expected_quantity)) + assert order.order_type == exchange_pb2.OrderType.BUY + assert order.margin == str(int(expected_margin)) + assert order.trigger_price == "0" def test_buy_binary_option_order_creation_without_fixed_denom( - self, - basic_composer: Composer, - first_match_bet_market: BinaryOptionMarket, + self, + basic_composer: Composer, + first_match_bet_market: BinaryOptionMarket, ): fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" price = 6.869 @@ -231,23 +234,29 @@ def test_buy_binary_option_order_creation_without_fixed_denom( price_decimals = first_match_bet_market.quote_token.decimals chain_format_price = Decimal(str(price)) * Decimal(f"1e{price_decimals}") - expected_price = ((chain_format_price // first_match_bet_market.min_price_tick_size) - * first_match_bet_market.min_price_tick_size - * Decimal("1e18")) + expected_price = ( + (chain_format_price // first_match_bet_market.min_price_tick_size) + * first_match_bet_market.min_price_tick_size + * Decimal("1e18") + ) chain_format_quantity = Decimal(str(quantity)) - expected_quantity = ((chain_format_quantity // first_match_bet_market.min_quantity_tick_size) - * first_match_bet_market.min_quantity_tick_size - * Decimal("1e18")) - chain_format_margin = (chain_format_quantity * chain_format_price) - expected_margin = ((chain_format_margin // first_match_bet_market.min_quantity_tick_size) - * first_match_bet_market.min_quantity_tick_size - * Decimal("1e18")) - - assert (order.market_id == first_match_bet_market.id) - assert (order.order_info.subaccount_id == "1") - assert (order.order_info.fee_recipient == fee_recipient) - assert (order.order_info.price == str(int(expected_price))) - assert (order.order_info.quantity == str(int(expected_quantity))) - assert (order.order_type == exchange_pb2.OrderType.BUY) - assert (order.margin == str(int(expected_margin))) - assert (order.trigger_price == "0") + expected_quantity = ( + (chain_format_quantity // first_match_bet_market.min_quantity_tick_size) + * first_match_bet_market.min_quantity_tick_size + * Decimal("1e18") + ) + chain_format_margin = chain_format_quantity * chain_format_price + expected_margin = ( + (chain_format_margin // first_match_bet_market.min_quantity_tick_size) + * first_match_bet_market.min_quantity_tick_size + * Decimal("1e18") + ) + + assert order.market_id == first_match_bet_market.id + assert order.order_info.subaccount_id == "1" + assert order.order_info.fee_recipient == fee_recipient + assert order.order_info.price == str(int(expected_price)) + assert order.order_info.quantity == str(int(expected_quantity)) + assert order.order_type == exchange_pb2.OrderType.BUY + assert order.margin == str(int(expected_margin)) + assert order.trigger_price == "0" diff --git a/tests/test_orderhash.py b/tests/test_orderhash.py index c5331e26..c57b6305 100644 --- a/tests/test_orderhash.py +++ b/tests/test_orderhash.py @@ -5,7 +5,6 @@ class TestOrderHashManager: - def test_spot_order_hash(self, requests_mock): network = Network.devnet() composer = Composer(network=network.string()) @@ -17,11 +16,7 @@ def test_spot_order_hash(self, requests_mock): url = network.lcd_endpoint + "/injective/exchange/v1beta1/exchange/" + subaccount_id requests_mock.get(url, json={"nonce": 0}) - order_hash_manager = OrderHashManager( - address=address, - network=network, - subaccount_indexes=[0] - ) + order_hash_manager = OrderHashManager(address=address, network=network, subaccount_indexes=[0]) spot_market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0" fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" @@ -34,7 +29,7 @@ def test_spot_order_hash(self, requests_mock): price=0.524, quantity=0.01, is_buy=True, - is_po=False + is_po=False, ), composer.SpotOrder( market_id=spot_market_id, @@ -43,17 +38,15 @@ def test_spot_order_hash(self, requests_mock): price=27.92, quantity=0.01, is_buy=False, - is_po=False + is_po=False, ), ] order_hashes_response = order_hash_manager.compute_order_hashes( - spot_orders=spot_orders, - derivative_orders=[], - subaccount_index=0 + spot_orders=spot_orders, derivative_orders=[], subaccount_index=0 ) - assert (len(order_hashes_response.spot) == 2) - assert (len(order_hashes_response.derivative) == 0) - assert (order_hashes_response.spot[0] == "0x6b1e4d1fb3012735dd5e386175eb4541c024e0d8dbfeb452767b973d70ae0924") - assert (order_hashes_response.spot[1] == "0xb36146f913955d989269732d167ec554e6d0d544411d82d7f86aef18350b252b") + assert len(order_hashes_response.spot) == 2 + assert len(order_hashes_response.derivative) == 0 + assert order_hashes_response.spot[0] == "0x6b1e4d1fb3012735dd5e386175eb4541c024e0d8dbfeb452767b973d70ae0924" + assert order_hashes_response.spot[1] == "0xb36146f913955d989269732d167ec554e6d0d544411d82d7f86aef18350b252b" diff --git a/tests/test_wallet.py b/tests/test_wallet.py index aaaeeb7f..a2740a97 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -4,20 +4,20 @@ class TestPrivateKey: - def test_private_key_signature_generation(self): private_key = PrivateKey.from_mnemonic("test mnemonic never use other places") signature = private_key.sign(msg="test message".encode()) - expected_signature = (b'\x8f\xae\xcb#z\x9a+\x12\x88\xea\xb5xZ"\x8f\x98y\xb8\x97\xa7F\xd5\xdd\x15s\x05;' - b'\x04\x1d\xbaY|rw\x8b\xbb\x19\xfc\x8e\x15\x8b\xf1\x18\x08\xba\xc7\x15\xed\xb0\xee\x95' - b'\x0e|Ch\x7f\xaf\x9cH\xc6\x9f\xbf\x14\xa5') + expected_signature = ( + b'\x8f\xae\xcb#z\x9a+\x12\x88\xea\xb5xZ"\x8f\x98y\xb8\x97\xa7F\xd5\xdd\x15s\x05;' + b"\x04\x1d\xbaY|rw\x8b\xbb\x19\xfc\x8e\x15\x8b\xf1\x18\x08\xba\xc7\x15\xed\xb0\xee\x95" + b"\x0e|Ch\x7f\xaf\x9cH\xc6\x9f\xbf\x14\xa5" + ) - assert (expected_signature == signature) + assert expected_signature == signature class TestPublicKey: - def test_convert_public_key_to_address(self): private_key = PrivateKey.from_mnemonic("test mnemonic never use other places") public_key = private_key.to_public_key() @@ -27,4 +27,4 @@ def test_convert_public_key_to_address(self): hashed_value = keccak(key[1:]) expected_address = Address(hashed_value[12:]) - assert (expected_address == address) + assert expected_address == address