SPB Git

Repository Public

PlannerTests.swift 27.8 KB 366 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraTronTests/PlannerTests.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 QyvoraEthereum46@testable import QyvoraTron4748/// Planner rules and fee arithmetic with fixed chain parameters (the values every network reported on 2026-12-05:49/// 1000 sun per byte, 100 sun per energy unit, 1 TRX activation, 0.1 TRX account-creation, 1 TRX memo).50@Suite struct TronSendPlannerTests {51    static let parameters = TronChainParameters(bandwidthPriceSun: 1000, energyPriceSun: 100, accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000,52                                                createAccountBandwidthRate: 1, maximumFeeLimitSun: 15_000_000_000, memoFeeSun: 1_000_000)53    static let now: UInt64 = 1_796_447_400_00054    static let reference = TronBlockReference(number: 88_590_960, id: hex("000000000547ca70d6b17c88b4254293ed8d65c1e7b6836b4178d970ab50c210"), timestamp: 1_796_447_349_000)!5556    let me = TronAddress(TronVectors.derivation[0].address)!57    let other = TronAddress(TronVectors.derivation[1].address)!58    let usdt = TronAddress("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")!59    let usdc = TronAddress("TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8")!60    let planner = TronSendPlanner()6162    func state(_ network: TronNetwork = .mainnet, parameters: TronChainParameters = TronSendPlannerTests.parameters, now: UInt64 = TronSendPlannerTests.now) -> TronSendPlanner.ChainState {63        TronSendPlanner.ChainState(network: network, parameters: parameters, reference: Self.reference, nowMilliseconds: now)64    }6566    func account(_ a: TronAddress, _ balance: UInt64 = 0, activated: Bool = true, contract: Bool = false) -> TronAccount {67        TronAccount(address: a, isActivated: activated, balanceSun: balance, isContract: contract)68    }6970    func resources(free: UInt64 = 600, staked: UInt64 = 0, energy: UInt64 = 0) -> TronResources {71        TronResources(freeNetLimit: 600, freeNetUsed: 600 - free, netLimit: staked, netUsed: 0, energyLimit: energy, energyUsed: 0)72    }7374    /// QYV-SVC-105: at a size boundary of the amount, send-max keeps the largest amount that still travels for the75    /// smaller fee (found by the audit's property campaign, seed 2046850160945862867).76    @Test func sendMaxAtAnEncodingBoundarySendsTheLargestAmountThatTravelsFree() throws {77        // exactly 267 bytes of free bandwidth left: a 3-byte amount fits, a 4-byte amount (268 bytes) burns 268 000 sun78        for balance in [UInt64(2_223_499), 2_269_264] {79            let plan = try planner.planTransfer(state: state(.nile), sender: account(me, balance), resources: resources(free: 267),80                                                recipient: account(other), amount: .max)81            #expect(plan.amount == UInt256(2_097_151))          // 2^21 − 1, the largest 3-byte amount82            #expect(plan.estimatedFeeSun == 0 && plan.bandwidthBytes == 267)83            // one more sun needs the longer encoding and its fee, which the balance cannot carry84            #expect(planError { try planner.planTransfer(state: state(.nile), sender: account(me, balance), resources: resources(free: 267),85                                                         recipient: account(other), amount: .exact(2_097_152)) } != nil)86        }87        // burned bandwidth near the smallest balances: 267 000 sun carries a 2-byte amount (266 bytes, 266 000 sun burned)88        // of 1 000 sun, more than the largest 1-byte amount (127 sun) with its 265 000 sun89        let small = try planner.planTransfer(state: state(.nile), sender: account(me, 267_000), resources: resources(free: 0), recipient: account(other), amount: .max)90        #expect(small.amount == UInt256(1_000) && small.estimatedFeeSun == 266_000)91        // away from a boundary nothing changes: the whole balance leaves when it travels free92        let free = try planner.planTransfer(state: state(.nile), sender: account(me, 1_500_000), resources: resources(free: 600), recipient: account(other), amount: .max)93        #expect(free.amount == UInt256(1_500_000) && free.estimatedFeeSun == 0)94    }9596    func planError(_ body: () throws -> TronSendPlan) -> TronPlanError? {97        do {98            _ = try body()99            return nil100        } catch let error as TronPlanError {101            return error102        } catch {103            Issue.record("the planner threw something other than a TronPlanError: \(error)")104            return nil105        }106    }107108    // MARK: TRX109110    @Test func trxWithFreeBandwidth() throws {111        let plan = try planner.planTransfer(state: state(), sender: account(me, 10_000_000), resources: resources(), recipient: account(other), amount: .exact(1_000_000))112        #expect(plan.asset == .trx && plan.from == me && plan.to == other && plan.amount == UInt256(1_000_000))113        // 133 bytes of raw data, 3 of envelope, 67 of signature, 64 of result overhead114        #expect(plan.bandwidthBytes == 267 && plan.bandwidthBytes == UInt64(plan.transaction.bandwidthSize()))115        #expect(plan.bandwidthSource == .free && plan.bandwidthFeeSun == 0)116        #expect(plan.estimatedFeeSun == 0 && plan.maximumFeeSun == 267_000 && plan.maximumDebitSun == 1_267_000)117        #expect(plan.feeLimitSun == 0 && plan.energyEstimate == 0 && plan.activationFeeSun == 0 && plan.memoFeeSun == 0)118        #expect(plan.notes.isEmpty)119        // the transaction: local bytes, on the reference block, valid for two minutes from the device clock120        #expect(plan.transaction.refBlockBytes == hex("ca70") && plan.transaction.refBlockHash == hex("d6b17c88b4254293"))121        #expect(plan.transaction.timestamp == Self.now && plan.transaction.expiration == Self.now + 120_000)122        #expect(plan.review.action == .trxTransfer(from: me, to: other, amountSun: 1_000_000))123        let signed = try plan.transaction.sign(privateKey: hex(TronVectors.derivation[0].privateKey))124        #expect(signed.isSignedByOwner)125        #expect(signed.serialized.count + 64 == 267)126    }127128    @Test func trxBandwidthSources() throws {129        func plan(_ r: TronResources) throws -> TronSendPlan {130            try planner.planTransfer(state: state(), sender: account(me, 10_000_000), resources: r, recipient: account(other), amount: .exact(1_000_000))131        }132        // staked bandwidth is used first133        #expect(try plan(resources(free: 600, staked: 267)).bandwidthSource == .staked)134        #expect(try plan(resources(free: 267, staked: 266)).bandwidthSource == .free)135        // one byte short on both: everything is burned136        let burned = try plan(resources(free: 266, staked: 266))137        #expect(burned.bandwidthSource == .burned && burned.bandwidthFeeSun == 267_000 && burned.estimatedFeeSun == 267_000)138        #expect(burned.notes == [.burnsTRXForBandwidth(sun: 267_000)])139        // the two allowances are never added together140        #expect(try plan(resources(free: 200, staked: 200)).bandwidthSource == .burned)141        #expect(try plan(resources(free: 0, staked: 0)).maximumFeeSun == 267_000)142    }143144    @Test func trxToNewAccount() throws {145        let fresh = account(other, activated: false)146        let plan = try planner.planTransfer(state: state(), sender: account(me, 10_000_000), resources: resources(), recipient: fresh, amount: .exact(1_000_000))147        #expect(plan.bandwidthSource == .accountCreation && plan.bandwidthFeeSun == 0)148        #expect(plan.activationFeeSun == 1_100_000 && plan.estimatedFeeSun == 1_100_000 && plan.maximumFeeSun == 1_100_000)149        #expect(plan.notes == [.activatesRecipient(feeSun: 1_100_000)])150        // staked bandwidth covers the creating transaction: only the 1 TRX remains151        let staked = try planner.planTransfer(state: state(), sender: account(me, 10_000_000), resources: resources(staked: 267), recipient: fresh, amount: .exact(1_000_000))152        #expect(staked.activationFeeSun == 1_000_000 && staked.estimatedFeeSun == 1_000_000 && staked.maximumFeeSun == 1_100_000)153        // free bandwidth does not count for an account creation154        let short = try planner.planTransfer(state: state(), sender: account(me, 10_000_000), resources: resources(free: 600, staked: 266), recipient: fresh, amount: .exact(1_000_000))155        #expect(short.activationFeeSun == 1_100_000)156        // the balance must cover amount + fee, to the sun157        #expect(try planner.planTransfer(state: state(), sender: account(me, 2_100_000), resources: resources(), recipient: fresh, amount: .exact(1_000_000)).amount == UInt256(1_000_000))158        #expect(planError { try planner.planTransfer(state: state(), sender: account(me, 2_099_999), resources: resources(), recipient: fresh, amount: .exact(1_000_000)) }159            == .insufficientBalance(requiredSun: 2_100_000, availableSun: 2_099_999))160    }161162    @Test func trxMemo() throws {163        let plan = try planner.planTransfer(state: state(), sender: account(me, 10_000_000), resources: resources(free: 0), recipient: account(other),164                                            amount: .exact(1_000_000), memo: Bytes("QYVORA memo".utf8))165        // eleven bytes of memo and two of field header166        #expect(plan.bandwidthBytes == 280)167        #expect(plan.memoFeeSun == 1_000_000 && plan.bandwidthFeeSun == 280_000 && plan.estimatedFeeSun == 1_280_000 && plan.maximumFeeSun == 1_280_000)168        #expect(plan.notes == [.burnsTRXForBandwidth(sun: 280_000), .memoFee(sun: 1_000_000)])169        #expect(plan.review.memoText == "QYVORA memo")170        #expect(planError { try planner.planTransfer(state: state(), sender: account(me, 10_000_000), resources: resources(), recipient: account(other),171                                                     amount: .exact(1), memo: Bytes(repeating: 65, count: 257)) } == .invalidTransaction(.memoTooLong))172    }173174    @Test func trxSendMax() throws {175        // free bandwidth: the whole balance goes176        let free = try planner.planTransfer(state: state(), sender: account(me, 5_000_000), resources: resources(), recipient: account(other), amount: .max)177        #expect(free.amount == UInt256(5_000_000) && free.estimatedFeeSun == 0)178        // burned bandwidth: the fee stays behind179        let burned = try planner.planTransfer(state: state(), sender: account(me, 5_000_000), resources: resources(free: 0), recipient: account(other), amount: .max)180        // 5 000 000 takes four bytes of varint (one more than 1 000 000): 268 bytes181        #expect(burned.amount == UInt256(4_732_000) && burned.estimatedFeeSun == 268_000 && burned.bandwidthBytes == 268)182        // new recipient183        let fresh = try planner.planTransfer(state: state(), sender: account(me, 5_000_000), resources: resources(), recipient: account(other, activated: false), amount: .max)184        #expect(fresh.amount == UInt256(3_900_000) && fresh.estimatedFeeSun == 1_100_000)185        // amount + fee never exceeds the balance, at every size of the amount186        for balance in [UInt64(267_001), 268_000, 394_000, 395_000, 16_651_000, 16_652_000, 2_147_750_000, 2_147_751_000, 1 << 40, UInt64(Int64.max)] {187            let plan = try planner.planTransfer(state: state(), sender: account(me, balance), resources: resources(free: 0), recipient: account(other), amount: .max)188            let amount = try #require(plan.amount.uint64)189            #expect(amount > 0 && amount + plan.estimatedFeeSun <= balance)190            // at most two bytes of bandwidth are left behind191            #expect(balance - amount - plan.estimatedFeeSun <= 2000)192            #expect(plan.estimatedFeeSun == plan.bandwidthBytes * 1000)193        }194        // nothing left after the fee195        #expect(planError { try planner.planTransfer(state: state(), sender: account(me, 265_000), resources: resources(free: 0), recipient: account(other), amount: .max) } != nil)196        #expect(planError { try planner.planTransfer(state: state(), sender: account(me, 0), resources: resources(), recipient: account(other), amount: .max) }197            == .insufficientBalance(requiredSun: 1, availableSun: 0))198        #expect(planError { try planner.planTransfer(state: state(), sender: account(me, 1_100_000), resources: resources(), recipient: account(other, activated: false), amount: .max) }199            == .insufficientBalance(requiredSun: 1_100_001, availableSun: 1_100_000))200    }201202    @Test func trxRefusals() throws {203        let rich = account(me, 10_000_000)204        func refusal(sender: TronAccount? = nil, to: TronAccount, amount: TronSendPlanner.Amount = .exact(1), planner p: TronSendPlanner? = nil,205                     state s: TronSendPlanner.ChainState? = nil) -> TronPlanError? {206            planError { try (p ?? planner).planTransfer(state: s ?? state(), sender: sender ?? rich, resources: resources(), recipient: to, amount: amount) }207        }208        #expect(refusal(to: account(other), amount: .exact(0)) == .zeroAmount)209        #expect(refusal(to: account(me)) == .recipientIsSender)210        #expect(refusal(to: account(.zero)) == .recipientIsZeroAddress)211        #expect(refusal(to: account(usdt, contract: true)) == .recipientIsTokenContract(usdt))212        #expect(refusal(to: account(usdc, contract: true)) == .recipientIsTokenContract(usdc))213        // the built-in list is per network: on Nile that address is an ordinary one214        #expect(refusal(to: account(usdt), state: state(.nile)) == nil)215        #expect(refusal(sender: account(me, activated: false), to: account(other)) == .senderNotActivated)216        #expect(refusal(to: account(other), amount: .exact(10_000_001)) == .insufficientBalance(requiredSun: 10_000_001, availableSun: 10_000_000))217        #expect(refusal(to: account(other), amount: .exact(UInt64.max)) == .arithmeticOverflow)218        // a contract recipient is allowed and flagged219        let toContract = try planner.planTransfer(state: state(), sender: rich, resources: resources(), recipient: account(other, contract: true), amount: .exact(1))220        #expect(toContract.notes == [.recipientIsContract])221        // per-transaction limit of the policy222        let limited = TronSendPlanner(policy: .init(maximumAmountSun: 5_000_000))223        #expect(refusal(to: account(other), amount: .exact(5_000_001), planner: limited) == .amountAboveLimit(limitSun: 5_000_000))224        #expect(refusal(to: account(other), amount: .exact(5_000_000), planner: limited) == nil)225        #expect(refusal(to: account(other), amount: .max, planner: limited) == .amountAboveLimit(limitSun: 5_000_000))226        // clock and reference block more than five minutes apart, either way227        #expect(refusal(to: account(other), state: state(now: Self.reference.timestamp + 300_001)) == .clockSkew)228        #expect(refusal(to: account(other), state: state(now: Self.reference.timestamp - 300_001)) == .clockSkew)229        #expect(refusal(to: account(other), state: state(now: Self.reference.timestamp + 300_000)) == nil)230        // a clock behind the block: the transaction is dated from the block231        let behind = try planner.planTransfer(state: state(now: Self.reference.timestamp - 60_000), sender: rich, resources: resources(), recipient: account(other), amount: .exact(1))232        #expect(behind.transaction.timestamp == Self.reference.timestamp && behind.transaction.expiration == Self.reference.timestamp + 120_000)233        // policy out of range234        for bad in [TronSendPlanner.Policy(lifetimeSeconds: 29), .init(lifetimeSeconds: 3601), .init(energyMarginPercent: 101), .init(maximumClockSkewSeconds: 3601),235                    .init(maximumFeeLimitSun: UInt64.max)] {236            #expect(refusal(to: account(other), planner: TronSendPlanner(policy: bad)) == .invalidPolicy)237        }238        #expect(try TronSendPlanner(policy: .init(lifetimeSeconds: 600)).planTransfer(state: state(), sender: rich, resources: resources(), recipient: account(other), amount: .exact(1))239            .transaction.expiration == Self.now + 600_000)240    }241242    // MARK: TRC-20243244    func simulation(_ energy: UInt64 = 29_650, ok: Bool = true, message: String = "") -> TronConstantResult {245        TronConstantResult(succeeded: ok, message: message, output: Bytes(repeating: 0, count: 32), energyUsed: energy)246    }247248    func tokenPlan(planner p: TronSendPlanner? = nil, state s: TronSendPlanner.ChainState? = nil, trx: UInt64 = 10_000_000, resources r: TronResources? = nil,249                   to: TronAccount? = nil, token: TronAccount? = nil, balance: UInt64 = 5_000_000, amount: UInt64 = 1_000_000,250                   simulation sim: TronConstantResult? = nil) throws(TronPlanError) -> TronSendPlan {251        try (p ?? planner).planTokenTransfer(state: s ?? state(), sender: account(me, trx), resources: r ?? resources(), recipient: to ?? account(other),252                                             token: token ?? account(usdt, contract: true), tokenBalance: UInt256(balance), amount: UInt256(amount),253                                             simulation: sim ?? simulation())254    }255256    @Test func tokenFees() throws {257        let plan = try tokenPlan()258        #expect(plan.asset == .trc20(usdt) && plan.amount == UInt256(1_000_000))259        // 29650 × 1.25 = 37062.5, rounded up; fee limit at 100 sun per unit260        #expect(plan.energyEstimate == 29_650 && plan.energyLimit == 37_063 && plan.feeLimitSun == 3_706_300)261        #expect(plan.transaction.feeLimit == 3_706_300)262        #expect(plan.bandwidthBytes == 345 && plan.bandwidthBytes == UInt64(plan.transaction.bandwidthSize()))263        #expect(plan.bandwidthSource == .free && plan.bandwidthFeeSun == 0)264        #expect(plan.energyAvailable == 0 && plan.energyFeeSun == 2_965_000 && plan.estimatedFeeSun == 2_965_000)265        #expect(plan.maximumFeeSun == 345_000 + 3_706_300 && plan.maximumDebitSun == plan.maximumFeeSun)266        #expect(plan.activationFeeSun == 0 && plan.memoFeeSun == 0)267        #expect(plan.notes == [.burnsTRXForEnergy(sun: 2_965_000), .confirmWithReceipt])268        #expect(plan.review.action == .trc20Transfer(from: me, token: usdt, to: other, amount: UInt256(1_000_000)))269        #expect(plan.review.feeLimitSun == 3_706_300 && !plan.review.requiresBlindSigning)270        #expect(try plan.transaction.sign(privateKey: hex(TronVectors.derivation[0].privateKey)).isSignedByOwner)271        // no bandwidth left: bytes burned too272        let burned = try tokenPlan(resources: resources(free: 344))273        #expect(burned.bandwidthSource == .burned && burned.bandwidthFeeSun == 345_000 && burned.estimatedFeeSun == 3_310_000)274        #expect(burned.notes == [.burnsTRXForBandwidth(sun: 345_000), .burnsTRXForEnergy(sun: 2_965_000), .confirmWithReceipt])275        // exact margins276        #expect(try tokenPlan(simulation: simulation(100)).energyLimit == 125)277        #expect(try tokenPlan(simulation: simulation(1)).energyLimit == 2)278        #expect(try tokenPlan(planner: TronSendPlanner(policy: .init(energyMarginPercent: 0))).feeLimitSun == 2_965_000)279        #expect(try tokenPlan(planner: TronSendPlanner(policy: .init(energyMarginPercent: 100))).feeLimitSun == 5_930_000)280    }281282    @Test func tokenWithStakedEnergy() throws {283        // energy covers the estimate but not the margin: nothing expected to burn, the margin must still be payable284        let partial = try tokenPlan(trx: 706_300, resources: resources(energy: 30_000))285        #expect(partial.energyAvailable == 30_000 && partial.energyFeeSun == 0 && partial.estimatedFeeSun == 0)286        #expect(partial.feeLimitSun == 3_706_300 && partial.notes == [.confirmWithReceipt])287        #expect(planError { try tokenPlan(trx: 706_299, resources: resources(energy: 30_000)) } == .insufficientTRXForFees(requiredSun: 706_300, availableSun: 706_299))288        // energy covers everything: no TRX needed at all289        #expect(try tokenPlan(trx: 0, resources: resources(energy: 37_063)).estimatedFeeSun == 0)290        // part of the estimate is burned291        let some = try tokenPlan(resources: resources(energy: 10_000))292        #expect(some.energyFeeSun == 1_965_000)293        // without energy the whole margin plus the bandwidth must be payable294        #expect(planError { try tokenPlan(trx: 3_706_299) } == .insufficientTRXForFees(requiredSun: 3_706_300, availableSun: 3_706_299))295        #expect(planError { try tokenPlan(trx: 4_051_299, resources: resources(free: 0)) } == .insufficientTRXForFees(requiredSun: 4_051_300, availableSun: 4_051_299))296        #expect(try tokenPlan(trx: 4_051_300, resources: resources(free: 0)).estimatedFeeSun == 3_310_000)297    }298299    @Test func tokenRefusals() throws {300        #expect(planError { try tokenPlan(amount: 0) } == .zeroAmount)301        #expect(planError { try tokenPlan(to: account(me)) } == .recipientIsSender)302        #expect(planError { try tokenPlan(to: account(.zero)) } == .recipientIsZeroAddress)303        // the token's own contract, and another known token contract304        #expect(planError { try tokenPlan(to: account(usdt, contract: true)) } == .recipientIsTokenContract(usdt))305        #expect(planError { try tokenPlan(to: account(usdc, contract: true)) } == .recipientIsTokenContract(usdc))306        let custom = TronAddress(TronVectors.derivation[2].address)!307        #expect(planError { try tokenPlan(state: state(.nile), to: account(custom, contract: true), token: account(custom, contract: true)) } == .recipientIsTokenContract(custom))308        // a token address that is an ordinary account, an unknown address, the zero address309        #expect(planError { try tokenPlan(token: account(usdt, contract: false)) } == .tokenIsNotAContract)310        #expect(planError { try tokenPlan(token: account(usdt, activated: false)) } == .tokenIsNotAContract)311        #expect(planError { try tokenPlan(token: account(.zero, contract: true)) } == .tokenIsNotAContract)312        #expect(planError { try tokenPlan(balance: 999_999) } == .insufficientTokenBalance(required: UInt256(1_000_000), available: UInt256(999_999)))313        #expect(planError { try tokenPlan(simulation: simulation(1984, ok: false, message: "REVERT opcode executed")) } == .simulationFailed("REVERT opcode executed"))314        #expect(planError { try tokenPlan(simulation: simulation(0, ok: false)) } == .simulationFailed("the transfer would revert"))315        #expect(planError { try tokenPlan(simulation: simulation(0)) } == .invalidEnergyEstimate)316        #expect(planError { try (TronSendPlanner()).planTokenTransfer(state: state(), sender: account(me, 1, activated: false), resources: resources(), recipient: account(other),317                                                                      token: account(usdt, contract: true), tokenBalance: UInt256(5), amount: UInt256(1), simulation: simulation()) }318            == .senderNotActivated)319        #expect(planError { try tokenPlan(state: state(now: Self.reference.timestamp + 400_000)) } == .clockSkew)320    }321322    @Test func tokenFeeLimitCap() throws {323        // 800000 × 1.25 × 100 sun = 100 TRX: the cap itself is allowed, one unit more is not324        #expect(try tokenPlan(trx: 200_000_000, simulation: simulation(800_000)).feeLimitSun == 100_000_000)325        #expect(planError { try tokenPlan(trx: 200_000_000, simulation: simulation(800_001)) } == .feeLimitTooHigh(requiredSun: 100_000_200, capSun: 100_000_000))326        // a configurable cap, and the protocol's own ceiling when it is lower327        let low = TronSendPlanner(policy: .init(maximumFeeLimitSun: 3_000_000))328        #expect(planError { try tokenPlan(planner: low) } == .feeLimitTooHigh(requiredSun: 3_706_300, capSun: 3_000_000))329        let chain = TronChainParameters(bandwidthPriceSun: 1000, energyPriceSun: 100, accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000,330                                        createAccountBandwidthRate: 1, maximumFeeLimitSun: 1_000_000, memoFeeSun: 0)331        #expect(planError { try tokenPlan(state: state(parameters: chain)) } == .feeLimitTooHigh(requiredSun: 3_706_300, capSun: 1_000_000))332        // an energy price that changed on chain changes the plan, not the code333        let dear = TronChainParameters(bandwidthPriceSun: 1000, energyPriceSun: 420, accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000,334                                       createAccountBandwidthRate: 1, maximumFeeLimitSun: 15_000_000_000, memoFeeSun: 0)335        let plan = try tokenPlan(state: state(parameters: dear), trx: 100_000_000)336        #expect(plan.feeLimitSun == 15_566_460 && plan.energyFeeSun == 12_453_000)337        // absurd parameters or estimates overflow into a refusal, never a trap338        let absurd = TronChainParameters(bandwidthPriceSun: UInt64.max, energyPriceSun: UInt64.max, accountActivationFeeSun: UInt64.max, createAccountFeeSun: UInt64.max,339                                         createAccountBandwidthRate: UInt64.max, maximumFeeLimitSun: UInt64.max, memoFeeSun: UInt64.max)340        #expect(planError { try tokenPlan(state: state(parameters: absurd)) } == .arithmeticOverflow)341        #expect(planError { try tokenPlan(simulation: simulation(UInt64.max)) } == .arithmeticOverflow)342        #expect(planError { try planner.planTransfer(state: state(parameters: absurd), sender: account(me, 5), resources: resources(free: 0), recipient: account(other), amount: .exact(1)) }343            == .arithmeticOverflow)344        #expect(planError { try planner.planTransfer(state: state(parameters: absurd), sender: account(me, 5), resources: resources(), recipient: account(other, activated: false), amount: .max) }345            == .arithmeticOverflow)346    }347348    @Test func tokenToUnactivatedRecipient() throws {349        // allowed: no activation fee is charged by the protocol, the cost is in the (larger) energy estimate350        let plan = try tokenPlan(to: account(other, activated: false), simulation: simulation(64_285))351        #expect(plan.activationFeeSun == 0)352        #expect(plan.energyLimit == 80_357 && plan.feeLimitSun == 8_035_700 && plan.energyFeeSun == 6_428_500)353        #expect(plan.notes == [.tokenRecipientNotActivated, .burnsTRXForEnergy(sun: 6_428_500), .confirmWithReceipt])354    }355356    @Test func builtInTokens() {357        #expect(TronBuiltInTokens.mainnet.map(\.symbol) == ["USDT", "USDC"])358        #expect(TronBuiltInTokens.mainnet.map(\.contract.base58) == ["TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8"])359        #expect(TronBuiltInTokens.mainnet.allSatisfy { $0.decimals == 6 && !$0.custom && $0.network == .mainnet })360        #expect(TronBuiltInTokens.tokens(for: .nile).isEmpty && TronBuiltInTokens.tokens(for: .shasta).isEmpty)361        #expect(TronBuiltInTokens.token(usdt, on: .mainnet)?.name == "Tether USD" && TronBuiltInTokens.token(usdt, on: .nile) == nil)362        #expect(TronBuiltInTokens.token(usdc, on: .mainnet)?.note != nil && TronBuiltInTokens.token(usdt, on: .mainnet)?.note == nil)363        #expect(TronBuiltInTokens.mainnet[0].id == "mainnet:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")364    }365}366
Files main
Menu

Theme