Skip to content

Commit 11904a5

Browse files
Merge pull request #122 from InjectiveLabs/f/optional_args_binary_options
F/Binary-options
2 parents 7994d50 + 09ca7d5 commit 11904a5

File tree

8 files changed

+1084
-298
lines changed

8 files changed

+1084
-298
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Copyright 2022 Injective Labs
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
import asyncio
17+
import logging
18+
19+
from pyinjective.composer import Composer as ProtoMsgComposer
20+
from pyinjective.async_client import AsyncClient
21+
from pyinjective.transaction import Transaction
22+
from pyinjective.constant import Network
23+
from pyinjective.wallet import PrivateKey
24+
25+
26+
async def main() -> None:
27+
# select network: local, testnet, mainnet
28+
network = Network.testnet()
29+
composer = ProtoMsgComposer(network=network.string())
30+
31+
# initialize grpc client
32+
client = AsyncClient(network, insecure=False)
33+
await client.sync_timeout_height()
34+
35+
# load account
36+
priv_key = PrivateKey.from_hex("f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3")
37+
pub_key = priv_key.to_public_key()
38+
address = await pub_key.to_address().async_init_num_seq(network.lcd_endpoint)
39+
40+
provider = "ufc"
41+
symbols = ["0x7ba77b6c69c15270bd9235f11a0068f3080017116aa3c57e17c16f49ea13f57f", "0x7ba77b6c69c15270bd9235f11a0068f3080017116aa3c57e17c16f49ea13f57f"]
42+
prices = [0.5, 0.8]
43+
44+
# prepare tx msg
45+
msg = composer.MsgRelayProviderPrices(
46+
sender=address.to_acc_bech32(),
47+
provider=provider,
48+
symbols=symbols,
49+
prices=prices
50+
)
51+
52+
# build sim tx
53+
tx = (
54+
Transaction()
55+
.with_messages(msg)
56+
.with_sequence(address.get_sequence())
57+
.with_account_num(address.get_number())
58+
.with_chain_id(network.chain_id)
59+
)
60+
sim_sign_doc = tx.get_sign_doc(pub_key)
61+
sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
62+
sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)
63+
64+
# simulate tx
65+
(sim_res, success) = await client.simulate_tx(sim_tx_raw_bytes)
66+
if not success:
67+
print(sim_res)
68+
return
69+
70+
sim_res_msg = ProtoMsgComposer.MsgResponses(sim_res.result.data, simulation=True)
71+
print("---Simulation Response---")
72+
print(sim_res_msg)
73+
74+
# build tx
75+
gas_price = 500000000
76+
gas_limit = sim_res.gas_info.gas_used + 20000 # add 20k for gas, fee computation
77+
gas_fee = '{:.18f}'.format((gas_price * gas_limit) / pow(10, 18)).rstrip('0')
78+
fee = [composer.Coin(
79+
amount=gas_price * gas_limit,
80+
denom=network.fee_denom,
81+
)]
82+
tx = tx.with_gas(gas_limit).with_fee(fee).with_memo('').with_timeout_height(client.timeout_height)
83+
sign_doc = tx.get_sign_doc(pub_key)
84+
sig = priv_key.sign(sign_doc.SerializeToString())
85+
tx_raw_bytes = tx.get_tx_data(sig, pub_key)
86+
87+
# broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
88+
res = await client.send_tx_sync_mode(tx_raw_bytes)
89+
print("---Transaction Response---")
90+
print(res)
91+
print("gas wanted: {}".format(gas_limit))
92+
print("gas fee: {} INJ".format(gas_fee))
93+
94+
if __name__ == "__main__":
95+
logging.basicConfig(level=logging.INFO)
96+
asyncio.get_event_loop().run_until_complete(main())

pyinjective/composer.py

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -414,25 +414,49 @@ def MsgAdminUpdateBinaryOptionsMarket(
414414
self,
415415
sender: str,
416416
market_id: str,
417-
settlement_price: float,
418-
expiration_timestamp: int,
419-
settlement_timestamp: int,
420-
status: str
417+
status: str,
418+
**kwargs,
421419
):
422420

423-
scale_price = Decimal((settlement_price * pow(10, 18)))
424-
price_to_bytes = bytes(str(scale_price), "utf-8")
425-
print(scale_price)
421+
price_to_bytes = None
422+
423+
if kwargs.get("settlement_price") is not None:
424+
scale_price = Decimal((kwargs.get("settlement_price") * pow(10, 18)))
425+
price_to_bytes = bytes(str(scale_price), "utf-8")
426+
427+
else:
428+
price_to_bytes = ""
426429

427430
return injective_exchange_tx_pb.MsgAdminUpdateBinaryOptionsMarket(
428431
sender=sender,
429432
market_id=market_id,
430433
settlement_price=price_to_bytes,
431-
expiration_timestamp=expiration_timestamp,
432-
settlement_timestamp=settlement_timestamp,
434+
expiration_timestamp=kwargs.get("expiration_timestamp"),
435+
settlement_timestamp=kwargs.get("settlement_timestamp"),
433436
status=status
434437
)
435438

439+
def MsgRelayProviderPrices (
440+
self,
441+
sender: str,
442+
provider: str,
443+
symbols: list,
444+
prices: list
445+
):
446+
oracle_prices = []
447+
448+
for price in prices:
449+
scale_price = Decimal((price) * pow (10, 18))
450+
price_to_bytes = bytes(str(scale_price), "utf-8")
451+
oracle_prices.append(price_to_bytes)
452+
453+
return injective_oracle_tx_pb.MsgRelayProviderPrices(
454+
sender=sender,
455+
provider=provider,
456+
symbols=symbols,
457+
prices=oracle_prices
458+
)
459+
436460
def MsgInstantBinaryOptionsMarketLaunch(
437461
self,
438462
sender: str,
@@ -778,7 +802,8 @@ def MsgResponses(data, simulation=False):
778802
"/cosmos.authz.v1beta1.MsgGrant": cosmos_authz_tx_pb.MsgGrantResponse,
779803
"/cosmos.authz.v1beta1.MsgExec": cosmos_authz_tx_pb.MsgExecResponse,
780804
"/cosmos.authz.v1beta1.MsgRevoke": cosmos_authz_tx_pb.MsgRevokeResponse,
781-
"/injective.oracle.v1beta1.MsgRelayPriceFeedPrice": injective_oracle_tx_pb.MsgRelayPriceFeedPriceResponse
805+
"/injective.oracle.v1beta1.MsgRelayPriceFeedPrice": injective_oracle_tx_pb.MsgRelayPriceFeedPriceResponse,
806+
"/injective.oracle.v1beta1.MsgRelayProviderPrices": injective_oracle_tx_pb.MsgRelayProviderPrices
782807
}
783808

784809
response = tx_response_pb.TxResponseData.FromString(data)

pyinjective/proto/exchange/injective_derivative_exchange_rpc_pb2.py

Lines changed: 433 additions & 91 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyinjective/proto/exchange/injective_derivative_exchange_rpc_pb2_grpc.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ def __init__(self, channel):
3131
request_serializer=exchange_dot_injective__derivative__exchange__rpc__pb2.StreamMarketRequest.SerializeToString,
3232
response_deserializer=exchange_dot_injective__derivative__exchange__rpc__pb2.StreamMarketResponse.FromString,
3333
)
34+
self.BinaryOptionsMarkets = channel.unary_unary(
35+
'/injective_derivative_exchange_rpc.InjectiveDerivativeExchangeRPC/BinaryOptionsMarkets',
36+
request_serializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketsRequest.SerializeToString,
37+
response_deserializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketsResponse.FromString,
38+
)
39+
self.BinaryOptionsMarket = channel.unary_unary(
40+
'/injective_derivative_exchange_rpc.InjectiveDerivativeExchangeRPC/BinaryOptionsMarket',
41+
request_serializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketRequest.SerializeToString,
42+
response_deserializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketResponse.FromString,
43+
)
3444
self.Orderbook = channel.unary_unary(
3545
'/injective_derivative_exchange_rpc.InjectiveDerivativeExchangeRPC/Orderbook',
3646
request_serializer=exchange_dot_injective__derivative__exchange__rpc__pb2.OrderbookRequest.SerializeToString,
@@ -129,6 +139,20 @@ def StreamMarket(self, request, context):
129139
context.set_details('Method not implemented!')
130140
raise NotImplementedError('Method not implemented!')
131141

142+
def BinaryOptionsMarkets(self, request, context):
143+
"""BinaryOptionsMarkets gets a list of Binary Options Markets
144+
"""
145+
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
146+
context.set_details('Method not implemented!')
147+
raise NotImplementedError('Method not implemented!')
148+
149+
def BinaryOptionsMarket(self, request, context):
150+
"""BinaryOptionMarket gets details of a single binary options market
151+
"""
152+
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
153+
context.set_details('Method not implemented!')
154+
raise NotImplementedError('Method not implemented!')
155+
132156
def Orderbook(self, request, context):
133157
"""Orderbook gets the Orderbook of a Derivative Market
134158
"""
@@ -246,6 +270,16 @@ def add_InjectiveDerivativeExchangeRPCServicer_to_server(servicer, server):
246270
request_deserializer=exchange_dot_injective__derivative__exchange__rpc__pb2.StreamMarketRequest.FromString,
247271
response_serializer=exchange_dot_injective__derivative__exchange__rpc__pb2.StreamMarketResponse.SerializeToString,
248272
),
273+
'BinaryOptionsMarkets': grpc.unary_unary_rpc_method_handler(
274+
servicer.BinaryOptionsMarkets,
275+
request_deserializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketsRequest.FromString,
276+
response_serializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketsResponse.SerializeToString,
277+
),
278+
'BinaryOptionsMarket': grpc.unary_unary_rpc_method_handler(
279+
servicer.BinaryOptionsMarket,
280+
request_deserializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketRequest.FromString,
281+
response_serializer=exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketResponse.SerializeToString,
282+
),
249283
'Orderbook': grpc.unary_unary_rpc_method_handler(
250284
servicer.Orderbook,
251285
request_deserializer=exchange_dot_injective__derivative__exchange__rpc__pb2.OrderbookRequest.FromString,
@@ -379,6 +413,40 @@ def StreamMarket(request,
379413
options, channel_credentials,
380414
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
381415

416+
@staticmethod
417+
def BinaryOptionsMarkets(request,
418+
target,
419+
options=(),
420+
channel_credentials=None,
421+
call_credentials=None,
422+
insecure=False,
423+
compression=None,
424+
wait_for_ready=None,
425+
timeout=None,
426+
metadata=None):
427+
return grpc.experimental.unary_unary(request, target, '/injective_derivative_exchange_rpc.InjectiveDerivativeExchangeRPC/BinaryOptionsMarkets',
428+
exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketsRequest.SerializeToString,
429+
exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketsResponse.FromString,
430+
options, channel_credentials,
431+
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
432+
433+
@staticmethod
434+
def BinaryOptionsMarket(request,
435+
target,
436+
options=(),
437+
channel_credentials=None,
438+
call_credentials=None,
439+
insecure=False,
440+
compression=None,
441+
wait_for_ready=None,
442+
timeout=None,
443+
metadata=None):
444+
return grpc.experimental.unary_unary(request, target, '/injective_derivative_exchange_rpc.InjectiveDerivativeExchangeRPC/BinaryOptionsMarket',
445+
exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketRequest.SerializeToString,
446+
exchange_dot_injective__derivative__exchange__rpc__pb2.BinaryOptionsMarketResponse.FromString,
447+
options, channel_credentials,
448+
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
449+
382450
@staticmethod
383451
def Orderbook(request,
384452
target,

0 commit comments

Comments
 (0)