From d8431bcefad3eeaca058f2d159d6ffa191fa0795 Mon Sep 17 00:00:00 2001 From: ibadia Date: Fri, 25 Aug 2023 11:59:47 +0500 Subject: [PATCH 1/5] adding sub account --- examples/11.sub_accounts.py | 12 ++- src/bluefin_client_sui/client.py | 148 ++++++++++++++++++---------- src/bluefin_client_sui/constants.py | 2 +- src/bluefin_client_sui/contracts.py | 8 ++ src/bluefin_client_sui/rpc.py | 2 +- src/bluefin_client_sui/utilities.py | 4 + 6 files changed, 119 insertions(+), 57 deletions(-) diff --git a/examples/11.sub_accounts.py b/examples/11.sub_accounts.py index 651bc72..d0a8e3a 100644 --- a/examples/11.sub_accounts.py +++ b/examples/11.sub_accounts.py @@ -1,6 +1,9 @@ +import sys,os +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 +19,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/src/bluefin_client_sui/client.py b/src/bluefin_client_sui/client.py index b95dd09..15501eb 100644 --- a/src/bluefin_client_sui/client.py +++ b/src/bluefin_client_sui/client.py @@ -31,6 +31,7 @@ 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): @@ -362,9 +363,14 @@ async def deposit_margin_to_bank(self, amount: int, coin_id: str)-> bool: callArgs.append(self.account.getUserAddress()) callArgs.append(str(amount)) 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) @@ -386,7 +392,7 @@ async def withdraw_margin_from_bank(self, amount): account_address=self.account.getUserAddress() callArgs=[bank_id, account_address, str(amount)] - txBytes=rpc_unsafe_moveCall("https://fullnode.testnet.sui.io:443", + txBytes=rpc_unsafe_moveCall(self.url, callArgs, "withdraw_from_bank", "margin_bank", @@ -394,7 +400,7 @@ 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) @@ -407,7 +413,7 @@ async def withdraw_all_margin_from_bank(self): 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,7 +421,7 @@ 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) @@ -464,7 +470,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=""): """ 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 +486,124 @@ 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) - + callArgs = [] + callArgs.append(self.contracts.get_perpetual_id()) + 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==MARGIN_TYPE.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) + rpc_sui_executeTransactionBlock("",txBytes, signature) + return True - 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: + 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 fromSuiBase(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))) diff --git a/src/bluefin_client_sui/constants.py b/src/bluefin_client_sui/constants.py index 610349d..11a29b1 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", diff --git a/src/bluefin_client_sui/contracts.py b/src/bluefin_client_sui/contracts.py index 2e8d204..6a35bee 100644 --- a/src/bluefin_client_sui/contracts.py +++ b/src/bluefin_client_sui/contracts.py @@ -9,6 +9,14 @@ def set_contract_addresses(self,contract_address,market=None,name=None): self.contract_addresses["auxiliaryContractsAddresses"]=contract_address['auxiliaryContractsAddresses'] self.contract_addresses[market]=contract_address[market.value] + 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): + return self.contract_addresses[market]['PriceOracle']['id'] def get_perpetual_id(self, market: MARKET_SYMBOLS=MARKET_SYMBOLS.ETH): return self.contract_addresses[market]['Perpetual']['id'] diff --git a/src/bluefin_client_sui/rpc.py b/src/bluefin_client_sui/rpc.py index 2afb631..0a51af7 100644 --- a/src/bluefin_client_sui/rpc.py +++ b/src/bluefin_client_sui/rpc.py @@ -46,7 +46,7 @@ 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"): base_dict={} base_dict["jsonrpc"]="2.0" base_dict["id"]= 1 diff --git a/src/bluefin_client_sui/utilities.py b/src/bluefin_client_sui/utilities.py index 77abeeb..10d2942 100644 --- a/src/bluefin_client_sui/utilities.py +++ b/src/bluefin_client_sui/utilities.py @@ -16,6 +16,10 @@ def fromDapiBase(number: Union[int, float], dtype=int)-> int: def toSuiBase(number: Union[int,float]) -> int: return int(number*SUI_BASE_NUM) +def fromSuiBase(number: Union[str,int])-> float: + number=float(number) + return number/float(SUI_BASE_NUM) + def numberToHex(num, pad=32): #converting number to Hexadecimal format From a1a686facd59f2e33a4fb7413580851c1d3ea264 Mon Sep 17 00:00:00 2001 From: ibadia Date: Fri, 25 Aug 2023 13:01:03 +0500 Subject: [PATCH 2/5] adding adjusting leverage --- examples/20.contract_call.py | 18 +++++-- examples/4.placing_orders.py | 13 +---- examples/5.adjusting_leverage.py | 13 ++++- examples/6.adjusting_margin.py | 79 +++++++++++++++++++++++++++-- src/bluefin_client_sui/client.py | 42 ++++++++------- src/bluefin_client_sui/contracts.py | 2 +- 6 files changed, 127 insertions(+), 40 deletions(-) diff --git a/examples/20.contract_call.py b/examples/20.contract_call.py index ddd9967..9277d37 100644 --- a/examples/20.contract_call.py +++ b/examples/20.contract_call.py @@ -21,15 +21,27 @@ async def main(): ### the below functions just gets usdc coins that you have. usdc_coins=client.get_usdc_coins() - coin_obj_id=usdc_coins["data"][0]["coinObjectId"] + coin_obj_id=usdc_coins["data"][1]["coinObjectId"] await client.deposit_margin_to_bank(1000, coin_obj_id) - await client.withdraw_margin_from_bank(100) + #await client.withdraw_margin_from_bank(100) - await client.withdraw_all_margin_from_bank() + #await client.withdraw_all_margin_from_bank() + print ("Printing Margin Bank balance") + print (await client.get_margin_bank_balance()) + + print ("Printing usdc balance") + print (await client.get_usdc_balance()) + + print ("Printing SUI balance") + print (await client.get_native_chain_token_balance()) + + + print ("getting usdc coins") + print (client.get_usdc_coins()) diff --git a/examples/4.placing_orders.py b/examples/4.placing_orders.py index da48268..6ca074e 100644 --- a/examples/4.placing_orders.py +++ b/examples/4.placing_orders.py @@ -42,19 +42,8 @@ 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) - # 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", price = toSuiBase(0), quantity = toSuiBase(1), leverage = toSuiBase(1), @@ -96,7 +85,7 @@ async def main(): client.add_market(MARKET_SYMBOLS.ETH) # await place_limit_order(client) - await place_market_order(client) + await (client) await place_limit_order(client) await client.close_connections() diff --git a/examples/5.adjusting_leverage.py b/examples/5.adjusting_leverage.py index 0734be3..52d185a 100644 --- a/examples/5.adjusting_leverage.py +++ b/examples/5.adjusting_leverage.py @@ -12,10 +12,11 @@ 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) + await client.init(True, symbol= MARKET_SYMBOLS.BTC) print('Leverage on BTC market:', await client.get_user_leverage(MARKET_SYMBOLS.BTC)) # we have a position on BTC so this will perform on-chain leverage update @@ -24,6 +25,14 @@ async def main(): print('Leverage on BTC market:', await client.get_user_leverage(MARKET_SYMBOLS.BTC)) + # 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, symbol=MARKET_SYMBOLS.ETH) print('Leverage on ETH market:', await client.get_user_leverage(MARKET_SYMBOLS.ETH)) # since we don't have a position on-chain, it will perform off-chain leverage adjustment diff --git a/examples/6.adjusting_margin.py b/examples/6.adjusting_margin.py index a2f6db8..096c554 100644 --- a/examples/6.adjusting_margin.py +++ b/examples/6.adjusting_margin.py @@ -3,17 +3,86 @@ 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 +92,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/src/bluefin_client_sui/client.py b/src/bluefin_client_sui/client.py index 15501eb..4dcc3b5 100644 --- a/src/bluefin_client_sui/client.py +++ b/src/bluefin_client_sui/client.py @@ -346,7 +346,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 @@ -356,7 +356,7 @@ async def deposit_margin_to_bank(self, amount: int, coin_id: str)-> bool: Returns: Boolean: true if amount is successfully deposited, false otherwise """ - package_id=self.contracts.get_package_id() + package_id=self.contracts.get_package_id(market=market) user_address=self.account.getUserAddress() callArgs=[] callArgs.append(self.contracts.get_bank_id()) @@ -377,7 +377,7 @@ async def deposit_margin_to_bank(self, amount: int, coin_id: str)-> bool: return res - async def withdraw_margin_from_bank(self, amount): + async def withdraw_margin_from_bank(self, amount, market=MARKET_SYMBOLS.ETH): """ Withdraws given amount of usdc from margin bank if possible @@ -397,7 +397,7 @@ async def withdraw_margin_from_bank(self, amount): "withdraw_from_bank", "margin_bank", self.account.getUserAddress(), - self.contracts.get_package_id() + self.contracts.get_package_id(market=market) ) signature=self.contract_signer.sign_tx(txBytes, self.account) res=rpc_sui_executeTransactionBlock(self.url, @@ -406,7 +406,7 @@ async def withdraw_margin_from_bank(self, amount): return res - async def withdraw_all_margin_from_bank(self): + async def withdraw_all_margin_from_bank(self, market=MARKET_SYMBOLS.ETH): bank_id=self.contracts.get_bank_id() account_address=self.account.getUserAddress() perp_id=self.contracts.get_perpetual_id() @@ -418,7 +418,7 @@ async def withdraw_all_margin_from_bank(self): "withdraw_all_margin_from_bank", "margin_bank", self.account.getUserAddress(), - self.contracts.get_package_id() + self.contracts.get_package_id(market=market) ) signature=self.contract_signer.sign_tx(txBytes, self.account) res=rpc_sui_executeTransactionBlock(self.url, @@ -447,14 +447,22 @@ 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.value)) + txBytes=rpc_unsafe_moveCall(self.url, + callArgs, + "adjust_leverage", + "exchange", + self.account.getUserAddress(), + self.contracts.get_package_id(market=symbol)) + signature=self.contract_signer.sign_tx(txBytes, self.account) + result=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) + return result else: await self.apis.post( @@ -498,7 +506,7 @@ async def adjust_margin(self, symbol: MARKET_SYMBOLS, operation: ADJUST_MARGIN, callArgs.append(self.account.getUserAddress()) callArgs.append(str(amount)) callArgs.append(self.contracts.get_price_oracle_object_id(symbol)) - if operation==MARGIN_TYPE.ADD: + if operation==ADJUST_MARGIN.ADD: txBytes=rpc_unsafe_moveCall(self.url, callArgs, "add_margin", @@ -515,7 +523,7 @@ async def adjust_margin(self, symbol: MARKET_SYMBOLS, operation: ADJUST_MARGIN, self.contracts.get_package_id()) signature=self.contract_signer.sign_tx(txBytes, self.account) - rpc_sui_executeTransactionBlock("",txBytes, signature) + result=rpc_sui_executeTransactionBlock(self.url,txBytes, signature) return True @@ -547,7 +555,7 @@ async def update_sub_account(self, sub_account_address: str, status: bool) -> bo if result['result']['effects']['status']['status']=='success': return True else: - False + return False async def get_native_chain_token_balance(self)-> float: """ diff --git a/src/bluefin_client_sui/contracts.py b/src/bluefin_client_sui/contracts.py index 6a35bee..75c1936 100644 --- a/src/bluefin_client_sui/contracts.py +++ b/src/bluefin_client_sui/contracts.py @@ -26,7 +26,7 @@ def get_package_id(self, market: MARKET_SYMBOLS=MARKET_SYMBOLS.ETH): 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=""): """ From 75c2991463dd7c06d458fb00ad553e1407907194 Mon Sep 17 00:00:00 2001 From: ibadia Date: Mon, 28 Aug 2023 09:25:16 +0500 Subject: [PATCH 3/5] more contract changes --- CHANGES.md | 2 ++ examples/1.initialization.py | 2 ++ examples/3.balance.py | 15 ++++++-- examples/4.placing_orders.py | 10 +++--- examples/5.adjusting_leverage.py | 10 +----- examples/7.cancelling_orders.py | 7 ++-- src/bluefin_client_sui/client.py | 56 ++++++++++++++++------------- src/bluefin_client_sui/constants.py | 3 +- src/bluefin_client_sui/contracts.py | 17 +++++---- src/bluefin_client_sui/utilities.py | 10 +++--- 10 files changed, 73 insertions(+), 59 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 86191d9..ff68ae4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -73,3 +73,5 @@ 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 BASE 6 but when we see balance it is in base9. internally the functions are implemented that way. \ No newline at end of file diff --git a/examples/1.initialization.py b/examples/1.initialization.py index b37edc0..7c4b6dd 100644 --- a/examples/1.initialization.py +++ b/examples/1.initialization.py @@ -6,6 +6,8 @@ from config import TEST_ACCT_KEY, TEST_NETWORK +import sys,os +sys.path.append(os.getcwd()+"/src/") from bluefin_client_sui import FireflyClient, Networks from pprint import pprint import asyncio diff --git a/examples/3.balance.py b/examples/3.balance.py index 93a51ed..d033655 100644 --- a/examples/3.balance.py +++ b/examples/3.balance.py @@ -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 6ca074e..3336bf5 100644 --- a/examples/4.placing_orders.py +++ b/examples/4.placing_orders.py @@ -40,10 +40,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) signature_request = OrderSignatureRequest( - symbol=MARKET_SYMBOLS.ETH, + symbol=MARKET_SYMBOLS.BTC, price = toSuiBase(0), quantity = toSuiBase(1), leverage = toSuiBase(1), @@ -51,7 +51,6 @@ async def place_market_order(client: FireflyClient): reduceOnly = False, postOnly = False, orderbookOnly = True, - maker = "0xa3c3504d90c428274beaa89f1238a769ea1d1c3516c31c0f4157f33787367af0", expiration = 1700530261000, salt = 1668690862116, orderType = ORDER_TYPE.MARKET, @@ -82,10 +81,11 @@ 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 (client) + await place_market_order(client) + #await (client) await place_limit_order(client) await client.close_connections() diff --git a/examples/5.adjusting_leverage.py b/examples/5.adjusting_leverage.py index 52d185a..35f9811 100644 --- a/examples/5.adjusting_leverage.py +++ b/examples/5.adjusting_leverage.py @@ -16,7 +16,7 @@ async def main(): ) - await client.init(True, symbol= MARKET_SYMBOLS.BTC) + await client.init(True) print('Leverage on BTC market:', await client.get_user_leverage(MARKET_SYMBOLS.BTC)) # we have a position on BTC so this will perform on-chain leverage update @@ -25,14 +25,6 @@ async def main(): print('Leverage on BTC market:', await client.get_user_leverage(MARKET_SYMBOLS.BTC)) - # 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, symbol=MARKET_SYMBOLS.ETH) print('Leverage on ETH market:', await client.get_user_leverage(MARKET_SYMBOLS.ETH)) # since we don't have a position on-chain, it will perform off-chain leverage adjustment diff --git a/examples/7.cancelling_orders.py b/examples/7.cancelling_orders.py index e29ca6b..720c82b 100644 --- a/examples/7.cancelling_orders.py +++ b/examples/7.cancelling_orders.py @@ -14,14 +14,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/src/bluefin_client_sui/client.py b/src/bluefin_client_sui/client.py index 4dcc3b5..0103756 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 * @@ -34,15 +34,16 @@ def __init__(self, are_terms_accepted, network, private_key=""): 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) + #await self.set_contracts_for_all_markets() + 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 @@ -56,6 +57,11 @@ async def init(self, user_onboarding=True, api_token="", symbol:MARKET_SYMBOLS=M self.socket.set_token(self.apis.auth_token) self.webSocketClient.set_token(self.apis.auth_token) + async def set_contracts_for_all_markets(self): + for symbol in MARKET_SYMBOLS: + self.contracts.contract_addresses = await self.get_contract_addresses(symbol) + self.contracts.set_contract_addresses(self.contracts.contract_addresses, market=symbol) + async def onboard_user(self, token:str=None): """ @@ -356,12 +362,12 @@ async def deposit_margin_to_bank(self, amount: int, coin_id: str, market=MARKET_ Returns: Boolean: true if amount is successfully deposited, false otherwise """ - package_id=self.contracts.get_package_id(market=market) + package_id=self.contracts.get_package_id() user_address=self.account.getUserAddress() 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(self.url, callArgs, @@ -374,8 +380,8 @@ async def deposit_margin_to_bank(self, amount: int, coin_id: str, market=MARKET_ txBytes, signature) + return res['result']['effects']['status']['status'] - return res async def withdraw_margin_from_bank(self, amount, market=MARKET_SYMBOLS.ETH): """ @@ -391,20 +397,20 @@ async def withdraw_margin_from_bank(self, amount, market=MARKET_SYMBOLS.ETH): bank_id=self.contracts.get_bank_id() account_address=self.account.getUserAddress() - callArgs=[bank_id, account_address, str(amount)] + callArgs=[bank_id, account_address, str(toSuiBase(amount, base=CONTRACTS_BASE_NUM))] txBytes=rpc_unsafe_moveCall(self.url, callArgs, "withdraw_from_bank", "margin_bank", self.account.getUserAddress(), - self.contracts.get_package_id(market=market) + self.contracts.get_package_id() ) signature=self.contract_signer.sign_tx(txBytes, self.account) res=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) - return res + return res['result']['effects']['status']['status'] async def withdraw_all_margin_from_bank(self, market=MARKET_SYMBOLS.ETH): bank_id=self.contracts.get_bank_id() @@ -418,14 +424,14 @@ async def withdraw_all_margin_from_bank(self, market=MARKET_SYMBOLS.ETH): "withdraw_all_margin_from_bank", "margin_bank", self.account.getUserAddress(), - self.contracts.get_package_id(market=market) + self.contracts.get_package_id() ) signature=self.contract_signer.sign_tx(txBytes, self.account) res=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) - return res + return res['result']['effects']['status']['status'] async def adjust_leverage(self, symbol, leverage, parentAddress:str=""): @@ -453,13 +459,13 @@ async def adjust_leverage(self, symbol, leverage, parentAddress:str=""): 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.value)) + 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(market=symbol)) + self.contracts.get_package_id()) signature=self.contract_signer.sign_tx(txBytes, self.account) result=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) return result @@ -478,7 +484,7 @@ async def adjust_leverage(self, symbol, leverage, parentAddress:str=""): return True - async def adjust_margin(self, symbol: MARKET_SYMBOLS, operation: ADJUST_MARGIN, amount: str, 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 @@ -499,7 +505,7 @@ async def adjust_margin(self, symbol: MARKET_SYMBOLS, operation: ADJUST_MARGIN, raise(Exception("User has no open position on market: {}".format(symbol))) else: callArgs = [] - callArgs.append(self.contracts.get_perpetual_id()) + callArgs.append(self.contracts.get_perpetual_id(symbol)) callArgs.append(self.contracts.get_bank_id()) callArgs.append(self.contracts.get_sub_account_id()) @@ -524,8 +530,10 @@ async def adjust_margin(self, symbol: MARKET_SYMBOLS, operation: ADJUST_MARGIN, signature=self.contract_signer.sign_tx(txBytes, self.account) result=rpc_sui_executeTransactionBlock(self.url,txBytes, signature) - - return True + if result['result']['effects']['status']['status']=='success': + return True + else: + return False async def update_sub_account(self, sub_account_address: str, status: bool) -> bool: @@ -591,7 +599,7 @@ async def get_usdc_balance(self)-> float: 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 fromSuiBase(result) + return float(result) except Exception as e: raise(Exception("Failed to get balance, Exception: {}".format(e))) @@ -808,19 +816,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 11a29b1..d092e8b 100644 --- a/src/bluefin_client_sui/constants.py +++ b/src/bluefin_client_sui/constants.py @@ -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 75c1936..aaa6840 100644 --- a/src/bluefin_client_sui/contracts.py +++ b/src/bluefin_client_sui/contracts.py @@ -5,9 +5,8 @@ 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_sub_account_id(self): return self.contract_addresses['auxiliaryContractsAddresses']['objects']['SubAccounts']['id'] @@ -15,14 +14,14 @@ def get_sub_account_id(self): def get_bank_table_id(self): return self.contract_addresses['auxiliaryContractsAddresses']['objects']['BankTable']['id'] - def get_price_oracle_object_id(self, market): - return self.contract_addresses[market]['PriceOracle']['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=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_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'] diff --git a/src/bluefin_client_sui/utilities.py b/src/bluefin_client_sui/utilities.py index 10d2942..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,12 +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])-> float: +def fromSuiBase(number: Union[str,int], base=SUI_BASE_NUM)-> float: number=float(number) - return number/float(SUI_BASE_NUM) + return number/float(base) def numberToHex(num, pad=32): From 2f3881d020ad587f5da1b03a80a83359a292c038 Mon Sep 17 00:00:00 2001 From: ibadia Date: Mon, 28 Aug 2023 09:57:37 +0500 Subject: [PATCH 4/5] making examples clear --- CHANGES.md | 19 +++++- examples/1.initialization.py | 12 +--- examples/10.1.socket_readonly.py | 3 +- examples/10.sockets.py | 4 +- examples/11.sub_accounts.py | 4 +- examples/12.open_order_event.py | 4 +- examples/13.orderbook_updates.py | 4 +- examples/14.web_sockets.py | 5 +- examples/15.get_funding_history.py | 4 +- .../16.listening_events_using_sub_account.py | 4 ++ examples/17.1.get_orders_readonly.py | 4 +- examples/17.get_orders.py | 4 +- examples/18.dms_api.py | 4 +- examples/19.Generate_readonly_token.py | 4 +- examples/2.user_info.py | 4 +- examples/20.contract_call.py | 58 ------------------- examples/3.balance.py | 4 +- examples/4.placing_orders.py | 5 +- examples/5.adjusting_leverage.py | 4 +- examples/6.adjusting_margin.py | 4 +- examples/7.cancelling_orders.py | 6 +- examples/8.exchange_data.py | 4 +- examples/9.user_data.py | 4 +- examples/contract_call.py | 52 ----------------- src/check.py | 31 ---------- 25 files changed, 81 insertions(+), 174 deletions(-) delete mode 100644 examples/20.contract_call.py delete mode 100644 examples/contract_call.py delete mode 100644 src/check.py diff --git a/CHANGES.md b/CHANGES.md index ff68ae4..96be085 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -74,4 +74,21 @@ #then we finally sign the hash ``` ## Margin Bank: -1. When you insert money to margin bank we give it in BASE 6 but when we see balance it is in base9. internally the functions are implemented that way. \ No newline at end of file +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 7c4b6dd..dce1244 100644 --- a/examples/1.initialization.py +++ b/examples/1.initialization.py @@ -1,13 +1,7 @@ -import os -import sys - -print (os.getcwd()) -sys.path.append(os.getcwd()+"/src/") - -from config import TEST_ACCT_KEY, TEST_NETWORK - 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 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 d0a8e3a..4ed2883 100644 --- a/examples/11.sub_accounts.py +++ b/examples/11.sub_accounts.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_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/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 9277d37..0000000 --- a/examples/20.contract_call.py +++ /dev/null @@ -1,58 +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"][1]["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() - - print ("Printing Margin Bank balance") - print (await client.get_margin_bank_balance()) - - print ("Printing usdc balance") - print (await client.get_usdc_balance()) - - print ("Printing SUI balance") - print (await client.get_native_chain_token_balance()) - - - print ("getting usdc coins") - print (client.get_usdc_coins()) - - - - - - 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 d033655..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 diff --git a/examples/4.placing_orders.py b/examples/4.placing_orders.py index 3336bf5..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 @@ -85,7 +87,6 @@ async def main(): client.add_market(MARKET_SYMBOLS.ETH) await place_market_order(client) - #await (client) await place_limit_order(client) await client.close_connections() diff --git a/examples/5.adjusting_leverage.py b/examples/5.adjusting_leverage.py index 35f9811..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 diff --git a/examples/6.adjusting_margin.py b/examples/6.adjusting_margin.py index 096c554..6519ffb 100644 --- a/examples/6.adjusting_margin.py +++ b/examples/6.adjusting_margin.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, ADJUST_MARGIN diff --git a/examples/7.cancelling_orders.py b/examples/7.cancelling_orders.py index 720c82b..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 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/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 From 7af02cf8d4336e75e650265d832014fdbd630635 Mon Sep 17 00:00:00 2001 From: ibadia Date: Mon, 28 Aug 2023 10:01:12 +0500 Subject: [PATCH 5/5] final changes --- requirements.in | 3 + src/bluefin_client_sui/client.py | 72 +++++++++------------ src/bluefin_client_sui/rpc.py | 103 +++++++++++-------------------- 3 files changed, 68 insertions(+), 110 deletions(-) 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 0103756..3ab96de 100644 --- a/src/bluefin_client_sui/client.py +++ b/src/bluefin_client_sui/client.py @@ -41,7 +41,6 @@ async def init(self, user_onboarding=True, api_token=""): 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 """ - #await self.set_contracts_for_all_markets() self.contracts.contract_addresses = await self.get_contract_addresses() self.contracts.set_contract_addresses(self.contracts.contract_addresses) @@ -56,12 +55,7 @@ async def init(self, user_onboarding=True, api_token=""): 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 set_contracts_for_all_markets(self): - for symbol in MARKET_SYMBOLS: - self.contracts.contract_addresses = await self.get_contract_addresses(symbol) - self.contracts.set_contract_addresses(self.contracts.contract_addresses, market=symbol) - + async def onboard_user(self, token:str=None): """ @@ -121,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): """ @@ -380,10 +349,13 @@ async def deposit_margin_to_bank(self, amount: int, coin_id: str, market=MARKET_ txBytes, signature) - return res['result']['effects']['status']['status'] + if res['result']['effects']['status']['status']=='success': + return True + else: + return False - async def withdraw_margin_from_bank(self, amount, market=MARKET_SYMBOLS.ETH): + 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 @@ -410,13 +382,23 @@ async def withdraw_margin_from_bank(self, amount, market=MARKET_SYMBOLS.ETH): txBytes, signature) - return res['result']['effects']['status']['status'] + if res['result']['effects']['status']['status']=='success': + return True + else: + return False - async def withdraw_all_margin_from_bank(self, market=MARKET_SYMBOLS.ETH): + async def withdraw_all_margin_from_bank(self) -> bool: + """ + Withdraws everything of usdc from margin bank + + 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(self.url, @@ -431,10 +413,13 @@ async def withdraw_all_margin_from_bank(self, market=MARKET_SYMBOLS.ETH): txBytes, signature) - return res['result']['effects']['status']['status'] + 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 @@ -453,7 +438,7 @@ 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 != {}): - callArgs = []; + callArgs = [] callArgs.append(self.contracts.get_perpetual_id(symbol)) callArgs.append(self.contracts.get_bank_id()) callArgs.append(self.contracts.get_sub_account_id()) @@ -468,7 +453,10 @@ async def adjust_leverage(self, symbol, leverage, parentAddress:str=""): self.contracts.get_package_id()) signature=self.contract_signer.sign_tx(txBytes, self.account) result=rpc_sui_executeTransactionBlock(self.url, txBytes, signature) - return result + if result['result']['effects']['status']['status']=='success': + return True + else: + return False else: await self.apis.post( diff --git a/src/bluefin_client_sui/rpc.py b/src/bluefin_client_sui/rpc.py index 0a51af7..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 @@ -47,6 +75,13 @@ def rpc_sui_executeTransactionBlock(url, txBytes, signature): 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_call_sui_function(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