|
| 1 | +package tx |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/hex" |
| 7 | + "fmt" |
| 8 | + "github.com/bcdevtools/devd/v2/cmd/utils" |
| 9 | + ethtypes "github.com/ethereum/go-ethereum/core/types" |
| 10 | + "github.com/spf13/cobra" |
| 11 | + "math/big" |
| 12 | +) |
| 13 | + |
| 14 | +func GetSendEvmTxCommand() *cobra.Command { |
| 15 | + cmd := &cobra.Command{ |
| 16 | + Use: "send [to] [amount]", |
| 17 | + Short: "Send some token to an address via EVM transfer", |
| 18 | + Args: cobra.ExactArgs(2), |
| 19 | + Run: func(cmd *cobra.Command, args []string) { |
| 20 | + ethClient8545, _ := mustGetEthClient(cmd) |
| 21 | + |
| 22 | + evmAddrs, err := utils.GetEvmAddressFromAnyFormatAddress(args[0]) |
| 23 | + utils.ExitOnErr(err, "failed to get evm address from input") |
| 24 | + |
| 25 | + receiverAddr := evmAddrs[0] |
| 26 | + amount, ok := new(big.Int).SetString(args[1], 10) |
| 27 | + if !ok { |
| 28 | + utils.ExitOnErr(fmt.Errorf("invalid amount %s", args[1]), "failed to parse amount") |
| 29 | + } |
| 30 | + display, _, _, err := utils.ConvertNumberIntoDisplayWithExponent(amount, 18) |
| 31 | + utils.ExitOnErr(err, "failed to convert amount into display with exponent") |
| 32 | + |
| 33 | + _, ecdsaPrivateKey, _, from := mustSecretEvmAccount(cmd) |
| 34 | + |
| 35 | + nonce, err := ethClient8545.NonceAt(context.Background(), *from, nil) |
| 36 | + utils.ExitOnErr(err, "failed to get nonce of sender") |
| 37 | + |
| 38 | + chainId, err := ethClient8545.ChainID(context.Background()) |
| 39 | + utils.ExitOnErr(err, "failed to get chain ID") |
| 40 | + |
| 41 | + txData := ethtypes.LegacyTx{ |
| 42 | + Nonce: nonce, |
| 43 | + GasPrice: big.NewInt(20_000_000_000), |
| 44 | + Gas: 21000, |
| 45 | + To: &receiverAddr, |
| 46 | + Value: amount, |
| 47 | + } |
| 48 | + tx := ethtypes.NewTx(&txData) |
| 49 | + |
| 50 | + fmt.Println("Send", display, "from", from.Hex(), "to", receiverAddr.Hex()) |
| 51 | + fmt.Println("EIP155 Chain ID:", chainId.String(), "and nonce", txData.Nonce) |
| 52 | + |
| 53 | + signedTx, err := ethtypes.SignTx(tx, ethtypes.LatestSignerForChainID(chainId), ecdsaPrivateKey) |
| 54 | + utils.ExitOnErr(err, "failed to sign tx") |
| 55 | + |
| 56 | + var buf bytes.Buffer |
| 57 | + err = signedTx.EncodeRLP(&buf) |
| 58 | + utils.ExitOnErr(err, "failed to encode tx") |
| 59 | + |
| 60 | + rawTxRLPHex := hex.EncodeToString(buf.Bytes()) |
| 61 | + fmt.Printf("RawTx: 0x%s\n", rawTxRLPHex) |
| 62 | + |
| 63 | + err = ethClient8545.SendTransaction(context.Background(), signedTx) |
| 64 | + utils.ExitOnErr(err, "failed to send tx") |
| 65 | + }, |
| 66 | + } |
| 67 | + |
| 68 | + cmd.Flags().String(flagRpc, "", flagEvmRpcDesc) |
| 69 | + cmd.Flags().String(flagSecretKey, "", flagSecretKeyDesc) |
| 70 | + |
| 71 | + return cmd |
| 72 | +} |
0 commit comments