def handler_change_mainnet(self,is_enabled): global client if is_enabled: client = TonClient(network={'server_address': MAINNET_BASE_URL}, abi={'message_expiration_timeout': 30000}) self.wrapper = TonWrapper({'server_address': MAINNET_BASE_URL}) else: client = TonClient(network={'server_address': DEVNET_BASE_URL}, abi={'message_expiration_timeout': 30000}) self.wrapper = TonWrapper({'server_address': DEVNET_BASE_URL}) self.update_balance()
class TestTonClientAsyncCore(unittest.TestCase): def setUp(self) -> None: self.client = TonClient(network={'server_address': DEVNET_BASE_URL}) def test_version(self): self.assertEqual(LIB_VERSION, self.client.version()) def test_get_api_reference(self): reference = self.client.get_api_reference() self.assertEqual(LIB_VERSION, reference['version']) def test_build_info(self): info = self.client.build_info() self.assertIsInstance(info, dict) def test_destroy_context(self): self.client.destroy_context()
class TestTonClientSyncCore(unittest.TestCase): """ Sync core is not recommended to use """ def setUp(self) -> None: config = ClientConfig() config.network.server_address = DEVNET_BASE_URL self.client = TonClient(config=config, is_core_async=False) def test_version(self): self.assertEqual(LIB_VERSION, self.client.version().version) def test_get_api_reference(self): reference = self.client.get_api_reference() self.assertGreater(len(reference.api['modules']), 0) def test_build_info(self): info = self.client.build_info() self.assertNotEqual(None, info.build_number) def test_destroy_context(self): self.client.destroy_context()
class TestTonClientAsyncCore(unittest.TestCase): def setUp(self) -> None: config = ClientConfig() config.network.server_address = DEVNET_BASE_URL self.client = TonClient(config=config) def test_version(self): result = self.client.version() self.assertEqual(LIB_VERSION, result.version) def test_get_api_reference(self): reference = self.client.get_api_reference() self.assertGreater(len(reference.api['modules']), 0) self.assertEqual(LIB_VERSION, reference.api['version']) def test_build_info(self): info = self.client.build_info() self.assertNotEqual(None, info.build_number) def test_destroy_context(self): self.client.destroy_context()
def test_suspend_resume(self): # Data for contract deployment keypair = async_custom_client.crypto.generate_random_sign_keys() abi = Abi.from_path(path=os.path.join(SAMPLES_DIR, 'Hello.abi.json')) with open(os.path.join(SAMPLES_DIR, 'Hello.tvc'), 'rb') as fp: tvc = base64.b64encode(fp.read()).decode() signer = Signer.Keys(keys=keypair) deploy_set = DeploySet(tvc=tvc) call_set = CallSet(function_name='constructor') # Prepare deployment params encode_params = ParamsOfEncodeMessage( abi=abi, signer=signer, deploy_set=deploy_set, call_set=call_set) encode = async_custom_client.abi.encode_message(params=encode_params) # Subscribe for address deploy transaction status transactions = [] def __callback(response_data, response_type, *args): if response_type == SubscriptionResponseType.OK: result = ResultOfSubscription(**response_data) transactions.append(result.result) self.assertEqual(encode.address, result.result['account_addr']) if response_type == SubscriptionResponseType.ERROR: logging.info(ClientError(**response_data).__str__()) subscribe_params = ParamsOfSubscribeCollection( collection='transactions', result='id account_addr', filter={'account_addr': {'eq': encode.address}, 'status_name': {'eq': 'Finalized'}}) subscribe = async_custom_client.net.subscribe_collection( params=subscribe_params, callback=__callback) # Send grams to new account to create first transaction send_grams(address=encode.address) # Give some time for subscription to receive all data time.sleep(2) # Suspend subscription async_custom_client.net.suspend() time.sleep(2) # Wait a bit for suspend # Deploy to create second transaction. # Use another client, because of error: Fetch first block failed: # Can not use network module since it is suspended second_config = ClientConfig() second_config.network.server_address = CUSTOM_BASE_URL second_client = TonClient(config=second_config) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) second_client.processing.process_message(params=process_params) second_client.destroy_context() # Check that second transaction is not received when # subscription suspended self.assertEqual(1, len(transactions)) # Resume subscription async_custom_client.net.resume() time.sleep(2) # Wait a bit for resume # Run contract function to create third transaction call_set = CallSet(function_name='touch') encode_params = ParamsOfEncodeMessage( abi=abi, signer=signer, address=encode.address, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_custom_client.processing.process_message(params=process_params) # Give some time for subscription to receive all data time.sleep(2) # Check that third transaction is now received after resume self.assertEqual(2, len(transactions)) self.assertNotEqual(transactions[0]['id'], transactions[1]['id']) # Unsubscribe async_custom_client.net.unsubscribe(params=subscribe)
def setUp(self) -> None: self.client = TonClient(network={'server_address': DEVNET_BASE_URL})
def setUp(self) -> None: self.client = TonClient(network={'server_address': DEVNET_BASE_URL}, is_core_async=False)
def setUp(self) -> None: client_config = ClientConfig() client_config.network.server_address = DEVNET_BASE_URL self.client = TonClient(config=client_config, is_async=True)
class TestTonClientAsync(unittest.TestCase): def setUp(self) -> None: client_config = ClientConfig() client_config.network.server_address = DEVNET_BASE_URL self.client = TonClient(config=client_config, is_async=True) def test_version(self): # Client async def __main(): result = await self.client.version() self.assertEqual(LIB_VERSION, result.version) asyncio.get_event_loop().run_until_complete(__main()) def test_gathering(self): # Some modules async def __main(): mnemonics, keypairs = await asyncio.gather( __coro_mnemonics(), __coro_keypairs()) self.assertEqual(10, len(mnemonics)) self.assertEqual(10, len(keypairs)) async def __coro_mnemonics(): mnemonics = [] while len(mnemonics) < 10: params = ParamsOfMnemonicFromRandom() mnemonic = await self.client.crypto.mnemonic_from_random( params=params) mnemonics.append(mnemonic) logging.info(f'[Mnemonic coro] {mnemonic.phrase}') return mnemonics async def __coro_keypairs(): keypairs = [] while len(keypairs) < 10: keypair = await self.client.crypto.generate_random_sign_keys() keypairs.append(keypair) logging.info(f'[Keypair coro] {keypair.public}') return keypairs asyncio.get_event_loop().run_until_complete(__main()) def test_register_signing_box(self): # Crypto async def __main(): keys = await self.client.crypto.generate_random_sign_keys() keys_box_handle = await self.client.crypto.get_signing_box( params=keys) def __callback(response_data, _, loop): request = ParamsOfAppRequest(**response_data) box_params = ParamsOfAppSigningBox.from_dict( data=request.request_data) box_result = None if isinstance(box_params, ParamsOfAppSigningBox.GetPublicKey): # Run thread safe coroutine and wait for result future = self.client.crypto.signing_box_get_public_key( params=keys_box_handle) future = asyncio.run_coroutine_threadsafe( coro=future, loop=loop) _result = future.result() # Resolve params box_result = ResultOfAppSigningBox.GetPublicKey( public_key=_result.pubkey) if isinstance(box_params, ParamsOfAppSigningBox.Sign): # Run thread safe coroutine and wait for result params = ParamsOfSigningBoxSign( signing_box=keys_box_handle.handle, unsigned=box_params.unsigned) future = self.client.crypto.signing_box_sign(params=params) future = asyncio.run_coroutine_threadsafe( coro=future, loop=loop) _result = future.result() # Resolve params box_result = ResultOfAppSigningBox.Sign( signature=_result.signature) # Create resolve app request params request_result = AppRequestResult.Ok( result=box_result.dict) resolve_params = ParamsOfResolveAppRequest( app_request_id=request.app_request_id, result=request_result) future = self.client.resolve_app_request(params=resolve_params) future = asyncio.run_coroutine_threadsafe( coro=future, loop=loop) future.result() # Get external signing box external_box = await self.client.crypto.register_signing_box( callback=__callback) # Request box public key box_pubkey = await self.client.crypto.signing_box_get_public_key( params=external_box) self.assertEqual(keys.public, box_pubkey.pubkey) # Get signature from signing box unsigned = base64.b64encode(b'Test Message').decode() sign_params = ParamsOfSigningBoxSign( signing_box=external_box.handle, unsigned=unsigned) box_sign = await self.client.crypto.signing_box_sign( params=sign_params) # Get signature by keys sign_params = ParamsOfSign(unsigned=unsigned, keys=keys) keys_sign = await self.client.crypto.sign(params=sign_params) self.assertEqual(keys_sign.signature, box_sign.signature) await self.client.crypto.remove_signing_box(params=external_box) asyncio.get_event_loop().run_until_complete(__main()) def test_parse_message(self): # Boc async def __main(): message = 'te6ccgEBAQEAWAAAq2n+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE/zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzSsG8DgAAAAAjuOu9NAL7BxYpA' params = ParamsOfParse(boc=message) result = await self.client.boc.parse_message(params=params) self.assertEqual( 'dfd47194f3058ee058bfbfad3ea40cbbd9ad17ca77cd0904d4d9f18a48c2fbca', result.parsed['id']) self.assertEqual( '-1:0000000000000000000000000000000000000000000000000000000000000000', result.parsed['src']) self.assertEqual( '-1:3333333333333333333333333333333333333333333333333333333333333333', result.parsed['dst']) with self.assertRaises(TonException): params = ParamsOfParse(boc='Wrong==') await self.client.boc.parse_message(params=params) asyncio.get_event_loop().run_until_complete(__main()) def test_subscribe_collection(self): # Net async def __main(): results = [] def __callback(response_data, response_type, *args): if response_type == SubscriptionResponseType.OK: result = ResultOfSubscription(**response_data) results.append(result.result) if response_type == SubscriptionResponseType.ERROR: raise TonException(error=ClientError(**response_data)) now = int(datetime.now().timestamp()) q_params = ParamsOfSubscribeCollection( collection='messages', result='created_at', filter={'created_at': {'gt': now}}) subscription = await self.client.net.subscribe_collection( params=q_params, callback=__callback) while True: if len(results) > 0 or \ int(datetime.now().timestamp()) > now + 10: await self.client.net.unsubscribe(params=subscription) break await asyncio.sleep(1) self.assertGreater(len(results), 0) asyncio.get_event_loop().run_until_complete(__main()) def test_run_executor_acc_none(self): # Tvm async def __main(): message = 'te6ccgEBAQEAXAAAs0gAV2lB0HI8/VEO/pBKDJJJeoOcIh+dL9JzpmRzM8PfdicAPGNEGwRWGaJsR6UYmnsFVC2llSo1ZZN5mgUnCiHf7ZaUBKgXyAAGFFhgAAAB69+UmQS/LjmiQA==' run_params = ParamsOfRunExecutor( message=message, account=AccountForExecutor.NoAccount(), skip_transaction_check=True, return_updated_account=True) result = await self.client.tvm.run_executor(params=run_params) parse_params = ParamsOfParse(boc=result.account) parsed = await self.client.boc.parse_account(params=parse_params) self.assertEqual( '0:f18d106c11586689b11e946269ec1550b69654a8d5964de668149c28877fb65a', parsed.parsed['id']) self.assertEqual('Uninit', parsed.parsed['acc_type_name']) asyncio.get_event_loop().run_until_complete(__main()) def test_convert_address(self): # Utils async def __main(): account_id = 'fcb91a3a3816d0f7b8c2c76108b8a9bc5a6b7a55bd79f8ab101c52db29232260' hex_ = '-1:fcb91a3a3816d0f7b8c2c76108b8a9bc5a6b7a55bd79f8ab101c52db29232260' hex_workchain0 = '0:fcb91a3a3816d0f7b8c2c76108b8a9bc5a6b7a55bd79f8ab101c52db29232260' base64 = 'Uf/8uRo6OBbQ97jCx2EIuKm8Wmt6Vb15+KsQHFLbKSMiYG+9' base64url = 'kf_8uRo6OBbQ97jCx2EIuKm8Wmt6Vb15-KsQHFLbKSMiYIny' convert_params = ParamsOfConvertAddress( address=account_id, output_format=AddressStringFormat.Hex()) converted = await self.client.utils.convert_address( params=convert_params) self.assertEqual(hex_workchain0, converted.address) convert_params = ParamsOfConvertAddress( address=converted.address, output_format=AddressStringFormat.AccountId()) converted = await self.client.utils.convert_address( params=convert_params) self.assertEqual(account_id, converted.address) convert_params = ParamsOfConvertAddress( address=hex_, output_format=AddressStringFormat.Base64( url=False, test=False, bounce=False)) converted = await self.client.utils.convert_address( params=convert_params) self.assertEqual(base64, converted.address) convert_params = ParamsOfConvertAddress( address=base64, output_format=AddressStringFormat.Base64( url=True, test=True, bounce=True)) converted = await self.client.utils.convert_address( params=convert_params) self.assertEqual(base64url, converted.address) convert_params = ParamsOfConvertAddress( address=base64url, output_format=AddressStringFormat.Hex()) converted = await self.client.utils.convert_address( params=convert_params) self.assertEqual(hex_, converted.address) with self.assertRaises(TonException): convert_params = ParamsOfConvertAddress( address='-1:00', output_format=AddressStringFormat.Hex()) await self.client.utils.convert_address(params=convert_params) asyncio.get_event_loop().run_until_complete(__main())
def setUp(self) -> None: config = ClientConfig() config.network.server_address = DEVNET_BASE_URL self.client = TonClient(config=config)
import os from tonclient.client import TonClient, DEVNET_BASE_URL from tonclient.types import Abi, CallSet, Signer BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:653b9a6452c7a982c6dc92b2da9eba832ade1c467699ebb3b43dca6d77b780dd' async_core_client = TonClient(network={'server_address': DEVNET_BASE_URL}) sync_core_client = TonClient(network={'server_address': DEVNET_BASE_URL}, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_json_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet(function_name='grant', inputs={'addr': address}) async_core_client.processing.process_message(abi=giver_abi, signer=Signer(), address=GIVER_ADDRESS, call_set=call_set, send_events=False)
def __init__(self,network={'server_address': DEVNET_BASE_URL},samples_dir='abi'): self.BASE_DIR = os.path.dirname(__file__) self.SAMPLES_DIR = os.path.join(self.BASE_DIR, 'abi') self.async_core_client = TonClient(network={'server_address': DEVNET_BASE_URL})
## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * import sys from tonclient.client import TonClient,DEVNET_BASE_URL, MAINNET_BASE_URL import os from tonclient.types import Abi, KeyPair, DeploySet, CallSet, Signer, \ MessageSource, StateInitSource import base64 from tonclient.net import TonQLQuery import json client = TonClient(network={'server_address': DEVNET_BASE_URL}, abi={'message_expiration_timeout': 30000}) def clearLayout(layout): if layout is not None: while layout.count(): child = layout.takeAt(0) if child.widget() is not None: child.widget().deleteLater() elif child.layout() is not None: clearLayout(child.layout()) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(1384, 1133)
import os from tonclient.client import TonClient, DEVNET_BASE_URL from tonclient.types import Abi, CallSet, Signer, ClientConfig, \ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' CUSTOM_BASE_URL = 'https://tonos.freeton.surf' client_config = ClientConfig() client_config.network.server_address = DEVNET_BASE_URL async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) client_config.network.server_address = CUSTOM_BASE_URL async_custom_client = TonClient(config=client_config) def send_grams(address: str): giver_abi = Abi.from_path(path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet(function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage(abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_custom_client.processing.process_message(params=process_params)