github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/x/vmbridge/types/protocol.go (about)

     1  package types
     2  
     3  import (
     4  	"bytes"
     5  	_ "embed"
     6  	"encoding/json"
     7  	"fmt"
     8  	"github.com/ethereum/go-ethereum/accounts/abi"
     9  	"github.com/ethereum/go-ethereum/common"
    10  	"math/big"
    11  )
    12  
    13  const (
    14  	SendToWasmEventName  = "__OKCSendToWasm"
    15  	WasmCalledMethodName = "mintCW20"
    16  
    17  	SendToEvmSubMsgName = "send-to-evm"
    18  	EvmCalledMethodName = "mintERC20"
    19  )
    20  
    21  var (
    22  	// SendToWasmEventName represent the signature of
    23  	// `event __SendToWasmEventName(string wasmAddr,string recipient, string amount)`
    24  	SendToWasmEvent abi.Event
    25  
    26  	EvmABI abi.ABI
    27  	//go:embed abi.json
    28  	abiJson []byte
    29  )
    30  
    31  func init() {
    32  	EvmABI, SendToWasmEvent = GetEVMABIConfig(abiJson)
    33  }
    34  
    35  type MintCW20Method struct {
    36  	Amount    string `json:"amount"`
    37  	Recipient string `json:"recipient"`
    38  }
    39  
    40  func GetMintCW20Input(amount, recipient string) ([]byte, error) {
    41  	method := MintCW20Method{
    42  		Amount:    amount,
    43  		Recipient: recipient,
    44  	}
    45  	input := struct {
    46  		Method MintCW20Method `json:"mint_c_w20"`
    47  	}{
    48  		Method: method,
    49  	}
    50  	return json.Marshal(input)
    51  }
    52  
    53  type MintERC20Method struct {
    54  	ABI abi.ABI
    55  }
    56  
    57  func GetMintERC20Input(callerAddr string, recipient common.Address, amount *big.Int) ([]byte, error) {
    58  	data, err := EvmABI.Pack(EvmCalledMethodName, callerAddr, recipient, amount)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  	return data, nil
    63  }
    64  
    65  func GetMintERC20Output(data []byte) (bool, error) {
    66  	result, err := EvmABI.Unpack(EvmCalledMethodName, data)
    67  	if err != nil {
    68  		return false, err
    69  	}
    70  	if len(result) != 1 {
    71  		return false, fmt.Errorf("%s method outputs must be one output", EvmCalledMethodName)
    72  	}
    73  	return result[0].(bool), nil
    74  }
    75  
    76  func GetEVMABIConfig(data []byte) (abi.ABI, abi.Event) {
    77  	ret, err := abi.JSON(bytes.NewReader(data))
    78  	if err != nil {
    79  		panic(fmt.Errorf("json decode failed: %s", err.Error()))
    80  	}
    81  	event, ok := ret.Events[SendToWasmEventName]
    82  	if !ok {
    83  		panic(fmt.Errorf("abi must have event %s,%s,%s", SendToWasmEvent, ret, string(data)))
    84  	}
    85  	return ret, event
    86  }