|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import os |
| 4 | + |
| 5 | +import dotenv |
| 6 | + |
| 7 | +from pyinjective.async_client_v2 import AsyncClient |
| 8 | +from pyinjective.core.broadcaster import MsgBroadcasterWithPk |
| 9 | +from pyinjective.core.network import Network |
| 10 | +from pyinjective.wallet import PrivateKey |
| 11 | + |
| 12 | + |
| 13 | +async def main() -> None: |
| 14 | + dotenv.load_dotenv() |
| 15 | + configured_private_key = os.getenv("INJECTIVE_PRIVATE_KEY") |
| 16 | + |
| 17 | + # select network: local, testnet, mainnet |
| 18 | + network = Network.testnet() |
| 19 | + |
| 20 | + # initialize grpc client |
| 21 | + client = AsyncClient(network) |
| 22 | + await client.initialize_tokens_from_chain_denoms() |
| 23 | + composer = await client.composer() |
| 24 | + |
| 25 | + gas_price = await client.current_chain_gas_price() |
| 26 | + # adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted |
| 27 | + gas_price = int(gas_price * 1.1) |
| 28 | + |
| 29 | + message_broadcaster = MsgBroadcasterWithPk.new_using_simulation( |
| 30 | + network=network, |
| 31 | + private_key=configured_private_key, |
| 32 | + gas_price=gas_price, |
| 33 | + client=client, |
| 34 | + composer=composer, |
| 35 | + ) |
| 36 | + |
| 37 | + # load account |
| 38 | + priv_key = PrivateKey.from_hex(configured_private_key) |
| 39 | + pub_key = priv_key.to_public_key() |
| 40 | + address = pub_key.to_address() |
| 41 | + await client.fetch_account(address.to_acc_bech32()) |
| 42 | + |
| 43 | + offsetting_subaccount_ids = { |
| 44 | + "0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000000", |
| 45 | + "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", |
| 46 | + } |
| 47 | + |
| 48 | + # prepare tx msg |
| 49 | + message = composer.msg_offset_position( |
| 50 | + sender=address.to_acc_bech32(), |
| 51 | + subaccount_id=address.get_subaccount_id(index=0), |
| 52 | + market_id="0x17ef48032cb24375ba7c2e39f384e56433bcab20cbee9a7357e4cba2eb00abe6", |
| 53 | + offsetting_subaccount_ids=offsetting_subaccount_ids, |
| 54 | + ) |
| 55 | + |
| 56 | + # broadcast the transaction |
| 57 | + result = await message_broadcaster.broadcast([message]) |
| 58 | + print("---Transaction Response---") |
| 59 | + print(json.dumps(result, indent=2)) |
| 60 | + |
| 61 | + gas_price = await client.current_chain_gas_price() |
| 62 | + # adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted |
| 63 | + gas_price = int(gas_price * 1.1) |
| 64 | + message_broadcaster.update_gas_price(gas_price=gas_price) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + asyncio.get_event_loop().run_until_complete(main()) |
0 commit comments