使用私钥通过 API 购买能源

这是使用私钥通过 API 密钥购买能源的完整示例

const TronWeb = require('tronweb')

const TRONSAVE_RECEIVER_ADDRESS = "TWZEhq5JuUVvGtutNgnRBATbF8BnHGyn4S" //在测试网络模式下,将其更改为"TATT1UzHRikft98bRFqApFTsaSw73ycfoS"
const PRIVATE_KEY = "your_private_key" //更改它
const TRON_FULLNODE = "https://api.trongrid.io"  //在测试网络模式下,将其更改为"https://api.nileex.io"
const TRONSAVE_API_URL = "https://api.tronsave.io" //在测试网络模式下,将其更改为"https://api-dev.tronsave.io"

const REQUEST_ADDRESS = "your_request_address" //更改它
const TARGET_ADDRESS = "your_target_address" //更改它
const BUY_AMOUNT = 100000 //可更改
const DURATION = 3 * 86400 * 1000 //3天。可更改

const tronWeb = new TronWeb({
    fullNode: TRON_FULLNODE,
    solidityNode: TRON_FULLNODE,
    eventServer: TRON_FULLNODE,
    privateKey: PRIVATE_KEY,
})

const GetEstimate = async (request_address, target_address, amount, duration) => {
    const url = TRONSAVE_API_URL + "/v0/estimate-trx"
    //更多信息请参见 https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
    const body = {
        "amount": amount,
        "buy_energy_type": "MEDIUM",
        "duration_millisec": duration,
        "request_address": request_address,
        "target_address": target_address || request_address,
        "is_partial": true
    }
    const data = await fetch(url, {
        method: "POST",
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify(body)
    })
    const response = await data.json()
    /**
     * 示例响应 
     * @link  https://docs.tronsave.io/market/how-to-buy-energy/buy-on-rest-api
   {
        "unit_price": 45,
        "duration_millisec": 259200000,
        "available_energy": 4298470,
        "estimate_trx": 13500000,
    }
     */
    return response
}

const GetSignedTransaction = async (estimate_trx, request_address) => {
    const dataSendTrx = await tronWeb.transactionBuilder.sendTrx(TRONSAVE_RECEIVER_ADDRESS, estimate_trx, request_address)
    const signed_tx = await tronWeb.trx.sign(dataSendTrx, PRIVATE_KEY);
    return signed_tx
}

const CreateOrder = async (signed_tx, target_address, unit_price, duration) => {
    const url = TRONSAVE_API_URL + "/v0/buy-energy"
    //更多信息请参见 https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
    const body = {
        "resource_type": "ENERGY",
        "unit_price": unit_price,
        "allow_partial_fill": true,
        "target_address": target_address,
        "duration_millisec": duration,
        "tx_id": signed_tx.txID,
        "signed_tx": signed_tx
    }
    const data = await fetch(url, {
        method: "POST",
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify(body)
    })
    const response = await data.text()
    //示例响应 
    // @link  https://docs.tronsave.io/market/how-to-buy-energy/buy-on-rest-api
    // "651d2306e55c073f6ca0992e" //在tronsave中的订单ID
    return response
}

const BuyEnergyUsingPrivateKey = async () => {
    //步骤1:估算购买订单的成本
    const estimate_data = await GetEstimate(REQUEST_ADDRESS, TARGET_ADDRESS, BUY_AMOUNT, DURATION)
    const { unit_price, estimate_trx, available_energy } = estimate_data
    console.log(estimate_data)
    /*
    {
        "unit_price": 45,
        "duration_millisec": 259200000,
        "available_energy": 4298470,
        "estimate_trx": 13500000,
    }
     */
    const is_ready_fulfilled = available_energy >= BUY_AMOUNT //如果available_energy等于buy_amount,则意味着您的订单可以完全执行100%
    if (is_ready_fulfilled) {
        //步骤2:使用私钥构建已签名的交易
        const signed_tx = await GetSignedTransaction(estimate_trx, REQUEST_ADDRESS)
        console.log(signed_tx);
        /*
        {
            "resource_type": "ENERGY",
            "unit_price": 45,
            "allow_partial_fill": true,
            "target_address": "TM6ZeEgpefyGWeMLuzSbfqTGkPv8Z6Jm4X",
            "duration_millisec": 259200000,
            "tx_id": "446eed36e31249b98b201db2e81a3825b185f1a3d8b2fea348b24fc021e58e0d",
            "signed_tx": {
            "visible": false,
            "txID": "446eed36e31249b98b201db2e81a3825b185f1a3d8b2fea348b24fc021e58e0d",
            "raw_data": {
                "contract": [
                {
                    "parameter": {
                    "value": {
                        "amount": 13500000,
                        "owner_address": "417a0d868d1418c9038584af1252f85d486502eec0",
                        "to_address": "41055756f33f419278d9ea059bd2b21120e6add748"
                    },
                    "type_url": "type.googleapis.com/protocol.TransferContract"
                    },
                    "type": "TransferContract"
                }
                ],
                "ref_block_bytes": "0713",
                "ref_block_hash": "6c5f7686f4176139",
                "expiration": 1691465106000,
                "timestamp": 1691465046758
            },
            "raw_data_hex": "0a02071322086c5f7686f417613940d084b5999d315a68080112640a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412330a15417a0d868d1418c9038584af1252f85d486502eec0121541055756f33f419278d9ea059bd2b21120e6add74818e0fcb70670e6b5b1999d31",
            "signature": ["xxxxxxxxx"]
            }
        }
         */
        //步骤3:创建订单
        const dataCreateOrder = await CreateOrder(signed_tx, TARGET_ADDRESS, unit_price, DURATION)
        console.log(dataCreateOrder);
    }
}

BuyEnergyUsingPrivateKey()

Last updated