赞
踩
web3tool 是一组 Go 语言库,它们用于连接和操作 Ethereum 区块链。它们提供了一组简单易用的 API,可以让您轻松地与以太坊区块链进行交互。
首先新建一个文件夹,复制下面代码到test.go文件,然后执行
go mod init testweb3tool
再执行:
go mod tidy
test.go 文件如下:
- package main
-
- import (
- "encoding/hex"
- "fmt"
- "github.com/yellomoon/web3tool"
- "github.com/yellomoon/web3tool/abi"
- "github.com/yellomoon/web3tool/contract"
- "github.com/yellomoon/web3tool/jsonrpc"
- "github.com/yellomoon/web3tool/wallet"
- "math"
- "math/big"
- "sync"
- )
-
- var RpcClient *jsonrpc.Client
- var mut sync.Mutex
- var erc20AbiStr = `[{"constant":false,"inputs":[{"name":"_evilUser","type":"address"}],"name":"addBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_blackListedUser","type":"address"}],"name":"destroyBlackFunds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"redeem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_clearedUser","type":"address"}],"name":"removeBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newBasisPoints","type":"uint256"},{"name":"newMaxFee","type":"uint256"}],"name":"setParams","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_initialSupply","type":"uint256"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Issue","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAddress","type":"address"}],"name":"Deprecate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"feeBasisPoints","type":"uint256"},{"indexed":false,"name":"maxFee","type":"uint256"}],"name":"Params","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_blackListedUser","type":"address"},{"indexed":false,"name":"_balance","type":"uint256"}],"name":"DestroyedBlackFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"AddedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"RemovedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"basisPointsRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"deprecated","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_maker","type":"address"}],"name":"getBlackListStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBlackListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MAX_UINT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maximumFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"upgradedAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"}]`
- var uniswapRouter3Abi = `[{"inputs":[{"internalType":"address","name":"_factoryV2","type":"address"},{"internalType":"address","name":"factoryV3","type":"address"},{"internalType":"address","name":"_positionManager","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveMax","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveMaxMinusOne","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveZeroThenMax","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveZeroThenMaxMinusOne","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"callPositionManager","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"paths","type":"bytes[]"},{"internalType":"uint128[]","name":"amounts","type":"uint128[]"},{"internalType":"uint24","name":"maximumTickDivergence","type":"uint24"},{"internalType":"uint32","name":"secondsAgo","type":"uint32"}],"name":"checkOracleSlippage","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"uint24","name":"maximumTickDivergence","type":"uint24"},{"internalType":"uint32","name":"secondsAgo","type":"uint32"}],"name":"checkOracleSlippage","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"}],"internalType":"struct IV3SwapRouter.ExactInputParams","name":"params","type":"tuple"}],"name":"exactInput","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IV3SwapRouter.ExactInputSingleParams","name":"params","type":"tuple"}],"name":"exactInputSingle","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"}],"internalType":"struct IV3SwapRouter.ExactOutputParams","name":"params","type":"tuple"}],"name":"exactOutput","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IV3SwapRouter.ExactOutputSingleParams","name":"params","type":"tuple"}],"name":"exactOutputSingle","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factoryV2","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"getApprovalType","outputs":[{"internalType":"enum IApproveAndCall.ApprovalType","name":"","type":"uint8"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"}],"internalType":"struct IApproveAndCall.IncreaseLiquidityParams","name":"params","type":"tuple"}],"name":"increaseLiquidity","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"internalType":"struct IApproveAndCall.MintParams","name":"params","type":"tuple"}],"name":"mint","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"previousBlockhash","type":"bytes32"},{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"positionManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"pull","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowed","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowedIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"}],"name":"swapExactTokensForTokens","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"}],"name":"swapTokensForExactTokens","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"sweepTokenWithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"sweepTokenWithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"unwrapWETH9WithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"unwrapWETH9WithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"wrapETH","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]`
- var privateKey = "6631a605adf5a9cbcb646a79abb32dd461c9b406b1ff6e9e12a6248272fcc06a"
- var myAddress = "0xc0a8C0eA40BD40E8de0aef98Cc1473D990077bE5"
- var uniswapRouter3Address = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
- var usdtAddress = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
- var wbtcAddress = "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"
- var rpcUrl = "https://eth-mainnet.public.blastapi.io" // RPC URL 如果地址不能使用了 请去 https://infura.io 注册账号获取免费的
-
- 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
- }
- func getErc20Abi() *abi.ABI {
- erc20Abi, _ := abi.NewABI(erc20AbiStr)
- return erc20Abi
- }
-
- func getUniswapAbi() *abi.ABI {
- uniswapAbi, _ := abi.NewABI(uniswapRouter3Abi)
- return uniswapAbi
- }
-
- func mycontract(contractAddress string, abi *abi.ABI) *contract.Contract {
- privateByte, _ := hex.DecodeString(privateKey)
- key, _ := wallet.NewWalletFromPrivKey(privateByte)
- opts := []contract.ContractOption{
- contract.WithJsonRPC(getClient().Eth()),
- contract.WithSender(key),
- }
- c := contract.NewContract(web3tool.HexToAddress(contractAddress), abi, opts...)
- return c
- }
-
- func mycontractCall(txn contract.Txn) string {
- err := txn.Do()
- receipt, err := txn.Wait()
- if err != nil {
- panic(err)
- }
- fmt.Printf("Transaction mined at: %s", receipt.TransactionHash)
- return receipt.TransactionHash.String()
- }
-
- /*
- 获取指定账户的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
- }
-
- /*
- 获取指定账户的erc20代币余额
- erc20Address:erc20合约地址
- ownerAddress: 指定账户地址
- :return:账户erc20代币余额
- */
- func getErc20Balance(erc20Address, ownerAddress string) *big.Int {
- client := getClient()
- number, err := client.Eth().BlockNumber()
- if err != nil {
- panic(err)
- }
- contract := contract.NewContract(web3tool.HexToAddress(erc20Address), getErc20Abi(), contract.WithJsonRPC(client.Eth()))
- result, _ := contract.Call("balanceOf", web3tool.BlockNumber(number), web3tool.HexToAddress(ownerAddress))
- return (result["0"]).(*big.Int)
- }
-
- /*
- 获取ERC20代币的授权量
- erc20Address:代币合约地址
- ownerAddress:授权主体
- contractAddress: 被授权方地址
- */
- func getErc20Allowance(erc20Address, ownerAddress, contractAddress string) *big.Int {
- client := getClient()
- contract := contract.NewContract(web3tool.HexToAddress(erc20Address), getErc20Abi(), contract.WithJsonRPC(client.Eth()))
- result, err := contract.Call("allowance", web3tool.Latest, web3tool.HexToAddress(ownerAddress), web3tool.HexToAddress(contractAddress))
- if err != nil {
- return big.NewInt(0)
- }
- return (result["remaining"]).(*big.Int)
- }
-
- /*
- 发送指定数量的eth给指定地址
- toAddress:接收方地址
- amount:发送eth数量
- */
- func transferEth(toAddress string, amount float64) string {
- amountInt := int64(amount * math.Pow10(18))
- to := web3tool.HexToAddress(toAddress)
- number, err := getClient().Eth().BlockNumber()
- if err != nil {
- panic(err)
- }
- nonce, _ := getClient().Eth().GetNonce(web3tool.HexToAddress(myAddress), web3tool.BlockNumber(number))
- txn := &web3tool.Transaction{
- To: &to,
- Value: big.NewInt(amountInt),
- GasPrice: 10,
- 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)
- }
- return hash.String()
- }
-
- /*
- 发送erc20代币给指定地址指定数量
- erc20Address:erc20代币合约地址
- toAddress:接收方地址
- amount:发送erc20代币数量
- */
- func transferErc20(erc20Address, toAddress string, amount int64) string {
- c := mycontract(erc20Address, getErc20Abi())
- txn, e := c.Txn("transfer", web3tool.HexToAddress(toAddress), amount, web3tool.Latest)
- if e != nil {
- fmt.Printf("%v", e)
- }
- hash := mycontractCall(txn)
- return hash
- }
-
- /*
- 授权给指定地址指定数量的消费额度
- erc20Address: erc20代币地址
- ownerAddress:授权方地址
- contractAddress:指定的其他消费代币的合约地址
- amount:授权数量
- */
- func approve(erc20Address, ownerAddress, contractAddress string, amount uint64) string {
- c := mycontract(erc20Address, getErc20Abi())
- txn, e := c.Txn("approve", web3tool.HexToAddress(contractAddress), amount, web3tool.Latest)
- if e != nil {
- fmt.Printf("%v", e)
- }
- hash := mycontractCall(txn)
- return hash
- }
-
- /*
- 发起dex交易,通过uniswapV3 dex进行交易
- :param inputAddress: 输入的erc20 代币地址
- :param outAddress: 输出的erc20 代币地址
- :param inputAmount: 输入数量
- */
- func UniswapV3Swap(inputAddress, outAddress string, inputAmount int64) string {
- allowance := getErc20Allowance(inputAddress, myAddress, uniswapRouter3Address)
- if allowance.Cmp(big.NewInt(inputAmount)) == -1 {
- h := approve(inputAddress, myAddress, uniswapRouter3Address, uint64(0xfffffffffffffff))
- fmt.Printf("hash: %s", h)
- }
- c := mycontract(uniswapRouter3Address, getUniswapAbi())
- txn, e := c.Txn("exactInputSingle", map[string]interface{}{
- "tokenIn": web3tool.HexToAddress(inputAddress),
- "tokenOut": web3tool.HexToAddress(outAddress),
- "fee": 3000,
- "recipient": web3tool.HexToAddress(myAddress),
- "amountIn": inputAmount,
- "amountOutMinimum": 0,
- "sqrtPriceLimitX96": 0,
- }, web3tool.Latest)
- if e != nil {
- fmt.Printf("%v", e)
- }
- hash := mycontractCall(txn)
- return hash
- }
-
- func main() {
- var hash string
- //获取账户以太坊余额
- balance := getEthBalance(myAddress)
- fmt.Printf("balance: %s", balance.String())
- //获取账户usdt余额
- erc20balance := getErc20Balance(usdtAddress, myAddress)
- fmt.Printf("erc20 balance: %s", erc20balance.String())
- // 发送1个以太坊给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707
- hash = transferEth("0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707", 1)
- fmt.Printf("%s", hash)
- //# 发送1usdt 给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707
- hash = transferErc20(usdtAddress, "0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707", 1)
- fmt.Printf("%s", hash)
- //# 给 uniswapRouter3Address 授权 100usdt的消费额度
- hash = approve(usdtAddress, myAddress, uniswapRouter3Address, 0)
- fmt.Printf("%s", hash)
- //myAddress uniswapRouter3Address 授权量多少usdt消费额度
- erc20allowance := getErc20Allowance(usdtAddress, myAddress, uniswapRouter3Address)
- fmt.Printf("erc20 allowance: %s", erc20allowance.String())
- //花 100 usdt 买入 WBTC
- hash = UniswapV3Swap(usdtAddress, wbtcAddress, 100)
- fmt.Errorf("%s", hash)
- }
通过test.go的例子,就可以实现链上套利交易啦
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。