This commit is contained in:
hashbro
2026-08-07 05:46:46 +08:00
parent 78b61f85d2
commit 82f8a8fffe
9 changed files with 399 additions and 44 deletions
+51
View File
@@ -75,6 +75,46 @@ class TronDriver implements ChainDriver
return TronAddress::isValid($address);
}
public function getNativeBalance(string $address): string
{
if (! $this->isValidAddress($address)) {
throw new RuntimeException('Invalid Tron address');
}
$account = $this->post('/wallet/getaccount', [
'address' => $address,
'visible' => true,
]);
$sun = (string) ($account['balance'] ?? 0);
return $this->fromSun($sun);
}
public function getTokenBalance(string $address, string $contract): string
{
if (! $this->isValidAddress($address) || ! $this->isValidAddress($contract)) {
throw new RuntimeException('Invalid Tron address');
}
$parameter = str_pad(TronAddress::toHex($address), 64, '0', STR_PAD_LEFT);
$ext = $this->post('/wallet/triggerconstantcontract', [
'owner_address' => $address,
'contract_address' => $contract,
'function_selector' => 'balanceOf(address)',
'parameter' => $parameter,
'visible' => true,
]);
$hex = $ext['constant_result'][0] ?? null;
if (! is_string($hex) || $hex === '') {
return '0';
}
$sun = gmp_strval(gmp_init($hex, 16), 10);
return $this->fromSun($sun);
}
private function path(int $index): string
{
return "m/44'/195'/0'/0/{$index}";
@@ -93,6 +133,17 @@ class TronDriver implements ChainDriver
return $sun;
}
private function fromSun(string $sun): string
{
if (! preg_match('/^\d+$/', $sun)) {
$sun = '0';
}
$human = bcdiv($sun, '1000000', 6);
$human = rtrim(rtrim($human, '0'), '.');
return $human === '' ? '0' : $human;
}
private function encodeTransferParameter(string $toBase58, string $amountSun): string
{
$toHex = TronAddress::toHex($toBase58); // 41 + 20 bytes