I have an error that I don’t know what is the problem after having read documentation and michaelhly docs. Also, my fiber connection is broken and I work with an airbox that my ISP gave me in the meantime to troubleshoot and which I don’t know if it could be the cause.
My error in the terminal is this one :
- Creating associated token account…
- token_associated_account: DoXq1Bw4B8dehwovAVZgyZrWVHnjuYvgLNBhmTPwqMH
- Error occurred while creating ATA: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:997)
It seems that the problem is with ata in _create_associated_token_account.
Code is:
import base64
import based58
import httpx
import asyncio
import requests
import json
import time
from solana.rpc.async_api import AsyncClient
from solana.rpc.types import TxOpts
from solana.publickey import PublicKey
from solana.keypair import Keypair
from solana.transaction import Transaction
from spl.token.instructions import get_associated_token_address, create_associated_token_account
from usdc_swaps import route_map
SOLANA_CLIENT = AsyncClient('https://ti-dawn-eld.solana-mainnet.discover.quiknode.pro/e1/')
WALLET = Keypair.from_secret_key(based58.b58decode('********'.encode("ascii")))
INPUT_USDC_AMOUNT = 500000
USDC_BASE = 1000000
def get_mint(index, indexedRouteMap):
return indexedRouteMap["mintKeys"][int(index)]
def get_route_map():
return route_map
async def get_coin_quote(INPUT_MINT, TOKEN_MINT, amount):
try:
url = "https://quote-api.jup.ag/v6/quote"
params = {
"inputMint": INPUT_MINT,
"outputMint": TOKEN_MINT,
"amount": amount,
"slippageBps": 500,
"swapMode": "ExactIn",
}
headers = {"Accept": "application/json"}
async with httpx.AsyncClient() as client:
r = await client.get(url, params=params, headers=headers, timeout=30.0)
r.raise_for_status()
data = r.json()
output_mint = data.get("outputMint")
print("Token Adress:", output_mint)
return data
except requests.exceptions.RequestException as e:
print("Error occurred during request:", e)
return None
except Exception as e:
print("Error occurred:", e)
return None
async def get_coin_swap_quote(route):
try:
url = "https://quote-api.jup.ag/v6/swap"
payload = {
"quoteResponse": route,
"userPublicKey": str(WALLET.public_key),
"wrapAndUnwrapSol": True,
"useSharedAccounts": True,
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
async with httpx.AsyncClient() as client:
r = await client.post(url, json=payload, headers=headers, timeout=30.0)
r.raise_for_status()
data = r.json()
output_mint = data.get("outputMint")
threshold = data.get("otherAmountThreshold")
print("POST Coin Swap Quote Response - Output Mint:", output_mint)
print("POST Coin Swap Quote Response - Other Amount Threshold:", threshold)
return data
except httpx.HTTPError as e:
print("HTTP error occurred:", e)
return None
except Exception as e:
print("Error occurred during request:", e)
return None
async def execute_transaction(transaction):
try:
opts = TxOpts(skip_preflight=True, max_retries=11)
await SOLANA_CLIENT.send_transaction(transaction, WALLET, opts=opts)
except Exception as e:
print("Error occurred during transaction execution:", e)
return str(e)
async def serialized_swap_transaction(usdcToTokenRoute, tokenToUsdcRoute):
try:
if usdcToTokenRoute:
usdcToTokenTransaction = await get_coin_swap_quote(usdcToTokenRoute)
if usdcToTokenTransaction:
await execute_transaction(
Transaction.deserialize(base64.b64decode(usdcToTokenTransaction))
)
if tokenToUsdcRoute:
tokenToUsdcTransaction = await get_coin_swap_quote(tokenToUsdcRoute)
if tokenToUsdcTransaction:
await execute_transaction(
Transaction.deserialize(base64.b64decode(tokenToUsdcTransaction))
)
except Exception as e:
print("Error occurred during serialized swap transaction:", e)
async def _create_associated_token_account(token):
try:
# Create Associated token account for token to swap if not available
token_associated_account = get_associated_token_address(WALLET.public_key, PublicKey(token))
print("token_associated_account:", token_associated_account)
# Use the get_account_info method to check if the associated token account exists
ata = await SOLANA_CLIENT.get_account_info(token_associated_account)
print("ata:", ata)
opts = TxOpts(skip_preflight=True, max_retries=11)
# Check if the associated token account exists
if not ata.value:
# Create the associated token account if it doesn't exist
instruction = create_associated_token_account(
WALLET.public_key(), WALLET.public_key(), PublicKey(token)
)
txn = Transaction().add(instruction)
txn.recent_blockhash = await SOLANA_CLIENT.get_recent_blockhash()
await SOLANA_CLIENT.send_transaction(txn, WALLET, opts=opts)
print("Associated token account created successfully.")
else:
print("Associated token account already exists.")
except Exception as e:
print("Error occurred while creating ATA: ", str(e))
return e
async def swap(input, generatedRouteMap):
try:
with open("arbitrage.json", "r") as f:
tradable_mints = json.load(f)
for token in tradable_mints:
try:
usdcToToken = await get_coin_quote(
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", token, input
)
aller = usdcToToken.get("otherAmountThreshold")
print("Quote from USDC to Token:", aller)
if usdcToToken:
tokenToUsdc = await get_coin_quote(
token,
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
aller,
)
retour = tokenToUsdc.get("otherAmountThreshold")
print("33[91mQuote from Token to USDC:33[0m", retour)
print("-------------------------------------------")
if (
tokenToUsdc and int(retour) > input
):
print("Creating associated token account...")
await _create_associated_token_account(token)
print("Associated token account created successfully.")
print("Executing swap transaction...")
await serialized_swap_transaction(
usdcToToken.get("otherAmountThreshold"), tokenToUsdc.get("otherAmountThreshold")
)
print("Swap transaction executed successfully.")
profit = (
tokenToUsdc.get("otherAmountThreshold") - input
)
print("Approx Profit made: ", profit / USDC_BASE)
except Exception as e:
print("Error occurred during token swap:", e)
continue # Passe au token suivant en cas d'erreur
await asyncio.sleep(1) # Délai de 1 seconde entre les requêtes API
except Exception as e:
print("Error occurred during swap:", e)
except Exception as e:
print("Error occurred during swap:", e)
async def update_token_list():
try:
url = "https://quote-api.jup.ag/v6/tokens"
headers = {"Accept": "application/json"}
response = requests.request("GET", url, headers=headers)
response.raise_for_status()
tradable_mints = response.json()
with open("arbitrage.json", "w") as f:
json.dump(tradable_mints, f)
print("Token list updated successfully")
except requests.exceptions.RequestException as e:
print("Error occurred during token list update:", e)
except Exception as e:
print("Error occurred during token list update:", e)
async def main():
await update_token_list()
while True:
generatedRouteMap = get_route_map()
await swap(INPUT_USDC_AMOUNT, generatedRouteMap)
await asyncio.sleep(3600)
if __name__ == "__main__":
asyncio.run(main())