// Copyright 2023 The AthanorLabs/atomic-swap Authors
// SPDX-License-Identifier: LGPL-3.0-only

package contracts

import (
	"bytes"
	"context"
	"errors"
	"fmt"

	ethcommon "github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/ethclient"
)

// expectedSwapCreatorBytecodeHex is generated by deploying an instance of
// SwapCreator.sol and reading back the bytecode. See the unit test
// TestExpectedSwapCreatorBytecodeHex if you need to update this value.
const (
	expectedSwapCreatorBytecodeHex = "[encoded data, 10232 characters]" //nolint:lll
)

var (
	errInvalidSwapCreatorContract = errors.New("given contract address does not contain correct SwapCreator code")
)

// CheckSwapCreatorContractCode checks that the bytecode at the given address
// matches the SwapCreator.sol contract.
func CheckSwapCreatorContractCode(
	ctx context.Context,
	ec *ethclient.Client,
	contractAddr ethcommon.Address,
) error {
	code, err := ec.CodeAt(ctx, contractAddr, nil)
	if err != nil {
		return fmt.Errorf("failed to get code at %s: %w", contractAddr, err)
	}

	expectedCode := ethcommon.FromHex(expectedSwapCreatorBytecodeHex)

	if len(code) != len(expectedCode) {
		return fmt.Errorf("length mismatch: %w", errInvalidSwapCreatorContract)
	}

	if !bytes.Equal(expectedCode, code) {
		return errInvalidSwapCreatorContract
	}

	return nil
}
