---
description: 预测Tron合约调用能量消耗
---

# Estimate Energy Usage

## Python Code

![Estimate Energy Usage of USDT](https://884680271-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1i8_0ZYNNyyp5Mxzr5%2F-MVL1IM_Qo8dIUCbO9Je%2F-MVL2geNEfoS0_p2WSS5%2Fimage.png?alt=media\&token=70cf53dc-18a9-49a9-8ce1-2164eee3e6f9)

```python
#!/bin/env python3


import collections
import statistics
import sys

import requests
import base58


CNTR = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
PAGE = 1  # max 5
PRICE = 140

if len(sys.argv) >= 2:
    CNTR = sys.argv[1]
if len(sys.argv) >= 3:
    PAGE = int(sys.argv[2])


url = f"https://api.trongrid.io/v1/accounts/{CNTR}/transactions?only_confirmed=true&only_to=true&limit=200&search_internal=false"

resp = requests.get(url)
payload = resp.json()
data = payload['data']

for i in range(1, PAGE):
    print(f"paging ... {i}/{PAGE}")
    url = payload['meta']['links']['next']
    resp = requests.get(url)
    payload = resp.json()
    data += payload['data']


stat = collections.defaultdict(list)

txns = 0

for txn in data:
    if (
        txn.get('energy_usage_total', 0) > 0
        and txn['raw_data']['contract'][0]['parameter']['value']['contract_address']
        == base58.b58decode_check(CNTR).hex()
    ):
        txns += 1
        stat[txn['ret'][0]['contractRet']].append(txn['energy_usage_total'])

print("TXNs:", txns)
print("RESULT_CODE\tMAX\tMIN\tMEAN\tMEDIAN\tRate")
for state, values in stat.items():
    print(
        "%15s" % state,
        max(values),
        min(values),
        int(statistics.mean(values)),
        int(statistics.median(values)),
        "%.1f%%" % (len(values) / txns * 100),
        sep='\t',
    )


print('Use fee_limit >', (max(stat['SUCCESS']) * PRICE) / 1_000_000, 'TRX')
```
