Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraTron/TronClient.swift8// Module : Qyvora Tron9// 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 QyvoraSymmetric44import QyvoraCore45import QyvoraEthereum46import QyvoraNetworking4748/// An optional TronGrid API key supplied by the user. It is sent in the `TRON-PRO-API-KEY` header to TronGrid hosts49/// over https only, and it never appears in a description, a mirror, an error or a URL.50public struct TronAPIKey: Sendable, Equatable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {51 let value: String5253 /// nil unless the text is 8 to 128 characters of letters, digits, "-" and "_" (no white space, nothing that could54 /// break out of a header).55 public init?(_ text: String) {56 let u = text.utf857 guard (8...128).contains(u.count), u.allSatisfy({ ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x41 && $0 <= 0x5a) || ($0 >= 0x61 && $0 <= 0x7a) || $0 == 0x2d || $0 == 0x5f }) else {58 return nil59 }60 value = text61 }6263 public var description: String { "TronAPIKey(redacted)" }64 public var debugDescription: String { description }65 public var customMirror: Mirror { Mirror(self, children: [:]) }66}6768/// How politely the client talks to public endpoints. Keyless TronGrid access is rate-limited (a few requests per69/// second, then a suspension of several seconds): requests to one host are spaced, and an HTTP 429 is waited out once.70public struct TronPacing: Equatable, Sendable {71 /// Least time between two requests to a TronGrid host, in milliseconds.72 public var tronGridIntervalMilliseconds: UInt6473 /// Least time between two requests to any other host, in milliseconds.74 public var otherIntervalMilliseconds: UInt6475 /// Wait after an HTTP 429 before the retry, in milliseconds, when the server gives no `Retry-After`.76 public var rateLimitBackoffMilliseconds: UInt6477 /// Retries after an HTTP 429 (0 = report it at once).78 public var rateLimitRetries: Int7980 public static let `default` = TronPacing(tronGridIntervalMilliseconds: 380, otherIntervalMilliseconds: 50, rateLimitBackoffMilliseconds: 5300, rateLimitRetries: 1)81 /// With a paid key, or against one's own node.82 public static let unthrottled = TronPacing(tronGridIntervalMilliseconds: 0, otherIntervalMilliseconds: 0, rateLimitBackoffMilliseconds: 0, rateLimitRetries: 0)8384 public init(tronGridIntervalMilliseconds: UInt64, otherIntervalMilliseconds: UInt64, rateLimitBackoffMilliseconds: UInt64, rateLimitRetries: Int) {85 self.tronGridIntervalMilliseconds = tronGridIntervalMilliseconds86 self.otherIntervalMilliseconds = otherIntervalMilliseconds87 self.rateLimitBackoffMilliseconds = rateLimitBackoffMilliseconds88 self.rateLimitRetries = max(0, min(rateLimitRetries, 3))89 }90}9192/// Gives each host its next free slot, so that concurrent callers are spaced too.93actor TronPacer {94 private var nextSlot = [String: ContinuousClock.Instant]()9596 func delay(host: String, interval: Duration) -> Duration {97 let now = ContinuousClock.now98 let start = max(now, nextSlot[host] ?? now)99 nextSlot[host] = start + interval100 return start - now101 }102}103104/// State of an account as the node reports it.105public struct TronAccount: Equatable, Sendable {106 public let address: TronAddress107 /// False for an address the chain has never seen: it has no balance, and the first TRX sent to it pays the108 /// account-creation fee.109 public let isActivated: Bool110 public let balanceSun: UInt64111 /// True for a smart-contract account.112 public let isContract: Bool113114 public init(address: TronAddress, isActivated: Bool, balanceSun: UInt64, isContract: Bool) {115 self.address = address116 self.isActivated = isActivated117 self.balanceSun = balanceSun118 self.isContract = isContract119 }120}121122/// Bandwidth and energy of an account. Limits and usage are in bytes (bandwidth) and energy units.123public struct TronResources: Equatable, Sendable {124 public let freeNetLimit: UInt64125 public let freeNetUsed: UInt64126 /// Bandwidth obtained by staking or delegation.127 public let netLimit: UInt64128 public let netUsed: UInt64129 public let energyLimit: UInt64130 public let energyUsed: UInt64131132 public static let none = TronResources(freeNetLimit: 0, freeNetUsed: 0, netLimit: 0, netUsed: 0, energyLimit: 0, energyUsed: 0)133134 public init(freeNetLimit: UInt64, freeNetUsed: UInt64, netLimit: UInt64, netUsed: UInt64, energyLimit: UInt64, energyUsed: UInt64) {135 self.freeNetLimit = freeNetLimit136 self.freeNetUsed = freeNetUsed137 self.netLimit = netLimit138 self.netUsed = netUsed139 self.energyLimit = energyLimit140 self.energyUsed = energyUsed141 }142143 /// Free daily bandwidth left, in bytes.144 public var freeBandwidth: UInt64 { freeNetLimit > freeNetUsed ? freeNetLimit - freeNetUsed : 0 }145 /// Staked bandwidth left, in bytes.146 public var stakedBandwidth: UInt64 { netLimit > netUsed ? netLimit - netUsed : 0 }147 /// Energy left.148 public var energy: UInt64 { energyLimit > energyUsed ? energyLimit - energyUsed : 0 }149}150151/// The chain parameters that price a transaction, all in sun.152public struct TronChainParameters: Equatable, Sendable {153 /// `getTransactionFee`: price of one byte of bandwidth when it is burned.154 public let bandwidthPriceSun: UInt64155 /// `getEnergyFee`: price of one unit of energy when it is burned.156 public let energyPriceSun: UInt64157 /// `getCreateNewAccountFeeInSystemContract`: burned when a TRX transfer creates the recipient account.158 public let accountActivationFeeSun: UInt64159 /// `getCreateAccountFee`: added to the activation fee when the sender has no staked bandwidth for the transaction.160 public let createAccountFeeSun: UInt64161 /// `getCreateNewAccountBandwidthRate`: bandwidth multiplier of an account-creating transaction.162 public let createAccountBandwidthRate: UInt64163 /// `getMaxFeeLimit`: protocol ceiling of `fee_limit`.164 public let maximumFeeLimitSun: UInt64165 /// `getMemoFee`: burned when the transaction carries a memo (0 when the chain has no such parameter).166 public let memoFeeSun: UInt64167168 public init(bandwidthPriceSun: UInt64, energyPriceSun: UInt64, accountActivationFeeSun: UInt64, createAccountFeeSun: UInt64,169 createAccountBandwidthRate: UInt64, maximumFeeLimitSun: UInt64, memoFeeSun: UInt64) {170 self.bandwidthPriceSun = bandwidthPriceSun171 self.energyPriceSun = energyPriceSun172 self.accountActivationFeeSun = accountActivationFeeSun173 self.createAccountFeeSun = createAccountFeeSun174 self.createAccountBandwidthRate = createAccountBandwidthRate175 self.maximumFeeLimitSun = maximumFeeLimitSun176 self.memoFeeSun = memoFeeSun177 }178}179180/// Result of a read-only contract execution (`triggerconstantcontract`).181public struct TronConstantResult: Equatable, Sendable {182 /// False when the call reverted or failed; `message` then says why, as the node reports it.183 public let succeeded: Bool184 public let message: String185 /// Returned data (ABI-encoded).186 public let output: Bytes187 /// Energy the execution used. For a simulated transfer this is the estimate the planner starts from.188 public let energyUsed: UInt64189190 public init(succeeded: Bool, message: String, output: Bytes, energyUsed: UInt64) {191 self.succeeded = succeeded192 self.message = message193 self.output = output194 self.energyUsed = energyUsed195 }196}197198/// What the network answered to a broadcast.199public enum TronBroadcastResult: Equatable, Sendable {200 /// A node accepted the transaction into its pool. This is not a confirmation: follow `transactionStatus`.201 case accepted(txID: String)202 /// The node already had this transaction (`DUP_TRANSACTION_ERROR`): it was broadcast before.203 case alreadyKnown(txID: String)204 /// Every node that answered refused it; code and message of the first refusal (`SIGERROR`,205 /// `CONTRACT_VALIDATE_ERROR`, `TAPOS_ERROR`, `TRANSACTION_EXPIRATION_ERROR`…).206 case rejected(code: String, message: String)207}208209/// Where a transaction stands.210public struct TronTransactionStatus: Equatable, Sendable {211 public enum State: String, Sendable {212 /// The node does not know the transaction (not broadcast, still in a pool, or expired).213 case notFound214 /// The node has the transaction in a block but no execution record yet.215 case pending216 /// Included in a block and executed successfully.217 case succeeded218 /// Included in a block and failed (revert, out of energy…): nothing moved, the fee was still charged.219 case failed220 }221222 public let txID: String223 public let state: State224 /// True when the answer comes from the irreversible state (`/walletsolidity`).225 public let irreversible: Bool226 public let blockNumber: UInt64?227 /// Block time, milliseconds since 1970.228 public let blockTimestamp: UInt64?229 /// Total TRX burned by the transaction, in sun.230 public let feeSun: UInt64231 /// Energy the execution used, whoever paid for it.232 public let energyUsed: UInt64233 /// TRX burned for energy, in sun.234 public let energyFeeSun: UInt64235 /// TRX burned for bandwidth, in sun.236 public let netFeeSun: UInt64237 /// `ret[0].contractRet` of the transaction ("SUCCESS", "REVERT", "OUT_OF_ENERGY"…).238 public let contractResult: String?239 /// `receipt.result` of the execution record. A TRC-20 `transfer` may return nothing or false (USDT does): this240 /// field and `contractResult`, never the returned value, say whether the transfer happened.241 public let receiptResult: String?242 /// Failure message of the node, when there is one.243 public let message: String?244 /// The transaction itself, decoded from the bytes the node returned, when they hash to `txID`.245 public let transaction: TronTransaction?246}247248/// One line of history, normalised from the TronGrid index.249public struct TronTransfer: Equatable, Sendable, Identifiable {250 public enum Kind: String, Sendable {251 /// A TRX transfer (`TransferContract`).252 case trx253 /// A TRC-20 `Transfer` event.254 case trc20255 /// Any other transaction of the account (contract call, staking, vote…): `amount` is the TRX attached, if any.256 case other257 }258259 public let kind: Kind260 public let txID: String261 public let from: TronAddress262 /// Recipient; for `.other`, the contract called, when there is one.263 public let to: TronAddress?264 /// Sun for `.trx` and `.other`, token base units for `.trc20`.265 public let amount: UInt256266 /// Block time, milliseconds since 1970.267 public let timestamp: UInt64?268 public let blockNumber: UInt64?269 public let succeeded: Bool270 /// False while the index marks the entry as not yet confirmed.271 public let confirmed: Bool272 /// TRX burned by the transaction, in sun (native history only).273 public let feeSun: UInt64?274 /// Token contract of a `.trc20` entry. Symbol and decimals are what the index claims: identify a token by its275 /// contract address, and read its decimals on chain.276 public let token: TronAddress?277 public let tokenSymbol: String?278 public let tokenDecimals: Int?279 /// Contract type of an `.other` entry ("TriggerSmartContract", "FreezeBalanceV2Contract"…).280 public let contractType: String?281282 public var id: String { "\(kind.rawValue):\(txID):\(token?.base58 ?? ""):\(from.base58):\(to?.base58 ?? ""):\(amount)" }283 public var date: Date? { timestamp.map { Date(timeIntervalSince1970: TimeInterval($0 / 1000)) } }284}285286/// A page of history and the cursor of the next one.287public struct TronHistoryPage: Equatable, Sendable {288 public let items: [TronTransfer]289 /// Pass it back as `fingerprint` to read the following page; nil on the last page.290 public let nextFingerprint: String?291}292293/// Client of the java-tron full-node HTTP API (`/wallet/...`, `/walletsolidity/...`) and of the TronGrid history index294/// (`/v1/accounts/...`), over the injected transport.295///296/// Addresses and call data are always sent in hexadecimal; integers are read exactly (never through `Double`); every297/// answer is bounded in size and validated before use. Several bases are tried in order and the first that answers298/// wins; an error reported by a node is an answer and is not retried elsewhere. Call `verifyChain()` once per session299/// before trusting what the endpoints say.300public struct TronClient: Sendable {301 /// Largest answer accepted, in bytes (a history page of 200 entries is well under a megabyte).302 public static let maximumResponseBytes = 4 << 20303 /// Most history entries asked for in one page (the index allows 200).304 public static let maximumPageSize = 200305306 public let network: TronNetwork307 let nodes: [URL]308 let indexes: [URL]309 let transport: HTTPTransport310 let apiKey: TronAPIKey?311 let pacing: TronPacing312 /// One pacer for every client of the process: two clients of the same host are spaced as one.313 static let pacer = TronPacer()314315 public init(network: TronNetwork, endpoints: TronEndpoints = .default, transport: HTTPTransport, apiKey: TronAPIKey? = nil, pacing: TronPacing = .default) {316 self.network = network317 nodes = TronEndpoints.bases(endpoints.fullNodes[network.rawValue] ?? [])318 indexes = TronEndpoints.bases(endpoints.history[network.rawValue] ?? [])319 self.transport = transport320 self.apiKey = apiKey321 self.pacing = pacing322 }323324 public var isConfigured: Bool { !nodes.isEmpty }325 public var hasHistory: Bool { !indexes.isEmpty }326327 // MARK: Transport328329 static func isTronGrid(_ url: URL) -> Bool {330 guard let host = url.host?.lowercased() else { return false }331 return host == "trongrid.io" || host.hasSuffix(".trongrid.io")332 }333334 /// One request to one base. `body` nil = GET.335 func request(_ base: URL, _ path: String, _ body: TronJSON?) async throws -> TronJSON {336 guard let url = URL(string: base.absoluteString + path) else { throw NetworkError.invalidURL }337 var r = URLRequest(url: url)338 r.httpMethod = body == nil ? "GET" : "POST"339 r.setValue("application/json", forHTTPHeaderField: "Accept")340 if let body {341 r.setValue("application/json", forHTTPHeaderField: "Content-Type")342 r.httpBody = body.serialized343 }344 let grid = Self.isTronGrid(url)345 if let apiKey, grid, url.scheme == "https" { r.setValue(apiKey.value, forHTTPHeaderField: "TRON-PRO-API-KEY") }346 let interval = grid ? pacing.tronGridIntervalMilliseconds : pacing.otherIntervalMilliseconds347 var attempt = 0348 while true {349 let wait = await Self.pacer.delay(host: url.host ?? "", interval: .milliseconds(Int64(min(interval, 60_000))))350 if wait > .zero { try await Task.sleep(for: wait) }351 let (data, response) = try await transport.send(r)352 if response.statusCode == 429, attempt < pacing.rateLimitRetries {353 attempt += 1354 var backoff = min(pacing.rateLimitBackoffMilliseconds, 30_000)355 if let text = response.value(forHTTPHeaderField: "Retry-After"), let seconds = UInt64(text) { backoff = min(seconds, 30) * 1000 }356 if backoff > 0 { try await Task.sleep(for: .milliseconds(Int64(backoff))) }357 continue358 }359 guard (200...299).contains(response.statusCode) else {360 throw NetworkError.http(status: response.statusCode, body: String(decoding: data.prefix(200), as: UTF8.self))361 }362 guard data.count <= Self.maximumResponseBytes else { throw NetworkError.invalidResponse("response larger than \(Self.maximumResponseBytes) bytes") }363 guard let json = TronJSON.parse(data) else { throw NetworkError.invalidResponse(path) }364 if let message = json["Error"]?.string { throw NetworkError.rpc(code: 0, message: Self.clean(message)) }365 return json366 }367 }368369 /// Tries each base in order; the first that gives a usable answer wins. A node-reported error is thrown at once.370 func first<T: Sendable>(_ bases: [URL], _ path: String, _ body: TronJSON?, _ map: @Sendable (TronJSON) throws -> T) async throws -> T {371 guard !bases.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }372 var failures = [String]()373 for base in bases {374 do {375 return try map(try await request(base, path, body))376 } catch let e as NetworkError {377 if case .rpc = e { throw e }378 failures.append("\(base.host ?? "?"): \(e.summary)")379 } catch is CancellationError {380 throw CancellationError()381 } catch {382 failures.append("\(base.host ?? "?"): \(NetworkError.transportSummary(error))")383 }384 }385 throw NetworkError.allEndpointsFailed(failures)386 }387388 func node<T: Sendable>(_ path: String, _ body: [String: TronJSON] = [:], _ map: @Sendable (TronJSON) throws -> T) async throws -> T {389 try await first(nodes, path, .object(body), map)390 }391392 /// Text from a server, made safe to show: printable characters only, 200 at most.393 static func clean(_ text: String) -> String {394 String(String.UnicodeScalarView(text.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7f }.prefix(200)))395 }396397 /// A message field of the node: sometimes text, sometimes the hexadecimal of UTF-8 text.398 static func message(_ v: TronJSON?) -> String {399 guard let s = v?.string, !s.isEmpty else { return "" }400 if s.utf8.count % 2 == 0, s.utf8.count <= 2000, let bytes = Hex.decode(s), let decoded = String(validating: bytes, as: UTF8.self),401 decoded.unicodeScalars.allSatisfy({ $0.value >= 0x20 && $0.value != 0x7f }) {402 return clean(decoded)403 }404 return clean(s)405 }406407 static func hexBytes(_ v: TronJSON?, count: Int? = nil, maximum: Int = 1 << 16) -> Bytes? {408 guard let s = v?.string, s.utf8.count <= maximum * 2, let b = Hex.decode(s) else { return nil }409 if let count, b.count != count { return nil }410 return b411 }412413 static func isTxID(_ s: String) -> Bool {414 s.utf8.count == 64 && s.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) }415 }416417 // MARK: Blocks and chain identity418419 static func block(_ json: TronJSON, _ what: String) throws -> TronBlockReference {420 let raw = json["block_header"]?["raw_data"]421 guard let id = hexBytes(json["blockID"], count: 32), let raw, raw.object != nil else { throw NetworkError.invalidResponse(what) }422 // the genesis block has no "number" member423 let number: UInt64424 if let n = raw["number"] {425 guard let v = n.uint64 else { throw NetworkError.invalidResponse(what) }426 number = v427 } else {428 number = 0429 }430 let timestamp = raw["timestamp"]?.uint64 ?? 0431 guard let reference = TronBlockReference(number: number, id: id, timestamp: timestamp) else { throw NetworkError.invalidResponse(what) }432 return reference433 }434435 /// Checks that every endpoint that answers serves this network, by the id of its genesis block436 /// (`/wallet/getblockbynum {"num":0}`). At least one must answer; one that serves another chain is a437 /// `disagreement`, whatever the others say.438 public func verifyChain() async throws {439 guard !nodes.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }440 var verified = 0441 var failures = [String]()442 for base in nodes {443 do {444 let genesis = try Self.block(try await request(base, "/wallet/getblockbynum", .object(["num": .number("0")])), "genesis block")445 guard genesis.number == 0, genesis.idHex == network.genesisBlockID else {446 throw NetworkError.disagreement("\(base.host ?? "?") serves another chain than \(network.displayName) (genesis block \(genesis.idHex.prefix(24))…)")447 }448 verified += 1449 } catch let e as NetworkError {450 if case .disagreement = e { throw e }451 failures.append("\(base.host ?? "?"): \(e.summary)")452 } catch is CancellationError {453 throw CancellationError()454 } catch {455 failures.append("\(base.host ?? "?"): \(NetworkError.transportSummary(error))")456 }457 }458 guard verified > 0 else { throw NetworkError.allEndpointsFailed(failures) }459 }460461 /// The head block (header only).462 public func latestBlock() async throws -> TronBlockReference {463 try await node("/wallet/getblock", ["detail": .bool(false)]) { try Self.block($0, "head block") }464 }465466 /// The latest irreversible block (header only): the reference block to build a transaction on, since a block that467 /// can still be replaced would invalidate the transaction with it.468 public func latestSolidBlock() async throws -> TronBlockReference {469 try await node("/walletsolidity/getblock", ["detail": .bool(false)]) { try Self.block($0, "irreversible block") }470 }471472 /// The block a new transaction refers to: an irreversible block on which every full node that answers agrees.473 ///474 /// Nothing in a TRON transaction names its chain: the reference block alone ties it to one. A node that lies475 /// about that block (a block of another TRON network, for example) would get a transaction signed that is valid476 /// elsewhere. So the block is not taken from the first answer: each configured node is asked for its latest477 /// irreversible block, the oldest of them is kept (the others must already have it), and every other node is478 /// asked for the block of that number (`/walletsolidity/getblockbynum`). A node that gives another id is a479 /// `disagreement` and nothing is built. A node that does not answer, or does not have the block yet, is left480 /// out; with a single node configured (or reachable) there is nothing to compare with, and `confirmations` says so.481 ///482 /// - Returns: the block, and how many nodes other than its source vouched for the same id.483 public func referenceBlock() async throws -> (block: TronBlockReference, confirmations: Int) {484 guard !nodes.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }485 var heads = [(base: URL, block: TronBlockReference)]()486 var failures = [String]()487 for base in nodes {488 do {489 heads.append((base, try Self.block(try await request(base, "/walletsolidity/getblock", .object(["detail": .bool(false)])), "irreversible block")))490 } catch is CancellationError {491 throw CancellationError()492 } catch let e as NetworkError {493 failures.append("\(base.host ?? "?"): \(e.summary)")494 } catch {495 failures.append("\(base.host ?? "?"): \(NetworkError.transportSummary(error))")496 }497 }498 guard let chosen = heads.min(by: { $0.block.number < $1.block.number }) else { throw NetworkError.allEndpointsFailed(failures) }499 var confirmations = 0500 for (base, head) in heads where base != chosen.base {501 let seen: TronBlockReference?502 if head.number == chosen.block.number {503 seen = head504 } else {505 do {506 let json = try await request(base, "/walletsolidity/getblockbynum", .object(["num": .number(String(chosen.block.number))]))507 // a node that does not have the block answers an empty object508 seen = json.object?.isEmpty == true ? nil : try Self.block(json, "irreversible block \(chosen.block.number)")509 } catch is CancellationError {510 throw CancellationError()511 } catch {512 seen = nil513 }514 }515 guard let seen else { continue }516 guard seen.number == chosen.block.number, seen.id == chosen.block.id else {517 throw NetworkError.disagreement("\(base.host ?? "?") and \(chosen.base.host ?? "?") give different irreversible blocks at height \(chosen.block.number): one of them serves another chain")518 }519 confirmations += 1520 }521 return (chosen.block, confirmations)522 }523524 /// True when a transaction carrying these `ref_block_bytes` and `ref_block_hash` passes the reference-block check525 /// (TaPoS) of THIS network now: the chain keeps, for each value of the two low-order bytes of a block number, the526 /// hash of the latest block with that number; the transaction is accepted when bytes 8 to 15 of that block's id527 /// are its `ref_block_hash`. Used to make sure that a transaction prepared for a test network is not also valid528 /// on the main one. Only the two fields are involved: no address, no amount is sent.529 public func acceptsReference(refBlockBytes: Bytes, refBlockHash: Bytes) async throws -> Bool {530 guard refBlockBytes.count == 2, refBlockHash.count == 8 else { throw NetworkError.invalidURL }531 let head = try await latestBlock()532 let low = UInt64(refBlockBytes[0]) << 8 | UInt64(refBlockBytes[1])533 // the latest block, at or under the head, whose number ends with these two bytes534 let aligned = (head.number & ~UInt64(0xffff)) | low535 if aligned > head.number, aligned < 0x1_0000 { return false }536 let height = aligned > head.number ? aligned - 0x1_0000 : aligned537 if height == head.number { return head.refBlockHash == refBlockHash }538 let block = try await node("/wallet/getblockbynum", ["num": .number(String(height))]) { try Self.block($0, "block") }539 guard block.number == height else { throw NetworkError.invalidResponse("getblockbynum: another block than the one asked for") }540 return block.refBlockHash == refBlockHash541 }542543 // MARK: Accounts544545 /// Balance and kind of an account (`/wallet/getaccount`). An address the chain has never seen is returned with546 /// `isActivated` false and a zero balance.547 public func account(_ address: TronAddress) async throws -> TronAccount {548 try await node("/wallet/getaccount", ["address": .string(address.hex)]) { json in549 guard let o = json.object else { throw NetworkError.invalidResponse("getaccount") }550 guard let reported = o["address"] else { return TronAccount(address: address, isActivated: false, balanceSun: 0, isContract: false) }551 guard let s = reported.string, TronAddress(any: s) == address else { throw NetworkError.invalidResponse("getaccount: another address") }552 var balance: UInt64 = 0553 if let b = o["balance"] {554 guard let v = b.uint64, v <= UInt64(Int64.max) else { throw NetworkError.invalidResponse("getaccount: balance") }555 balance = v556 }557 return TronAccount(address: address, isActivated: true, balanceSun: balance, isContract: o["type"]?.string == "Contract")558 }559 }560561 /// Bandwidth and energy of an account (`/wallet/getaccountresource`); all zero for an unactivated address.562 public func resources(_ address: TronAddress) async throws -> TronResources {563 try await node("/wallet/getaccountresource", ["address": .string(address.hex)]) { json in564 guard let o = json.object else { throw NetworkError.invalidResponse("getaccountresource") }565 func value(_ key: String) throws -> UInt64 {566 guard let v = o[key] else { return 0 }567 guard let n = v.uint64 else { throw NetworkError.invalidResponse("getaccountresource: \(key)") }568 return n569 }570 return TronResources(freeNetLimit: try value("freeNetLimit"), freeNetUsed: try value("freeNetUsed"), netLimit: try value("NetLimit"),571 netUsed: try value("NetUsed"), energyLimit: try value("EnergyLimit"), energyUsed: try value("EnergyUsed"))572 }573 }574575 /// The fee parameters of the chain (`/wallet/getchainparameters`). A missing or non-positive price is refused:576 /// the planner must not compute a fee from a default.577 public func chainParameters() async throws -> TronChainParameters {578 try await node("/wallet/getchainparameters") { json in579 guard let list = json["chainParameter"]?.array, list.count <= 1000 else { throw NetworkError.invalidResponse("getchainparameters") }580 var values = [String: UInt64]()581 for entry in list {582 if let key = entry["key"]?.string, let v = entry["value"]?.uint64 { values[key] = v }583 }584 func required(_ key: String, positive: Bool = false) throws -> UInt64 {585 guard let v = values[key], v <= UInt64(Int64.max), !positive || v > 0 else { throw NetworkError.invalidResponse("chain parameter \(key)") }586 return v587 }588 return TronChainParameters(bandwidthPriceSun: try required("getTransactionFee", positive: true),589 energyPriceSun: try required("getEnergyFee", positive: true),590 accountActivationFeeSun: try required("getCreateNewAccountFeeInSystemContract"),591 createAccountFeeSun: try required("getCreateAccountFee"),592 createAccountBandwidthRate: try required("getCreateNewAccountBandwidthRate"),593 maximumFeeLimitSun: try required("getMaxFeeLimit", positive: true),594 memoFeeSun: min(values["getMemoFee"] ?? 0, UInt64(Int64.max)))595 }596 }597598 // MARK: Contracts599600 /// Executes a call without broadcasting anything (`/wallet/triggerconstantcontract`). A revert is reported in the601 /// result (`succeeded` false), not thrown; a call the node refuses to run (no contract at the address…) throws602 /// `NetworkError.rpc`.603 public func constantCall(owner: TronAddress, contract: TronAddress, data: Bytes) async throws -> TronConstantResult {604 guard data.count <= 4096 else { throw NetworkError.invalidURL }605 return try await node("/wallet/triggerconstantcontract", ["owner_address": .string(owner.hex), "contract_address": .string(contract.hex), "data": .string(Hex.encode(data))]) { json in606 guard let result = json["result"], result.object != nil else { throw NetworkError.invalidResponse("triggerconstantcontract") }607 guard result["result"]?.bool == true else {608 throw NetworkError.rpc(code: 0, message: Self.clean("\(result["code"]?.string ?? "rejected"): \(Self.message(result["message"]))"))609 }610 let message = Self.message(result["message"])611 let failed = !message.isEmpty || json["transaction"]?["ret"]?.array?.first?["ret"]?.string == "FAILED"612 var output = Bytes()613 if let first = json["constant_result"]?.array?.first {614 guard let b = Self.hexBytes(first, maximum: 8192) else { throw NetworkError.invalidResponse("triggerconstantcontract: result") }615 output = b616 }617 var energy: UInt64 = 0618 if let e = json["energy_used"] {619 guard let v = e.uint64 else { throw NetworkError.invalidResponse("triggerconstantcontract: energy") }620 energy = v621 }622 return TronConstantResult(succeeded: !failed, message: message, output: output, energyUsed: energy)623 }624 }625626 private func read(_ token: TronAddress, _ data: Bytes, _ what: String) async throws -> Bytes {627 let r = try await constantCall(owner: .zero, contract: token, data: data)628 guard r.succeeded else { throw NetworkError.invalidResponse("\(what): the call failed") }629 return r.output630 }631632 /// `balanceOf(owner)` of a TRC-20 contract, in base units.633 public func tokenBalance(token: TronAddress, owner: TronAddress) async throws -> UInt256 {634 guard let v = ERC20.decodeUInt(try await read(token, ERC20.balanceOf(owner.evm), "balanceOf")) else { throw NetworkError.invalidResponse("balanceOf") }635 return v636 }637638 /// `decimals()` of a TRC-20 contract (refused above 77: such a unit could not be a uint256 amount).639 public func tokenDecimals(_ token: TronAddress) async throws -> Int {640 guard let v = ERC20.decodeUInt(try await read(token, ERC20.decimalsSelector, "decimals"))?.uint64, v <= 77 else { throw NetworkError.invalidResponse("decimals") }641 return Int(v)642 }643644 /// `symbol()` of a TRC-20 contract: what the contract claims, nothing more.645 public func tokenSymbol(_ token: TronAddress) async throws -> String {646 guard let s = ERC20.decodeString(try await read(token, ERC20.symbolSelector, "symbol")) else { throw NetworkError.invalidResponse("symbol") }647 return s648 }649650 /// `name()` of a TRC-20 contract.651 public func tokenName(_ token: TronAddress) async throws -> String {652 guard let s = ERC20.decodeString(try await read(token, ERC20.nameSelector, "name")) else { throw NetworkError.invalidResponse("name") }653 return s654 }655656 /// True when the address is a contract whose `decimals()` and `symbol()` are those recorded for the token.657 public func verify(token: TronToken) async throws -> Bool {658 guard token.network == network, try await account(token.contract).isContract else { return false }659 guard try await tokenDecimals(token.contract) == token.decimals else { return false }660 return try await tokenSymbol(token.contract) == token.symbol661 }662663 /// Simulates `transfer(to, amount)` sent by `from` on current state: `energyUsed` is the energy estimate, and664 /// `succeeded` false means the real transfer would revert (insufficient balance, frozen account…). The value the665 /// call returns is deliberately ignored: USDT returns false or nothing on a transfer that succeeds.666 public func simulateTokenTransfer(token: TronAddress, from: TronAddress, to: TronAddress, amount: UInt256) async throws -> TronConstantResult {667 try await constantCall(owner: from, contract: token, data: ERC20.transfer(to: to.evm, amount: amount))668 }669670 // MARK: Building cross-check671672 /// Asks a node to build the same TRX transfer (`/wallet/createtransaction`) and returns the `raw_data` bytes it673 /// proposes. For comparison only: the wallet signs the bytes it encoded itself, never these.674 public func nodeBuiltTransfer(from: TronAddress, to: TronAddress, amountSun: UInt64) async throws -> Bytes {675 guard amountSun <= UInt64(Int64.max) else { throw NetworkError.invalidURL }676 return try await node("/wallet/createtransaction", ["owner_address": .string(from.hex), "to_address": .string(to.hex), "amount": .number(String(amountSun))]) { json in677 guard let raw = Self.hexBytes(json["raw_data_hex"], maximum: TronTransaction.maximumRawDataBytes), !raw.isEmpty else {678 throw NetworkError.invalidResponse("createtransaction")679 }680 return raw681 }682 }683684 // MARK: Broadcast685686 /// Sends a signed transaction (`/wallet/broadcasthex`) to the nodes in turn until one accepts it. The transaction687 /// id a node returns must be the local one. Acceptance is not confirmation.688 public func broadcast(_ signed: SignedTronTransaction) async throws -> TronBroadcastResult {689 guard !nodes.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }690 guard !signed.signatures.isEmpty else { return .rejected(code: "UNSIGNED", message: "the transaction carries no signature") }691 let txID = signed.txIDHex692 var rejection: TronBroadcastResult?693 var failures = [String]()694 for base in nodes {695 do {696 let json = try await request(base, "/wallet/broadcasthex", .object(["transaction": .string(signed.hex)]))697 guard json.object != nil else { throw NetworkError.invalidResponse("broadcasthex") }698 if let reported = json["txid"]?.string, !reported.isEmpty, reported.lowercased() != txID {699 throw NetworkError.invalidResponse("broadcasthex: another transaction id")700 }701 let code = json["code"]?.string702 if json["result"]?.bool == true || code == "SUCCESS" { return .accepted(txID: txID) }703 if code == "DUP_TRANSACTION_ERROR" { return .alreadyKnown(txID: txID) }704 if rejection == nil { rejection = .rejected(code: Self.clean(code ?? "REJECTED"), message: Self.message(json["message"])) }705 } catch let e as NetworkError {706 if case .rpc(_, let message) = e {707 if rejection == nil { rejection = .rejected(code: "ERROR", message: message) }708 } else {709 failures.append("\(base.host ?? "?"): \(e.summary)")710 }711 } catch is CancellationError {712 throw CancellationError()713 } catch {714 failures.append("\(base.host ?? "?"): \(NetworkError.transportSummary(error))")715 }716 }717 if let rejection { return rejection }718 throw NetworkError.allEndpointsFailed(failures)719 }720721 // MARK: Transaction status722723 /// Where a transaction stands (`gettransactioninfobyid` and `gettransactionbyid`), on head state or, with724 /// `irreversibleOnly`, on the irreversible state: only the latter is final.725 public func transactionStatus(id: String, irreversibleOnly: Bool = false) async throws -> TronTransactionStatus {726 guard Self.isTxID(id) else { throw NetworkError.invalidURL }727 let prefix = irreversibleOnly ? "/walletsolidity" : "/wallet"728 let body: [String: TronJSON] = ["value": .string(id)]729 let info = try await node(prefix + "/gettransactioninfobyid", body) { json -> TronJSON in730 guard json.object != nil else { throw NetworkError.invalidResponse("gettransactioninfobyid") }731 return json732 }733 let tx = try await node(prefix + "/gettransactionbyid", body) { json -> TronJSON in734 guard json.object != nil else { throw NetworkError.invalidResponse("gettransactionbyid") }735 return json736 }737 let included = info["id"]?.string == id738 let known = tx["txID"]?.string == id739 var transaction: TronTransaction?740 if known, let raw = Self.hexBytes(tx["raw_data_hex"], maximum: TronTransaction.maximumRawDataBytes) {741 guard Hex.encode(SHA256.hash(raw)) == id else { throw NetworkError.invalidResponse("gettransactionbyid: the bytes do not hash to the id") }742 transaction = try? TronTransaction.decode(rawData: raw)743 }744 let contractResult = known ? tx["ret"]?.array?.first?["contractRet"]?.string.map(Self.clean) : nil745 guard included else {746 return TronTransactionStatus(txID: id, state: known ? .pending : .notFound, irreversible: irreversibleOnly, blockNumber: nil, blockTimestamp: nil,747 feeSun: 0, energyUsed: 0, energyFeeSun: 0, netFeeSun: 0, contractResult: contractResult, receiptResult: nil,748 message: nil, transaction: transaction)749 }750 let receipt = info["receipt"]751 let receiptResult = receipt?["result"]?.string.map(Self.clean)752 let failed = info["result"]?.string == "FAILED" || (receiptResult != nil && receiptResult != "SUCCESS") || (contractResult != nil && contractResult != "SUCCESS")753 let message = Self.message(info["resMessage"])754 return TronTransactionStatus(txID: id, state: failed ? .failed : .succeeded, irreversible: irreversibleOnly,755 blockNumber: info["blockNumber"]?.uint64, blockTimestamp: info["blockTimeStamp"]?.uint64,756 feeSun: info["fee"]?.uint64 ?? 0, energyUsed: receipt?["energy_usage_total"]?.uint64 ?? 0,757 energyFeeSun: receipt?["energy_fee"]?.uint64 ?? 0, netFeeSun: receipt?["net_fee"]?.uint64 ?? 0,758 contractResult: contractResult, receiptResult: receiptResult, message: message.isEmpty ? nil : message,759 transaction: transaction)760 }761762 // MARK: History (TronGrid index)763764 private func page(_ path: String, limit: Int, _ item: @Sendable (TronJSON) -> TronTransfer?) async throws -> TronHistoryPage {765 try await first(indexes, path, nil) { json in766 guard json["success"]?.bool == true, let data = json["data"]?.array else { throw NetworkError.invalidResponse("history") }767 var next: String?768 if let f = json["meta"]?["fingerprint"]?.string, Self.isFingerprint(f) { next = f }769 return TronHistoryPage(items: data.prefix(limit).compactMap(item), nextFingerprint: next)770 }771 }772773 static func isFingerprint(_ s: String) -> Bool {774 (1...1024).contains(s.utf8.count) && s.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x41 && $0 <= 0x5a) || ($0 >= 0x61 && $0 <= 0x7a) }775 }776777 private static func query(limit: Int, fingerprint: String?, confirmedOnly: Bool, onlyFrom: Bool = false) throws -> String {778 var q = "limit=\(limit)&order_by=block_timestamp,desc"779 if confirmedOnly { q += "&only_confirmed=true" }780 if onlyFrom { q += "&only_from=true" }781 if let fingerprint {782 guard isFingerprint(fingerprint) else { throw NetworkError.invalidURL }783 q += "&fingerprint=\(fingerprint)"784 }785 return q786 }787788 /// Transactions of the account, newest first (`/v1/accounts/{address}/transactions`). Each entry is rebuilt from789 /// the raw bytes the index returns, which must hash to the transaction id: an entry that does not is dropped.790 ///791 /// `onlyFrom` asks the index for the transactions the account itself initiated (`only_from=true`). The index is792 /// not trusted to have filtered: the caller still checks `from` on every entry.793 public func transactions(of address: TronAddress, limit: Int = 20, fingerprint: String? = nil, confirmedOnly: Bool = false,794 onlyFrom: Bool = false) async throws -> TronHistoryPage {795 let limit = max(1, min(limit, Self.maximumPageSize))796 let path = "/v1/accounts/\(address.base58)/transactions?" + (try Self.query(limit: limit, fingerprint: fingerprint, confirmedOnly: confirmedOnly, onlyFrom: onlyFrom))797 return try await page(path, limit: limit) { t in798 guard let id = t["txID"]?.string, Self.isTxID(id), let raw = Self.hexBytes(t["raw_data_hex"], maximum: TronTransaction.maximumRawDataBytes),799 Hex.encode(SHA256.hash(raw)) == id, let tx = try? TronTransaction.decode(rawData: raw) else { return nil }800 let ret = t["ret"]?.array?.first801 let succeeded = ret?["contractRet"]?.string == "SUCCESS"802 let common = (timestamp: t["block_timestamp"]?.uint64, block: t["blockNumber"]?.uint64, confirmed: t["_unconfirmed"]?.bool != true, fee: ret?["fee"]?.uint64 ?? 0)803 switch tx.contract {804 case .transfer(let c):805 return TronTransfer(kind: .trx, txID: id, from: c.owner, to: c.to, amount: UInt256(c.amount), timestamp: common.timestamp, blockNumber: common.block,806 succeeded: succeeded, confirmed: common.confirmed, feeSun: common.fee, token: nil, tokenSymbol: nil, tokenDecimals: nil, contractType: nil)807 case .triggerSmartContract(let c):808 return TronTransfer(kind: .other, txID: id, from: c.owner, to: c.contract, amount: UInt256(c.callValue), timestamp: common.timestamp, blockNumber: common.block,809 succeeded: succeeded, confirmed: common.confirmed, feeSun: common.fee, token: nil, tokenSymbol: nil, tokenDecimals: nil,810 contractType: "TriggerSmartContract")811 case .unknown(let type, _, _):812 // the owner of a contract the wallet does not decode is taken from the index, for display only813 guard let owner = t["raw_data"]?["contract"]?.array?.first?["parameter"]?["value"]?["owner_address"]?.string.flatMap({ TronAddress(any: $0) }) else { return nil }814 return TronTransfer(kind: .other, txID: id, from: owner, to: nil, amount: .zero, timestamp: common.timestamp, blockNumber: common.block,815 succeeded: succeeded, confirmed: common.confirmed, feeSun: common.fee, token: nil, tokenSymbol: nil, tokenDecimals: nil,816 contractType: TronContract.typeName(type) ?? "contract type \(type)")817 }818 }819 }820821 /// TRC-20 transfers touching the account, newest first (`/v1/accounts/{address}/transactions/trc20`), optionally822 /// for one token contract. These come from the index alone: confirm an entry with `transactionStatus` before823 /// treating it as a payment.824 public func tokenTransfers(of address: TronAddress, token: TronAddress? = nil, limit: Int = 20, fingerprint: String? = nil, confirmedOnly: Bool = false) async throws -> TronHistoryPage {825 let limit = max(1, min(limit, Self.maximumPageSize))826 var path = "/v1/accounts/\(address.base58)/transactions/trc20?" + (try Self.query(limit: limit, fingerprint: fingerprint, confirmedOnly: confirmedOnly))827 if let token { path += "&contract_address=\(token.base58)" }828 return try await page(path, limit: limit) { t in829 guard let id = t["transaction_id"]?.string, Self.isTxID(id), t["type"]?.string == "Transfer",830 let from = t["from"]?.string.flatMap({ TronAddress(any: $0) }), let to = t["to"]?.string.flatMap({ TronAddress(any: $0) }),831 let value = t["value"]?.string, let amount = UInt256(decimal: value),832 let info = t["token_info"], let contract = info["address"]?.string.flatMap({ TronAddress(any: $0) }) else { return nil }833 if let token, token != contract { return nil }834 let symbol = info["symbol"]?.string.map { String(Self.clean($0).prefix(16)) }835 let decimals = info["decimals"]?.uint64.flatMap { $0 <= 77 ? Int($0) : nil }836 return TronTransfer(kind: .trc20, txID: id, from: from, to: to, amount: amount, timestamp: t["block_timestamp"]?.uint64, blockNumber: nil,837 succeeded: true, confirmed: t["_unconfirmed"]?.bool != true, feeSun: nil, token: contract, tokenSymbol: symbol,838 tokenDecimals: decimals, contractType: nil)839 }840 }841}842