iexbase / tron-api Goto Github PK
View Code? Open in Web Editor NEWA PHP API for interacting with Tron (TRX)
Home Page: https://iexbase.github.io/tron-api/
License: MIT License
A PHP API for interacting with Tron (TRX)
Home Page: https://iexbase.github.io/tron-api/
License: MIT License
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!
Is possible to set public address using private key? And or have private key and publick address from tronlink?
it will be nice to have similar method on this library
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
include_once '/iexbase/tron-api/vendor/autoload.php';
$tron = new \IEXBase\TronAPI\Tron();
how to set new timeout value now 30000
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?
hi
i use
$tron->getAccount('address')
but i dont get trc20 token balance
how to find trc20 token balance
Any way to transfer contract TRC20 to one account to another?
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?
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:
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 ?
$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?
How to check the contract currency amount in your account
Hello everyone,
How to send TRC10 tokens to another address using this API?
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
Is possibe to get estimated energy and bandwidth before call transaction on smart contract?
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
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.
Implement missing method
https://developers.tron.network/reference#walletgetassetissuebyname
You can see how it looks like in tron.js
https://github.com/tronprotocol/tron-web/blob/04a96d826c1dc084c73689d7db6d1ddab2f26810/src/lib/trx.js#L1218
Looks too easy but api not working.....
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 ?
Hi.
i write private key and later how to get public address from privatekey?
why function sendTransactionByPassword() and sendTransactionByPrivateKey() deleted?
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
file: \src\Concerns\ManagesUniversal.php
line:79
correct:$this->send($item[0], $item[1], null, $from));
I've found this issue when working with lib. It breaks my user land code, since it changes my default values to zero, and I don't have digits after decimal
tron-api/src/Support/Crypto.php
Line 17 in 259cb36
tron-api/src/Support/Crypto.php
Line 40 in 259cb36
Can you fix it (or I can do it if you want)?
And make new bugfix release v2.0.3
Hi @serderovsh
Currently tron-api uses wallet api to generate new address / account which might be insecure in certain cases.
Can you implement the account generation locally in the library?
E.g. similar to - https://github.com/mattvb91/tron-trx-php/blob/master/src/Wallet.php#L59
Would be also nice to implement deterministic address generation (this way the user will only need specific seed to generate subset of addresses).
Thanks.
It's possible to interact with Contracts? https://developers.tron.network/reference#contract
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.
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?
For example:
"constant_result" => array:1 [ 0 => "0000000000000000000000000000000000000000000000000000000000001099000000000000000000000000000000000000000000000000000000618e589e000000000000000000000000000000000000000000000000000000006056301f89000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000" ]
If I call this function directly on the contract I get this:
code
echo fromtron(10);
1.0E5
how to fix it
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('TV4NbrAoxheTJCTeEDkAMyqCcWXtG48e9g','TBEteZd9whwjm2Jf8ZWBDFT5uHE147oUwo','ComicCon',1)
array:1 [▼
"Error" => "class org.tron.core.exception.ContractValidateException : assetBalance is not sufficient."
]
Why is not sufficient?
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?
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
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.
Laravel requires guzzlehttp/guzzle
^7.0.1
To be able to install tron-api, I had to bump the version down to 6.5.x-dev
Can Guzzle version be bumped to latest without breaking anything?
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.
It would be great if return types will be some special objects instead of array, it would be too much comfortable to work with it
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.
Line 711 in fafeab3
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));
$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"
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??
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 ?
Method createAddress doesn't work.
Return value of IEXBase\\TronAPI\\Tron::createAccount() must be of the type array, object returned
Should use generateAddress
is it secure to set $tron->setPrivateKey and $tron->sendTrx?
is Private key sending to https://api.trongrid.io?
Thanks,
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.