Skip to content

Commit

Permalink
add func to do eth transfers
Browse files Browse the repository at this point in the history
Signed-off-by: Guillem Bonet <[email protected]>
  • Loading branch information
Guillembonet committed Nov 24, 2023
1 parent 2bfcda5 commit 855aba8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
32 changes: 32 additions & 0 deletions test/common.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package test

import (
"context"
"crypto/ecdsa"
"fmt"
"math/big"
Expand Down Expand Up @@ -186,3 +187,34 @@ func DeployHermes(opts *bind.TransactOpts, backend bind.ContractBackend, timeout
HermesAddress: hermesAddress,
}, nil
}

func TransferEth(opts *bind.TransactOpts, backend bind.ContractBackend, chainID *big.Int, to common.Address, value *big.Int, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

nonce, err := backend.PendingNonceAt(ctx, opts.From)
if err != nil {
return fmt.Errorf("failed to get nonce: %w", err)
}
gasFeeCap, err := backend.SuggestGasPrice(ctx)
if err != nil {
return fmt.Errorf("failed to get gas price: %w", err)
}
tx := types.NewTx(&types.DynamicFeeTx{
Nonce: nonce,
ChainID: chainID,
To: &to,
Value: value,
Gas: 21000,
GasFeeCap: gasFeeCap,
})
signedTx, err := opts.Signer(opts.From, tx)
if err != nil {
return fmt.Errorf("failed to sign transaction: %w", err)
}
err = backend.SendTransaction(ctx, signedTx)
if err != nil {
return fmt.Errorf("failed to send transaction: %w", err)
}
return nil
}
24 changes: 24 additions & 0 deletions test/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ import (
"testing"
"time"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/magefile/mage/sh"
"github.com/mysteriumnetwork/payments/units"
"github.com/stretchr/testify/assert"
)

var client *ethclient.Client
Expand All @@ -30,6 +33,27 @@ func TestMain(m *testing.M) {
os.Exit(code)
}

func TestTransferEth(t *testing.T) {
address, privateKey, err := GetKeyPair(privateKey0)
assert.NoError(t, err)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
chainID, err := client.ChainID(ctx)
assert.NoError(t, err)

t.Run("transfer", func(t *testing.T) {
to := common.HexToAddress("0x123452222222")
value := units.FloatEthToBigIntWei(1)
err := TransferEth(GetTransactOpts(address, privateKey, chainID), client, chainID, to, value, 10*time.Second)
assert.NoError(t, err)

balance, err := client.BalanceAt(context.Background(), to, nil)
assert.NoError(t, err)
assert.Equal(t, balance.String(), value.String())
})
}

func startCompose() error {
_, err := sh.Output("docker-compose", "-f", "docker-compose.yml", "up", "-d")
if err != nil {
Expand Down

0 comments on commit 855aba8

Please sign in to comment.