Skip to content

Instantly share code, notes, and snippets.

@donma
Last active February 26, 2025 05:30
Show Gist options
  • Save donma/26c342b6660595f91002065f2bb38162 to your computer and use it in GitHub Desktop.
Save donma/26c342b6660595f91002065f2bb38162 to your computer and use it in GitHub Desktop.
static string ConvertHexToBase58Check(string hexAddress)
{
byte[] addressBytes = HexToBytes(hexAddress);
// 計算雙重 SHA-256 校驗碼
using (SHA256 sha256 = SHA256.Create())
{
byte[] hash1 = sha256.ComputeHash(addressBytes);
byte[] hash2 = sha256.ComputeHash(hash1);
// 取前 4 位作為校驗碼
byte[] checksum = hash2.Take(4).ToArray();
// 拼接地址與校驗碼
byte[] addressWithChecksum = addressBytes.Concat(checksum).ToArray();
// 轉換為 Base58
return EncodeBase58(addressWithChecksum);
}
}
static byte[] HexToBytes(string hex)
{
return Enumerable.Range(0, hex.Length / 2)
.Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16))
.ToArray();
}
var contractTransResult = GetTransactionByTXId("70cfc24c7fd731e1ea523268a3c9fdf738fe8ffa6ed410f520e1a32631d7b33e");
int methodOffset = contractTransResult.raw_data_hex.IndexOf("a9059cbb");
if (methodOffset == -1)
{
Console.WriteLine("這不是 TRC20 轉帳交易!");
return;
}
var rawDataHex = contractTransResult.raw_data_hex;
// 顯示結果 原始 rawdata_hex
Console.WriteLine(rawDataHex);
Console.WriteLine("-");
//From Address
int fromIndex = rawDataHex.IndexOf("0a15"); // "0a15" 是 owner_address 的標誌
if (fromIndex == -1)
{
Console.WriteLine("找不到 owner_address");
return;
}
string fromHex = rawDataHex.Substring(fromIndex + 4, 42);
var fromAddress = ConvertHexToBase58Check(fromHex);
Console.WriteLine("接收端地址: " + fromAddress);
//To Address
int toIndex = rawDataHex.IndexOf("a9059cbb");
if (toIndex == -1)
{
Console.WriteLine("找不到 to 地址");
return;
}
string toHex = rawDataHex.Substring(toIndex + 8 + 24, 40);
string toAddress = ConvertHexToBase58Check("41" + toHex);
Console.WriteLine("接收端地址: " + toAddress);
//Contract Address
int contractIndex = fromIndex + 4 + 42 + 4; // 4 是 TRON Protobuf 格式的 offset
string contractHex = rawDataHex.Substring(contractIndex, 42);
string contractAddress = ConvertHexToBase58Check(contractHex);
Console.WriteLine("合約地址: " + contractAddress);
///金額
int amountStartIndex = methodOffset + 8 + 64; // 64 = 32 bytes (To Address)
string amountHex = rawDataHex.Substring(amountStartIndex, 64); // 擷取 32 個 hex 字符 (16 bytes)
BigInteger amount = BigInteger.Parse(amountHex, NumberStyles.HexNumber);
Console.WriteLine("轉帳金額 (Amount): " + amount);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment