type Client struct {
node string
GRPC *client.GrpcClient
}
func NewClient(node string) (*Client, error) {
c := new(Client)
if node == "" {
c.node = "grpc.trongrid.io:50051"
}
c.node = node
c.GRPC = client.NewGrpcClient(node)
err := c.GRPC.Start(grpc.WithInsecure())
if err != nil {
return nil, fmt.Errorf("grpc client start error: %v", err)
}
return c, nil
}
func (c *Client) keepConnect() error {
_, err := c.GRPC.GetNodeInfo()
if err != nil {
if strings.Contains(err.Error(), "no such host") {
return c.GRPC.Reconnect(c.node)
}
return fmt.Errorf("node connect error: %v", err)
}
return err
}
func (c *Client) Transfer(from, to string, amount int64) (*api.TransactionExtention, error) {
err := c.keepConnect()
if err != nil {
return nil, err
}
return c.GRPC.Transfer(from, to, amount)
}
func (c *Client) Broadcast(tx *core.Transaction) (*api.Return, error) {
return c.GRPC.Broadcast(tx)
}
func (c *Client) GetTrxBalance(addr string) (float64, error) {
err := c.keepConnect()
if err != nil {
return 0, err
}
account, err := c.GRPC.GetAccount(addr)
if err != nil {
return 0, err
}
return float64(account.Balance) / 1000000, err
}