代码拉取完成,页面将自动刷新
package ethtx
import (
"bytes"
"errors"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
type TokenBuilder struct {
err error
from common.Address
to common.Address
contract common.Address
nonce uint64
amount *big.Int
limit uint64
price *big.Int
}
func NewTokenBuilder() *TokenBuilder {
builder := new(TokenBuilder)
builder.price = big.NewInt(10000000000)
builder.limit = 1000000
builder.amount = big.NewInt(0)
return builder
}
func (b *TokenBuilder) 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 *TokenBuilder) 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 *TokenBuilder) SetContract(contract string) {
if b.err != nil {
return
}
contract_addr := common.HexToAddress(contract)
zero_addr := common.Address{}
if contract_addr == zero_addr {
b.err = errors.New("eth contract address format error")
return
}
b.contract = contract_addr
return
}
func (b *TokenBuilder) SetNonce(nonce uint64) {
if b.err != nil {
return
}
b.nonce = nonce
}
func (b *TokenBuilder) 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 *TokenBuilder) 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 *TokenBuilder) SetLimit(limit uint64) {
b.limit = limit
return
}
func (b *TokenBuilder) Build() ([]byte, error) {
if b.err != nil {
return []byte{}, b.err
}
// 构建调用信息
parsed, _ := abi.JSON(strings.NewReader(TokenABI))
input, _ := parsed.Pack("transfer", b.to, b.amount)
// 构建交易
unsign_tx := types.NewTransaction(
b.nonce,
b.contract,
big.NewInt(0),
b.limit,
b.price,
input,
)
// 进行编码
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。