├── .gitignore ├── LICENSE ├── README.md ├── demo1.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | /.idea 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 encoderlee 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python SunSwap Demo 2 | some examples of interact with sunswap using python 3 | 4 | ### demo1.py 5 | 6 | check the USDT balance on the account 7 | 8 | monitor the price of SUN, if the price of SUN is lower than 0.0054 USDT/SUN, buy 1 USDT of SUN. 9 | 10 | ### References 11 | 12 | tron explorer: 13 | 14 | [https://tronscan.org/](https://tronscan.org/) 15 | 16 | tron developers docs: 17 | 18 | [https://developers.tron.network/docs](https://developers.tron.network/docs) 19 | 20 | tron api key 21 | 22 | [https://developers.tron.network/reference/select-network](https://developers.tron.network/reference/select-network) 23 | 24 | tronpy: 25 | 26 | [https://tronpy.readthedocs.io/en/latest/index.html](https://tronpy.readthedocs.io/en/latest/index.html) 27 | -------------------------------------------------------------------------------- /demo1.py: -------------------------------------------------------------------------------- 1 | import time 2 | from decimal import Decimal 3 | from typing import List 4 | from datetime import datetime, timedelta 5 | import os 6 | from dataclasses import dataclass 7 | from tronpy import Tron 8 | from tronpy.keys import PrivateKey 9 | from tronpy.providers import HTTPProvider 10 | 11 | 12 | @dataclass 13 | class Contract: 14 | symbol: str 15 | address: str 16 | decimals: int = None 17 | 18 | 19 | class Known: 20 | usdt = Contract("USDT", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", 6) 21 | sun = Contract("SUN", "TSSMHYeV2uE9qYH95DqyoCuNCzEL1NvU3S", 18) 22 | sunswap = Contract("SunswapV2Router02", "TKzxdSv2FZKQrEqkKVgp5DcwEXBEKMg2Ax") 23 | 24 | 25 | class SunSwap: 26 | 27 | def __init__(self, address_wallet: str, private_key: str = None): 28 | self.wallet: str = address_wallet 29 | provider = HTTPProvider(timeout=30, api_key="b0ed0858-e287-45be-beec-57c6cb509c46") 30 | provider.sess.trust_env = False 31 | self.tron = Tron(provider) 32 | self.private_key = PrivateKey(bytes.fromhex(private_key)) 33 | 34 | # get ERC20 token balance of the account 35 | def erc20_balance(self, erc20: Contract) -> Decimal: 36 | contract = self.tron.get_contract(erc20.address) 37 | # get the token decimals if not 38 | decimals = erc20.decimals 39 | if not decimals: 40 | decimals = contract.functions.decimals() 41 | # get the balance of tokens and convert it 42 | balance = contract.functions.balanceOf(self.wallet) 43 | balance = Decimal(balance) / (10 ** decimals) 44 | return balance 45 | 46 | # approve the sunswap contract to use erc20 tokens 47 | def approve_erc20_to_sunswap(self, erc20: Contract): 48 | contract = self.tron.get_contract(erc20.address) 49 | approve_amount = 2 ** 256 - 1 50 | amount = contract.functions.allowance(self.wallet, Known.sunswap.address) 51 | if amount >= approve_amount / 2: 52 | print("already approved") 53 | return None 54 | txn = ( 55 | contract.functions.approve(Known.sunswap.address, approve_amount) 56 | .with_owner(self.wallet) 57 | .fee_limit(100 * 1000000) 58 | .build() 59 | .sign(self.private_key) 60 | ) 61 | result = txn.broadcast().wait() 62 | if result["receipt"]["result"] == "SUCCESS": 63 | print("transaction ok: {0}".format(result)) 64 | else: 65 | print("transaction error: {0}".format(result)) 66 | return result 67 | 68 | # query the price of token pair 69 | def query_price(self, token_path: List[Contract]) -> Decimal: 70 | contract = self.tron.get_contract(Known.sunswap.address) 71 | path = [item.address for item in token_path] 72 | amount = contract.functions.getAmountsOut(1 * 10 ** token_path[0].decimals, path) 73 | amount_in = Decimal(amount[0]) / (10 ** token_path[0].decimals) 74 | amount_out = Decimal(amount[1]) / (10 ** token_path[-1].decimals) 75 | return amount_in / amount_out 76 | 77 | # swap token 78 | def swap_token(self, amount_in: Decimal, token_path: List[Contract]): 79 | # approve token to sunswap if not 80 | self.approve_erc20_to_sunswap(token_path[0]) 81 | 82 | contract = self.tron.get_contract(Known.sunswap.address) 83 | path = [item.address for item in token_path] 84 | 85 | amount_in = int(amount_in * 10 ** token_path[0].decimals) 86 | amount = contract.functions.getAmountsOut(amount_in, path) 87 | # slippage 0.5% fee 0.3% ,minimum received 99.2 % 88 | minimum_out = int(amount[1] * (1 - Decimal("0.005") - Decimal("0.003"))) 89 | deadline = datetime.now() + timedelta(minutes=5) 90 | txn = (contract.functions.swapExactTokensForTokens(amount_in, minimum_out, path, self.wallet, 91 | int(deadline.timestamp())) 92 | .with_owner(self.wallet) 93 | .fee_limit(100 * 1000000) 94 | .build() 95 | .sign(self.private_key) 96 | ) 97 | result = txn.broadcast().wait() 98 | if result["receipt"]["result"] == "SUCCESS": 99 | print("transaction ok: {0}".format(result)) 100 | else: 101 | print("transaction error: {0}".format(result)) 102 | return result 103 | 104 | 105 | def main(): 106 | # change it to your wallet address 107 | address_wallet = "TGrDfWjBrefFdsT6VNB4ZpN9qBpmfM6Smo" 108 | # set your private key to the environment variable 'key' 109 | private_key = os.getenv("key") 110 | sunswap = SunSwap(address_wallet, private_key) 111 | 112 | balance = sunswap.erc20_balance(Known.usdt) 113 | print("usdt balance: {0}".format(balance)) 114 | 115 | limit_price = Decimal("0.0054") 116 | amount_buy = Decimal(1) 117 | print("if the price of SUN is lower than {0} USDT/SUN, buy {1} USDT of SUN".format(limit_price, amount_buy)) 118 | 119 | token_path = [Known.usdt, Known.sun] 120 | 121 | while True: 122 | price = sunswap.query_price(token_path) 123 | print("sun price: {0} USDT/SUN".format(price)) 124 | if price <= limit_price: 125 | print("price ok, buy {0} USDT of SUN".format(amount_buy)) 126 | sunswap.swap_token(amount_buy, token_path) 127 | break 128 | time.sleep(2) 129 | 130 | 131 | if __name__ == '__main__': 132 | main() 133 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tronpy 2 | --------------------------------------------------------------------------------