Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraTronTests/LiveTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// Last Modified : 2026-12-0513//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import Testing44import QyvoraCore45import QyvoraNetworking46@testable import QyvoraTron4748/// Opt-in tests against the public networks: `QYVORA_LIVE=1 swift test --filter TronLiveTests`.49/// They only read public chain data: no key, no signature, no broadcast.50@Suite(.enabled(if: ProcessInfo.processInfo.environment["QYVORA_LIVE"] == "1"), .serialized)51struct TronLiveTests {52 let transport = URLSessionTransport()53 /// A public Nile account with TRX, test USDT and history, and the Nile test USDT contract.54 let holder = TronAddress("TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs")!55 let nileUSDT = TronAddress("TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf")!56 /// An address derived from a published test key, never activated on Nile when this was written.57 let fresh = TronAddress(TronVectors.keys[0].address)!5859 @Test func nile() async throws {60 let c = TronClient(network: .nile, transport: transport)61 try await c.verifyChain()62 print("LIVE nile: chain identity verified on \(TronEndpoints.default.fullNodes["nile"] ?? []) (genesis \(TronNetwork.nile.genesisBlockID))")6364 let head = try await c.latestBlock(), solid = try await c.latestSolidBlock()65 #expect(head.number > 73_000_000 && solid.number <= head.number && head.number - solid.number < 200)66 let now = UInt64(Date().timeIntervalSince1970 * 1000)67 #expect(now > solid.timestamp ? now - solid.timestamp < 600_000 : solid.timestamp - now < 600_000)68 print("LIVE nile: head block \(head.number) \(head.idHex.prefix(24))…, irreversible \(solid.number) (\(head.number - solid.number) behind), ref \(Hex.encode(solid.refBlockBytes))/\(Hex.encode(solid.refBlockHash))")6970 let parameters = try await c.chainParameters()71 #expect(parameters.bandwidthPriceSun > 0 && parameters.energyPriceSun > 0 && parameters.maximumFeeLimitSun >= 1_000_000_000)72 print("LIVE nile: parameters bandwidth \(parameters.bandwidthPriceSun) sun/byte, energy \(parameters.energyPriceSun) sun/unit, activation \(parameters.accountActivationFeeSun), create-account \(parameters.createAccountFeeSun) ×\(parameters.createAccountBandwidthRate), memo \(parameters.memoFeeSun), max fee limit \(parameters.maximumFeeLimitSun)")7374 let account = try await c.account(holder), resources = try await c.resources(holder)75 #expect(account.isActivated && !account.isContract && account.balanceSun > 0)76 print("LIVE nile: \(holder) balance \(TronUnits.formatTRX(account.balanceSun)) TRX; bandwidth free \(resources.freeBandwidth)/\(resources.freeNetLimit), staked \(resources.stakedBandwidth); energy \(resources.energy)")77 let unknown = try await c.account(fresh), unknownResources = try await c.resources(fresh)78 print("LIVE nile: \(fresh) activated \(unknown.isActivated), balance \(unknown.balanceSun) sun, resources \(unknownResources == .none ? "none" : "some")")7980 // token metadata and balance by constant call81 let tokenAccount = try await c.account(nileUSDT)82 let decimals = try await c.tokenDecimals(nileUSDT), symbol = try await c.tokenSymbol(nileUSDT), name = try await c.tokenName(nileUSDT)83 let balance = try await c.tokenBalance(token: nileUSDT, owner: holder)84 #expect(tokenAccount.isContract && decimals == 6 && symbol == "USDT")85 print("LIVE nile: token \(nileUSDT) contract \(tokenAccount.isContract), \(symbol) \"\(name)\", \(decimals) decimals; holder balance \(BaseUnits.format(balance, decimals: decimals))")8687 // energy estimate of a USDT-like transfer, to a holder-less address and to an existing holder88 let amount = UInt256(1_000_000)89 let toFresh = try await c.simulateTokenTransfer(token: nileUSDT, from: holder, to: fresh, amount: amount)90 let toSelfLike = try await c.simulateTokenTransfer(token: nileUSDT, from: holder, to: TronAddress("TPQ4R9qRz8q5LMJJCbsQFrUoHB5mB7GkEb")!, amount: amount)91 #expect(toFresh.succeeded && toFresh.energyUsed > 5000 && toSelfLike.succeeded && toSelfLike.energyUsed > 5000)92 print("LIVE nile: simulated transfer of 1 USDT: \(toFresh.energyUsed) energy to a new holder, \(toSelfLike.energyUsed) to an existing holder; returned \(Hex.encode(toFresh.output).suffix(4)) (ignored)")93 let reverting = try await c.simulateTokenTransfer(token: nileUSDT, from: fresh, to: holder, amount: amount)94 #expect(!reverting.succeeded)95 print("LIVE nile: simulated transfer from an empty account: succeeded \(reverting.succeeded), \"\(reverting.message)\"")9697 // the planner on live state (nothing is signed)98 let state = TronSendPlanner.ChainState(network: .nile, parameters: parameters, reference: solid, nowMilliseconds: now)99 let planner = TronSendPlanner()100 let trxPlan = try planner.planTransfer(state: state, sender: account, resources: resources, recipient: unknown, amount: .exact(1_000_000))101 print("LIVE nile: plan 1 TRX → \(fresh): \(trxPlan.bandwidthBytes) bytes (\(trxPlan.bandwidthSource)), fee \(TronUnits.formatTRX(trxPlan.estimatedFeeSun)) TRX, max \(TronUnits.formatTRX(trxPlan.maximumFeeSun)), notes \(trxPlan.notes)")102 let tokenPlan = try planner.planTokenTransfer(state: state, sender: account, resources: resources, recipient: unknown, token: tokenAccount, tokenBalance: balance,103 amount: amount, simulation: toFresh)104 #expect(tokenPlan.feeLimitSun == tokenPlan.energyLimit * parameters.energyPriceSun)105 print("LIVE nile: plan 1 USDT → \(fresh): \(tokenPlan.bandwidthBytes) bytes (\(tokenPlan.bandwidthSource)), energy \(tokenPlan.energyEstimate) → limit \(tokenPlan.energyLimit), fee_limit \(TronUnits.formatTRX(tokenPlan.feeLimitSun)) TRX, expected fee \(TronUnits.formatTRX(tokenPlan.estimatedFeeSun)) TRX, max \(TronUnits.formatTRX(tokenPlan.maximumFeeSun))")106107 // the node builds the same TRX transfer: with its block and time fields, the local bytes are identical108 let theirs = try await c.nodeBuiltTransfer(from: holder, to: fresh, amountSun: 1_000_000)109 let decoded = try TronTransaction.decode(rawData: theirs)110 let mine = try TronTransaction(refBlockBytes: decoded.refBlockBytes, refBlockHash: decoded.refBlockHash, expiration: decoded.expiration, timestamp: decoded.timestamp,111 contract: .transfer(TronTransferContract(owner: holder, to: fresh, amount: 1_000_000)))112 #expect(mine.rawData == theirs)113 #expect(TronTransactionReview(decoded).action == .trxTransfer(from: holder, to: fresh, amountSun: 1_000_000))114 // the block the node referred to is a recent one: our own reference differs only by being irreversible115 let after = try await c.latestBlock()116 let theirNumber = UInt64(decoded.refBlockBytes[0]) << 8 | UInt64(decoded.refBlockBytes[1])117 let distance = (after.number & 0xffff) >= theirNumber ? (after.number & 0xffff) - theirNumber : (after.number & 0xffff) + 0x10000 - theirNumber118 #expect(distance < 100)119 print("LIVE nile: createtransaction cross-check: \(theirs.count) bytes, byte-identical to the local encoding = \(mine.rawData == theirs); txID \(mine.txIDHex); node ref block \(distance) behind head, lifetime \(decoded.expiration - decoded.timestamp) ms")120121 // status of a known transaction, on the irreversible state122 let status = try await c.transactionStatus(id: NileSamples.tokenTxID, irreversibleOnly: true)123 #expect(status.state == .succeeded && status.feeSun == 346_000 && status.energyUsed == 29_650 && status.transaction?.txIDHex == NileSamples.tokenTxID)124 #expect(status.transaction?.bandwidthSize() == 346)125 print("LIVE nile: tx \(NileSamples.tokenTxID.prefix(16))… \(status.state.rawValue) in block \(status.blockNumber ?? 0), fee \(status.feeSun) sun (net \(status.netFeeSun), energy \(status.energyFeeSun)), energy used \(status.energyUsed), receipt \(status.receiptResult ?? "-")")126 let missing = try await c.transactionStatus(id: String(repeating: "0", count: 64))127 #expect(missing.state == .notFound)128129 // history130 let native = try await c.transactions(of: holder, limit: 10)131 #expect(!native.items.isEmpty && native.items.count <= 10)132 let tokens = try await c.tokenTransfers(of: holder, limit: 10)133 #expect(!tokens.items.isEmpty && tokens.items.allSatisfy { $0.kind == .trc20 && $0.token != nil })134 if let cursor = native.nextFingerprint {135 let second = try await c.transactions(of: holder, limit: 10, fingerprint: cursor)136 #expect(Set(second.items.map(\.txID)).isDisjoint(with: Set(native.items.map(\.txID))))137 print("LIVE nile: history page 2: \(second.items.count) entries")138 }139 print("LIVE nile: history: \(native.items.count) transactions (first: \(native.items[0].kind.rawValue) \(native.items[0].amount) sun, fee \(native.items[0].feeSun ?? 0), \(native.items[0].date.map { "\($0)" } ?? "-")), \(tokens.items.count) token transfers (first: \(tokens.items[0].amount) of \(tokens.items[0].tokenSymbol ?? "?") \(tokens.items[0].token?.base58 ?? ""))")140 let empty = try await c.transactions(of: fresh)141 print("LIVE nile: history of the unactivated address: \(empty.items.count) entries")142 }143144 /// The other default endpoints, and the built-in tokens read on mainnet (read-only).145 @Test func otherNetworks() async throws {146 let shasta = TronClient(network: .shasta, transport: transport)147 try await shasta.verifyChain()148 let shastaHead = try await shasta.latestSolidBlock()149 print("LIVE shasta: chain identity verified, irreversible block \(shastaHead.number)")150151 let mainnet = TronClient(network: .mainnet, transport: transport)152 try await mainnet.verifyChain()153 let parameters = try await mainnet.chainParameters()154 print("LIVE mainnet: chain identity verified on \(TronEndpoints.default.fullNodes["mainnet"] ?? []); energy \(parameters.energyPriceSun) sun/unit, bandwidth \(parameters.bandwidthPriceSun) sun/byte, activation \(parameters.accountActivationFeeSun), memo \(parameters.memoFeeSun)")155 for token in TronBuiltInTokens.mainnet {156 #expect(try await mainnet.verify(token: token))157 let name = try await mainnet.tokenName(token.contract)158 #expect(name == token.name)159 print("LIVE mainnet: built-in \(token.symbol) \(token.contract) verified on chain (contract, \(token.decimals) decimals, name \"\(name)\")")160 }161 // a network presented under the wrong name is refused162 let crossed = TronClient(network: .mainnet, endpoints: TronEndpoints(fullNodes: ["mainnet": TronEndpoints.default.fullNodes["nile"] ?? []], history: [:]), transport: transport)163 do {164 try await crossed.verifyChain()165 Issue.record("Nile endpoints verified as mainnet")166 } catch let e as NetworkError {167 guard case .disagreement(let text) = e else { throw e }168 print("LIVE: Nile endpoints presented as mainnet → \(text)")169 }170 }171}172