github.com/0xsequence/ethkit@v1.25.0/ethtest/erc20.go (about)

     1  package ethtest
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"math/big"
     7  	"testing"
     8  
     9  	"github.com/0xsequence/ethkit"
    10  	"github.com/0xsequence/ethkit/ethcontract"
    11  	"github.com/0xsequence/ethkit/ethwallet"
    12  	"github.com/0xsequence/ethkit/go-ethereum/core/types"
    13  	"github.com/stretchr/testify/assert"
    14  	"github.com/stretchr/testify/require"
    15  )
    16  
    17  // ERC20 helper methods to deploy, mint and transfer between wallets
    18  // using the ERC20Mock contract.
    19  
    20  // TODO: perhaps remove use of testing.T and instead just return errors.
    21  
    22  type ERC20Mock struct {
    23  	Contract  *ethcontract.Contract
    24  	testchain *Testchain
    25  }
    26  
    27  func DeployERC20Mock(t *testing.T, testchain *Testchain) (*ERC20Mock, *types.Receipt) {
    28  	contract, receipt := testchain.Deploy(t, "ERC20Mock")
    29  	return &ERC20Mock{
    30  		Contract:  contract,
    31  		testchain: testchain,
    32  	}, receipt
    33  }
    34  
    35  func (c *ERC20Mock) Mint(t *testing.T, wallet *ethwallet.Wallet, amount int64) *types.Receipt {
    36  	// Call mockMint on erc20mock contract
    37  	calldata, err := c.Contract.Encode("mockMint", wallet.Address(), big.NewInt(amount))
    38  	assert.NoError(t, err)
    39  
    40  	txn, receipt := SendTransactionAndWaitForReceipt(t, wallet, c.Contract.Address, calldata, nil)
    41  	require.NotNil(t, txn)
    42  	require.NotNil(t, receipt)
    43  	return receipt
    44  }
    45  
    46  func (c *ERC20Mock) Transfer(t *testing.T, owner *ethwallet.Wallet, to ethkit.Address, amount int64) *types.Receipt {
    47  	calldata, err := c.Contract.Encode("transfer", to, big.NewInt(amount))
    48  	require.NoError(t, err)
    49  
    50  	txn, receipt := SendTransactionAndWaitForReceipt(t, owner, c.Contract.Address, calldata, nil)
    51  	require.NotNil(t, txn)
    52  	require.NotNil(t, receipt)
    53  	return receipt
    54  }
    55  
    56  func (c *ERC20Mock) GetBalance(t *testing.T, account ethkit.Address, expectedAmount int64) {
    57  	provider := c.testchain.Provider
    58  
    59  	ret, err := provider.ContractQuery(context.Background(), c.Contract.Address.Hex(), "balanceOf(address)", "uint256", []string{account.Hex()})
    60  	require.NoError(t, err)
    61  	require.Equal(t, 1, len(ret))
    62  	require.Equal(t, fmt.Sprintf("%d", expectedAmount), ret[0])
    63  }