r402-tron 0.14.0

Tron chain support for the x402 payment protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Tron chain provider backed by the TronGrid HTTP REST API.
//!
//! Unlike EVM chains, Tron does not expose a JSON-RPC interface compatible
//! with `alloy-provider`; instead, TronGrid (and any TronGrid-compatible
//! node) exposes a JSON-over-HTTP "wallet" API. This provider implements
//! the subset needed for x402 settlement:
//!
//! - `wallet/triggerconstantcontract` — read-only calls (e.g. `balanceOf`)
//! - `wallet/triggersmartcontract` — builds an unsigned state-changing call
//! - `wallet/broadcasttransaction` — submits a signed transaction
//! - `wallet/gettransactioninfobyid` — polls for confirmation
//!
//! Tron transaction signing is over the SHA256 hash of the serialized
//! `raw_data` protobuf, which TronGrid conveniently returns pre-computed as
//! the transaction's `txID` — so signing never requires protobuf encoding
//! on our side, only a secp256k1 signature over the returned digest.

use std::fmt::{Debug, Formatter};
use std::time::Duration;

use alloy_primitives::{Address as EvmAddress, Bytes, U256, hex};
use alloy_signer::Signer;
use alloy_signer_local::PrivateKeySigner;
use r402_core::chain::{ChainId, ChainProvider};
use serde::Deserialize;
use serde_json::{Value, json};
use url::Url;

use crate::chain::{Address, TronChainReference};
use crate::exact::TronExactError;

/// An unsigned Tron transaction as returned by `triggersmartcontract`.
///
/// Opaque beyond its `tx_id` and `raw_data_hex`: this provider never
/// decodes the protobuf-encoded `raw_data`, it only signs over the
/// pre-computed digest (`tx_id`) and re-submits the untouched JSON value
/// with a `signature` field attached.
#[derive(Debug, Clone)]
pub struct UnsignedTransaction {
    /// Hex-encoded transaction ID (`SHA256(raw_data)`), the digest to sign.
    pub tx_id: [u8; 32],
    /// The full `transaction` JSON object returned by `TronGrid`, forwarded
    /// verbatim to `broadcasttransaction` with a `signature` array attached.
    raw: Value,
}

/// Outcome of `wallet/gettransactioninfobyid`.
#[derive(Debug, Clone, Deserialize)]
pub struct TransactionInfo {
    /// The transaction ID, hex-encoded without `0x` prefix.
    #[serde(default, rename = "id")]
    pub id: String,
    /// Execution receipt; `result` is `"SUCCESS"` on success.
    #[serde(default)]
    pub receipt: Option<TransactionReceipt>,
}

/// Execution receipt embedded in [`TransactionInfo`].
#[derive(Debug, Clone, Deserialize)]
pub struct TransactionReceipt {
    /// `"SUCCESS"` on success; any other value (e.g. `"REVERT"`) is a failure.
    #[serde(default)]
    pub result: Option<String>,
}

impl TransactionInfo {
    /// Returns `true` once `TronGrid` has indexed a receipt for this transaction.
    #[must_use]
    pub const fn is_confirmed(&self) -> bool {
        self.receipt.is_some()
    }

    /// Returns `true` if the receipt indicates successful execution.
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.receipt
            .as_ref()
            .and_then(|r| r.result.as_deref())
            .is_some_and(|r| r == "SUCCESS")
    }
}

/// Thin HTTP client for the `TronGrid` "wallet" REST API.
pub struct TronGridClient {
    base_url: Url,
    http: reqwest::Client,
}

impl Debug for TronGridClient {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TronGridClient")
            .field("base_url", &self.base_url)
            .finish_non_exhaustive()
    }
}

impl TronGridClient {
    /// Creates a new client pointed at the given TronGrid-compatible base URL
    /// (e.g. `https://api.trongrid.io`).
    #[must_use]
    pub fn new(base_url: Url) -> Self {
        Self {
            base_url,
            http: reqwest::Client::new(),
        }
    }

    /// Creates a client with a caller-supplied `reqwest::Client` (for
    /// sharing connection pools or attaching an API key header).
    #[must_use]
    pub const fn with_http_client(base_url: Url, http: reqwest::Client) -> Self {
        Self { base_url, http }
    }

    fn endpoint(&self, path: &str) -> Url {
        #[allow(
            clippy::expect_used,
            reason = "path is a hardcoded literal at every call site"
        )]
        self.base_url.join(path).expect("invalid TronGrid path")
    }

    async fn post_json(&self, path: &str, body: Value) -> Result<Value, TronExactError> {
        let response = self
            .http
            .post(self.endpoint(path))
            .json(&body)
            .send()
            .await
            .map_err(|e| TronExactError::TronGrid(e.to_string()))?;
        response
            .json::<Value>()
            .await
            .map_err(|e| TronExactError::TronGrid(e.to_string()))
    }

    /// Calls a read-only contract method via `wallet/triggerconstantcontract`.
    ///
    /// `calldata` is the full ABI-encoded call (selector + arguments); the
    /// return value is the raw ABI-encoded result bytes.
    ///
    /// # Errors
    ///
    /// Returns [`TronExactError::TronGrid`] on transport failure or if the
    /// node reports the call did not succeed.
    pub async fn trigger_constant_contract(
        &self,
        owner: EvmAddress,
        contract: EvmAddress,
        calldata: &Bytes,
    ) -> Result<Bytes, TronExactError> {
        let (selector, parameter) = split_calldata(calldata);
        let body = json!({
            "owner_address": format!("41{}", hex::encode(owner)),
            "contract_address": format!("41{}", hex::encode(contract)),
            "function_selector": selector,
            "parameter": parameter,
            "visible": false,
        });
        let response = self
            .post_json("wallet/triggerconstantcontract", body)
            .await?;
        let ok = response
            .get("result")
            .and_then(|r| r.get("result"))
            .and_then(Value::as_bool)
            .unwrap_or(false);
        if !ok {
            let message = response
                .get("result")
                .and_then(|r| r.get("message"))
                .and_then(Value::as_str)
                .unwrap_or("triggerconstantcontract failed")
                .to_owned();
            return Err(TronExactError::TronGrid(message));
        }
        let hex_result = response
            .get("constant_result")
            .and_then(Value::as_array)
            .and_then(|arr| arr.first())
            .and_then(Value::as_str)
            .ok_or_else(|| TronExactError::TronGrid("missing constant_result".to_owned()))?;
        let bytes = hex::decode(hex_result)
            .map_err(|e| TronExactError::TronGrid(format!("invalid hex result: {e}")))?;
        Ok(Bytes::from(bytes))
    }

    /// Builds an unsigned state-changing contract call via
    /// `wallet/triggersmartcontract`.
    ///
    /// # Errors
    ///
    /// Returns [`TronExactError::TronGrid`] on transport failure or if the
    /// node rejects the call (e.g. insufficient energy/bandwidth estimate).
    pub async fn trigger_smart_contract(
        &self,
        owner: EvmAddress,
        contract: EvmAddress,
        calldata: &Bytes,
        fee_limit: u64,
    ) -> Result<UnsignedTransaction, TronExactError> {
        let (selector, parameter) = split_calldata(calldata);
        let body = json!({
            "owner_address": format!("41{}", hex::encode(owner)),
            "contract_address": format!("41{}", hex::encode(contract)),
            "function_selector": selector,
            "parameter": parameter,
            "fee_limit": fee_limit,
            "call_value": 0,
            "visible": false,
        });
        let response = self.post_json("wallet/triggersmartcontract", body).await?;
        let ok = response
            .get("result")
            .and_then(|r| r.get("result"))
            .and_then(Value::as_bool)
            .unwrap_or(false);
        if !ok {
            let message = response
                .get("result")
                .and_then(|r| r.get("message"))
                .and_then(Value::as_str)
                .unwrap_or("triggersmartcontract failed")
                .to_owned();
            return Err(TronExactError::TronGrid(message));
        }
        let transaction = response
            .get("transaction")
            .cloned()
            .ok_or_else(|| TronExactError::TronGrid("missing transaction".to_owned()))?;
        let tx_id_hex = transaction
            .get("txID")
            .and_then(Value::as_str)
            .ok_or_else(|| TronExactError::TronGrid("missing txID".to_owned()))?;
        let tx_id_vec = hex::decode(tx_id_hex)
            .map_err(|e| TronExactError::TronGrid(format!("invalid txID: {e}")))?;
        let tx_id: [u8; 32] = tx_id_vec
            .try_into()
            .map_err(|_| TronExactError::TronGrid("txID is not 32 bytes".to_owned()))?;
        Ok(UnsignedTransaction {
            tx_id,
            raw: transaction,
        })
    }

    /// Broadcasts a signed transaction via `wallet/broadcasttransaction`.
    ///
    /// # Errors
    ///
    /// Returns [`TronExactError::TransactionFailed`] if the network rejects
    /// the transaction, or [`TronExactError::TronGrid`] on transport failure.
    pub async fn broadcast_transaction(
        &self,
        mut unsigned: UnsignedTransaction,
        signature: &[u8],
    ) -> Result<String, TronExactError> {
        let Value::Object(ref mut map) = unsigned.raw else {
            return Err(TronExactError::TronGrid(
                "malformed transaction envelope".to_owned(),
            ));
        };
        let _ = map.insert(
            "signature".to_owned(),
            Value::Array(vec![Value::String(hex::encode(signature))]),
        );
        let response = self
            .post_json("wallet/broadcasttransaction", unsigned.raw)
            .await?;
        let ok = response
            .get("result")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        if !ok {
            let message = response.get("message").and_then(Value::as_str).map_or_else(
                || "broadcasttransaction failed".to_owned(),
                |b64_or_text| {
                    // TronGrid often hex-encodes the message field.
                    hex::decode(b64_or_text)
                        .ok()
                        .and_then(|bytes| String::from_utf8(bytes).ok())
                        .unwrap_or_else(|| b64_or_text.to_owned())
                },
            );
            return Err(TronExactError::TransactionFailed(message));
        }
        Ok(hex::encode(unsigned.tx_id))
    }

    /// Polls `wallet/gettransactioninfobyid` once for the given transaction ID.
    ///
    /// # Errors
    ///
    /// Returns [`TronExactError::TronGrid`] on transport failure.
    pub async fn get_transaction_info(
        &self,
        tx_id_hex: &str,
    ) -> Result<TransactionInfo, TronExactError> {
        let body = json!({ "value": tx_id_hex });
        let response = self
            .post_json("wallet/gettransactioninfobyid", body)
            .await?;
        serde_json::from_value(response)
            .map_err(|e| TronExactError::TronGrid(format!("malformed transaction info: {e}")))
    }

    /// Polls until the transaction is confirmed or `timeout` elapses.
    ///
    /// # Errors
    ///
    /// Returns [`TronExactError::ConfirmationTimeout`] if no receipt appears
    /// within `timeout`, or [`TronExactError::TransactionFailed`] if the
    /// receipt indicates on-chain failure.
    pub async fn wait_for_confirmation(
        &self,
        tx_id_hex: &str,
        timeout: Duration,
        poll_interval: Duration,
    ) -> Result<TransactionInfo, TronExactError> {
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let info = self.get_transaction_info(tx_id_hex).await?;
            if info.is_confirmed() {
                return Self::confirm_result(tx_id_hex, info);
            }
            if tokio::time::Instant::now() >= deadline {
                return Err(TronExactError::ConfirmationTimeout);
            }
            tokio::time::sleep(poll_interval).await;
        }
    }

    fn confirm_result(
        tx_id_hex: &str,
        info: TransactionInfo,
    ) -> Result<TransactionInfo, TronExactError> {
        if info.is_success() {
            Ok(info)
        } else {
            Err(TronExactError::TransactionFailed(format!(
                "transaction {tx_id_hex} reverted"
            )))
        }
    }
}

/// Splits full ABI calldata (4-byte selector + arguments) into the
/// `(function_selector, parameter)` shape `TronGrid`'s trigger endpoints
/// expect: a human-readable signature is NOT required by `TronGrid` for the
/// `parameter` field — only the hex-encoded argument words are needed,
/// while `function_selector` here is passed as the raw 4-byte selector hex
/// so nodes that require a textual signature should instead be configured
/// with `contracts::*::SIGNATURE` constants at the call site.
fn split_calldata(calldata: &Bytes) -> (String, String) {
    let selector = hex::encode(calldata.get(..4).unwrap_or_default());
    let parameter = hex::encode(calldata.get(4..).unwrap_or_default());
    (selector, parameter)
}

/// Configuration for constructing a [`TronChainProvider`].
#[derive(Debug, Clone)]
pub struct TronChainProviderConfig {
    /// The Tron network this provider operates on.
    pub chain_reference: TronChainReference,
    /// TronGrid-compatible base URL (e.g. `https://api.trongrid.io`).
    pub base_url: Url,
    /// The facilitator's signing key (pays energy/bandwidth for settlement).
    pub signer: PrivateKeySigner,
    /// Fee limit (in SUN) attached to settlement transactions.
    pub fee_limit: u64,
    /// How long to wait for transaction confirmation.
    pub confirmation_timeout: Duration,
    /// Interval between confirmation polls.
    pub confirmation_poll_interval: Duration,
}

/// Provider for interacting with the Tron blockchain via `TronGrid`.
///
/// Handles balance checks, transaction construction, signing, broadcast,
/// and confirmation polling for the Tron exact scheme facilitator.
pub struct TronChainProvider {
    chain_reference: TronChainReference,
    grid: TronGridClient,
    signer: PrivateKeySigner,
    fee_limit: u64,
    confirmation_timeout: Duration,
    confirmation_poll_interval: Duration,
}

impl Debug for TronChainProvider {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TronChainProvider")
            .field("chain_reference", &self.chain_reference)
            .field("signer", &self.signer.address())
            .field("fee_limit", &self.fee_limit)
            .finish_non_exhaustive()
    }
}

impl TronChainProvider {
    /// Creates a new Tron chain provider from the given configuration.
    #[must_use]
    pub fn new(config: TronChainProviderConfig) -> Self {
        #[cfg(feature = "telemetry")]
        tracing::info!(
            chain = %ChainId::from(config.chain_reference),
            signer = %config.signer.address(),
            base_url = %config.base_url,
            "Using Tron provider"
        );
        Self {
            chain_reference: config.chain_reference,
            grid: TronGridClient::new(config.base_url),
            signer: config.signer,
            fee_limit: config.fee_limit,
            confirmation_timeout: config.confirmation_timeout,
            confirmation_poll_interval: config.confirmation_poll_interval,
        }
    }

    /// Returns the Tron network this provider operates on.
    #[must_use]
    pub const fn chain_reference(&self) -> TronChainReference {
        self.chain_reference
    }

    /// Returns the underlying `TronGrid` HTTP client.
    #[must_use]
    pub const fn grid(&self) -> &TronGridClient {
        &self.grid
    }

    /// Returns the facilitator's signing address (raw EVM hex form).
    #[must_use]
    pub const fn signer_address(&self) -> EvmAddress {
        self.signer.address()
    }

    /// Reads a TRC-20 token balance via `triggerconstantcontract`.
    ///
    /// # Errors
    ///
    /// Returns [`TronExactError::TronGrid`] on transport failure or a
    /// malformed response.
    pub async fn trc20_balance_of(
        &self,
        token: EvmAddress,
        account: EvmAddress,
    ) -> Result<U256, TronExactError> {
        let call = crate::chain::contracts::trc20::balanceOfCall { account };
        let calldata =
            <crate::chain::contracts::trc20::balanceOfCall as alloy_sol_types::SolCall>::abi_encode(
                &call,
            );
        let result = self
            .grid
            .trigger_constant_contract(self.signer_address(), token, &Bytes::from(calldata))
            .await?;
        let padded: [u8; 32] = result
            .get(..32)
            .and_then(|slice| slice.try_into().ok())
            .ok_or_else(|| TronExactError::TronGrid("malformed balanceOf result".to_owned()))?;
        Ok(U256::from_be_bytes(padded))
    }

    /// Builds, signs, broadcasts, and confirms a state-changing contract call.
    ///
    /// # Errors
    ///
    /// Returns a [`TronExactError`] variant on any step failure (request
    /// construction, signing, broadcast, or confirmation timeout/failure).
    pub async fn send_contract_call(
        &self,
        contract: EvmAddress,
        calldata: Bytes,
    ) -> Result<String, TronExactError> {
        let unsigned = self
            .grid
            .trigger_smart_contract(self.signer_address(), contract, &calldata, self.fee_limit)
            .await?;
        let signature = self
            .signer
            .sign_hash(&unsigned.tx_id.into())
            .await
            .map_err(|e| TronExactError::SignatureRecovery(e.to_string()))?;
        let tx_id = self
            .grid
            .broadcast_transaction(unsigned, signature.as_bytes().as_ref())
            .await?;
        let info = self
            .grid
            .wait_for_confirmation(
                &tx_id,
                self.confirmation_timeout,
                self.confirmation_poll_interval,
            )
            .await?;
        Ok(info.id)
    }
}

impl ChainProvider for TronChainProvider {
    fn signer_addresses(&self) -> Vec<String> {
        vec![Address::from_evm(self.signer.address()).to_string()]
    }

    fn chain_id(&self) -> ChainId {
        self.chain_reference.into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn split_calldata_extracts_selector_and_parameter() {
        let calldata = Bytes::from(vec![0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03, 0x04]);
        let (selector, parameter) = split_calldata(&calldata);
        assert_eq!(selector, "deadbeef");
        assert_eq!(parameter, "01020304");
    }
}