Giter Site home page Giter Site logo

iexbase / tron-api Goto Github PK

View Code? Open in Web Editor NEW
386.0 19.0 276.0 201 KB

A PHP API for interacting with Tron (TRX)

Home Page: https://iexbase.github.io/tron-api/

License: MIT License

PHP 100.00%
tron tron-api tron-rest tron-library tron-protocol tron-wallet tronscan php

tron-api's Introduction

TRON API

A PHP API for interacting with the Tron Protocol

Latest Stable Version Software License Build Status Contributors Total Downloads

Install

> composer require iexbase/tron-api --ignore-platform-reqs

Requirements

The following versions of PHP are supported by this version.

  • PHP 7.4

Example Usage

use IEXBase\TronAPI\Tron;

$fullNode = new \IEXBase\TronAPI\Provider\HttpProvider('https://api.trongrid.io');
$solidityNode = new \IEXBase\TronAPI\Provider\HttpProvider('https://api.trongrid.io');
$eventServer = new \IEXBase\TronAPI\Provider\HttpProvider('https://api.trongrid.io');

try {
    $tron = new \IEXBase\TronAPI\Tron($fullNode, $solidityNode, $eventServer);
} catch (\IEXBase\TronAPI\Exception\TronException $e) {
    exit($e->getMessage());
}


$this->setAddress('..');
//Balance
$tron->getBalance(null, true);

// Transfer Trx
var_dump($tron->send('to', 1.5));

//Generate Address
var_dump($tron->createAccount());

//Get Last Blocks
var_dump($tron->getLatestBlocks(2));

//Change account name (only once)
var_dump($tron->changeAccountName('address', 'NewName'));


// Contract
$tron->contract('Contract Address');

Testing

$ vendor/bin/phpunit

Donations

Tron(TRX): TRWBqiqoFZysoAeyR1J35ibuyc8EvhUAoY

tron-api's People

Contributors

1099511627776 avatar dogdev avatar kaankozan avatar sashabeton avatar serderovsh avatar sharifzadesina avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tron-api's Issues

TRC20 Transfer

There is a function sendToken in this package which accepts token id as parameter to initiate a transaction but we can only get only id for trc10 token but how to transfer trc20 token ?

getEventByTransactionID not working

Getting events for a specific transaction is not working.

$tron->getEventByTransactionID($tr_id);

response is
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: POST https://api.trongrid.io/event/transaction/3fe74875a6edf91d68b54f6cf305716d7870c328aad0089d056f027a6c4af997 resulted in a 404 Not Found

I think that the URL format is not valid, instead of
https://api.trongrid.io/event/transaction/**ID**
it should be
https://api.trongrid.io/v1/transactions/**ID**/events

how to set new time out value

include_once '/iexbase/tron-api/vendor/autoload.php';
$tron = new \IEXBase\TronAPI\Tron();

how to set new timeout value now 30000

Many timeouts

Getting many timeouts while trying to connect to trongrid and send trx.
It used to work very well, I don't know if it's the tron network being too busy because of FOMO, or there's a problem with trongrid. What do you think?
The error I get once in a while:

Fatal error: Uncaught RuntimeException: Error creating resource: [message] fopen(https://api.trongrid.io/wallet/broadcasttransaction): failed to open stream: Connection timed out [file] /var/www/html/mysite/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php [line] 324 in /var/www/html/mysite/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php:253 Stack trace: #0 /var/www/html/mysite/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(335): GuzzleHttp\Handler\StreamHandler->createResource(Object(Closure)) #1 /var/www/html/mysite/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(52): GuzzleHttp\Handler\StreamHandler->createStream(Object(GuzzleHttp\Psr7\Request), Array) #2 /var/www/html/mysite/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php(66): GuzzleHttp\Handler\StreamHandler->__invoke(Object(GuzzleHttp\Psr7\Request), Array) #3 /var/www/html/mysite/vendor/guzzlehttp/guzzle/src/Middleware.php(29): GuzzleHttp\PrepareBodyMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array) in /var/www/html/mysite/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 52

Possible syntax error in Tron.php

public function __construct(?HttpProviderInterface $fullNode = null,
?HttpProviderInterface $solidityNode = null,

Lines 84 & 85

Are you sure the ?'s are supposed to be there ? gives out a syntax error on my IDE.

Transaction builder TRC20

Any way to transfer contract TRC20 to one account to another?
Tronweb have this function, is possible to add it?
We see trigger smart contract but we need just transfer contract.

Thanks

triggerSmartContract return OTHER_ERROR

Contract source code: https://github.com/gfijrb/tronditeco/blob/master/contracts/Test.sol

Curl example

// request 
curl -G https://api.shasta.trongrid.io/wallet/triggersmartcontract -X POST -d '{"contract_address":"TWMfdPPmzSybGfT47F3c9hqdMch6vVFXVG","function_selector":"doit()","parameter":"","fee_limit":1000000,"call_value":0,"owner_address":"TRC6hn9q7xdKZ67E3VyRpADo6EAeFjyEyu"}'

// response
{"result":{"code":"OTHER_ERROR","message":"636c617373206f72672e74726f6e2e636f72652e73657276696365732e687474702e4a736f6e466f726d6174245061727365457863657074696f6e203a20313a313a20457870656374656420227b222e"}}

And can you explain. In code if func by signature has params they must be sent as usual string or in bytecode?

contract_address - HEX or BASE58
owner_address - HEX or BASE58
fee_limit - max possible value?

OTHER_ERROR : msg: blablabla....
How to read this message?

need example getTokenBalance

there is a function but i cant found my tokenID. hown can i generate wallet for my token? and i want getToken balance with my wallet address. need exaple over php

ABI TriggerSmartContract

Hi.

Set ABI contract

$json= ' [ { "inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_wtrx","type":"address"}], "payable":false, "stateMutability":"nonpayable", "type":"constructor" }, {"payable":true,"stateMutability":"payable","type":"fallback"}, {"constant":false,"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint256","name":"amountADesired","type":"uint256"},{"internalType":"uint256","name":"amountBDesired","type":"uint256"},{"internalType":"uint256","name":"amountAMin","type":"uint256"},{"internalType":"uint256","name":"amountBMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"addLiquidity","outputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"amountB","type":"uint256"},{"internalType":"uint256","name":"liquidity","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"}, ]'; $abi = json_decode($json);

ERROR:

PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array in C:\xampp7\htdocs\tron\vendor\iexbase\tron-api\src\TransactionBuilder.php:424 Stack trace: #0 C:\xampp7\htdocs\tron\index.php(58): IEXBase\TronAPI\TransactionBuilder->triggerSmartContract() #1 {main} thrown in C:\xampp7\htdocs\tron\vendor\iexbase\tron-api\src\TransactionBuilder.php on line 424

USE:
$tron->getTransactionBuilder()->triggerSmartContract($abi, $data['contract_address'], $data['function_selector'], ['uint256', 'address', 'address', 'bool'], $data['fee_limit'], $data['contract_address']);

I cannot understand how it should be. It seems like I'm doing everything right, but it doesn't work.
I tried to redo it from an object into an array and various other ways, in the end it does not work. Maybe there is some exactly correct option and someone will share?

getBalance method gives wrong amount

$tron->getBalance('TMuA6YqfCeX8EhbfYEg5y7S4DqzSJireY9')
or even
$tron->getBalance('TMuA6YqfCeX8EhbfYEg5y7S4DqzSJireY9',true)

I get wrong balance, because in first case I get 15286180772100810 and in second case I get 15286180772.101
the difference is rounding done after .10
this method should return 15286180772.10081
I know that 0.001 is not that much but I still makes wrong calculations.
I would like to see correct result up to 18 decimals (that's what trc-20 max decimals are)

Is there a way to do this?

"Undefined index: balance" in getAccount

public function getBalance(string $address = null, bool $fromTron = false): float
{
$address = (!is_null($address) ? $address : $this->address);
$account = $this->getAccount($address);

    if(!$account['balance'] || !array_key_exists('balance', $account)) {
        return 0;
    }

    return ($fromTron == true ?
        $this->fromTron($account['balance']) :
        $account['balance']);
}

"Undefined index: balance"

Do you know why the error?

Make functions from TronAwareTrait - static

I suggest you to convert functions like fromTron, toTron, fromHex, toHex etc to static as thay do not use Tron object internal state and should be called without instantiating whole tron object.

If you are afraid of braking api compatibility then you should do this in 4 steps.

  1. Make static copies of those functions
  2. Make non static functions to use static ones
  3. Declare non-static functions as deprecated
  4. After some time - remove non-static functions from trait

triggerSmartContract issues

i try triggerSmartContract but i have a problem

i using simple

transaction = $tron->getTransactionBuilder()->triggerSmartContract(
$abi,
$contract,
$function,
$params,
$feeLimit,
$address,
$callValue = 0,
$bandwidthLimit = 0);

but problem ethabi in

iexbase/tron-api/vendor/sc0vu/web3.php/src/Contracts/Ethabi.php on line 176

this function in
encodeParameters($types, $params)

176th line
return '0x' . $this->encodeMultiWithOffset($types, $solidityTypes, $encodes, $dynamicOffset);

what is a problem??

$tron->createAccount();

hi

i have again one question

i use creat account

$tron->createAccount();
return array in privatekey and publickey

and i sent to 1 trx to new address

but i dont send

response

AccountResourceInsufficient

why i dont send ? i try again 40 minutes later but i dont send again

what can i do ?

createAddress() doesn't work

Method createAddress doesn't work.
Return value of IEXBase\\TronAPI\\Tron::createAccount() must be of the type array, object returned
Should use generateAddress

send TRC10

Hello everyone,
How to send TRC10 tokens to another address using this API?

Calling a TRC20 Smart Contracts Function Example.

I am pretty new to blockchain programming but am fairly well versed in php and javascript. If I wanted to call a public function in a deployed smart contract is that possible with this api and could you provide some sample code.

For example, if I wanted to call the public read-only function "calculateTokensReceived" in the smart contract address below, what might that look like, and does this PHP API support that?

var the_contact_address = TSXnUzYWuockj3KspfGAd8hnRhshPm1yyw;

// The javascript clientside tronWeb version of what I want to do would look a bit like this:

fund = await tronWeb.contract().at(the_contact_address );

function clientsidecallto_calculateTokensReceived() {
    var _trxtocovert = 1000;
    var _trx_in_suns_to_convert = BigNumber(_trxneeded * 1e18).toFixed(0);

    fund.calculateTokensReceived(amt).call().then(result => {
     console.log('result',result.toString());
       document.getElementById("tokens_you_will_get" ).textContent = (result/1e18).toFixed(2); 
   });

If you can put me on the right track to start, I will produce a few examples of making calls to smart contracts and parsing the output for the php api project... Thanks!

PHP version required

I get the following error when i try to install with composer,

./composer.phar require iexbase/tron-api

[InvalidArgumentException]
Package iexbase/tron-api at version has a PHP requirement incompatible with your PHP version (7.0.31)

What version of PHP is needed ?

getAccount still use walletsolidity

As nile testnet and the latest version of tron 4.0.1. There's no need to use soliditynode to getdata. Is there any plan to suit the latest version of tron?

Installation issue

By running the following command : composer require iexbase/tron-api, i have this errors :

Using version ^3.1 for iexbase/tron-api
./composer.json has been updated
Running composer update iexbase/tron-api
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - iexbase/tron-api[v3.1.1, ..., v3.1.2] require guzzlehttp/guzzle ^7.0 -> found guzzlehttp/guzzle[dev-master, 7.0.0-beta.1, ..., 7.2.0] but the package is fixed to 6.5.5 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - Root composer.json requires iexbase/tron-api ^3.1 -> satisfiable by iexbase/tron-api[v3.1.1, v3.1.2].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Create syntatic sugar method similar to getBalance

it would be nice to have similar method to getBalance that will get balance of an asset,
I think the signature should look like this
getTokenBalance(string $tokenID, string $address = null, bool $formated = false): float

the internal code should look like,

   public function getTokenBalanceByAddress(string $tokenId, string $address = null, bool $formatted = false): float
    {
        $account = $this->tron->getAccount($address);

        if(!array_key_exists('assetV2', $account)) {
            return 0.0;
        }

        $amount = 0.0;
        foreach ($account['assetV2'] as $asset) {
            if ($asset['key'] === $tokenId) {
                $amount = $asset['value'];
            }
        }
        if ($amount === 0.0) {
            return $amount;
        }

        if ($formatted) {
            $tokenInfo = $this->tron->getTokenFromID($tokenId);
            if (array_key_exists('precision', $tokenInfo)) {
                $precision = $tokenInfo['precision'];
            } else {
                $precision = 0;
            }
            return (float)bcdiv((string)$amount, bcpow('10', (string)$precision), $precision);
        }
        return $amount;
    }

createSendAssetTransaction() assetBalance is not sufficient.

createSendAssetTransaction('TV4NbrAoxheTJCTeEDkAMyqCcWXtG48e9g','TBEteZd9whwjm2Jf8ZWBDFT5uHE147oUwo','ComicCon',1)

array:1 [▼
"Error" => "class org.tron.core.exception.ContractValidateException : assetBalance is not sufficient."
]

Why is not sufficient?

Issue with latest version

Upgraded to latest version and started getting this error, was working fine before.

Type: GuzzleHttp\Exception\ServerException
Message: Server error: POST https://api.trongrid.io/wallet/getblockbynum resulted
in a 504 Gateway Time-out response:

Sending transactions

var_dump($tron->sendTransaction('from', 'to', 'amount'));

Are the from and to addresses decoded from base58 format ? ie. do they start with the 'T' as seen in wallets or '41' as seen in blockchain transaction data ?

how many decimal places has the amount got ? ie. to send 1 tron what do u need to enter ? as opposed to say 1.01 tron ?

Thanks.

getTransactionsRelated : 400 Bad Request

I tried getTransactionsRelated and got the output:

Client error: POST https://api.trongrid.io/walletextension/gettransactionstothis resulted in a 400 Bad Request response: {"success":false,"error":{"code":400,"status":"Bad Request.","message":"TronGrid does not support /walletextension API." (truncated...)

I also read https://developers.tron.network/docs/new-api-service
There might be a slight improvement in the request url

Thankyou

signTransaction method has bug with the second param "message"

As the example of transactionbuilder shows, I set the second param "message" to something. Finally, sendRawTransaction returning sigerror with

validate signature error xxxxxx is signed by xxxxxx but it is not contained of permission.

public function signTransaction($transaction, string $message = null): array

here is the partial of my code:

$transaction = $tron->getTransactionBuilder()->sendTrx($dest_address, 300.0);

$signedtxs = $tron->signTransaction($transaction, $msg);
//die(print_r($signedtxs));

try {
    $response = $tron->sendRawTransaction($signedtxs);
}catch (\IEXBase\TronAPI\Exception\TronException $e) {
    exit($e->getMessage());
}

if (isset($response['code']) && $response['code'] === 'SIGERROR') {
    exit(hex2bin($response['message']));
}

die(print_r($response));

how to get balance trc20

hi
i use
$tron->getAccount('address')

but i dont get trc20 token balance

how to find trc20 token balance

Explorer not activated

$tron = new Tron($fullNode, $solidityNode, $eventServer);
                $transactions = $tron->getTransactionByAddress([
                    'address' => $address,
                    'only_to' => true,
                    'only_confirmed' => true,
                    'limit' => 2,
                    'order_by' => 'timestamp,desc',
                ]);

how do you get the transaction from certain address? i tried this and i got error "explorer is not activated"

How to decode "constant_result" to an array

For example:

"constant_result" => array:1 [ 0 => "0000000000000000000000000000000000000000000000000000000000001099000000000000000000000000000000000000000000000000000000618e589e000000000000000000000000000000000000000000000000000000006056301f89000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000" ]

If I call this function directly on the contract I get this:

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.