代码拉取完成,页面将自动刷新
package ethtx
import (
"bytes"
"errors"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
type Builder struct {
err error
from common.Address
to common.Address
nonce uint64
balance *big.Int
amount *big.Int
price *big.Int
}
func NewBuilder() *Builder {
builder := new(Builder)
builder.price = big.NewInt(40000000000)
builder.amount = big.NewInt(0)
return builder
}
func (b *Builder) SetFrom(from string) {
if b.err != nil {
return
}
from_addr := common.HexToAddress(from)
zero_addr := common.Address{}
if from_addr == zero_addr {
b.err = errors.New("eth from address format error")
return
}
b.from = from_addr
return
}
func (b *Builder) SetTo(to string) {
if b.err != nil {
return
}
to_addr := common.HexToAddress(to)
zero_addr := common.Address{}
if to_addr == zero_addr {
b.err = errors.New("eth to address format error")
return
}
b.to = to_addr
return
}
func (b *Builder) SetNonce(nonce uint64) {
if b.err != nil {
return
}
b.nonce = nonce
}
func (b *Builder) SetBalance(balance *big.Int) {
if b.err != nil {
return
}
if balance == nil {
b.err = errors.New("The balance cannot be zero and negative")
return
}
if balance.Cmp(big.NewInt(0)) == -1 {
b.err = errors.New("The balance cannot be zero and negative")
return
}
if balance.Cmp(big.NewInt(0)) == 0 {
b.err = errors.New("The balance cannot be zero and negative")
return
}
b.balance = balance
return
}
func (b *Builder) SetAmount(amount *big.Int) {
if b.err != nil {
return
}
if amount == nil {
b.err = errors.New("The amount cannot be zero and negative")
return
}
if amount.Cmp(big.NewInt(0)) == -1 {
b.err = errors.New("The amount cannot be zero and negative")
return
}
if amount.Cmp(big.NewInt(0)) == 0 {
b.err = errors.New("The amount cannot be zero and negative")
return
}
b.amount = amount
return
}
func (b *Builder) SetPrice(price *big.Int) {
if b.err != nil {
return
}
if price == nil {
b.err = errors.New("eth price is zero")
return
}
if price.Cmp(big.NewInt(0)) == 0 {
b.err = errors.New("eth price is zero")
return
}
b.price = price
return
}
func (b *Builder) Build() ([]byte, error) {
if b.err != nil {
return []byte{}, b.err
}
// 计算交易费用
fee := big.NewInt(0).Mul(b.price, big.NewInt(21000))
if big.NewInt(0).Sub(b.balance, fee).Cmp(big.NewInt(0)) == -1 {
return []byte{}, fmt.Errorf("shortage of balance %d < %d ", fee, b.balance)
}
unsign_tx := types.NewTransaction(
b.nonce,
b.to,
b.amount,
21000,
b.price,
nil,
)
buf := bytes.NewBuffer(nil)
err := unsign_tx.EncodeRLP(buf)
if err != nil {
return []byte{}, err
}
dst := []byte{}
dst = append(dst, b.from.Bytes()...)
dst = append(dst, buf.Bytes()...)
return dst, nil
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。