当前位置:   article > 正文

golang web3 开发教程(web3tool)_web3 golang

web3 golang

web3tool 是一组 Go 语言库,它们用于连接和操作 Ethereum 区块链。它们提供了一组简单易用的 API,可以让您轻松地与以太坊区块链进行交互。

首先新建一个文件夹,复制下面代码到test.go文件,然后执行

go mod init testweb3tool

再执行:

go mod tidy

test.go 文件如下:

  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "github.com/yellomoon/web3tool"
  6. "github.com/yellomoon/web3tool/abi"
  7. "github.com/yellomoon/web3tool/contract"
  8. "github.com/yellomoon/web3tool/jsonrpc"
  9. "github.com/yellomoon/web3tool/wallet"
  10. "math"
  11. "math/big"
  12. "sync"
  13. )
  14. var RpcClient *jsonrpc.Client
  15. var mut sync.Mutex
  16. 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"}]`
  17. 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"}]`
  18. var privateKey = "6631a605adf5a9cbcb646a79abb32dd461c9b406b1ff6e9e12a6248272fcc06a"
  19. var myAddress = "0xc0a8C0eA40BD40E8de0aef98Cc1473D990077bE5"
  20. var uniswapRouter3Address = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
  21. var usdtAddress = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
  22. var wbtcAddress = "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"
  23. var rpcUrl = "https://eth-mainnet.public.blastapi.io" // RPC URL 如果地址不能使用了 请去 https://infura.io 注册账号获取免费的
  24. func getClient() *jsonrpc.Client {
  25. mut.Lock()
  26. defer mut.Unlock()
  27. var err error
  28. if RpcClient == nil {
  29. RpcClient, err = jsonrpc.NewClient(rpcUrl)
  30. if err != nil {
  31. panic(err)
  32. }
  33. }
  34. return RpcClient
  35. }
  36. func getErc20Abi() *abi.ABI {
  37. erc20Abi, _ := abi.NewABI(erc20AbiStr)
  38. return erc20Abi
  39. }
  40. func getUniswapAbi() *abi.ABI {
  41. uniswapAbi, _ := abi.NewABI(uniswapRouter3Abi)
  42. return uniswapAbi
  43. }
  44. func mycontract(contractAddress string, abi *abi.ABI) *contract.Contract {
  45. privateByte, _ := hex.DecodeString(privateKey)
  46. key, _ := wallet.NewWalletFromPrivKey(privateByte)
  47. opts := []contract.ContractOption{
  48. contract.WithJsonRPC(getClient().Eth()),
  49. contract.WithSender(key),
  50. }
  51. c := contract.NewContract(web3tool.HexToAddress(contractAddress), abi, opts...)
  52. return c
  53. }
  54. func mycontractCall(txn contract.Txn) string {
  55. err := txn.Do()
  56. receipt, err := txn.Wait()
  57. if err != nil {
  58. panic(err)
  59. }
  60. fmt.Printf("Transaction mined at: %s", receipt.TransactionHash)
  61. return receipt.TransactionHash.String()
  62. }
  63. /*
  64. 获取指定账户的eth余额
  65. address: 指定账户地址
  66. :return:账户余额
  67. */
  68. func getEthBalance(address string) *big.Int {
  69. client := getClient()
  70. number, err := client.Eth().BlockNumber()
  71. if err != nil {
  72. panic(err)
  73. }
  74. balance, e := client.Eth().GetBalance(web3tool.HexToAddress(address), web3tool.BlockNumber(number))
  75. if e != nil {
  76. panic(e)
  77. }
  78. return balance
  79. }
  80. /*
  81. 获取指定账户的erc20代币余额
  82. erc20Address:erc20合约地址
  83. ownerAddress: 指定账户地址
  84. :return:账户erc20代币余额
  85. */
  86. func getErc20Balance(erc20Address, ownerAddress string) *big.Int {
  87. client := getClient()
  88. number, err := client.Eth().BlockNumber()
  89. if err != nil {
  90. panic(err)
  91. }
  92. contract := contract.NewContract(web3tool.HexToAddress(erc20Address), getErc20Abi(), contract.WithJsonRPC(client.Eth()))
  93. result, _ := contract.Call("balanceOf", web3tool.BlockNumber(number), web3tool.HexToAddress(ownerAddress))
  94. return (result["0"]).(*big.Int)
  95. }
  96. /*
  97. 获取ERC20代币的授权量
  98. erc20Address:代币合约地址
  99. ownerAddress:授权主体
  100. contractAddress: 被授权方地址
  101. */
  102. func getErc20Allowance(erc20Address, ownerAddress, contractAddress string) *big.Int {
  103. client := getClient()
  104. contract := contract.NewContract(web3tool.HexToAddress(erc20Address), getErc20Abi(), contract.WithJsonRPC(client.Eth()))
  105. result, err := contract.Call("allowance", web3tool.Latest, web3tool.HexToAddress(ownerAddress), web3tool.HexToAddress(contractAddress))
  106. if err != nil {
  107. return big.NewInt(0)
  108. }
  109. return (result["remaining"]).(*big.Int)
  110. }
  111. /*
  112. 发送指定数量的eth给指定地址
  113. toAddress:接收方地址
  114. amount:发送eth数量
  115. */
  116. func transferEth(toAddress string, amount float64) string {
  117. amountInt := int64(amount * math.Pow10(18))
  118. to := web3tool.HexToAddress(toAddress)
  119. number, err := getClient().Eth().BlockNumber()
  120. if err != nil {
  121. panic(err)
  122. }
  123. nonce, _ := getClient().Eth().GetNonce(web3tool.HexToAddress(myAddress), web3tool.BlockNumber(number))
  124. txn := &web3tool.Transaction{
  125. To: &to,
  126. Value: big.NewInt(amountInt),
  127. GasPrice: 10,
  128. Gas: 21000,
  129. Nonce: nonce,
  130. }
  131. privateByte, _ := hex.DecodeString(privateKey)
  132. key, _ := wallet.NewWalletFromPrivKey(privateByte)
  133. signer := wallet.NewEIP155Signer(1) //主网 chainID是1
  134. txn, _ = signer.SignTx(txn, key)
  135. data, _ := txn.MarshalRLPTo(nil)
  136. hash, err := getClient().Eth().SendRawTransaction(data)
  137. if err != nil {
  138. fmt.Printf("%v", err)
  139. }
  140. return hash.String()
  141. }
  142. /*
  143. 发送erc20代币给指定地址指定数量
  144. erc20Address:erc20代币合约地址
  145. toAddress:接收方地址
  146. amount:发送erc20代币数量
  147. */
  148. func transferErc20(erc20Address, toAddress string, amount int64) string {
  149. c := mycontract(erc20Address, getErc20Abi())
  150. txn, e := c.Txn("transfer", web3tool.HexToAddress(toAddress), amount, web3tool.Latest)
  151. if e != nil {
  152. fmt.Printf("%v", e)
  153. }
  154. hash := mycontractCall(txn)
  155. return hash
  156. }
  157. /*
  158. 授权给指定地址指定数量的消费额度
  159. erc20Address: erc20代币地址
  160. ownerAddress:授权方地址
  161. contractAddress:指定的其他消费代币的合约地址
  162. amount:授权数量
  163. */
  164. func approve(erc20Address, ownerAddress, contractAddress string, amount uint64) string {
  165. c := mycontract(erc20Address, getErc20Abi())
  166. txn, e := c.Txn("approve", web3tool.HexToAddress(contractAddress), amount, web3tool.Latest)
  167. if e != nil {
  168. fmt.Printf("%v", e)
  169. }
  170. hash := mycontractCall(txn)
  171. return hash
  172. }
  173. /*
  174. 发起dex交易,通过uniswapV3 dex进行交易
  175. :param inputAddress: 输入的erc20 代币地址
  176. :param outAddress: 输出的erc20 代币地址
  177. :param inputAmount: 输入数量
  178. */
  179. func UniswapV3Swap(inputAddress, outAddress string, inputAmount int64) string {
  180. allowance := getErc20Allowance(inputAddress, myAddress, uniswapRouter3Address)
  181. if allowance.Cmp(big.NewInt(inputAmount)) == -1 {
  182. h := approve(inputAddress, myAddress, uniswapRouter3Address, uint64(0xfffffffffffffff))
  183. fmt.Printf("hash: %s", h)
  184. }
  185. c := mycontract(uniswapRouter3Address, getUniswapAbi())
  186. txn, e := c.Txn("exactInputSingle", map[string]interface{}{
  187. "tokenIn": web3tool.HexToAddress(inputAddress),
  188. "tokenOut": web3tool.HexToAddress(outAddress),
  189. "fee": 3000,
  190. "recipient": web3tool.HexToAddress(myAddress),
  191. "amountIn": inputAmount,
  192. "amountOutMinimum": 0,
  193. "sqrtPriceLimitX96": 0,
  194. }, web3tool.Latest)
  195. if e != nil {
  196. fmt.Printf("%v", e)
  197. }
  198. hash := mycontractCall(txn)
  199. return hash
  200. }
  201. func main() {
  202. var hash string
  203. //获取账户以太坊余额
  204. balance := getEthBalance(myAddress)
  205. fmt.Printf("balance: %s", balance.String())
  206. //获取账户usdt余额
  207. erc20balance := getErc20Balance(usdtAddress, myAddress)
  208. fmt.Printf("erc20 balance: %s", erc20balance.String())
  209. // 发送1个以太坊给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707
  210. hash = transferEth("0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707", 1)
  211. fmt.Printf("%s", hash)
  212. //# 发送1usdt 给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707
  213. hash = transferErc20(usdtAddress, "0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707", 1)
  214. fmt.Printf("%s", hash)
  215. //# 给 uniswapRouter3Address 授权 100usdt的消费额度
  216. hash = approve(usdtAddress, myAddress, uniswapRouter3Address, 0)
  217. fmt.Printf("%s", hash)
  218. //myAddress uniswapRouter3Address 授权量多少usdt消费额度
  219. erc20allowance := getErc20Allowance(usdtAddress, myAddress, uniswapRouter3Address)
  220. fmt.Printf("erc20 allowance: %s", erc20allowance.String())
  221. //花 100 usdt 买入 WBTC
  222. hash = UniswapV3Swap(usdtAddress, wbtcAddress, 100)
  223. fmt.Errorf("%s", hash)
  224. }

通过test.go的例子,就可以实现链上套利交易啦

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/607523
推荐阅读
相关标签
  

闽ICP备14008679号