From 5633382ab1747997786e971441cd0d700598aa8b Mon Sep 17 00:00:00 2001 From: Suryansh <39276431+0xsuryansh@users.noreply.github.com> Date: Fri, 29 Nov 2024 16:40:42 +0530 Subject: [PATCH] CCIP-4160 Token Transfer Tests (#15278) * CCIP-4160 test refactoring * resolving imports and using local dev env * comments fix * comments fix * test update with common methods * import fix for lint * refactor: updated test with new setup * fix: lint (imports) * Yolo * feat: self serve pool test + ability to add custom deployer for token and pools * fix : Use LocalDevEnvironment * temp: trying out with AdditionalSimulatedPvtKeys * fix: lints and unused function * fix: lints and unused function * fix: imports for lint * Move tt tests to a separate file * Move tt tests to a separate file * Fix * Fix * Fix * Fix * Fix * Fix * Fix * Fix --------- Co-authored-by: Mateusz Sekara --- .github/e2e-tests.yml | 15 +- deployment/ccip/changeset/test_helpers.go | 170 ++++++++++-- .../ccip/changeset/test_usdc_helpers.go | 8 +- .../smoke/ccip/ccip_fees_test.go | 2 + integration-tests/smoke/ccip/ccip_test.go | 137 +--------- .../smoke/ccip/ccip_token_transfer_test.go | 245 ++++++++++++++++++ .../smoke/ccip/ccip_usdc_test.go | 154 ++--------- 7 files changed, 437 insertions(+), 294 deletions(-) create mode 100644 integration-tests/smoke/ccip/ccip_token_transfer_test.go diff --git a/.github/e2e-tests.yml b/.github/e2e-tests.yml index 681e35b1c40..570ebcf4503 100644 --- a/.github/e2e-tests.yml +++ b/.github/e2e-tests.yml @@ -947,7 +947,7 @@ runner-test-matrix: test_env_vars: E2E_TEST_SELECTED_NETWORK: SIMULATED_1,SIMULATED_2 E2E_JD_VERSION: 0.6.0 - + - id: smoke/ccip/ccip_batching_test.go:* path: integration-tests/smoke/ccip/ccip_batching_test.go test_env_type: docker @@ -961,6 +961,19 @@ runner-test-matrix: E2E_TEST_SELECTED_NETWORK: SIMULATED_1,SIMULATED_2,SIMULATED_3 E2E_JD_VERSION: 0.6.0 + - id: smoke/ccip/ccip_token_transfer_test.go:* + path: integration-tests/smoke/ccip/ccip_token_transfer_test.go + test_env_type: docker + runs_on: ubuntu-latest + triggers: + - PR E2E Core Tests + - Nightly E2E Tests + test_cmd: cd integration-tests/ && go test smoke/ccip/ccip_token_transfer_test.go -timeout 16m -test.parallel=1 -count=1 -json + pyroscope_env: ci-smoke-ccipv1_6-evm-simulated + test_env_vars: + E2E_TEST_SELECTED_NETWORK: SIMULATED_1,SIMULATED_2 + E2E_JD_VERSION: 0.6.0 + - id: smoke/ccip/ccip_usdc_test.go:* path: integration-tests/smoke/ccip/ccip_usdc_test.go test_env_type: docker diff --git a/deployment/ccip/changeset/test_helpers.go b/deployment/ccip/changeset/test_helpers.go index 50c64a5d778..b205463454e 100644 --- a/deployment/ccip/changeset/test_helpers.go +++ b/deployment/ccip/changeset/test_helpers.go @@ -40,6 +40,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" commonutils "github.com/smartcontractkit/chainlink-common/pkg/utils" + "github.com/smartcontractkit/chainlink-common/pkg/utils/tests" "github.com/smartcontractkit/chainlink/deployment" "github.com/smartcontractkit/chainlink/deployment/environment/devenv" @@ -743,53 +744,54 @@ func DeployTransferableToken( lggr logger.Logger, chains map[uint64]deployment.Chain, src, dst uint64, + srcActor, dstActor *bind.TransactOpts, state CCIPOnChainState, addresses deployment.AddressBook, token string, ) (*burn_mint_erc677.BurnMintERC677, *burn_mint_token_pool.BurnMintTokenPool, *burn_mint_erc677.BurnMintERC677, *burn_mint_token_pool.BurnMintTokenPool, error) { // Deploy token and pools - srcToken, srcPool, err := deployTransferTokenOneEnd(lggr, chains[src], addresses, token) + srcToken, srcPool, err := deployTransferTokenOneEnd(lggr, chains[src], srcActor, addresses, token) if err != nil { return nil, nil, nil, nil, err } - dstToken, dstPool, err := deployTransferTokenOneEnd(lggr, chains[dst], addresses, token) + dstToken, dstPool, err := deployTransferTokenOneEnd(lggr, chains[dst], dstActor, addresses, token) if err != nil { return nil, nil, nil, nil, err } // Attach token pools to registry - if err := attachTokenToTheRegistry(chains[src], state.Chains[src], chains[src].DeployerKey, srcToken.Address(), srcPool.Address()); err != nil { + if err := attachTokenToTheRegistry(chains[src], state.Chains[src], srcActor, srcToken.Address(), srcPool.Address()); err != nil { return nil, nil, nil, nil, err } - if err := attachTokenToTheRegistry(chains[dst], state.Chains[dst], chains[dst].DeployerKey, dstToken.Address(), dstPool.Address()); err != nil { + if err := attachTokenToTheRegistry(chains[dst], state.Chains[dst], dstActor, dstToken.Address(), dstPool.Address()); err != nil { return nil, nil, nil, nil, err } // Connect pool to each other - if err := setTokenPoolCounterPart(chains[src], srcPool, dst, dstToken.Address(), dstPool.Address()); err != nil { + if err := setTokenPoolCounterPart(chains[src], srcPool, srcActor, dst, dstToken.Address(), dstPool.Address()); err != nil { return nil, nil, nil, nil, err } - if err := setTokenPoolCounterPart(chains[dst], dstPool, src, srcToken.Address(), srcPool.Address()); err != nil { + if err := setTokenPoolCounterPart(chains[dst], dstPool, dstActor, src, srcToken.Address(), srcPool.Address()); err != nil { return nil, nil, nil, nil, err } // Add burn/mint permissions - if err := grantMintBurnPermissions(lggr, chains[src], srcToken, srcPool.Address()); err != nil { + if err := grantMintBurnPermissions(lggr, chains[src], srcToken, srcActor, srcPool.Address()); err != nil { return nil, nil, nil, nil, err } - if err := grantMintBurnPermissions(lggr, chains[dst], dstToken, dstPool.Address()); err != nil { + if err := grantMintBurnPermissions(lggr, chains[dst], dstToken, dstActor, dstPool.Address()); err != nil { return nil, nil, nil, nil, err } return srcToken, srcPool, dstToken, dstPool, nil } -func grantMintBurnPermissions(lggr logger.Logger, chain deployment.Chain, token *burn_mint_erc677.BurnMintERC677, address common.Address) error { +func grantMintBurnPermissions(lggr logger.Logger, chain deployment.Chain, token *burn_mint_erc677.BurnMintERC677, actor *bind.TransactOpts, address common.Address) error { lggr.Infow("Granting burn permissions", "token", token.Address(), "burner", address) - tx, err := token.GrantBurnRole(chain.DeployerKey, address) + tx, err := token.GrantBurnRole(actor, address) if err != nil { return err } @@ -799,7 +801,7 @@ func grantMintBurnPermissions(lggr logger.Logger, chain deployment.Chain, token } lggr.Infow("Granting mint permissions", "token", token.Address(), "minter", address) - tx, err = token.GrantMintRole(chain.DeployerKey, address) + tx, err = token.GrantMintRole(actor, address) if err != nil { return err } @@ -811,6 +813,7 @@ func setUSDCTokenPoolCounterPart( chain deployment.Chain, tokenPool *usdc_token_pool.USDCTokenPool, destChainSelector uint64, + actor *bind.TransactOpts, destTokenAddress common.Address, destTokenPoolAddress common.Address, ) error { @@ -843,18 +846,12 @@ func setUSDCTokenPoolCounterPart( return err } - return setTokenPoolCounterPart(chain, pool, destChainSelector, destTokenAddress, destTokenPoolAddress) + return setTokenPoolCounterPart(chain, pool, actor, destChainSelector, destTokenAddress, destTokenPoolAddress) } -func setTokenPoolCounterPart( - chain deployment.Chain, - tokenPool *burn_mint_token_pool.BurnMintTokenPool, - destChainSelector uint64, - destTokenAddress common.Address, - destTokenPoolAddress common.Address, -) error { +func setTokenPoolCounterPart(chain deployment.Chain, tokenPool *burn_mint_token_pool.BurnMintTokenPool, actor *bind.TransactOpts, destChainSelector uint64, destTokenAddress common.Address, destTokenPoolAddress common.Address) error { tx, err := tokenPool.ApplyChainUpdates( - chain.DeployerKey, + actor, []uint64{}, []burn_mint_token_pool.TokenPoolChainUpdate{ { @@ -884,7 +881,7 @@ func setTokenPoolCounterPart( } tx, err = tokenPool.AddRemotePool( - chain.DeployerKey, + actor, destChainSelector, destTokenPoolAddress.Bytes(), ) @@ -944,6 +941,7 @@ func attachTokenToTheRegistry( func deployTransferTokenOneEnd( lggr logger.Logger, chain deployment.Chain, + deployer *bind.TransactOpts, addressBook deployment.AddressBook, tokenSymbol string, ) (*burn_mint_erc677.BurnMintERC677, *burn_mint_token_pool.BurnMintTokenPool, error) { @@ -969,7 +967,7 @@ func deployTransferTokenOneEnd( tokenContract, err := deployment.DeployContract(lggr, chain, addressBook, func(chain deployment.Chain) deployment.ContractDeploy[*burn_mint_erc677.BurnMintERC677] { tokenAddress, tx, token, err2 := burn_mint_erc677.DeployBurnMintERC677( - chain.DeployerKey, + deployer, chain.Client, tokenSymbol, tokenSymbol, @@ -985,7 +983,7 @@ func deployTransferTokenOneEnd( return nil, nil, err } - tx, err := tokenContract.Contract.GrantMintRole(chain.DeployerKey, chain.DeployerKey.From) + tx, err := tokenContract.Contract.GrantMintRole(deployer, deployer.From) if err != nil { return nil, nil, err } @@ -997,7 +995,7 @@ func deployTransferTokenOneEnd( tokenPool, err := deployment.DeployContract(lggr, chain, addressBook, func(chain deployment.Chain) deployment.ContractDeploy[*burn_mint_token_pool.BurnMintTokenPool] { tokenPoolAddress, tx, tokenPoolContract, err2 := burn_mint_token_pool.DeployBurnMintTokenPool( - chain.DeployerKey, + deployer, chain.Client, tokenContract.Address, tokenDecimals, @@ -1016,3 +1014,127 @@ func deployTransferTokenOneEnd( return tokenContract.Contract, tokenPool.Contract, nil } + +// MintAndAllow mints tokens for deployers and allow router to spend them +func MintAndAllow( + t *testing.T, + e deployment.Environment, + state CCIPOnChainState, + owners map[uint64]*bind.TransactOpts, + tkMap map[uint64][]*burn_mint_erc677.BurnMintERC677, +) { + tenCoins := new(big.Int).Mul(big.NewInt(1e18), big.NewInt(10)) + + for chain, tokens := range tkMap { + owner, ok := owners[chain] + require.True(t, ok) + + for _, token := range tokens { + tx, err := token.Mint( + owner, + e.Chains[chain].DeployerKey.From, + new(big.Int).Mul(tenCoins, big.NewInt(10)), + ) + require.NoError(t, err) + _, err = e.Chains[chain].Confirm(tx) + require.NoError(t, err) + + tx, err = token.Approve(e.Chains[chain].DeployerKey, state.Chains[chain].Router.Address(), tenCoins) + require.NoError(t, err) + _, err = e.Chains[chain].Confirm(tx) + require.NoError(t, err) + } + } +} + +// TransferAndWaitForSuccess sends a message from sourceChain to destChain and waits for it to be executed +func TransferAndWaitForSuccess( + ctx context.Context, + t *testing.T, + env deployment.Environment, + state CCIPOnChainState, + sourceChain, destChain uint64, + tokens []router.ClientEVMTokenAmount, + receiver common.Address, + data []byte, + expectedStatus int, +) { + identifier := SourceDestPair{ + SourceChainSelector: sourceChain, + DestChainSelector: destChain, + } + + startBlocks := make(map[uint64]*uint64) + expectedSeqNum := make(map[SourceDestPair]uint64) + expectedSeqNumExec := make(map[SourceDestPair][]uint64) + + latesthdr, err := env.Chains[destChain].Client.HeaderByNumber(ctx, nil) + require.NoError(t, err) + block := latesthdr.Number.Uint64() + startBlocks[destChain] = &block + + msgSentEvent := TestSendRequest(t, env, state, sourceChain, destChain, false, router.ClientEVM2AnyMessage{ + Receiver: common.LeftPadBytes(receiver.Bytes(), 32), + Data: data, + TokenAmounts: tokens, + FeeToken: common.HexToAddress("0x0"), + ExtraArgs: nil, + }) + expectedSeqNum[identifier] = msgSentEvent.SequenceNumber + expectedSeqNumExec[identifier] = []uint64{msgSentEvent.SequenceNumber} + + // Wait for all commit reports to land. + ConfirmCommitForAllWithExpectedSeqNums(t, env, state, expectedSeqNum, startBlocks) + + // Wait for all exec reports to land + states := ConfirmExecWithSeqNrsForAll(t, env, state, expectedSeqNumExec, startBlocks) + require.Equal(t, expectedStatus, states[identifier][msgSentEvent.SequenceNumber]) +} + +func WaitForTheTokenBalance( + ctx context.Context, + t *testing.T, + token common.Address, + receiver common.Address, + chain deployment.Chain, + expected *big.Int, +) { + tokenContract, err := burn_mint_erc677.NewBurnMintERC677(token, chain.Client) + require.NoError(t, err) + + require.Eventually(t, func() bool { + actualBalance, err := tokenContract.BalanceOf(&bind.CallOpts{Context: ctx}, receiver) + require.NoError(t, err) + + t.Log("Waiting for the token balance", + "expected", expected, + "actual", actualBalance, + "token", token, + "receiver", receiver, + ) + + return actualBalance.Cmp(expected) == 0 + }, tests.WaitTimeout(t), 100*time.Millisecond) +} + +func GetTokenBalance( + ctx context.Context, + t *testing.T, + token common.Address, + receiver common.Address, + chain deployment.Chain, +) *big.Int { + tokenContract, err := burn_mint_erc677.NewBurnMintERC677(token, chain.Client) + require.NoError(t, err) + + balance, err := tokenContract.BalanceOf(&bind.CallOpts{Context: ctx}, receiver) + require.NoError(t, err) + + t.Log("Getting token balance", + "actual", balance, + "token", token, + "receiver", receiver, + ) + + return balance +} diff --git a/deployment/ccip/changeset/test_usdc_helpers.go b/deployment/ccip/changeset/test_usdc_helpers.go index 4f96070e63c..b3f2579fd8f 100644 --- a/deployment/ccip/changeset/test_usdc_helpers.go +++ b/deployment/ccip/changeset/test_usdc_helpers.go @@ -39,12 +39,12 @@ func ConfigureUSDCTokenPools( } // Connect pool to each other - if err := setUSDCTokenPoolCounterPart(chains[src], srcPool, dst, dstToken.Address(), dstPool.Address()); err != nil { + if err := setUSDCTokenPoolCounterPart(chains[src], srcPool, dst, chains[src].DeployerKey, dstToken.Address(), dstPool.Address()); err != nil { lggr.Errorw("Failed to set counter part", "err", err, "srcPool", srcPool.Address(), "dstPool", dstPool.Address()) return nil, nil, err } - if err := setUSDCTokenPoolCounterPart(chains[dst], dstPool, src, srcToken.Address(), srcPool.Address()); err != nil { + if err := setUSDCTokenPoolCounterPart(chains[dst], dstPool, src, chains[dst].DeployerKey, srcToken.Address(), srcPool.Address()); err != nil { lggr.Errorw("Failed to set counter part", "err", err, "srcPool", dstPool.Address(), "dstPool", srcPool.Address()) return nil, nil, err } @@ -55,7 +55,7 @@ func ConfigureUSDCTokenPools( state.Chains[src].MockUSDCTokenMessenger.Address(), state.Chains[src].MockUSDCTransmitter.Address(), } { - if err := grantMintBurnPermissions(lggr, chains[src], srcToken, addr); err != nil { + if err := grantMintBurnPermissions(lggr, chains[src], srcToken, chains[src].DeployerKey, addr); err != nil { lggr.Errorw("Failed to grant mint/burn permissions", "err", err, "token", srcToken.Address(), "minter", addr) return nil, nil, err } @@ -67,7 +67,7 @@ func ConfigureUSDCTokenPools( state.Chains[dst].MockUSDCTokenMessenger.Address(), state.Chains[dst].MockUSDCTransmitter.Address(), } { - if err := grantMintBurnPermissions(lggr, chains[dst], dstToken, addr); err != nil { + if err := grantMintBurnPermissions(lggr, chains[dst], dstToken, chains[dst].DeployerKey, addr); err != nil { lggr.Errorw("Failed to grant mint/burn permissions", "err", err, "token", dstToken.Address(), "minter", addr) return nil, nil, err } diff --git a/integration-tests/smoke/ccip/ccip_fees_test.go b/integration-tests/smoke/ccip/ccip_fees_test.go index 89b8b973036..adf73edad7a 100644 --- a/integration-tests/smoke/ccip/ccip_fees_test.go +++ b/integration-tests/smoke/ccip/ccip_fees_test.go @@ -42,6 +42,8 @@ func setupTokens( tenv.Env.Chains, src, dest, + tenv.Env.Chains[src].DeployerKey, + tenv.Env.Chains[dest].DeployerKey, state, tenv.Env.ExistingAddresses, "MY_TOKEN", diff --git a/integration-tests/smoke/ccip/ccip_test.go b/integration-tests/smoke/ccip/ccip_test.go index d2adbaaa484..fb6fb2cf960 100644 --- a/integration-tests/smoke/ccip/ccip_test.go +++ b/integration-tests/smoke/ccip/ccip_test.go @@ -1,17 +1,14 @@ package smoke import ( - "math/big" "testing" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-testing-framework/lib/utils/testcontext" - "github.com/smartcontractkit/chainlink/deployment/ccip/changeset" testsetups "github.com/smartcontractkit/chainlink/integration-tests/testsetups/ccip" - "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/ccip/generated/onramp" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/ccip/generated/router" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -19,7 +16,8 @@ import ( func TestInitialDeployOnLocal(t *testing.T) { t.Parallel() lggr := logger.TestLogger(t) - tenv, _, _ := testsetups.NewLocalDevEnvironmentWithDefaultPrice(t, lggr, nil) + config := &changeset.TestConfigs{} + tenv, _, _ := testsetups.NewLocalDevEnvironmentWithDefaultPrice(t, lggr, config) e := tenv.Env state, err := changeset.LoadOnchainState(e) require.NoError(t, err) @@ -75,134 +73,3 @@ func TestInitialDeployOnLocal(t *testing.T) { // TODO: Apply the proposal. } - -func TestTokenTransfer(t *testing.T) { - t.Parallel() - lggr := logger.TestLogger(t) - tenv, _, _ := testsetups.NewLocalDevEnvironmentWithDefaultPrice(t, lggr, nil) - e := tenv.Env - state, err := changeset.LoadOnchainState(e) - require.NoError(t, err) - - srcToken, _, dstToken, _, err := changeset.DeployTransferableToken( - lggr, - tenv.Env.Chains, - tenv.HomeChainSel, - tenv.FeedChainSel, - state, - e.ExistingAddresses, - "MY_TOKEN", - ) - require.NoError(t, err) - - // Add all lanes - require.NoError(t, changeset.AddLanesForAll(e, state)) - // Need to keep track of the block number for each chain so that event subscription can be done from that block. - startBlocks := make(map[uint64]*uint64) - // Send a message from each chain to every other chain. - expectedSeqNum := make(map[changeset.SourceDestPair]uint64) - expectedSeqNumExec := make(map[changeset.SourceDestPair][]uint64) - - twoCoins := new(big.Int).Mul(big.NewInt(1e18), big.NewInt(2)) - tx, err := srcToken.Mint( - e.Chains[tenv.HomeChainSel].DeployerKey, - e.Chains[tenv.HomeChainSel].DeployerKey.From, - new(big.Int).Mul(twoCoins, big.NewInt(10)), - ) - require.NoError(t, err) - _, err = e.Chains[tenv.HomeChainSel].Confirm(tx) - require.NoError(t, err) - - tx, err = dstToken.Mint( - e.Chains[tenv.FeedChainSel].DeployerKey, - e.Chains[tenv.FeedChainSel].DeployerKey.From, - new(big.Int).Mul(twoCoins, big.NewInt(10)), - ) - require.NoError(t, err) - _, err = e.Chains[tenv.FeedChainSel].Confirm(tx) - require.NoError(t, err) - - tx, err = srcToken.Approve(e.Chains[tenv.HomeChainSel].DeployerKey, state.Chains[tenv.HomeChainSel].Router.Address(), twoCoins) - require.NoError(t, err) - _, err = e.Chains[tenv.HomeChainSel].Confirm(tx) - require.NoError(t, err) - tx, err = dstToken.Approve(e.Chains[tenv.FeedChainSel].DeployerKey, state.Chains[tenv.FeedChainSel].Router.Address(), twoCoins) - require.NoError(t, err) - _, err = e.Chains[tenv.FeedChainSel].Confirm(tx) - require.NoError(t, err) - - tokens := map[uint64][]router.ClientEVMTokenAmount{ - tenv.HomeChainSel: {{ - Token: srcToken.Address(), - Amount: twoCoins, - }}, - tenv.FeedChainSel: {{ - Token: dstToken.Address(), - Amount: twoCoins, - }}, - } - - for src := range e.Chains { - for dest, destChain := range e.Chains { - if src == dest { - continue - } - latesthdr, err := destChain.Client.HeaderByNumber(testcontext.Get(t), nil) - require.NoError(t, err) - block := latesthdr.Number.Uint64() - startBlocks[dest] = &block - - var ( - receiver = common.LeftPadBytes(state.Chains[dest].Receiver.Address().Bytes(), 32) - data = []byte("hello world") - feeToken = common.HexToAddress("0x0") - msgSentEvent *onramp.OnRampCCIPMessageSent - ) - if src == tenv.HomeChainSel && dest == tenv.FeedChainSel { - msgSentEvent = changeset.TestSendRequest(t, e, state, src, dest, false, router.ClientEVM2AnyMessage{ - Receiver: receiver, - Data: data, - TokenAmounts: tokens[src], - FeeToken: feeToken, - ExtraArgs: nil, - }) - } else { - msgSentEvent = changeset.TestSendRequest(t, e, state, src, dest, false, router.ClientEVM2AnyMessage{ - Receiver: receiver, - Data: data, - TokenAmounts: nil, - FeeToken: feeToken, - ExtraArgs: nil, - }) - } - - expectedSeqNum[changeset.SourceDestPair{ - SourceChainSelector: src, - DestChainSelector: dest, - }] = msgSentEvent.SequenceNumber - expectedSeqNumExec[changeset.SourceDestPair{ - SourceChainSelector: src, - DestChainSelector: dest, - }] = []uint64{msgSentEvent.SequenceNumber} - } - } - - // Wait for all commit reports to land. - changeset.ConfirmCommitForAllWithExpectedSeqNums(t, e, state, expectedSeqNum, startBlocks) - - // After commit is reported on all chains, token prices should be updated in FeeQuoter. - for dest := range e.Chains { - linkAddress := state.Chains[dest].LinkToken.Address() - feeQuoter := state.Chains[dest].FeeQuoter - timestampedPrice, err := feeQuoter.GetTokenPrice(nil, linkAddress) - require.NoError(t, err) - require.Equal(t, changeset.MockLinkPrice, timestampedPrice.Value) - } - - // Wait for all exec reports to land - changeset.ConfirmExecWithSeqNrsForAll(t, e, state, expectedSeqNumExec, startBlocks) - - balance, err := dstToken.BalanceOf(nil, state.Chains[tenv.FeedChainSel].Receiver.Address()) - require.NoError(t, err) - require.Equal(t, twoCoins, balance) -} diff --git a/integration-tests/smoke/ccip/ccip_token_transfer_test.go b/integration-tests/smoke/ccip/ccip_token_transfer_test.go new file mode 100644 index 00000000000..870648508e0 --- /dev/null +++ b/integration-tests/smoke/ccip/ccip_token_transfer_test.go @@ -0,0 +1,245 @@ +package smoke + +import ( + "context" + "math/big" + "testing" + + "golang.org/x/exp/maps" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/require" + + sel "github.com/smartcontractkit/chain-selectors" + + "github.com/smartcontractkit/chainlink-common/pkg/utils/tests" + "github.com/smartcontractkit/chainlink/deployment" + "github.com/smartcontractkit/chainlink/deployment/ccip/changeset" + testsetups "github.com/smartcontractkit/chainlink/integration-tests/testsetups/ccip" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" + "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/ccip/generated/router" + "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/shared/generated/burn_mint_erc677" + "github.com/smartcontractkit/chainlink/v2/core/logger" +) + +func TestTokenTransfer(t *testing.T) { + lggr := logger.TestLogger(t) + ctx := tests.Context(t) + config := &changeset.TestConfigs{} + tenv, _, _ := testsetups.NewLocalDevEnvironmentWithDefaultPrice(t, lggr, config) + inMemoryEnv := false + + // use this if you are testing locally in memory + // tenv := changeset.NewMemoryEnvironmentWithJobsAndContracts(t, lggr, 2, 4, config) + // inMemoryEnv := true + + e := tenv.Env + state, err := changeset.LoadOnchainState(e) + require.NoError(t, err) + + allChainSelectors := maps.Keys(e.Chains) + sourceChain, destChain := allChainSelectors[0], allChainSelectors[1] + ownerSourceChain := e.Chains[sourceChain].DeployerKey + ownerDestChain := e.Chains[destChain].DeployerKey + + oneE18 := new(big.Int).SetUint64(1e18) + funds := new(big.Int).Mul(oneE18, new(big.Int).SetUint64(10)) + + // Deploy and fund self-serve actors + selfServeSrcTokenPoolDeployer := createAndFundSelfServeActor(ctx, t, ownerSourceChain, e.Chains[sourceChain], funds, inMemoryEnv) + selfServeDestTokenPoolDeployer := createAndFundSelfServeActor(ctx, t, ownerDestChain, e.Chains[destChain], funds, inMemoryEnv) + + // Deploy tokens and pool by CCIP Owner + srcToken, _, destToken, _, err := changeset.DeployTransferableToken( + lggr, + tenv.Env.Chains, + sourceChain, + destChain, + ownerSourceChain, + ownerDestChain, + state, + e.ExistingAddresses, + "OWNER_TOKEN", + ) + require.NoError(t, err) + + // Deploy Self Serve tokens and pool + selfServeSrcToken, _, selfServeDestToken, _, err := changeset.DeployTransferableToken( + lggr, + tenv.Env.Chains, + sourceChain, + destChain, + selfServeSrcTokenPoolDeployer, + selfServeDestTokenPoolDeployer, + state, + e.ExistingAddresses, + "SELF_SERVE_TOKEN", + ) + require.NoError(t, err) + require.NoError(t, changeset.AddLanesForAll(e, state)) + + changeset.MintAndAllow(t, e, state, map[uint64]*bind.TransactOpts{ + sourceChain: ownerSourceChain, + destChain: ownerDestChain, + }, map[uint64][]*burn_mint_erc677.BurnMintERC677{ + sourceChain: {srcToken}, + destChain: {destToken}, + }) + changeset.MintAndAllow(t, e, state, map[uint64]*bind.TransactOpts{ + sourceChain: selfServeSrcTokenPoolDeployer, + destChain: selfServeDestTokenPoolDeployer, + }, map[uint64][]*burn_mint_erc677.BurnMintERC677{ + sourceChain: {selfServeSrcToken}, + destChain: {selfServeDestToken}, + }) + + tcs := []struct { + name string + srcChain uint64 + dstChain uint64 + tokenAmounts []router.ClientEVMTokenAmount + receiver common.Address + data []byte + expectedTokenBalances map[common.Address]*big.Int + expectedExecutionState int + }{ + { + name: "Send token to EOA", + srcChain: sourceChain, + dstChain: destChain, + tokenAmounts: []router.ClientEVMTokenAmount{ + { + Token: srcToken.Address(), + Amount: oneE18, + }, + }, + receiver: utils.RandomAddress(), + expectedTokenBalances: map[common.Address]*big.Int{ + destToken.Address(): oneE18, + }, + expectedExecutionState: changeset.EXECUTION_STATE_SUCCESS, + }, + { + name: "Send token to contract", + srcChain: sourceChain, + dstChain: destChain, + tokenAmounts: []router.ClientEVMTokenAmount{ + { + Token: srcToken.Address(), + Amount: oneE18, + }, + }, + receiver: state.Chains[destChain].Receiver.Address(), + expectedTokenBalances: map[common.Address]*big.Int{ + destToken.Address(): oneE18, + }, + expectedExecutionState: changeset.EXECUTION_STATE_SUCCESS, + }, + { + name: "Send N tokens to contract", + srcChain: destChain, + dstChain: sourceChain, + tokenAmounts: []router.ClientEVMTokenAmount{ + { + Token: selfServeDestToken.Address(), + Amount: oneE18, + }, + { + Token: destToken.Address(), + Amount: oneE18, + }, + { + Token: selfServeDestToken.Address(), + Amount: oneE18, + }, + }, + receiver: state.Chains[sourceChain].Receiver.Address(), + expectedTokenBalances: map[common.Address]*big.Int{ + selfServeSrcToken.Address(): new(big.Int).Add(oneE18, oneE18), + srcToken.Address(): oneE18, + }, + expectedExecutionState: changeset.EXECUTION_STATE_SUCCESS, + }, + } + + for _, tt := range tcs { + t.Run(tt.name, func(t *testing.T) { + initialBalances := map[common.Address]*big.Int{} + for token := range tt.expectedTokenBalances { + initialBalance := changeset.GetTokenBalance(ctx, t, token, tt.receiver, e.Chains[tt.dstChain]) + initialBalances[token] = initialBalance + } + + changeset.TransferAndWaitForSuccess( + ctx, + t, + e, + state, + tt.srcChain, + tt.dstChain, + tt.tokenAmounts, + tt.receiver, + tt.data, + tt.expectedExecutionState, + ) + + for token, balance := range tt.expectedTokenBalances { + expected := new(big.Int).Add(initialBalances[token], balance) + changeset.WaitForTheTokenBalance(ctx, t, token, tt.receiver, e.Chains[tt.dstChain], expected) + } + }) + } +} + +func createAndFundSelfServeActor( + ctx context.Context, + t *testing.T, + deployer *bind.TransactOpts, + chain deployment.Chain, + amountToFund *big.Int, + isInMemory bool, +) *bind.TransactOpts { + key, err := crypto.GenerateKey() + require.NoError(t, err) + + // Simulated backend sets chainID to 1337 always + chainID := big.NewInt(1337) + if !isInMemory { + // Docker environment runs real geth so chainID has to be set accordingly + stringChainID, err1 := sel.GetChainIDFromSelector(chain.Selector) + require.NoError(t, err1) + chainID, _ = new(big.Int).SetString(stringChainID, 10) + } + + actor, err := bind.NewKeyedTransactorWithChainID(key, chainID) + require.NoError(t, err) + + nonce, err := chain.Client.PendingNonceAt(ctx, deployer.From) + require.NoError(t, err) + + gasPrice, err := chain.Client.SuggestGasPrice(ctx) + require.NoError(t, err) + + tx := types.NewTx(&types.LegacyTx{ + Nonce: nonce, + To: &actor.From, + Value: amountToFund, + Gas: uint64(21000), + GasPrice: gasPrice, + Data: nil, + }) + + signedTx, err := deployer.Signer(deployer.From, tx) + require.NoError(t, err) + + err = chain.Client.SendTransaction(ctx, signedTx) + require.NoError(t, err) + + _, err = chain.Confirm(signedTx) + require.NoError(t, err) + + return actor +} diff --git a/integration-tests/smoke/ccip/ccip_usdc_test.go b/integration-tests/smoke/ccip/ccip_usdc_test.go index c50c2617094..ab758b48326 100644 --- a/integration-tests/smoke/ccip/ccip_usdc_test.go +++ b/integration-tests/smoke/ccip/ccip_usdc_test.go @@ -3,18 +3,14 @@ package smoke import ( "math/big" "testing" - "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" - "golang.org/x/exp/maps" "github.com/smartcontractkit/chainlink-common/pkg/utils/tests" "github.com/smartcontractkit/chainlink-testing-framework/lib/utils/testcontext" - - "github.com/smartcontractkit/chainlink/deployment" "github.com/smartcontractkit/chainlink/deployment/ccip/changeset" testsetups "github.com/smartcontractkit/chainlink/integration-tests/testsetups/ccip" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" @@ -34,6 +30,7 @@ import ( */ func TestUSDCTokenTransfer(t *testing.T) { lggr := logger.TestLogger(t) + ctx := tests.Context(t) config := &changeset.TestConfigs{ IsUSDC: true, } @@ -49,6 +46,10 @@ func TestUSDCTokenTransfer(t *testing.T) { chainC := allChainSelectors[1] chainB := allChainSelectors[2] + ownerChainA := e.Chains[chainA].DeployerKey + ownerChainC := e.Chains[chainC].DeployerKey + ownerChainB := e.Chains[chainB].DeployerKey + aChainUSDC, cChainUSDC, err := changeset.ConfigureUSDCTokenPools(lggr, e.Chains, chainA, chainC, state) require.NoError(t, err) @@ -60,6 +61,8 @@ func TestUSDCTokenTransfer(t *testing.T) { tenv.Env.Chains, chainA, chainC, + ownerChainA, + ownerChainC, state, e.ExistingAddresses, "MY_TOKEN", @@ -69,11 +72,18 @@ func TestUSDCTokenTransfer(t *testing.T) { // Add all lanes require.NoError(t, changeset.AddLanesForAll(e, state)) - mintAndAllow(t, e, state, map[uint64][]*burn_mint_erc677.BurnMintERC677{ - chainA: {aChainUSDC, aChainToken}, - chainB: {bChainUSDC}, - chainC: {cChainUSDC, cChainToken}, - }) + changeset.MintAndAllow( + t, + e, + state, + map[uint64]*bind.TransactOpts{ + chainA: ownerChainA, + chainB: ownerChainB, + chainC: ownerChainC}, map[uint64][]*burn_mint_erc677.BurnMintERC677{ + chainA: {aChainUSDC, aChainToken}, + chainB: {bChainUSDC}, + chainC: {cChainUSDC, cChainToken}, + }) err = changeset.UpdateFeeQuoterForUSDC(lggr, e.Chains[chainA], state.Chains[chainA], chainC, aChainUSDC) require.NoError(t, err) @@ -177,11 +187,12 @@ func TestUSDCTokenTransfer(t *testing.T) { t.Run(tt.name, func(t *testing.T) { initialBalances := map[common.Address]*big.Int{} for token := range tt.expectedTokenBalances { - initialBalance := getTokenBalance(t, token, tt.receiver, e.Chains[tt.destChain]) + initialBalance := changeset.GetTokenBalance(ctx, t, token, tt.receiver, e.Chains[tt.destChain]) initialBalances[token] = initialBalance } - transferAndWaitForSuccess( + changeset.TransferAndWaitForSuccess( + ctx, t, e, state, @@ -195,7 +206,7 @@ func TestUSDCTokenTransfer(t *testing.T) { for token, balance := range tt.expectedTokenBalances { expected := new(big.Int).Add(initialBalances[token], balance) - waitForTheTokenBalance(t, token, tt.receiver, e.Chains[tt.destChain], expected) + changeset.WaitForTheTokenBalance(ctx, t, token, tt.receiver, e.Chains[tt.destChain], expected) } }) } @@ -243,123 +254,6 @@ func TestUSDCTokenTransfer(t *testing.T) { // We sent 1 coin from each source chain, so we should have 2 coins on the destination chain // Receiver is randomly generated so we don't need to get the initial balance first expectedBalance := new(big.Int).Add(tinyOneCoin, tinyOneCoin) - waitForTheTokenBalance(t, cChainUSDC.Address(), receiver, e.Chains[chainC], expectedBalance) - }) -} - -// mintAndAllow mints tokens for deployers and allow router to spend them -func mintAndAllow( - t *testing.T, - e deployment.Environment, - state changeset.CCIPOnChainState, - tkMap map[uint64][]*burn_mint_erc677.BurnMintERC677, -) { - for chain, tokens := range tkMap { - for _, token := range tokens { - twoCoins := new(big.Int).Mul(big.NewInt(1e18), big.NewInt(2)) - - tx, err := token.Mint( - e.Chains[chain].DeployerKey, - e.Chains[chain].DeployerKey.From, - new(big.Int).Mul(twoCoins, big.NewInt(10)), - ) - require.NoError(t, err) - _, err = e.Chains[chain].Confirm(tx) - require.NoError(t, err) - - tx, err = token.Approve(e.Chains[chain].DeployerKey, state.Chains[chain].Router.Address(), twoCoins) - require.NoError(t, err) - _, err = e.Chains[chain].Confirm(tx) - require.NoError(t, err) - } - } -} - -// transferAndWaitForSuccess sends a message from sourceChain to destChain and waits for it to be executed -func transferAndWaitForSuccess( - t *testing.T, - env deployment.Environment, - state changeset.CCIPOnChainState, - sourceChain, destChain uint64, - tokens []router.ClientEVMTokenAmount, - receiver common.Address, - data []byte, - expectedStatus int, -) { - identifier := changeset.SourceDestPair{ - SourceChainSelector: sourceChain, - DestChainSelector: destChain, - } - - startBlocks := make(map[uint64]*uint64) - expectedSeqNum := make(map[changeset.SourceDestPair]uint64) - expectedSeqNumExec := make(map[changeset.SourceDestPair][]uint64) - - latesthdr, err := env.Chains[destChain].Client.HeaderByNumber(testcontext.Get(t), nil) - require.NoError(t, err) - block := latesthdr.Number.Uint64() - startBlocks[destChain] = &block - - msgSentEvent := changeset.TestSendRequest(t, env, state, sourceChain, destChain, false, router.ClientEVM2AnyMessage{ - Receiver: common.LeftPadBytes(receiver.Bytes(), 32), - Data: data, - TokenAmounts: tokens, - FeeToken: common.HexToAddress("0x0"), - ExtraArgs: nil, + changeset.WaitForTheTokenBalance(ctx, t, cChainUSDC.Address(), receiver, e.Chains[chainC], expectedBalance) }) - expectedSeqNum[identifier] = msgSentEvent.SequenceNumber - expectedSeqNumExec[identifier] = []uint64{msgSentEvent.SequenceNumber} - - // Wait for all commit reports to land. - changeset.ConfirmCommitForAllWithExpectedSeqNums(t, env, state, expectedSeqNum, startBlocks) - - // Wait for all exec reports to land - states := changeset.ConfirmExecWithSeqNrsForAll(t, env, state, expectedSeqNumExec, startBlocks) - require.Equal(t, expectedStatus, states[identifier][msgSentEvent.SequenceNumber]) -} - -func waitForTheTokenBalance( - t *testing.T, - token common.Address, - receiver common.Address, - chain deployment.Chain, - expected *big.Int, -) { - tokenContract, err := burn_mint_erc677.NewBurnMintERC677(token, chain.Client) - require.NoError(t, err) - - require.Eventually(t, func() bool { - actualBalance, err := tokenContract.BalanceOf(&bind.CallOpts{Context: tests.Context(t)}, receiver) - require.NoError(t, err) - - t.Log("Waiting for the token balance", - "expected", expected, - "actual", actualBalance, - "token", token, - "receiver", receiver, - ) - - return actualBalance.Cmp(expected) == 0 - }, tests.WaitTimeout(t), 100*time.Millisecond) -} - -func getTokenBalance( - t *testing.T, - token common.Address, - receiver common.Address, - chain deployment.Chain, -) *big.Int { - tokenContract, err := burn_mint_erc677.NewBurnMintERC677(token, chain.Client) - require.NoError(t, err) - - balance, err := tokenContract.BalanceOf(&bind.CallOpts{Context: tests.Context(t)}, receiver) - require.NoError(t, err) - - t.Log("Getting token balance", - "actual", balance, - "token", token, - "receiver", receiver, - ) - - return balance }