diff --git a/README.md b/README.md index a13911d3..93a165d3 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ pip install nibiru-py ### Usage Requires Python 3.7+ -[Examples](https://github.com/NibiruLabs/sdk-python/tree/master/examples) +[Examples](https://github.com/NibiruChain/sdk-python/tree/master/examples) ```bash $ pipenv shell $ pipenv install diff --git a/compatibility-tests/README.md b/compatibility-tests/README.md index 25abb93e..83f54f75 100644 --- a/compatibility-tests/README.md +++ b/compatibility-tests/README.md @@ -8,7 +8,7 @@ The aim of this repo was to test all python versions from 3.7.0 to 3.9.6 for com A) Downloads all python versions and extracts the contents B) Opens a subshell and installs python - C) Installs all the dependencies used by the Injective Exchange API and Chain Client + C) Installs all the dependencies used by the Nibiru Exchange API and Chain Client D) Saves the python version and the stdout/stderr of the tests.py script to the results.txt file to have both successful and error output. E) Purges python and all its dependencies, repeats until the last version. @@ -16,7 +16,7 @@ The aim of this repo was to test all python versions from 3.7.0 to 3.9.6 for com 2. tests.py -This python script imports all the libraries used by the Injective Exchange API and Chain Client. It makes a gRPC request and uses the data to broadcast a transaction to the chain with both cosmos-sdk and exchange messages using a REST API endpoint. Certain libraries are imported from injective-py which you can find [here](https://pypi.org/project/injective-py/). +This python script imports all the libraries used by the Nibiru Exchange API and Chain Client. It makes a gRPC request and uses the data to broadcast a transaction to the chain with both cosmos-sdk and exchange messages using a REST API endpoint. Certain libraries are imported from nibiru-py which you can find [here](https://pypi.org/project/injective-py/). 3. results.txt diff --git a/compatibility-tests/run.sh b/compatibility-tests/run.sh index efd38396..b4686786 100644 --- a/compatibility-tests/run.sh +++ b/compatibility-tests/run.sh @@ -20,7 +20,7 @@ install_libraries() { python3 -m pip install grpcio python3 -m pip install typing python3 -m pip install protobuf - python3 -m pip install injective-py + python3 -m pip install nibiru-py } wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz diff --git a/compatibility-tests/tests.py b/compatibility-tests/tests.py index 98feaed1..7fa1b11a 100644 --- a/compatibility-tests/tests.py +++ b/compatibility-tests/tests.py @@ -10,7 +10,7 @@ import grpc from typing import Any, Dict, List -from injective.chain_client._wallet import ( +from nibiru.chain_client._wallet import ( generate_wallet, privkey_to_address, privkey_to_pubkey, @@ -18,9 +18,9 @@ seed_to_privkey, DEFAULT_BECH32_HRP, ) -from injective.chain_client._typings import SyncMode -import injective.exchange_api.injective_accounts_rpc_pb2 as accounts_rpc_pb -import injective.exchange_api.injective_accounts_rpc_pb2_grpc as accounts_rpc_grpc +from nibiru.chain_client._typings import SyncMode +import nibiru.exchange_api.nibiru_accounts_rpc_pb2 as accounts_rpc_pb +import nibiru.exchange_api.nibiru_accounts_rpc_pb2_grpc as accounts_rpc_grpc MIN_GAS_PRICE = 500000000 @@ -35,9 +35,9 @@ def __init__( sequence: int, fee: int, gas: int, - fee_denom: str = "inj", + fee_denom: str = "unibi", memo: str = "", - chain_id: str = "injective-888", + chain_id: str = "nibiru-888", hrp: str = DEFAULT_BECH32_HRP, sync_mode: SyncMode = "block", ) -> None: @@ -66,7 +66,7 @@ def add_cosmos_bank_msg_send(self, recipient: str, amount: int, denom: str = "in } self._msgs.append(msg) - # Injective • Exchange Module + # Nibiru Exchange Module def add_exchange_msg_deposit(self, subaccount: str, amount: int, denom: str = "inj") -> None: msg = { @@ -93,7 +93,7 @@ def get_signed(self) -> str: "signatures": [ { "signature": self._sign(), - "pub_key": {"type": "injective/PubKeyEthSecp256k1", "value": base64_pubkey}, + "pub_key": {"type": "nibiru/PubKeyEthSecp256k1", "value": base64_pubkey}, "account_number": str(self._account_num), "sequence": str(self._sequence), } @@ -139,8 +139,8 @@ async def main() -> None: 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: - accounts_rpc = accounts_rpc_grpc.InjectiveAccountsRPCStub(channel) + async with grpc.aio.insecure_channel('testnet-sentry0.nibiru.network:9910') as channel: + accounts_rpc = accounts_rpc_grpc.nibiruAccountsRPCStub(channel) account_addr = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku" subacc = await accounts_rpc.SubaccountsList(accounts_rpc_pb.SubaccountsListRequest(account_address = account_addr)) @@ -175,7 +175,7 @@ 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, + 'GET', 'http://staking-lcd-testnet.nibiru.network/cosmos/auth/v1beta1/accounts/' + address, headers={'Accept-Encoding': 'application/json'}, ) as response: if response.status != 200: @@ -189,7 +189,7 @@ async def get_account_num_seq(address: str) -> (int, int): 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, + 'POST', 'http://staking-lcd-testnet.nibiru.network/txs', data=tx_json, headers={'Content-Type': 'application/json'}, ) as response: if response.status != 200: diff --git a/compatibility-tests/unit_tests.py b/compatibility-tests/unit_tests.py index 31314aea..33c41df0 100644 --- a/compatibility-tests/unit_tests.py +++ b/compatibility-tests/unit_tests.py @@ -7,7 +7,7 @@ import base64 from typing import Any, Dict, List -from injective.chain_client._wallet import ( +from nibiru.chain_client._wallet import ( generate_wallet, privkey_to_address, privkey_to_pubkey, @@ -16,9 +16,9 @@ DEFAULT_BECH32_HRP, ) -from injective.chain_client._typings import SyncMode -import injective.exchange_api.injective_accounts_rpc_pb2 as accounts_rpc_pb -import injective.exchange_api.injective_accounts_rpc_pb2_grpc as accounts_rpc_grpc +from nibiru.chain_client._typings import SyncMode +import nibiru.exchange_api.nibiru_accounts_rpc_pb2 as accounts_rpc_pb +import nibiru.exchange_api.nibiru_accounts_rpc_pb2_grpc as accounts_rpc_grpc MIN_GAS_PRICE = 500000000 @@ -34,7 +34,7 @@ def __init__( gas: int, fee_denom: str = "inj", memo: str = "", - chain_id: str = "injective-888", + chain_id: str = "nibiru-888", hrp: str = DEFAULT_BECH32_HRP, sync_mode: SyncMode = "block", ) -> None: @@ -62,7 +62,7 @@ def add_cosmos_bank_msg_send(self, recipient: str, amount: int, denom: str = "in } self._msgs.append(msg) - # Injective • Exchange Module + # nibiru • Exchange Module def add_exchange_msg_deposit(self, subaccount: str, amount: int, denom: str = "inj") -> None: msg = { @@ -89,7 +89,7 @@ def get_signed(self) -> str: "signatures": [ { "signature": self._sign(), - "pub_key": {"type": "injective/PubKeyEthSecp256k1", "value": base64_pubkey}, + "pub_key": {"type": "nibiru/PubKeyEthSecp256k1", "value": base64_pubkey}, "account_number": str(self._account_num), "sequence": str(self._sequence), } @@ -130,7 +130,7 @@ 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, + 'GET', 'http://staking-lcd-testnet.nibiru.network/cosmos/auth/v1beta1/accounts/' + address, headers={'Accept-Encoding': 'application/json'}, ) as response: if response.status != 200: @@ -144,7 +144,7 @@ async def get_account_num_seq(address: str) -> (int, int): 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, + 'POST', 'http://staking-lcd-testnet.nibiru.network/txs', data=tx_json, headers={'Content-Type': 'application/json'}, ) as response: if response.status != 200: @@ -168,8 +168,8 @@ async def msg_send(): 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: - accounts_rpc = accounts_rpc_grpc.InjectiveAccountsRPCStub(channel) + async with grpc.aio.insecure_channel('testnet-sentry0.nibiru.network:9910') as channel: + accounts_rpc = accounts_rpc_grpc.nibiruAccountsRPCStub(channel) account_addr = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku" subacc = await accounts_rpc.SubaccountsList(accounts_rpc_pb.SubaccountsListRequest(account_address = account_addr)) diff --git a/examples/chain_client/dex/create_pool.py b/examples/chain_client/dex/create_pool.py index 144029f2..364e4915 100644 --- a/examples/chain_client/dex/create_pool.py +++ b/examples/chain_client/dex/create_pool.py @@ -15,24 +15,12 @@ import asyncio import logging -from nibiru import Composer, PoolAsset, Client, Transaction, Network, PrivateKey -from nibiru.constant import GAS_PRICE +from nibiru import Sdk, Composer, PoolAsset async def main() -> None: - # select network: local, testnet, mainnet - network = Network.local() - - # initialize grpc client - client = Client(network, insecure=True) - await client.sync_timeout_height() - - priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - pub_key = priv_key.to_public_key() - address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) - - # prepare tx msg - msg = Composer.dex.create_pool( - creator=address.to_acc_bech32(), + trader = Sdk.authorize("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") + res = await trader.tx.dex.create_pool( + creator=trader.address, swap_fee="2", exit_fee="3", assets=[ @@ -40,38 +28,7 @@ async def main() -> None: PoolAsset(token=Composer.coin(5, "unibi"),weight="4"), ], ) - - # build sim tx - tx = ( - Transaction() - .with_messages(msg) - .with_sequence(address.get_sequence()) - .with_account_num(address.get_number()) - .with_chain_id(network.chain_id) - .with_signer(priv_key) - ) - sim_tx_raw_bytes = tx.get_signed_tx_data() - - # simulate tx - (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) - if not success: - print(sim_res) - return - - # build tx - gas_limit = sim_res.gas_info.gas_used * 1.25 - fee = [Composer.coin( - amount=int(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) - tx_raw_bytes = tx.get_signed_tx_data() - - # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode - res = await client.send_tx_sync_mode(tx_raw_bytes) print(res) - print("gas wanted: {}".format(gas_limit)) - print("gas fee: {} unibi".format(res.gas_used * GAS_PRICE)) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) diff --git a/examples/chain_client/dex/create_pool2.py b/examples/chain_client/dex/create_pool2.py deleted file mode 100644 index 364e4915..00000000 --- a/examples/chain_client/dex/create_pool2.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2022 Nibiru Chain -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import asyncio -import logging - -from nibiru import Sdk, Composer, PoolAsset - -async def main() -> None: - trader = Sdk.authorize("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - res = await trader.tx.dex.create_pool( - creator=trader.address, - swap_fee="2", - exit_fee="3", - assets=[ - PoolAsset(token=Composer.coin(4, "unusd"),weight="3"), - PoolAsset(token=Composer.coin(5, "unibi"),weight="4"), - ], - ) - print(res) - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/dex/create_pool_ext.py b/examples/chain_client/dex/create_pool_ext.py new file mode 100644 index 00000000..144029f2 --- /dev/null +++ b/examples/chain_client/dex/create_pool_ext.py @@ -0,0 +1,78 @@ +# Copyright 2022 Nibiru Chain +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import logging + +from nibiru import Composer, PoolAsset, Client, Transaction, Network, PrivateKey +from nibiru.constant import GAS_PRICE + +async def main() -> None: + # select network: local, testnet, mainnet + network = Network.local() + + # initialize grpc client + client = Client(network, insecure=True) + await client.sync_timeout_height() + + priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") + pub_key = priv_key.to_public_key() + address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) + + # prepare tx msg + msg = Composer.dex.create_pool( + creator=address.to_acc_bech32(), + swap_fee="2", + exit_fee="3", + assets=[ + PoolAsset(token=Composer.coin(4, "unusd"),weight="3"), + PoolAsset(token=Composer.coin(5, "unibi"),weight="4"), + ], + ) + + # build sim tx + tx = ( + Transaction() + .with_messages(msg) + .with_sequence(address.get_sequence()) + .with_account_num(address.get_number()) + .with_chain_id(network.chain_id) + .with_signer(priv_key) + ) + sim_tx_raw_bytes = tx.get_signed_tx_data() + + # simulate tx + (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) + if not success: + print(sim_res) + return + + # build tx + gas_limit = sim_res.gas_info.gas_used * 1.25 + fee = [Composer.coin( + amount=int(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) + tx_raw_bytes = tx.get_signed_tx_data() + + # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode + res = await client.send_tx_sync_mode(tx_raw_bytes) + print(res) + print("gas wanted: {}".format(gas_limit)) + print("gas fee: {} unibi".format(res.gas_used * GAS_PRICE)) + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/msg_delegate.py b/examples/chain_client/msg_delegate.py index 485c31a6..3f88263e 100644 --- a/examples/chain_client/msg_delegate.py +++ b/examples/chain_client/msg_delegate.py @@ -1,85 +1,85 @@ -# Copyright 2022 Injective Labs -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# # Copyright 2022 Nibiru Labs +# # +# # Licensed under the Apache License, Version 2.0 (the "License"); +# # you may not use this file except in compliance with the License. +# # You may obtain a copy of the License at +# # +# # http://www.apache.org/licenses/LICENSE-2.0 +# # +# # Unless required by applicable law or agreed to in writing, software +# # distributed under the License is distributed on an "AS IS" BASIS, +# # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# # See the License for the specific language governing permissions and +# # limitations under the License. -import asyncio -import logging +# import asyncio +# import logging -from nibiru.composer import Composer as ProtoMsgComposer -from nibiru.client import Client -from nibiru.transaction import Transaction -from nibiru.network import Network -from nibiru.wallet import PrivateKey +# from nibiru.composer import Composer as ProtoMsgComposer +# from nibiru.client import Client +# from nibiru.transaction import Transaction +# from nibiru.network import Network +# from nibiru.wallet import PrivateKey -async def main() -> None: - # select network: local, testnet, mainnet - network = Network.local() - composer = ProtoMsgComposer(network=network.string()) +# async def main() -> None: +# # select network: local, testnet, mainnet +# network = Network.local() +# composer = ProtoMsgComposer(network=network.string()) - # initialize grpc client - client = Client(network, insecure=True) - await client.sync_timeout_height() +# # initialize grpc client +# client = Client(network, insecure=True) +# await client.sync_timeout_height() - # load account - priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - pub_key = priv_key.to_public_key() - address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) +# # load account +# priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") +# pub_key = priv_key.to_public_key() +# address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) - # prepare tx msg - validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" - amount = 100 +# # prepare tx msg +# validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" +# amount = 100 - msg = composer.msg_delegate( - delegator_address=address.to_acc_bech32(), - validator_address=validator_address, - amount=amount - ) +# msg = composer.msg_delegate( +# delegator_address=address.to_acc_bech32(), +# validator_address=validator_address, +# amount=amount +# ) - # build sim tx - tx = ( - Transaction() - .with_messages(msg) - .with_sequence(address.get_sequence()) - .with_account_num(address.get_number()) - .with_chain_id(network.chain_id) - .with_signer(priv_key) - ) - sim_tx_raw_bytes = tx.get_signed_tx_data() +# # build sim tx +# tx = ( +# Transaction() +# .with_messages(msg) +# .with_sequence(address.get_sequence()) +# .with_account_num(address.get_number()) +# .with_chain_id(network.chain_id) +# .with_signer(priv_key) +# ) +# sim_tx_raw_bytes = tx.get_signed_tx_data() - # simulate tx - (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) - if not success: - print(sim_res) - return +# # simulate tx +# (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) +# if not success: +# print(sim_res) +# return - # 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) - tx_raw_bytes = tx.get_signed_tx_data() +# # 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) +# tx_raw_bytes = tx.get_signed_tx_data() - # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode - res = await client.send_tx_sync_mode(tx_raw_bytes) - print(res) - print("gas wanted: {}".format(gas_limit)) - print("gas fee: {} unibi".format(gas_fee)) +# # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode +# res = await client.send_tx_sync_mode(tx_raw_bytes) +# print(res) +# print("gas wanted: {}".format(gas_limit)) +# print("gas fee: {} unibi".format(gas_fee)) -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - asyncio.get_event_loop().run_until_complete(main()) +# if __name__ == "__main__": +# logging.basicConfig(level=logging.INFO) +# asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/msg_exec.py b/examples/chain_client/msg_exec.py index b4d54ec4..32a8bd49 100644 --- a/examples/chain_client/msg_exec.py +++ b/examples/chain_client/msg_exec.py @@ -1,4 +1,4 @@ -# # Copyright 2022 Injective Labs +# # Copyright 2022 Nibiru Labs # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. diff --git a/examples/chain_client/msg_revoke.py b/examples/chain_client/msg_revoke.py index c9a60c7a..69db39ff 100644 --- a/examples/chain_client/msg_revoke.py +++ b/examples/chain_client/msg_revoke.py @@ -1,83 +1,83 @@ -# Copyright 2022 Injective Labs -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# # Copyright 2022 Nibiru Labs +# # +# # Licensed under the Apache License, Version 2.0 (the "License"); +# # you may not use this file except in compliance with the License. +# # You may obtain a copy of the License at +# # +# # http://www.apache.org/licenses/LICENSE-2.0 +# # +# # Unless required by applicable law or agreed to in writing, software +# # distributed under the License is distributed on an "AS IS" BASIS, +# # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# # See the License for the specific language governing permissions and +# # limitations under the License. -import asyncio -import logging +# import asyncio +# import logging -from nibiru.composer import Composer as ProtoMsgComposer -from nibiru.client import Client -from nibiru.transaction import Transaction -from nibiru.network import Network -from nibiru.wallet import PrivateKey +# from nibiru.composer import Composer as ProtoMsgComposer +# from nibiru.client import Client +# from nibiru.transaction import Transaction +# from nibiru.network import Network +# from nibiru.wallet import PrivateKey -async def main() -> None: - # select network: local, testnet, mainnet - network = Network.local() - composer = ProtoMsgComposer(network=network.string()) +# async def main() -> None: +# # select network: local, testnet, mainnet +# network = Network.local() +# composer = ProtoMsgComposer(network=network.string()) - # initialize grpc client - client = Client(network, insecure=True) - await client.sync_timeout_height() +# # initialize grpc client +# client = Client(network, insecure=True) +# await client.sync_timeout_height() - # load account - priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - pub_key = priv_key.to_public_key() - address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) - subaccount_id = address.get_subaccount_id(index=0) +# # load account +# priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") +# pub_key = priv_key.to_public_key() +# address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) +# subaccount_id = address.get_subaccount_id(index=0) - # prepare tx msg - msg = composer.msg_revoke( - granter = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", - grantee = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", - msg_type = "/injective.exchange.v1beta1.MsgCreateSpotLimitOrder" - ) +# # prepare tx msg +# msg = composer.msg_revoke( +# granter = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", +# grantee = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", +# msg_type = "/nibiru.exchange.v1beta1.MsgCreateSpotLimitOrder" +# ) - # build sim tx - tx = ( - Transaction() - .with_messages(msg) - .with_sequence(address.get_sequence()) - .with_account_num(address.get_number()) - .with_chain_id(network.chain_id) - .with_signer(priv_key) - ) - sim_tx_raw_bytes = tx.get_signed_tx_data() +# # build sim tx +# tx = ( +# Transaction() +# .with_messages(msg) +# .with_sequence(address.get_sequence()) +# .with_account_num(address.get_number()) +# .with_chain_id(network.chain_id) +# .with_signer(priv_key) +# ) +# sim_tx_raw_bytes = tx.get_signed_tx_data() - # simulate tx - (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) - if not success: - print(sim_res) - return +# # simulate tx +# (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) +# if not success: +# print(sim_res) +# return - # 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) - tx_raw_bytes = tx.get_signed_tx_data() +# # 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) +# tx_raw_bytes = tx.get_signed_tx_data() - # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode - res = await client.send_tx_sync_mode(tx_raw_bytes) - print(res) - print("gas wanted: {}".format(gas_limit)) - print("gas fee: {} unibi".format(gas_fee)) +# # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode +# res = await client.send_tx_sync_mode(tx_raw_bytes) +# print(res) +# print("gas wanted: {}".format(gas_limit)) +# print("gas fee: {} unibi".format(gas_fee)) -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - asyncio.get_event_loop().run_until_complete(main()) +# if __name__ == "__main__": +# logging.basicConfig(level=logging.INFO) +# asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/msg_send.py b/examples/chain_client/msg_send.py index 0d0989c6..840c8ab2 100644 --- a/examples/chain_client/msg_send.py +++ b/examples/chain_client/msg_send.py @@ -15,67 +15,23 @@ import asyncio import logging -from nibiru.composer import Composer -from nibiru.client import Client -from nibiru.constant import GAS_PRICE -from nibiru.transaction import Transaction -from nibiru.network import Network -from nibiru.wallet import PrivateKey - +from nibiru import Sdk async def main() -> None: - # select network: local, testnet, mainnet - network = Network.local() - - # initialize grpc client - client = Client(network, insecure=True) - await client.sync_timeout_height() + sender = Sdk.authorize("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") + receiver = Sdk.authorize() - # load account - priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - pub_key = priv_key.to_public_key() - address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) - - # prepare tx msg - msg = Composer.msg_send( - from_address=address.to_acc_bech32(), - to_address="nibi1j38z56cus02vq6f5m0mz2mygufvjss43fj34gk", + res = await sender.tx.msg_send( + from_address=sender.address, + to_address=receiver.address, amount=5, - denom='unibi' - ) - - # build tx - tx = ( - Transaction() - .with_messages(msg) - .with_sequence(address.get_sequence()) - .with_account_num(address.get_number()) - .with_chain_id(network.chain_id) - .with_signer(priv_key) + denom='unibi', + # additional params for gas price can be passed + # gas_price = 7, + # gas_multiplier = 1.25, + # gas_wanted = 50_000, ) - sim_tx_raw_bytes = tx.get_signed_tx_data() - - # simulate tx - (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) - if not success: - print(sim_res) - return - - print(sim_res) - # build tx - gas_limit = sim_res.gas_info.gas_used * 1.25 # add 25% to the limit - fee = [composer.Coin( - amount=int(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) - tx_raw_bytes = tx.get_signed_tx_data() - - # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode - res = await client.send_tx_block_mode(tx_raw_bytes) - print(res) - print("gas wanted: {}".format(gas_limit)) - print("gas fee: {} unibi".format(res.gas_used * GAS_PRICE)) + logging.info("Result: %s", res) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) diff --git a/examples/chain_client/msg_send2.py b/examples/chain_client/msg_send2.py deleted file mode 100644 index bab4f4df..00000000 --- a/examples/chain_client/msg_send2.py +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright 2022 Nibiru Chain -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import asyncio -import logging - -from nibiru import Sdk - -async def main() -> None: - trader = Sdk.authorize("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - trader2 = Sdk.authorize() - - res = await trader.tx.msg_send( - from_address=trader.address, - to_address=trader2.address, - amount=5, - denom='unibi' - ) - print(res) - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/msg_send_ext.py b/examples/chain_client/msg_send_ext.py new file mode 100644 index 00000000..776e02b1 --- /dev/null +++ b/examples/chain_client/msg_send_ext.py @@ -0,0 +1,78 @@ +# Copyright 2022 Nibiru Chain +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import logging + +from nibiru import Composer, Client, Transaction, Network, PrivateKey +from nibiru.constant import GAS_PRICE + + +async def main() -> None: + # select network: local, testnet, mainnet + network = Network.local() + + # initialize grpc client + client = Client(network, insecure=True) + await client.sync_timeout_height() + + # load account + priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") + pub_key = priv_key.to_public_key() + address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) + + # prepare tx msg + msg = Composer.msg_send( + from_address=address.to_acc_bech32(), + to_address="nibi1j38z56cus02vq6f5m0mz2mygufvjss43fj34gk", + amount=5, + denom='unibi' + ) + + # build tx + tx = ( + Transaction() + .with_messages(msg) + .with_sequence(address.get_sequence()) + .with_account_num(address.get_number()) + .with_chain_id(network.chain_id) + .with_signer(priv_key) + ) + sim_tx_raw_bytes = tx.get_signed_tx_data() + + # simulate tx + (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) + if not success: + print(sim_res) + return + + print(sim_res) + # build tx + gas_limit = sim_res.gas_info.gas_used * 1.25 # add 25% to the limit + fee = [Composer.coin( + amount=int(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) + tx_raw_bytes = tx.get_signed_tx_data() + + # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode + res = await client.send_tx_block_mode(tx_raw_bytes) + print(res) + print("gas wanted: {}".format(gas_limit)) + print("gas fee: {} unibi".format(res.gas_used * GAS_PRICE)) + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/msg_withdraw_delegator_reward.py b/examples/chain_client/msg_withdraw_delegator_reward.py index a7b06a8a..4025b662 100644 --- a/examples/chain_client/msg_withdraw_delegator_reward.py +++ b/examples/chain_client/msg_withdraw_delegator_reward.py @@ -1,83 +1,83 @@ -# Copyright 2022 Injective Labs -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# # Copyright 2022 Injective Labs +# # +# # Licensed under the Apache License, Version 2.0 (the "License"); +# # you may not use this file except in compliance with the License. +# # You may obtain a copy of the License at +# # +# # http://www.apache.org/licenses/LICENSE-2.0 +# # +# # Unless required by applicable law or agreed to in writing, software +# # distributed under the License is distributed on an "AS IS" BASIS, +# # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# # See the License for the specific language governing permissions and +# # limitations under the License. -import asyncio -import logging +# import asyncio +# import logging -from nibiru.composer import Composer as ProtoMsgComposer -from nibiru.client import Client -from nibiru.transaction import Transaction -from nibiru.network import Network -from nibiru.wallet import PrivateKey +# from nibiru.composer import Composer as ProtoMsgComposer +# from nibiru.client import Client +# from nibiru.transaction import Transaction +# from nibiru.network import Network +# from nibiru.wallet import PrivateKey -async def main() -> None: - # select network: local, testnet, mainnet - network = Network.local() - composer = ProtoMsgComposer(network=network.string()) +# async def main() -> None: +# # select network: local, testnet, mainnet +# network = Network.local() +# composer = ProtoMsgComposer(network=network.string()) - # initialize grpc client - client = Client(network, insecure=True) - await client.sync_timeout_height() +# # initialize grpc client +# client = Client(network, insecure=True) +# await client.sync_timeout_height() - # load account - priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - pub_key = priv_key.to_public_key() - address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) +# # load account +# priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") +# pub_key = priv_key.to_public_key() +# address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) - # prepare tx msg - validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" +# # prepare tx msg +# validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" - msg = composer.msg_withdraw_delegator_reward( - delegator_address=address.to_acc_bech32(), - validator_address=validator_address - ) +# msg = composer.msg_withdraw_delegator_reward( +# delegator_address=address.to_acc_bech32(), +# validator_address=validator_address +# ) - # build sim tx - tx = ( - Transaction() - .with_messages(msg) - .with_sequence(address.get_sequence()) - .with_account_num(address.get_number()) - .with_chain_id(network.chain_id) - .with_signer(priv_key) - ) - sim_tx_raw_bytes = tx.get_signed_tx_data() +# # build sim tx +# tx = ( +# Transaction() +# .with_messages(msg) +# .with_sequence(address.get_sequence()) +# .with_account_num(address.get_number()) +# .with_chain_id(network.chain_id) +# .with_signer(priv_key) +# ) +# sim_tx_raw_bytes = tx.get_signed_tx_data() - # simulate tx - (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) - if not success: - print(sim_res) - return +# # simulate tx +# (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) +# if not success: +# print(sim_res) +# return - # 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) - tx_raw_bytes = tx.get_signed_tx_data() +# # 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) +# tx_raw_bytes = tx.get_signed_tx_data() - # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode - res = await client.send_tx_sync_mode(tx_raw_bytes) - print(res) - print("gas wanted: {}".format(gas_limit)) - print("gas fee: {} unibi".format(gas_fee)) +# # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode +# res = await client.send_tx_sync_mode(tx_raw_bytes) +# print(res) +# print("gas wanted: {}".format(gas_limit)) +# print("gas fee: {} unibi".format(gas_fee)) -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - asyncio.get_event_loop().run_until_complete(main()) +# if __name__ == "__main__": +# logging.basicConfig(level=logging.INFO) +# asyncio.get_event_loop().run_until_complete(main()) diff --git a/examples/chain_client/perp/open_position.py b/examples/chain_client/perp/open_position.py index ced01e42..62dc0edf 100644 --- a/examples/chain_client/perp/open_position.py +++ b/examples/chain_client/perp/open_position.py @@ -14,71 +14,20 @@ import asyncio import logging -from nibiru.common import Side - -from nibiru.composer import Composer -from nibiru.client import Client -from nibiru.transaction import Transaction -from nibiru.network import Network -from nibiru.wallet import PrivateKey +from nibiru import Sdk, Side async def main() -> None: - # select network: local, testnet, mainnet - network = Network.local() - composer = Composer(network=network.string()) - - # initialize grpc client - client = Client(network, insecure=True) - await client.sync_timeout_height() - - priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") - pub_key = priv_key.to_public_key() - address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) - - # prepare tx msg - msg = composer.perp.open_position( - sender = address.to_acc_bech32(), + trader = Sdk.authorize("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host") + res = await trader.tx.perp.open_position( + sender = trader.address, token_pair = "unusd:unibi", side=Side.BUY, quote_asset_amount="5", leverage="5", base_asset_amount_limit="5", ) - - # build sim tx - tx = ( - Transaction() - .with_messages(msg) - .with_sequence(address.get_sequence()) - .with_account_num(address.get_number()) - .with_chain_id(network.chain_id) - .with_signer(priv_key) - ) - sim_tx_raw_bytes = tx.get_signed_tx_data() - - # simulate tx - (sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes) - if not success: - print(sim_res) - return - - # build tx - gas_price = 1 - gas_limit = sim_res.gas_info.gas_used + 2 # add 2 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) - tx_raw_bytes = tx.get_signed_tx_data() - - # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode - res = await client.send_tx_sync_mode(tx_raw_bytes) print(res) - print("gas wanted: {}".format(gas_limit)) - print("gas fee: {} unibi".format(gas_fee)) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) diff --git a/examples/chain_client/dex/transfer_coins.py b/examples/chain_client/perp/open_position_ext.py similarity index 80% rename from examples/chain_client/dex/transfer_coins.py rename to examples/chain_client/perp/open_position_ext.py index 2560c11c..bc3afb57 100644 --- a/examples/chain_client/dex/transfer_coins.py +++ b/examples/chain_client/perp/open_position_ext.py @@ -1,4 +1,4 @@ -# Copyright 2022 Nibiru Chain +# Copyright 2022 Nibiru Labs # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,18 +14,13 @@ import asyncio import logging +from nibiru.common import Side -from nibiru.composer import Composer, PoolAsset -from nibiru.client import Client -from nibiru.transaction import Transaction -from nibiru.network import Network -from nibiru.wallet import PrivateKey - +from nibiru import Composer, Client, Transaction, Network, PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.local() - composer = Composer(network=network.string()) # initialize grpc client client = Client(network, insecure=True) @@ -36,14 +31,13 @@ async def main() -> None: address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint) # prepare tx msg - msg = composer.dex.create_pool( - creator=address.to_acc_bech32(), - swap_fee="2", - exit_fee="3", - assets=[ - PoolAsset(token=composer.Coin(4, "unusd"),weight="3"), - PoolAsset(token=composer.Coin(5, "uusdc"),weight="4"), - ], + msg = Composer.perp.open_position( + sender = address.to_acc_bech32(), + token_pair = "unusd:unibi", + side=Side.BUY, + quote_asset_amount="5", + leverage="5", + base_asset_amount_limit="5", ) # build sim tx @@ -67,7 +61,7 @@ async def main() -> None: gas_price = 1 gas_limit = sim_res.gas_info.gas_used + 2 # add 2 for gas, fee computation gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( + fee = [Composer.coin( amount=gas_price * gas_limit, denom=network.fee_denom, )] diff --git a/nibiru/__init__.py b/nibiru/__init__.py index 4fd49197..68ef1607 100644 --- a/nibiru/__init__.py +++ b/nibiru/__init__.py @@ -4,4 +4,4 @@ from .composer import Composer from .transaction import Transaction from .wallet import PrivateKey, PublicKey, Address -from .common import PoolAsset, Side \ No newline at end of file +from .common import PoolAsset, Side, TxConfig \ No newline at end of file diff --git a/nibiru/client.py b/nibiru/client.py index 3a454bec..698effdd 100644 --- a/nibiru/client.py +++ b/nibiru/client.py @@ -7,10 +7,10 @@ from typing import List, Optional, Tuple, Union from .clients import ( - DexClient, PerpClient, + Dex as DexClient, Perp as PerpClient, ) -from .exceptions import NotFoundError, EmptyMsgError +from .exceptions import NotFoundError from .proto.cosmos.base.abci.v1beta1 import abci_pb2 as abci_type @@ -152,19 +152,19 @@ async def sync_timeout_height(self): self.timeout_height = block.block.header.height + DEFAULT_TIMEOUTHEIGHT # cookie helper methods - async def fetch_cookie(self, type): + async def fetch_cookie(self, chain_type): metadata = None - if type == "chain": + if chain_type == "chain": req = tendermint_query.GetLatestBlockRequest() metadata = await self.stubCosmosTendermint.GetLatestBlock(req).initial_metadata() time.sleep(DEFAULT_BLOCK_TIME) - # if type == "exchange": + # if chain_type == "exchange": # not sure what to do here, do we have a counterpart or can any req/resp be used?? # req = exchange_meta_rpc_pb.VersionRequest() # metadata = await self.stubMeta.Version(req).initial_metadata() return metadata - async def renew_cookie(self, existing_cookie, type): + async def renew_cookie(self, existing_cookie, chain_type): metadata = None # format cookie date into RFC1123 standard cookie = SimpleCookie() @@ -180,35 +180,35 @@ async def renew_cookie(self, existing_cookie, type): # renew session if timestamp diff < offset timestamp_diff = expire_timestamp - int(time.time()) if timestamp_diff < DEFAULT_SESSION_RENEWAL_OFFSET: - metadata = await self.fetch_cookie(type) + metadata = await self.fetch_cookie(chain_type) else: metadata = (("cookie", existing_cookie),) return metadata - async def load_cookie(self, type): + async def load_cookie(self, chain_type): metadata = None if self.insecure: return metadata - if type == "chain": + if chain_type == "chain": if self.chain_cookie != "": - metadata = await self.renew_cookie(self.chain_cookie, type) - self.set_cookie(metadata, type) + metadata = await self.renew_cookie(self.chain_cookie, chain_type) + self.set_cookie(metadata, chain_type) else: - metadata = await self.fetch_cookie(type) - self.set_cookie(metadata, type) + metadata = await self.fetch_cookie(chain_type) + self.set_cookie(metadata, chain_type) - if type == "exchange": + if chain_type == "exchange": if self.exchange_cookie != "": - metadata = await self.renew_cookie(self.exchange_cookie, type) - self.set_cookie(metadata, type) + metadata = await self.renew_cookie(self.exchange_cookie, chain_type) + self.set_cookie(metadata, chain_type) else: - metadata = await self.fetch_cookie(type) - self.set_cookie(metadata, type) + metadata = await self.fetch_cookie(chain_type) + self.set_cookie(metadata, chain_type) return metadata - def set_cookie(self, metadata, type): + def set_cookie(self, metadata, chain_type): new_cookie = None if self.insecure: return new_cookie @@ -220,7 +220,7 @@ def set_cookie(self, metadata, type): if new_cookie == None: return - if type == "chain": + if chain_type == "chain": # write to client instance self.chain_cookie = new_cookie # write to disk @@ -229,7 +229,7 @@ def set_cookie(self, metadata, type): cookie_file.close() print("chain session cookie saved to disk") - if type == "exchange": + if chain_type == "exchange": self.exchange_cookie = new_cookie # default client methods @@ -273,26 +273,26 @@ async def simulate_tx( ) -> Tuple[Union[abci_type.SimulationResponse, grpc.RpcError], bool]: try: req = tx_service.SimulateRequest(tx_bytes=tx_byte) - metadata = await self.load_cookie(type="chain") + metadata = await self.load_cookie(chain_type="chain") return await self.stubTx.Simulate.__call__(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) - metadata = await self.load_cookie(type="chain") + metadata = await self.load_cookie(chain_type="chain") result = await self.stubTx.BroadcastTx.__call__(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) - metadata = await self.load_cookie(type="chain") + metadata = await self.load_cookie(chain_type="chain") result = await self.stubTx.BroadcastTx.__call__(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) - metadata = await self.load_cookie(type="chain") + metadata = await self.load_cookie(chain_type="chain") result = await self.stubTx.BroadcastTx.__call__(req, metadata=metadata) return result.tx_response @@ -323,6 +323,3 @@ async def get_bank_balance(self, address: str, denom: str): denom=denom ) ) - - # Nibiru Exchange client methods - diff --git a/nibiru/clients/__init__.py b/nibiru/clients/__init__.py index e675451e..9580fa8d 100644 --- a/nibiru/clients/__init__.py +++ b/nibiru/clients/__init__.py @@ -1,2 +1,2 @@ -from .dex_client import DexClient -from .perp_client import PerpClient +from .dex import Dex +from .perp import Perp diff --git a/nibiru/clients/dex_client.py b/nibiru/clients/dex.py similarity index 86% rename from nibiru/clients/dex_client.py rename to nibiru/clients/dex.py index 8f70f6bb..e02dc15d 100644 --- a/nibiru/clients/dex_client.py +++ b/nibiru/clients/dex.py @@ -1,13 +1,17 @@ from grpc import Channel +from typing import List + from nibiru.proto.cosmos.base.v1beta1 import coin_pb2 as cosmos_base_coin_pb from nibiru.proto.dex.v1 import ( query_pb2_grpc as dex_query, query_pb2 as dex_type, ) from nibiru.proto.cosmos.base.query.v1beta1.pagination_pb2 import PageRequest -from typing import List -class DexClient: +class Dex: + """ + Dex allows to query the endpoints made available by the Nibiru Chain's DEX module. + """ def __init__( self, channel: Channel @@ -27,6 +31,15 @@ async def pool(self, pool_id: int): return await self.api.Pool(req) async def pools(self, **kwargs): + ''' + Returns all available pools + Parameters: + key (bytes): The page key for the next page. Only key or offset should be set + offset (int): The number of entries to skip. Only offset or key should be set + limit (int): The number of max results in the page + count_total (bool): Indicates if the response should contain the total number of results + reverse (bool): Indicates if the results should be returned in descending order + ''' req = dex_type.QueryPoolsRequest(pagination = PageRequest( key = kwargs.get("key"), offset = kwargs.get("offset"), diff --git a/nibiru/clients/perp_client.py b/nibiru/clients/perp.py similarity index 83% rename from nibiru/clients/perp_client.py rename to nibiru/clients/perp.py index 57c5cce3..06695096 100644 --- a/nibiru/clients/perp_client.py +++ b/nibiru/clients/perp.py @@ -4,7 +4,10 @@ query_pb2 as perp_type, ) -class PerpClient: +class Perp: + """ + Perp allows to query the endpoints made available by the Nibiru Chain's PERP module. + """ def __init__( self, channel: Channel diff --git a/nibiru/common.py b/nibiru/common.py index d89d925e..755f0459 100644 --- a/nibiru/common.py +++ b/nibiru/common.py @@ -1,6 +1,6 @@ from enum import Enum from dataclasses import dataclass -from nibiru.proto.cosmos.base.v1beta1 import coin_pb2 as coin_pb +from .proto.cosmos.base.v1beta1 import coin_pb2 as coin_pb class Side(Enum): BUY = 1 @@ -10,3 +10,17 @@ class Side(Enum): class PoolAsset: token: coin_pb.Coin weight: str + +class TxConfig: + def __init__(self, gas_wanted: int = 0, gas_multiplier: float = 0, gas_price: float = 0): + ''' + Parameters: + gas_wanted (int): Set the absolute gas_wanted to be used + gas_multiplier (float): Set the gas multiplier that's being applied to the estimated gas, defaults to 1.25. + If gas_wanted is set this property is ignored. + gas_price(float): Set the gas price used to calculate the fee + ''' + self.gas_multiplier = gas_multiplier + self.gas_wanted = gas_wanted + self.gas_price = gas_price + \ No newline at end of file diff --git a/nibiru/composer.py b/nibiru/composer.py index 9a6c42cd..52a3e441 100644 --- a/nibiru/composer.py +++ b/nibiru/composer.py @@ -1,24 +1,19 @@ from google.protobuf import any_pb2 +from typing import List -from nibiru.composers import ( - DexComposer, PerpComposer, +from .composers import ( + Dex, Perp ) from .proto.cosmos.authz.v1beta1 import tx_pb2 as cosmos_authz_tx_pb - from .proto.cosmos.bank.v1beta1 import tx_pb2 as cosmos_bank_tx_pb from .proto.cosmos.base.v1beta1 import coin_pb2 as cosmos_base_coin_pb - from .proto.cosmos.staking.v1beta1 import tx_pb2 as cosmos_staking_tx_pb - from .proto.cosmos.distribution.v1beta1 import tx_pb2 as cosmos_distribution_tx_pb -from typing import List - - class Composer: - dex = DexComposer - perp = PerpComposer + dex = Dex + perp = Perp @staticmethod def coin(amount: float, denom: str): @@ -72,34 +67,34 @@ def msg_withdraw_delegator_reward( delegator_address: str, validator_address: st # if not simulation: # data = bytes.fromhex(data) # header_map = { - # "/injective.exchange.v1beta1.MsgCreateSpotLimitOrder": injective_exchange_tx_pb.MsgCreateSpotLimitOrderResponse, - # "/injective.exchange.v1beta1.MsgCreateSpotMarketOrder": injective_exchange_tx_pb.MsgCreateSpotMarketOrderResponse, - # "/injective.exchange.v1beta1.MsgCreateDerivativeLimitOrder": injective_exchange_tx_pb.MsgCreateDerivativeLimitOrderResponse, - # "/injective.exchange.v1beta1.MsgCreateDerivativeMarketOrder": injective_exchange_tx_pb.MsgCreateDerivativeMarketOrderResponse, - # "/injective.exchange.v1beta1.MsgCancelSpotOrder": injective_exchange_tx_pb.MsgCancelSpotOrderResponse, - # "/injective.exchange.v1beta1.MsgCancelDerivativeOrder": injective_exchange_tx_pb.MsgCancelDerivativeOrderResponse, - # "/injective.exchange.v1beta1.MsgBatchCancelSpotOrders": injective_exchange_tx_pb.MsgBatchCancelSpotOrdersResponse, - # "/injective.exchange.v1beta1.MsgBatchCancelDerivativeOrders": injective_exchange_tx_pb.MsgBatchCancelDerivativeOrdersResponse, - # "/injective.exchange.v1beta1.MsgBatchCreateSpotLimitOrders": injective_exchange_tx_pb.MsgBatchCreateSpotLimitOrdersResponse, - # "/injective.exchange.v1beta1.MsgBatchCreateDerivativeLimitOrders": injective_exchange_tx_pb.MsgBatchCreateDerivativeLimitOrdersResponse, - # "/injective.exchange.v1beta1.MsgBatchUpdateOrders": injective_exchange_tx_pb.MsgBatchUpdateOrdersResponse, - # "/injective.exchange.v1beta1.MsgDeposit": injective_exchange_tx_pb.MsgDepositResponse, - # "/injective.exchange.v1beta1.MsgWithdraw": injective_exchange_tx_pb.MsgWithdrawResponse, - # "/injective.exchange.v1beta1.MsgSubaccountTransfer": injective_exchange_tx_pb.MsgSubaccountTransferResponse, - # "/injective.exchange.v1beta1.MsgLiquidatePosition": injective_exchange_tx_pb.MsgLiquidatePositionResponse, - # "/injective.exchange.v1beta1.MsgIncreasePositionMargin": injective_exchange_tx_pb.MsgIncreasePositionMarginResponse, - # "/injective.auction.v1beta1.MsgBid": injective_auction_tx_pb.MsgBidResponse, - # "/injective.exchange.v1beta1.MsgCreateBinaryOptionsLimitOrder": injective_exchange_tx_pb.MsgCreateBinaryOptionsLimitOrderResponse, - # "/injective.exchange.v1beta1.MsgCreateBinaryOptionsMarketOrder": injective_exchange_tx_pb.MsgCreateBinaryOptionsMarketOrderResponse, - # "/injective.exchange.v1beta1.MsgCancelBinaryOptionsOrder": injective_exchange_tx_pb.MsgCancelBinaryOptionsOrderResponse, - # "/injective.exchange.v1beta1.MsgAdminUpdateBinaryOptionsMarket": injective_exchange_tx_pb.MsgAdminUpdateBinaryOptionsMarketResponse, - # "/injective.exchange.v1beta1.MsgInstantBinaryOptionsMarketLaunch": injective_exchange_tx_pb.MsgInstantBinaryOptionsMarketLaunchResponse, + # "/nibiru.exchange.v1beta1.MsgCreateSpotLimitOrder": injective_exchange_tx_pb.MsgCreateSpotLimitOrderResponse, + # "/nibiru.exchange.v1beta1.MsgCreateSpotMarketOrder": injective_exchange_tx_pb.MsgCreateSpotMarketOrderResponse, + # "/nibiru.exchange.v1beta1.MsgCreateDerivativeLimitOrder": injective_exchange_tx_pb.MsgCreateDerivativeLimitOrderResponse, + # "/nibiru.exchange.v1beta1.MsgCreateDerivativeMarketOrder": injective_exchange_tx_pb.MsgCreateDerivativeMarketOrderResponse, + # "/nibiru.exchange.v1beta1.MsgCancelSpotOrder": injective_exchange_tx_pb.MsgCancelSpotOrderResponse, + # "/nibiru.exchange.v1beta1.MsgCancelDerivativeOrder": injective_exchange_tx_pb.MsgCancelDerivativeOrderResponse, + # "/nibiru.exchange.v1beta1.MsgBatchCancelSpotOrders": injective_exchange_tx_pb.MsgBatchCancelSpotOrdersResponse, + # "/nibiru.exchange.v1beta1.MsgBatchCancelDerivativeOrders": injective_exchange_tx_pb.MsgBatchCancelDerivativeOrdersResponse, + # "/nibiru.exchange.v1beta1.MsgBatchCreateSpotLimitOrders": injective_exchange_tx_pb.MsgBatchCreateSpotLimitOrdersResponse, + # "/nibiru.exchange.v1beta1.MsgBatchCreateDerivativeLimitOrders": injective_exchange_tx_pb.MsgBatchCreateDerivativeLimitOrdersResponse, + # "/nibiru.exchange.v1beta1.MsgBatchUpdateOrders": injective_exchange_tx_pb.MsgBatchUpdateOrdersResponse, + # "/nibiru.exchange.v1beta1.MsgDeposit": injective_exchange_tx_pb.MsgDepositResponse, + # "/nibiru.exchange.v1beta1.MsgWithdraw": injective_exchange_tx_pb.MsgWithdrawResponse, + # "/nibiru.exchange.v1beta1.MsgSubaccountTransfer": injective_exchange_tx_pb.MsgSubaccountTransferResponse, + # "/nibiru.exchange.v1beta1.MsgLiquidatePosition": injective_exchange_tx_pb.MsgLiquidatePositionResponse, + # "/nibiru.exchange.v1beta1.MsgIncreasePositionMargin": injective_exchange_tx_pb.MsgIncreasePositionMarginResponse, + # "/nibiru.auction.v1beta1.MsgBid": injective_auction_tx_pb.MsgBidResponse, + # "/nibiru.exchange.v1beta1.MsgCreateBinaryOptionsLimitOrder": injective_exchange_tx_pb.MsgCreateBinaryOptionsLimitOrderResponse, + # "/nibiru.exchange.v1beta1.MsgCreateBinaryOptionsMarketOrder": injective_exchange_tx_pb.MsgCreateBinaryOptionsMarketOrderResponse, + # "/nibiru.exchange.v1beta1.MsgCancelBinaryOptionsOrder": injective_exchange_tx_pb.MsgCancelBinaryOptionsOrderResponse, + # "/nibiru.exchange.v1beta1.MsgAdminUpdateBinaryOptionsMarket": injective_exchange_tx_pb.MsgAdminUpdateBinaryOptionsMarketResponse, + # "/nibiru.exchange.v1beta1.MsgInstantBinaryOptionsMarketLaunch": injective_exchange_tx_pb.MsgInstantBinaryOptionsMarketLaunchResponse, # "/cosmos.bank.v1beta1.MsgSend": cosmos_bank_tx_pb.MsgSendResponse, # "/cosmos.authz.v1beta1.MsgGrant": cosmos_authz_tx_pb.MsgGrantResponse, # "/cosmos.authz.v1beta1.MsgExec": cosmos_authz_tx_pb.MsgExecResponse, # "/cosmos.authz.v1beta1.MsgRevoke": cosmos_authz_tx_pb.MsgRevokeResponse, - # "/injective.oracle.v1beta1.MsgRelayPriceFeedPrice": injective_oracle_tx_pb.MsgRelayPriceFeedPriceResponse, - # "/injective.oracle.v1beta1.MsgRelayProviderPrices": injective_oracle_tx_pb.MsgRelayProviderPrices + # "/nibiru.oracle.v1beta1.MsgRelayPriceFeedPrice": injective_oracle_tx_pb.MsgRelayPriceFeedPriceResponse, + # "/nibiru.oracle.v1beta1.MsgRelayProviderPrices": injective_oracle_tx_pb.MsgRelayProviderPrices # } # response = tx_response_pb.TxResponseData.FromString(data) @@ -112,27 +107,27 @@ def msg_withdraw_delegator_reward( delegator_address: str, validator_address: st # @staticmethod # def UnpackMsgExecResponse(msg_type, data): # header_map = { - # "MsgCreateSpotLimitOrder": injective_exchange_tx_pb.MsgCreateSpotLimitOrderResponse, - # "MsgCreateSpotMarketOrder": injective_exchange_tx_pb.MsgCreateSpotMarketOrderResponse, - # "MsgCreateDerivativeLimitOrder": injective_exchange_tx_pb.MsgCreateDerivativeLimitOrderResponse, - # "MsgCreateDerivativeMarketOrder": injective_exchange_tx_pb.MsgCreateDerivativeMarketOrderResponse, - # "MsgCancelSpotOrder": injective_exchange_tx_pb.MsgCancelSpotOrderResponse, - # "MsgCancelDerivativeOrder": injective_exchange_tx_pb.MsgCancelDerivativeOrderResponse, - # "MsgBatchCancelSpotOrders": injective_exchange_tx_pb.MsgBatchCancelSpotOrdersResponse, - # "MsgBatchCancelDerivativeOrders": injective_exchange_tx_pb.MsgBatchCancelDerivativeOrdersResponse, - # "MsgBatchCreateSpotLimitOrders": injective_exchange_tx_pb.MsgBatchCreateSpotLimitOrdersResponse, - # "MsgBatchCreateDerivativeLimitOrders": injective_exchange_tx_pb.MsgBatchCreateDerivativeLimitOrdersResponse, - # "MsgBatchUpdateOrders": injective_exchange_tx_pb.MsgBatchUpdateOrdersResponse, - # "MsgDeposit": injective_exchange_tx_pb.MsgDepositResponse, - # "MsgWithdraw": injective_exchange_tx_pb.MsgWithdrawResponse, - # "MsgSubaccountTransfer": injective_exchange_tx_pb.MsgSubaccountTransferResponse, - # "MsgLiquidatePosition": injective_exchange_tx_pb.MsgLiquidatePositionResponse, - # "MsgIncreasePositionMargin": injective_exchange_tx_pb.MsgIncreasePositionMarginResponse, - # "MsgCreateBinaryOptionsLimitOrder": injective_exchange_tx_pb.MsgCreateBinaryOptionsLimitOrderResponse, - # "MsgCreateBinaryOptionsMarketOrder": injective_exchange_tx_pb.MsgCreateBinaryOptionsMarketOrderResponse, - # "MsgCancelBinaryOptionsOrder": injective_exchange_tx_pb.MsgCancelBinaryOptionsOrderResponse, - # "MsgAdminUpdateBinaryOptionsMarket": injective_exchange_tx_pb.MsgAdminUpdateBinaryOptionsMarketResponse, - # "MsgInstantBinaryOptionsMarketLaunch": injective_exchange_tx_pb.MsgInstantBinaryOptionsMarketLaunchResponse + # "MsgCreateSpotLimitOrder": nibiru_exchange_tx_pb.MsgCreateSpotLimitOrderResponse, + # "MsgCreateSpotMarketOrder": nibiru_exchange_tx_pb.MsgCreateSpotMarketOrderResponse, + # "MsgCreateDerivativeLimitOrder": nibiru_exchange_tx_pb.MsgCreateDerivativeLimitOrderResponse, + # "MsgCreateDerivativeMarketOrder": nibiru_exchange_tx_pb.MsgCreateDerivativeMarketOrderResponse, + # "MsgCancelSpotOrder": nibiru_exchange_tx_pb.MsgCancelSpotOrderResponse, + # "MsgCancelDerivativeOrder": nibiru_exchange_tx_pb.MsgCancelDerivativeOrderResponse, + # "MsgBatchCancelSpotOrders": nibiru_exchange_tx_pb.MsgBatchCancelSpotOrdersResponse, + # "MsgBatchCancelDerivativeOrders": nibiru_exchange_tx_pb.MsgBatchCancelDerivativeOrdersResponse, + # "MsgBatchCreateSpotLimitOrders": nibiru_exchange_tx_pb.MsgBatchCreateSpotLimitOrdersResponse, + # "MsgBatchCreateDerivativeLimitOrders": nibiru_exchange_tx_pb.MsgBatchCreateDerivativeLimitOrdersResponse, + # "MsgBatchUpdateOrders": nibiru_exchange_tx_pb.MsgBatchUpdateOrdersResponse, + # "MsgDeposit": nibiru_exchange_tx_pb.MsgDepositResponse, + # "MsgWithdraw": nibiru_exchange_tx_pb.MsgWithdrawResponse, + # "MsgSubaccountTransfer": nibiru_exchange_tx_pb.MsgSubaccountTransferResponse, + # "MsgLiquidatePosition": nibiru_exchange_tx_pb.MsgLiquidatePositionResponse, + # "MsgIncreasePositionMargin": nibiru_exchange_tx_pb.MsgIncreasePositionMarginResponse, + # "MsgCreateBinaryOptionsLimitOrder": nibiru_exchange_tx_pb.MsgCreateBinaryOptionsLimitOrderResponse, + # "MsgCreateBinaryOptionsMarketOrder": nibiru_exchange_tx_pb.MsgCreateBinaryOptionsMarketOrderResponse, + # "MsgCancelBinaryOptionsOrder": nibiru_exchange_tx_pb.MsgCancelBinaryOptionsOrderResponse, + # "MsgAdminUpdateBinaryOptionsMarket": nibiru_exchange_tx_pb.MsgAdminUpdateBinaryOptionsMarketResponse, + # "MsgInstantBinaryOptionsMarketLaunch": nibiru_exchange_tx_pb.MsgInstantBinaryOptionsMarketLaunchResponse # } # return header_map[msg_type].FromString(bytes(data, "utf-8")) diff --git a/nibiru/composers/__init__.py b/nibiru/composers/__init__.py index 13788019..9580fa8d 100644 --- a/nibiru/composers/__init__.py +++ b/nibiru/composers/__init__.py @@ -1,2 +1,2 @@ -from .dex_composer import DexComposer -from .perp_composer import PerpComposer +from .dex import Dex +from .perp import Perp diff --git a/nibiru/composers/dex_composer.py b/nibiru/composers/dex.py similarity index 98% rename from nibiru/composers/dex_composer.py rename to nibiru/composers/dex.py index 2e5c8782..49bb0f38 100644 --- a/nibiru/composers/dex_composer.py +++ b/nibiru/composers/dex.py @@ -9,7 +9,7 @@ from nibiru.proto.cosmos.base.v1beta1 import coin_pb2 as coin_pb -class DexComposer: +class Dex: @staticmethod def create_pool(creator: str, swap_fee: str, exit_fee: str, assets: List[PoolAsset]): pool_assets = [pool_tx_pb.PoolAsset(token=a.token, weight=a.weight) for a in assets] diff --git a/nibiru/composers/perp_composer.py b/nibiru/composers/perp.py similarity index 98% rename from nibiru/composers/perp_composer.py rename to nibiru/composers/perp.py index cbd76e0f..cf21571d 100644 --- a/nibiru/composers/perp_composer.py +++ b/nibiru/composers/perp.py @@ -1,4 +1,3 @@ - from nibiru.proto.perp.v1 import ( tx_pb2 as tx, state_pb2 as state_pb, @@ -7,7 +6,7 @@ from nibiru.proto.cosmos.base.v1beta1 import coin_pb2 as coin_pb from nibiru.common import Side -class PerpComposer: +class Perp: @staticmethod def remove_margin(sender: str, token_pair: str, margin: coin_pb.Coin): return tx.MsgRemoveMargin( diff --git a/nibiru/proto/perp/v1/event_pb2.py b/nibiru/proto/perp/v1/event_pb2.py index 1af81f4c..ee24389e 100644 --- a/nibiru/proto/perp/v1/event_pb2.py +++ b/nibiru/proto/perp/v1/event_pb2.py @@ -18,14 +18,13 @@ from cosmos.base.v1beta1 import coin_pb2 as cosmos_dot_base_dot_v1beta1_dot_coin__pb2 -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13perp/v1/event.proto\x12\x0enibiru.perp.v1\x1a\x14gogoproto/gogo.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x13perp/v1/state.proto\x1a\x1e\x63osmos/base/v1beta1/coin.proto\"\x92\x07\n\x14PositionChangedEvent\x12\x0c\n\x04pair\x18\x01 \x01(\t\x12\x16\n\x0etrader_address\x18\x02 \x01(\t\x12@\n\x06margin\x18\x03 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x15\xf2\xde\x1f\ryaml:\"margin\"\xc8\xde\x1f\x00\x12I\n\x11position_notional\x18\x04 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12O\n\x17\x65xchanged_position_size\x18\x05 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12R\n\x0ftransaction_fee\x18\x06 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x1e\xf2\xde\x1f\x16yaml:\"transaction_fee\"\xc8\xde\x1f\x00\x12\x45\n\rposition_size\x18\x07 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x44\n\x0crealized_pnl\x18\x08 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12L\n\x14unrealized_pnl_after\x18\t \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12@\n\x08\x62\x61\x64_debt\x18\n \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12K\n\x13liquidation_penalty\x18\x0b \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x42\n\nspot_price\x18\x0c \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12G\n\x0f\x66unding_payment\x18\r \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x14\n\x0c\x62lock_height\x18\x0e \x01(\x03\x12\x15\n\rblock_time_ms\x18\x0f \x01(\x03\"\x82\x07\n\x17PositionLiquidatedEvent\x12\x0c\n\x04pair\x18\x01 \x01(\t\x12\x16\n\x0etrader_address\x18\x02 \x01(\t\x12N\n\x16\x65xchanged_quote_amount\x18\x03 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12O\n\x17\x65xchanged_position_size\x18\x04 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x1a\n\x12liquidator_address\x18\x05 \x01(\t\x12V\n\x11\x66\x65\x65_to_liquidator\x18\x06 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB \xf2\xde\x1f\x18yaml:\"fee_to_liquidator\"\xc8\xde\x1f\x00\x12^\n\x15\x66\x65\x65_to_ecosystem_fund\x18\x07 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB$\xf2\xde\x1f\x1cyaml:\"fee_to_ecosystem_fund\"\xc8\xde\x1f\x00\x12@\n\x08\x62\x61\x64_debt\x18\x08 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12@\n\x06margin\x18\t \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x15\xf2\xde\x1f\ryaml:\"margin\"\xc8\xde\x1f\x00\x12I\n\x11position_notional\x18\n \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x45\n\rposition_size\x18\x0b \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x45\n\runrealizedPnl\x18\x0c \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x42\n\nmark_price\x18\r \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x14\n\x0c\x62lock_height\x18\x0e \x01(\x03\x12\x15\n\rblock_time_ms\x18\x0f \x01(\x03\"\xb8\x01\n\x14PositionSettledEvent\x12\x0c\n\x04pair\x18\x01 \x01(\t\x12\x16\n\x0etrader_address\x18\x02 \x01(\t\x12z\n\rsettled_coins\x18\x03 \x03(\x0b\x32\x19.cosmos.base.v1beta1.CoinBH\xaa\xdf\x1f(github.com/cosmos/cosmos-sdk/types.Coins\xf2\xde\x1f\x14yaml:\"settled_coins\"\xc8\xde\x1f\x00\"\xca\x01\n\x12MarginChangedEvent\x12\x0c\n\x04pair\x18\x01 \x01(\t\x12\x16\n\x0etrader_address\x18\x02 \x01(\t\x12\x45\n\rmargin_amount\x18\x03 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Int\xc8\xde\x1f\x00\x12G\n\x0f\x66unding_payment\x18\x04 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x42,Z*github.com/NibiruChain/nibiru/x/perp/typesb\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13perp/v1/event.proto\x12\x0enibiru.perp.v1\x1a\x14gogoproto/gogo.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x13perp/v1/state.proto\x1a\x1e\x63osmos/base/v1beta1/coin.proto\"\x83\x07\n\x14PositionChangedEvent\x12\x0c\n\x04pair\x18\x01 \x01(\t\x12\x16\n\x0etrader_address\x18\x02 \x01(\t\x12@\n\x06margin\x18\x03 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x15\xf2\xde\x1f\ryaml:\"margin\"\xc8\xde\x1f\x00\x12I\n\x11position_notional\x18\x04 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12O\n\x17\x65xchanged_position_size\x18\x05 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12R\n\x0ftransaction_fee\x18\x06 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x1e\xf2\xde\x1f\x16yaml:\"transaction_fee\"\xc8\xde\x1f\x00\x12\x45\n\rposition_size\x18\x07 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x44\n\x0crealized_pnl\x18\x08 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12L\n\x14unrealized_pnl_after\x18\t \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x31\n\x08\x62\x61\x64_debt\x18\n \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x04\xc8\xde\x1f\x00\x12K\n\x13liquidation_penalty\x18\x0b \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x42\n\nspot_price\x18\x0c \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12G\n\x0f\x66unding_payment\x18\r \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x14\n\x0c\x62lock_height\x18\x0e \x01(\x03\x12\x15\n\rblock_time_ms\x18\x0f \x01(\x03\"\xf3\x06\n\x17PositionLiquidatedEvent\x12\x0c\n\x04pair\x18\x01 \x01(\t\x12\x16\n\x0etrader_address\x18\x02 \x01(\t\x12N\n\x16\x65xchanged_quote_amount\x18\x03 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12O\n\x17\x65xchanged_position_size\x18\x04 \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x1a\n\x12liquidator_address\x18\x05 \x01(\t\x12V\n\x11\x66\x65\x65_to_liquidator\x18\x06 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB \xf2\xde\x1f\x18yaml:\"fee_to_liquidator\"\xc8\xde\x1f\x00\x12^\n\x15\x66\x65\x65_to_ecosystem_fund\x18\x07 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB$\xf2\xde\x1f\x1cyaml:\"fee_to_ecosystem_fund\"\xc8\xde\x1f\x00\x12\x31\n\x08\x62\x61\x64_debt\x18\x08 \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x04\xc8\xde\x1f\x00\x12@\n\x06margin\x18\t \x01(\x0b\x32\x19.cosmos.base.v1beta1.CoinB\x15\xf2\xde\x1f\ryaml:\"margin\"\xc8\xde\x1f\x00\x12I\n\x11position_notional\x18\n \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x45\n\rposition_size\x18\x0b \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x45\n\runrealizedPnl\x18\x0c \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x42\n\nmark_price\x18\r \x01(\tB.\xda\xde\x1f&github.com/cosmos/cosmos-sdk/types.Dec\xc8\xde\x1f\x00\x12\x14\n\x0c\x62lock_height\x18\x0e \x01(\x03\x12\x15\n\rblock_time_ms\x18\x0f \x01(\x03\"\xb8\x01\n\x14PositionSettledEvent\x12\x0c\n\x04pair\x18\x01 \x01(\t\x12\x16\n\x0etrader_address\x18\x02 \x01(\t\x12z\n\rsettled_coins\x18\x03 \x03(\x0b\x32\x19.cosmos.base.v1beta1.CoinBH\xaa\xdf\x1f(github.com/cosmos/cosmos-sdk/types.Coins\xf2\xde\x1f\x14yaml:\"settled_coins\"\xc8\xde\x1f\x00\x42,Z*github.com/NibiruChain/nibiru/x/perp/typesb\x06proto3') _POSITIONCHANGEDEVENT = DESCRIPTOR.message_types_by_name['PositionChangedEvent'] _POSITIONLIQUIDATEDEVENT = DESCRIPTOR.message_types_by_name['PositionLiquidatedEvent'] _POSITIONSETTLEDEVENT = DESCRIPTOR.message_types_by_name['PositionSettledEvent'] -_MARGINCHANGEDEVENT = DESCRIPTOR.message_types_by_name['MarginChangedEvent'] PositionChangedEvent = _reflection.GeneratedProtocolMessageType('PositionChangedEvent', (_message.Message,), { 'DESCRIPTOR' : _POSITIONCHANGEDEVENT, '__module__' : 'perp.v1.event_pb2' @@ -47,13 +46,6 @@ }) _sym_db.RegisterMessage(PositionSettledEvent) -MarginChangedEvent = _reflection.GeneratedProtocolMessageType('MarginChangedEvent', (_message.Message,), { - 'DESCRIPTOR' : _MARGINCHANGEDEVENT, - '__module__' : 'perp.v1.event_pb2' - # @@protoc_insertion_point(class_scope:nibiru.perp.v1.MarginChangedEvent) - }) -_sym_db.RegisterMessage(MarginChangedEvent) - if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None @@ -73,7 +65,7 @@ _POSITIONCHANGEDEVENT.fields_by_name['unrealized_pnl_after']._options = None _POSITIONCHANGEDEVENT.fields_by_name['unrealized_pnl_after']._serialized_options = b'\332\336\037&github.com/cosmos/cosmos-sdk/types.Dec\310\336\037\000' _POSITIONCHANGEDEVENT.fields_by_name['bad_debt']._options = None - _POSITIONCHANGEDEVENT.fields_by_name['bad_debt']._serialized_options = b'\332\336\037&github.com/cosmos/cosmos-sdk/types.Dec\310\336\037\000' + _POSITIONCHANGEDEVENT.fields_by_name['bad_debt']._serialized_options = b'\310\336\037\000' _POSITIONCHANGEDEVENT.fields_by_name['liquidation_penalty']._options = None _POSITIONCHANGEDEVENT.fields_by_name['liquidation_penalty']._serialized_options = b'\332\336\037&github.com/cosmos/cosmos-sdk/types.Dec\310\336\037\000' _POSITIONCHANGEDEVENT.fields_by_name['spot_price']._options = None @@ -89,7 +81,7 @@ _POSITIONLIQUIDATEDEVENT.fields_by_name['fee_to_ecosystem_fund']._options = None _POSITIONLIQUIDATEDEVENT.fields_by_name['fee_to_ecosystem_fund']._serialized_options = b'\362\336\037\034yaml:\"fee_to_ecosystem_fund\"\310\336\037\000' _POSITIONLIQUIDATEDEVENT.fields_by_name['bad_debt']._options = None - _POSITIONLIQUIDATEDEVENT.fields_by_name['bad_debt']._serialized_options = b'\332\336\037&github.com/cosmos/cosmos-sdk/types.Dec\310\336\037\000' + _POSITIONLIQUIDATEDEVENT.fields_by_name['bad_debt']._serialized_options = b'\310\336\037\000' _POSITIONLIQUIDATEDEVENT.fields_by_name['margin']._options = None _POSITIONLIQUIDATEDEVENT.fields_by_name['margin']._serialized_options = b'\362\336\037\ryaml:\"margin\"\310\336\037\000' _POSITIONLIQUIDATEDEVENT.fields_by_name['position_notional']._options = None @@ -102,16 +94,10 @@ _POSITIONLIQUIDATEDEVENT.fields_by_name['mark_price']._serialized_options = b'\332\336\037&github.com/cosmos/cosmos-sdk/types.Dec\310\336\037\000' _POSITIONSETTLEDEVENT.fields_by_name['settled_coins']._options = None _POSITIONSETTLEDEVENT.fields_by_name['settled_coins']._serialized_options = b'\252\337\037(github.com/cosmos/cosmos-sdk/types.Coins\362\336\037\024yaml:\"settled_coins\"\310\336\037\000' - _MARGINCHANGEDEVENT.fields_by_name['margin_amount']._options = None - _MARGINCHANGEDEVENT.fields_by_name['margin_amount']._serialized_options = b'\332\336\037&github.com/cosmos/cosmos-sdk/types.Int\310\336\037\000' - _MARGINCHANGEDEVENT.fields_by_name['funding_payment']._options = None - _MARGINCHANGEDEVENT.fields_by_name['funding_payment']._serialized_options = b'\332\336\037&github.com/cosmos/cosmos-sdk/types.Dec\310\336\037\000' _POSITIONCHANGEDEVENT._serialized_start=145 - _POSITIONCHANGEDEVENT._serialized_end=1059 - _POSITIONLIQUIDATEDEVENT._serialized_start=1062 - _POSITIONLIQUIDATEDEVENT._serialized_end=1960 - _POSITIONSETTLEDEVENT._serialized_start=1963 - _POSITIONSETTLEDEVENT._serialized_end=2147 - _MARGINCHANGEDEVENT._serialized_start=2150 - _MARGINCHANGEDEVENT._serialized_end=2352 + _POSITIONCHANGEDEVENT._serialized_end=1044 + _POSITIONLIQUIDATEDEVENT._serialized_start=1047 + _POSITIONLIQUIDATEDEVENT._serialized_end=1930 + _POSITIONSETTLEDEVENT._serialized_start=1933 + _POSITIONSETTLEDEVENT._serialized_end=2117 # @@protoc_insertion_point(module_scope) diff --git a/nibiru/proto/perp/v1/event_pb2.pyi b/nibiru/proto/perp/v1/event_pb2.pyi index bffa1b4d..42b3bf60 100644 --- a/nibiru/proto/perp/v1/event_pb2.pyi +++ b/nibiru/proto/perp/v1/event_pb2.pyi @@ -61,9 +61,10 @@ class PositionChangedEvent(google.protobuf.message.Message): unrealized_pnl_after: typing.Text """unrealized profits and losses after the change""" - bad_debt: typing.Text - """Amount of bad debt cleared by the PerpEF during the change. Bad debt is negative net margin past the liquidation point of a position.""" - + @property + def bad_debt(self) -> cosmos.base.v1beta1.coin_pb2.Coin: + """Amount of bad debt cleared by the PerpEF during the change. Bad debt is negative net margin past the liquidation point of a position.""" + pass liquidation_penalty: typing.Text """amt of margin (y) lost due to liquidation""" @@ -95,14 +96,14 @@ class PositionChangedEvent(google.protobuf.message.Message): position_size: typing.Text = ..., realized_pnl: typing.Text = ..., unrealized_pnl_after: typing.Text = ..., - bad_debt: typing.Text = ..., + bad_debt: typing.Optional[cosmos.base.v1beta1.coin_pb2.Coin] = ..., liquidation_penalty: typing.Text = ..., spot_price: typing.Text = ..., funding_payment: typing.Text = ..., block_height: builtins.int = ..., block_time_ms: builtins.int = ..., ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["margin",b"margin","transaction_fee",b"transaction_fee"]) -> builtins.bool: ... + def HasField(self, field_name: typing_extensions.Literal["bad_debt",b"bad_debt","margin",b"margin","transaction_fee",b"transaction_fee"]) -> builtins.bool: ... def ClearField(self, field_name: typing_extensions.Literal["bad_debt",b"bad_debt","block_height",b"block_height","block_time_ms",b"block_time_ms","exchanged_position_size",b"exchanged_position_size","funding_payment",b"funding_payment","liquidation_penalty",b"liquidation_penalty","margin",b"margin","pair",b"pair","position_notional",b"position_notional","position_size",b"position_size","realized_pnl",b"realized_pnl","spot_price",b"spot_price","trader_address",b"trader_address","transaction_fee",b"transaction_fee","unrealized_pnl_after",b"unrealized_pnl_after"]) -> None: ... global___PositionChangedEvent = PositionChangedEvent @@ -147,9 +148,10 @@ class PositionLiquidatedEvent(google.protobuf.message.Message): def fee_to_ecosystem_fund(self) -> cosmos.base.v1beta1.coin_pb2.Coin: """Commission (in margin units) given to the ecosystem fund.""" pass - bad_debt: typing.Text - """ Bad debt (margin units) cleared by the PerpEF during the tx. Bad debt is negative net margin past the liquidation point of a position.""" - + @property + def bad_debt(self) -> cosmos.base.v1beta1.coin_pb2.Coin: + """ Bad debt (margin units) cleared by the PerpEF during the tx. Bad debt is negative net margin past the liquidation point of a position.""" + pass @property def margin(self) -> cosmos.base.v1beta1.coin_pb2.Coin: """Remaining margin in the position after liquidation""" @@ -181,7 +183,7 @@ class PositionLiquidatedEvent(google.protobuf.message.Message): liquidator_address: typing.Text = ..., fee_to_liquidator: typing.Optional[cosmos.base.v1beta1.coin_pb2.Coin] = ..., fee_to_ecosystem_fund: typing.Optional[cosmos.base.v1beta1.coin_pb2.Coin] = ..., - bad_debt: typing.Text = ..., + bad_debt: typing.Optional[cosmos.base.v1beta1.coin_pb2.Coin] = ..., margin: typing.Optional[cosmos.base.v1beta1.coin_pb2.Coin] = ..., position_notional: typing.Text = ..., position_size: typing.Text = ..., @@ -190,7 +192,7 @@ class PositionLiquidatedEvent(google.protobuf.message.Message): block_height: builtins.int = ..., block_time_ms: builtins.int = ..., ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["fee_to_ecosystem_fund",b"fee_to_ecosystem_fund","fee_to_liquidator",b"fee_to_liquidator","margin",b"margin"]) -> builtins.bool: ... + def HasField(self, field_name: typing_extensions.Literal["bad_debt",b"bad_debt","fee_to_ecosystem_fund",b"fee_to_ecosystem_fund","fee_to_liquidator",b"fee_to_liquidator","margin",b"margin"]) -> builtins.bool: ... def ClearField(self, field_name: typing_extensions.Literal["bad_debt",b"bad_debt","block_height",b"block_height","block_time_ms",b"block_time_ms","exchanged_position_size",b"exchanged_position_size","exchanged_quote_amount",b"exchanged_quote_amount","fee_to_ecosystem_fund",b"fee_to_ecosystem_fund","fee_to_liquidator",b"fee_to_liquidator","liquidator_address",b"liquidator_address","margin",b"margin","mark_price",b"mark_price","pair",b"pair","position_notional",b"position_notional","position_size",b"position_size","trader_address",b"trader_address","unrealizedPnl",b"unrealizedPnl"]) -> None: ... global___PositionLiquidatedEvent = PositionLiquidatedEvent @@ -218,32 +220,3 @@ class PositionSettledEvent(google.protobuf.message.Message): ) -> None: ... def ClearField(self, field_name: typing_extensions.Literal["pair",b"pair","settled_coins",b"settled_coins","trader_address",b"trader_address"]) -> None: ... global___PositionSettledEvent = PositionSettledEvent - -class MarginChangedEvent(google.protobuf.message.Message): - """Emitted when a position's margin is changed (AddMargin or RemoveMargin).""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor - PAIR_FIELD_NUMBER: builtins.int - TRADER_ADDRESS_FIELD_NUMBER: builtins.int - MARGIN_AMOUNT_FIELD_NUMBER: builtins.int - FUNDING_PAYMENT_FIELD_NUMBER: builtins.int - pair: typing.Text - """Identifier for the virtual pool of the position.""" - - trader_address: typing.Text - """Owner of the position.""" - - margin_amount: typing.Text - """Amount of margin exchanged.""" - - funding_payment: typing.Text - """Amount of funding payment applied.""" - - def __init__(self, - *, - pair: typing.Text = ..., - trader_address: typing.Text = ..., - margin_amount: typing.Text = ..., - funding_payment: typing.Text = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["funding_payment",b"funding_payment","margin_amount",b"margin_amount","pair",b"pair","trader_address",b"trader_address"]) -> None: ... -global___MarginChangedEvent = MarginChangedEvent diff --git a/nibiru/sdk.py b/nibiru/sdk.py index 5e709b8e..1da1d120 100644 --- a/nibiru/sdk.py +++ b/nibiru/sdk.py @@ -1,5 +1,6 @@ import logging -from nibiru.sdks.tx.tx_client import TxClient +from .common import TxConfig +from .sdks.tx import TxClient from .wallet import PrivateKey from .client import Client from .network import Network @@ -13,6 +14,7 @@ def __init__(self, _error_do_not_use_init_directly=None) -> None: self.query = None self.tx = None self._network = None + self.config = TxConfig() @classmethod def authorize(cls, key: str = "") -> "Sdk": @@ -37,7 +39,12 @@ def with_network(self, network: Network) -> "Sdk": def with_query_client(self, client: Client) -> "Sdk": self.query = client - self.tx = TxClient(client = client, network = self._network, priv_key = self._priv_key) + tx_client = TxClient(client = self.query, network = self._network, priv_key = self._priv_key, config = self.config) + self.with_tx_client(tx_client) + return self + + def with_tx_client(self, client: TxClient) -> "Sdk": + self.tx = client return self def with_priv_key(self, priv_key: PrivateKey) -> "Sdk": @@ -45,6 +52,12 @@ def with_priv_key(self, priv_key: PrivateKey) -> "Sdk": self._network = self.with_network(Network.local()) return self + def with_config(self, config: TxConfig) -> "Sdk": + self.config = config + tx_client = TxClient(client = self.query, network = self._network, priv_key = self._priv_key, config = self.config) + self.with_tx_client(tx_client) + return self + @property def address(self): pub_key = self._priv_key.to_public_key() diff --git a/nibiru/sdks/tx/__init__.py b/nibiru/sdks/tx/__init__.py index eed9015d..9eb46f51 100644 --- a/nibiru/sdks/tx/__init__.py +++ b/nibiru/sdks/tx/__init__.py @@ -1,2 +1 @@ -from .dex import DexComposer -from .perp import PerpComposer +from .tx_client import TxClient \ No newline at end of file diff --git a/nibiru/sdks/tx/common.py b/nibiru/sdks/tx/common.py index 84fdfafc..aae7d590 100644 --- a/nibiru/sdks/tx/common.py +++ b/nibiru/sdks/tx/common.py @@ -1,25 +1,25 @@ - +from copy import deepcopy +import logging from google.protobuf import message - from nibiru.client import Client +from nibiru.common import TxConfig from nibiru.composer import Composer +from nibiru.transaction import Transaction from nibiru.constant import GAS_PRICE from nibiru.exceptions import SimulationError - from nibiru.network import Network -from nibiru.transaction import Transaction from nibiru.wallet import PrivateKey - class Tx: - def __init__(self, priv_key: PrivateKey, network: Network, client: Client): + def __init__(self, priv_key: PrivateKey, network: Network, client: Client, config: TxConfig): self.priv_key = priv_key self.network = network self.client = client self.address = None + self.config = config - async def execute(self, msg: message.Message): + async def execute(self, msg: message.Message, **kwargs): await self.client.sync_timeout_height() address = await self.get_address_info() tx = ( @@ -33,22 +33,30 @@ async def execute(self, msg: message.Message): try: sim_res = await self.simulate(tx) except SimulationError as err: - print("Aborting execution due to error: {}".format(err)) + logging.error("Aborting execution due to error: %s", err) else: - gas_wanted = sim_res.gas_info.gas_used * 1.25 - return await self.execute_tx(tx, gas_wanted) + gas_estimate = sim_res.gas_info.gas_used + return await self.execute_tx(tx, gas_estimate, **kwargs) + + async def execute_tx(self, tx: Transaction, gas_estimate: float, **kwargs): + conf = self.get_config(**kwargs) + gas_wanted = gas_estimate * 1.25 + if conf.gas_wanted > 0: + gas_wanted = conf.gas_wanted + elif conf.gas_multiplier > 0: + gas_wanted = gas_estimate * conf.gas_multiplier + gas_price = GAS_PRICE if conf.gas_price <= 0 else conf.gas_price - async def execute_tx(self, tx: Transaction, gas_wanted: float): - fee = [Composer.coin( - amount=int(GAS_PRICE * gas_wanted), - denom=self.network.fee_denom, - )] - tx = tx.with_gas(gas_wanted).with_fee(fee).with_memo('').with_timeout_height(self.client.timeout_height) - tx_raw_bytes = tx.get_signed_tx_data() + fee = [Composer.coin( + amount=int(gas_price * gas_wanted), + denom=self.network.fee_denom, + )] + logging.info("Executing transaction with fee: %s and gas_wanted: %d", fee, gas_wanted) + tx = tx.with_gas(gas_wanted).with_fee(fee).with_memo('').with_timeout_height(self.client.timeout_height) + tx_raw_bytes = tx.get_signed_tx_data() - # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode - return await self.client.send_tx_block_mode(tx_raw_bytes) + return await self.client.send_tx_block_mode(tx_raw_bytes) async def simulate(self, tx: Transaction): @@ -65,4 +73,18 @@ async def get_address_info(self): pub_key = self.priv_key.to_public_key() self.address = await pub_key.to_address().async_init_num_seq(self.network.lcd_endpoint) - return self.address \ No newline at end of file + return self.address + + def get_config(self, **kwargs): + ''' + Properties in kwargs overwrite config + ''' + c = deepcopy(self.config) + props = dir(c) + for (k, v) in kwargs.items(): + if k in props: + setattr(c, k, v) + else: + logging.warning("%s is not a supported config property, ignoring", k) + + return c \ No newline at end of file diff --git a/nibiru/sdks/tx/dex.py b/nibiru/sdks/tx/dex.py index 38d11dab..91a45d95 100644 --- a/nibiru/sdks/tx/dex.py +++ b/nibiru/sdks/tx/dex.py @@ -1,25 +1,25 @@ -from nibiru.composers.dex_composer import DexComposer +from typing import List + from nibiru.common import PoolAsset +from nibiru.composers.dex import Dex as DexComposer from nibiru.proto.cosmos.base.v1beta1 import coin_pb2 as coin_pb -from typing import List - from .common import Tx class Dex(Tx): - def create_pool(self, creator: str, swap_fee: str, exit_fee: str, assets: List[PoolAsset]): + async def create_pool(self, creator: str, swap_fee: str, exit_fee: str, assets: List[PoolAsset], **kwargs): msg = DexComposer.create_pool(creator=creator, swap_fee=swap_fee, exit_fee=exit_fee, assets=assets) - return super().execute(msg) + return await super().execute(msg, **kwargs) - def join_pool(self, sender: str, pool_id: int, tokens: List[coin_pb.Coin]): + async def join_pool(self, sender: str, pool_id: int, tokens: List[coin_pb.Coin], **kwargs): msg = DexComposer.join_pool(sender=sender, pool_id=pool_id, tokens=tokens) - return super().execute(msg) + return await super().execute(msg, **kwargs) - def exit_pool(self, sender: str, pool_id: int, pool_shares: coin_pb.Coin): + async def exit_pool(self, sender: str, pool_id: int, pool_shares: coin_pb.Coin, **kwargs): msg = DexComposer.exit_pool(sender=sender, pool_id=pool_id, pool_shares=pool_shares) - return super().execute(msg) + return await super().execute(msg, **kwargs) - def swap_assets(self, sender: str, pool_id: int, token_in: coin_pb.Coin, token_out_denom): + async def swap_assets(self, sender: str, pool_id: int, token_in: coin_pb.Coin, token_out_denom, **kwargs): msg = DexComposer.swap_assets(sender=sender, pool_id=pool_id, token_in=token_in, token_out_denom=token_out_denom) - return super().execute(msg) + return await super().execute(msg, **kwargs) diff --git a/nibiru/sdks/tx/perp.py b/nibiru/sdks/tx/perp.py index 7a707a67..8c7d8b1d 100644 --- a/nibiru/sdks/tx/perp.py +++ b/nibiru/sdks/tx/perp.py @@ -1,25 +1,24 @@ from nibiru.common import Side -from nibiru.composers.perp_composer import PerpComposer +from nibiru.composers import Perp as PerpComposer from nibiru.proto.cosmos.base.v1beta1 import coin_pb2 as coin_pb from .common import Tx class Perp(Tx): - def remove_margin(self, sender: str, token_pair: str, margin: coin_pb.Coin): + async def remove_margin(self, sender: str, token_pair: str, margin: coin_pb.Coin, **kwargs): msg = PerpComposer.remove_margin(sender = sender, token_pair = token_pair, margin = margin) - return super().execute(msg) + return await super().execute(msg, **kwargs) - - def add_margin(self, sender: str, token_pair: str, margin: coin_pb.Coin): + async def add_margin(self, sender: str, token_pair: str, margin: coin_pb.Coin, **kwargs): msg = PerpComposer.add_margin(sender = sender, token_pair = token_pair, margin = margin) - return super().execute(msg) + return await super().execute(msg, **kwargs) - def liquidate(self, sender: str, token_pair: str, trader: str): + async def liquidate(self, sender: str, token_pair: str, trader: str, **kwargs): msg = PerpComposer.liquidate(sender = sender, token_pair = token_pair, trader = trader) - return super().execute(msg) + return await super().execute(msg, **kwargs) - def open_position(self, sender: str, token_pair: str, side: Side, quote_asset_amount: str, leverage: str, base_asset_amount_limit: str): + async def open_position(self, sender: str, token_pair: str, side: Side, quote_asset_amount: str, leverage: str, base_asset_amount_limit: str, **kwargs): msg = PerpComposer.open_position( sender = sender, token_pair = token_pair, @@ -28,11 +27,11 @@ def open_position(self, sender: str, token_pair: str, side: Side, quote_asset_am leverage = leverage, base_asset_amount_limit = base_asset_amount_limit, ) - return super().execute(msg) + return await super().execute(msg, **kwargs) - def close_position(self, sender: str, token_pair: str): + async def close_position(self, sender: str, token_pair: str, **kwargs): msg = PerpComposer.close_position( sender = sender, token_pair = token_pair, ) - return super().execute(msg) + return await super().execute(msg, **kwargs) diff --git a/nibiru/sdks/tx/tx_client.py b/nibiru/sdks/tx/tx_client.py index 05187c08..0661f462 100644 --- a/nibiru/sdks/tx/tx_client.py +++ b/nibiru/sdks/tx/tx_client.py @@ -1,34 +1,35 @@ from typing import List from nibiru.client import Client +from nibiru.common import TxConfig +from nibiru.wallet import PrivateKey from nibiru.composer import Composer from nibiru.network import Network -from nibiru.wallet import PrivateKey from .common import Tx from .dex import Dex from .perp import Perp class TxClient(Tx): - def __init__(self, client: Client, network: Network, priv_key: PrivateKey): - super().__init__(client=client, network=network, priv_key = priv_key) - self.dex = Dex(client=client, network=network, priv_key = priv_key) - self.perp = Perp(client=client, network=network, priv_key = priv_key) + def __init__(self, client: Client, network: Network, priv_key: PrivateKey, config: TxConfig): + super().__init__(client=client, network=network, priv_key = priv_key, config = config) + self.dex = Dex(client=client, network=network, priv_key = priv_key, config = config) + self.perp = Perp(client=client, network=network, priv_key = priv_key, config = config) - async def msg_send(self, from_address: str, to_address: str, amount: int, denom: str): + async def msg_send(self, from_address: str, to_address: str, amount: int, denom: str, **kwargs): msg = Composer.msg_send(from_address, to_address, amount, denom) - return await super().execute(msg) + return await super().execute(msg, **kwargs) - async def msg_exec(self, grantee: str, msgs: List): + async def msg_exec(self, grantee: str, msgs: List, **kwargs): msg = Composer.msg_exec(grantee, msgs) - return await super().execute(msg) + return await super().execute(msg, **kwargs) - async def msg_revoke(self, granter: str, grantee: str, msg_type: str): + async def msg_revoke(self, granter: str, grantee: str, msg_type: str, **kwargs): msg = Composer.msg_revoke(granter, grantee, msg_type) - return await super().execute(msg) + return await super().execute(msg, **kwargs) - async def msg_delegate(self, delegator_address: str, validator_address: str, amount: float): + async def msg_delegate(self, delegator_address: str, validator_address: str, amount: float, **kwargs): msg = Composer.msg_delegate(delegator_address, validator_address, amount) - return await super().execute(msg) + return await super().execute(msg, **kwargs) - async def msg_withdraw_delegator_reward(self, delegator_address: str, validator_address: str): + async def msg_withdraw_delegator_reward(self, delegator_address: str, validator_address: str, **kwargs): msg = Composer.msg_withdraw_delegator_reward(delegator_address, validator_address) - return await super().execute(msg) \ No newline at end of file + return await super().execute(msg, **kwargs) \ No newline at end of file