github.com/ethersphere/bee/v2@v2.2.0/pkg/settlement/swap/erc20/mock/erc20.go (about)

     1  // Copyright 2021 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package mock
     6  
     7  import (
     8  	"context"
     9  	"errors"
    10  	"math/big"
    11  
    12  	"github.com/ethereum/go-ethereum/common"
    13  	"github.com/ethersphere/bee/v2/pkg/settlement/swap/erc20"
    14  )
    15  
    16  type Service struct {
    17  	balanceOfFunc func(ctx context.Context, address common.Address) (*big.Int, error)
    18  	transferFunc  func(ctx context.Context, address common.Address, value *big.Int) (common.Hash, error)
    19  }
    20  
    21  func WithBalanceOfFunc(f func(ctx context.Context, address common.Address) (*big.Int, error)) Option {
    22  	return optionFunc(func(s *Service) {
    23  		s.balanceOfFunc = f
    24  	})
    25  }
    26  
    27  func WithTransferFunc(f func(ctx context.Context, address common.Address, value *big.Int) (common.Hash, error)) Option {
    28  	return optionFunc(func(s *Service) {
    29  		s.transferFunc = f
    30  	})
    31  }
    32  
    33  func New(opts ...Option) erc20.Service {
    34  	mock := new(Service)
    35  	for _, o := range opts {
    36  		o.apply(mock)
    37  	}
    38  	return mock
    39  }
    40  
    41  func (s *Service) BalanceOf(ctx context.Context, address common.Address) (*big.Int, error) {
    42  	if s.balanceOfFunc != nil {
    43  		return s.balanceOfFunc(ctx, address)
    44  	}
    45  	return big.NewInt(0), errors.New("Error")
    46  }
    47  
    48  func (s *Service) Transfer(ctx context.Context, address common.Address, value *big.Int) (common.Hash, error) {
    49  	if s.transferFunc != nil {
    50  		return s.transferFunc(ctx, address, value)
    51  	}
    52  	return common.Hash{}, errors.New("Error")
    53  }
    54  
    55  // Option is the option passed to the mock Chequebook service
    56  type Option interface {
    57  	apply(*Service)
    58  }
    59  
    60  type optionFunc func(*Service)
    61  
    62  func (f optionFunc) apply(r *Service) { f(r) }