diff --git a/source/includes/_account.md b/source/includes/_account.md index 3c677e27..9ec2f07e 100644 --- a/source/includes/_account.md +++ b/source/includes/_account.md @@ -11,37 +11,32 @@ Includes all messages related to accounts and transfers. ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet - network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) + network = Network.testnet(node="sentry") # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare tx msg - msg = composer.MsgDeposit( - sender=address.to_acc_bech32(), - subaccount_id=subaccount_id, - amount=0.000001, - denom='INJ' - ) + msg = composer.MsgDeposit(sender=address.to_acc_bech32(), subaccount_id=subaccount_id, amount=0.000001, denom="INJ") # build sim tx tx = ( @@ -62,14 +57,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -80,9 +77,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -216,38 +214,32 @@ gas fee: 0.0000660495 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare tx msg - msg = composer.MsgWithdraw( - sender=address.to_acc_bech32(), - subaccount_id=subaccount_id, - amount=1, - denom="USDT" - ) + msg = composer.MsgWithdraw(sender=address.to_acc_bech32(), subaccount_id=subaccount_id, amount=1, denom="USDT") # build sim tx tx = ( @@ -268,14 +260,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -286,9 +280,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -422,29 +417,28 @@ gas fee: 0.000064803 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) dest_subaccount_id = address.get_subaccount_id(index=1) @@ -454,7 +448,7 @@ async def main() -> None: source_subaccount_id=subaccount_id, destination_subaccount_id=dest_subaccount_id, amount=100, - denom="inj" + denom="INJ", ) # build sim tx @@ -476,14 +470,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -494,9 +490,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -632,29 +629,28 @@ gas fee: 0.0000610515 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) dest_subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000" @@ -664,7 +660,7 @@ async def main() -> None: source_subaccount_id=subaccount_id, destination_subaccount_id=dest_subaccount_id, amount=100, - denom="INJ" + denom="INJ", ) # build sim tx @@ -686,14 +682,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -704,9 +702,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -841,30 +840,30 @@ gas fee: 0.0000611985 INJ ``` python import asyncio -import logging + import requests -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) - subaccount_id = address.get_subaccount_id(index=0) + await client.get_account(address.to_acc_bech32()) # prepare msg asset = "injective-protocol" @@ -879,7 +878,7 @@ async def main() -> None: denom="INJ", eth_dest="0xaf79152ac5df276d9a8e1e2e22822f9713474902", amount=23, - bridge_fee=bridge_fee + bridge_fee=bridge_fee, ) # build sim tx @@ -901,14 +900,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -919,9 +920,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go diff --git a/source/includes/_auction.md b/source/includes/_auction.md index a62f0ef6..36b34011 100644 --- a/source/includes/_auction.md +++ b/source/includes/_auction.md @@ -12,35 +12,31 @@ Includes the message for placing bids in auctions. ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare tx msg - msg = composer.MsgBid( - sender=address.to_acc_bech32(), - round=23, - bid_amount=1 - ) + msg = composer.MsgBid(sender=address.to_acc_bech32(), round=16250, bid_amount=1) # build sim tx tx = ( @@ -61,14 +57,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -79,9 +77,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go diff --git a/source/includes/_authz.md b/source/includes/_authz.md index 7b4c31b3..01a1c6da 100644 --- a/source/includes/_authz.md +++ b/source/includes/_authz.md @@ -13,43 +13,42 @@ There are two types of authorization, Generic and Typed. Generic authorization w ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) - subaccount_id = address.get_subaccount_id(index=0) - market_ids = ["0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa"] + await client.get_account(address.to_acc_bech32()) + # subaccount_id = address.get_subaccount_id(index=0) + # market_ids = ["0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa"] # prepare tx msg - #GENERIC AUTHZ + # GENERIC AUTHZ msg = composer.MsgGrantGeneric( - granter = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", - grantee = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", - msg_type = "/injective.exchange.v1beta1.MsgCreateSpotLimitOrder", - expire_in=31536000 # 1 year + granter="inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", + grantee="inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", + msg_type="/injective.exchange.v1beta1.MsgCreateSpotLimitOrder", + expire_in=31536000, # 1 year ) - #TYPED AUTHZ + # TYPED AUTHZ # msg = composer.MsgGrantTyped( # granter = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", # grantee = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", @@ -78,14 +77,16 @@ async def main() -> None: 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) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -98,8 +99,8 @@ async def main() -> None: if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -262,29 +263,29 @@ gas fee: 0.0000589365 INJ ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network -from pyinjective.wallet import PrivateKey, Address +from pyinjective.transaction import Transaction +from pyinjective.wallet import Address, PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare tx msg market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" @@ -300,13 +301,11 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ) - msg = composer.MsgExec( - grantee=grantee, - msgs=[msg0] - ) + msg = composer.MsgExec(grantee=grantee, msgs=[msg0]) # build sim tx tx = ( @@ -326,24 +325,23 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) - data=sim_res_msg[0] - unpacked_msg_res = ProtoMsgComposer.UnpackMsgExecResponse( - msg_type=msg0.__class__.__name__, - data=data - ) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) + data = sim_res_msg[0] + unpacked_msg_res = composer.UnpackMsgExecResponse(msg_type=msg0.__class__.__name__, data=data) print("simulation msg response") print(unpacked_msg_res) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -354,9 +352,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -532,36 +531,34 @@ gas fee: 0.000066986 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) - subaccount_id = address.get_subaccount_id(index=0) + await client.get_account(address.to_acc_bech32()) # prepare tx msg msg = composer.MsgRevoke( - granter = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", - grantee = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", - msg_type = "/injective.exchange.v1beta1.MsgCreateSpotLimitOrder" + granter="inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku", + grantee="inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", + msg_type="/injective.exchange.v1beta1.MsgCreateSpotLimitOrder", ) # build sim tx @@ -583,14 +580,16 @@ async def main() -> None: 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) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -601,9 +600,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go diff --git a/source/includes/_bank.md b/source/includes/_bank.md index 932e79b7..6d955362 100644 --- a/source/includes/_bank.md +++ b/source/includes/_bank.md @@ -12,36 +12,35 @@ Bank module. ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare tx msg msg = composer.MsgSend( from_address=address.to_acc_bech32(), - to_address='inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r', + to_address="inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", amount=0.000000000000000001, - denom='INJ' + denom="INJ", ) # build sim tx @@ -63,14 +62,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -81,9 +82,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go diff --git a/source/includes/_binaryoptions.md b/source/includes/_binaryoptions.md index 210de40c..8bb6a3d4 100644 --- a/source/includes/_binaryoptions.md +++ b/source/includes/_binaryoptions.md @@ -11,28 +11,30 @@ Includes all messages related to binary options. ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE +from pyinjective.utils.denom import Denom +from pyinjective.core.network import Network from pyinjective.transaction import Transaction -from pyinjective.core.network import Network, Denom from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info @@ -40,8 +42,7 @@ async def main() -> None: fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" # set custom denom to bypass ini file load (optional) - denom = Denom(description="desc", base=0, quote=6, - min_price_tick_size=1000, min_quantity_tick_size=0.0001) + denom = Denom(description="desc", base=0, quote=6, min_price_tick_size=1000, min_quantity_tick_size=0.0001) # prepare tx msg msg = composer.MsgCreateBinaryOptionsLimitOrder( @@ -53,7 +54,8 @@ async def main() -> None: quantity=1, is_buy=False, is_reduce_only=False, - denom=denom + denom=denom, + cid=str(uuid.uuid4()), ) # build sim tx @@ -74,19 +76,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -98,9 +102,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -149,29 +154,29 @@ gas fee: 0.0000606245 INJ ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info @@ -187,7 +192,8 @@ async def main() -> None: price=0.5, quantity=1, is_buy=True, - is_reduce_only=False + is_reduce_only=False, + cid=str(uuid.uuid4()), ) # build sim tx tx = ( @@ -207,19 +213,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -231,9 +239,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -281,29 +290,28 @@ gas fee: 0.0000539515 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info @@ -312,10 +320,7 @@ async def main() -> None: # prepare tx msg msg = composer.MsgCancelBinaryOptionsOrder( - sender=address.to_acc_bech32(), - market_id=market_id, - subaccount_id=subaccount_id, - order_hash=order_hash + sender=address.to_acc_bech32(), market_id=market_id, subaccount_id=subaccount_id, order_hash=order_hash ) # build sim tx tx = ( @@ -335,19 +340,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -359,9 +366,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -402,28 +410,28 @@ gas fee: 0.0000556515 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare trade info market_id = "0xfafec40a7b93331c1fc89c23f66d11fbb48f38dfdd78f7f4fc4031fad90f6896" @@ -439,7 +447,7 @@ async def main() -> None: settlement_price=settlement_price, expiration_timestamp=expiration_timestamp, settlement_timestamp=settlement_timestamp, - status=status + status=status, ) # build sim tx @@ -460,19 +468,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -484,9 +494,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -529,29 +540,28 @@ gas fee: 0.0000556515 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare tx msg msg = composer.MsgInstantBinaryOptionsMarketLaunch( @@ -564,12 +574,12 @@ async def main() -> None: quote_denom="peggy0xdAC17F958D2ee523a2206206994597C13D831ec7", quote_decimals=6, oracle_scale_factor=6, - maker_fee_rate=0.0005, # 0.05% - taker_fee_rate=0.0010, # 0.10% + maker_fee_rate=0.0005, # 0.05% + taker_fee_rate=0.0010, # 0.10% expiration_timestamp=1680730982, settlement_timestamp=1690730982, min_price_tick_size=0.01, - min_quantity_tick_size=0.01 + min_quantity_tick_size=0.01, ) # build sim tx @@ -590,19 +600,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -614,9 +626,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -666,29 +679,28 @@ gas fee: 0.0000863755 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) provider = "ufc" symbols = ["KHABIB-TKO-05/30/2023", "KHABIB-TKO-05/26/2023"] @@ -696,10 +708,7 @@ async def main() -> None: # prepare tx msg msg = composer.MsgRelayProviderPrices( - sender=address.to_acc_bech32(), - provider=provider, - symbols=symbols, - prices=prices + sender=address.to_acc_bech32(), provider=provider, symbols=symbols, prices=prices ) # build sim tx @@ -720,19 +729,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -744,9 +755,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -792,39 +804,39 @@ Further note that if no marketIDs are provided in the SpotMarketIdsToCancelAll o ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" - derivative_market_id_create = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" + derivative_market_id_create = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" spot_market_id_create = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" derivative_market_id_cancel = "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff" - derivative_market_id_cancel_2 = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" + derivative_market_id_cancel_2 = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" spot_market_id_cancel = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" spot_market_id_cancel_2 = "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0" @@ -832,26 +844,26 @@ async def main() -> None: composer.OrderData( market_id=derivative_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103" + order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103", ), composer.OrderData( market_id=derivative_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] spot_orders_to_cancel = [ composer.OrderData( market_id=spot_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + cid="0e5c3ad5-2cc4-4a2a-bbe5-b12697739163", ), composer.OrderData( market_id=spot_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" - ) + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", + ), ] derivative_orders_to_create = [ @@ -863,7 +875,8 @@ async def main() -> None: quantity=0.1, leverage=1, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.DerivativeOrder( market_id=derivative_market_id_create, @@ -873,7 +886,8 @@ async def main() -> None: quantity=0.01, leverage=1, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -885,7 +899,8 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id_create, @@ -894,7 +909,8 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -904,7 +920,7 @@ async def main() -> None: derivative_orders_to_create=derivative_orders_to_create, spot_orders_to_create=spot_orders_to_create, derivative_orders_to_cancel=derivative_orders_to_cancel, - spot_orders_to_cancel=spot_orders_to_cancel + spot_orders_to_cancel=spot_orders_to_cancel, ) # build sim tx @@ -925,19 +941,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -949,145 +967,151 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + + ``` ``` go package main import ( - "fmt" - "os" - "time" - - "github.com/InjectiveLabs/sdk-go/client/common" - "github.com/shopspring/decimal" - - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - cosmtypes "github.com/cosmos/cosmos-sdk/types" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" + "fmt" + "github.com/google/uuid" + "os" + "time" + + "github.com/InjectiveLabs/sdk-go/client/common" + "github.com/shopspring/decimal" + + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + cosmtypes "github.com/cosmos/cosmos-sdk/types" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - smarketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" - samount := decimal.NewFromFloat(2) - sprice := decimal.NewFromFloat(22.5) - smarketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"} - - spot_order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: samount, - Price: sprice, - FeeRecipient: senderAddress.String(), - MarketId: smarketId, - }) - - dmarketId := "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" - damount := decimal.NewFromFloat(0.01) - dprice := cosmtypes.MustNewDecFromStr("31000000000") //31,000 - dleverage := cosmtypes.MustNewDecFromStr("2") - dmarketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"} - - derivative_order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: damount, - Price: dprice, - Leverage: dleverage, - FeeRecipient: senderAddress.String(), - MarketId: dmarketId, - IsReduceOnly: false, - }) - - msg := new(exchangetypes.MsgBatchUpdateOrders) - msg.Sender = senderAddress.String() - msg.SubaccountId = defaultSubaccountID.Hex() - msg.SpotOrdersToCreate = []*exchangetypes.SpotOrder{spot_order} - msg.DerivativeOrdersToCreate = []*exchangetypes.DerivativeOrder{derivative_order} - msg.SpotMarketIdsToCancelAll = smarketIds - msg.DerivativeMarketIdsToCancelAll = dmarketIds - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - } - - simResMsgs := common.MsgResponse(simRes.Result.Data) - MsgBatchUpdateOrdersResponse := exchangetypes.MsgBatchUpdateOrdersResponse{} - MsgBatchUpdateOrdersResponse.Unmarshal(simResMsgs[0].Data) - - fmt.Println("simulated spot order hashes", MsgBatchUpdateOrdersResponse.SpotOrderHashes) - - fmt.Println("simulated derivative order hashes", MsgBatchUpdateOrdersResponse.DerivativeOrderHashes) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + + if err != nil { + panic(err) + } + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + return + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + return + } + + defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) + + smarketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" + samount := decimal.NewFromFloat(2) + sprice := decimal.NewFromFloat(22.5) + smarketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"} + + spot_order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: samount, + Price: sprice, + FeeRecipient: senderAddress.String(), + MarketId: smarketId, + Cid: uuid.NewString(), + }) + + dmarketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce" + damount := decimal.NewFromFloat(0.01) + dprice := cosmtypes.MustNewDecFromStr("31000000000") //31,000 + dleverage := cosmtypes.MustNewDecFromStr("2") + dmarketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"} + + derivative_order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: damount, + Price: dprice, + Leverage: dleverage, + FeeRecipient: senderAddress.String(), + MarketId: dmarketId, + IsReduceOnly: false, + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgBatchUpdateOrders) + msg.Sender = senderAddress.String() + msg.SubaccountId = defaultSubaccountID.Hex() + msg.SpotOrdersToCreate = []*exchangetypes.SpotOrder{spot_order} + msg.DerivativeOrdersToCreate = []*exchangetypes.DerivativeOrder{derivative_order} + msg.SpotMarketIdsToCancelAll = smarketIds + msg.DerivativeMarketIdsToCancelAll = dmarketIds + + simRes, err := chainClient.SimulateMsg(clientCtx, msg) + + if err != nil { + fmt.Println(err) + return + } + + MsgBatchUpdateOrdersResponse := exchangetypes.MsgBatchUpdateOrdersResponse{} + MsgBatchUpdateOrdersResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) + + fmt.Println("simulated spot order hashes", MsgBatchUpdateOrdersResponse.SpotOrderHashes) + + fmt.Println("simulated derivative order hashes", MsgBatchUpdateOrdersResponse.DerivativeOrderHashes) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg) + + if err != nil { + fmt.Println(err) + return + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } + ``` @@ -1114,6 +1138,7 @@ func main() { |fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| |price|Float|The price of the base asset|Yes| |quantity|Float|The quantity of the base asset|Yes| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| @@ -1128,7 +1153,8 @@ func main() { |price|Float|The price of the base asset|Yes| |quantity|Float|The quantity of the base asset|Yes| |leverage|Float|The leverage factor for the order|No| -|trigger_price|Boolean|Set the trigger price for conditional orders|No| +|trigger_price|String|Set the trigger price for conditional orders|No| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| |is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| @@ -1146,6 +1172,7 @@ func main() { |fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| |price|Float|The price of the base asset|Yes| |quantity|Float|The quantity of the base asset|Yes| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |leverage|Float|The leverage factor for the order|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| @@ -1159,6 +1186,7 @@ func main() { |market_id|String|Market ID of the market we want to cancel an order|Yes| |subaccount_id|String|The subaccount we want to cancel an order from|Yes| |order_hash|String|The hash of a specific order|Yes| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_conditional|Boolean|Set to true or false for conditional and regular orders respectively. Setting this value will incur less gas for the order cancellation and faster execution|No| |order_direction|Boolean|The direction of the order (Should be one of: [buy sell]). Setting this value will incur less gas for the order cancellation and faster execution|No| |order_type|Boolean|The type of the order (Should be one of: [market limit]). Setting this value will incur less gas for the order cancellation and faster execution|No| diff --git a/source/includes/_broadcaster.md b/source/includes/_broadcaster.md index f998f7e0..868702f6 100644 --- a/source/includes/_broadcaster.md +++ b/source/includes/_broadcaster.md @@ -16,6 +16,7 @@ To use the broadcaster you just need to create an instance of *MsgBroadcasterWit ``` python import asyncio +import uuid from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.core.broadcaster import MsgBroadcasterWithPk @@ -32,7 +33,6 @@ async def main() -> None: message_broadcaster = MsgBroadcasterWithPk.new_using_simulation( network=network, private_key=private_key_in_hexa, - use_secure_connection=True ) priv_key = PrivateKey.from_hex(private_key_in_hexa) @@ -53,7 +53,8 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id_create, @@ -62,7 +63,8 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -77,6 +79,7 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) @@ -144,6 +147,7 @@ This is the most common broadcaster configuration. Unless you are using grantee ``` python import asyncio +import uuid from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.core.broadcaster import MsgBroadcasterWithPk @@ -160,7 +164,6 @@ async def main() -> None: message_broadcaster = MsgBroadcasterWithPk.new_without_simulation( network=network, private_key=private_key_in_hexa, - use_secure_connection=True ) priv_key = PrivateKey.from_hex(private_key_in_hexa) @@ -181,7 +184,8 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id_create, @@ -190,7 +194,8 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -205,6 +210,7 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) @@ -225,12 +231,13 @@ This is the required broadcaster configuration when operating with grantee accou ``` python import asyncio +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient +from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.core.broadcaster import MsgBroadcasterWithPk from pyinjective.core.network import Network -from pyinjective.wallet import PrivateKey, Address +from pyinjective.wallet import Address, PrivateKey async def main() -> None: @@ -251,7 +258,6 @@ async def main() -> None: message_broadcaster = MsgBroadcasterWithPk.new_for_grantee_account_using_simulation( network=network, grantee_private_key=private_key_in_hexa, - use_secure_connection=True ) # prepare tx msg @@ -268,7 +274,8 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ) # broadcast the transaction @@ -276,6 +283,7 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) @@ -335,12 +343,13 @@ For the broadcaster to calculate the gas fee running the simulation, create an i ``` python import asyncio +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient +from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.core.broadcaster import MsgBroadcasterWithPk from pyinjective.core.network import Network -from pyinjective.wallet import PrivateKey, Address +from pyinjective.wallet import Address, PrivateKey async def main() -> None: @@ -361,7 +370,6 @@ async def main() -> None: message_broadcaster = MsgBroadcasterWithPk.new_for_grantee_account_without_simulation( network=network, grantee_private_key=private_key_in_hexa, - use_secure_connection=True ) # prepare tx msg @@ -378,7 +386,8 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ) # broadcast the transaction @@ -386,6 +395,7 @@ async def main() -> None: print("---Transaction Response---") print(result) + if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) diff --git a/source/includes/_chainstream.md b/source/includes/_chainstream.md new file mode 100644 index 00000000..ab9b8e7b --- /dev/null +++ b/source/includes/_chainstream.md @@ -0,0 +1,461 @@ +# - Chain Stream +Chain Stream is a gRPC service that allows clients to receive low-latency updates from the Injective Chain. +This API is exposed directly from a dedicated server running on a chain node and provides the fastest way to receive events data (like trades, orders, balances, etc.). +Under the hood, a stream message is computed by the chain node immediately after the event is emitted and is sent to the client via a gRPC stream once the block is committed. + + + +## Stream Request +Its possible to specify multiple filters to customize the stream. +A filter can be specified with a list of values, generally MarketIds, SubaccountIds and Accounts address. +A filter can also be omitted, in this case the stream will return all the events for the specified type. +In addition each filter supports a `*` wildcard to match all possible values. + +``` python +import asyncio + +from google.protobuf import json_format + +from pyinjective.async_client import AsyncClient +from pyinjective.composer import Composer +from pyinjective.core.network import Network + + +async def main() -> None: + network = Network.testnet() + + client = AsyncClient(network) + composer = Composer(network=network.string()) + + subaccount_id = "0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000000" + + inj_usdt_market = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" + inj_usdt_perp_market = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" + + bank_balances_filter = composer.chain_stream_bank_balances_filter( + accounts=["inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"] + ) + subaccount_deposits_filter = composer.chain_stream_subaccount_deposits_filter(subaccount_ids=[subaccount_id]) + spot_trades_filter = composer.chain_stream_trades_filter(subaccount_ids=["*"], market_ids=[inj_usdt_market]) + derivative_trades_filter = composer.chain_stream_trades_filter( + subaccount_ids=["*"], market_ids=[inj_usdt_perp_market] + ) + spot_orders_filter = composer.chain_stream_orders_filter( + subaccount_ids=[subaccount_id], market_ids=[inj_usdt_market] + ) + derivative_orders_filter = composer.chain_stream_orders_filter( + subaccount_ids=[subaccount_id], market_ids=[inj_usdt_perp_market] + ) + spot_orderbooks_filter = composer.chain_stream_orderbooks_filter(market_ids=[inj_usdt_market]) + derivative_orderbooks_filter = composer.chain_stream_orderbooks_filter(market_ids=[inj_usdt_perp_market]) + positions_filter = composer.chain_stream_positions_filter( + subaccount_ids=[subaccount_id], market_ids=[inj_usdt_perp_market] + ) + oracle_price_filter = composer.chain_stream_oracle_price_filter(symbols=["INJ", "USDT"]) + stream = await client.chain_stream( + bank_balances_filter=bank_balances_filter, + subaccount_deposits_filter=subaccount_deposits_filter, + spot_trades_filter=spot_trades_filter, + derivative_trades_filter=derivative_trades_filter, + spot_orders_filter=spot_orders_filter, + derivative_orders_filter=derivative_orders_filter, + spot_orderbooks_filter=spot_orderbooks_filter, + derivative_orderbooks_filter=derivative_orderbooks_filter, + positions_filter=positions_filter, + oracle_price_filter=oracle_price_filter, + ) + async for event in stream: + print( + json_format.MessageToJson( + message=event, including_default_value_fields=True, preserving_proto_field_name=True + ) + ) + + +if __name__ == "__main__": + asyncio.get_event_loop().run_until_complete(main()) + +``` + +``` go +package main + +import ( + "context" + "encoding/json" + "fmt" + chainStreamModule "github.com/InjectiveLabs/sdk-go/chain/stream/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + "github.com/InjectiveLabs/sdk-go/client/common" +) + +func main() { + network := common.LoadNetwork("devnet", "lb") + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + "", + nil, + ) + if err != nil { + fmt.Println(err) + } + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + if err != nil { + panic(err) + } + + ctx := context.Background() + + subaccountId := "0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000000" + + injUsdtMarket := "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" + injUsdtPerpMarket := "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" + + req := chainStreamModule.StreamRequest{ + BankBalancesFilter: &chainStreamModule.BankBalancesFilter{ + Accounts: String Array{"*"}, + }, + SpotOrdersFilter: &chainStreamModule.OrdersFilter{ + MarketIds: String Array{injUsdtMarket}, + SubaccountIds: String Array{subaccountId}, + }, + DerivativeOrdersFilter: &chainStreamModule.OrdersFilter{ + MarketIds: String Array{injUsdtPerpMarket}, + SubaccountIds: String Array{subaccountId}, + }, + SpotTradesFilter: &chainStreamModule.TradesFilter{ + MarketIds: String Array{injUsdtMarket}, + SubaccountIds: String Array{"*"}, + }, + SubaccountDepositsFilter: &chainStreamModule.SubaccountDepositsFilter{ + SubaccountIds: String Array{subaccountId}, + }, + DerivativeOrderbooksFilter: &chainStreamModule.OrderbookFilter{ + MarketIds: String Array{injUsdtPerpMarket}, + }, + SpotOrderbooksFilter: &chainStreamModule.OrderbookFilter{ + MarketIds: String Array{injUsdtMarket}, + }, + PositionsFilter: &chainStreamModule.PositionsFilter{ + SubaccountIds: String Array{subaccountId}, + MarketIds: String Array{injUsdtPerpMarket}, + }, + DerivativeTradesFilter: &chainStreamModule.TradesFilter{ + SubaccountIds: String Array{"*"}, + MarketIds: String Array{injUsdtPerpMarket}, + }, + OraclePriceFilter: &chainStreamModule.OraclePriceFilter{ + Symbol: String Array{"INJ", "USDT"}, + }, + } + stream, err := chainClient.ChainStream(ctx, req) + if err != nil { + panic(err) + } + + for { + select { + case <-ctx.Done(): + return + default: + res, err := stream.Recv() + if err != nil { + panic(err) + return + } + str, _ := json.MarshalIndent(res, "", " ") + fmt.Print(string(str)) + } + } +} + +``` + +``` typescript + +``` +### Request parameters + +| Parameter | Type | Description | Required | +| -------------------------- | ------------------------ | ---------------------------------------- | -------- | +| BankBalancesFilter | BankBalancesFilter | Filter for bank balances events | No | +| SpotOrdersFilter | OrdersFilter | Filter for spot orders events | No | +| DerivativeOrdersFilter | OrdersFilter | Filter for derivative orders events | No | +| SpotTradesFilter | TradesFilter | Filter for spot trades events | No | +| SubaccountDepositsFilter | SubaccountDepositsFilter | Filter for subaccount deposits events | No | +| DerivativeOrderbooksFilter | OrderbookFilter | Filter for derivative order books events | No | +| SpotOrderbooksFilter | OrderbookFilter | Filter for spot order books events | No | +| PositionsFilter | PositionsFilter | Filter for positions events | No | +| DerivativeTradesFilter | TradesFilter | Filter for derivative trades events | No | +| OraclePriceFilter | OraclePriceFilter | Filter for oracle price events | No | + +### BankBalancesFilter + + Structure for filtering bank balances. + +| Parameter | Type | Description | Required | +| --------- | ------------ | -------------------------- | -------- | +| Accounts | String Array | List of account addresses. | No | + +### SubaccountDepositsFilter + + Structure for filtering subaccount deposits. + +| Parameter | Type | Description | Required | +| ------------- | ------------ | ----------------------- | -------- | +| SubaccountIds | String Array | List of subaccount IDs. | No | + +### TradesFilter + + Structure for filtering trades. + +| Parameter | Type | Description | Required | +| ------------- | ------------ | ----------------------- | -------- | +| SubaccountIds | String Array | List of subaccount IDs. | No | +| MarketIds | String Array | List of market IDs. | No | + +### OrdersFilter + + Structure for filtering orders. + +| Parameter | Type | Description | Required | +| ------------- | ------------ | ----------------------- | -------- | +| SubaccountIds | String Array | List of subaccount IDs. | No | +| MarketIds | String Array | List of market IDs. | No | + +### OrderbookFilter + + Structure for filtering orderbook. + +| Parameter | Type | Description | Required | +| --------- | ------------ | ------------------- | -------- | +| MarketIds | String Array | List of market IDs. | No | + +### PositionsFilter + + Structure for filtering positions. + +| Parameter | Type | Description | Required | +| ------------- | ------------ | ----------------------- | -------- | +| SubaccountIds | String Array | List of subaccount IDs. | No | +| MarketIds | String Array | List of market IDs. | No | + +### OraclePriceFilter + + Structure for filtering oracle prices. + +| Parameter | Type | Description | Required | +| --------- | ------------ | ---------------- | -------- | +| Symbol | String Array | List of symbols. | No | + + +## StreamResponse +The stream response is a stream of events that are sent to the client. +Each message contains a list of events that are filtered by the request parameters and it's identified by the block height. + +### Response parameters + +Response structure for the data stream. + +| Parameter | Type | Description | Required | +| -------------------------- | ------------------------ | ------------------------------------- | -------- | +| BlockHeight | Integer | The current block height. | | +| BankBalances | BankBalance Array | List of bank balances. | | +| SubaccountDeposits | SubaccountDeposits Array | List of subaccount deposits. | | +| SpotTrades | SpotTrade Array | List of spot trades. | | +| DerivativeTrades | DerivativeTrade Array | List of derivative trades. | | +| SpotOrders | SpotOrder Array | List of spot orders. | | +| DerivativeOrders | DerivativeOrder Array | List of derivative orders. | | +| SpotOrderbookUpdates | OrderbookUpdate Array | List of spot orderbook updates. | | +| DerivativeOrderbookUpdates | OrderbookUpdate Array | List of derivative orderbook updates. | | +| Positions | Position Array | List of positions. | | +| OraclePrices | OraclePrice Array | List of oracle prices. | | + +### BankBalance + +Structure for bank balances. + +| Parameter | Type | Description | Required | +| --------- | ------ | ------------------------------- | -------- | +| Account | String | The account name. | | +| Balances | Coins | The list of available balances. | | + +### SubaccountDeposits + +Structure for subaccount deposits. + +| Parameter | Type | Description | Required | +| ------------ | ------------- | ------------------ | -------- | +| SubaccountId | String | The subaccount ID. | | +| Deposits | Deposit Array | List of deposits. | | + +### SpotTrade + +Structure for spot trades. + +| Parameter | Type | Description | Required | +| ------------------- | ------ | ---------------------------------------------- | -------- | +| MarketId | String | The market ID. | | +| IsBuy | bool | True if it is a buy, False if it is a sell. | | +| ExecutionType | String | The execution type. | | +| Quantity | Dec | The quantity of the trade. | | +| Price | Dec | The price of the trade. | | +| SubaccountId | String | The subaccount ID that executed the trade. | | +| Fee | Dec | The fee of the trade. | | +| OrderHash | String | The hash of the order. | | +| FeeRecipientAddress | String | The fee recipient address. | | +| Cid | String | Identifier for the order specified by the user | | + +### DerivativeTrade + +Structure for derivative trades. + +| Parameter | Type | Description | Required | +| ------------------- | ------------- | ---------------------------------------------- | -------- | +| MarketId | String | The market ID. | | +| IsBuy | bool | True if it is a buy, False if it is a sell. | | +| ExecutionType | String | The execution type. | | +| SubaccountId | String | The subaccount ID that executed the trade. | | +| PositionDelta | PositionDelta | The position delta. | | +| Payout | Dec | The payout of the trade. | | +| Fee | Dec | The fee of the trade. | | +| OrderHash | String | The hash of the order. | | +| FeeRecipientAddress | String | The fee recipient address. | | +| Cid | String | Identifier for the order specified by the user | | + +### SpotOrder + +Structure for spot orders. + +| Parameter | Type | Description | Required | +| --------- | -------------- | --------------- | -------- | +| MarketId | String | The market ID. | | +| Order | SpotLimitOrder | The spot order. | | + +### DerivativeOrder + +Structure for derivative orders. + +| Parameter | Type | Description | Required | +| --------- | -------------------- | ----------------------------------------------------------- | -------- | +| MarketId | String | The market ID. | | +| Order | DerivativeLimitOrder | The derivative order. | | +| IsMarket | bool | True if it is a market order, False if it is a limit order. | | + +### OrderbookUpdate + +Structure for orderbook updates. + +| Parameter | Type | Description | Required | +| --------- | --------- | ---------------------- | -------- | +| Seq | Integer | The sequence number. | | +| Orderbook | Orderbook | The updated orderbook. | | + +### Position + +Structure for positions. + +| Parameter | Type | Description | Required | +| ---------------------- | ------ | ---------------------------------------------------- | -------- | +| MarketId | String | The market ID. | | +| SubaccountId | String | The subaccount ID. | | +| IsLong | bool | True if it is a long position, False if it is short. | | +| Quantity | Dec | The quantity of the position. | | +| EntryPrice | Dec | The entry price of the position. | | +| Margin | Dec | The margin of the position. | | +| CumulativeFundingEntry | Dec | The cumulative funding entry of the position. | | + +### OraclePrice + +Structure for oracle prices. + +| Parameter | Type | Description | Required | +| --------- | ------ | ------------------------ | -------- | +| Symbol | String | The symbol of the price. | Yes | +| Price | Dec | The oracle price. | Yes | +| Type | String | The price type. | | + +### SubaccountDeposit + +Structure for subaccount deposits. + +| Parameter | Type | Description | Required | +| --------- | ------- | -------------------------------- | -------- | +| Denom | String | The denomination of the deposit. | | +| Deposit | Deposit | The deposit details. | | + +### Deposit + +Structure for deposit details. + +| Parameter | Type | Description | Required | +| ---------------- | ---- | ------------------------------------- | -------- | +| AvailableBalance | Dec | The available balance in the deposit. | | +| TotalBalance | Dec | The total balance in the deposit. | | + +### SpotLimitOrder + +Structure for spot limit orders. + +| Parameter | Type | Description | Required | +| ------------ | ----------------- | --------------------------------------- | -------- | +| OrderInfo | OrderInfo | Information about the order. | | +| OrderType | OrderType | The order type. | | +| Fillable | Dec | The remaining fillable quantity. | | +| TriggerPrice | Dec (optional) | The trigger price for stop/take orders. | | +| OrderHash | []byte (optional) | The hash of the order. | | + +### DerivativeLimitOrder + +Structure for derivative limit orders. + +| Parameter | Type | Description | Required | +| ------------ | ----------------- | --------------------------------------- | -------- | +| OrderInfo | OrderInfo | Information about the order. | | +| OrderType | OrderType | The order type. | | +| Margin | Dec | The margin used by the order. | | +| Fillable | Dec | The remaining fillable quantity. | | +| TriggerPrice | Dec (optional) | The trigger price for stop/take orders. | | +| OrderHash | []byte (optional) | The hash of the order. | | + +### OrderInfo + +Structure for order information. + +| Parameter | Type | Description | Required | +| ------------ | ------ | ---------------------------------------------- | -------- | +| SubaccountId | String | The subaccount ID of the order creator. | | +| FeeRecipient | String | The fee recipient address for the order. | | +| Price | Dec | The price of the order. | | +| Quantity | Dec | The quantity of the order. | | +| Cid | String | Identifier for the order specified by the user | | + +### OrderType + +Any of the possible [order types](#overview-order-types) + +### Orderbook + +Structure for the orderbook. + +| Parameter | Type | Description | Required | +| ---------- | ----------- | -------------------- | -------- | +| MarketId | String | The market ID. | | +| BuyLevels | Level Array | List of buy levels. | | +| SellLevels | Level Array | List of sell levels. | | + +### Level + +Structure for the orderbook levels. + +| Parameter | Type | Description | Required | +| --------- | ---- | -------------------------- | -------- | +| P | Dec | The price of the level. | | +| Q | Dec | The quantity of the level. | | \ No newline at end of file diff --git a/source/includes/_changelog.md b/source/includes/_changelog.md index f591410c..e40def0d 100644 --- a/source/includes/_changelog.md +++ b/source/includes/_changelog.md @@ -1,5 +1,12 @@ # Change Log +## 2023-11-13 +- Python SDK v1.0 and Go SDK v1.49 + - Added logic to support use of Client Order ID (CID) new identifier in OrderInfo + - New chain stream support + - Remove support for `sentry` nodes in mainnet network. The only supported node option in mainnet is `lb` + - Migrated all proto objects dependency to support chain version 1.12 + ## 2023-09-06 - Python SDK v0.8 release - Network class was moved from `pyinjective.constant` to `pyinjective.core.network` diff --git a/source/includes/_derivatives.md b/source/includes/_derivatives.md index 48f3b8ec..ff32d59a 100644 --- a/source/includes/_derivatives.md +++ b/source/includes/_derivatives.md @@ -11,33 +11,33 @@ Includes all messages related to derivative markets. ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info - market_id = "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" + market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" # prepare tx msg @@ -49,7 +49,8 @@ async def main() -> None: price=50000, quantity=0.01, leverage=3, - is_buy=True + is_buy=True, + cid=str(uuid.uuid4()), ) # build sim tx @@ -70,19 +71,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -94,129 +97,134 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go package main import ( - "fmt" - "os" - "time" - - "github.com/InjectiveLabs/sdk-go/client/common" - "github.com/shopspring/decimal" - - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - cosmtypes "github.com/cosmos/cosmos-sdk/types" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" + "fmt" + "github.com/google/uuid" + "os" + "time" + + "github.com/InjectiveLabs/sdk-go/client/common" + "github.com/shopspring/decimal" + + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + cosmtypes "github.com/cosmos/cosmos-sdk/types" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - marketId := "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" - amount := decimal.NewFromFloat(0.01) - price := cosmtypes.MustNewDecFromStr("33000000000") //33,000 - leverage := cosmtypes.MustNewDecFromStr("2.5") - - order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ - OrderType: exchangetypes.OrderType_SELL, //BUY SELL - Quantity: amount, - Price: price, - Leverage: leverage, - FeeRecipient: senderAddress.String(), - MarketId: marketId, - IsReduceOnly: false, - }) - - msg := new(exchangetypes.MsgCreateDerivativeMarketOrder) - msg.Sender = senderAddress.String() - msg.Order = exchangetypes.DerivativeOrder(*order) - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - } - - simResMsgs := common.MsgResponse(simRes.Result.Data) - msgCreateDerivativeMarketOrderResponse := exchangetypes.MsgCreateDerivativeMarketOrderResponse{} - msgCreateDerivativeMarketOrderResponse.Unmarshal(simResMsgs[0].Data) - - if err != nil { - fmt.Println(err) - } - - fmt.Println("simulated order hash", msgCreateDerivativeMarketOrderResponse.OrderHash) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + + if err != nil { + panic(err) + } + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + return + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + return + } + + defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) + + marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce" + amount := decimal.NewFromFloat(0.01) + price := cosmtypes.MustNewDecFromStr("33000000000") //33,000 + leverage := cosmtypes.MustNewDecFromStr("2.5") + + order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ + OrderType: exchangetypes.OrderType_SELL, //BUY SELL + Quantity: amount, + Price: price, + Leverage: leverage, + FeeRecipient: senderAddress.String(), + MarketId: marketId, + IsReduceOnly: true, + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgCreateDerivativeMarketOrder) + msg.Sender = senderAddress.String() + msg.Order = exchangetypes.DerivativeOrder(*order) + + simRes, err := chainClient.SimulateMsg(clientCtx, msg) + + if err != nil { + fmt.Println(err) + return + } + + msgCreateDerivativeMarketOrderResponse := exchangetypes.MsgCreateDerivativeMarketOrderResponse{} + err = msgCreateDerivativeMarketOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("simulated order hash", msgCreateDerivativeMarketOrderResponse.OrderHash) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg) + + if err != nil { + fmt.Println(err) + return + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } + ``` ``` typescript @@ -231,6 +239,7 @@ https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgcrae | fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | | price | Float | The worst accepted price of the base asset | Yes | | quantity | Float | The quantity of the base asset | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | | leverage | Float | The leverage factor for the order | Yes | | is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | | is_reduce_only | Boolean | Set to true or false for reduce-only or normal orders respectively | No | @@ -269,33 +278,33 @@ gas fee: 0.000069981 INJ ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info - market_id = "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" + market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" # prepare tx msg @@ -308,7 +317,8 @@ async def main() -> None: quantity=0.1, leverage=1, is_buy=False, - is_reduce_only=False + is_reduce_only=False, + cid=str(uuid.uuid4()), ) # build sim tx @@ -329,19 +339,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -353,129 +365,129 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go package main import ( - "fmt" - "os" - "time" - - "github.com/InjectiveLabs/sdk-go/client/common" - "github.com/shopspring/decimal" - - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - cosmtypes "github.com/cosmos/cosmos-sdk/types" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" + "fmt" + "github.com/google/uuid" + "os" + "time" + + "github.com/InjectiveLabs/sdk-go/client/common" + "github.com/shopspring/decimal" + + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + cosmtypes "github.com/cosmos/cosmos-sdk/types" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - marketId := "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" - amount := decimal.NewFromFloat(0.001) - price := cosmtypes.MustNewDecFromStr("31000000000") //31,000 - leverage := cosmtypes.MustNewDecFromStr("2.5") - - order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: amount, - Price: price, - Leverage: leverage, - FeeRecipient: senderAddress.String(), - MarketId: marketId, - IsReduceOnly: false, - }) - - msg := new(exchangetypes.MsgCreateDerivativeLimitOrder) - msg.Sender = senderAddress.String() - msg.Order = exchangetypes.DerivativeOrder(*order) - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - } - - simResMsgs := common.MsgResponse(simRes.Result.Data) - msgCreateDerivativeLimitOrderResponse := exchangetypes.MsgCreateDerivativeLimitOrderResponse{} - msgCreateDerivativeLimitOrderResponse.Unmarshal(simResMsgs[0].Data) - - if err != nil { - fmt.Println(err) - } - - fmt.Println("simulated order hash", msgCreateDerivativeLimitOrderResponse.OrderHash) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + + if err != nil { + panic(err) + } + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + } + + defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) + + marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce" + amount := decimal.NewFromFloat(0.001) + price := cosmtypes.MustNewDecFromStr("31000000000") //31,000 + leverage := cosmtypes.MustNewDecFromStr("2.5") + + order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: amount, + Price: price, + Leverage: leverage, + FeeRecipient: senderAddress.String(), + MarketId: marketId, + IsReduceOnly: true, + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgCreateDerivativeLimitOrder) + msg.Sender = senderAddress.String() + msg.Order = exchangetypes.DerivativeOrder(*order) + + simRes, err := chainClient.SimulateMsg(clientCtx, msg) + + if err != nil { + fmt.Println(err) + } + + msgCreateDerivativeLimitOrderResponse := exchangetypes.MsgCreateDerivativeLimitOrderResponse{} + err = msgCreateDerivativeLimitOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) + + if err != nil { + fmt.Println(err) + } + + fmt.Println("simulated order hash", msgCreateDerivativeLimitOrderResponse.OrderHash) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg) + + if err != nil { + fmt.Println(err) + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } + ``` ``` typescript @@ -490,6 +502,7 @@ https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgcrae | fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | | price | Float | The price of the base asset | Yes | | quantity | Float | The quantity of the base asset | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | | leverage | Float | The leverage factor for the order | Yes | | trigger_price | String | Set the trigger price for conditional orders | No | | is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | @@ -533,41 +546,37 @@ gas fee: 0.0000857195 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info - market_id = "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" + market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" order_hash = "0x667ee6f37f6d06bf473f4e1434e92ac98ff43c785405e2a511a0843daeca2de9" # prepare tx msg msg = composer.MsgCancelDerivativeOrder( - sender=address.to_acc_bech32(), - market_id=market_id, - subaccount_id=subaccount_id, - order_hash=order_hash + sender=address.to_acc_bech32(), market_id=market_id, subaccount_id=subaccount_id, order_hash=order_hash ) # build sim tx @@ -589,14 +598,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -607,9 +618,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -754,39 +766,39 @@ Further note that if no marketIDs are provided in the SpotMarketIdsToCancelAll o ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" - derivative_market_id_create = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" + derivative_market_id_create = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" spot_market_id_create = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" derivative_market_id_cancel = "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff" - derivative_market_id_cancel_2 = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" + derivative_market_id_cancel_2 = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" spot_market_id_cancel = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" spot_market_id_cancel_2 = "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0" @@ -794,26 +806,26 @@ async def main() -> None: composer.OrderData( market_id=derivative_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103" + order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103", ), composer.OrderData( market_id=derivative_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] spot_orders_to_cancel = [ composer.OrderData( market_id=spot_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + cid="0e5c3ad5-2cc4-4a2a-bbe5-b12697739163", ), composer.OrderData( market_id=spot_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" - ) + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", + ), ] derivative_orders_to_create = [ @@ -825,7 +837,8 @@ async def main() -> None: quantity=0.1, leverage=1, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.DerivativeOrder( market_id=derivative_market_id_create, @@ -835,7 +848,8 @@ async def main() -> None: quantity=0.01, leverage=1, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -847,7 +861,8 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id_create, @@ -856,7 +871,8 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -866,7 +882,7 @@ async def main() -> None: derivative_orders_to_create=derivative_orders_to_create, spot_orders_to_create=spot_orders_to_create, derivative_orders_to_cancel=derivative_orders_to_cancel, - spot_orders_to_cancel=spot_orders_to_cancel + spot_orders_to_cancel=spot_orders_to_cancel, ) # build sim tx @@ -887,19 +903,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -911,145 +929,150 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go package main import ( - "fmt" - "os" - "time" - - "github.com/InjectiveLabs/sdk-go/client/common" - "github.com/shopspring/decimal" - - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - cosmtypes "github.com/cosmos/cosmos-sdk/types" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" + "fmt" + "github.com/google/uuid" + "os" + "time" + + "github.com/InjectiveLabs/sdk-go/client/common" + "github.com/shopspring/decimal" + + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + cosmtypes "github.com/cosmos/cosmos-sdk/types" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - smarketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" - samount := decimal.NewFromFloat(2) - sprice := decimal.NewFromFloat(22.5) - smarketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"} - - spot_order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: samount, - Price: sprice, - FeeRecipient: senderAddress.String(), - MarketId: smarketId, - }) - - dmarketId := "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" - damount := decimal.NewFromFloat(0.01) - dprice := cosmtypes.MustNewDecFromStr("31000000000") //31,000 - dleverage := cosmtypes.MustNewDecFromStr("2") - dmarketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"} - - derivative_order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: damount, - Price: dprice, - Leverage: dleverage, - FeeRecipient: senderAddress.String(), - MarketId: dmarketId, - IsReduceOnly: false, - }) - - msg := new(exchangetypes.MsgBatchUpdateOrders) - msg.Sender = senderAddress.String() - msg.SubaccountId = defaultSubaccountID.Hex() - msg.SpotOrdersToCreate = []*exchangetypes.SpotOrder{spot_order} - msg.DerivativeOrdersToCreate = []*exchangetypes.DerivativeOrder{derivative_order} - msg.SpotMarketIdsToCancelAll = smarketIds - msg.DerivativeMarketIdsToCancelAll = dmarketIds - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - } - - simResMsgs := common.MsgResponse(simRes.Result.Data) - MsgBatchUpdateOrdersResponse := exchangetypes.MsgBatchUpdateOrdersResponse{} - MsgBatchUpdateOrdersResponse.Unmarshal(simResMsgs[0].Data) - - fmt.Println("simulated spot order hashes", MsgBatchUpdateOrdersResponse.SpotOrderHashes) - - fmt.Println("simulated derivative order hashes", MsgBatchUpdateOrdersResponse.DerivativeOrderHashes) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + + if err != nil { + panic(err) + } + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + return + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + return + } + + defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) + + smarketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" + samount := decimal.NewFromFloat(2) + sprice := decimal.NewFromFloat(22.5) + smarketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"} + + spot_order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: samount, + Price: sprice, + FeeRecipient: senderAddress.String(), + MarketId: smarketId, + Cid: uuid.NewString(), + }) + + dmarketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce" + damount := decimal.NewFromFloat(0.01) + dprice := cosmtypes.MustNewDecFromStr("31000000000") //31,000 + dleverage := cosmtypes.MustNewDecFromStr("2") + dmarketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"} + + derivative_order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: damount, + Price: dprice, + Leverage: dleverage, + FeeRecipient: senderAddress.String(), + MarketId: dmarketId, + IsReduceOnly: false, + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgBatchUpdateOrders) + msg.Sender = senderAddress.String() + msg.SubaccountId = defaultSubaccountID.Hex() + msg.SpotOrdersToCreate = []*exchangetypes.SpotOrder{spot_order} + msg.DerivativeOrdersToCreate = []*exchangetypes.DerivativeOrder{derivative_order} + msg.SpotMarketIdsToCancelAll = smarketIds + msg.DerivativeMarketIdsToCancelAll = dmarketIds + + simRes, err := chainClient.SimulateMsg(clientCtx, msg) + + if err != nil { + fmt.Println(err) + return + } + + MsgBatchUpdateOrdersResponse := exchangetypes.MsgBatchUpdateOrdersResponse{} + MsgBatchUpdateOrdersResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) + + fmt.Println("simulated spot order hashes", MsgBatchUpdateOrdersResponse.SpotOrderHashes) + + fmt.Println("simulated derivative order hashes", MsgBatchUpdateOrdersResponse.DerivativeOrderHashes) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg) + + if err != nil { + fmt.Println(err) + return + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } + ``` ``` typescript @@ -1079,6 +1102,7 @@ https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgbatc |fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| |price|Float|The price of the base asset|Yes| |quantity|Float|The quantity of the base asset|Yes| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| @@ -1093,7 +1117,8 @@ https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgbatc |price|Float|The price of the base asset|Yes| |quantity|Float|The quantity of the base asset|Yes| |leverage|Float|The leverage factor for the order|No| -|trigger_price|Boolean|Set the trigger price for conditional orders|No| +|trigger_price|String|Set the trigger price for conditional orders|No| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| |is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| @@ -1111,6 +1136,7 @@ https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgbatc |fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| |price|Float|The price of the base asset|Yes| |quantity|Float|The quantity of the base asset|Yes| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |leverage|Float|The leverage factor for the order|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| @@ -1124,6 +1150,7 @@ https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgbatc |market_id|String|Market ID of the market we want to cancel an order|Yes| |subaccount_id|String|The subaccount we want to cancel an order from|Yes| |order_hash|String|The hash of a specific order|Yes| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_conditional|Boolean|Set to true or false for conditional and regular orders respectively. Setting this value will incur less gas for the order cancellation and faster execution|No| |order_direction|Boolean|The direction of the order (Should be one of: [buy sell]). Setting this value will incur less gas for the order cancellation and faster execution|No| |order_type|Boolean|The type of the order (Should be one of: [market limit]). Setting this value will incur less gas for the order cancellation and faster execution|No| @@ -1171,33 +1198,32 @@ gas fee: 0.000329546 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info - market_id = "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" + market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" # prepare tx msg msg = composer.MsgIncreasePositionMargin( @@ -1205,7 +1231,7 @@ async def main() -> None: market_id=market_id, source_subaccount_id=subaccount_id, destination_subaccount_id=subaccount_id, - amount=2 + amount=2, ) # build sim tx @@ -1227,14 +1253,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -1245,9 +1273,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -1386,41 +1415,38 @@ This function computes order hashes locally for SpotOrder and DerivativeOrder. F ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network -from pyinjective.wallet import PrivateKey from pyinjective.orderhash import OrderHashManager +from pyinjective.transaction import Transaction +from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) subaccount_id_2 = address.get_subaccount_id(index=1) - order_hash_manager = OrderHashManager( - address=address, - network=network, - subaccount_indexes=[0,1,2,7] - ) + order_hash_manager = OrderHashManager(address=address, network=network, subaccount_indexes=[0, 1, 2, 7]) # prepare trade info spot_market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" - deriv_market_id = "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" + deriv_market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" spot_orders = [ @@ -1431,7 +1457,8 @@ async def main() -> None: price=0.524, quantity=0.01, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id, @@ -1440,7 +1467,8 @@ async def main() -> None: price=27.92, quantity=0.01, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -1453,7 +1481,8 @@ async def main() -> None: quantity=0.01, leverage=1.5, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.DerivativeOrder( market_id=deriv_market_id, @@ -1463,23 +1492,20 @@ async def main() -> None: quantity=0.01, leverage=2, is_buy=False, - is_reduce_only=False + is_reduce_only=False, + cid=str(uuid.uuid4()), ), ] # prepare tx msg - spot_msg = composer.MsgBatchCreateSpotLimitOrders( - sender=address.to_acc_bech32(), - orders=spot_orders - ) + spot_msg = composer.MsgBatchCreateSpotLimitOrders(sender=address.to_acc_bech32(), orders=spot_orders) - deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders( - sender=address.to_acc_bech32(), - orders=derivative_orders - ) + deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders(sender=address.to_acc_bech32(), orders=derivative_orders) # compute order hashes - order_hashes = order_hash_manager.compute_order_hashes(spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0) + order_hashes = order_hash_manager.compute_order_hashes( + spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0 + ) print("computed spot order hashes", order_hashes.spot) print("computed derivative order hashes", order_hashes.derivative) @@ -1492,15 +1518,17 @@ async def main() -> None: .with_account_num(client.get_number()) .with_chain_id(network.chain_id) ) - gas_price = 500000000 + gas_price = GAS_PRICE base_gas = 85000 - gas_limit = base_gas + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_limit = base_gas + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -1511,9 +1539,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) - # compute order hashes - order_hashes = order_hash_manager.compute_order_hashes(spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0) + order_hashes = order_hash_manager.compute_order_hashes( + spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0 + ) print("computed spot order hashes", order_hashes.spot) print("computed derivative order hashes", order_hashes.derivative) @@ -1526,15 +1555,17 @@ async def main() -> None: .with_account_num(client.get_number()) .with_chain_id(network.chain_id) ) - gas_price = 500000000 + gas_price = GAS_PRICE base_gas = 85000 - gas_limit = base_gas + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_limit = base_gas + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -1553,7 +1584,8 @@ async def main() -> None: price=1.524, quantity=0.01, is_buy=True, - is_po=True + is_po=True, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id, @@ -1562,7 +1594,8 @@ async def main() -> None: price=27.92, quantity=0.01, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -1575,7 +1608,8 @@ async def main() -> None: quantity=0.01, leverage=1.5, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.DerivativeOrder( market_id=deriv_market_id, @@ -1585,23 +1619,20 @@ async def main() -> None: quantity=0.01, leverage=2, is_buy=False, - is_reduce_only=False + is_reduce_only=False, + cid=str(uuid.uuid4()), ), ] # prepare tx msg - spot_msg = composer.MsgBatchCreateSpotLimitOrders( - sender=address.to_acc_bech32(), - orders=spot_orders - ) + spot_msg = composer.MsgBatchCreateSpotLimitOrders(sender=address.to_acc_bech32(), orders=spot_orders) - deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders( - sender=address.to_acc_bech32(), - orders=derivative_orders - ) + deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders(sender=address.to_acc_bech32(), orders=derivative_orders) # compute order hashes - order_hashes = order_hash_manager.compute_order_hashes(spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=1) + order_hashes = order_hash_manager.compute_order_hashes( + spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=1 + ) print("computed spot order hashes", order_hashes.spot) print("computed derivative order hashes", order_hashes.derivative) @@ -1614,15 +1645,17 @@ async def main() -> None: .with_account_num(client.get_number()) .with_chain_id(network.chain_id) ) - gas_price = 500000000 + gas_price = GAS_PRICE base_gas = 85000 - gas_limit = base_gas + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_limit = base_gas + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -1633,8 +1666,8 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) ``` @@ -1643,120 +1676,119 @@ if __name__ == "__main__": package main import ( - "fmt" - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - "github.com/InjectiveLabs/sdk-go/client/common" - cosmtypes "github.com/cosmos/cosmos-sdk/types" - "github.com/shopspring/decimal" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" - "os" - "time" + "fmt" + "github.com/google/uuid" + "os" + "time" + + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + "github.com/InjectiveLabs/sdk-go/client/common" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + cosmtypes "github.com/cosmos/cosmos-sdk/types" + "github.com/shopspring/decimal" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - // initialize grpc client - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - // prepare tx msg - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - spotOrder := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ - OrderType: exchangetypes.OrderType_BUY, - Quantity: decimal.NewFromFloat(2), - Price: decimal.NewFromFloat(22.55), - FeeRecipient: senderAddress.String(), - MarketId: "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa", - }) - - derivativeOrder := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ - OrderType: exchangetypes.OrderType_BUY, - Quantity: decimal.NewFromFloat(2), - Price: cosmtypes.MustNewDecFromStr("31000000000"), - Leverage: cosmtypes.MustNewDecFromStr("2.5"), - FeeRecipient: senderAddress.String(), - MarketId: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce", - }) - - msg := new(exchangetypes.MsgBatchCreateSpotLimitOrders) - msg.Sender = senderAddress.String() - msg.Orders = []exchangetypes.SpotOrder{*spotOrder} - - msg1 := new(exchangetypes.MsgBatchCreateDerivativeLimitOrders) - msg1.Sender = senderAddress.String() - msg1.Orders = []exchangetypes.DerivativeOrder{*derivativeOrder, *derivativeOrder} - - // compute local order hashes - orderHashes, err := chainClient.ComputeOrderHashes(msg.Orders, msg1.Orders) - - if err != nil { - fmt.Println(err) - } - - fmt.Println("computed spot order hashes: ", orderHashes.Spot) - fmt.Println("computed derivative order hashes: ", orderHashes.Derivative) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg, msg1) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + if err != nil { + panic(err) + } + + // initialize grpc client + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + } + + // prepare tx msg + defaultSubaccountID := chainClient.Subaccount(senderAddress, 1) + + spotOrder := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ + OrderType: exchangetypes.OrderType_BUY, + Quantity: decimal.NewFromFloat(2), + Price: decimal.NewFromFloat(22.55), + FeeRecipient: senderAddress.String(), + MarketId: "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa", + Cid: uuid.NewString(), + }) + + derivativeOrder := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ + OrderType: exchangetypes.OrderType_BUY, + Quantity: decimal.NewFromFloat(2), + Price: cosmtypes.MustNewDecFromStr("31000000000"), + Leverage: cosmtypes.MustNewDecFromStr("2.5"), + FeeRecipient: senderAddress.String(), + MarketId: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce", + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgBatchCreateSpotLimitOrders) + msg.Sender = senderAddress.String() + msg.Orders = []exchangetypes.SpotOrder{*spotOrder} + + msg1 := new(exchangetypes.MsgBatchCreateDerivativeLimitOrders) + msg1.Sender = senderAddress.String() + msg1.Orders = []exchangetypes.DerivativeOrder{*derivativeOrder, *derivativeOrder} + + // compute local order hashes + orderHashes, err := chainClient.ComputeOrderHashes(msg.Orders, msg1.Orders, defaultSubaccountID) + + if err != nil { + fmt.Println(err) + } + + fmt.Println("computed spot order hashes: ", orderHashes.Spot) + fmt.Println("computed derivative order hashes: ", orderHashes.Derivative) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg, msg1) + + if err != nil { + fmt.Println(err) + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } ``` @@ -1786,6 +1818,7 @@ https://github.com/InjectiveLabs/injective-ts/blob/master/packages/sdk-ts/src/co |quantity|Float|The quantity of the base asset|Yes| |leverage|Float|The leverage factor for the order|No| |trigger_price|String|Set the trigger price for conditional orders|No| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| |is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| @@ -1811,6 +1844,7 @@ https://github.com/InjectiveLabs/injective-ts/blob/master/packages/sdk-ts/src/co |fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| |price|Float|The price of the base asset|Yes| |quantity|Float|The quantity of the base asset|Yes| +|cid|String|Identifier for the order specified by the user (up to 36 characters, like a UUID)|No| |is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| |is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| diff --git a/source/includes/_derivativesrpc.md b/source/includes/_derivativesrpc.md index 9e02fb39..4d555b84 100644 --- a/source/includes/_derivativesrpc.md +++ b/source/includes/_derivativesrpc.md @@ -77,9 +77,9 @@ const market = await indexerGrpcDerivativesApi.fetchMarket(marketId) console.log(market) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|ID of the market to fetch|Yes| +| Parameter | Type | Description | Required | +| --------- | ------ | ------------------------- | -------- | +| market_id | String | ID of the market to fetch | Yes | @@ -210,71 +210,71 @@ market { } ``` -|Parameter|Type|Description| -|----|----|----| -|market|DerivativeMarketInfo|Info about a particular derivative market| +| Parameter | Type | Description | +| --------- | -------------------- | ----------------------------------------- | +| market | DerivativeMarketInfo | Info about a particular derivative market | **DerivativeMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|oracle_quote|String|Oracle quote currency| -|oracle_type|String|Oracle Type| -|quote_denom|String|Coin denom used for the quote asset| -|is_perpetual|Boolean|True if the market is a perpetual swap market| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|oracle_scale_factor|Integer|Scaling multiple to scale oracle prices to the correct number of decimals| -|taker_fee_rate|String|Defines the fee percentage takers pay (in quote asset) when trading| -|expiry_futures_market_info|ExpiryFuturesMarketInfo|Info about expiry futures market| -|initial_margin_ratio|String|The initial margin ratio of the derivative market| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|oracle_base|String|Oracle base currency| -|perpetual_market_funding|PerpetualMarketFunding|PerpetualMarketFunding object| -|perpetual_market_info|PerpetualMarketInfo|Information about the perpetual market| -|ticker|String|The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset| -|maintenance_margin_ratio|String|The maintenance margin ratio of the derivative market| -|market_id|String|The market ID| -|quoteTokenMeta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| +| Parameter | Type | Description | +| -------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------- | +| oracle_quote | String | Oracle quote currency | +| oracle_type | String | Oracle Type | +| quote_denom | String | Coin denom used for the quote asset | +| is_perpetual | Boolean | True if the market is a perpetual swap market | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| oracle_scale_factor | Integer | Scaling multiple to scale oracle prices to the correct number of decimals | +| taker_fee_rate | String | Defines the fee percentage takers pay (in quote asset) when trading | +| expiry_futures_market_info | ExpiryFuturesMarketInfo | Info about expiry futures market | +| initial_margin_ratio | String | The initial margin ratio of the derivative market | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| oracle_base | String | Oracle base currency | +| perpetual_market_funding | PerpetualMarketFunding | PerpetualMarketFunding object | +| perpetual_market_info | PerpetualMarketInfo | Information about the perpetual market | +| ticker | String | The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset | +| maintenance_margin_ratio | String | The maintenance margin ratio of the derivative market | +| market_id | String | The market ID | +| quoteTokenMeta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | **ExpiryFuturesMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|expiration_timestamp|Integer|Defines the expiration time for a time expiry futures market in UNIX seconds| -|settlement_price|String|Defines the settlement price for a time expiry futures market| +| Parameter | Type | Description | +| -------------------- | ------- | ---------------------------------------------------------------------------- | +| expiration_timestamp | Integer | Defines the expiration time for a time expiry futures market in UNIX seconds | +| settlement_price | String | Defines the settlement price for a time expiry futures market | **PerpetualMarketFunding** -|Parameter|Type|Description| -|----|----|----| -|cumulative_funding|String|Defines the cumulative funding of a perpetual market| -|cumulative_price|String|Defines the cumulative price for the current hour up to the last timestamp| -|last_timestamp|Integer|Defines the last funding timestamp in UNIX seconds| +| Parameter | Type | Description | +| ------------------ | ------- | -------------------------------------------------------------------------- | +| cumulative_funding | String | Defines the cumulative funding of a perpetual market | +| cumulative_price | String | Defines the cumulative price for the current hour up to the last timestamp | +| last_timestamp | Integer | Defines the last funding timestamp in UNIX seconds | **PerpetualMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|hourly_funding_rate_cap|String|Defines the default maximum absolute value of the hourly funding rate| -|hourly_interest_rate|String|Defines the hourly interest rate of the perpetual market| -|next_funding_timestamp|Integer|Defines the next funding timestamp in UNIX seconds| -|funding_interval|Integer|Defines the funding interval in seconds| +| Parameter | Type | Description | +| ----------------------- | ------- | --------------------------------------------------------------------- | +| hourly_funding_rate_cap | String | Defines the default maximum absolute value of the hourly funding rate | +| hourly_interest_rate | String | Defines the hourly interest rate of the perpetual market | +| next_funding_timestamp | Integer | Defines the next funding timestamp in UNIX seconds | +| funding_interval | Integer | Defines the funding interval in seconds | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | ## Markets @@ -363,10 +363,10 @@ const markets = await indexerGrpcDerivativesApi.fetchMarkets() console.log(markets) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_status|String|Filter by market status (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])|No| -|quote_denom|String|Filter by the Coin denomination of the quote currency|No| +| Parameter | Type | Description | Required | +| ------------- | ------ | ------------------------------------------------------------------------------------------------------ | -------- | +| market_status | String | Filter by market status (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | No | +| quote_denom | String | Filter by the Coin denomination of the quote currency | No | @@ -599,71 +599,71 @@ markets { ``` -|Parameter|Type|Description| -|----|----|----| -|markets|DerivativeMarketInfo Array|List of derivative markets and associated info| +| Parameter | Type | Description | +| --------- | -------------------------- | ---------------------------------------------- | +| markets | DerivativeMarketInfo Array | List of derivative markets and associated info | **DerivativeMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|oracle_quote|String|Oracle quote currency| -|oracle_type|String|Oracle Type| -|quote_denom|String|Coin denom used for the quote asset| -|is_perpetual|Boolean|True if the market is a perpetual swap market| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|oracle_scale_factor|Integer|Scaling multiple to scale oracle prices to the correct number of decimals| -|taker_fee_rate|String|Defines the fee percentage takers pay (in quote asset) when trading| -|expiry_futures_market_info|ExpiryFuturesMarketInfo|Info about expiry futures market| -|initial_margin_ratio|String|The initial margin ratio of the derivative market| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|oracle_base|String|Oracle base currency| -|perpetual_market_funding|PerpetualMarketFunding|PerpetualMarketFunding object| -|perpetual_market_info|PerpetualMarketInfo|Information about the perpetual market| -|ticker|String|The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset| -|maintenance_margin_ratio|String|The maintenance margin ratio of the derivative market| -|market_id|String|The market ID| -|quoteTokenMeta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| +| Parameter | Type | Description | +| -------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------- | +| oracle_quote | String | Oracle quote currency | +| oracle_type | String | Oracle Type | +| quote_denom | String | Coin denom used for the quote asset | +| is_perpetual | Boolean | True if the market is a perpetual swap market | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| oracle_scale_factor | Integer | Scaling multiple to scale oracle prices to the correct number of decimals | +| taker_fee_rate | String | Defines the fee percentage takers pay (in quote asset) when trading | +| expiry_futures_market_info | ExpiryFuturesMarketInfo | Info about expiry futures market | +| initial_margin_ratio | String | The initial margin ratio of the derivative market | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| oracle_base | String | Oracle base currency | +| perpetual_market_funding | PerpetualMarketFunding | PerpetualMarketFunding object | +| perpetual_market_info | PerpetualMarketInfo | Information about the perpetual market | +| ticker | String | The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset | +| maintenance_margin_ratio | String | The maintenance margin ratio of the derivative market | +| market_id | String | The market ID | +| quoteTokenMeta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | **ExpiryFuturesMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|expiration_timestamp|Integer|Defines the expiration time for a time expiry futures market in UNIX seconds| -|settlement_price|String|Defines the settlement price for a time expiry futures market| +| Parameter | Type | Description | +| -------------------- | ------- | ---------------------------------------------------------------------------- | +| expiration_timestamp | Integer | Defines the expiration time for a time expiry futures market in UNIX seconds | +| settlement_price | String | Defines the settlement price for a time expiry futures market | **PerpetualMarketFunding** -|Parameter|Type|Description| -|----|----|----| -|cumulative_funding|String|Defines the cumulative funding of a perpetual market| -|cumulative_price|String|Defines the cumulative price for the current hour up to the last timestamp| -|last_timestamp|Integer|Defines the last funding timestamp in UNIX seconds| +| Parameter | Type | Description | +| ------------------ | ------- | -------------------------------------------------------------------------- | +| cumulative_funding | String | Defines the cumulative funding of a perpetual market | +| cumulative_price | String | Defines the cumulative price for the current hour up to the last timestamp | +| last_timestamp | Integer | Defines the last funding timestamp in UNIX seconds | **PerpetualMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|hourly_funding_rate_cap|String|Defines the default maximum absolute value of the hourly funding rate| -|hourly_interest_rate|String|Defines the hourly interest rate of the perpetual market| -|next_funding_timestamp|Integer|Defines the next funding timestamp in UNIX seconds| -|funding_interval|Integer|Defines the funding interval in seconds| +| Parameter | Type | Description | +| ----------------------- | ------- | --------------------------------------------------------------------- | +| hourly_funding_rate_cap | String | Defines the default maximum absolute value of the hourly funding rate | +| hourly_interest_rate | String | Defines the hourly interest rate of the perpetual market | +| next_funding_timestamp | Integer | Defines the next funding timestamp in UNIX seconds | +| funding_interval | Integer | Defines the funding interval in seconds | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | ## StreamMarkets @@ -765,9 +765,9 @@ const streamFnArgs = { streamFn(streamFnArgs) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for updates streaming, empty means 'ALL' derivative markets|No| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------------------------------ | -------- | +| market_ids | String Array | List of market IDs for updates streaming, empty means 'ALL' derivative markets | No | ### Response Parameters > Streaming Response Example: @@ -902,73 +902,73 @@ timestamp: 1652792406000 } ``` -|Parameter|Type|Description| -|----|----|----| -|market|DerivativeMarketInfo|Info about a particular derivative market| -|operation_type|String|Update type (Should be one of: ["insert", "delete", "replace", "update", "invalidate"])| -|timestamp|Integer|Operation timestamp in UNIX millis| +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------------------------------------------- | +| market | DerivativeMarketInfo | Info about a particular derivative market | +| operation_type | String | Update type (Should be one of: ["insert", "delete", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | **DerivativeMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|oracle_quote|String|Oracle quote currency| -|oracle_type|String|Oracle Type| -|quote_denom|String|Coin denom used for the quote asset| -|is_perpetual|Boolean|True if the market is a perpetual swap market| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|oracle_scale_factor|Integer|Scaling multiple to scale oracle prices to the correct number of decimals| -|taker_fee_rate|String|Defines the fee percentage takers pay (in quote asset) when trading| -|expiry_futures_market_info|ExpiryFuturesMarketInfo|Info about expiry futures market| -|initial_margin_ratio|String|The initial margin ratio of the derivative market| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|oracle_base|String|Oracle base currency| -|perpetual_market_funding|PerpetualMarketFunding|PerpetualMarketFunding object| -|perpetual_market_info|PerpetualMarketInfo|Information about the perpetual market| -|ticker|String|The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset| -|maintenance_margin_ratio|String|The maintenance margin ratio of the derivative market| -|market_id|String|The market ID| -|quoteTokenMeta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| +| Parameter | Type | Description | +| -------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------- | +| oracle_quote | String | Oracle quote currency | +| oracle_type | String | Oracle Type | +| quote_denom | String | Coin denom used for the quote asset | +| is_perpetual | Boolean | True if the market is a perpetual swap market | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| oracle_scale_factor | Integer | Scaling multiple to scale oracle prices to the correct number of decimals | +| taker_fee_rate | String | Defines the fee percentage takers pay (in quote asset) when trading | +| expiry_futures_market_info | ExpiryFuturesMarketInfo | Info about expiry futures market | +| initial_margin_ratio | String | The initial margin ratio of the derivative market | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| oracle_base | String | Oracle base currency | +| perpetual_market_funding | PerpetualMarketFunding | PerpetualMarketFunding object | +| perpetual_market_info | PerpetualMarketInfo | Information about the perpetual market | +| ticker | String | The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset | +| maintenance_margin_ratio | String | The maintenance margin ratio of the derivative market | +| market_id | String | The market ID | +| quoteTokenMeta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | **ExpiryFuturesMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|expiration_timestamp|Integer|Defines the expiration time for a time expiry futures market in UNIX seconds| -|settlement_price|String|Defines the settlement price for a time expiry futures market| +| Parameter | Type | Description | +| -------------------- | ------- | ---------------------------------------------------------------------------- | +| expiration_timestamp | Integer | Defines the expiration time for a time expiry futures market in UNIX seconds | +| settlement_price | String | Defines the settlement price for a time expiry futures market | **PerpetualMarketFunding** -|Parameter|Type|Description| -|----|----|----| -|cumulative_funding|String|Defines the cumulative funding of a perpetual market| -|cumulative_price|String|Defines the cumulative price for the current hour up to the last timestamp| -|last_timestamp|Integer|Defines the last funding timestamp in UNIX seconds| +| Parameter | Type | Description | +| ------------------ | ------- | -------------------------------------------------------------------------- | +| cumulative_funding | String | Defines the cumulative funding of a perpetual market | +| cumulative_price | String | Defines the cumulative price for the current hour up to the last timestamp | +| last_timestamp | Integer | Defines the last funding timestamp in UNIX seconds | **PerpetualMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|hourly_funding_rate_cap|String|Defines the default maximum absolute value of the hourly funding rate| -|hourly_interest_rate|String|Defines the hourly interest rate of the perpetual market| -|next_funding_timestamp|Integer|Defines the next funding timestamp in UNIX seconds| -|funding_interval|Integer|Defines the funding interval in seconds| +| Parameter | Type | Description | +| ----------------------- | ------- | --------------------------------------------------------------------- | +| hourly_funding_rate_cap | String | Defines the default maximum absolute value of the hourly funding rate | +| hourly_interest_rate | String | Defines the hourly interest rate of the perpetual market | +| next_funding_timestamp | Integer | Defines the next funding timestamp in UNIX seconds | +| funding_interval | Integer | Defines the funding interval in seconds | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | ## OrdersHistory @@ -1061,21 +1061,24 @@ func main() { ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by a single market ID|Yes| -|market_ids|String Array|Filter by multiple market IDs|No| -|subaccount_id|String|Filter by subaccount ID|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| -|direction|String|Filter by order direction (Should be one of: ["buy", "sell"])|No| -|is_conditional|String|Search for conditional/non-conditional orders(Should be one of: ["true", "false"])|No| -|start_time|Integer|Search for orders where createdAt >= startTime, time in milliseconds|No| -|end_time|Integer|Search for orders where createdAt <= startTime, time in milliseconds|No| -|state|String|The order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])|No| -|execution_types|String Array|The execution of the order (Should be one of: ["limit", "market"])|No| -|order_type|String|The order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])|No| -|order_types|String Array|The order types to be included (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])|No| +| Parameter | Type | Description | Required | +| ------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| subaccount_id | String | Filter by subaccount ID | No | +| market_id | String | Filter by a single market ID | Yes | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | +| order_types | String Array | The order types to be included (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | No | +| direction | String | Filter by order direction (Should be one of: ["buy", "sell"]) | No | +| start_time | Integer | Search for orders where createdAt >= startTime, time in milliseconds | No | +| end_time | Integer | Search for orders where createdAt <= startTime, time in milliseconds | No | +| is_conditional | String | Search for conditional/non-conditional orders(Should be one of: ["true", "false"]) | No | +| order_type | String | The order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | No | +| state | String | The order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | No | +| execution_types | String Array | The execution of the order (Should be one of: ["limit", "market"]) | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| trade_id | String | Filter by the trade's trade id | No | +| active_markets_only | Bool | Return only orders for active markets | No | +| cid | String | Filter by the custom client order id of the trade's order | No | ### Response Parameters @@ -1246,41 +1249,43 @@ paging { ``` -|Parameter|Type|Description| -|----|----|----| -|orders|DerivativeOrderHistory Array|list of historical derivative orders| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | ---------------------------- | ------------------------------------ | +| orders | DerivativeOrderHistory Array | list of historical derivative orders | +| paging | Paging | Pagination of results | **DerivativeOrderHistory** -|Parameter|Type|Description| -|----|----|----| -|order_hash|String|Hash of the order| -|market_id|String|Derivative market ID| -|is_active|Boolean|Indicates if the order is active| -|subaccount_id|String|The subaccountId that this order belongs to| -|execution_type|String|The type of the order (Should be one of: ["limit", "market"])| -|order_type|String|Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])| -|price|String|Price of the order| -|trigger_price|String|The price that triggers stop/take orders| -|quantity|String|Quantity of the order| -|filled_quantity|String|The amount of the quantity filled| -|state|String|Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])| -|created_at|Integer|Order created timestamp in UNIX millis| -|updated_at|Integer|Order updated timestamp in UNIX millis| -|is_reduce_only|Boolean|Indicates if the order is reduce-only| -|direction|String|The direction of the order (Should be one of: ["buy", "sell"])| -|is_conditional|Boolean|Indicates if the order is conditional| -|trigger_at|Integer|Trigger timestamp in UNIX millis| -|placed_order_hash|String|Hash of order placed upon conditional order trigger| -|margin|String|The margin of the order| +| Parameter | Type | Description | +| ----------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | Hash of the order | +| market_id | String | Derivative market ID | +| is_active | Boolean | Indicates if the order is active | +| subaccount_id | String | The subaccountId that this order belongs to | +| execution_type | String | The type of the order (Should be one of: ["limit", "market"]) | +| order_type | String | Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | +| price | String | Price of the order | +| trigger_price | String | The price that triggers stop/take orders | +| quantity | String | Quantity of the order | +| filled_quantity | String | The amount of the quantity filled | +| state | String | Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | +| created_at | Integer | Order created timestamp in UNIX millis | +| updated_at | Integer | Order updated timestamp in UNIX millis | +| is_reduce_only | Boolean | Indicates if the order is reduce-only | +| direction | String | The direction of the order (Should be one of: ["buy", "sell"]) | +| is_conditional | Boolean | Indicates if the order is conditional | +| trigger_at | Integer | Trigger timestamp in UNIX millis | +| placed_order_hash | String | Hash of order placed upon conditional order trigger | +| margin | String | The margin of the order | +| tx_hash | String | Transaction hash in which the order was created (not all orders have this value) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of available records| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of available records | ## StreamOrdersHistory @@ -1403,14 +1408,14 @@ const orderHistory = await indexerGrpcDerivativesApi.fetchOrderHistory({ console.log(orderHistory) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by market ID|Yes| -|subaccount_id|String|Filter by subaccount ID|No| -|direction|String|Filter by direction (Should be one of: ["buy", "sell"])|No| -|state|String|Filter by state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])|No| -|order_types|String Array|Filter by order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])|No| -|execution_types|String Array|Filter by execution type (Should be one of: ["limit", "market"])|No| +| Parameter | Type | Description | Required | +| --------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | -------- | +| market_id | String | Filter by market ID | Yes | +| subaccount_id | String | Filter by subaccount ID | No | +| direction | String | Filter by direction (Should be one of: ["buy", "sell"]) | No | +| state | String | Filter by state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | No | +| order_types | String Array | Filter by order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | No | +| execution_types | String Array | Filter by execution type (Should be one of: ["limit", "market"]) | No | ### Response Parameters @@ -1485,35 +1490,37 @@ timestamp: 1665487078000 ``` -|Parameter|Type|Description| -|----|----|----| -|order|DerivativeOrderHistory|Updated order| -|operation_type|String|Order update type (Should be one of: ["insert", "replace", "update", "invalidate"])| -|timestamp|Integer|Operation timestamp in UNIX millis| +| Parameter | Type | Description | +| -------------- | ---------------------- | ----------------------------------------------------------------------------------- | +| order | DerivativeOrderHistory | Updated order | +| operation_type | String | Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | **DerivativeOrderHistory** -|Parameter|Type|Description| -|----|----|----| -|order_hash|String|Hash of the order| -|market_id|String|Derivative market ID| -|is_active|Boolean|Indicates if the order is active| -|subaccount_id|String|The subaccountId that this order belongs to| -|execution_type|String|The type of the order (Should be one of: ["limit", "market"])| -|order_type|String|Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])| -|price|String|Price of the order| -|trigger_price|String|The price that triggers stop/take orders| -|quantity|String|Quantity of the order| -|filled_quantity|String|The amount of the quantity filled| -|state|String|Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])| -|created_at|Integer|Order created timestamp in UNIX millis| -|updated_at|Integer|Order updated timestamp in UNIX millis| -|is_reduce_only|Boolean|Indicates if the order is reduce-only| -|direction|String|The direction of the order (Should be one of: ["buy", "sell"])| -|is_conditional|Boolean|Indicates if the order is conditional| -|trigger_at|Integer|Trigger timestamp in UNIX millis| -|placed_order_hash|String|Hash of order placed upon conditional order trigger| -|margin|String|The margin of the order| +| Parameter | Type | Description | +| ----------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | Hash of the order | +| market_id | String | Derivative market ID | +| is_active | Boolean | Indicates if the order is active | +| subaccount_id | String | The subaccountId that this order belongs to | +| execution_type | String | The type of the order (Should be one of: ["limit", "market"]) | +| order_type | String | Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | +| price | String | Price of the order | +| trigger_price | String | The price that triggers stop/take orders | +| quantity | String | Quantity of the order | +| filled_quantity | String | The amount of the quantity filled | +| state | String | Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | +| created_at | Integer | Order created timestamp in UNIX millis | +| updated_at | Integer | Order updated timestamp in UNIX millis | +| is_reduce_only | Boolean | Indicates if the order is reduce-only | +| direction | String | The direction of the order (Should be one of: ["buy", "sell"]) | +| is_conditional | Boolean | Indicates if the order is conditional | +| trigger_at | Integer | Trigger timestamp in UNIX millis | +| placed_order_hash | String | Hash of order placed upon conditional order trigger | +| margin | String | The margin of the order | +| tx_hash | String | Transaction hash in which the order was created (not all orders have this value) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | @@ -1625,19 +1632,22 @@ const trades = await indexerGrpcDerivativesApi.fetchTrades({ console.log(trades) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by a single market ID|No| -|market_ids|String Array|Filter by multiple market IDs|No| -|subaccount_id|String|Filter by a single subaccount ID|No| -|subaccount_ids|String Array|Filter by multiple subaccount IDs|No| -|direction|String|Filter by the direction of the trade (Should be one of: ["buy", "sell"])|No| -|execution_side|String|Filter by the execution side of the trade (Should be one of: ["maker", "taker"])|No| -|execution_types|String Array|Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"])|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| -|start_time|Integer|startTime <= trade execution timestamp <= endTime|No| -|end_time|Integer|startTime <= trade execution timestamp <= endTime|No| +| Parameter | Type | Description | Required | +| --------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | -------- | +| market_id | String | Filter by a single market ID | No | +| execution_side | String | Filter by the execution side of the trade (Should be one of: ["maker", "taker"]) | No | +| direction | String | Filter by the direction of the trade (Should be one of: ["buy", "sell"]) | No | +| subaccount_id | String | Filter by a single subaccount ID | No | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | +| start_time | Integer | startTime <= trade execution timestamp <= endTime | No | +| end_time | Integer | startTime <= trade execution timestamp <= endTime | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| subaccount_ids | String Array | Filter by multiple subaccount IDs | No | +| execution_types | String Array | Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | No | +| trade_id | String | Filter by the trade id of the trade | No | +| account_address | String | Filter by the account address | No | +| cid | String | Filter by the custom client order id of the trade's order | No | ### Response Parameters > Response Example: @@ -1791,42 +1801,43 @@ paging { ] ``` -|Parameter|Type|Description| -|----|----|----| -|trades|DerivativeTrade Array|List of trades of derivative markets| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | --------------------- | ------------------------------------ | +| trades | DerivativeTrade Array | List of trades of derivative markets | +| paging | Paging | Pagination of results | **DerivativeTrade** -|Parameter|Type| Description | -|----|----|--------------------------------------------------------------------------------------------------------------------------| -|executed_at|Integer| Timestamp of trade execution (on chain) in UNIX millis | -|position_delta|PositionDelta| Position delta from the trade | -|subaccount_id|String| ID of subaccount that executed the trade | -|trade_execution_type|String| *Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | -|fee|String| The fee associated with the trade | -|is_liquidation|Boolean| True if the trade is a liquidation | -|market_id|String| The market ID | -|order_hash|String| The order hash | -|payout|String| The payout associated with the trade | -|fee_recipient|String| The address that received 40% of the fees | -|trade_id|String| Unique identifier to differentiate between trades | -|execution_side|String| Execution side of trade (Should be one of: ["maker", "taker"]) +| Parameter | Type | Description | +| -------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------ | +| order_hash | String | The order hash | +| subaccount_id | String | ID of subaccount that executed the trade | +| market_id | String | The market ID | +| trade_execution_type | String | *Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | +| is_liquidation | Boolean | True if the trade is a liquidation | +| position_delta | PositionDelta | Position delta from the trade | +| payout | String | The payout associated with the trade | +| fee | String | The fee associated with the trade | +| executed_at | Integer | Timestamp of trade execution (on chain) in UNIX millis | +| fee_recipient | String | The address that received 40% of the fees | +| trade_id | String | Unique identifier to differentiate between trades | +| execution_side | String | Execution side of trade (Should be one of: ["maker", "taker"]) | +| cid | String | Custom client order id | **PositionDelta** -|Parameter|Type|Description| -|----|----|----| -|execution_price|String|Execution price of the trade| -|execution_quantity|String|Execution quantity of the trade| -|trade_direction|String|The direction the trade (Should be one of: ["buy", "sell"]) | -|execution_margin|String|Execution margin of the trade| +| Parameter | Type | Description | +| ------------------ | ------ | ----------------------------------------------------------- | +| execution_price | String | Execution price of the trade | +| execution_quantity | String | Execution quantity of the trade | +| trade_direction | String | The direction the trade (Should be one of: ["buy", "sell"]) | +| execution_margin | String | Execution margin of the trade | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of records available| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of records available | ## StreamTrades @@ -1966,15 +1977,22 @@ import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exch })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by a single market ID|No| -|market_ids|String Array|Filter by multiple market IDs|No| -|subaccount_id|String|Filter by a single subaccount ID|No| -|subaccount_ids|String Array|Filter by multiple subaccount IDs|No| -|direction|String|Filter by the direction of the trade (Should be one of: ["buy", "sell"])|No| -|execution_side|String|Filter by the execution side of the trade (Should be one of: ["maker", "taker"])|No| -|execution_types|String Array|Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"])|No| +| Parameter | Type | Description | Required | +| --------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | -------- | +| market_id | String | Filter by a single market ID | No | +| execution_side | String | Filter by the execution side of the trade (Should be one of: ["maker", "taker"]) | No | +| direction | String | Filter by the direction of the trade (Should be one of: ["buy", "sell"]) | No | +| subaccount_id | String | Filter by a single subaccount ID | No | +| skip | Integer | Skip will skip the first N items from the result | No | +| limit | Integer | Maximum number of items to be returned | No | +| start_time | Integer | Start timestamp (UNIX milliseconds) from when to filter trades | No | +| end_time | Integer | End timestamp (UNIX milliseconds) to filter trades | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| subaccount_ids | String Array | Filter by multiple subaccount IDs | No | +| execution_types | String Array | Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | No | +| trade_id | String | Filter by the trade's trade id | No | +| account_address | String | Filter by the account address | No | +| cid | String | Filter by the custom client order id of the trade's order | No | ### Response Parameters > Streaming Response Example: @@ -2110,38 +2128,39 @@ timestamp: 1652793013000 } ``` -|Parameter|Type|Description| -|----|----|----| -|trade|DerivativeTrade|New derivative market trade| -|operation_type|String|Trade operation type (Should be one of: ["insert", "invalidate"]) | -|timestamp|Integer|Timestamp the new trade is written into the database in UNIX millis| +| Parameter | Type | Description | +| -------------- | --------------- | ------------------------------------------------------------------- | +| trade | DerivativeTrade | New derivative market trade | +| operation_type | String | Trade operation type (Should be one of: ["insert", "invalidate"]) | +| timestamp | Integer | Timestamp the new trade is written into the database in UNIX millis | **DerivativeTrade** -|Parameter|Type| Description | -|----|----|--------------------------------------------------------------------------------------------------------------------------| -|executed_at|Integer| Timestamp of trade execution (on chain) in UNIX millis | -|position_delta|PositionDelta| Position delta from the trade | -|subaccount_id|String| ID of subaccount that executed the trade | -|trade_execution_type|String| *Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | -|fee|String| The fee associated with the trade | -|is_liquidation|Boolean| True if the trade is a liquidation | -|market_id|String| The market ID | -|order_hash|String| The order hash | -|payout|String| The payout associated with the trade | -|fee_recipient|String| The address that received 40% of the fees | -|trade_id|String| Unique identifier to differentiate between trades | -|execution_side|String| Execution side of trade (Should be one of: ["maker", "taker"]) +| Parameter | Type | Description | +| -------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------ | +| order_hash | String | The order hash | +| subaccount_id | String | ID of subaccount that executed the trade | +| market_id | String | The market ID | +| trade_execution_type | String | *Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | +| is_liquidation | Boolean | True if the trade is a liquidation | +| position_delta | PositionDelta | Position delta from the trade | +| payout | String | The payout associated with the trade | +| fee | String | The fee associated with the trade | +| executed_at | Integer | Timestamp of trade execution (on chain) in UNIX millis | +| fee_recipient | String | The address that received 40% of the fees | +| trade_id | String | Unique identifier to differentiate between trades | +| execution_side | String | Execution side of trade (Should be one of: ["maker", "taker"]) | +| cid | String | Custom client order id | **PositionDelta** -|Parameter|Type|Description| -|----|----|----| -|execution_price|String|Execution price of the trade| -|execution_quantity|String|Execution quantity of the trade| -|trade_direction|String|The direction the trade (Should be one of: ["buy", "sell"]) | -|execution_margin|String|Execution margin of the trade| +| Parameter | Type | Description | +| ------------------ | ------ | ----------------------------------------------------------- | +| execution_price | String | Execution price of the trade | +| execution_quantity | String | Execution quantity of the trade | +| trade_direction | String | The direction the trade (Should be one of: ["buy", "sell"]) | +| execution_margin | String | Execution margin of the trade | ## Positions @@ -2263,17 +2282,17 @@ import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/E })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by a single market ID|No| -|market_ids|String Array|Filter by multiple market IDs|No| -|subaccount_id|String|Filter by subaccount ID|No| -|direction|String|Filter by direction of position (Should be one of: ["long", "short"]) -|subaccount_total_positions|Boolean|Choose to return subaccount total positions (Should be one of: [True, False]) -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| -|start_time|Integer|startTime <= position timestamp <= endTime|No| -|end_time|Integer|startTime <= position timestamp <= endTime|No| +| Parameter | Type | Description | Required | +| -------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------- | -------- | +| market_id | String | Filter by a single market ID | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| subaccount_id | String | Filter by subaccount ID | No | +| direction | String | Filter by direction of position (Should be one of: ["long", "short"]) | | +| subaccount_total_positions | Boolean | Choose to return subaccount total positions (Should be one of: [True, False]) | | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | +| start_time | Integer | startTime <= position timestamp <= endTime | No | +| end_time | Integer | startTime <= position timestamp <= endTime | No | ### Response Parameters > Response Example: @@ -2392,34 +2411,34 @@ paging { } ``` -|Parameter|Type|Description| -|----|----|----| -|positions|DerivativePosition Array|List of derivative positions| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | ------------------------ | ---------------------------- | +| positions | DerivativePosition Array | List of derivative positions | +| paging | Paging | Pagination of results | **DerivativePosition** -|Parameter|Type|Description| -|----|----|----| -|direction|String|Direction of the position (Should be one of: ["long", "short"])| -|market_id|String|ID of the market the position is in| -|subaccount_id|String|The subaccount ID the position belongs to| -|ticker|String|Ticker of the derivative market| -|aggregate_reduce_only_quantity|String|Aggregate quantity of the reduce-only orders associated with the position| -|entry_price|String|Entry price of the position| -|liquidation_price|String|Liquidation price of the position| -|margin|String|Margin of the position| -|mark_price|String|Oracle price of the base asset| -|quantity|String|Quantity of the position| -|updated_at|Integer|Position updated timestamp in UNIX millis| -|created_at|Integer|Position created timestamp in UNIX millis. Currently not supported (value will be inaccurate).| +| Parameter | Type | Description | +| ------------------------------ | ------- | ---------------------------------------------------------------------------------------------- | +| direction | String | Direction of the position (Should be one of: ["long", "short"]) | +| market_id | String | ID of the market the position is in | +| subaccount_id | String | The subaccount ID the position belongs to | +| ticker | String | Ticker of the derivative market | +| aggregate_reduce_only_quantity | String | Aggregate quantity of the reduce-only orders associated with the position | +| entry_price | String | Entry price of the position | +| liquidation_price | String | Liquidation price of the position | +| margin | String | Margin of the position | +| mark_price | String | Oracle price of the base asset | +| quantity | String | Quantity of the position | +| updated_at | Integer | Position updated timestamp in UNIX millis | +| created_at | Integer | Position created timestamp in UNIX millis. Currently not supported (value will be inaccurate). | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of available records| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of available records | ## StreamPositions @@ -2535,12 +2554,12 @@ import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exch })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|ID of the market to stream position data from|No| -|market_ids|String Array|IDs of the markets to stream position data from|No| -|subaccount_ids|String Array|Subaccount IDs of the traders to stream positions from|No| -|subaccount_id|String|Subaccount ID of the trader to stream positions from|No| +| Parameter | Type | Description | Required | +| -------------- | ------------ | ------------------------------------------------------ | -------- | +| market_id | String | ID of the market to stream position data from | No | +| market_ids | String Array | IDs of the markets to stream position data from | No | +| subaccount_ids | String Array | Subaccount IDs of the traders to stream positions from | No | +| subaccount_id | String | Subaccount ID of the trader to stream positions from | No | ### Response Parameters @@ -2643,27 +2662,27 @@ timestamp: 1652793296000 } ``` -|Parameter|Type|Description| -|----|----|----| -|position|DerivativePosition|Updated derivative position| -|timestamp|Integer|Timestamp of update in UNIX millis| +| Parameter | Type | Description | +| --------- | ------------------ | ---------------------------------- | +| position | DerivativePosition | Updated derivative position | +| timestamp | Integer | Timestamp of update in UNIX millis | **DerivativePosition** -|Parameter|Type|Description| -|----|----|----| -|direction|String|Direction of the position (Should be one of: ["long", "short"])| -|market_id|String|ID of the market the position is in| -|subaccount_id|String|The subaccount ID the position belongs to| -|ticker|String|Ticker of the derivative market| -|aggregate_reduce_only_quantity|String|Aggregate quantity of the reduce-only orders associated with the position| -|entry_price|String|Entry price of the position| -|liquidation_price|String|Liquidation price of the position| -|margin|String|Margin of the position| -|mark_price|String|Oracle price of the base asset| -|quantity|String|Quantity of the position| -|updated_at|Integer|Position updated timestamp in UNIX millis| -|created_at|Integer|Position created timestamp in UNIX millis. Currently not supported (value will be inaccurate).| +| Parameter | Type | Description | +| ------------------------------ | ------- | ---------------------------------------------------------------------------------------------- | +| direction | String | Direction of the position (Should be one of: ["long", "short"]) | +| market_id | String | ID of the market the position is in | +| subaccount_id | String | The subaccount ID the position belongs to | +| ticker | String | Ticker of the derivative market | +| aggregate_reduce_only_quantity | String | Aggregate quantity of the reduce-only orders associated with the position | +| entry_price | String | Entry price of the position | +| liquidation_price | String | Liquidation price of the position | +| margin | String | Margin of the position | +| mark_price | String | Oracle price of the base asset | +| quantity | String | Quantity of the position | +| updated_at | Integer | Position updated timestamp in UNIX millis | +| created_at | Integer | Position created timestamp in UNIX millis. Currently not supported (value will be inaccurate). | ## \[DEPRECATED\] Orderbook @@ -2750,9 +2769,9 @@ import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/E })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|ID of the market to fetch orderbook from|Yes| +| Parameter | Type | Description | Required | +| --------- | ------ | ---------------------------------------- | -------- | +| market_id | String | ID of the market to fetch orderbook from | Yes | @@ -2888,24 +2907,24 @@ orderbook { -|Parameter|Type|Description| -|----|----|----| -|orderbook|DerivativeLimitOrderbook|Orderbook of a particular derivative market| +| Parameter | Type | Description | +| --------- | ------------------------ | ------------------------------------------- | +| orderbook | DerivativeLimitOrderbook | Orderbook of a particular derivative market | **DerivativeLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------ | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| -|price|String|Price number of the price level| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | +| price | String | Price number of the price level | ## \[DEPRECATED\] Orderbooks @@ -2995,9 +3014,9 @@ import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/E })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of IDs of markets to get orderbooks from|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | --------------------------------------------- | -------- | +| market_ids | String Array | List of IDs of markets to get orderbooks from | Yes | ### Response Parameters @@ -3142,31 +3161,31 @@ orderbooks { } ``` -|Parameter|Type|Description| -|----|----|----| -|orderbooks|SingleDerivativeLimitOrderbook Array|List of derivative market orderbooks| +| Parameter | Type | Description | +| ---------- | ------------------------------------ | ------------------------------------ | +| orderbooks | SingleDerivativeLimitOrderbook Array | List of derivative market orderbooks | **SingleDerivativeLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|ID of the market that the orderbook belongs to| -|orderbook|DerivativeLimitOrderbook|Orderbook of the market| +| Parameter | Type | Description | +| --------- | ------------------------ | ---------------------------------------------- | +| market_id | String | ID of the market that the orderbook belongs to | +| orderbook | DerivativeLimitOrderbook | Orderbook of the market | **DerivativeLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------ | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| -|price|String|Price number of the price level| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | +| price | String | Price number of the price level | ## \[DEPRECATED\] StreamOrderbooks @@ -3273,9 +3292,9 @@ import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exch ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for orderbook streaming, empty means 'ALL' derivative markets|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | -------------------------------------------------------------------------------- | -------- | +| market_ids | String Array | List of market IDs for orderbook streaming, empty means 'ALL' derivative markets | Yes | @@ -3447,27 +3466,27 @@ market_id: "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" } ``` -|Parameter|Type|Description| -|----|----|----| -|operation_type|String|Order update type (Should be one of: ["insert", "delete", "replace", "update", "invalidate"])| -|orderbook|DerivativeLimitOrderbook|Orderbook of a Derivative Market| -|timestamp|Integer|Orderbook update timestamp in UNIX millis| -|market_id|String|ID of the market the orderbook belongs to| +| Parameter | Type | Description | +| -------------- | ------------------------ | --------------------------------------------------------------------------------------------- | +| operation_type | String | Order update type (Should be one of: ["insert", "delete", "replace", "update", "invalidate"]) | +| orderbook | DerivativeLimitOrderbook | Orderbook of a Derivative Market | +| timestamp | Integer | Orderbook update timestamp in UNIX millis | +| market_id | String | ID of the market the orderbook belongs to | **DerivativeLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------ | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| -|price|String|Price number of the price level| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | +| price | String | Price number of the price level | ## OrderbooksV2 @@ -3513,9 +3532,9 @@ if __name__ == '__main__': ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of IDs of markets to get orderbook snapshots from|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------ | -------- | +| market_ids | String Array | List of IDs of markets to get orderbook snapshots from | Yes | ### Response Parameters @@ -3599,32 +3618,32 @@ orderbooks { ``` -|Parameter|Type|Description| -|----|----|----| -|orderbooks|SingleDerivativeLimitOrderbookV2 Array|List of derivative market orderbooks| +| Parameter | Type | Description | +| ---------- | -------------------------------------- | ------------------------------------ | +| orderbooks | SingleDerivativeLimitOrderbookV2 Array | List of derivative market orderbooks | **SingleDerivativeLimitOrderbookV2** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|ID of the market that the orderbook belongs to| -|orderbook|DerivativeLimitOrderbookV2|Orderbook of the market| +| Parameter | Type | Description | +| --------- | -------------------------- | ---------------------------------------------- | +| market_id | String | ID of the market that the orderbook belongs to | +| orderbook | DerivativeLimitOrderbookV2 | Orderbook of the market | **DerivativeLimitOrderbookV2** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| -|sequence|Integer|Sequence number of the orderbook; increments by 1 each update| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------------------------------------- | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | +| sequence | Integer | Sequence number of the orderbook; increments by 1 each update | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| -|price|String|Price number of the price level| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | +| price | String | Price number of the price level | ## StreamOrderbooksV2 @@ -3689,9 +3708,9 @@ streamFn(streamFnArgs) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for orderbook streaming; empty means all spot markets|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------------------------ | -------- | +| market_ids | String Array | List of market IDs for orderbook streaming; empty means all spot markets | Yes | ### Response Parameters @@ -3773,28 +3792,28 @@ market_id: "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" ``` -|Parameter|Type|Description| -|----|----|----| -|orderbook|DerivativeLimitOrderbookV2|Orderbook of a Derivative Market| -|operation_type|String|Order update type (Should be one of: ["insert", "replace", "update", "invalidate"])| -|timestamp|Integer|Operation timestamp in UNIX millis| -|market_id|String|ID of the market the orderbook belongs to| +| Parameter | Type | Description | +| -------------- | -------------------------- | ----------------------------------------------------------------------------------- | +| orderbook | DerivativeLimitOrderbookV2 | Orderbook of a Derivative Market | +| operation_type | String | Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | +| market_id | String | ID of the market the orderbook belongs to | **DerivativeLimitOrderbookV2** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| -|sequence|Integer|Sequence number of the orderbook; increments by 1 each update| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------------------------------------- | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | +| sequence | Integer | Sequence number of the orderbook; increments by 1 each update | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## StreamOrderbookUpdate @@ -3969,9 +3988,9 @@ streamFn(streamFnArgs) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for orderbook streaming; empty means all derivative markets|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------------------------------ | -------- | +| market_ids | String Array | List of market IDs for orderbook streaming; empty means all derivative markets | Yes | ### Response Parameters @@ -4037,31 +4056,31 @@ price: 1000000000 | quantity: 0.0014 | timestamp: 1676622220695 ``` -|Parameter|Type|Description| -|----|----|----| -|orderbook_level_updates|OrderbookLevelUpdates|Orderbook level updates of a derivative market| -|operation_type|String|Order update type (Should be one of: ["insert", "replace", "update", "invalidate"])| -|timestamp|Integer|Operation timestamp in UNIX millis| -|market_id|String|ID of the market the orderbook belongs to| +| Parameter | Type | Description | +| ----------------------- | --------------------- | ----------------------------------------------------------------------------------- | +| orderbook_level_updates | OrderbookLevelUpdates | Orderbook level updates of a derivative market | +| operation_type | String | Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | +| market_id | String | ID of the market the orderbook belongs to | **OrderbookLevelUpdates** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|ID of the market the orderbook belongs to| -|sequence|Integer|Orderbook update sequence number; increments by 1 each update| -|buys|PriceLevelUpdate Array|List of buy level updates| -|sells|PriceLevelUpdate Array|List of sell level updates| -|updated_at|Integer|Timestamp of the updates in UNIX millis| +| Parameter | Type | Description | +| ---------- | ---------------------- | ------------------------------------------------------------- | +| market_id | String | ID of the market the orderbook belongs to | +| sequence | Integer | Orderbook update sequence number; increments by 1 each update | +| buys | PriceLevelUpdate Array | List of buy level updates | +| sells | PriceLevelUpdate Array | List of sell level updates | +| updated_at | Integer | Timestamp of the updates in UNIX millis | **PriceLevelUpdate** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|is_active|Boolean|Price level status| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| is_active | Boolean | Price level status | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## SubaccountOrdersList @@ -4170,12 +4189,12 @@ const subaccountOrders = await indexerGrpcDerivativesApi.fetchSubaccountOrdersLi console.log(subaccountOrders) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|subaccount_id|String|Filter by subaccount ID|Yes| -|market_id|String|Filter by market ID|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| +| Parameter | Type | Description | Required | +| ------------- | ------- | ---------------------------------------------------------------------------------------------------------- | -------- | +| subaccount_id | String | Filter by subaccount ID | Yes | +| market_id | String | Filter by market ID | No | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | ### Response Parameters @@ -4298,35 +4317,39 @@ orders { ] ``` -|Parameter|Type|Description| -|----|----|----| -|orders|DerivativeLimitOrder Array|List of derivative orders| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | -------------------------- | ------------------------- | +| orders | DerivativeLimitOrder Array | List of derivative orders | +| paging | Paging | Pagination of results | **DerivativeLimitOrder** -|Parameter|Type|Description| -|----|----|----| -|fee_recipient|String|Fee recipient address| -|order_hash|String|Hash of the order| -|quantity|String|Quantity of the order| -|state|String|Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | -|trigger_price|String|The price that triggers stop/take orders| -|market_id|String|The market ID| -|created_at|Integer|Order created timestamp in UNIX millis| -|price|String|Price of the order| -|subaccount_id|String|The subaccount ID this order belongs to| -|updated_at|Integer|Order updated timestamp in UNIX millis| -|is_reduce_only|Boolean|True if the order is a reduce-only order| -|margin|String|Margin of the order| -|order_side|String|The side of the order (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell"])| -|unfilled_quantity|String|The amount of the quantity remaining unfilled| -|order_number|Integer|Order number of subaccount| -|order_type|String|Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])| -|is_conditional|Boolean|If the order is conditional| -|trigger_at|Integer|Trigger timestamp, only exists for conditional orders| -|placed_order_hash|String|OrderHash of order that is triggered by this conditional order -|execution_type|String|Execution type of conditional order| +| Parameter | Type | Description | +| ----------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | Hash of the order | +| order_side | String | The side of the order (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell"]) | +| market_id | String | The market ID | +| subaccount_id | String | The subaccount ID this order belongs to | +| is_reduce_only | Boolean | True if the order is a reduce-only order | +| margin | String | Margin of the order | +| price | String | Price of the order | +| quantity | String | Quantity of the order | +| unfilled_quantity | String | The amount of the quantity remaining unfilled | +| trigger_price | String | The price that triggers stop/take orders | +| fee_recipient | String | Fee recipient address | +| state | String | Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | +| created_at | Integer | Order created timestamp in UNIX millis | +| updated_at | Integer | Order updated timestamp in UNIX millis | +| order_number | Integer | Order number of subaccount | +| order_type | String | Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | +| is_conditional | Boolean | If the order is conditional | +| trigger_at | Integer | Trigger timestamp, only exists for conditional orders | +| placed_order_hash | String | OrderHash of order that is triggered by this conditional order | +| execution_type | String | Execution type of conditional order | +| tx_hash | String | Transaction hash in which the order was created (not all orders have this value) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | + + ## SubaccountTradesList @@ -4453,14 +4476,14 @@ const subaccountTrades = await indexerGrpcDerivativesApi.fetchSubaccountTradesLi console.log(subaccountTrades) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|subaccount_id|String|Subaccount ID of trader to get trades from|Yes| -|market_id|String|Filter by Market ID|No| -|direction|String|Filter by the direction of the trades (Should be one of: ["buy", "sell"])|No| -|execution_type|String|Filter by the *execution type of the trades (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"])|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| +| Parameter | Type | Description | Required | +| -------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| subaccount_id | String | Subaccount ID of trader to get trades from | Yes | +| market_id | String | Filter by Market ID | No | +| direction | String | Filter by the direction of the trades (Should be one of: ["buy", "sell"]) | No | +| execution_type | String | Filter by the *execution type of the trades (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | No | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | ### Response Parameters @@ -4601,35 +4624,36 @@ trades { ] ``` -|Parameter|Type|Description| -|----|----|----| -|trades|DerivativeTrade Array|List of derivative market trades| +| Parameter | Type | Description | +| --------- | --------------------- | -------------------------------- | +| trades | DerivativeTrade Array | List of derivative market trades | **DerivativeTrade** -|Parameter|Type| Description | -|----|----|--------------------------------------------------------------------------------------------------------------------------| -|executed_at|Integer| Timestamp of trade execution (on chain) in UNIX millis | -|position_delta|PositionDelta| Position delta from the trade | -|subaccount_id|String| ID of subaccount that executed the trade | -|trade_execution_type|String| *Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | -|fee|String| The fee associated with the trade | -|is_liquidation|Boolean| True if the trade is a liquidation | -|market_id|String| The market ID | -|order_hash|String| The order hash | -|payout|String| The payout associated with the trade | -|fee_recipient|String| The address that received 40% of the fees | -|trade_id|String| Unique identifier to differentiate between trades | -|execution_side|String| Execution side of trade (Should be one of: ["maker", "taker"]) +| Parameter | Type | Description | +| -------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------ | +| order_hash | String | The order hash | +| subaccount_id | String | ID of subaccount that executed the trade | +| market_id | String | The market ID | +| trade_execution_type | String | *Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | +| is_liquidation | Boolean | True if the trade is a liquidation | +| position_delta | PositionDelta | Position delta from the trade | +| payout | String | The payout associated with the trade | +| fee | String | The fee associated with the trade | +| executed_at | Integer | Timestamp of trade execution (on chain) in UNIX millis | +| fee_recipient | String | The address that received 40% of the fees | +| trade_id | String | Unique identifier to differentiate between trades | +| execution_side | String | Execution side of trade (Should be one of: ["maker", "taker"]) | +| cid | String | Custom client order id | **PositionDelta** -|Parameter|Type|Description| -|----|----|----| -|execution_price|String|Execution price of the trade| -|execution_quantity|String|Execution quantity of the trade| -|trade_direction|String|The direction the trade (Should be one of: ["buy", "sell"]) | -|execution_margin|String|Execution margin of the trade| +| Parameter | Type | Description | +| ------------------ | ------ | ----------------------------------------------------------- | +| execution_price | String | Execution price of the trade | +| execution_quantity | String | Execution quantity of the trade | +| trade_direction | String | The direction the trade (Should be one of: ["buy", "sell"]) | +| execution_margin | String | Execution margin of the trade | ## FundingPayments @@ -4733,14 +4757,14 @@ const fundingPayments = await indexerGrpcDerivativesApi.fetchFundingPayments({ console.log(fundingPayments) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|subaccount_id|String|Subaccount ID of the trader we want to get the positions from|Yes| -|market_id|String|Filter by a single market ID|No| -|market_ids|String Array|Filter by multiple market IDs|No| -|skip|Integer|Skip the last *n* funding payments. This can be used to fetch all payments since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| -|end_time|Integer|Upper bound (inclusive) of the funding payment timestamp|No| +| Parameter | Type | Description | Required | +| ------------- | ------------ | ---------------------------------------------------------------------------------------------------- | -------- | +| subaccount_id | String | Subaccount ID of the trader we want to get the positions from | Yes | +| market_id | String | Filter by a single market ID | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| skip | Integer | Skip the last *n* funding payments. This can be used to fetch all payments since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | +| end_time | Integer | Upper bound (inclusive) of the funding payment timestamp | No | ### Response Parameters @@ -4819,25 +4843,25 @@ paging { ] ``` -|Parameter|Type|Description| -|----|----|----| -|payments|FundingPayment Array|List of funding payments| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | -------------------- | ------------------------ | +| payments | FundingPayment Array | List of funding payments | +| paging | Paging | Pagination of results | **FundingPayment** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|The market ID| -|subaccount_id|String|The subaccount ID| -|amount|String|The amount of the funding payment| -|timestamp|Integer|Operation timestamp in UNIX millis| +| Parameter | Type | Description | +| ------------- | ------- | ---------------------------------- | +| market_id | String | The market ID | +| subaccount_id | String | The subaccount ID | +| amount | String | The amount of the funding payment | +| timestamp | Integer | Operation timestamp in UNIX millis | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of records available| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of records available | ## FundingRates @@ -4937,12 +4961,12 @@ const fundingRates = await indexerGrpcDerivativesApi.fetchFundingRates({ console.log(fundingRates) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|ID of the market to get funding rates for|Yes| -|skip|Integer|Skip the last *n* funding rates. This can be used to fetch all funding rates since the API caps at 100|No| -|limit|Integer|Maximum number of funding rates to be returned. 1 <= *n* <= 100|No| -|end_time|Integer|Upper bound (inclusive) of funding rate timestamp|No| +| Parameter | Type | Description | Required | +| --------- | ------- | ------------------------------------------------------------------------------------------------------ | -------- | +| market_id | String | ID of the market to get funding rates for | Yes | +| skip | Integer | Skip the last *n* funding rates. This can be used to fetch all funding rates since the API caps at 100 | No | +| limit | Integer | Maximum number of funding rates to be returned. 1 <= *n* <= 100 | No | +| end_time | Integer | Upper bound (inclusive) of funding rate timestamp | No | ### Response Parameters @@ -5011,25 +5035,25 @@ paging { ] ``` -|Parameter|Type|Description| -|----|----|----| -|funding_rates|FundingRate Array|List of funding rates| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| ------------- | ----------------- | --------------------- | +| funding_rates | FundingRate Array | List of funding rates | +| paging | Paging | Pagination of results | **FundingRate** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|The derivative market ID| -|rate|String|Value of the funding rate| -|timestamp|Integer|Timestamp of funding rate in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ---------------------------------------- | +| market_id | String | The derivative market ID | +| rate | String | Value of the funding rate | +| timestamp | Integer | Timestamp of funding rate in UNIX millis | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of records available| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of records available | ## BinaryOptionsMarket @@ -5082,9 +5106,9 @@ const binaryOptionsMarket = await indexerGrpcDerivativesApi.fetchBinaryOptionsMa console.log(binaryOptionsMarket) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|ID of the binary options market to fetch|Yes| +| Parameter | Type | Description | Required | +| --------- | ------ | ---------------------------------------- | -------- | +| market_id | String | ID of the binary options market to fetch | Yes | ### Response Parameters @@ -5146,42 +5170,42 @@ market { ``` -|Parameter|Type|Description| -|----|----|----| -|market|BinaryOptionsMarketInfo|Info about a particular binary options market| +| Parameter | Type | Description | +| --------- | ----------------------- | --------------------------------------------- | +| market | BinaryOptionsMarketInfo | Info about a particular binary options market | **BinaryOptionsMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|The market ID| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|ticker|String|The name of the binary options market| -|oracle_symbol|String|Oracle symbol| -|oracle_provider|String|Oracle provider| -|oracle_type|String|Oracle Type| -|oracle_scale_factor|Integer|Scaling multiple to scale oracle prices to the correct number of decimals| -|expiration_timestamp|Integer|Defines the expiration time for the market in UNIX seconds| -|settlement_timestamp|Integer|Defines the settlement time for the market in UNIX seconds| -|quote_denom|String|Coin denom used for the quote asset| -|quoteTokenMeta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|taker_fee_rate|String|Defines the fee percentage takers pay (in quote asset) when trading| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|settlement_price|String|Defines the settlement price of the market| +| Parameter | Type | Description | +| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------- | +| market_id | String | The market ID | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| ticker | String | The name of the binary options market | +| oracle_symbol | String | Oracle symbol | +| oracle_provider | String | Oracle provider | +| oracle_type | String | Oracle Type | +| oracle_scale_factor | Integer | Scaling multiple to scale oracle prices to the correct number of decimals | +| expiration_timestamp | Integer | Defines the expiration time for the market in UNIX seconds | +| settlement_timestamp | Integer | Defines the settlement time for the market in UNIX seconds | +| quote_denom | String | Coin denom used for the quote asset | +| quoteTokenMeta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| taker_fee_rate | String | Defines the fee percentage takers pay (in quote asset) when trading | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| settlement_price | String | Defines the settlement price of the market | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | ## BinaryOptionsMarkets @@ -5243,12 +5267,12 @@ console.log(binaryOptionsMarket) ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_status|String|Filter by the status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])|No| -|quote_denom|String|Filter by the Coin denomination of the quote currency|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| +| Parameter | Type | Description | Required | +| ------------- | ------- | ----------------------------------------------------------------------------------------------------------------- | -------- | +| market_status | String | Filter by the status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | No | +| quote_denom | String | Filter by the Coin denomination of the quote currency | No | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | ### Response Parameters @@ -5336,46 +5360,46 @@ paging { ``` -|Parameter|Type|Description| -|----|----|----| -|market|BinaryOptionsMarketInfo Array|List of binary options markets and associated info| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | ----------------------------- | -------------------------------------------------- | +| market | BinaryOptionsMarketInfo Array | List of binary options markets and associated info | +| paging | Paging | Pagination of results | **BinaryOptionsMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|The market ID| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|ticker|String|The name of the binary options market| -|oracle_symbol|String|Oracle symbol| -|oracle_provider|String|Oracle provider| -|oracle_type|String|Oracle Type| -|oracle_scale_factor|Integer|Scaling multiple to scale oracle prices to the correct number of decimals| -|expiration_timestamp|Integer|Defines the expiration time for the market in UNIX seconds| -|settlement_timestamp|Integer|Defines the settlement time for the market in UNIX seconds| -|quote_denom|String|Coin denom used for the quote asset| -|quoteTokenMeta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|taker_fee_rate|String|Defines the fee percentage takers pay (in quote asset) when trading| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|settlement_price|String|Defines the settlement price of the market| +| Parameter | Type | Description | +| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------- | +| market_id | String | The market ID | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| ticker | String | The name of the binary options market | +| oracle_symbol | String | Oracle symbol | +| oracle_provider | String | Oracle provider | +| oracle_type | String | Oracle Type | +| oracle_scale_factor | Integer | Scaling multiple to scale oracle prices to the correct number of decimals | +| expiration_timestamp | Integer | Defines the expiration time for the market in UNIX seconds | +| settlement_timestamp | Integer | Defines the settlement time for the market in UNIX seconds | +| quote_denom | String | Coin denom used for the quote asset | +| quoteTokenMeta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| taker_fee_rate | String | Defines the fee percentage takers pay (in quote asset) when trading | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| settlement_price | String | Defines the settlement price of the market | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of available records| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of available records | diff --git a/source/includes/_faq.md b/source/includes/_faq.md index 3b52843e..5c166e88 100644 --- a/source/includes/_faq.md +++ b/source/includes/_faq.md @@ -16,13 +16,7 @@ 500000000 * 104519 / 1e18 = 0.0000522595 INJ ## 4. Which API nodes can I connect to? - The SDKs default to using a [K8s cluster endpoint](https://docs.injective.network/develop/public-endpoints). If you do not wish to use this endpoint, there are currently three sentry nodes you can connect to on Mainnet that are based in the U.S. and Tokyo. It's recommended you connect to the sentry node closest to your location in order to reduce latency. You can also run your own Injective Node and Exchange API backend to have lower latency and full control over the infrastructure. The guide to set up your own node can be found [here](https://www.notion.so/injective/Injective-Exchange-Service-Setup-Guide-7e59980634d54991862300670583d46a). - - U.S. Sentry Node: sentry0.injective.network - - U.S. Sentry Node: sentry1.injective.network - - Tokyo Sentry Node: sentry3.injective.network + The SDKs default to using a [load balanced endpoint](https://docs.injective.network/develop/public-endpoints). It is possible also to run a local node. The guide to set up your own node can be found [here](https://www.notion.so/injective/Injective-Exchange-Service-Setup-Guide-7e59980634d54991862300670583d46a). ## 5. Does Injective have an API support channel? @@ -30,9 +24,11 @@ ## 6. Can I get the order_hash (order_id) right after I send a new order? Yes, you can actually fetch the order_hash before you even send the transaction through our simulation, you can see the Chain API examples on how to use the simulation. + + A better alternative is to set a client order id (cid) to the orders. It is possible to then cancel the orders by cid instead of hash. With this it is no longer necessary to calculate the order hash in advance. ## 7. Are there limits in the API requests? - No, there are currently no limits in the API requests. + All public nodes have limits to the number of request they allow per IP. Please check the [rate limits page](#overview-rate-limits). ## 8. What is the normal order latency I can expect? There's no guarantee on when the chain will process your transaction. It depends on the peer to peer gossip of the network and whether your transaction reaches a given block producer to get included in a block. You can read more details about this here [https://docs.tendermint.com/v0.35/assets/img/tm-transaction-flow.258ca020.png](https://docs.tendermint.com/v0.35/assets/img/tm-transaction-flow.258ca020.png) as well as the docs here [https://docs.tendermint.com/v0.35/introduction/what-is-tendermint.html](https://docs.tendermint.com/v0.35/introduction/what-is-tendermint.html) @@ -84,8 +80,6 @@ **Async:** Don’t wait for the tx to pass/fail CheckTx; send and return tx immediately - **Block:** Wait for the tx to pass/fail CheckTx, DeliverTx, and be committed in a block - ## 17. When may I see a max subscriptions per client error? You can open up to 5 chain channels per IP, if you run more than 5 trading bots from the same IP then this error would naturally show up and you should use a different IP. Every trading bot should open one chain channel only, thus if you're seeing this error and don't have 5 distinct trading bots then it indicates an issue in your logic. If you want to broadcast multiple transactions in a single block you can use sync mode and open one channel only. You can refer [here](https://github.com/InjectiveLabs/sdk-python/blob/master/examples/async/chain_client/1_MsgSend.py#L32) for the chain channel initialization in sdk-python. diff --git a/source/includes/_insurance.md b/source/includes/_insurance.md index 44ccf3cb..1926d802 100644 --- a/source/includes/_insurance.md +++ b/source/includes/_insurance.md @@ -11,38 +11,39 @@ Includes the messages to create, underwrite and redeem in insurance funds. ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client + # set custom cookie location (optional) - defaults to current dir client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) msg = composer.MsgCreateInsuranceFund( sender=address.to_acc_bech32(), - ticker="5202d32a9-1701406800-SA", + ticker="5202d32a9-1701406800-SF", quote_denom="USDT", oracle_base="Frontrunner", oracle_quote="Frontrunner", oracle_type=11, expiry=-2, - initial_deposit=1000 + initial_deposit=1000, ) # build sim tx @@ -64,14 +65,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -82,9 +85,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` |Parameter|Type|Description|Required| @@ -118,34 +122,35 @@ gas fee: 0.000075824 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client + # set custom cookie location (optional) - defaults to current dir client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) msg = composer.MsgUnderwrite( sender=address.to_acc_bech32(), market_id="0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74", quote_denom="USDT", - amount=100 + amount=100, ) # build sim tx @@ -167,14 +172,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -185,9 +192,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` |Parameter|Type|Description|Required| @@ -217,34 +225,35 @@ gas fee: 0.000071021 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client + # set custom cookie location (optional) - defaults to current dir client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) msg = composer.MsgRequestRedemption( sender=address.to_acc_bech32(), market_id="0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74", share_denom="share15", - amount=100 # raw chain value + amount=100, # raw chain value ) # build sim tx @@ -266,14 +275,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -284,9 +295,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` |Parameter|Type|Description|Required| diff --git a/source/includes/_metarpc.md b/source/includes/_metarpc.md index 733e4bcf..07c99800 100644 --- a/source/includes/_metarpc.md +++ b/source/includes/_metarpc.md @@ -391,18 +391,18 @@ Subscribe to a stream and gracefully disconnect and connect to another sentry no ``` python import asyncio -import logging from pyinjective.async_client import AsyncClient from pyinjective.core.network import Network + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() client = AsyncClient(network) - task1 = asyncio.create_task(get_markets(client)) - task2 = asyncio.create_task(keepalive(client, [task1])) + task1 = asyncio.get_event_loop().create_task(get_markets(client)) + task2 = asyncio.get_event_loop().create_task(keepalive(client, [task1])) try: await asyncio.gather( @@ -422,15 +422,15 @@ async def get_markets(client): async def keepalive(client, tasks: list): stream = await client.stream_keepalive() async for announce in stream: - print('Server announce:', announce) + print("Server announce:", announce) async for task in tasks: task.cancel() - print('Cancelled all tasks') + print("Cancelled all tasks") -if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) +if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go diff --git a/source/includes/_oracle.md b/source/includes/_oracle.md index 0935cba1..b9512af9 100644 --- a/source/includes/_oracle.md +++ b/source/includes/_oracle.md @@ -11,40 +11,36 @@ Includes the message to relay a price feed. ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) - price = 100 - price_to_send = [str(int(price * 10 ** 18))] - base = ["BAYC"] - quote = ["WETH"] + provider = "ufc" + symbols = ["KHABIB-TKO-05/30/2023", "KHABIB-TKO-05/26/2023"] + prices = [0.5, 0.8] # prepare tx msg - msg = composer.MsgRelayPriceFeedPrice( - sender=address.to_acc_bech32(), - price=price_to_send, - base=base, - quote=quote + msg = composer.MsgRelayProviderPrices( + sender=address.to_acc_bech32(), provider=provider, symbols=symbols, prices=prices ) # build sim tx @@ -65,28 +61,36 @@ async def main() -> None: print(sim_res) return + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) + print("---Simulation Response---") + print(sim_res_msg) + # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) # 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("---Transaction Response---") print(res) print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go diff --git a/source/includes/_spot.md b/source/includes/_spot.md index 69879838..e5225603 100644 --- a/source/includes/_spot.md +++ b/source/includes/_spot.md @@ -11,29 +11,29 @@ Includes all messages related to spot markets. ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info @@ -48,7 +48,8 @@ async def main() -> None: fee_recipient=fee_recipient, price=10.522, quantity=0.01, - is_buy=True + is_buy=True, + cid=str(uuid.uuid4()), ) # build sim tx @@ -69,19 +70,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -93,140 +96,144 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go package main import ( - "fmt" - "os" - "time" - - "github.com/InjectiveLabs/sdk-go/client/common" - "github.com/shopspring/decimal" + "fmt" + "github.com/google/uuid" + "os" + "time" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" + "github.com/InjectiveLabs/sdk-go/client/common" + "github.com/shopspring/decimal" - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx.WithNodeURI(network.TmEndpoint) - clientCtx = clientCtx.WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - marketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" - amount := decimal.NewFromFloat(0.1) - price := decimal.NewFromFloat(22) - - order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ - OrderType: exchangetypes.OrderType_SELL, //BUY SELL - Quantity: amount, - Price: price, - FeeRecipient: senderAddress.String(), - MarketId: marketId, - }) - - msg := new(exchangetypes.MsgCreateSpotMarketOrder) - msg.Sender = senderAddress.String() - msg.Order = exchangetypes.SpotOrder(*order) - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - if err != nil { - fmt.Println(err) - } - simResMsgs := common.MsgResponse(simRes.Result.Data) - msgCreateSpotMarketOrderResponse := exchangetypes.MsgCreateSpotMarketOrderResponse{} - msgCreateSpotMarketOrderResponse.Unmarshal(simResMsgs[0].Data) - - if err != nil { - fmt.Println(err) - } - - fmt.Println("simulated order hash", msgCreateSpotMarketOrderResponse.OrderHash) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + + if err != nil { + panic(err) + } + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + return + } + + defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) + + marketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" + amount := decimal.NewFromFloat(0.1) + price := decimal.NewFromFloat(22) + + order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ + OrderType: exchangetypes.OrderType_SELL, //BUY SELL + Quantity: amount, + Price: price, + FeeRecipient: senderAddress.String(), + MarketId: marketId, + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgCreateSpotMarketOrder) + msg.Sender = senderAddress.String() + msg.Order = exchangetypes.SpotOrder(*order) + + simRes, err := chainClient.SimulateMsg(clientCtx, msg) + if err != nil { + fmt.Println(err) + return + } + + msgCreateSpotMarketOrderResponse := exchangetypes.MsgCreateSpotMarketOrderResponse{} + err = msgCreateSpotMarketOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("simulated order hash", msgCreateSpotMarketOrderResponse.OrderHash) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg) + + if err != nil { + fmt.Println(err) + return + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } + ``` ``` typescript https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgcreatespotmarketorder ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to send an order|Yes| -|sender|String|The Injective Chain address|Yes| -|subaccount_id|String|The subaccount we want to send an order from|Yes| -|fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| -|price|Float|The worst accepted price of the base asset|Yes| -|quantity|Float|The quantity of the base asset|Yes| -|is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| +| Parameter | Type | Description | Required | +| ------------- | ------- | ------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to send an order | Yes | +| sender | String | The Injective Chain address | Yes | +| subaccount_id | String | The subaccount we want to send an order from | Yes | +| fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | +| price | Float | The worst accepted price of the base asset | Yes | +| quantity | Float | The quantity of the base asset | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | > Response Example: @@ -262,34 +269,35 @@ gas fee: 0.000065298 INJ ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" + cid = str(uuid.uuid4()) # prepare tx msg msg = composer.MsgCreateSpotLimitOrder( @@ -300,7 +308,8 @@ async def main() -> None: price=7.523, quantity=0.01, is_buy=True, - is_po=False + is_po=False, + cid=cid, ) # build sim tx @@ -321,19 +330,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -344,143 +355,148 @@ async def main() -> None: print(res) print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + print(f"\n\ncid: {cid}") + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go package main import ( - "fmt" - "os" - "time" + "fmt" + "github.com/google/uuid" + "os" + "time" - "github.com/InjectiveLabs/sdk-go/client/common" - "github.com/shopspring/decimal" + "github.com/InjectiveLabs/sdk-go/client/common" + "github.com/shopspring/decimal" - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - marketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" - - amount := decimal.NewFromFloat(2) - price := decimal.NewFromFloat(22.55) - - order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: amount, - Price: price, - FeeRecipient: senderAddress.String(), - MarketId: marketId, - }) - - msg := new(exchangetypes.MsgCreateSpotLimitOrder) - msg.Sender = senderAddress.String() - msg.Order = exchangetypes.SpotOrder(*order) - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - } - - simResMsgs := common.MsgResponse(simRes.Result.Data) - msgCreateSpotLimitOrderResponse := exchangetypes.MsgCreateSpotLimitOrderResponse{} - msgCreateSpotLimitOrderResponse.Unmarshal(simResMsgs[0].Data) - - if err != nil { - fmt.Println(err) - } - - fmt.Println("simulated order hash: ", msgCreateSpotLimitOrderResponse.OrderHash) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("mainnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + + if err != nil { + panic(err) + } + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + if err != nil { + fmt.Println(err) + return + } + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + return + } + + defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) + + marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0" + + amount := decimal.NewFromFloat(2) + price := decimal.NewFromFloat(22.55) + + order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: amount, + Price: price, + FeeRecipient: senderAddress.String(), + MarketId: marketId, + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgCreateSpotLimitOrder) + msg.Sender = senderAddress.String() + msg.Order = exchangetypes.SpotOrder(*order) + + simRes, err := chainClient.SimulateMsg(clientCtx, msg) + + if err != nil { + fmt.Println(err) + return + } + + msgCreateSpotLimitOrderResponse := exchangetypes.MsgCreateSpotLimitOrderResponse{} + err = msgCreateSpotLimitOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("simulated order hash: ", msgCreateSpotLimitOrderResponse.OrderHash) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg) + + if err != nil { + fmt.Println(err) + return + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } + ``` ``` typescript https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgcreatespotlimitorder ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to send an order|Yes| -|sender|String|The Injective Chain address|Yes| -|subaccount_id|String|The subaccount we want to send an order from|Yes| -|fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| -|price|Float|The price of the base asset|Yes| -|quantity|Float|The quantity of the base asset|Yes| -|is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| -|is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| +| Parameter | Type | Description | Required | +| ------------- | ------- | ------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to send an order | Yes | +| sender | String | The Injective Chain address | Yes | +| subaccount_id | String | The subaccount we want to send an order from | Yes | +| fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | +| price | Float | The price of the base asset | Yes | +| quantity | Float | The quantity of the base asset | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | +| is_po | Boolean | Set to true or false for post-only or normal orders respectively | No | > Response Example: @@ -515,28 +531,28 @@ gas fee: 0.000064956 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info @@ -545,10 +561,7 @@ async def main() -> None: # prepare tx msg msg = composer.MsgCancelSpotOrder( - sender=address.to_acc_bech32(), - market_id=market_id, - subaccount_id=subaccount_id, - order_hash=order_hash + sender=address.to_acc_bech32(), market_id=market_id, subaccount_id=subaccount_id, order_hash=order_hash ) # build sim tx @@ -570,14 +583,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -588,9 +603,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -685,12 +701,12 @@ func main() { https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgcancelspotorder ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to cancel an order|Yes| -|sender|String|The Injective Chain address|Yes| -|subaccount_id|String|The subaccount we want to cancel an order from|Yes| -|order_hash|String|The hash of a specific order|Yes| +| Parameter | Type | Description | Required | +| ------------- | ------ | -------------------------------------------------- | -------- | +| market_id | String | Market ID of the market we want to cancel an order | Yes | +| sender | String | The Injective Chain address | Yes | +| subaccount_id | String | The subaccount we want to cancel an order from | Yes | +| order_hash | String | The hash of a specific order | Yes | > Response Example: @@ -727,39 +743,39 @@ Further note that if no marketIDs are provided in the SpotMarketIdsToCancelAll o ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) # prepare trade info fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" - derivative_market_id_create = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" + derivative_market_id_create = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" spot_market_id_create = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" derivative_market_id_cancel = "0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff" - derivative_market_id_cancel_2 = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3" + derivative_market_id_cancel_2 = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" spot_market_id_cancel = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" spot_market_id_cancel_2 = "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0" @@ -767,26 +783,26 @@ async def main() -> None: composer.OrderData( market_id=derivative_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103" + order_hash="0x48690013c382d5dbaff9989db04629a16a5818d7524e027d517ccc89fd068103", ), composer.OrderData( market_id=derivative_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5" - ) + order_hash="0x7ee76255d7ca763c56b0eab9828fca89fdd3739645501c8a80f58b62b4f76da5", + ), ] spot_orders_to_cancel = [ composer.OrderData( market_id=spot_market_id_cancel, subaccount_id=subaccount_id, - order_hash="0x3870fbdd91f07d54425147b1bb96404f4f043ba6335b422a6d494d285b387f2d" + cid="0e5c3ad5-2cc4-4a2a-bbe5-b12697739163", ), composer.OrderData( market_id=spot_market_id_cancel_2, subaccount_id=subaccount_id, - order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2" - ) + order_hash="0x222daa22f60fe9f075ed0ca583459e121c23e64431c3fbffdedda04598ede0d2", + ), ] derivative_orders_to_create = [ @@ -798,7 +814,8 @@ async def main() -> None: quantity=0.1, leverage=1, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.DerivativeOrder( market_id=derivative_market_id_create, @@ -808,7 +825,8 @@ async def main() -> None: quantity=0.01, leverage=1, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -820,7 +838,8 @@ async def main() -> None: price=3, quantity=55, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id_create, @@ -829,7 +848,8 @@ async def main() -> None: price=300, quantity=55, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -839,7 +859,7 @@ async def main() -> None: derivative_orders_to_create=derivative_orders_to_create, spot_orders_to_create=spot_orders_to_create, derivative_orders_to_cancel=derivative_orders_to_cancel, - spot_orders_to_cancel=spot_orders_to_cancel + spot_orders_to_cancel=spot_orders_to_cancel, ) # build sim tx @@ -860,19 +880,21 @@ async def main() -> None: print(sim_res) return - sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res, simulation=True) + sim_res_msg = composer.MsgResponses(sim_res, simulation=True) print("---Simulation Response---") print(sim_res_msg) # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -884,223 +906,232 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go package main import ( - "fmt" - "os" - "time" - - "github.com/InjectiveLabs/sdk-go/client/common" - "github.com/shopspring/decimal" - - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - cosmtypes "github.com/cosmos/cosmos-sdk/types" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" + "fmt" + "github.com/google/uuid" + "os" + "time" + + "github.com/InjectiveLabs/sdk-go/client/common" + "github.com/shopspring/decimal" + + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + cosmtypes "github.com/cosmos/cosmos-sdk/types" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - smarketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" - samount := decimal.NewFromFloat(2) - sprice := decimal.NewFromFloat(22.5) - smarketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"} - - spot_order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: samount, - Price: sprice, - FeeRecipient: senderAddress.String(), - MarketId: smarketId, - }) - - dmarketId := "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" - damount := decimal.NewFromFloat(0.01) - dprice := cosmtypes.MustNewDecFromStr("31000000000") //31,000 - dleverage := cosmtypes.MustNewDecFromStr("2") - dmarketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"} - - derivative_order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ - OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO - Quantity: damount, - Price: dprice, - Leverage: dleverage, - FeeRecipient: senderAddress.String(), - MarketId: dmarketId, - IsReduceOnly: false, - }) - - msg := new(exchangetypes.MsgBatchUpdateOrders) - msg.Sender = senderAddress.String() - msg.SubaccountId = defaultSubaccountID.Hex() - msg.SpotOrdersToCreate = []*exchangetypes.SpotOrder{spot_order} - msg.DerivativeOrdersToCreate = []*exchangetypes.DerivativeOrder{derivative_order} - msg.SpotMarketIdsToCancelAll = smarketIds - msg.DerivativeMarketIdsToCancelAll = dmarketIds - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - } - - simResMsgs := common.MsgResponse(simRes.Result.Data) - MsgBatchUpdateOrdersResponse := exchangetypes.MsgBatchUpdateOrdersResponse{} - MsgBatchUpdateOrdersResponse.Unmarshal(simResMsgs[0].Data) - - fmt.Println("simulated spot order hashes", MsgBatchUpdateOrdersResponse.SpotOrderHashes) - - fmt.Println("simulated derivative order hashes", MsgBatchUpdateOrdersResponse.DerivativeOrderHashes) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + + if err != nil { + panic(err) + } + + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + return + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + return + } + + defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) + + smarketId := "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa" + samount := decimal.NewFromFloat(2) + sprice := decimal.NewFromFloat(22.5) + smarketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"} + + spot_order := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: samount, + Price: sprice, + FeeRecipient: senderAddress.String(), + MarketId: smarketId, + Cid: uuid.NewString(), + }) + + dmarketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce" + damount := decimal.NewFromFloat(0.01) + dprice := cosmtypes.MustNewDecFromStr("31000000000") //31,000 + dleverage := cosmtypes.MustNewDecFromStr("2") + dmarketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"} + + derivative_order := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ + OrderType: exchangetypes.OrderType_BUY, //BUY SELL BUY_PO SELL_PO + Quantity: damount, + Price: dprice, + Leverage: dleverage, + FeeRecipient: senderAddress.String(), + MarketId: dmarketId, + IsReduceOnly: false, + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgBatchUpdateOrders) + msg.Sender = senderAddress.String() + msg.SubaccountId = defaultSubaccountID.Hex() + msg.SpotOrdersToCreate = []*exchangetypes.SpotOrder{spot_order} + msg.DerivativeOrdersToCreate = []*exchangetypes.DerivativeOrder{derivative_order} + msg.SpotMarketIdsToCancelAll = smarketIds + msg.DerivativeMarketIdsToCancelAll = dmarketIds + + simRes, err := chainClient.SimulateMsg(clientCtx, msg) + + if err != nil { + fmt.Println(err) + return + } + + MsgBatchUpdateOrdersResponse := exchangetypes.MsgBatchUpdateOrdersResponse{} + MsgBatchUpdateOrdersResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) + + fmt.Println("simulated spot order hashes", MsgBatchUpdateOrdersResponse.SpotOrderHashes) + + fmt.Println("simulated derivative order hashes", MsgBatchUpdateOrdersResponse.DerivativeOrderHashes) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg) + + if err != nil { + fmt.Println(err) + return + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } + ``` ``` typescript https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgbatchupdateorders ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|sender|String|The Injective Chain address|Yes| -|subaccount_id|String|The subaccount ID|Conditional| -|derivative_orders_to_create|DerivativeOrder|DerivativeOrder object|No| -|binary_options_orders_to_create|BinaryOptionsOrder|BinaryOptionsOrder object|No| -|spot_orders_to_create|SpotOrder|SpotOrder object|No| -|derivative_orders_to_cancel|OrderData|OrderData object to cancel|No| -|binary_options_orders_to_cancel|OrderData|OrderData object to cancel|No| -|spot_orders_to_cancel|Orderdata|OrderData object to cancel|No| -|spot_market_ids_to_cancel_all|List|Spot Market IDs for the markets the trader wants to cancel all active orders|No| -|derivative_market_ids_to_cancel_all|List|Derivative Market IDs for the markets the trader wants to cancel all active orders|No| -|binary_options_market_ids_to_cancel_all|List|Binary Options Market IDs for the markets the trader wants to cancel all active orders|No| +| Parameter | Type | Description | Required | +| --------------------------------------- | ------------------ | -------------------------------------------------------------------------------------- | ----------- | +| sender | String | The Injective Chain address | Yes | +| subaccount_id | String | The subaccount ID | Conditional | +| derivative_orders_to_create | DerivativeOrder | DerivativeOrder object | No | +| binary_options_orders_to_create | BinaryOptionsOrder | BinaryOptionsOrder object | No | +| spot_orders_to_create | SpotOrder | SpotOrder object | No | +| derivative_orders_to_cancel | OrderData | OrderData object to cancel | No | +| binary_options_orders_to_cancel | OrderData | OrderData object to cancel | No | +| spot_orders_to_cancel | Orderdata | OrderData object to cancel | No | +| spot_market_ids_to_cancel_all | List | Spot Market IDs for the markets the trader wants to cancel all active orders | No | +| derivative_market_ids_to_cancel_all | List | Derivative Market IDs for the markets the trader wants to cancel all active orders | No | +| binary_options_market_ids_to_cancel_all | List | Binary Options Market IDs for the markets the trader wants to cancel all active orders | No | **SpotOrder** -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to send an order|Yes| -|subaccount_id|String|The subaccount we want to send an order from|Yes| -|fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| -|price|Float|The price of the base asset|Yes| -|quantity|Float|The quantity of the base asset|Yes| -|is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| -|is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| +| Parameter | Type | Description | Required | +| ------------- | ------- | ------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to send an order | Yes | +| subaccount_id | String | The subaccount we want to send an order from | Yes | +| fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | +| price | Float | The price of the base asset | Yes | +| quantity | Float | The quantity of the base asset | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | +| is_po | Boolean | Set to true or false for post-only or normal orders respectively | No | **DerivativeOrder** -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to send an order|Yes| -|subaccount_id|String|The subaccount ID we want to send an order from|Yes| -|fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| -|price|Float|The price of the base asset|Yes| -|quantity|Float|The quantity of the base asset|Yes| -|leverage|Float|The leverage factor for the order|No| -|trigger_price|String|Set the trigger price for conditional orders|No| -|is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| -|is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| -|is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| -|stop_buy|Boolean|Set to true for conditional stop_buy orders|No| -|stop_sell|Boolean|Set to true for conditional stop_sell orders|No| -|take_buy|Boolean|Set to true for conditional take_buy orders|No| -|take_sell|Boolean|Set to true for conditional take_sell|No| +| Parameter | Type | Description | Required | +| -------------- | ------- | ------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to send an order | Yes | +| subaccount_id | String | The subaccount ID we want to send an order from | Yes | +| fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | +| price | Float | The price of the base asset | Yes | +| quantity | Float | The quantity of the base asset | Yes | +| leverage | Float | The leverage factor for the order | No | +| trigger_price | String | Set the trigger price for conditional orders | No | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | +| is_reduce_only | Boolean | Set to true or false for reduce-only or normal orders respectively | No | +| is_po | Boolean | Set to true or false for post-only or normal orders respectively | No | +| stop_buy | Boolean | Set to true for conditional stop_buy orders | No | +| stop_sell | Boolean | Set to true for conditional stop_sell orders | No | +| take_buy | Boolean | Set to true for conditional take_buy orders | No | +| take_sell | Boolean | Set to true for conditional take_sell | No | **BinaryOptionsOrder** -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to send an order|Yes| -|subaccount_id|String|The subaccount ID we want to send an order from|Yes| -|fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| -|price|Float|The price of the base asset|Yes| -|quantity|Float|The quantity of the base asset|Yes| -|leverage|Float|The leverage factor for the order|No| -|is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| -|is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| -|is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| +| Parameter | Type | Description | Required | +| -------------- | ------- | ------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to send an order | Yes | +| subaccount_id | String | The subaccount ID we want to send an order from | Yes | +| fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | +| price | Float | The price of the base asset | Yes | +| quantity | Float | The quantity of the base asset | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| leverage | Float | The leverage factor for the order | No | +| is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | +| is_reduce_only | Boolean | Set to true or false for reduce-only or normal orders respectively | No | +| is_po | Boolean | Set to true or false for post-only or normal orders respectively | No | **OrderData** -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to cancel an order|Yes| -|subaccount_id|String|The subaccount we want to cancel an order from|Yes| -|order_hash|String|The hash of a specific order|Yes| -|is_conditional|Boolean|Set to true or false for conditional and regular orders respectively. Setting this value will incur less gas for the order cancellation and faster execution|No| -|order_direction|Boolean|The direction of the order (Should be one of: [buy sell]). Setting this value will incur less gas for the order cancellation and faster execution|No| -|order_type|Boolean|The type of the order (Should be one of: [market limit]). Setting this value will incur less gas for the order cancellation and faster execution|No| +| Parameter | Type | Description | Required | +| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to cancel an order | Yes | +| subaccount_id | String | The subaccount we want to cancel an order from | Yes | +| order_hash | String | The hash of a specific order | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| is_conditional | Boolean | Set to true or false for conditional and regular orders respectively. Setting this value will incur less gas for the order cancellation and faster execution | No | +| order_direction | Boolean | The direction of the order (Should be one of: [buy sell]). Setting this value will incur less gas for the order cancellation and faster execution | No | +| order_type | Boolean | The type of the order (Should be one of: [market limit]). Setting this value will incur less gas for the order cancellation and faster execution | No | > Response Example: @@ -1147,41 +1178,38 @@ This function computes order hashes locally for SpotOrder and DerivativeOrder. F ``` python import asyncio -import logging +import uuid -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network -from pyinjective.wallet import PrivateKey from pyinjective.orderhash import OrderHashManager +from pyinjective.transaction import Transaction +from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) subaccount_id = address.get_subaccount_id(index=0) subaccount_id_2 = address.get_subaccount_id(index=1) - order_hash_manager = OrderHashManager( - address=address, - network=network, - subaccount_indexes=[0,1,2,7] - ) + order_hash_manager = OrderHashManager(address=address, network=network, subaccount_indexes=[0, 1, 2, 7]) # prepare trade info spot_market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" - deriv_market_id = "0x141e3c92ed55107067ceb60ee412b86256cedef67b1227d6367b4cdf30c55a74" + deriv_market_id = "0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6" fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" spot_orders = [ @@ -1192,7 +1220,8 @@ async def main() -> None: price=0.524, quantity=0.01, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id, @@ -1201,7 +1230,8 @@ async def main() -> None: price=27.92, quantity=0.01, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -1214,7 +1244,8 @@ async def main() -> None: quantity=0.01, leverage=1.5, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.DerivativeOrder( market_id=deriv_market_id, @@ -1224,23 +1255,20 @@ async def main() -> None: quantity=0.01, leverage=2, is_buy=False, - is_reduce_only=False + is_reduce_only=False, + cid=str(uuid.uuid4()), ), ] # prepare tx msg - spot_msg = composer.MsgBatchCreateSpotLimitOrders( - sender=address.to_acc_bech32(), - orders=spot_orders - ) + spot_msg = composer.MsgBatchCreateSpotLimitOrders(sender=address.to_acc_bech32(), orders=spot_orders) - deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders( - sender=address.to_acc_bech32(), - orders=derivative_orders - ) + deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders(sender=address.to_acc_bech32(), orders=derivative_orders) # compute order hashes - order_hashes = order_hash_manager.compute_order_hashes(spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0) + order_hashes = order_hash_manager.compute_order_hashes( + spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0 + ) print("computed spot order hashes", order_hashes.spot) print("computed derivative order hashes", order_hashes.derivative) @@ -1253,15 +1281,17 @@ async def main() -> None: .with_account_num(client.get_number()) .with_chain_id(network.chain_id) ) - gas_price = 500000000 + gas_price = GAS_PRICE base_gas = 85000 - gas_limit = base_gas + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_limit = base_gas + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -1272,9 +1302,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) - # compute order hashes - order_hashes = order_hash_manager.compute_order_hashes(spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0) + order_hashes = order_hash_manager.compute_order_hashes( + spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=0 + ) print("computed spot order hashes", order_hashes.spot) print("computed derivative order hashes", order_hashes.derivative) @@ -1287,15 +1318,17 @@ async def main() -> None: .with_account_num(client.get_number()) .with_chain_id(network.chain_id) ) - gas_price = 500000000 + gas_price = GAS_PRICE base_gas = 85000 - gas_limit = base_gas + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_limit = base_gas + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -1314,7 +1347,8 @@ async def main() -> None: price=1.524, quantity=0.01, is_buy=True, - is_po=True + is_po=True, + cid=str(uuid.uuid4()), ), composer.SpotOrder( market_id=spot_market_id, @@ -1323,7 +1357,8 @@ async def main() -> None: price=27.92, quantity=0.01, is_buy=False, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), ] @@ -1336,7 +1371,8 @@ async def main() -> None: quantity=0.01, leverage=1.5, is_buy=True, - is_po=False + is_po=False, + cid=str(uuid.uuid4()), ), composer.DerivativeOrder( market_id=deriv_market_id, @@ -1346,23 +1382,20 @@ async def main() -> None: quantity=0.01, leverage=2, is_buy=False, - is_reduce_only=False + is_reduce_only=False, + cid=str(uuid.uuid4()), ), ] # prepare tx msg - spot_msg = composer.MsgBatchCreateSpotLimitOrders( - sender=address.to_acc_bech32(), - orders=spot_orders - ) + spot_msg = composer.MsgBatchCreateSpotLimitOrders(sender=address.to_acc_bech32(), orders=spot_orders) - deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders( - sender=address.to_acc_bech32(), - orders=derivative_orders - ) + deriv_msg = composer.MsgBatchCreateDerivativeLimitOrders(sender=address.to_acc_bech32(), orders=derivative_orders) # compute order hashes - order_hashes = order_hash_manager.compute_order_hashes(spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=1) + order_hashes = order_hash_manager.compute_order_hashes( + spot_orders=spot_orders, derivative_orders=derivative_orders, subaccount_index=1 + ) print("computed spot order hashes", order_hashes.spot) print("computed derivative order hashes", order_hashes.derivative) @@ -1375,15 +1408,17 @@ async def main() -> None: .with_account_num(client.get_number()) .with_chain_id(network.chain_id) ) - gas_price = 500000000 + gas_price = GAS_PRICE base_gas = 85000 - gas_limit = base_gas + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_limit = base_gas + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -1394,8 +1429,8 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) ``` @@ -1404,120 +1439,119 @@ if __name__ == "__main__": package main import ( - "fmt" - exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - "github.com/InjectiveLabs/sdk-go/client/common" - cosmtypes "github.com/cosmos/cosmos-sdk/types" - "github.com/shopspring/decimal" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" - "os" - "time" + "fmt" + "github.com/google/uuid" + "os" + "time" + + exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + "github.com/InjectiveLabs/sdk-go/client/common" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + cosmtypes "github.com/cosmos/cosmos-sdk/types" + "github.com/shopspring/decimal" ) func main() { - // network := common.LoadNetwork("mainnet", "lb") - network := common.LoadNetwork("testnet", "k8s") - tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket") - - if err != nil { - fmt.Println(err) - } - - senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( - os.Getenv("HOME")+"/.injectived", - "injectived", - "file", - "inj-user", - "12345678", - "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided - false, - ) - - if err != nil { - panic(err) - } - - // initialize grpc client - - clientCtx, err := chainclient.NewClientContext( - network.ChainId, - senderAddress.String(), - cosmosKeyring, - ) - - if err != nil { - fmt.Println(err) - } - - clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC) - - chainClient, err := chainclient.NewChainClient( - clientCtx, - network.ChainGrpcEndpoint, - common.OptionTLSCert(network.ChainTlsCert), - common.OptionGasPrices("500000000inj"), - ) - - if err != nil { - fmt.Println(err) - } - - // prepare tx msg - defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress) - - spotOrder := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ - OrderType: exchangetypes.OrderType_BUY, - Quantity: decimal.NewFromFloat(2), - Price: decimal.NewFromFloat(22.55), - FeeRecipient: senderAddress.String(), - MarketId: "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa", - }) - - derivativeOrder := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ - OrderType: exchangetypes.OrderType_BUY, - Quantity: decimal.NewFromFloat(2), - Price: cosmtypes.MustNewDecFromStr("31000000000"), - Leverage: cosmtypes.MustNewDecFromStr("2.5"), - FeeRecipient: senderAddress.String(), - MarketId: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce", - }) - - msg := new(exchangetypes.MsgBatchCreateSpotLimitOrders) - msg.Sender = senderAddress.String() - msg.Orders = []exchangetypes.SpotOrder{*spotOrder} - - msg1 := new(exchangetypes.MsgBatchCreateDerivativeLimitOrders) - msg1.Sender = senderAddress.String() - msg1.Orders = []exchangetypes.DerivativeOrder{*derivativeOrder, *derivativeOrder} - - // compute local order hashes - orderHashes, err := chainClient.ComputeOrderHashes(msg.Orders, msg1.Orders) - - if err != nil { - fmt.Println(err) - } - - fmt.Println("computed spot order hashes: ", orderHashes.Spot) - fmt.Println("computed derivative order hashes: ", orderHashes.Derivative) - - //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg, msg1) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("gas fee:", gasFee, "INJ") + network := common.LoadNetwork("testnet", "lb") + tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket") + if err != nil { + panic(err) + } + + senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring( + os.Getenv("HOME")+"/.injectived", + "injectived", + "file", + "inj-user", + "12345678", + "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided + false, + ) + if err != nil { + panic(err) + } + + // initialize grpc client + clientCtx, err := chainclient.NewClientContext( + network.ChainId, + senderAddress.String(), + cosmosKeyring, + ) + + if err != nil { + fmt.Println(err) + } + + clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient) + + chainClient, err := chainclient.NewChainClient( + clientCtx, + network, + common.OptionGasPrices("500000000inj"), + ) + + if err != nil { + fmt.Println(err) + } + + // prepare tx msg + defaultSubaccountID := chainClient.Subaccount(senderAddress, 1) + + spotOrder := chainClient.SpotOrder(defaultSubaccountID, network, &chainclient.SpotOrderData{ + OrderType: exchangetypes.OrderType_BUY, + Quantity: decimal.NewFromFloat(2), + Price: decimal.NewFromFloat(22.55), + FeeRecipient: senderAddress.String(), + MarketId: "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa", + Cid: uuid.NewString(), + }) + + derivativeOrder := chainClient.DerivativeOrder(defaultSubaccountID, network, &chainclient.DerivativeOrderData{ + OrderType: exchangetypes.OrderType_BUY, + Quantity: decimal.NewFromFloat(2), + Price: cosmtypes.MustNewDecFromStr("31000000000"), + Leverage: cosmtypes.MustNewDecFromStr("2.5"), + FeeRecipient: senderAddress.String(), + MarketId: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce", + Cid: uuid.NewString(), + }) + + msg := new(exchangetypes.MsgBatchCreateSpotLimitOrders) + msg.Sender = senderAddress.String() + msg.Orders = []exchangetypes.SpotOrder{*spotOrder} + + msg1 := new(exchangetypes.MsgBatchCreateDerivativeLimitOrders) + msg1.Sender = senderAddress.String() + msg1.Orders = []exchangetypes.DerivativeOrder{*derivativeOrder, *derivativeOrder} + + // compute local order hashes + orderHashes, err := chainClient.ComputeOrderHashes(msg.Orders, msg1.Orders, defaultSubaccountID) + + if err != nil { + fmt.Println(err) + } + + fmt.Println("computed spot order hashes: ", orderHashes.Spot) + fmt.Println("computed derivative order hashes: ", orderHashes.Derivative) + + //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + err = chainClient.QueueBroadcastMsg(msg, msg1) + + if err != nil { + fmt.Println(err) + } + + time.Sleep(time.Second * 5) + + gasFee, err := chainClient.GetGasFee() + + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("gas fee:", gasFee, "INJ") } ``` @@ -1531,44 +1565,52 @@ https://github.com/InjectiveLabs/injective-ts/blob/master/packages/sdk-ts/src/co **MsgBatchCreateDerivativeLimitOrders** -|Parameter|Type|Description|Required| -|----|----|----|----| -|sender|String|The Injective Chain address|Yes| -|orders|DerivativeOrder|DerivativeOrder object|Yes| +| Parameter | Type | Description | Required | +| --------- | --------------- | --------------------------- | -------- | +| sender | String | The Injective Chain address | Yes | +| orders | DerivativeOrder | DerivativeOrder object | Yes | **DerivativeOrder** -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to send an order|Yes| -|subaccount_id|String|The subaccount ID we want to send an order from|Yes| -|fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| -|price|Float|The price of the base asset|Yes| -|quantity|Float|The quantity of the base asset|Yes| -|leverage|Float|The leverage factor for the order|No| -|is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| -|is_reduce_only|Boolean|Set to true or false for reduce-only or normal orders respectively|No| -|is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| +| Parameter | Type | Description | Required | +| -------------- | ------- | ------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to send an order | Yes | +| subaccount_id | String | The subaccount ID we want to send an order from | Yes | +| fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | +| price | Float | The price of the base asset | Yes | +| quantity | Float | The quantity of the base asset | Yes | +| leverage | Float | The leverage factor for the order | No | +| trigger_price | String | Set the trigger price for conditional orders | No | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | +| is_reduce_only | Boolean | Set to true or false for reduce-only or normal orders respectively | No | +| is_po | Boolean | Set to true or false for post-only or normal orders respectively | No | +| stop_buy | Boolean | Set to true for conditional stop_buy orders | No | +| stop_sell | Boolean | Set to true for conditional stop_sell orders | No | +| take_buy | Boolean | Set to true for conditional take_buy orders | No | +| take_sell | Boolean | Set to true for conditional take_sell | No | **MsgBatchCreateSpotLimitOrders** -|Parameter|Type|Description|Required| -|----|----|----|----| -|sender|String|The Injective Chain address|Yes| -|orders|SpotOrder|SpotOrder object|Yes| +| Parameter | Type | Description | Required | +| --------- | --------- | --------------------------- | -------- | +| sender | String | The Injective Chain address | Yes | +| orders | SpotOrder | SpotOrder object | Yes | **SpotOrder** -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the market we want to send an order|Yes| -|subaccount_id|String|The subaccount we want to send an order from|Yes| -|fee_recipient|String|The address that will receive 40% of the fees, this could be set to your own address|Yes| -|price|Float|The price of the base asset|Yes| -|quantity|Float|The quantity of the base asset|Yes| -|is_buy|Boolean|Set to true or false for buy and sell orders respectively|Yes| -|is_po|Boolean|Set to true or false for post-only or normal orders respectively|No| +| Parameter | Type | Description | Required | +| ------------- | ------- | ------------------------------------------------------------------------------------ | -------- | +| market_id | String | Market ID of the market we want to send an order | Yes | +| subaccount_id | String | The subaccount we want to send an order from | Yes | +| fee_recipient | String | The address that will receive 40% of the fees, this could be set to your own address | Yes | +| price | Float | The price of the base asset | Yes | +| quantity | Float | The quantity of the base asset | Yes | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | No | +| is_buy | Boolean | Set to true or false for buy and sell orders respectively | Yes | +| is_po | Boolean | Set to true or false for post-only or normal orders respectively | No | + > Response Example: diff --git a/source/includes/_spotrpc.md b/source/includes/_spotrpc.md index a5a1354a..7889ebfe 100644 --- a/source/includes/_spotrpc.md +++ b/source/includes/_spotrpc.md @@ -80,9 +80,9 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|MarketId of the market we want to fetch|Yes| +| Parameter | Type | Description | Required | +| --------- | ------ | --------------------------------------- | -------- | +| market_id | String | MarketId of the market we want to fetch | Yes | ### Response Parameters @@ -169,37 +169,37 @@ market { } ``` -|Parameter|Type|Description| -|----|----|----| -|market|SpotMarketInfo|Info about particular spot market| +| Parameter | Type | Description | +| --------- | -------------- | --------------------------------- | +| market | SpotMarketInfo | Info about particular spot market | **SpotMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|base_denom|String|Coin denom of the base asset| -|market_id|String|ID of the spot market of interest| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|quote_token_meta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|base_token_meta|TokenMeta|Token metadata for base asset, only for Ethereum-based assets| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|quote_denom|String|Coin denom of the quote asset| -|taker_fee_rate|String|Defines the fee percentage takers pay (in the quote asset) when trading| -|ticker|String|A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset| +| Parameter | Type | Description | +| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------- | +| base_denom | String | Coin denom of the base asset | +| market_id | String | ID of the spot market of interest | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| quote_token_meta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| base_token_meta | TokenMeta | Token metadata for base asset, only for Ethereum-based assets | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| quote_denom | String | Coin denom of the quote asset | +| taker_fee_rate | String | Defines the fee percentage takers pay (in the quote asset) when trading | +| ticker | String | A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | ## Markets @@ -299,11 +299,11 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|base_denom|String|Filter by the Coin denomination of the base currency|No| -|market_status|String|Filter by status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])|No| -|quote_denom|String|Filter by the Coin denomination of the quote currency|No| +| Parameter | Type | Description | Required | +| ------------- | ------ | ------------------------------------------------------------------------------------------------------------- | -------- | +| base_denom | String | Filter by the Coin denomination of the base currency | No | +| market_status | String | Filter by status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | No | +| quote_denom | String | Filter by the Coin denomination of the quote currency | No | ### Response Parameters @@ -452,37 +452,37 @@ markets { ] ``` -|Parameter|Type|Description| -|----|----|----| -|markets|SpotMarketInfo Array|List of spot markets| +| Parameter | Type | Description | +| --------- | -------------------- | -------------------- | +| markets | SpotMarketInfo Array | List of spot markets | **SpotMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|base_denom|String|Coin denom of the base asset| -|market_id|String|ID of the spot market of interest| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|quote_token_meta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|base_token_meta|TokenMeta|Token metadata for base asset, only for Ethereum-based assets| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|quote_denom|String|Coin denom of the quote asset| -|taker_fee_rate|String|Defines the fee percentage takers pay (in the quote asset) when trading| -|ticker|String|A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset| +| Parameter | Type | Description | +| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------- | +| base_denom | String | Coin denom of the base asset | +| market_id | String | ID of the spot market of interest | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| quote_token_meta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| base_token_meta | TokenMeta | Token metadata for base asset, only for Ethereum-based assets | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| quote_denom | String | Coin denom of the quote asset | +| taker_fee_rate | String | Defines the fee percentage takers pay (in the quote asset) when trading | +| ticker | String | A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | @@ -592,9 +592,9 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for updates streaming, empty means 'ALL' spot markets|No| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------------------------ | -------- | +| market_ids | String Array | List of market IDs for updates streaming, empty means 'ALL' spot markets | No | ### Response Parameters > Streaming Response Example: @@ -703,39 +703,39 @@ market: { } ``` -|Parameter|Type|Description| -|----|----|----| -|market|SpotMarketInfo|Info about particular spot market| -|operation_type|String|Update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | -|timestamp|Integer|Operation timestamp in UNIX millis| +| Parameter | Type | Description | +| -------------- | -------------- | ----------------------------------------------------------------------------- | +| market | SpotMarketInfo | Info about particular spot market | +| operation_type | String | Update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | **SpotMarketInfo** -|Parameter|Type|Description| -|----|----|----| -|base_denom|String|Coin denom of the base asset| -|market_id|String|ID of the spot market of interest| -|market_status|String|The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"])| -|min_quantity_tick_size|String|Defines the minimum required tick size for the order's quantity| -|quote_token_meta|TokenMeta|Token metadata for quote asset, only for Ethereum-based assets| -|service_provider_fee|String|Percentage of the transaction fee shared with the service provider| -|base_token_meta|TokenMeta|Token metadata for base asset, only for Ethereum-based assets| -|maker_fee_rate|String|Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading| -|min_price_tick_size|String|Defines the minimum required tick size for the order's price| -|quote_denom|String|Coin denom of the quote asset| -|taker_fee_rate|String|Defines the fee percentage takers pay (in the quote asset) when trading| -|ticker|String|A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset| +| Parameter | Type | Description | +| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------- | +| base_denom | String | Coin denom of the base asset | +| market_id | String | ID of the spot market of interest | +| market_status | String | The status of the market (Should be one of: ["active", "paused", "suspended", "demolished", "expired"]) | +| min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity | +| quote_token_meta | TokenMeta | Token metadata for quote asset, only for Ethereum-based assets | +| service_provider_fee | String | Percentage of the transaction fee shared with the service provider | +| base_token_meta | TokenMeta | Token metadata for base asset, only for Ethereum-based assets | +| maker_fee_rate | String | Defines the fee percentage makers pay (or receive, if negative) in quote asset when trading | +| min_price_tick_size | String | Defines the minimum required tick size for the order's price | +| quote_denom | String | Coin denom of the quote asset | +| taker_fee_rate | String | Defines the fee percentage takers pay (in the quote asset) when trading | +| ticker | String | A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset | **TokenMeta** -|Parameter|Type|Description| -|----|----|----| -|address|String|Token's Ethereum contract address| -|decimals|Integer|Token decimals| -|logo|String|URL to the logo image| -|name|String|Token full name| -|symbol|String|Token symbol short name| -|updatedAt|Integer|Token metadata fetched timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| address | String | Token's Ethereum contract address | +| decimals | Integer | Token decimals | +| logo | String | URL to the logo image | +| name | String | Token full name | +| symbol | String | Token symbol short name | +| updatedAt | Integer | Token metadata fetched timestamp in UNIX millis | ## OrdersHistory @@ -827,19 +827,22 @@ func main() { ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|subaccount_id|String|Filter by subaccount ID|No| -|market_id|String|Filter by market ID|Yes| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| -|order_types|String Array|The order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])|No| -|direction|String|Filter by order direction (Should be one of: ["buy", "sell"])|No| -|start_time|Integer|Search for orders where createdAt >= startTime, time in milliseconds|No| -|end_time|Integer|Search for orders where createdAt <= startTime, time in milliseconds|No| -|state|String|The order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])|No| -|execution_types|String Array|The execution of the order (Should be one of: ["limit", "market"])|No| -|market_ids|Array of String|Filter by more than one market ID (replaces market_id parameter)|No| +| Parameter | Type | Description | Required | +| ------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| subaccount_id | String | Filter by subaccount ID | No | +| market_id | String | Filter by a single market ID | Yes | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all results since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | +| order_types | String Array | The order types to be included (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | No | +| direction | String | Filter by order direction (Should be one of: ["buy", "sell"]) | No | +| start_time | Integer | Search for orders where createdAt >= startTime, time in milliseconds | No | +| end_time | Integer | Search for orders where createdAt <= startTime, time in milliseconds | No | +| state | String | The order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | No | +| execution_types | String Array | The execution of the order (Should be one of: ["limit", "market"]) | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| trade_id | String | Filter by the trade's trade id | No | +| active_markets_only | Bool | Return only orders for active markets | No | +| cid | String | Filter by the custom client order id of the trade's order | No | ### Response Parameters @@ -1063,35 +1066,37 @@ paging { ``` -|Parameter|Type|Description| -|----|----|----| -|orders|SpotOrderHistory Array|List of prior spot orders| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | ---------------------- | ------------------------- | +| orders | SpotOrderHistory Array | List of prior spot orders | +| paging | Paging | Pagination of results | ***SpotOrderHistory*** -|Parameter|Type|Description| -|----|----|----| -|order_hash|String|Hash of the order| -|market_id|String|ID of the spot market| -|is_active|Boolean|Indicates if the order is active| -|subaccount_id|String|ID of the subaccount that the order belongs to| -|execution_type|String|The type of the order (Should be one of: ["limit", "market"]) | -|order_type|String|Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])| -|price|String|Price of the order| -|trigger_price|String|Trigger price used by stop/take orders| -|quantity|String|Quantity of the order| -|filled_quantity|String|The amount of the quantity filled| -|state|String|Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])| -|created_at|Integer|Order created timestamp in UNIX millis| -|updated_at|Integer|Order updated timestamp in UNIX millis| -|direction|String|The direction of the order (Should be one of: ["buy", "sell"])| +| Parameter | Type | Description | +| --------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | Hash of the order | +| market_id | String | ID of the spot market | +| is_active | Boolean | Indicates if the order is active | +| subaccount_id | String | ID of the subaccount that the order belongs to | +| execution_type | String | The type of the order (Should be one of: ["limit", "market"]) | +| order_type | String | Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | +| price | String | Price of the order | +| trigger_price | String | Trigger price used by stop/take orders | +| quantity | String | Quantity of the order | +| filled_quantity | String | The amount of the quantity filled | +| state | String | Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | +| created_at | Integer | Order created timestamp in UNIX millis | +| updated_at | Integer | Order updated timestamp in UNIX millis | +| direction | String | The direction of the order (Should be one of: ["buy", "sell"]) | +| tx_hash | String | Transaction hash in which the order was created (not all orders have this value) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of available records| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of available records | ## StreamOrdersHistory @@ -1217,14 +1222,14 @@ console.log(orderHistory) })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by market ID|Yes| -|subaccount_id|String|Filter by subaccount ID|No| -|direction|String|Filter by direction (Should be one of: ["buy", "sell"])|No| -|state|String|Filter by state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])|No| -|order_types|String Array|Filter by order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])|No| -|execution_types|String Array|Filter by execution type (Should be one of: ["limit", "market"])|No| +| Parameter | Type | Description | Required | +| --------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | -------- | +| market_id | String | Filter by market ID | Yes | +| subaccount_id | String | Filter by subaccount ID | No | +| direction | String | Filter by direction (Should be one of: ["buy", "sell"]) | No | +| state | String | Filter by state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | No | +| order_types | String Array | Filter by order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | No | +| execution_types | String Array | Filter by execution type (Should be one of: ["limit", "market"]) | No | ### Response Parameters @@ -1295,30 +1300,32 @@ timestamp: 1665486462000 ``` -|Parameter|Type|Description| -|----|----|----| -|order|SpotOrderHistory|Updated Order| -|operation_type|String|Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | -|timestamp|Integer|Operation timestamp in UNIX millis| +| Parameter | Type | Description | +| -------------- | ---------------- | ----------------------------------------------------------------------------------- | +| order | SpotOrderHistory | Updated Order | +| operation_type | String | Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | **SpotOrderHistory** -|Parameter|Type|Description| -|----|----|----| -|order_hash|String|Hash of the order| -|market_id|String|ID of the spot market| -|is_active|Boolean|Indicates if the order is active| -|subaccount_id|String|ID of the subaccount that the order belongs to| -|execution_type|String|The type of the order (Should be one of: ["limit", "market"]) | -|order_type|String|Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"])| -|price|String|Price of the order| -|trigger_price|String|Trigger price used by stop/take orders| -|quantity|String|Quantity of the order| -|filled_quantity|String|The amount of the quantity filled| -|state|String|Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"])| -|created_at|Integer|Order created timestamp in UNIX millis| -|updated_at|Integer|Order updated timestamp in UNIX millis| -|direction|String|The direction of the order (Should be one of: ["buy", "sell"])| +| Parameter | Type | Description | +| --------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | Hash of the order | +| market_id | String | ID of the spot market | +| is_active | Boolean | Indicates if the order is active | +| subaccount_id | String | ID of the subaccount that the order belongs to | +| execution_type | String | The type of the order (Should be one of: ["limit", "market"]) | +| order_type | String | Order type (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell", "buy_po", "sell_po"]) | +| price | String | Price of the order | +| trigger_price | String | Trigger price used by stop/take orders | +| quantity | String | Quantity of the order | +| filled_quantity | String | The amount of the quantity filled | +| state | String | Order state (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | +| created_at | Integer | Order created timestamp in UNIX millis | +| updated_at | Integer | Order updated timestamp in UNIX millis | +| direction | String | The direction of the order (Should be one of: ["buy", "sell"]) | +| tx_hash | String | Transaction hash in which the order was created (not all orders have this value) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | ## Trades @@ -1440,19 +1447,22 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by a single market ID|No| -|market_ids|String Array|Filter by multiple market IDs|No| -|subaccount_id|String|Filter by a single subaccount ID|No| -|subaccount_ids|String Array|Filter by multiple subaccount IDs|No| -|direction|String|Filter by the direction of the trade (Should be one of: ["buy", "sell"])|No| -|execution_side|String|Filter by the execution side of the trade (Should be one of: ["maker", "taker"])|No| -|execution_types|String Array|Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"])|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| -|start_time|Integer|startTime <= trade execution timestamp <= endTime|No| -|end_time|Integer|startTime <= trade execution timestamp <= endTime|No| +| Parameter | Type | Description | Required | +| --------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | -------- | +| market_id | String | Filter by a single market ID | No | +| execution_side | String | Filter by the execution side of the trade (Should be one of: ["maker", "taker"]) | No | +| direction | String | Filter by the direction of the trade (Should be one of: ["buy", "sell"]) | No | +| subaccount_id | String | Filter by a single subaccount ID | No | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | +| start_time | Integer | startTime <= trade execution timestamp <= endTime | No | +| end_time | Integer | startTime <= trade execution timestamp <= endTime | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| subaccount_ids | String Array | Filter by multiple subaccount IDs | No | +| execution_types | String Array | Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | No | +| trade_id | String | Filter by the trade id of the trade | No | +| account_address | String | Filter by the account address | No | +| cid | String | Filter by the custom client order id of the trade's order | No | ### Response Parameters @@ -1589,41 +1599,42 @@ paging { ] ``` -|Parameter|Type|Description| -|----|----|----| -|trades|SpotTrade Array|Trades of a particular spot market| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------- | +| trades | SpotTrade Array | Trades of a particular spot market | +| paging | Paging | Pagination of results | **SpotTrade** -|Parameter|Type| Description | -|----|----|-------------------------------------------------------------------------------------------------------------------------| -|trade_direction|String| Direction of the trade(Should be one of: ["buy", "sell"]) | -|trade_execution_type|String| Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | -|fee|String| The fee associated with the trade (quote asset denom) | -|market_id|String| The ID of the market that this trade is in | -|order_hash|String| The order hash | -|price|PriceLevel| Price level at which trade has been executed | -|subaccount_id|String| The subaccountId that executed the trade | -|executed_at|Integer| Timestamp of trade execution (on chain) in UNIX millis | -|fee_recipient|String| The address that received 40% of the fees | -|trade_id|String| Unique identifier to differentiate between trades | -|execution_side|String| Execution side of trade (Should be one of: ["maker", "taker"]) +| Parameter | Type | Description | +| -------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | The order hash | +| subaccount_id | String | The subaccountId that executed the trade | +| market_id | String | The ID of the market that this trade is in | +| trade_execution_type | String | Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | +| trade_direction | String | Direction of the trade(Should be one of: ["buy", "sell"]) | +| price | PriceLevel | Price level at which trade has been executed | +| fee | String | The fee associated with the trade (quote asset denom) | +| executed_at | Integer | Timestamp of trade execution (on chain) in UNIX millis | +| fee_recipient | String | The address that received 40% of the fees | +| trade_id | String | Unique identifier to differentiate between trades | +| execution_side | String | Execution side of trade (Should be one of: ["maker", "taker"]) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of records available| +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| total | Integer | Total number of records available | ## StreamTrades @@ -1769,15 +1780,22 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Filter by a single market ID|No| -|market_ids|String Array|Filter by multiple market IDs|No| -|subaccount_id|String|Filter by a single subaccount ID|No| -|subaccount_ids|String Array|Filter by multiple subaccount IDs|No| -|direction|String|Filter by the direction of the trade (Should be one of: ["buy", "sell"])|No| -|execution_side|String|Filter by the execution side of the trade (Should be one of: ["maker", "taker"])|No| -|execution_types|String Array|Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"])|No| +| Parameter | Type | Description | Required | +| --------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | -------- | +| market_id | String | Filter by a single market ID | No | +| execution_side | String | Filter by the execution side of the trade (Should be one of: ["maker", "taker"]) | No | +| direction | String | Filter by the direction of the trade (Should be one of: ["buy", "sell"]) | No | +| subaccount_id | String | Filter by a single subaccount ID | No | +| skip | Integer | Skip will skip the first N items from the result | No | +| limit | Integer | Maximum number of items to be returned | No | +| start_time | Integer | Start timestamp (UNIX milliseconds) from when to filter trades | No | +| end_time | Integer | End timestamp (UNIX milliseconds) to filter trades | No | +| market_ids | String Array | Filter by multiple market IDs | No | +| subaccount_ids | String Array | Filter by multiple subaccount IDs | No | +| execution_types | String Array | Filter by the *trade execution type (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | No | +| trade_id | String | Filter by the trade's trade id | No | +| account_address | String | Filter by the account address | No | +| cid | String | Filter by the custom client order id of the trade's order | No | ### Response Parameters > Streaming Response Example: @@ -1905,35 +1923,37 @@ timestamp: 1676015260000 } ``` -|Parameter|Type| Description | -|----|----|---------------------------------------------------------------------| -|trade|SpotTrade| New spot market trade | -|operation_type|String| Trade operation type (Should be one of: ["insert", "invalidate"]) | -|timestamp|Integer| Timestamp the new trade is written into the database in UNIX millis | +| Parameter | Type | Description | +| -------------- | --------- | ------------------------------------------------------------------- | +| trade | SpotTrade | New spot market trade | +| operation_type | String | Trade operation type (Should be one of: ["insert", "invalidate"]) | +| timestamp | Integer | Timestamp the new trade is written into the database in UNIX millis | **SpotTrade** -|Parameter|Type| Description | -|----|----|-------------------------------------------------------------------------------------------------------------------------| -|trade_direction|String| Direction of the trade(Should be one of: ["buy", "sell"]) | -|trade_execution_type|String| Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | -|fee|String| The fee associated with the trade (quote asset denom) | -|market_id|String| The ID of the market that this trade is in | -|order_hash|String| The order hash | -|price|PriceLevel| Price level at which trade has been executed | -|subaccount_id|String| The subaccountId that executed the trade | -|executed_at|Integer| Timestamp of trade execution (on chain) in UNIX millis | -|fee_recipient|String| The address that received 40% of the fees | -|trade_id|String| Unique identifier to differentiate between trades | -|execution_side|String| Execution side of trade (Should be one of: ["maker", "taker"]) +| Parameter | Type | Description | +| -------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | The order hash | +| subaccount_id | String | The subaccountId that executed the trade | +| market_id | String | The ID of the market that this trade is in | +| trade_execution_type | String | Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | +| trade_direction | String | Direction of the trade(Should be one of: ["buy", "sell"]) | +| price | PriceLevel | Price level at which trade has been executed | +| fee | String | The fee associated with the trade (quote asset denom) | +| executed_at | Integer | Timestamp of trade execution (on chain) in UNIX millis | +| fee_recipient | String | The address that received 40% of the fees | +| trade_id | String | Unique identifier to differentiate between trades | +| execution_side | String | Execution side of trade (Should be one of: ["maker", "taker"]) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | + **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## \[DEPRECATED\] Orderbook @@ -2019,9 +2039,9 @@ import { protoObjectToJson, ExchangeClient } from "@injectivelabs/sdk-ts"; ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_id|String|Market ID of the spot market to get orderbook from|Yes| +| Parameter | Type | Description | Required | +| --------- | ------ | -------------------------------------------------- | -------- | +| market_id | String | Market ID of the spot market to get orderbook from | Yes | ### Response Parameters @@ -2144,24 +2164,24 @@ orderbook { } ``` -|Parameter|Type|Description| -|----|----|----| -|orderbook|SpotLimitOrderbook|Orderbook of a particular spot market| +| Parameter | Type | Description | +| --------- | ------------------ | ------------------------------------- | +| orderbook | SpotLimitOrderbook | Orderbook of a particular spot market | **SpotLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------ | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## \[DEPRECATED\] Orderbooks @@ -2249,9 +2269,9 @@ import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/E })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|Filter by one or more market IDs|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | -------------------------------- | -------- | +| market_ids | String Array | Filter by one or more market IDs | Yes | ### Response Parameters @@ -2444,32 +2464,32 @@ orderbooks { -|Parameter|Type|Description| -|----|----|----| -|orderbooks|SingleSpotLimitOrderbook Array|List of spot market orderbooks with market IDs| +| Parameter | Type | Description | +| ---------- | ------------------------------ | ---------------------------------------------- | +| orderbooks | SingleSpotLimitOrderbook Array | List of spot market orderbooks with market IDs | **SingleSpotLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|ID of spot market| -|orderbook|SpotLimitOrderBook|Orderbook of the market| +| Parameter | Type | Description | +| --------- | ------------------ | ----------------------- | +| market_id | String | ID of spot market | +| orderbook | SpotLimitOrderBook | Orderbook of the market | **SpotLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------ | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## \[DEPRECATED\] StreamOrderbooks @@ -2579,9 +2599,9 @@ import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exch })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for orderbook streaming; empty means all spot markets|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------------------------ | -------- | +| market_ids | String Array | List of market IDs for orderbook streaming; empty means all spot markets | Yes | @@ -2739,27 +2759,27 @@ market_id: "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" } ``` -|Parameter|Type|Description| -|----|----|----| -|orderbook|SpotLimitOrderbook|Orderbook of a Spot Market| -|operation_type|String|Order update type (Should be one of: ["insert", "replace", "update", "invalidate"])| -|timestamp|Integer|Operation timestamp in UNIX millis| -|market_id|String|ID of the market the orderbook belongs to| +| Parameter | Type | Description | +| -------------- | ------------------ | ----------------------------------------------------------------------------------- | +| orderbook | SpotLimitOrderbook | Orderbook of a Spot Market | +| operation_type | String | Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | +| market_id | String | ID of the market the orderbook belongs to | **SpotLimitOrderbook** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------ | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## OrderbooksV2 @@ -2817,9 +2837,9 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of IDs of markets to get orderbook snapshots from|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------ | -------- | +| market_ids | String Array | List of IDs of markets to get orderbook snapshots from | Yes | ### Response Parameters @@ -3267,33 +3287,33 @@ orderbooks { -|Parameter|Type|Description| -|----|----|----| -|orderbooks|SingleSpotLimitOrderbookV2 Array|List of spot market orderbooks with market IDs| +| Parameter | Type | Description | +| ---------- | -------------------------------- | ---------------------------------------------- | +| orderbooks | SingleSpotLimitOrderbookV2 Array | List of spot market orderbooks with market IDs | **SingleSpotLimitOrderbookV2** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|ID of spot market| -|orderbook|SpotLimitOrderBookV2|Orderbook of the market| +| Parameter | Type | Description | +| --------- | -------------------- | ----------------------- | +| market_id | String | ID of spot market | +| orderbook | SpotLimitOrderBookV2 | Orderbook of the market | **SpotLimitOrderbookV2** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| -|sequence|Integer|Sequence number of the orderbook; increments by 1 each update| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------------------------------------- | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | +| sequence | Integer | Sequence number of the orderbook; increments by 1 each update | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## StreamOrderbooksV2 @@ -3366,9 +3386,9 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for orderbook streaming; empty means all spot markets|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------------------------ | -------- | +| market_ids | String Array | List of market IDs for orderbook streaming; empty means all spot markets | Yes | ### Response Parameters @@ -3443,28 +3463,28 @@ market_id: "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe" } ``` -|Parameter|Type|Description| -|----|----|----| -|orderbook|SpotLimitOrderbookV2|Orderbook of a Spot Market| -|operation_type|String|Order update type (Should be one of: ["insert", "replace", "update", "invalidate"])| -|timestamp|Integer|Operation timestamp in UNIX millis| -|market_id|String|ID of the market the orderbook belongs to| +| Parameter | Type | Description | +| -------------- | -------------------- | ----------------------------------------------------------------------------------- | +| orderbook | SpotLimitOrderbookV2 | Orderbook of a Spot Market | +| operation_type | String | Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | +| market_id | String | ID of the market the orderbook belongs to | **SpotLimitOrderbookV2** -|Parameter|Type|Description| -|----|----|----| -|buys|PriceLevel Array|List of price levels for buys| -|sells|PriceLevel Array|List of price levels for sells| -|sequence|Integer|Sequence number of the orderbook; increments by 1 each update| +| Parameter | Type | Description | +| --------- | ---------------- | ------------------------------------------------------------- | +| buys | PriceLevel Array | List of price levels for buys | +| sells | PriceLevel Array | List of price levels for sells | +| sequence | Integer | Sequence number of the orderbook; increments by 1 each update | **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## StreamOrderbookUpdate @@ -3643,9 +3663,9 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|market_ids|String Array|List of market IDs for orderbook streaming; empty means all spot markets|Yes| +| Parameter | Type | Description | Required | +| ---------- | ------------ | ------------------------------------------------------------------------ | -------- | +| market_ids | String Array | List of market IDs for orderbook streaming; empty means all spot markets | Yes | ### Response Parameters @@ -3707,31 +3727,31 @@ price: 1E-15 | quantity: 17983000000000000000 | timestamp: 1675880932648 } ``` -|Parameter|Type|Description| -|----|----|----| -|orderbook_level_updates|OrderbookLevelUpdates|Orderbook level updates of a spot market| -|operation_type|String|Order update type (Should be one of: ["insert", "replace", "update", "invalidate"])| -|timestamp|Integer|Operation timestamp in UNIX millis| -|market_id|String|ID of the market the orderbook belongs to| +| Parameter | Type | Description | +| ----------------------- | --------------------- | ----------------------------------------------------------------------------------- | +| orderbook_level_updates | OrderbookLevelUpdates | Orderbook level updates of a spot market | +| operation_type | String | Order update type (Should be one of: ["insert", "replace", "update", "invalidate"]) | +| timestamp | Integer | Operation timestamp in UNIX millis | +| market_id | String | ID of the market the orderbook belongs to | **OrderbookLevelUpdates** -|Parameter|Type|Description| -|----|----|----| -|market_id|String|ID of the market the orderbook belongs to| -|sequence|Integer|Orderbook update sequence number; increments by 1 each update| -|buys|PriceLevelUpdate Array|List of buy level updates| -|sells|PriceLevelUpdate Array|List of sell level updates| -|updated_at|Integer|Timestamp of the updates in UNIX millis| +| Parameter | Type | Description | +| ---------- | ---------------------- | ------------------------------------------------------------- | +| market_id | String | ID of the market the orderbook belongs to | +| sequence | Integer | Orderbook update sequence number; increments by 1 each update | +| buys | PriceLevelUpdate Array | List of buy level updates | +| sells | PriceLevelUpdate Array | List of sell level updates | +| updated_at | Integer | Timestamp of the updates in UNIX millis | **PriceLevelUpdate** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|is_active|Boolean|Price level status| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| is_active | Boolean | Price level status | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | ## SubaccountOrdersList @@ -3840,12 +3860,12 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|subaccount_id|String|Filter by subaccount ID|Yes| -|market_id|String|Filter by market ID|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| +| Parameter | Type | Description | Required | +| ------------- | ------- | --------------------------------------------------------------------------------------------------------- | -------- | +| subaccount_id | String | Filter by subaccount ID | Yes | +| market_id | String | Filter by market ID | No | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | ### Response Parameters @@ -4011,37 +4031,39 @@ paging { ] ``` -|Parameter|Type|Description| -|----|----|----| -|orders|SpotLimitOrder Array|List of spot market orders| -|paging|Paging|Pagination of results| +| Parameter | Type | Description | +| --------- | -------------------- | -------------------------- | +| orders | SpotLimitOrder Array | List of spot market orders | +| paging | Paging | Pagination of results | **SpotLimitOrder** -|Parameter|Type|Description| -|----|----|----| -|state|String|State of the order (Should be one of: ["booked", "partial_filled", "filled", "canceled"])| -|subaccount_id|String|The subaccount ID the order belongs to| -|unfilled_quantity|String|The amount of the quantity remaining unfilled| -|market_id|String|ID of the market the order belongs to| -|order_hash|String|Hash of the order| -|order_side|String|The side of the order (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell"])| -|fee_recipient|String|The address that receives fees if the order is executed| -|price|String|The price of the order| -|quantity|String|The quantity of the order| -|trigger_price|String|The price that triggers stop and take orders. If no price is set, the default is 0| -|created_at|Integer|Order committed timestamp in UNIX millis| -|updated_at|Integer|Order updated timestamp in UNIX millis| +| Parameter | Type | Description | +| ----------------- | ------- | ----------------------------------------------------------------------------------------------------------- | +| order_hash | String | Hash of the order | +| order_side | String | The side of the order (Should be one of: ["buy", "sell", "stop_buy", "stop_sell", "take_buy", "take_sell"]) | +| market_id | String | ID of the market the order belongs to | +| subaccount_id | String | The subaccount ID the order belongs to | +| price | String | The price of the order | +| quantity | String | The quantity of the order | +| unfilled_quantity | String | The amount of the quantity remaining unfilled | +| trigger_price | String | The price that triggers stop and take orders. If no price is set, the default is 0 | +| fee_recipient | String | The address that receives fees if the order is executed | +| state | String | State of the order (Should be one of: ["booked", "partial_filled", "filled", "canceled"]) | +| created_at | Integer | Order committed timestamp in UNIX millis | +| updated_at | Integer | Order updated timestamp in UNIX millis | +| tx_hash | String | Transaction hash in which the order was created (not all orders have this value) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | **Paging** -|Parameter|Type|Description| -|----|----|----| -|total|Integer|Total number of available records| -|from|Integer|Lower bound of indices of records returned| -|to|integer|Upper bound of indices of records returned| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------ | +| total | Integer | Total number of available records | +| from | Integer | Lower bound of indices of records returned | +| to | integer | Upper bound of indices of records returned | ## SubaccountTradesList @@ -4171,14 +4193,14 @@ import { getNetworkEndpoints, Network } from "@injectivelabs/networks"; })(); ``` -|Parameter|Type|Description|Required| -|----|----|----|----| -|subaccount_id|String|Filter by subaccount ID|Yes| -|market_id|String|Filter by market ID|No| -|direction|String|Filter by the direction of the trades (Should be one of: ["buy", "sell"])|No| -|execution_type|String|Filter by the *execution type of the trades (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"])|No| -|skip|Integer|Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100|No| -|limit|Integer|Maximum number of items to be returned. 1 <= *n* <= 100|No| +| Parameter | Type | Description | Required | +| -------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| subaccount_id | String | Filter by subaccount ID | Yes | +| market_id | String | Filter by market ID | No | +| direction | String | Filter by the direction of the trades (Should be one of: ["buy", "sell"]) | No | +| execution_type | String | Filter by the *execution type of the trades (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | No | +| skip | Integer | Skip the first *n* items from the results. This can be used to fetch all trades since the API caps at 100 | No | +| limit | Integer | Maximum number of items to be returned. 1 <= *n* <= 100 | No | ### Response Parameters > Response Example: @@ -4325,30 +4347,32 @@ trades { ] ``` -|Parameter|Type|Description| -|----|----|----| -|trades|SpotTrade Array|List of spot market trades| +| Parameter | Type | Description | +| --------- | --------------- | -------------------------- | +| trades | SpotTrade Array | List of spot market trades | **SpotTrade** -|Parameter|Type| Description | -|----|----|-----------------------------------------------------------------------------------------------------------------------------| -|trade_direction|String| The direction the trade (Should be one of: ["buy", "sell"]) | -|trade_execution_type|String| The execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | -|fee|String| The fee associated with the trade (quote asset denom) | -|market_id|String| The ID of the market that this trade is in | -|order_hash|String| The order hash | -|price|PriceLevel| Price level at which trade has been executed | -|subaccount_id|String| Filter by the subaccount ID | -|executed_at|Integer| Timestamp of trade execution (on chain) in UNIX millis | -|fee_recipient|String| Address that received fees from the order | -|trade_id|String| A unique string that helps differentiate between trades | -|execution_side|String| Trade's execution side (Should be one of: ["maker", "taker"]) | +| Parameter | Type | Description | +| -------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------- | +| order_hash | String | The order hash | +| subaccount_id | String | The subaccountId that executed the trade | +| market_id | String | The ID of the market that this trade is in | +| trade_execution_type | String | Execution type of the trade (Should be one of: ["market", "limitFill", "limitMatchRestingOrder", "limitMatchNewOrder"]) | +| trade_direction | String | Direction of the trade(Should be one of: ["buy", "sell"]) | +| price | PriceLevel | Price level at which trade has been executed | +| fee | String | The fee associated with the trade (quote asset denom) | +| executed_at | Integer | Timestamp of trade execution (on chain) in UNIX millis | +| fee_recipient | String | The address that received 40% of the fees | +| trade_id | String | Unique identifier to differentiate between trades | +| execution_side | String | Execution side of trade (Should be one of: ["maker", "taker"]) | +| cid | String | Identifier for the order specified by the user (up to 36 characters, like a UUID) | + **PriceLevel** -|Parameter|Type|Description| -|----|----|----| -|price|String|Price number of the price level| -|quantity|String|Quantity of the price level| -|timestamp|Integer|Price level last updated timestamp in UNIX millis| +| Parameter | Type | Description | +| --------- | ------- | ------------------------------------------------- | +| price | String | Price number of the price level | +| quantity | String | Quantity of the price level | +| timestamp | Integer | Price level last updated timestamp in UNIX millis | diff --git a/source/includes/_staking.md b/source/includes/_staking.md index fc8b6e50..639f7d8a 100644 --- a/source/includes/_staking.md +++ b/source/includes/_staking.md @@ -11,36 +11,34 @@ Includes the messages to claim and withdraw delegator rewards ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare tx msg validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" msg = composer.MsgWithdrawDelegatorReward( - delegator_address=address.to_acc_bech32(), - validator_address=validator_address + delegator_address=address.to_acc_bech32(), validator_address=validator_address ) # build sim tx @@ -62,14 +60,16 @@ async def main() -> None: 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) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -80,9 +80,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go @@ -209,37 +210,35 @@ gas fee: 0.000097523 INJ ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey + async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare tx msg validator_address = "injvaloper1ultw9r29l8nxy5u6thcgusjn95vsy2caw722q5" amount = 100 msg = composer.MsgDelegate( - delegator_address=address.to_acc_bech32(), - validator_address=validator_address, - amount=amount + delegator_address=address.to_acc_bech32(), validator_address=validator_address, amount=amount ) # build sim tx @@ -261,14 +260,16 @@ async def main() -> None: 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) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -279,9 +280,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` ``` go diff --git a/source/includes/_wasm.md b/source/includes/_wasm.md index eabfbbc9..8c033641 100644 --- a/source/includes/_wasm.md +++ b/source/includes/_wasm.md @@ -13,42 +13,45 @@ CosmWasm smart contract interactions. ``` python import asyncio -import logging -from pyinjective.composer import Composer as ProtoMsgComposer from pyinjective.async_client import AsyncClient -from pyinjective.transaction import Transaction +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.core.network import Network +from pyinjective.transaction import Transaction from pyinjective.wallet import PrivateKey async def main() -> None: # select network: local, testnet, mainnet network = Network.testnet() - composer = ProtoMsgComposer(network=network.string()) # initialize grpc client + # set custom cookie location (optional) - defaults to current dir client = AsyncClient(network) + composer = await client.composer() await client.sync_timeout_height() # load account priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3") pub_key = priv_key.to_public_key() address = pub_key.to_address() - account = await client.get_account(address.to_acc_bech32()) + await client.get_account(address.to_acc_bech32()) # prepare tx msg # NOTE: COIN MUST BE SORTED IN ALPHABETICAL ORDER BY DENOMS funds = [ - composer.Coin(amount=69, denom='factory/inj1hdvy6tl89llqy3ze8lv6mz5qh66sx9enn0jxg6/inj12ngevx045zpvacus9s6anr258gkwpmthnz80e9'), - composer.Coin(amount=420, denom='peggy0x44C21afAaF20c270EBbF5914Cfc3b5022173FEB7'), - composer.Coin(amount=1, denom='peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5'), + composer.Coin( + amount=69, + denom="factory/inj1hdvy6tl89llqy3ze8lv6mz5qh66sx9enn0jxg6/inj12ngevx045zpvacus9s6anr258gkwpmthnz80e9", + ), + composer.Coin(amount=420, denom="peggy0x44C21afAaF20c270EBbF5914Cfc3b5022173FEB7"), + composer.Coin(amount=1, denom="peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5"), ] msg = composer.MsgExecuteContract( sender=address.to_acc_bech32(), contract="inj1ady3s7whq30l4fx8sj3x6muv5mx4dfdlcpv8n7", msg='{"increment":{}}', - funds=funds + funds=funds, ) # build sim tx @@ -70,14 +73,16 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 25000 # add 25k for gas, fee computation - gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0') - fee = [composer.Coin( - amount=gas_price * gas_limit, - denom=network.fee_denom, - )] - tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height) + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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) sign_doc = tx.get_sign_doc(pub_key) sig = priv_key.sign(sign_doc.SerializeToString()) tx_raw_bytes = tx.get_tx_data(sig, pub_key) @@ -88,9 +93,10 @@ async def main() -> None: print("gas wanted: {}".format(gas_limit)) print("gas fee: {} INJ".format(gas_fee)) + if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main()) + ``` @@ -134,6 +140,7 @@ import json import logging from pyinjective.composer import Composer as ProtoMsgComposer +from pyinjective.constant import GAS_FEE_BUFFER_AMOUNT, GAS_PRICE from pyinjective.async_client import AsyncClient from pyinjective.transaction import Transaction from pyinjective.core.network import Network @@ -190,8 +197,8 @@ async def main() -> None: return # build tx - gas_price = 500000000 - gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation + gas_price = GAS_PRICE + gas_limit = sim_res.gas_info.gas_used + GAS_FEE_BUFFER_AMOUNT # add buffer 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, diff --git a/source/index.html.md b/source/index.html.md index de86c843..fe73c399 100644 --- a/source/index.html.md +++ b/source/index.html.md @@ -42,6 +42,7 @@ includes: - insurance - historicalqueries - healthapi + - chainstream - glossary - faq # - exchangerpc