from ton_core import Address, NetworkGlobalID, TextCipher, to_nano
from tonutils.clients import ToncenterClient
from tonutils.contracts import WalletV4R2, get_public_key_get_method
# Mnemonic phrase
MNEMONIC = "word1 word2 word3 ..."
# Destination address (recipient)
# Recipient must have a deployed wallet contract with a public key
# accessible via the get_public_key get-method
DESTINATION_ADDRESS = Address("UQ...")
async def main() -> None:
client = ToncenterClient(network=NetworkGlobalID.MAINNET)
await client.connect()
# Keep private_key for encryption as our_private_key
wallet, _, our_private_key, _ = WalletV4R2.from_mnemonic(client, MNEMONIC)
# Retrieve recipient's public key from the blockchain
# Raises an error if the wallet is uninit or lacks the get_public_key method
their_public_key = await get_public_key_get_method(
client=client,
address=DESTINATION_ADDRESS,
)
# Encrypt the message; only the sender and the recipient can decrypt it
body = TextCipher.encrypt(
payload="Hello from tonutils!",
sender_address=wallet.address,
our_private_key=our_private_key,
their_public_key=their_public_key,
)
msg = await wallet.transfer(
destination=DESTINATION_ADDRESS,
amount=to_nano(0.01),
body=body,
)
# Normalized hash of the signed external message (computed locally) —
# not the on-chain transaction hash
print(f"Transaction hash: {msg.normalized_hash}")
await client.close()
if __name__ == "__main__":
import asyncio
asyncio.run(main())