github.com/0xsequence/ethkit@v1.25.0/ethartifact/ethartifact.go (about) 1 package ethartifact 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os" 7 "strings" 8 9 "github.com/0xsequence/ethkit/go-ethereum/accounts/abi" 10 "github.com/0xsequence/ethkit/go-ethereum/common" 11 ) 12 13 type Artifact struct { 14 ContractName string 15 ABI abi.ABI 16 Bin []byte 17 DeployedBin []byte 18 } 19 20 func (a Artifact) Encode(method string, args ...interface{}) ([]byte, error) { 21 return a.ABI.Pack(method, args...) 22 } 23 24 func (a Artifact) Decode(result interface{}, method string, data []byte) error { 25 return a.ABI.UnpackIntoInterface(result, method, data) 26 } 27 28 func ParseArtifactJSON(artifactJSON string) (Artifact, error) { 29 var rawArtifact RawArtifact 30 err := json.Unmarshal([]byte(artifactJSON), &rawArtifact) 31 if err != nil { 32 return Artifact{}, err 33 } 34 35 var artifact Artifact 36 37 artifact.ContractName = rawArtifact.ContractName 38 if rawArtifact.ContractName == "" { 39 return Artifact{}, fmt.Errorf("contract name is empty") 40 } 41 42 parsedABI, err := abi.JSON(strings.NewReader(string(rawArtifact.ABI))) 43 if err != nil { 44 return Artifact{}, fmt.Errorf("unable to parse abi json in artifact: %w", err) 45 } 46 artifact.ABI = parsedABI 47 48 if len(rawArtifact.Bytecode) > 2 { 49 artifact.Bin = common.FromHex(rawArtifact.Bytecode) 50 } 51 if len(rawArtifact.DeployedBytecode) > 2 { 52 artifact.DeployedBin = common.FromHex(rawArtifact.DeployedBytecode) 53 } 54 55 return artifact, nil 56 } 57 58 func MustParseArtifactJSON(artifactJSON string) Artifact { 59 artifact, err := ParseArtifactJSON(artifactJSON) 60 if err != nil { 61 panic(err) 62 } 63 return artifact 64 } 65 66 type RawArtifact struct { 67 ContractName string `json:"contractName"` 68 ABI json.RawMessage `json:"abi"` 69 Bytecode string `json:"bytecode"` 70 DeployedBytecode string `json:"deployedBytecode"` 71 } 72 73 func ParseArtifactFile(path string) (RawArtifact, error) { 74 filedata, err := os.ReadFile(path) 75 if err != nil { 76 return RawArtifact{}, err 77 } 78 79 var artifact RawArtifact 80 err = json.Unmarshal(filedata, &artifact) 81 if err != nil { 82 return RawArtifact{}, err 83 } 84 85 return artifact, nil 86 }