Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactored to use new sdk wrapper and cleanup
Browse files Browse the repository at this point in the history
john-connor84 committed Jul 8, 2022

Verified

This commit was signed with the committer’s verified signature.
ronnnnn Seiya Kokushi
1 parent 2675ed6 commit 6155c94
Showing 35 changed files with 660 additions and 703 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -26,7 +26,7 @@ pip install nibiru-py
### Usage
Requires Python 3.7+

[Examples](https://github.com/NibiruLabs/sdk-python/tree/master/examples)
[Examples](https://github.com/NibiruChain/sdk-python/tree/master/examples)
```bash
$ pipenv shell
$ pipenv install
4 changes: 2 additions & 2 deletions compatibility-tests/README.md
Original file line number Diff line number Diff line change
@@ -8,15 +8,15 @@ The aim of this repo was to test all python versions from 3.7.0 to 3.9.6 for com

A) Downloads all python versions and extracts the contents
B) Opens a subshell and installs python
C) Installs all the dependencies used by the Injective Exchange API and Chain Client
C) Installs all the dependencies used by the Nibiru Exchange API and Chain Client
D) Saves the python version and the stdout/stderr of the tests.py script to the results.txt file to have both successful and error output.
E) Purges python and all its dependencies, repeats until the last version.

- NOTE: DO NOT USE THIS SCRIPT IN YOUR OWN MACHINE, USE IT ONLY IN A TEST ENVIRONMENT AS THE SCRIPT WILL UNINSTALL ALL THE DEPENDENCIES THAT COME WITH PYTHON.

2. tests.py

This python script imports all the libraries used by the Injective Exchange API and Chain Client. It makes a gRPC request and uses the data to broadcast a transaction to the chain with both cosmos-sdk and exchange messages using a REST API endpoint. Certain libraries are imported from injective-py which you can find [here](https://pypi.org/project/injective-py/).
This python script imports all the libraries used by the Nibiru Exchange API and Chain Client. It makes a gRPC request and uses the data to broadcast a transaction to the chain with both cosmos-sdk and exchange messages using a REST API endpoint. Certain libraries are imported from nibiru-py which you can find [here](https://pypi.org/project/injective-py/).

3. results.txt

2 changes: 1 addition & 1 deletion compatibility-tests/run.sh
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@ install_libraries() {
python3 -m pip install grpcio
python3 -m pip install typing
python3 -m pip install protobuf
python3 -m pip install injective-py
python3 -m pip install nibiru-py
}

wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz
24 changes: 12 additions & 12 deletions compatibility-tests/tests.py
Original file line number Diff line number Diff line change
@@ -10,17 +10,17 @@
import grpc

from typing import Any, Dict, List
from injective.chain_client._wallet import (
from nibiru.chain_client._wallet import (
generate_wallet,
privkey_to_address,
privkey_to_pubkey,
pubkey_to_address,
seed_to_privkey,
DEFAULT_BECH32_HRP,
)
from injective.chain_client._typings import SyncMode
import injective.exchange_api.injective_accounts_rpc_pb2 as accounts_rpc_pb
import injective.exchange_api.injective_accounts_rpc_pb2_grpc as accounts_rpc_grpc
from nibiru.chain_client._typings import SyncMode
import nibiru.exchange_api.nibiru_accounts_rpc_pb2 as accounts_rpc_pb
import nibiru.exchange_api.nibiru_accounts_rpc_pb2_grpc as accounts_rpc_grpc


MIN_GAS_PRICE = 500000000
@@ -35,9 +35,9 @@ def __init__(
sequence: int,
fee: int,
gas: int,
fee_denom: str = "inj",
fee_denom: str = "unibi",
memo: str = "",
chain_id: str = "injective-888",
chain_id: str = "nibiru-888",
hrp: str = DEFAULT_BECH32_HRP,
sync_mode: SyncMode = "block",
) -> None:
@@ -66,7 +66,7 @@ def add_cosmos_bank_msg_send(self, recipient: str, amount: int, denom: str = "in
}
self._msgs.append(msg)

# Injective • Exchange Module
# Nibiru Exchange Module

def add_exchange_msg_deposit(self, subaccount: str, amount: int, denom: str = "inj") -> None:
msg = {
@@ -93,7 +93,7 @@ def get_signed(self) -> str:
"signatures": [
{
"signature": self._sign(),
"pub_key": {"type": "injective/PubKeyEthSecp256k1", "value": base64_pubkey},
"pub_key": {"type": "nibiru/PubKeyEthSecp256k1", "value": base64_pubkey},
"account_number": str(self._account_num),
"sequence": str(self._sequence),
}
@@ -139,8 +139,8 @@ async def main() -> None:

acc_num, acc_seq = await get_account_num_seq(sender_acc_addr)

async with grpc.aio.insecure_channel('testnet-sentry0.injective.network:9910') as channel:
accounts_rpc = accounts_rpc_grpc.InjectiveAccountsRPCStub(channel)
async with grpc.aio.insecure_channel('testnet-sentry0.nibiru.network:9910') as channel:
accounts_rpc = accounts_rpc_grpc.nibiruAccountsRPCStub(channel)
account_addr = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"

subacc = await accounts_rpc.SubaccountsList(accounts_rpc_pb.SubaccountsListRequest(account_address = account_addr))
@@ -175,7 +175,7 @@ async def main() -> None:
async def get_account_num_seq(address: str) -> (int, int):
async with aiohttp.ClientSession() as session:
async with session.request(
'GET', 'http://staking-lcd-testnet.injective.network/cosmos/auth/v1beta1/accounts/' + address,
'GET', 'http://staking-lcd-testnet.nibiru.network/cosmos/auth/v1beta1/accounts/' + address,
headers={'Accept-Encoding': 'application/json'},
) as response:
if response.status != 200:
@@ -189,7 +189,7 @@ async def get_account_num_seq(address: str) -> (int, int):
async def post_tx(tx_json: str):
async with aiohttp.ClientSession() as session:
async with session.request(
'POST', 'http://staking-lcd-testnet.injective.network/txs', data=tx_json,
'POST', 'http://staking-lcd-testnet.nibiru.network/txs', data=tx_json,
headers={'Content-Type': 'application/json'},
) as response:
if response.status != 200:
22 changes: 11 additions & 11 deletions compatibility-tests/unit_tests.py
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@
import base64

from typing import Any, Dict, List
from injective.chain_client._wallet import (
from nibiru.chain_client._wallet import (
generate_wallet,
privkey_to_address,
privkey_to_pubkey,
@@ -16,9 +16,9 @@
DEFAULT_BECH32_HRP,
)

from injective.chain_client._typings import SyncMode
import injective.exchange_api.injective_accounts_rpc_pb2 as accounts_rpc_pb
import injective.exchange_api.injective_accounts_rpc_pb2_grpc as accounts_rpc_grpc
from nibiru.chain_client._typings import SyncMode
import nibiru.exchange_api.nibiru_accounts_rpc_pb2 as accounts_rpc_pb
import nibiru.exchange_api.nibiru_accounts_rpc_pb2_grpc as accounts_rpc_grpc

MIN_GAS_PRICE = 500000000

@@ -34,7 +34,7 @@ def __init__(
gas: int,
fee_denom: str = "inj",
memo: str = "",
chain_id: str = "injective-888",
chain_id: str = "nibiru-888",
hrp: str = DEFAULT_BECH32_HRP,
sync_mode: SyncMode = "block",
) -> None:
@@ -62,7 +62,7 @@ def add_cosmos_bank_msg_send(self, recipient: str, amount: int, denom: str = "in
}
self._msgs.append(msg)

# Injective • Exchange Module
# nibiru • Exchange Module

def add_exchange_msg_deposit(self, subaccount: str, amount: int, denom: str = "inj") -> None:
msg = {
@@ -89,7 +89,7 @@ def get_signed(self) -> str:
"signatures": [
{
"signature": self._sign(),
"pub_key": {"type": "injective/PubKeyEthSecp256k1", "value": base64_pubkey},
"pub_key": {"type": "nibiru/PubKeyEthSecp256k1", "value": base64_pubkey},
"account_number": str(self._account_num),
"sequence": str(self._sequence),
}
@@ -130,7 +130,7 @@ def _get_sign_message(self) -> Dict[str, Any]:
async def get_account_num_seq(address: str) -> (int, int):
async with aiohttp.ClientSession() as session:
async with session.request(
'GET', 'http://staking-lcd-testnet.injective.network/cosmos/auth/v1beta1/accounts/' + address,
'GET', 'http://staking-lcd-testnet.nibiru.network/cosmos/auth/v1beta1/accounts/' + address,
headers={'Accept-Encoding': 'application/json'},
) as response:
if response.status != 200:
@@ -144,7 +144,7 @@ async def get_account_num_seq(address: str) -> (int, int):
async def post_tx(tx_json: str):
async with aiohttp.ClientSession() as session:
async with session.request(
'POST', 'http://staking-lcd-testnet.injective.network/txs', data=tx_json,
'POST', 'http://staking-lcd-testnet.nibiru.network/txs', data=tx_json,
headers={'Content-Type': 'application/json'},
) as response:
if response.status != 200:
@@ -168,8 +168,8 @@ async def msg_send():

acc_num, acc_seq = await get_account_num_seq(sender_acc_addr)

async with grpc.aio.insecure_channel('testnet-sentry0.injective.network:9910') as channel:
accounts_rpc = accounts_rpc_grpc.InjectiveAccountsRPCStub(channel)
async with grpc.aio.insecure_channel('testnet-sentry0.nibiru.network:9910') as channel:
accounts_rpc = accounts_rpc_grpc.nibiruAccountsRPCStub(channel)
account_addr = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"

subacc = await accounts_rpc.SubaccountsList(accounts_rpc_pb.SubaccountsListRequest(account_address = account_addr))
51 changes: 4 additions & 47 deletions examples/chain_client/dex/create_pool.py
Original file line number Diff line number Diff line change
@@ -15,63 +15,20 @@
import asyncio
import logging

from nibiru import Composer, PoolAsset, Client, Transaction, Network, PrivateKey
from nibiru.constant import GAS_PRICE
from nibiru import Sdk, Composer, PoolAsset

async def main() -> None:
# select network: local, testnet, mainnet
network = Network.local()

# initialize grpc client
client = Client(network, insecure=True)
await client.sync_timeout_height()

priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host")
pub_key = priv_key.to_public_key()
address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint)

# prepare tx msg
msg = Composer.dex.create_pool(
creator=address.to_acc_bech32(),
trader = Sdk.authorize("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host")
res = await trader.tx.dex.create_pool(
creator=trader.address,
swap_fee="2",
exit_fee="3",
assets=[
PoolAsset(token=Composer.coin(4, "unusd"),weight="3"),
PoolAsset(token=Composer.coin(5, "unibi"),weight="4"),
],
)

# build sim tx
tx = (
Transaction()
.with_messages(msg)
.with_sequence(address.get_sequence())
.with_account_num(address.get_number())
.with_chain_id(network.chain_id)
.with_signer(priv_key)
)
sim_tx_raw_bytes = tx.get_signed_tx_data()

# simulate tx
(sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes)
if not success:
print(sim_res)
return

# build tx
gas_limit = sim_res.gas_info.gas_used * 1.25
fee = [Composer.coin(
amount=int(GAS_PRICE * gas_limit),
denom=network.fee_denom,
)]
tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height)
tx_raw_bytes = tx.get_signed_tx_data()

# broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
res = await client.send_tx_sync_mode(tx_raw_bytes)
print(res)
print("gas wanted: {}".format(gas_limit))
print("gas fee: {} unibi".format(res.gas_used * GAS_PRICE))

if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
35 changes: 0 additions & 35 deletions examples/chain_client/dex/create_pool2.py

This file was deleted.

78 changes: 78 additions & 0 deletions examples/chain_client/dex/create_pool_ext.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Copyright 2022 Nibiru Chain
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import logging

from nibiru import Composer, PoolAsset, Client, Transaction, Network, PrivateKey
from nibiru.constant import GAS_PRICE

async def main() -> None:
# select network: local, testnet, mainnet
network = Network.local()

# initialize grpc client
client = Client(network, insecure=True)
await client.sync_timeout_height()

priv_key = PrivateKey.from_mnemonic("guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host")
pub_key = priv_key.to_public_key()
address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint)

# prepare tx msg
msg = Composer.dex.create_pool(
creator=address.to_acc_bech32(),
swap_fee="2",
exit_fee="3",
assets=[
PoolAsset(token=Composer.coin(4, "unusd"),weight="3"),
PoolAsset(token=Composer.coin(5, "unibi"),weight="4"),
],
)

# build sim tx
tx = (
Transaction()
.with_messages(msg)
.with_sequence(address.get_sequence())
.with_account_num(address.get_number())
.with_chain_id(network.chain_id)
.with_signer(priv_key)
)
sim_tx_raw_bytes = tx.get_signed_tx_data()

# simulate tx
(sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes)
if not success:
print(sim_res)
return

# build tx
gas_limit = sim_res.gas_info.gas_used * 1.25
fee = [Composer.coin(
amount=int(GAS_PRICE * gas_limit),
denom=network.fee_denom,
)]
tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height)
tx_raw_bytes = tx.get_signed_tx_data()

# broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
res = await client.send_tx_sync_mode(tx_raw_bytes)
print(res)
print("gas wanted: {}".format(gas_limit))
print("gas fee: {} unibi".format(res.gas_used * GAS_PRICE))

if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
Loading

0 comments on commit 6155c94

Please sign in to comment.