From 7a2eb86dd5724a7fd8835824415529442faba854 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Fri, 10 Mar 2023 10:46:30 -0800 Subject: [PATCH] feat: cli: Add an EVM command to fetch a contract's bytecode --- cli/evm.go | 49 +++++++++++++++++++++++++++++++++++ documentation/en/cli-lotus.md | 14 ++++++++++ 2 files changed, 63 insertions(+) diff --git a/cli/evm.go b/cli/evm.go index d153e7212..84cbf8c61 100644 --- a/cli/evm.go +++ b/cli/evm.go @@ -35,6 +35,7 @@ var EvmCmd = &cli.Command{ EvmGetInfoCmd, EvmCallSimulateCmd, EvmGetContractAddress, + EvmGetBytecode, }, } @@ -486,3 +487,51 @@ func ethAddrFromFilecoinAddress(ctx context.Context, addr address.Address, fnapi return ethAddr, faddr, nil } + +var EvmGetBytecode = &cli.Command{ + Name: "bytecode", + Usage: "Write the bytecode of a smart contract to a file", + ArgsUsage: "[contract-address] [file-name]", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "bin", + Usage: "write the bytecode as raw binary and don't hex-encode", + }, + }, + Action: func(cctx *cli.Context) error { + + if cctx.NArg() != 2 { + return IncorrectNumArgs(cctx) + } + + contractAddr, err := ethtypes.ParseEthAddress(cctx.Args().Get(0)) + if err != nil { + return err + } + + fileName := cctx.Args().Get(1) + + api, closer, err := GetFullNodeAPIV1(cctx) + if err != nil { + return err + } + defer closer() + ctx := ReqContext(cctx) + + code, err := api.EthGetCode(ctx, contractAddr, "latest") + if err != nil { + return err + } + if !cctx.Bool("bin") { + newCode := make([]byte, hex.EncodedLen(len(code))) + hex.Encode(newCode, code) + code = newCode + } + if err := os.WriteFile(fileName, code, 0o666); err != nil { + return xerrors.Errorf("failed to write bytecode to file %s: %w", fileName, err) + } + + fmt.Printf("Code for %s written to %s\n", contractAddr, fileName) + return nil + }, +} diff --git a/documentation/en/cli-lotus.md b/documentation/en/cli-lotus.md index 4458599ab..325b2738d 100644 --- a/documentation/en/cli-lotus.md +++ b/documentation/en/cli-lotus.md @@ -2647,6 +2647,7 @@ COMMANDS: stat Print eth/filecoin addrs and code cid call Simulate an eth contract call contract-address Generate contract address from smart contract code + bytecode Write the bytecode of a smart contract to a file help, h Shows a list of commands or help for one command OPTIONS: @@ -2721,6 +2722,19 @@ OPTIONS: ``` +### lotus evm bytecode +``` +NAME: + lotus evm bytecode - Write the bytecode of a smart contract to a file + +USAGE: + lotus evm bytecode [command options] [contract-address] [file-name] + +OPTIONS: + --bin write the bytecode as raw binary and don't hex-encode (default: false) + +``` + ## lotus net ``` NAME: