1 Star 0 Fork 0

coin-kit/eth-tx

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
builder.go 2.77 KB
一键复制 编辑 原始数据 按行查看 历史
跃迁雷电 提交于 2019-01-10 14:54 +08:00 . rm data from addr
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
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/coin-kit/eth-tx.git
git@gitee.com:coin-kit/eth-tx.git
coin-kit
eth-tx
eth-tx
302523317217

搜索帮助