Creare transazioni di token TRC20 su TRON
Introduzione
Sezione intitolata “Introduzione”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.
Cosa fa l’API e cosa non fa
Sezione intitolata “Cosa fa l’API e cosa non fa”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 fare | Endpoint |
|---|---|
| Creare un indirizzo TRON | POST /v2/tron/addresses |
| Importare una private key esistente | POST /v2/tron/addresses/import |
| Leggere nome, simbolo, decimali e supply | GET /v2/tron/trc20/{contract_address} |
| Leggere il saldo di un token | GET /v2/tron/balances/{address}/trc20/{contract_address} |
| Inviare un transfer TRC20 | POST /v2/tron/transactions/trc20 |
| Costruire un transfer senza trasmetterlo | POST /v2/tron/transactions/trc20/build |
| Trasmettere una transazione firmata | POST /v2/tron/transactions/broadcast |
| Ricevere notifiche sui token in arrivo | POST /v2/tron/webhooks |
Passo 1: Creare un indirizzo TRON
Sezione intitolata “Passo 1: Creare un indirizzo TRON”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.
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"}'import requests
url = "https://api.chaingateway.io/v2/tron/addresses"payload = {"password": "test123"}headers = { 'Accept': 'application/json', 'content-type': 'application/json', 'Authorization': 'YOUR_API_TOKEN'}
response = requests.post(url, json=payload, headers=headers)print(response.json())const axios = require('axios');
const url = 'https://api.chaingateway.io/v2/tron/addresses';const payload = { password: 'test123' };const headers = { 'Accept': 'application/json', 'content-type': 'application/json', 'Authorization': 'YOUR_API_TOKEN'};
axios.post(url, payload, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });<?phprequire 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();$response = $client->post('https://api.chaingateway.io/v2/tron/addresses', [ 'headers' => [ 'Accept' => 'application/json', 'content-type' => 'application/json', 'Authorization' => 'YOUR_API_TOKEN', ], 'json' => [ 'password' => 'test123' ]]);
echo $response->getBody();?>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.
Passo 2: Leggere il contratto token
Sezione intitolata “Passo 2: Leggere il contratto token”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.
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.
Passo 3: Controllare il saldo del token
Sezione intitolata “Passo 3: Controllare il saldo del token”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.
Passo 4: Inviare il transfer TRC20
Sezione intitolata “Passo 4: Inviare il transfer TRC20”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.
Parametri
Sezione intitolata “Parametri”- 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
privatekeynon è presente. - privatekey: La private key del mittente, per indirizzi creati o importati senza password.
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"}'import requests
url = "https://api.chaingateway.io/v2/tron/transactions/trc20"payload = { "from": "TLkkCeNdJKPNUwucdro84WjswkzM62LCTH", "to": "TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp", "contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "amount": 1, "password": "test123"}headers = { 'Accept': 'application/json', 'content-type': 'application/json', 'Authorization': 'YOUR_API_TOKEN'}
response = requests.post(url, json=payload, headers=headers)print(response.json())const axios = require('axios');
const url = 'https://api.chaingateway.io/v2/tron/transactions/trc20';const payload = { from: 'TLkkCeNdJKPNUwucdro84WjswkzM62LCTH', to: 'TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp', contractaddress: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', amount: 1, password: 'test123'};const headers = { 'Accept': 'application/json', 'content-type': 'application/json', 'Authorization': 'YOUR_API_TOKEN'};
axios.post(url, payload, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });<?phprequire 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();$response = $client->post('https://api.chaingateway.io/v2/tron/transactions/trc20', [ 'headers' => [ 'Accept' => 'application/json', 'content-type' => 'application/json', 'Authorization' => 'YOUR_API_TOKEN', ], 'json' => [ 'from' => 'TLkkCeNdJKPNUwucdro84WjswkzM62LCTH', 'to' => 'TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp', 'contractaddress' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'amount' => 1, 'password' => 'test123' ]]);
echo $response->getBody();?>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.
Il wallet mittente ha bisogno di TRX
Sezione intitolata “Il wallet mittente ha bisogno di TRX”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.
Firmare la transazione da soli
Sezione intitolata “Firmare la transazione da soli”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.
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.
Ricevere notifiche sui token in arrivo
Sezione intitolata “Ricevere notifiche sui token in arrivo”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.
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.
Test su Nile
Sezione intitolata “Test su Nile”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.