diff --git a/CHANGES.md b/CHANGES.md index 86191d9..96be085 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -73,3 +73,22 @@ hash=hashlib.blake2b(intent,digest_size=32) #then we finally sign the hash ``` +## Margin Bank: +1. When you insert money to margin bank we give it in BASE6 but when we see balance it is in base9. internally the functions are implemented that way. +2. We expect you to give the arguments directly in DECIMALS. + + +## Making Direct Contract Calls: +1. for making contract calls. The one interacting with our contracts are implemented internally in `client.py` +2. we have exposed some generic functions through which you can make direct contract calls yourself + 1. `def rpc_unsafe_moveCall(url,params, function_name: str, function_library: str, userAddress ,packageId, gasBudget=100000000 ):` + 2. `def rpc_sui_executeTransactionBlock(url, txBytes, signature):` + 3. The first one is used to serialise the contract calls you are going to make. + 4. for second one you need to sign the result of first call with your signer and then make call along with serialised call and signature. + 5. internally all our contract calls to packages uses these functions. for more information have a look at `rpc.py` +3. For making calls to SUI functions + 1. For that we have exposed `def rpc_call_sui_function(url, params, method="suix_getCoins"):` + 2. Here you can specify the params and the name of the sui function you are calling. + 3. internally we use these calls to get the chain balance, usdc coins. + + diff --git a/examples/1.initialization.py b/examples/1.initialization.py index b37edc0..dce1244 100644 --- a/examples/1.initialization.py +++ b/examples/1.initialization.py @@ -1,11 +1,7 @@ -import os -import sys - -print (os.getcwd()) -sys.path.append(os.getcwd()+"/src/") - +import sys,os +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") from config import TEST_ACCT_KEY, TEST_NETWORK - from bluefin_client_sui import FireflyClient, Networks from pprint import pprint import asyncio diff --git a/examples/10.1.socket_readonly.py b/examples/10.1.socket_readonly.py index 3c27096..214c4da 100644 --- a/examples/10.1.socket_readonly.py +++ b/examples/10.1.socket_readonly.py @@ -1,5 +1,6 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") import time from config import TEST_ACCT_KEY, TEST_NETWORK diff --git a/examples/10.sockets.py b/examples/10.sockets.py index 6ccfb1e..97c21de 100644 --- a/examples/10.sockets.py +++ b/examples/10.sockets.py @@ -1,5 +1,7 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + import time from config import TEST_ACCT_KEY, TEST_NETWORK diff --git a/examples/11.sub_accounts.py b/examples/11.sub_accounts.py index 651bc72..4ed2883 100644 --- a/examples/11.sub_accounts.py +++ b/examples/11.sub_accounts.py @@ -1,6 +1,11 @@ +import sys,os +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_SUB_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, MARKET_SYMBOLS, ORDER_SIDE, ORDER_TYPE, Networks, OrderSignatureRequest import asyncio +from bluefin_client_sui.utilities import * async def main(): @@ -16,22 +21,23 @@ async def main(): print("Child: ", clientChild.get_public_address()) # # whitelist sub account - status = await clientParent.update_sub_account(MARKET_SYMBOLS.ETH, clientChild.get_public_address(), True) + status = await clientParent.update_sub_account(clientChild.get_public_address(), True) print("Sub account created: {}".format(status)) clientChild.add_market(MARKET_SYMBOLS.ETH) parent_leverage = await clientParent.get_user_leverage(MARKET_SYMBOLS.ETH) - + await clientParent.adjust_leverage(MARKET_SYMBOLS.ETH,1) + parent_leverage = await clientParent.get_user_leverage(MARKET_SYMBOLS.ETH) signature_request = OrderSignatureRequest( symbol=MARKET_SYMBOLS.ETH, # sub account is only whitelisted for ETH market maker=clientParent.get_public_address(), # maker of the order is the parent account price=0, - quantity=0.02, + quantity=toSuiBase(0.02), side=ORDER_SIDE.BUY, orderType=ORDER_TYPE.MARKET, - leverage=parent_leverage, + leverage=toSuiBase(parent_leverage), ) # order is signed using sub account's private key diff --git a/examples/12.open_order_event.py b/examples/12.open_order_event.py index 75f07d2..4cf2dc4 100644 --- a/examples/12.open_order_event.py +++ b/examples/12.open_order_event.py @@ -4,7 +4,9 @@ an event, log its data and terminate connection ''' import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + import time from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, SOCKET_EVENTS, ORDER_SIDE, ORDER_TYPE, OrderSignatureRequest diff --git a/examples/13.orderbook_updates.py b/examples/13.orderbook_updates.py index 5f6acfd..fd5a6a2 100644 --- a/examples/13.orderbook_updates.py +++ b/examples/13.orderbook_updates.py @@ -3,7 +3,9 @@ In this code example we open a socket connection and listen to orderbook update event ''' import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + import time from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, SOCKET_EVENTS, ORDER_SIDE, ORDER_TYPE, OrderSignatureRequest diff --git a/examples/14.web_sockets.py b/examples/14.web_sockets.py index de2060b..db3bc0e 100644 --- a/examples/14.web_sockets.py +++ b/examples/14.web_sockets.py @@ -1,6 +1,7 @@ - import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + import time from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, SOCKET_EVENTS, config_logging diff --git a/examples/15.get_funding_history.py b/examples/15.get_funding_history.py index 5e41bb6..9435572 100644 --- a/examples/15.get_funding_history.py +++ b/examples/15.get_funding_history.py @@ -1,6 +1,8 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, GetFundingHistoryRequest from pprint import pprint diff --git a/examples/16.listening_events_using_sub_account.py b/examples/16.listening_events_using_sub_account.py index 6c87c48..17291e9 100644 --- a/examples/16.listening_events_using_sub_account.py +++ b/examples/16.listening_events_using_sub_account.py @@ -4,6 +4,10 @@ has no position of its own. So when placing orders or listening to position updates the sub account must specify the parent address whose position its listening. ''' +import sys,os +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + import time, sys from config import TEST_ACCT_KEY, TEST_NETWORK, TEST_SUB_ACCT_KEY from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, OrderSignatureRequest, ORDER_SIDE, ORDER_TYPE, SOCKET_EVENTS diff --git a/examples/17.1.get_orders_readonly.py b/examples/17.1.get_orders_readonly.py index 7824502..fec5696 100644 --- a/examples/17.1.get_orders_readonly.py +++ b/examples/17.1.get_orders_readonly.py @@ -5,7 +5,9 @@ ''' import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ORDER_STATUS, ORDER_TYPE import asyncio diff --git a/examples/17.get_orders.py b/examples/17.get_orders.py index c4a80af..ae322e7 100644 --- a/examples/17.get_orders.py +++ b/examples/17.get_orders.py @@ -4,7 +4,9 @@ mixed together to fetch the exact data that user needs. ''' import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ORDER_STATUS, ORDER_TYPE import asyncio diff --git a/examples/18.dms_api.py b/examples/18.dms_api.py index 8db738e..ea96e92 100644 --- a/examples/18.dms_api.py +++ b/examples/18.dms_api.py @@ -1,7 +1,9 @@ import json import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_SUB_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, MARKET_SYMBOLS, ORDER_SIDE, ORDER_TYPE, Networks, OrderSignatureRequest import asyncio diff --git a/examples/19.Generate_readonly_token.py b/examples/19.Generate_readonly_token.py index 083b73a..1e960f5 100644 --- a/examples/19.Generate_readonly_token.py +++ b/examples/19.Generate_readonly_token.py @@ -1,6 +1,8 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks from pprint import pprint diff --git a/examples/2.user_info.py b/examples/2.user_info.py index 0e91289..2481b4d 100644 --- a/examples/2.user_info.py +++ b/examples/2.user_info.py @@ -1,5 +1,7 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS from pprint import pprint diff --git a/examples/20.contract_call.py b/examples/20.contract_call.py deleted file mode 100644 index ddd9967..0000000 --- a/examples/20.contract_call.py +++ /dev/null @@ -1,46 +0,0 @@ -import sys,os -sys.path.append(os.getcwd()+"/src/") -import base64 -from bluefin_client_sui.utilities import * -from config import TEST_ACCT_KEY, TEST_NETWORK -from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ORDER_SIDE, ORDER_TYPE, OrderSignatureRequest -import asyncio -from bluefin_client_sui import signer -from bluefin_client_sui import * - -async def main(): - - # initialize client - client = FireflyClient( - True, # agree to terms and conditions - Networks[TEST_NETWORK], # network to connect with - TEST_ACCT_KEY, # private key of wallet - ) - await client.init(True) - ### you need to have usdc coins to deposit it to margin bank. - ### the below functions just gets usdc coins that you have. - usdc_coins=client.get_usdc_coins() - - coin_obj_id=usdc_coins["data"][0]["coinObjectId"] - await client.deposit_margin_to_bank(1000, coin_obj_id) - - - await client.withdraw_margin_from_bank(100) - - - await client.withdraw_all_margin_from_bank() - - - - - - - await client.close_connections() - - - - -if __name__ == "__main__": - loop = asyncio.new_event_loop() - loop.run_until_complete(main()) - loop.close() \ No newline at end of file diff --git a/examples/3.balance.py b/examples/3.balance.py index 93a51ed..fea28e6 100644 --- a/examples/3.balance.py +++ b/examples/3.balance.py @@ -1,6 +1,6 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") - +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks import asyncio @@ -32,18 +32,27 @@ async def main(): # deposit usdc to margin bank # must have native chain tokens to pay for gas fee - print('USDC deposited:', await client.deposit_margin_to_bank(10)) + usdc_coins=client.get_usdc_coins() + ## we expect that you have some coins in your usdc, + coin_obj_id=usdc_coins["data"][1]["coinObjectId"] + print('USDC deposited:', await client.deposit_margin_to_bank(50, coin_obj_id)) # check margin bank balance resp = await client.get_margin_bank_balance() print('Margin bank balance:', resp) - # withdraw margin bank balance - print('USDC Withdrawn:', await client.withdraw_margin_from_bank(resp)) + # withdraw 10 USD from margin bank balance + print('USDC Withdrawn:', await client.withdraw_margin_from_bank(10)) # check margin bank balance print('Margin bank balance:', await client.get_margin_bank_balance()) + + + print ("Withdraw everything from margin balance", await client.withdraw_all_margin_from_bank()) + # check margin bank balance + print('Margin bank balance:', await client.get_margin_bank_balance()) + await client.close_connections() diff --git a/examples/4.placing_orders.py b/examples/4.placing_orders.py index da48268..d01673f 100644 --- a/examples/4.placing_orders.py +++ b/examples/4.placing_orders.py @@ -1,5 +1,7 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from bluefin_client_sui.utilities import toSuiBase from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ORDER_SIDE, ORDER_TYPE, OrderSignatureRequest @@ -40,21 +42,10 @@ async def place_market_order(client: FireflyClient): # default leverage of account is set to 3 on firefly - user_leverage = await client.get_user_leverage(MARKET_SYMBOLS.ETH) + await client.adjust_leverage(MARKET_SYMBOLS.BTC,1) - # creates a LIMIT order to be signed - ''' - signature_request = OrderSignatureRequest( - symbol=MARKET_SYMBOLS.ETH, # market symbol - price=0, # price at which you want to place order - quantity=0.01, # quantity - side=ORDER_SIDE.BUY, - orderType=ORDER_TYPE.MARKET, - leverage=user_leverage - ) ''' signature_request = OrderSignatureRequest( - symbol=MARKET_SYMBOLS.ETH, - # market = "0x25a869797387e2eaa09c658c83dc0deaba99bb02c94447339c06fdbe8287347e", + symbol=MARKET_SYMBOLS.BTC, price = toSuiBase(0), quantity = toSuiBase(1), leverage = toSuiBase(1), @@ -62,7 +53,6 @@ async def place_market_order(client: FireflyClient): reduceOnly = False, postOnly = False, orderbookOnly = True, - maker = "0xa3c3504d90c428274beaa89f1238a769ea1d1c3516c31c0f4157f33787367af0", expiration = 1700530261000, salt = 1668690862116, orderType = ORDER_TYPE.MARKET, @@ -93,9 +83,9 @@ async def main(): await client.init(True) # add market that you wish to trade on ETH/BTC are supported currently + client.add_market(MARKET_SYMBOLS.BTC) client.add_market(MARKET_SYMBOLS.ETH) - # await place_limit_order(client) await place_market_order(client) await place_limit_order(client) diff --git a/examples/5.adjusting_leverage.py b/examples/5.adjusting_leverage.py index 0734be3..3a0dd03 100644 --- a/examples/5.adjusting_leverage.py +++ b/examples/5.adjusting_leverage.py @@ -1,5 +1,7 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS @@ -12,7 +14,8 @@ async def main(): client = FireflyClient( True, # agree to terms and conditions Networks[TEST_NETWORK], # network to connect with - TEST_ACCT_KEY, # private key of wallet + TEST_ACCT_KEY # private key of wallet + ) await client.init(True) diff --git a/examples/6.adjusting_margin.py b/examples/6.adjusting_margin.py index a2f6db8..6519ffb 100644 --- a/examples/6.adjusting_margin.py +++ b/examples/6.adjusting_margin.py @@ -1,19 +1,90 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ADJUST_MARGIN -from eth_utils import from_wei import asyncio - +from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ORDER_SIDE, ORDER_TYPE, OrderSignatureRequest +from bluefin_client_sui.utilities import toSuiBase TEST_NETWORK="SUI_STAGING" + +async def place_limit_order(client: FireflyClient): + + # default leverage of account is set to 3 on firefly + user_leverage = await client.get_user_leverage(MARKET_SYMBOLS.ETH) + await client.adjust_leverage(MARKET_SYMBOLS.ETH, 3) + user_leverage = await client.get_user_leverage(MARKET_SYMBOLS.ETH) + + print ("User Leverage", user_leverage) + + + # creates a LIMIT order to be signed + signature_request = OrderSignatureRequest( + symbol=MARKET_SYMBOLS.ETH, # market symbol + price=toSuiBase(1636.8), # price at which you want to place order + quantity=toSuiBase(0.01), # quantity + side=ORDER_SIDE.BUY, + orderType=ORDER_TYPE.LIMIT, + leverage=toSuiBase(user_leverage) + ) + + # create signed order + signed_order = client.create_signed_order(signature_request) + + print("Placing a limit order") + # place signed order on orderbook + resp = await client.post_signed_order(signed_order) + + # returned order with PENDING state + print(resp) + + return + +async def place_market_order(client: FireflyClient): + + + # default leverage of account is set to 3 on firefly + user_leverage = await client.get_user_leverage(MARKET_SYMBOLS.ETH) + + signature_request = OrderSignatureRequest( + symbol=MARKET_SYMBOLS.ETH, + price = toSuiBase(0), + quantity = toSuiBase(1), + leverage = toSuiBase(user_leverage), + side = ORDER_SIDE.BUY, + orderType=ORDER_TYPE.MARKET, + ) + + # create signed order + signed_order = client.create_signed_order(signature_request) + + print("Placing a market order") + # place signed order on orderbook + resp = await client.post_signed_order(signed_order) + + # returned order with PENDING state + print(resp) + + + return async def main(): client = FireflyClient(True, Networks[TEST_NETWORK], TEST_ACCT_KEY) await client.init(True) + client.add_market(MARKET_SYMBOLS.ETH) + print (await client.get_usdc_balance()) + + #usdc_coins=client.get_usdc_coins() + #coin_obj_id=usdc_coins["data"][1]["coinObjectId"] + #await client.deposit_margin_to_bank(1000000000000, coin_obj_id) + + print (await client.get_margin_bank_balance()) + await place_market_order(client) position = await client.get_user_position({"symbol":MARKET_SYMBOLS.ETH}) - print("Current margin in position:", from_wei(int(position["margin"]), "ether")) + print("Current margin in position:", position) # adding 100$ from our margin bank into our BTC position on-chain # must have native chain tokens to pay for gas fee @@ -23,14 +94,14 @@ async def main(): # to on-chain positions on exchange as off-chain infrastructure waits for blockchain # to emit position update event position = await client.get_user_position({"symbol":MARKET_SYMBOLS.ETH}) - print("Current margin in position:", from_wei(int(position["margin"]), "ether")) + print("Current margin in position:",position["margin"]) # removing 100$ from margin await client.adjust_margin(MARKET_SYMBOLS.ETH, ADJUST_MARGIN.REMOVE, 100) position = await client.get_user_position({"symbol":MARKET_SYMBOLS.ETH}) - print("Current margin in position:", from_wei(int(position["margin"]), "ether")) + print("Current margin in position:", int(position["margin"])) try: diff --git a/examples/7.cancelling_orders.py b/examples/7.cancelling_orders.py index e29ca6b..f9e89d0 100644 --- a/examples/7.cancelling_orders.py +++ b/examples/7.cancelling_orders.py @@ -1,5 +1,7 @@ -import sys,os, random -sys.path.append(os.getcwd()+"/src/") +import sys,os +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + import time from config import TEST_ACCT_KEY, TEST_NETWORK @@ -14,14 +16,17 @@ async def main(): client = FireflyClient(True, Networks[TEST_NETWORK], TEST_ACCT_KEY) await client.init(True) - + # must add market before cancelling its orders client.add_market(MARKET_SYMBOLS.ETH) + client.add_market(MARKET_SYMBOLS.BTC) + #client.create_order_to_sign() await client.adjust_leverage(MARKET_SYMBOLS.ETH, 1) + await client.adjust_leverage(MARKET_SYMBOLS.BTC,1) - # creates a LIMIT order to be signed + # creates a LIMIT order to be signed order = OrderSignatureRequest( symbol=MARKET_SYMBOLS.ETH, # market symbol price=toSuiBase(1636.8), # price at which you want to place order diff --git a/examples/8.exchange_data.py b/examples/8.exchange_data.py index 35b4d06..0893cda 100644 --- a/examples/8.exchange_data.py +++ b/examples/8.exchange_data.py @@ -1,5 +1,7 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, TRADE_TYPE, Interval diff --git a/examples/9.user_data.py b/examples/9.user_data.py index 5525e53..422c33a 100644 --- a/examples/9.user_data.py +++ b/examples/9.user_data.py @@ -1,5 +1,7 @@ import sys,os -sys.path.append(os.getcwd()+"/src/") +#Commented as of now, to be only uncommented when testing library +#sys.path.append(os.getcwd()+"/src/") + from config import TEST_ACCT_KEY, TEST_NETWORK from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ORDER_STATUS diff --git a/examples/contract_call.py b/examples/contract_call.py deleted file mode 100644 index dbdd689..0000000 --- a/examples/contract_call.py +++ /dev/null @@ -1,52 +0,0 @@ -import sys,os -sys.path.append(os.getcwd()+"/src/") -import base64 -from bluefin_client_sui.utilities import * -from config import TEST_ACCT_KEY, TEST_NETWORK -from bluefin_client_sui import FireflyClient, Networks, MARKET_SYMBOLS, ORDER_SIDE, ORDER_TYPE, OrderSignatureRequest -import asyncio -from bluefin_client_sui import signer -from bluefin_client_sui import * - -async def main(): - - # initialize client - client = FireflyClient( - True, # agree to terms and conditions - Networks[TEST_NETWORK], # network to connect with - TEST_ACCT_KEY, # private key of wallet - ) - await client.init(True) - - await client.withdraw_margin_from_bank(1000) - - - - - # add market that you wish to trade on ETH/BTC are supported currently - client.add_market(MARKET_SYMBOLS.ETH) - txBytes="AAADAQGPzuAZV5krLKJWD1WUXOjk7Guz2vki2pBMZJ6CXkRf1XLGgQAAAAAAAQAgH/qFdX+Vzs7ShiLTDkGkUsiFFt9TRQyxkTgS3YKNWWgAEOgDAAAAAAAAAAAAAAAAAAABAF82iNaL7Cly31h0P767ErFoKbQb8bxQeNNRAJDvbPWOC21hcmdpbl9iYW5rEndpdGhkcmF3X2Zyb21fYmFuawADAQAAAQEAAQIAH/qFdX+Vzs7ShiLTDkGkUsiFFt9TRQyxkTgS3YKNWWgBWiybg/9fRf7zXUmsdBU3umIFeucEZNWeMGzlLttPf86tHg8AAAAAACA3qZfzxP1+yVILtVkJ6LdfZvkF7gK877AJco9Xook9Th/6hXV/lc7O0oYi0w5BpFLIhRbfU0UMsZE4Et2CjVlo6AMAAAAAAAAA4fUFAAAAAAA=" - dec_msg=base64.b64decode(txBytes) - mysigner=signer.Signer() - - seed="negative repeat fold noodle symptom spirit spend trophy merge ethics math erupt" - sui_wallet=SuiWallet(seed=seed) - - #private_key=mnemonicToPrivateKey(seed) - #privateKeyBytes=private_key.ToBytes() - #publicKey=privateKeyToPublicKey(private_key) - #publicKeyBytes=publicKey.ToBytes() - - - result=mysigner.sign_tx(dec_msg, sui_wallet) - print (result) - - await client.close_connections() - - - - -if __name__ == "__main__": - loop = asyncio.new_event_loop() - loop.run_until_complete(main()) - loop.close() diff --git a/requirements.in b/requirements.in index 47dfbbe..1477b2b 100644 --- a/requirements.in +++ b/requirements.in @@ -6,6 +6,7 @@ attrs==23.1.0 bidict==0.22.1 bip-utils==2.7.1 cbor2==5.4.6 +certifi==2023.7.22 cffi==1.15.1 charset-normalizer==3.2.0 coincurve==17.0.0 @@ -24,8 +25,10 @@ pycryptodome==3.18.0 PyNaCl==1.5.0 python-engineio==4.6.0 python-socketio==5.8.0 +requests==2.31.0 six==1.16.0 socketio==0.2.1 +urllib3==2.0.4 websocket==0.2.1 websocket-client==1.6.2 yarl==1.9.2 diff --git a/src/bluefin_client_sui/client.py b/src/bluefin_client_sui/client.py index b95dd09..3ab96de 100644 --- a/src/bluefin_client_sui/client.py +++ b/src/bluefin_client_sui/client.py @@ -4,7 +4,7 @@ from .order_signer import OrderSigner from .onboarding_signer import OnboardingSigner from .utilities import * -from .constants import TIME, SERVICE_URLS +from .constants import * from .interfaces import * from .sockets_lib import Sockets from .enumerations import * @@ -31,17 +31,18 @@ def __init__(self, are_terms_accepted, network, private_key=""): self.order_signers = {} self.onboarding_signer = OnboardingSigner() self.contract_signer=Signer() + self.url=self.network['url'] - async def init(self, user_onboarding=True, api_token="", symbol:MARKET_SYMBOLS=MARKET_SYMBOLS.ETH): + async def init(self, user_onboarding=True, api_token=""): """ Initialize the client. Inputs: user_onboarding (bool, optional): If set to true onboards the user address to exchange and gets authToken. Defaults to True. api_token(string, optional): API token to initialize client in read-only mode """ - self.contracts.contract_addresses = await self.get_contract_addresses(symbol) - self.contracts.set_contract_addresses(self.contracts.contract_addresses, market=symbol) + self.contracts.contract_addresses = await self.get_contract_addresses() + self.contracts.set_contract_addresses(self.contracts.contract_addresses) if api_token: self.apis.api_token = api_token @@ -54,7 +55,7 @@ async def init(self, user_onboarding=True, api_token="", symbol:MARKET_SYMBOLS=M self.dmsApi.auth_token = self.apis.auth_token self.socket.set_token(self.apis.auth_token) self.webSocketClient.set_token(self.apis.auth_token) - + async def onboard_user(self, token:str=None): """ @@ -114,36 +115,11 @@ def add_market(self, symbol: MARKET_SYMBOLS, trader_contract=None): if (symbol_str in self.order_signers): return False - # if orders contract address is not provided get - # from addresses retrieved from dapi - #if trader_contract == None: - # try: - # trader_contract = self.contracts.contract_addresses[symbol_str]["IsolatedTrader"] - # except: - # raise SystemError("Can't find orders contract address for market: {}".format(symbol_str)) - self.order_signers[symbol_str] = OrderSigner( self.network["chainId"], ) return True - def add_contract(self,name,address,market=None): - """ - Adds contracts to the instance's contracts dictionary. - The contract name should match the contract's abi name in ./abi directory or a new abi should be added with the desired name. - Inputs: - name(str): The contract name. - address(str): The contract address. - market(str): The market (ETH/BTC) this contract belongs to (required for market specific contracts). - """ - abi = self.contracts.get_contract_abi(name) - if market: - contract=self.w3.eth.contract(address=Web3.toChecksumAddress(address), abi=abi) - self.contracts.set_contracts(market=market,name=name,contract=contract) - else: - contract=self.w3.eth.contract(address=Web3.toChecksumAddress(address), abi=abi) - self.contracts.set_contracts(name=name,contract=contract) - return def create_order_to_sign(self, params:OrderSignatureRequest): """ @@ -345,7 +321,7 @@ async def post_signed_order(self, params:PlaceOrderRequest): ) ## Contract calls - async def deposit_margin_to_bank(self, amount: int, coin_id: str)-> bool: + async def deposit_margin_to_bank(self, amount: int, coin_id: str, market=MARKET_SYMBOLS.ETH)-> bool: """ Deposits given amount of USDC from user's account to margin bank @@ -360,18 +336,26 @@ async def deposit_margin_to_bank(self, amount: int, coin_id: str)-> bool: callArgs=[] callArgs.append(self.contracts.get_bank_id()) callArgs.append(self.account.getUserAddress()) - callArgs.append(str(amount)) + callArgs.append(str(toSuiBase(amount,base=CONTRACTS_BASE_NUM))) callArgs.append(coin_id) - txBytes=rpc_unsafe_moveCall("https://fullnode.testnet.sui.io:443", callArgs, "deposit_to_bank","margin_bank",user_address, package_id) + txBytes=rpc_unsafe_moveCall(self.url, + callArgs, + "deposit_to_bank", + "margin_bank", + user_address, + package_id) signature=self.contract_signer.sign_tx(txBytes, self.account) - res=rpc_sui_executeTransactionBlock("https://fullnode.testnet.sui.io:443", + res=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) + if res['result']['effects']['status']['status']=='success': + return True + else: + return False - return res - async def withdraw_margin_from_bank(self, amount): + async def withdraw_margin_from_bank(self, amount: Union[int,float], market=MARKET_SYMBOLS.ETH)-> bool: """ Withdraws given amount of usdc from margin bank if possible @@ -385,8 +369,8 @@ async def withdraw_margin_from_bank(self, amount): bank_id=self.contracts.get_bank_id() account_address=self.account.getUserAddress() - callArgs=[bank_id, account_address, str(amount)] - txBytes=rpc_unsafe_moveCall("https://fullnode.testnet.sui.io:443", + callArgs=[bank_id, account_address, str(toSuiBase(amount, base=CONTRACTS_BASE_NUM))] + txBytes=rpc_unsafe_moveCall(self.url, callArgs, "withdraw_from_bank", "margin_bank", @@ -394,20 +378,30 @@ async def withdraw_margin_from_bank(self, amount): self.contracts.get_package_id() ) signature=self.contract_signer.sign_tx(txBytes, self.account) - res=rpc_sui_executeTransactionBlock("https://fullnode.testnet.sui.io:443", + res=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) - return res + if res['result']['effects']['status']['status']=='success': + return True + else: + return False + + async def withdraw_all_margin_from_bank(self) -> bool: + """ + Withdraws everything of usdc from margin bank - async def withdraw_all_margin_from_bank(self): + Inputs: + No input Required + Returns: + Boolean: true if amount is successfully withdrawn, false otherwise + """ bank_id=self.contracts.get_bank_id() account_address=self.account.getUserAddress() - perp_id=self.contracts.get_perpetual_id() - + callArgs=[bank_id, account_address] - txBytes=rpc_unsafe_moveCall("https://fullnode.testnet.sui.io:443", + txBytes=rpc_unsafe_moveCall(self.url, callArgs, "withdraw_all_margin_from_bank", "margin_bank", @@ -415,14 +409,17 @@ async def withdraw_all_margin_from_bank(self): self.contracts.get_package_id() ) signature=self.contract_signer.sign_tx(txBytes, self.account) - res=rpc_sui_executeTransactionBlock("https://fullnode.testnet.sui.io:443", + res=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) - return res + if res['result']['effects']['status']['status']=="success": + return True + else: + return False - async def adjust_leverage(self, symbol, leverage, parentAddress:str=""): + async def adjust_leverage(self, symbol, leverage, parentAddress:str="")-> bool: """ Adjusts user leverage to the provided one for their current position on-chain and off-chain. If a user has no position for the provided symbol, leverage only recorded off-chain @@ -441,14 +438,25 @@ async def adjust_leverage(self, symbol, leverage, parentAddress:str=""): account_address = self.account.address if parentAddress=="" else parentAddress # implies user has an open position on-chain, perform on-chain leverage update if(user_position != {}): - perp_contract = self.contracts.get_contract(name="Perpetual", market=symbol.value) - construct_txn = perp_contract.functions.adjustLeverage( - account_address, - toDapiBase(leverage)).buildTransaction({ - 'from': self.account.address, - 'nonce': self.w3.eth.getTransactionCount(self.account.address), - }) - self._execute_tx(construct_txn) + callArgs = [] + callArgs.append(self.contracts.get_perpetual_id(symbol)) + callArgs.append(self.contracts.get_bank_id()) + callArgs.append(self.contracts.get_sub_account_id()) + callArgs.append(account_address) + callArgs.append(str(toSuiBase(leverage))) + callArgs.append(self.contracts.get_price_oracle_object_id(symbol)) + txBytes=rpc_unsafe_moveCall(self.url, + callArgs, + "adjust_leverage", + "exchange", + self.account.getUserAddress(), + self.contracts.get_package_id()) + signature=self.contract_signer.sign_tx(txBytes, self.account) + result=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) + if result['result']['effects']['status']['status']=='success': + return True + else: + return False else: await self.apis.post( @@ -464,7 +472,7 @@ async def adjust_leverage(self, symbol, leverage, parentAddress:str=""): return True - async def adjust_margin(self, symbol, operation, amount, parentAddress:str=""): + async def adjust_margin(self, symbol: MARKET_SYMBOLS, operation: ADJUST_MARGIN, amount: str, parentAddress:str="") -> bool: """ Adjusts user's on-chain position by adding or removing the specified amount of margin. Performs on-chain contract call, the user must have gas tokens @@ -480,84 +488,126 @@ async def adjust_margin(self, symbol, operation, amount, parentAddress:str=""): user_position = await self.get_user_position({"symbol":symbol, "parentAddress": parentAddress}) - account_address = Web3.toChecksumAddress(self.account.address if parentAddress == "" else parentAddress) - + if(user_position == {}): raise(Exception("User has no open position on market: {}".format(symbol))) else: - perp_contract = self.contracts.get_contract(name="Perpetual", market=symbol.value) - on_chain_call = perp_contract.functions.addMargin if operation == ADJUST_MARGIN.ADD else perp_contract.functions.removeMargin - - construct_txn = on_chain_call( - account_address, - to_wei(amount, "ether")).buildTransaction({ - 'from': self.account.address, - 'nonce': self.w3.eth.getTransactionCount(self.account.address), - }) - - self._execute_tx(construct_txn) - - return True + callArgs = [] + callArgs.append(self.contracts.get_perpetual_id(symbol)) + callArgs.append(self.contracts.get_bank_id()) + + callArgs.append(self.contracts.get_sub_account_id()) + callArgs.append(self.account.getUserAddress()) + callArgs.append(str(amount)) + callArgs.append(self.contracts.get_price_oracle_object_id(symbol)) + if operation==ADJUST_MARGIN.ADD: + txBytes=rpc_unsafe_moveCall(self.url, + callArgs, + "add_margin", + "exchange", + self.account.getUserAddress(), + self.contracts.get_package_id()) + + else: + txBytes=rpc_unsafe_moveCall(self.url, + callArgs, + "remove_margin", + "exchange", + self.account.getUserAddress(), + self.contracts.get_package_id()) + + signature=self.contract_signer.sign_tx(txBytes, self.account) + result=rpc_sui_executeTransactionBlock(self.url,txBytes, signature) + if result['result']['effects']['status']['status']=='success': + return True + else: + return False + - async def update_sub_account(self, symbol, sub_account_address, status): + async def update_sub_account(self, sub_account_address: str, status: bool) -> bool: """ Used to whitelist and account as a sub account or revoke sub account status from an account. Inputs: - symbol (MARKET_SYMBOLS): market on which sub account status is to be updated sub_account_address (str): address of the sub account status (bool): new status of the sub account Returns: Boolean: true if the sub account status is update """ - perp_contract = self.contracts.get_contract(name="Perpetual", market=symbol.value) - - construct_txn = perp_contract.functions.setSubAccount( - sub_account_address, - status).buildTransaction({ - 'from': self.account.address, - 'nonce': self.w3.eth.getTransactionCount(self.account.address), - }) - - self._execute_tx(construct_txn) - - return True + callArgs=[] + callArgs.append(self.contracts.get_sub_account_id()) + callArgs.append(sub_account_address) + callArgs.append(status) + txBytes=rpc_unsafe_moveCall(self.url, + callArgs, + "set_sub_account", + "roles", + self.account.getUserAddress(), + self.contracts.get_package_id()) + + signature=self.contract_signer.sign_tx(txBytes, self.account) + + result=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) + if result['result']['effects']['status']['status']=='success': + return True + else: + return False - async def get_native_chain_token_balance(self): + async def get_native_chain_token_balance(self)-> float: """ - Returns user's native chain token (ETH/BOBA) balance + Returns user's native chain token (SUI) balance """ try: - return from_wei(self.w3.eth.get_balance(self.w3.toChecksumAddress(self.account.address)), "ether") + callArgs=[] + callArgs.append(self.account.getUserAddress()) + callArgs.append("0x2::sui::SUI") + + result=rpc_call_sui_function(self.url, callArgs, method="suix_getBalance")["totalBalance"] + return fromSuiBase(result) except Exception as e: raise(Exception("Failed to get balance, Exception: {}".format(e))) + def get_usdc_coins(self): - callArgs=[] - callArgs.append(self.account.getUserAddress()) - callArgs.append(self.contracts.get_currency_type()) - result=rpc_get_usdc_coins("https://fullnode.testnet.sui.io:443",callArgs ) - return result + try: + callArgs=[] + callArgs.append(self.account.getUserAddress()) + callArgs.append(self.contracts.get_currency_type()) + result=rpc_call_sui_function(self.url,callArgs, method="suix_getCoins" ) + return result + except Exception as e: + raise(Exception("Failed to get USDC coins, Exception: {}".format(e))) - async def get_usdc_balance(self): + async def get_usdc_balance(self)-> float: """ Returns user's USDC token balance on Firefly. """ try: - contract = self.contracts.get_contract(name="USDC") - raw_bal = contract.functions.balanceOf(self.account.address).call() - return from_wei(int(raw_bal), "mwei") + callArgs=[] + callArgs.append(self.account.getUserAddress()) + callArgs.append(self.contracts.get_currency_type()) + result=rpc_call_sui_function(self.url, callArgs, method="suix_getBalance")["totalBalance"] + return float(result) + except Exception as e: raise(Exception("Failed to get balance, Exception: {}".format(e))) - async def get_margin_bank_balance(self): + async def get_margin_bank_balance(self)-> float: """ Returns user's Margin Bank balance. - """ + """ try: - contract = self.contracts.get_contract(name="MarginBank") - return from_wei(contract.functions.getAccountBankBalance(self.account.address).call(),"ether") + callArgs=[] + callArgs.append(self.contracts.get_bank_table_id()) + callArgs.append({ + "type": "address", + "value": self.account.getUserAddress() + }) + result=rpc_call_sui_function(self.url, callArgs, method="suix_getDynamicFieldObject") + + balance=fromSuiBase(result["data"]["content"]["fields"]["value"]["fields"]["balance"]) + return balance except Exception as e: raise(Exception("Failed to get balance, Exception: {}".format(e))) @@ -754,19 +804,17 @@ async def get_market_recent_trades(self,params:GetMarketRecentTradesRequest): params ) - async def get_contract_addresses(self, symbol:MARKET_SYMBOLS=MARKET_SYMBOLS.ETH): + async def get_contract_addresses(self): """ Returns all contract addresses for the provided market. Inputs: - symbol(MARKET_SYMBOLS): the market symbol + nothing Returns: dict: all the contract addresses """ - query = {"symbol": symbol.value } if symbol else {} - + return await self.apis.get( - SERVICE_URLS["MARKET"]["CONTRACT_ADDRESSES"], - query + SERVICE_URLS["MARKET"]["CONTRACT_ADDRESSES"] ) ## User endpoints diff --git a/src/bluefin_client_sui/constants.py b/src/bluefin_client_sui/constants.py index 610349d..d092e8b 100644 --- a/src/bluefin_client_sui/constants.py +++ b/src/bluefin_client_sui/constants.py @@ -1,6 +1,6 @@ Networks = { "SUI_STAGING":{ - "url":"", + "url":"https://fullnode.testnet.sui.io:443", "chainId":1234, "apiGateway":"https://dapi.api.sui-staging.bluefin.io", "socketURL":"wss://dapi.api.sui-staging.bluefin.io", @@ -134,4 +134,5 @@ SUI_BASE_NUM=1000000000 -DAPI_BASE_NUM=1000000000000000000 \ No newline at end of file +DAPI_BASE_NUM=1000000000000000000 +CONTRACTS_BASE_NUM=1000000 \ No newline at end of file diff --git a/src/bluefin_client_sui/contracts.py b/src/bluefin_client_sui/contracts.py index 2e8d204..aaa6840 100644 --- a/src/bluefin_client_sui/contracts.py +++ b/src/bluefin_client_sui/contracts.py @@ -5,20 +5,27 @@ def __init__(self): self.contracts = {} self.contract_addresses = {} - def set_contract_addresses(self,contract_address,market=None,name=None): + def set_contract_addresses(self,contract_address): self.contract_addresses["auxiliaryContractsAddresses"]=contract_address['auxiliaryContractsAddresses'] - self.contract_addresses[market]=contract_address[market.value] - - def get_perpetual_id(self, market: MARKET_SYMBOLS=MARKET_SYMBOLS.ETH): - return self.contract_addresses[market]['Perpetual']['id'] - def get_package_id(self, market: MARKET_SYMBOLS=MARKET_SYMBOLS.ETH): - return self.contract_addresses[market]['package']['id'] + def get_sub_account_id(self): + return self.contract_addresses['auxiliaryContractsAddresses']['objects']['SubAccounts']['id'] + def get_bank_table_id(self): + return self.contract_addresses['auxiliaryContractsAddresses']['objects']['BankTable']['id'] + + def get_price_oracle_object_id(self, market: MARKET_SYMBOLS): + return self.contract_addresses[market.value]['PriceOracle']['id'] + + def get_perpetual_id(self, market: MARKET_SYMBOLS): + return self.contract_addresses[market.value]['Perpetual']['id'] + def get_package_id(self): + return self.contract_addresses['auxiliaryContractsAddresses']['objects']['package']['id'] + def get_currency_type(self): return self.contract_addresses['auxiliaryContractsAddresses']['objects']['Currency']['dataType'] - def get_bank_id(self, market: MARKET_SYMBOLS=MARKET_SYMBOLS.ETH): + def get_bank_id(self): return self.contract_addresses['auxiliaryContractsAddresses']['objects']['Bank']['id'] def get_contract(self,name,market=""): """ diff --git a/src/bluefin_client_sui/rpc.py b/src/bluefin_client_sui/rpc.py index 2afb631..dad746c 100644 --- a/src/bluefin_client_sui/rpc.py +++ b/src/bluefin_client_sui/rpc.py @@ -2,6 +2,22 @@ import json def rpc_unsafe_moveCall(url,params, function_name: str, function_library: str, userAddress ,packageId, gasBudget=100000000 ): + """ + Does the RPC call to SUI chain + Input: + url: url of the node + params: a list of arguments to be passed to function + function_name: name of the function to call on sui + function_library: name of the library/module in which the function exists + userAddress: Address of the signer + packageId: package id in which the module exists + gasBudget(optional): gasBudget defaults to 100000000 + + Output: + Returns the request form serialised in bytes ready to be signed. + + """ + base_dict={} base_dict["jsonrpc"]="2.0" base_dict["id"]=1689764924887 @@ -22,6 +38,18 @@ def rpc_unsafe_moveCall(url,params, function_name: str, function_library: str, u return result['result']['txBytes'] def rpc_sui_executeTransactionBlock(url, txBytes, signature): + """ + Execute the SUI call on sui chain + Input: + url: url of the node + txBytes: the call in serialised form + signature: txBytes signed by signer + + Output: + result of transaction + + + """ base_dict={} base_dict["jsonrpc"]="2.0" base_dict["id"]=5 @@ -46,7 +74,14 @@ def rpc_sui_executeTransactionBlock(url, txBytes, signature): return result -def rpc_get_usdc_coins(url, params, method="suix_getCoins"): +def rpc_call_sui_function(url, params, method="suix_getCoins"): + """ + for calling sui functions: + Input: + url: url of node + params: arguments of function + method(optional): the name of method in sui we want to call. defaults to suix_getCoins + """ base_dict={} base_dict["jsonrpc"]="2.0" base_dict["id"]= 1 @@ -59,71 +94,3 @@ def rpc_get_usdc_coins(url, params, method="suix_getCoins"): result=json.loads(response.text) return result["result"] -""" - -payload = json.dumps({ - "jsonrpc": "2.0", - "id": 5, - "method": "sui_executeTransactionBlock", - "params": [ - "AAADAQGPzuAZV5krLKJWD1WUXOjk7Guz2vki2pBMZJ6CXkRf1XLGgQAAAAAAAQAgH/qFdX+Vzs7ShiLTDkGkUsiFFt9TRQyxkTgS3YKNWWgAEOgDAAAAAAAAAAAAAAAAAAABAF82iNaL7Cly31h0P767ErFoKbQb8bxQeNNRAJDvbPWOC21hcmdpbl9iYW5rEndpdGhkcmF3X2Zyb21fYmFuawADAQAAAQEAAQIAH/qFdX+Vzs7ShiLTDkGkUsiFFt9TRQyxkTgS3YKNWWgBWiybg/9fRf7zXUmsdBU3umIFeucEZNWeMGzlLttPf86tHg8AAAAAACA3qZfzxP1+yVILtVkJ6LdfZvkF7gK877AJco9Xook9Th/6hXV/lc7O0oYi0w5BpFLIhRbfU0UMsZE4Et2CjVlo6AMAAAAAAAAA4fUFAAAAAAA=", - [ - "ANyIBWjL6U9T6qBoWWTc18qzVViytirDmwX+dOEqd77dibe0tgLcziDZpe3XoTRVbBJGUV9TIHCN2C21aNvUTA/JFlIyQTT87zRFBPBubLG+G22kP5UDgk3kIg8JPeUiBw==" - ], - { - "showInput": True, - "showEffects": True, - "showEvents": True, - "showObjectChanges": True - }, - "WaitForLocalExecution" - ] -}) -headers = { - 'Content-Type': 'application/json' -} - -response = requests.request("POST", url, headers=headers, data=payload) - -print(response.text) - - -""" - - - - - - - - -""" -url = "https://fullnode.testnet.sui.io:443" - -payload = json.dumps({ - "jsonrpc": "2.0", - "id": 1689764924887, - "method": "unsafe_moveCall", - "params": [ - "0x1ffa85757f95ceced28622d30e41a452c88516df53450cb1913812dd828d5968", - "0x5f3688d68bec2972df58743fbebb12b16829b41bf1bc5078d3510090ef6cf58e", - "margin_bank", - "withdraw_from_bank", - [], - [ - "0x8fcee01957992b2ca2560f55945ce8e4ec6bb3daf922da904c649e825e445fd5", - "0x1ffa85757f95ceced28622d30e41a452c88516df53450cb1913812dd828d5968", - "1000" - ], - "0x5a2c9b83ff5f45fef35d49ac741537ba62057ae70464d59e306ce52edb4f7fce", - "100000000" - ] -}) -headers = { - 'Content-Type': 'application/json' -} - -response = requests.request("POST", url, headers=headers, data=payload) - -print(response.text) -""" \ No newline at end of file diff --git a/src/bluefin_client_sui/utilities.py b/src/bluefin_client_sui/utilities.py index 77abeeb..42e1e72 100644 --- a/src/bluefin_client_sui/utilities.py +++ b/src/bluefin_client_sui/utilities.py @@ -5,7 +5,7 @@ import bip_utils import hashlib from typing import Union -from .constants import SUI_BASE_NUM, DAPI_BASE_NUM +from .constants import SUI_BASE_NUM, DAPI_BASE_NUM, CONTRACTS_BASE_NUM def toDapiBase(number: Union[int, float])->int: return int(number*DAPI_BASE_NUM) @@ -13,8 +13,12 @@ def toDapiBase(number: Union[int, float])->int: def fromDapiBase(number: Union[int, float], dtype=int)-> int: return dtype(number/DAPI_BASE_NUM) -def toSuiBase(number: Union[int,float]) -> int: - return int(number*SUI_BASE_NUM) +def toSuiBase(number: Union[int,float], base=SUI_BASE_NUM) -> int: + return int(number*base) + +def fromSuiBase(number: Union[str,int], base=SUI_BASE_NUM)-> float: + number=float(number) + return number/float(base) def numberToHex(num, pad=32): diff --git a/src/check.py b/src/check.py deleted file mode 100644 index cc76e9c..0000000 --- a/src/check.py +++ /dev/null @@ -1,31 +0,0 @@ -from bluefin_exchange_client_sui import FireflyClient, Networks -from pprint import pprint -import asyncio -TEST_ACCT_KEY="!#12" -TEST_NETWORK="SUI_STAGING" - - -async def main(): - # initialize client - client = FireflyClient( - True, # agree to terms and conditions - Networks[TEST_NETWORK], # network to connect with - TEST_ACCT_KEY, # private key of wallet - ) - - # Initializing client for the private key provided. The second argument api_token is optional - await client.init(True) - - print('Account Address:', client.get_public_address()) - - # # gets user account data on-chain - data = await client.get_user_account_data() - - await client.close_connections() - - pprint(data) - -if __name__ == "__main__": - loop = asyncio.new_event_loop() - loop.run_until_complete(main()) - loop.close() \ No newline at end of file