wallet/pkg/tron/tron_transaction.go

92 lines
2.2 KiB
Go
Raw Normal View History

2024-08-31 14:46:20 +00:00
package tron
import (
"crypto/sha256"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
ecommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/fbsobreira/gotron-sdk/pkg/client"
"github.com/fbsobreira/gotron-sdk/pkg/common"
"github.com/fbsobreira/gotron-sdk/pkg/proto/core"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
)
func (ta *TronAccount) SignTx(tx *core.Transaction) (*core.Transaction, error) {
rawData, err := proto.Marshal(tx.GetRawData())
if err != nil {
return nil, err
}
h256h := sha256.New()
h256h.Write(rawData)
hash := h256h.Sum(nil)
signature, err := crypto.Sign(hash, ta.privateKey.ToECDSA())
if err != nil {
return nil, err
}
tx.Signature = append(tx.Signature, signature)
return tx, nil
}
type TransactionRawData = map[string]interface{}
type TransactionData struct {
From string
To string
Value string
}
func DecodeTRC20Transfer(data []byte) (tx TransactionData, err error) {
abi, err := abi.JSON(strings.NewReader(COMMON_ABI))
if err != nil {
return TransactionData{}, err
}
raw := make(TransactionRawData)
if len(data) < 4 {
return TransactionData{}, nil
}
methodSigData := data[:4]
method, err := abi.MethodById(methodSigData)
if err != nil {
return TransactionData{}, err
}
inputsSigData := data[4:]
if err := method.Inputs.UnpackIntoMap(raw, inputsSigData); err != nil {
return TransactionData{}, err
}
tx = TransactionData{}
if raw["_from"] != nil {
tx.From = common.EncodeCheck(
ToTronAddress(raw["_from"].(ecommon.Address).Bytes()),
)
}
if raw["_to"] != nil {
tx.To = common.EncodeCheck(
ToTronAddress(raw["_to"].(ecommon.Address).Bytes()),
)
}
if raw["_value"] != nil {
tx.Value = raw["_value"].(*big.Int).String()
}
return tx, nil
}
func GetTransactionByHash(txHash string) (*core.Transaction, error) {
conn := client.NewGrpcClient(tronNode.grpcNode)
err := conn.Start(grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, err
}
tx, err := conn.GetTransactionByID(txHash)
if err != nil {
return nil, err
}
return tx, nil
}