使用 golang 将ETH账户的资产平均分散到其他账户
平时如果你需要把一个账户的eth打散到很多账户,其他账户批量操作的话,就需要一个个的发送,很麻烦,下面这段脚本可以把一个账户的eth打散发送到指定的很多账户
首先安装依赖插件
go mod init test
#复制下面代码放入 test.go 然后执行:
go mod tidy
如下代码展示如何将0xbf8B5bc7Ea580ca7cEDa5F79F6ef3362134fC695 账户的ETH平均分散到其他账户
package main
import (
"encoding/hex"
"fmt"
"github.com/yellomoon/web3tool"
"github.com/yellomoon/web3tool/jsonrpc"
"github.com/yellomoon/web3tool/wallet"
"math"
"math/big"
"sync"
)
var RpcClient *jsonrpc.Client
var mut sync.Mutex
var privateKey = "ea9c312161c541758038e374a53147b933d39f504649b82f823285eb0b2ffd6e"
var myAddress = "0xbf8B5bc7Ea580ca7cEDa5F79F6ef3362134fC695"
var rpcUrl = "https://eth-mainnet.public.blastapi.io" // RPC URL 如果地址不能使用了 请去 https://infura.io 注册账号获取免费的
var dispersion_accounts = []string{
"0xA3059b44852dF4c592d7916C19aC1B8EdF839C4C",
"0x2EE0B3Bb2A0222A9a424c861548e6b8d8fd49f65",
"0x1f7537d14A8274C2e1F3B522D7025c1F765438FD",
"0xd27F9cA676d393432722Ae88D9e0cD9152e5Cb41",
"0x5911d5b71E78261ba0D28f71017C9BF418d1e7a1",
"0x1a5CA207E3b6a4FAceADb20DfB7B3aAD3B98c0b8",
}
func getClient() *jsonrpc.Client {
mut.Lock()
defer mut.Unlock()
var err error
if RpcClient == nil {
RpcClient, err = jsonrpc.NewClient(rpcUrl)
if err != nil {
panic(err)
}
}
return RpcClient
}
/*
获取指定账户的eth余额
address: 指定账户地址
:return:账户余额
*/
func getEthBalance(address string) *big.Int {
client := getClient()
number, err := client.Eth().BlockNumber()
if err != nil {
panic(err)
}
balance, e := client.Eth().GetBalance(web3tool.HexToAddress(address), web3tool.BlockNumber(number))
if e != nil {
panic(e)
}
return balance
}
func dispersion_funds() {
//var hash string
//获取账户eth余额
balance := getEthBalance(myAddress)
number, err := getClient().Eth().BlockNumber()
if err != nil {
panic(err)
}
nonce, _ := getClient().Eth().GetNonce(web3tool.HexToAddress(myAddress), web3tool.BlockNumber(number))
fmt.Printf("balance: %s", balance.String())
oneAmount := new(big.Int).Sub(balance, big.NewInt(int64(math.Pow10(18))))
oneAmount = new(big.Int).Div(oneAmount, big.NewInt(int64(len(dispersion_accounts))))
for index := range dispersion_accounts {
to := web3tool.HexToAddress(dispersion_accounts[index])
txn := &web3tool.Transaction{
To: &to,
Value: oneAmount,
GasPrice: 20000000000,
Gas: 21000,
Nonce: nonce,
}
privateByte, _ := hex.DecodeString(privateKey)
key, _ := wallet.NewWalletFromPrivKey(privateByte)
signer := wallet.NewEIP155Signer(1) //主网 chainID是1
txn, _ = signer.SignTx(txn, key)
data, _ := txn.MarshalRLPTo(nil)
hash, err := getClient().Eth().SendRawTransaction(data)
if err != nil {
fmt.Printf("%v", err)
}
fmt.Printf("%s\n", hash.String())
nonce++
}
}
func main() {
dispersion_funds()
}
每天学习一点点,遨游在区块链知识海洋里
本文由博客一文多发平台 OpenWrite 发布!