Salta ai contenuti

Creare transazioni di token TRC20 su TRON

Questo tutorial copre gli endpoint TRC20 dell’API Chaingateway V2: creare un indirizzo TRON, leggere un contratto token, controllare il saldo di un token e inviare un transfer TRC20. Gli esempi sono forniti in Shell (cURL), PHP (Guzzle), Python (Requests) e JavaScript (Axios).

Per ottenere una API key e informazioni sull’autorizzazione, consulta la sezione Per iniziare della documentazione Chaingateway.

L’API non ha alcun endpoint che compili o distribuisca uno smart contract. Non esiste una route che pubblica un nuovo contratto TRC20 sulla rete TRON, e nessuno degli endpoint TRON accetta bytecode di contratto. Ogni route TRC20 richiede un contractaddress di un token che esiste già on-chain, USDT come qualsiasi altro token TRC20.

Se stai cercando un modo per distribuire il tuo contratto token, questa API non è lo strumento adatto per quel passaggio. Una volta distribuito il contratto, gli endpoint qui sotto coprono la parte di cui la maggior parte delle integrazioni ha davvero bisogno: indirizzi, saldi, transfer e notifiche.

Cosa vuoi fareEndpoint
Creare un indirizzo TRONPOST /v2/tron/addresses
Importare una private key esistentePOST /v2/tron/addresses/import
Leggere nome, simbolo, decimali e supplyGET /v2/tron/trc20/{contract_address}
Leggere il saldo di un tokenGET /v2/tron/balances/{address}/trc20/{contract_address}
Inviare un transfer TRC20POST /v2/tron/transactions/trc20
Costruire un transfer senza trasmetterloPOST /v2/tron/transactions/trc20/build
Trasmettere una transazione firmataPOST /v2/tron/transactions/broadcast
Ricevere notifiche sui token in arrivoPOST /v2/tron/webhooks

L’indirizzo mittente deve essere noto a Chaingateway. Puoi crearlo tramite l’API oppure importare una private key esistente con POST /v2/tron/addresses/import.

Se passi una password, la private key viene salvata crittografata e firmi le transazioni successive con quella password. Se ometti la password, la risposta contiene la private key stessa e devi inviarla con ogni richiesta di transazione. L’approccio con password è descritto in dettaglio in Gestione dei wallet.

Terminal window
curl --request POST\
--url https://api.chaingateway.io/v2/tron/addresses\
--header 'Accept: application/json'\
--header 'content-type: application/json'\
--header 'Authorization: YOUR_API_TOKEN'\
--data '{"password":"test123"}'

La risposta contiene il nuovo indirizzo:

{
"status": 201,
"ok": true,
"message": "Address created",
"data": [
{
"privateKey": "59f1c6200e01a2ca9471411f10198bfa63678d0e87cc2ca30f9c4a68dee78edc",
"publicKey": "040fe6e677442c36f7fdd5535ba3ff1cef0110d78363420f7e24b65298990e3467aed68b9a67e1396d84753db25b32a2fa3e1fc0a673f01638e9bcfab2d8f4ceb5",
"hexAddress": "41a56a6505ffbee78eb916dd44f4846874deddaebd",
"address": "TR3qx91smURF3R455V1ubqtoUsZbgqikfg"
}
]
}

Chaingateway non memorizza le password. Una password persa significa un wallet perso.

Prima di muovere un token, leggi il suo contratto. Il valore decimals è quello che ti servirà più spesso, perché indica come il saldo grezzo on-chain si traduce nell’importo che vede un utente.

Terminal window
curl --request GET\
--url https://api.chaingateway.io/v2/tron/trc20/TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t\
--header 'Accept: application/json'\
--header 'Authorization: YOUR_API_TOKEN'
{
"status": 200,
"ok": true,
"message": "TRC20 contract fetched",
"data": {
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"symbol": "USDT",
"name": "TetherUSD",
"totalSupply": "61742996582033118",
"decimals": "6"
}
}

Un indirizzo di contratto sconosciuto o non-TRC20 risponde con status 400 e il messaggio Error fetching TRC20 contract.

Terminal window
curl --request GET\
--url https://api.chaingateway.io/v2/tron/balances/TVF2Mp9QY7FEGTnr3DBpFLobA6jguHyMvi/trc20/TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj\
--header 'Accept: application/json'\
--header 'Authorization: YOUR_API_TOKEN'
{
"status": 200,
"ok": true,
"message": "TRC20 balance fetched",
"data": {
"tronaddress": "TVF2Mp9QY7FEGTnr3DBpFLobA6jguHyMvi",
"decimals": 6,
"balance": "1000000000000000000",
"contractaddress": "TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj"
}
}

Il campo balance è il valore intero grezzo. Dividilo per 10 elevato alla potenza di decimals per ottenere l’importo leggibile.

POST /v2/tron/transactions/trc20 richiede from, to, contractaddress e amount. Per firmare aggiungi password, se l’indirizzo è stato creato con una password, oppure privatekey per un indirizzo non protetto o importato.

  • from: L’indirizzo TRON del mittente.
  • to: L’indirizzo TRON del destinatario.
  • contractaddress: L’indirizzo del contratto del token.
  • amount: L’importo da inviare.
  • password: La password di un indirizzo Chaingateway protetto da password. Obbligatoria quando privatekey non è presente.
  • privatekey: La private key del mittente, per indirizzi creati o importati senza password.
Terminal window
curl --request POST\
--url https://api.chaingateway.io/v2/tron/transactions/trc20\
--header 'Accept: application/json'\
--header 'content-type: application/json'\
--header 'Authorization: YOUR_API_TOKEN'\
--data '{
"from": "TLkkCeNdJKPNUwucdro84WjswkzM62LCTH",
"to": "TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp",
"contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"amount": 1,
"password": "test123"
}'

Una chiamata riuscita risponde con l’hash della transazione:

{
"status": 201,
"ok": true,
"message": "Succesfully created transaction",
"data": {
"txid": "0x73344d178812d4919e9002c560781f288030edf72ece88823ef1c377dfb71f27"
}
}

Due errori tornano con status 422 e vale la pena gestirli separatamente. balance is not sufficient significa che l’indirizzo mittente non può pagare la transazione. Un messaggio Validate signature error significa che la chiave o la password non corrispondevano all’indirizzo from.

Un transfer TRC20 è una chiamata a uno smart contract, e TRON addebita energy e bandwidth per essa. Un indirizzo che possiede solo token non può inviarli. Puoi finanziare l’indirizzo con TRX, mettere in staking risorse tramite POST /v2/tron/freeze e POST /v2/tron/delegate, oppure far sponsorizzare la commissione. La sponsorizzazione delle commissioni è descritta in Sponsorizzare le commissioni TRC20.

Se preferisci tenere la private key fuori dalla richiesta, dividi il transfer in due chiamate. POST /v2/tron/transactions/trc20/build restituisce l’esadecimale grezzo della transazione senza trasmetterla. Firmi quell’esadecimale nel tuo codice e consegni la transazione firmata a POST /v2/tron/transactions/broadcast.

Terminal window
curl --request POST\
--url https://api.chaingateway.io/v2/tron/transactions/trc20/build\
--header 'Accept: application/json'\
--header 'content-type: application/json'\
--header 'Authorization: YOUR_API_TOKEN'\
--data '{
"from": "TLkkCeNdJKPNUwucdro84WjswkzM62LCTH",
"to": "TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp",
"contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"amount": 1
}'

La risposta contiene raw_data e raw_data_hex. A questo punto nulla ha ancora raggiunto la rete.

Per essere informato di un deposito TRC20 senza fare polling, registra un webhook con type impostato su TRC20 e il contractaddress del token. I filtri from e to restringono la notifica a un singolo indirizzo.

Terminal window
curl --request POST\
--url https://api.chaingateway.io/v2/tron/webhooks\
--header 'Accept: application/json'\
--header 'content-type: application/json'\
--header 'Authorization: YOUR_API_TOKEN'\
--data '{
"url": "https://example.com/webhook-receiver",
"type": "TRC20",
"contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"to": "TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp"
}'

Come scrivere il lato ricevente è trattato in Creare webhook, e come verificare che una notifica provenga davvero da Chaingateway in Proteggere i webhook.

Una notifica che il tuo server non ha accettato non viene reinviata automaticamente. Le notifiche fallite sono elencate sotto GET /v2/tron/webhooks/notifications/failed e possono essere rilanciate con POST /v2/tron/webhooks/notifications/{id}/retry.

Ogni chiamata qui sopra funziona anche sulla testnet TRON Nile. Aggiungi l’header X-Network: testnet e usa token di test invece di contratti mainnet. L’elenco delle reti è documentato in Reti supportate.