SPB Git

Repository Public

TronSendPlanner.swift 22.9 KB 415 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraTron/TronSendPlanner.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 QyvoraCore4445/// Why a transfer cannot be planned. Every refusal is decided on the device, before anything is signed.46public enum TronPlanError: Error, Equatable, Sendable {47    case zeroAmount48    case recipientIsSender49    /// The recipient is 0x41 followed by twenty zero bytes.50    case recipientIsZeroAddress51    /// The recipient is a token contract (the token being sent, or a built-in one): tokens and TRX sent there are lost.52    case recipientIsTokenContract(TronAddress)53    /// The token address is not a smart-contract account on this chain.54    case tokenIsNotAContract55    /// The sending address has never been activated: it holds nothing and cannot send.56    case senderNotActivated57    /// Not enough TRX for the amount plus the network fee.58    case insufficientBalance(requiredSun: UInt64, availableSun: UInt64)59    /// Not enough TRX to pay for the bandwidth and the energy of a token transfer, margin included.60    case insufficientTRXForFees(requiredSun: UInt64, availableSun: UInt64)61    case insufficientTokenBalance(required: UInt256, available: UInt256)62    /// The simulated transfer reverted; the text is the node's reason.63    case simulationFailed(String)64    /// The simulation reported no energy use: no fee limit can be derived from it.65    case invalidEnergyEstimate66    /// The fee limit the transfer needs is above the wallet's cap or the protocol's.67    case feeLimitTooHigh(requiredSun: UInt64, capSun: UInt64)68    /// The amount is above the per-transaction limit of the policy.69    case amountAboveLimit(limitSun: UInt64)70    /// The device clock and the reference block are too far apart: the clock is wrong or the endpoint is stale.71    case clockSkew72    /// The planner policy is out of its allowed ranges.73    case invalidPolicy74    /// The chain parameters or the amounts do not fit in the protocol's integers.75    case arithmeticOverflow76    /// The transaction could not be built.77    case invalidTransaction(TronTransaction.Error)78}7980/// A transfer ready for review: the unsigned transaction and everything it will cost.81public struct TronSendPlan: Equatable, Sendable {82    public enum Asset: Equatable, Sendable {83        case trx84        /// A TRC-20 token, by contract address.85        case trc20(TronAddress)86    }8788    /// What pays for the bytes of the transaction.89    public enum BandwidthSource: Equatable, Sendable {90        /// Bandwidth obtained by staking: nothing is burned.91        case staked92        /// The free daily allowance: nothing is burned.93        case free94        /// Neither is enough for the whole transaction: every byte is paid in TRX.95        case burned96        /// The transaction creates the recipient account: the account-creation fees replace the bandwidth charge.97        case accountCreation98    }99100    public enum Note: Equatable, Sendable {101        /// The recipient address is new: this TRX transfer creates it and burns the fee given, on top of the amount.102        case activatesRecipient(feeSun: UInt64)103        /// The recipient of the tokens has never been activated. The transfer is allowed and the protocol charges no104        /// activation fee for it; the energy estimate already includes the cost of a first-time holder, and the105        /// recipient will need TRX or energy to move the tokens.106        case tokenRecipientNotActivated107        /// The recipient is a smart contract.108        case recipientIsContract109        /// TRX is burned for bandwidth.110        case burnsTRXForBandwidth(sun: UInt64)111        /// TRX is burned for energy (expected amount; at most the fee limit).112        case burnsTRXForEnergy(sun: UInt64)113        /// The memo costs the chain's memo fee.114        case memoFee(sun: UInt64)115        /// A token `transfer` may return nothing or false even when it works (USDT): after broadcast, the outcome is116        /// `TronTransactionStatus.state`, read from the receipt.117        case confirmWithReceipt118    }119120    /// The unsigned transaction, built locally.121    public let transaction: TronTransaction122    public let asset: Asset123    public let from: TronAddress124    public let to: TronAddress125    /// Sun for TRX, base units for a token.126    public let amount: UInt256127128    /// Bytes charged as bandwidth (serialised transaction with one signature, plus 64).129    public let bandwidthBytes: UInt64130    public let bandwidthSource: BandwidthSource131    /// TRX burned for bandwidth as things stand, in sun.132    public let bandwidthFeeSun: UInt64133134    /// Energy the simulation used (0 for TRX).135    public let energyEstimate: UInt64136    /// The estimate with the safety margin: the most energy the fee limit lets the call use.137    public let energyLimit: UInt64138    /// Energy the sender has from staking.139    public let energyAvailable: UInt64140    /// TRX expected to be burned for energy, in sun.141    public let energyFeeSun: UInt64142143    /// Account-creation fees of a TRX transfer to a new address, in sun.144    public let activationFeeSun: UInt64145    public let memoFeeSun: UInt64146    /// `fee_limit` of the transaction, in sun (0 for TRX).147    public let feeLimitSun: UInt64148149    /// Network fee expected as things stand, in sun.150    public let estimatedFeeSun: UInt64151    /// The most the transaction can burn if the sender's free resources are used up before it is included, in sun.152    public let maximumFeeSun: UInt64153    /// Most TRX that can leave the account: the amount (for TRX) plus `maximumFeeSun`.154    public let maximumDebitSun: UInt64155156    public let notes: [Note]157158    /// The review of `transaction`, to show next to the fees.159    public var review: TronTransactionReview { TronTransactionReview(transaction) }160}161162/// Turns chain state into a reviewable transfer. Pure: no network access, no clock, no randomness. The service reads163/// the state with `TronClient`, hands it over and gets back either a plan or a typed refusal.164///165/// Fee model (java-tron `BandwidthProcessor`, `TransferActuator` and the VM fee rules; parameters read on chain):166/// - Bandwidth: the transaction costs its serialised size plus 64 bytes. It is taken whole from staked bandwidth if167///   that is enough, else whole from the free daily allowance if that is enough, else every byte is burned at168///   `bandwidthPriceSun`. The two allowances are never combined.169/// - A TRX transfer to an address the chain has never seen creates the account: `accountActivationFeeSun` is burned,170///   plus `createAccountFeeSun` unless staked bandwidth covers size × `createAccountBandwidthRate`; no ordinary171///   bandwidth is charged.172/// - A TRC-20 transfer uses energy: the estimate comes from a simulation, a margin is added, and `fee_limit` is that173///   energy at `energyPriceSun`. Staked energy is used first; the rest is burned. A call that runs out of energy174///   fails and still burns its fee, so the sender must be able to pay for the whole margin.175/// - A memo costs `memoFeeSun`.176public struct TronSendPlanner: Sendable {177    public struct Policy: Equatable, Sendable {178        /// Ceiling of `fee_limit`, in sun: a transfer that needs more is refused (default 100 TRX).179        public var maximumFeeLimitSun: UInt64180        /// Margin added to the simulated energy, in percent (0…100, default 25).181        public var energyMarginPercent: UInt64182        /// Time the signed transaction stays valid, in seconds (30…3600, default 120).183        public var lifetimeSeconds: UInt64184        /// Largest accepted distance between the device clock and the reference block, in seconds (default 300).185        public var maximumClockSkewSeconds: UInt64186        /// Largest TRX amount of one transfer, in sun; nil = no limit. The service sets it on an unaudited mainnet.187        public var maximumAmountSun: UInt64?188189        public init(maximumFeeLimitSun: UInt64 = 100_000_000, energyMarginPercent: UInt64 = 25, lifetimeSeconds: UInt64 = 120,190                    maximumClockSkewSeconds: UInt64 = 300, maximumAmountSun: UInt64? = nil) {191            self.maximumFeeLimitSun = maximumFeeLimitSun192            self.energyMarginPercent = energyMarginPercent193            self.lifetimeSeconds = lifetimeSeconds194            self.maximumClockSkewSeconds = maximumClockSkewSeconds195            self.maximumAmountSun = maximumAmountSun196        }197198        var isValid: Bool {199            energyMarginPercent <= 100 && (30...3600).contains(lifetimeSeconds) && maximumClockSkewSeconds <= 3600 && maximumFeeLimitSun <= UInt64(Int64.max)200        }201    }202203    /// What the planner needs to know about the chain at the time of planning.204    public struct ChainState: Equatable, Sendable {205        public let network: TronNetwork206        public let parameters: TronChainParameters207        /// The block the transaction will refer to (`TronClient.latestSolidBlock`).208        public let reference: TronBlockReference209        /// Device time, milliseconds since 1970.210        public let nowMilliseconds: UInt64211212        public init(network: TronNetwork, parameters: TronChainParameters, reference: TronBlockReference, nowMilliseconds: UInt64) {213            self.network = network214            self.parameters = parameters215            self.reference = reference216            self.nowMilliseconds = nowMilliseconds217        }218    }219220    public enum Amount: Equatable, Sendable {221        /// This many sun.222        case exact(UInt64)223        /// Everything the account holds, less the network fee.224        case max225    }226227    public var policy: Policy228229    public init(policy: Policy = Policy()) { self.policy = policy }230231    // MARK: Arithmetic232233    private static let limit = UInt64(Int64.max)234235    private static func mul(_ a: UInt64, _ b: UInt64) throws(TronPlanError) -> UInt64 {236        let (v, overflow) = a.multipliedReportingOverflow(by: b)237        guard !overflow, v <= limit else { throw .arithmeticOverflow }238        return v239    }240241    private static func add(_ a: UInt64, _ b: UInt64) throws(TronPlanError) -> UInt64 {242        let (v, overflow) = a.addingReportingOverflow(b)243        guard !overflow, v <= limit else { throw .arithmeticOverflow }244        return v245    }246247    /// Timestamp and expiration of a transaction built now on the reference block.248    private func times(_ state: ChainState) throws(TronPlanError) -> (timestamp: UInt64, expiration: UInt64) {249        guard policy.isValid else { throw .invalidPolicy }250        let now = state.nowMilliseconds, block = state.reference.timestamp251        let distance = now > block ? now - block : block - now252        guard distance <= policy.maximumClockSkewSeconds * 1000 else { throw .clockSkew }253        let base = max(now, block)254        return (base, try Self.add(base, policy.lifetimeSeconds * 1000))255    }256257    private func checkParties(state: ChainState, sender: TronAccount, recipient: TronAccount, token: TronAddress?) throws(TronPlanError) {258        guard !recipient.address.isZero else { throw .recipientIsZeroAddress }259        guard recipient.address != sender.address else { throw .recipientIsSender }260        if let token, recipient.address == token { throw .recipientIsTokenContract(token) }261        if TronBuiltInTokens.token(recipient.address, on: state.network) != nil { throw .recipientIsTokenContract(recipient.address) }262        guard sender.isActivated else { throw .senderNotActivated }263    }264265    /// Bandwidth of an ordinary transaction (no account creation): where it comes from and what it burns.266    private static func bandwidth(bytes: UInt64, resources: TronResources, parameters: TronChainParameters) throws(TronPlanError) -> (TronSendPlan.BandwidthSource, UInt64) {267        if resources.stakedBandwidth >= bytes { return (.staked, 0) }268        if resources.freeBandwidth >= bytes { return (.free, 0) }269        return (.burned, try mul(bytes, parameters.bandwidthPriceSun))270    }271272    // MARK: TRX273274    /// Plans a TRX transfer.275    ///276    /// Refused: zero amount, recipient equal to the sender, the zero address or a token contract, unactivated sender,277    /// amount above the policy limit, balance below the amount plus the fee, clock too far from the reference block.278    /// `.max` sends the balance less the expected fee (when bandwidth is burned it may leave up to 0.002 TRX, the price of two bytes).279    public func planTransfer(state: ChainState, sender: TronAccount, resources: TronResources, recipient: TronAccount,280                             amount: Amount, memo: Bytes = []) throws(TronPlanError) -> TronSendPlan {281        if case .exact(0) = amount { throw .zeroAmount }282        try checkParties(state: state, sender: sender, recipient: recipient, token: nil)283        let (timestamp, expiration) = try times(state)284        let p = state.parameters285        let memoFee = memo.isEmpty ? 0 : p.memoFeeSun286287        func build(_ sun: UInt64) throws(TronPlanError) -> TronTransaction {288            do {289                return try TronTransaction.transfer(from: sender.address, to: recipient.address, amountSun: sun, reference: state.reference,290                                                    timestamp: timestamp, expiration: expiration, memo: memo)291            } catch {292                throw .invalidTransaction(error)293            }294        }295        /// (source, bandwidth burn, activation fees, expected fee, maximum fee) of the transaction.296        func fees(_ tx: TronTransaction) throws(TronPlanError) -> (TronSendPlan.BandwidthSource, UInt64, UInt64, UInt64, UInt64) {297            let bytes = UInt64(tx.bandwidthSize())298            if recipient.isActivated {299                let (source, burn) = try Self.bandwidth(bytes: bytes, resources: resources, parameters: p)300                return (source, burn, 0, try Self.add(burn, memoFee), try Self.add(try Self.mul(bytes, p.bandwidthPriceSun), memoFee))301            }302            let covered = resources.stakedBandwidth >= (try Self.mul(bytes, p.createAccountBandwidthRate))303            let activation = try Self.add(p.accountActivationFeeSun, covered ? 0 : p.createAccountFeeSun)304            let worst = try Self.add(try Self.add(p.accountActivationFeeSun, p.createAccountFeeSun), memoFee)305            return (.accountCreation, 0, activation, try Self.add(activation, memoFee), worst)306        }307308        let sun: UInt64309        switch amount {310        case .exact(let v):311            sun = v312        case .max:313            // The fee depends on the encoded size of the amount (a varint of 1 to 9 bytes for values up to 2^63 − 1) and314            // on nothing else about it. For each length the largest amount that leaves its own fee is therefore315            // min(largest value of that length, balance − fee of that length), valid when it still has that length;316            // the answer is the largest of these. An iterative refinement is not used: at a size boundary it317            // alternates between two lengths and settles on less than can be sent (QYV-SVC-105).318            var best: UInt64?319            var lastFee: UInt64 = 0320            for length in 1...9 {321                let lowest: UInt64 = length == 1 ? 1 : UInt64(1) << UInt64(7 * (length - 1))322                let highest: UInt64 = length == 9 ? Self.limit : (UInt64(1) << UInt64(7 * length)) - 1323                guard lowest <= Self.limit, lowest <= sender.balanceSun else { break }324                let fee = try fees(try build(lowest)).3325                lastFee = fee326                guard sender.balanceSun > fee else { continue }327                let candidate = min(highest, sender.balanceSun - fee, Self.limit)328                if candidate >= lowest { best = max(best ?? 0, candidate) }329            }330            guard let best, best > 0 else { throw .insufficientBalance(requiredSun: try Self.add(lastFee, 1), availableSun: sender.balanceSun) }331            sun = best332        }333        guard sun <= Self.limit else { throw .arithmeticOverflow }334        if let cap = policy.maximumAmountSun, sun > cap { throw .amountAboveLimit(limitSun: cap) }335        let tx = try build(sun)336        let (source, bandwidthBurn, activation, expected, worst) = try fees(tx)337        let required = try Self.add(sun, expected)338        guard sender.balanceSun >= required else { throw .insufficientBalance(requiredSun: required, availableSun: sender.balanceSun) }339340        var notes = [TronSendPlan.Note]()341        if !recipient.isActivated { notes.append(.activatesRecipient(feeSun: activation)) }342        if recipient.isContract { notes.append(.recipientIsContract) }343        if bandwidthBurn > 0 { notes.append(.burnsTRXForBandwidth(sun: bandwidthBurn)) }344        if memoFee > 0 { notes.append(.memoFee(sun: memoFee)) }345        return TronSendPlan(transaction: tx, asset: .trx, from: sender.address, to: recipient.address, amount: UInt256(sun),346                            bandwidthBytes: UInt64(tx.bandwidthSize()), bandwidthSource: source, bandwidthFeeSun: bandwidthBurn,347                            energyEstimate: 0, energyLimit: 0, energyAvailable: resources.energy, energyFeeSun: 0,348                            activationFeeSun: activation, memoFeeSun: memoFee, feeLimitSun: 0, estimatedFeeSun: expected, maximumFeeSun: worst,349                            maximumDebitSun: try Self.add(sun, worst), notes: notes)350    }351352    // MARK: TRC-20353354    /// Plans a TRC-20 `transfer`.355    ///356    /// - Parameters:357    ///   - token: the account of the token contract, as `TronClient.account` returned it (it must be a contract).358    ///   - tokenBalance: the sender's balance of the token, in base units.359    ///   - simulation: `TronClient.simulateTokenTransfer` for this very sender, recipient and amount.360    ///361    /// Refused: zero amount, recipient equal to the sender, the zero address, the token's own contract or a built-in362    /// token contract, a token address that is not a contract, unactivated sender, token balance below the amount, a363    /// simulation that reverted or used no energy, a fee limit above the policy cap or the protocol's, not enough TRX364    /// for bandwidth plus energy with its margin. Sending to an address that has never been activated is allowed365    /// (see `Note.tokenRecipientNotActivated`).366    public func planTokenTransfer(state: ChainState, sender: TronAccount, resources: TronResources, recipient: TronAccount, token: TronAccount,367                                  tokenBalance: UInt256, amount: UInt256, simulation: TronConstantResult) throws(TronPlanError) -> TronSendPlan {368        guard !amount.isZero else { throw .zeroAmount }369        guard token.isActivated, token.isContract, !token.address.isZero else { throw .tokenIsNotAContract }370        try checkParties(state: state, sender: sender, recipient: recipient, token: token.address)371        guard tokenBalance >= amount else { throw .insufficientTokenBalance(required: amount, available: tokenBalance) }372        guard simulation.succeeded else { throw .simulationFailed(simulation.message.isEmpty ? "the transfer would revert" : simulation.message) }373        guard simulation.energyUsed > 0 else { throw .invalidEnergyEstimate }374        let (timestamp, expiration) = try times(state)375        let p = state.parameters376377        // energy with its margin, rounded up378        let scaled = try Self.mul(simulation.energyUsed, 100 + policy.energyMarginPercent)379        let energyLimit = scaled / 100 + (scaled % 100 == 0 ? 0 : 1)380        let feeLimit = try Self.mul(energyLimit, p.energyPriceSun)381        let cap = min(policy.maximumFeeLimitSun, p.maximumFeeLimitSun)382        guard feeLimit <= cap else { throw .feeLimitTooHigh(requiredSun: feeLimit, capSun: cap) }383384        let tx: TronTransaction385        do {386            tx = try TronTransaction.trc20Transfer(from: sender.address, token: token.address, to: recipient.address, amount: amount, feeLimitSun: feeLimit,387                                                   reference: state.reference, timestamp: timestamp, expiration: expiration)388        } catch {389            throw .invalidTransaction(error)390        }391        let bytes = UInt64(tx.bandwidthSize())392        let (source, bandwidthBurn) = try Self.bandwidth(bytes: bytes, resources: resources, parameters: p)393        let available = resources.energy394        let energyBurn = try Self.mul(simulation.energyUsed > available ? simulation.energyUsed - available : 0, p.energyPriceSun)395        let worstEnergyBurn = try Self.mul(energyLimit > available ? energyLimit - available : 0, p.energyPriceSun)396        let expected = try Self.add(bandwidthBurn, energyBurn)397        // the whole margin must be payable: a call that runs out of energy fails and burns its fee for nothing398        let required = try Self.add(bandwidthBurn, worstEnergyBurn)399        guard sender.balanceSun >= required else { throw .insufficientTRXForFees(requiredSun: required, availableSun: sender.balanceSun) }400        let worst = try Self.add(try Self.mul(bytes, p.bandwidthPriceSun), feeLimit)401402        var notes = [TronSendPlan.Note]()403        if !recipient.isActivated { notes.append(.tokenRecipientNotActivated) }404        if recipient.isContract { notes.append(.recipientIsContract) }405        if bandwidthBurn > 0 { notes.append(.burnsTRXForBandwidth(sun: bandwidthBurn)) }406        if energyBurn > 0 { notes.append(.burnsTRXForEnergy(sun: energyBurn)) }407        notes.append(.confirmWithReceipt)408        return TronSendPlan(transaction: tx, asset: .trc20(token.address), from: sender.address, to: recipient.address, amount: amount,409                            bandwidthBytes: bytes, bandwidthSource: source, bandwidthFeeSun: bandwidthBurn,410                            energyEstimate: simulation.energyUsed, energyLimit: energyLimit, energyAvailable: available, energyFeeSun: energyBurn,411                            activationFeeSun: 0, memoFeeSun: 0, feeLimitSun: feeLimit, estimatedFeeSun: expected, maximumFeeSun: worst,412                            maximumDebitSun: worst, notes: notes)413    }414}415
Files main
Menu

Theme