以太坊测试网转账客户端实现

背景:

因为需要频繁使用eth ropsten转账, python调用感觉不太方便, 所以整理了一个简单的转账客户端

代码:

package main

import (
	"context"
	"crypto/ecdsa"
	"fmt"
	"log"
	"math/big"
	"os"
	"strconv"


	//"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/common"
	//"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/crypto/sha3"
	"github.com/ethereum/go-ethereum/ethclient"

)


func main() {
	args := os.Args
	if len(args) != 4 {
		fmt.Println(`
pls input correct parameters
usage:
	$ ./transfer {to_address} {toke_type} {amount}
	to_address: to token address
	token_type: a***/usdt
	amount: amount of token
ex:
./transfer xxxxxxxxxxxxxxx usdt 1`)
		return
	}
	toArg := args[1]
	amountArg1 := args[3]
	token_type := args[2]

	var tokenAddress common.Address
	var gasLimit uint64
	base := new(big.Float)
	if token_type == "a***" {
		/* a*** */
		fmt.Println("transfer a***" )
		base.SetFloat64(1000000000000000000)
		tokenAddress = common.HexToAddress("xxxxxxxxxxxxxxxxxxxxxxxxxxxx")//合约地址
		gasLimit = 210000

		//fmt.Printf(contract )
	} else {
		/* USDT */
		fmt.Println("transfer usdt" )
		base.SetFloat64(1000000)
		tokenAddress = common.HexToAddress("0x98b78f473dcfa4122dce98583e088d594185fba7")//USDT Contract: 0x98b78f473dcfa4122dce98583e088d594185fba7
		gasLimit = 84309
	}
	amountArg, err := strconv.ParseFloat(amountArg1, 10)
	fmt.Println(fmt.Sprintf("amount : %v", amountArg))
	bigFloat := big.NewFloat(amountArg)
	var bigFloat1 big.Float
	bigFloat1.Mul(bigFloat, base)

	client, err := ethclient.Dial("https://ropsten.infura.io/v3/xxxxxxxxxxxxxxxxxxxxxxxxxxxx")//infura地址
	if err != nil {
		log.Fatal(err)
	}

	privateKey, err := crypto.HexToECDSA("xxxxxxxxxxxxxxx")//私钥
	if err != nil {
		log.Fatal(err)
	}

	publicKey := privateKey.Public()
	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
	if !ok {
		log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
	}

	fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
	nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
	if err != nil {
		log.Fatal(err)
	}

	value := big.NewInt(0) // in wei (0 eth)
	gasPrice, err := client.SuggestGasPrice(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	toAddress := common.HexToAddress(toArg)
	transferFnSignature := []byte("transfer(address,uint256)")
	hash := sha3.NewKeccak256()
	hash.Write(transferFnSignature)
	methodID := hash.Sum(nil)[:4]
	//fmt.Println(hexutil.Encode(methodID)) // 0xa9059cbb

	paddedAddress := common.LeftPadBytes(toAddress.Bytes(), 32)
	amount := new(big.Int)
	bigFloat1.Int(amount)
	paddedAmount := common.LeftPadBytes(amount.Bytes(), 32)

	var data []byte
	data = append(data, methodID...)
	data = append(data, paddedAddress...)
	data = append(data, paddedAmount...)

	tx := types.NewTransaction(nonce, tokenAddress, value, gasLimit, gasPrice, data)

	chainID, err := client.NetworkID(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey)
	if err != nil {
		log.Fatal(err)
	}

	err = client.SendTransaction(context.Background(), signedTx)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("tx sent: %s", signedTx.Hash().Hex()) // tx sent: xxxxxxxxxxxxxx
}

讲解:

合约地址

tokenAddress = common.HexToAddress("0x98b78f473dcfa4122dce98583e088d594185fba7")//USDT Contract: 0x98b78f473dcfa4122dce98583e088d594185fba7

来源:

https://ropsten.etherscan.io/token/0x98b78f473dcfa4122dce98583e088d594185fba7

infura地址:

client, err := ethclient.Dial("https://ropsten.infura.io/v3/xxxxxxxxxxxxxxxxxxxxxxxxxxxx")//infura地址

https://infura.io/dashboard/ethereum/02539f07320f43208937745e3058386f/settings

私钥:

privateKey, err := crypto.HexToECDSA("xxxxxxxxxxxxxxx")//私钥

 

编译收工

参考

https://goethereumbook.org/zh/transfer-tokens/

https://github.com/ethereum/go-ethereum

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要搭建本地以太坊私链并连接钱包实现转账,你需要按照以下步骤进行操作: 1. 安装以太坊客户端软件,比如 Geth、Parity、Quorum 等。 2. 创建私有络,可以使用以下命令: ``` geth --datadir=./chaindata init ./genesis.json ``` 其中,`./chaindata` 是指定数据目录,`./genesis.json` 是指定创世区块文件。 3. 启动私有络,可以使用以下命令: ``` geth --datadir=./chaindata --networkid=8888 --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpcapi="eth,net,web3,personal" console ``` 其中,`--networkid` 是指定络 ID,`--rpc` 是启用 JSON-RPC 接口,`--rpcaddr` 是指定 JSON-RPC 接口的 IP,`--rpcport` 是指定 JSON-RPC 接口的端口号,`--rpcapi` 是启用 JSON-RPC 接口的 API 列表。 4. 创建钱包地址,可以使用以下命令: ``` personal.newAccount("password") ``` 其中,`password` 是指定钱包密码。 5. 解锁钱包,可以使用以下命令: ``` personal.unlockAccount("address", "password", 0) ``` 其中,`address` 是指定钱包地址,`password` 是钱包密码,`0` 是指定解锁时间。 6. 发送转账交易,可以使用以下命令: ``` eth.sendTransaction({from:"from_address", to:"to_address", value: web3.toWei(1, "ether")}) ``` 其中,`from_address` 是发送方钱包地址,`to_address` 是接收方钱包地址,`1` 是转账金额,`ether` 是转账单位。 7. 确认交易状态,可以使用以下命令: ``` eth.getTransactionReceipt("transaction_hash") ``` 其中,`transaction_hash` 是指定交易哈希值。 以上是搭建本地以太坊私链并连接钱包实现转账的大致步骤,具体操作还需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值