diff --git a/bridges/ethMultiversX/bridgeExecutor.go b/bridges/ethMultiversX/bridgeExecutor.go index 701401ae..c9b52dfd 100644 --- a/bridges/ethMultiversX/bridgeExecutor.go +++ b/bridges/ethMultiversX/bridgeExecutor.go @@ -10,6 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/multiversx/mx-bridge-eth-go/clients" "github.com/multiversx/mx-bridge-eth-go/clients/ethereum/contract" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" "github.com/multiversx/mx-bridge-eth-go/parsers" @@ -50,7 +51,7 @@ type bridgeExecutor struct { maxQuorumRetriesOnMultiversX uint64 maxRetriesOnWasProposed uint64 - batch *clients.TransferBatch + batch *bridgeCommon.TransferBatch actionID uint64 msgHash common.Hash quorumRetriesOnEthereum uint64 @@ -150,7 +151,7 @@ func (executor *bridgeExecutor) MyTurnAsLeader() bool { } // GetBatchFromMultiversX fetches the pending batch from MultiversX -func (executor *bridgeExecutor) GetBatchFromMultiversX(ctx context.Context) (*clients.TransferBatch, error) { +func (executor *bridgeExecutor) GetBatchFromMultiversX(ctx context.Context) (*bridgeCommon.TransferBatch, error) { batch, err := executor.multiversXClient.GetPendingBatch(ctx) if err == nil { executor.statusHandler.SetIntMetric(core.MetricNumBatches, int(batch.ID)-1) @@ -159,7 +160,7 @@ func (executor *bridgeExecutor) GetBatchFromMultiversX(ctx context.Context) (*cl } // StoreBatchFromMultiversX saves the pending batch from MultiversX -func (executor *bridgeExecutor) StoreBatchFromMultiversX(batch *clients.TransferBatch) error { +func (executor *bridgeExecutor) StoreBatchFromMultiversX(batch *bridgeCommon.TransferBatch) error { if batch == nil { return ErrNilBatch } @@ -169,7 +170,7 @@ func (executor *bridgeExecutor) StoreBatchFromMultiversX(batch *clients.Transfer } // GetStoredBatch returns the stored batch -func (executor *bridgeExecutor) GetStoredBatch() *clients.TransferBatch { +func (executor *bridgeExecutor) GetStoredBatch() *bridgeCommon.TransferBatch { return executor.batch } @@ -461,7 +462,7 @@ func (executor *bridgeExecutor) GetAndStoreBatchFromEthereum(ctx context.Context } // addBatchSCMetadata fetches the logs containing sc calls metadata for the current batch -func (executor *bridgeExecutor) addBatchSCMetadata(ctx context.Context, transfers *clients.TransferBatch) (*clients.TransferBatch, error) { +func (executor *bridgeExecutor) addBatchSCMetadata(ctx context.Context, transfers *bridgeCommon.TransferBatch) (*bridgeCommon.TransferBatch, error) { if transfers == nil { return nil, ErrNilBatch } @@ -478,7 +479,7 @@ func (executor *bridgeExecutor) addBatchSCMetadata(ctx context.Context, transfer return transfers, nil } -func (executor *bridgeExecutor) addMetadataToTransfer(transfer *clients.DepositTransfer, events []*contract.ERC20SafeERC20SCDeposit) *clients.DepositTransfer { +func (executor *bridgeExecutor) addMetadataToTransfer(transfer *bridgeCommon.DepositTransfer, events []*contract.ERC20SafeERC20SCDeposit) *bridgeCommon.DepositTransfer { for _, event := range events { if event.DepositNonce.Uint64() == transfer.Nonce { transfer.Data = []byte(event.CallData) @@ -492,7 +493,7 @@ func (executor *bridgeExecutor) addMetadataToTransfer(transfer *clients.DepositT } } - transfer.Data = []byte{parsers.MissingDataProtocolMarker} + transfer.Data = []byte{parsers.MissingDataProtocolMarker} // make([]byte, 0) transfer.DisplayableData = "" return transfer diff --git a/bridges/ethMultiversX/bridgeExecutor_test.go b/bridges/ethMultiversX/bridgeExecutor_test.go index 76707cf0..7da6d87d 100644 --- a/bridges/ethMultiversX/bridgeExecutor_test.go +++ b/bridges/ethMultiversX/bridgeExecutor_test.go @@ -13,6 +13,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/multiversx/mx-bridge-eth-go/clients" "github.com/multiversx/mx-bridge-eth-go/clients/ethereum/contract" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" "github.com/multiversx/mx-bridge-eth-go/testsCommon" @@ -24,7 +25,7 @@ import ( ) var expectedErr = errors.New("expected error") -var providedBatch = &clients.TransferBatch{} +var providedBatch = &bridgeCommon.TransferBatch{} var expectedMaxRetries = uint64(3) func createMockExecutorArgs() ArgsBridgeExecutor { @@ -242,7 +243,7 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreActionIDForProposeTransferOnMu args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - GetActionIDForProposeTransferCalled: func(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { + GetActionIDForProposeTransferCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (uint64, error) { assert.True(t, providedBatch == batch) return 0, expectedErr }, @@ -261,7 +262,7 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreActionIDForProposeTransferOnMu providedActionID := uint64(48939) args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - GetActionIDForProposeTransferCalled: func(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { + GetActionIDForProposeTransferCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (uint64, error) { assert.True(t, providedBatch == batch) return providedActionID, nil }, @@ -288,7 +289,7 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreBatchFromEthereum(t *testing.T args := createMockExecutorArgs() providedNonce := uint64(8346) args.EthereumClient = &bridgeTests.EthereumClientStub{ - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { assert.Equal(t, providedNonce, nonce) return nil, false, expectedErr }, @@ -303,11 +304,11 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreBatchFromEthereum(t *testing.T args := createMockExecutorArgs() providedNonce := uint64(8346) - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: 0, } args.EthereumClient = &bridgeTests.EthereumClientStub{ - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { assert.Equal(t, providedNonce, nonce) return expectedBatch, true, nil }, @@ -325,11 +326,11 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreBatchFromEthereum(t *testing.T args := createMockExecutorArgs() providedNonce := uint64(8346) - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: providedNonce, } args.EthereumClient = &bridgeTests.EthereumClientStub{ - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { assert.Equal(t, providedNonce, nonce) return expectedBatch, true, nil }, @@ -347,14 +348,14 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreBatchFromEthereum(t *testing.T args := createMockExecutorArgs() providedNonce := uint64(8346) - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: providedNonce, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ {}, }, } args.EthereumClient = &bridgeTests.EthereumClientStub{ - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { assert.Equal(t, providedNonce, nonce) return expectedBatch, false, nil }, @@ -375,14 +376,14 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreBatchFromEthereum(t *testing.T args := createMockExecutorArgs() providedNonce := uint64(8346) - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: providedNonce, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ {}, }, } args.EthereumClient = &bridgeTests.EthereumClientStub{ - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { assert.Equal(t, providedNonce, nonce) return expectedBatch, true, nil }, @@ -402,16 +403,16 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreBatchFromEthereum(t *testing.T providedNonce := uint64(8346) depositNonce := uint64(100) depositData := "testData" - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: providedNonce, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: depositNonce, }, }, } args.EthereumClient = &bridgeTests.EthereumClientStub{ - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { assert.Equal(t, providedNonce, nonce) return expectedBatch, true, nil }, @@ -434,16 +435,16 @@ func TestEthToMultiversXBridgeExecutor_GetAndStoreBatchFromEthereum(t *testing.T providedNonce := uint64(8346) depositNonce := uint64(100) depositData := "" - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: providedNonce, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: depositNonce, }, }, } args.EthereumClient = &bridgeTests.EthereumClientStub{ - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { assert.Equal(t, providedNonce, nonce) return expectedBatch, true, nil }, @@ -511,7 +512,7 @@ func TestEthToMultiversXBridgeExecutor_VerifyLastDepositNonceExecutedOnEthereumB }, } executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{} + executor.batch = &bridgeCommon.TransferBatch{} err := executor.VerifyLastDepositNonceExecutedOnEthereumBatch(context.Background()) assert.Equal(t, expectedErr, err) @@ -529,8 +530,8 @@ func TestEthToMultiversXBridgeExecutor_VerifyLastDepositNonceExecutedOnEthereumB t.Parallel() executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{ - Deposits: []*clients.DepositTransfer{ + executor.batch = &bridgeCommon.TransferBatch{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: txId, }, @@ -545,8 +546,8 @@ func TestEthToMultiversXBridgeExecutor_VerifyLastDepositNonceExecutedOnEthereumB t.Parallel() executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{ - Deposits: []*clients.DepositTransfer{ + executor.batch = &bridgeCommon.TransferBatch{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: txId - 1, }, @@ -561,8 +562,8 @@ func TestEthToMultiversXBridgeExecutor_VerifyLastDepositNonceExecutedOnEthereumB t.Parallel() executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{ - Deposits: []*clients.DepositTransfer{ + executor.batch = &bridgeCommon.TransferBatch{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: txId + 1, }, @@ -580,8 +581,8 @@ func TestEthToMultiversXBridgeExecutor_VerifyLastDepositNonceExecutedOnEthereumB t.Parallel() executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{ - Deposits: []*clients.DepositTransfer{ + executor.batch = &bridgeCommon.TransferBatch{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: txId + 1, }, @@ -591,8 +592,8 @@ func TestEthToMultiversXBridgeExecutor_VerifyLastDepositNonceExecutedOnEthereumB err := executor.VerifyLastDepositNonceExecutedOnEthereumBatch(context.Background()) assert.Nil(t, err) - executor.batch = &clients.TransferBatch{ - Deposits: []*clients.DepositTransfer{ + executor.batch = &bridgeCommon.TransferBatch{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: txId + 1, }, @@ -626,7 +627,7 @@ func TestEthToMultiversXBridgeExecutor_WasTransferProposedOnMultiversX(t *testin args := createMockExecutorArgs() wasCalled := false args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - WasProposedTransferCalled: func(ctx context.Context, batch *clients.TransferBatch) (bool, error) { + WasProposedTransferCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (bool, error) { assert.True(t, providedBatch == batch) wasCalled = true return true, nil @@ -660,7 +661,7 @@ func TestEthToMultiversXBridgeExecutor_ProposeTransferOnMultiversX(t *testing.T) args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - ProposeTransferCalled: func(ctx context.Context, batch *clients.TransferBatch) (string, error) { + ProposeTransferCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (string, error) { assert.True(t, providedBatch == batch) return "", expectedErr @@ -678,7 +679,7 @@ func TestEthToMultiversXBridgeExecutor_ProposeTransferOnMultiversX(t *testing.T) args := createMockExecutorArgs() wasCalled := false args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - ProposeTransferCalled: func(ctx context.Context, batch *clients.TransferBatch) (string, error) { + ProposeTransferCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (string, error) { assert.True(t, providedBatch == batch) wasCalled = true @@ -822,7 +823,7 @@ func TestEthToMultiversXBridgeExecutor_PerformActionOnMultiversX(t *testing.T) { args := createMockExecutorArgs() providedActionID := uint64(7383) args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - PerformActionCalled: func(ctx context.Context, actionID uint64, batch *clients.TransferBatch) (string, error) { + PerformActionCalled: func(ctx context.Context, actionID uint64, batch *bridgeCommon.TransferBatch) (string, error) { assert.Equal(t, providedActionID, actionID) assert.True(t, providedBatch == batch) return "", expectedErr @@ -842,7 +843,7 @@ func TestEthToMultiversXBridgeExecutor_PerformActionOnMultiversX(t *testing.T) { wasCalled := false providedActionID := uint64(7383) args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - PerformActionCalled: func(ctx context.Context, actionID uint64, batch *clients.TransferBatch) (string, error) { + PerformActionCalled: func(ctx context.Context, actionID uint64, batch *bridgeCommon.TransferBatch) (string, error) { assert.Equal(t, providedActionID, actionID) assert.True(t, providedBatch == batch) wasCalled = true @@ -899,7 +900,7 @@ func TestMultiversXToEthBridgeExecutor_GetAndStoreBatchFromMultiversX(t *testing args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - GetPendingBatchCalled: func(ctx context.Context) (*clients.TransferBatch, error) { + GetPendingBatchCalled: func(ctx context.Context) (*bridgeCommon.TransferBatch, error) { return nil, expectedErr }, } @@ -927,7 +928,7 @@ func TestMultiversXToEthBridgeExecutor_GetAndStoreBatchFromMultiversX(t *testing wasCalled := false args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - GetPendingBatchCalled: func(ctx context.Context) (*clients.TransferBatch, error) { + GetPendingBatchCalled: func(ctx context.Context) (*bridgeCommon.TransferBatch, error) { wasCalled = true return providedBatch, nil }, @@ -963,7 +964,7 @@ func TestMultiversXToEthBridgeExecutor_GetAndStoreActionIDForProposeSetStatusFro args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - GetActionIDForSetStatusOnPendingTransferCalled: func(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { + GetActionIDForSetStatusOnPendingTransferCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (uint64, error) { return uint64(0), expectedErr }, } @@ -980,7 +981,7 @@ func TestMultiversXToEthBridgeExecutor_GetAndStoreActionIDForProposeSetStatusFro providedActionId := uint64(1123) args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - GetActionIDForSetStatusOnPendingTransferCalled: func(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { + GetActionIDForSetStatusOnPendingTransferCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (uint64, error) { wasCalled = true return providedActionId, nil }, @@ -1016,7 +1017,7 @@ func TestMultiversXToEthBridgeExecutor_WasSetStatusProposedOnMultiversX(t *testi args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - WasProposedSetStatusCalled: func(ctx context.Context, batch *clients.TransferBatch) (bool, error) { + WasProposedSetStatusCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (bool, error) { return false, expectedErr }, } @@ -1032,7 +1033,7 @@ func TestMultiversXToEthBridgeExecutor_WasSetStatusProposedOnMultiversX(t *testi wasCalled := false args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - WasProposedSetStatusCalled: func(ctx context.Context, batch *clients.TransferBatch) (bool, error) { + WasProposedSetStatusCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (bool, error) { assert.True(t, providedBatch == batch) wasCalled = true return true, nil @@ -1065,7 +1066,7 @@ func TestEthToMultiversXBridgeExecutor_ProposeSetStatusOnMultiversX(t *testing.T args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - ProposeSetStatusCalled: func(ctx context.Context, batch *clients.TransferBatch) (string, error) { + ProposeSetStatusCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (string, error) { return "", expectedErr }, } @@ -1081,7 +1082,7 @@ func TestEthToMultiversXBridgeExecutor_ProposeSetStatusOnMultiversX(t *testing.T wasCalled := false args := createMockExecutorArgs() args.MultiversXClient = &bridgeTests.MultiversXClientStub{ - ProposeSetStatusCalled: func(ctx context.Context, batch *clients.TransferBatch) (string, error) { + ProposeSetStatusCalled: func(ctx context.Context, batch *bridgeCommon.TransferBatch) (string, error) { assert.True(t, providedBatch == batch) wasCalled = true @@ -1404,7 +1405,7 @@ func TestWaitForTransferConfirmation(t *testing.T) { }, } executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{} + executor.batch = &bridgeCommon.TransferBatch{} ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -1430,7 +1431,7 @@ func TestWaitForTransferConfirmation(t *testing.T) { }, } executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{} + executor.batch = &bridgeCommon.TransferBatch{} ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -1475,7 +1476,7 @@ func TestGetBatchStatusesFromEthereum(t *testing.T) { t.Parallel() wasCalled := false - providedStatuses := []byte{clients.Executed, clients.Rejected} + providedStatuses := []byte{bridgeCommon.Executed, bridgeCommon.Rejected} args := createMockExecutorArgs() args.EthereumClient = &bridgeTests.EthereumClientStub{ GetTransactionsStatusesCalled: func(ctx context.Context, batchId uint64) ([]byte, error) { @@ -1540,7 +1541,7 @@ func TestWaitAndReturnFinalBatchStatuses(t *testing.T) { }, } executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{} + executor.batch = &bridgeCommon.TransferBatch{} ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -1553,7 +1554,7 @@ func TestWaitAndReturnFinalBatchStatuses(t *testing.T) { t.Run("GetBatchStatusesFromEthereum always returns success+statuses only after 4 checks", func(t *testing.T) { t.Parallel() - providedStatuses := []byte{clients.Executed, clients.Rejected} + providedStatuses := []byte{bridgeCommon.Executed, bridgeCommon.Rejected} args := createMockExecutorArgs() args.TimeForWaitOnEthereum = 10 * time.Second counter := 0 @@ -1567,7 +1568,7 @@ func TestWaitAndReturnFinalBatchStatuses(t *testing.T) { }, } executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{} + executor.batch = &bridgeCommon.TransferBatch{} ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -1584,7 +1585,7 @@ func TestWaitAndReturnFinalBatchStatuses(t *testing.T) { t.Run("GetBatchStatusesFromEthereum always returns success+statuses only after 4 checks, otherwise empty slice", func(t *testing.T) { t.Parallel() - providedStatuses := []byte{clients.Executed, clients.Rejected} + providedStatuses := []byte{bridgeCommon.Executed, bridgeCommon.Rejected} args := createMockExecutorArgs() args.TimeForWaitOnEthereum = 10 * time.Second counter := 0 @@ -1598,7 +1599,7 @@ func TestWaitAndReturnFinalBatchStatuses(t *testing.T) { }, } executor, _ := NewBridgeExecutor(args) - executor.batch = &clients.TransferBatch{} + executor.batch = &bridgeCommon.TransferBatch{} ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -1617,8 +1618,8 @@ func TestWaitAndReturnFinalBatchStatuses(t *testing.T) { func TestResolveNewDepositsStatuses(t *testing.T) { t.Parallel() - providedBatchForResolve := &clients.TransferBatch{ - Deposits: []*clients.DepositTransfer{ + providedBatchForResolve := &bridgeCommon.TransferBatch{ + Deposits: []*bridgeCommon.DepositTransfer{ { DisplayableTo: "to1", }, @@ -1637,11 +1638,11 @@ func TestResolveNewDepositsStatuses(t *testing.T) { executor.batch = providedBatchForResolve.Clone() executor.ResolveNewDepositsStatuses(uint64(0)) - assert.Equal(t, []byte{clients.Rejected, clients.Rejected}, executor.batch.Statuses) + assert.Equal(t, []byte{bridgeCommon.Rejected, bridgeCommon.Rejected}, executor.batch.Statuses) executor.batch = providedBatchForResolve.Clone() executor.batch.ResolveNewDeposits(1) - assert.Equal(t, []byte{0, clients.Rejected}, executor.batch.Statuses) + assert.Equal(t, []byte{0, bridgeCommon.Rejected}, executor.batch.Statuses) }) t.Run("equal new deposits", func(t *testing.T) { t.Parallel() @@ -1661,7 +1662,7 @@ func TestResolveNewDepositsStatuses(t *testing.T) { executor.batch = providedBatchForResolve.Clone() executor.ResolveNewDepositsStatuses(uint64(3)) - assert.Equal(t, []byte{0, 0, clients.Rejected}, executor.batch.Statuses) + assert.Equal(t, []byte{0, 0, bridgeCommon.Rejected}, executor.batch.Statuses) }) } @@ -1844,9 +1845,14 @@ func TestConvertToDisplayableData_ValidCallDataWithNoArguments(t *testing.T) { t.Parallel() callData := func() []byte { - b := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - b = append(b, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit - b = append(b, 0x00, 0x00, 0x00, 0x00) // numArguments + b := []byte{ + 1, + 0, 0, 0, 16, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + 0, // numArguments + } + return b }() @@ -1860,17 +1866,22 @@ func TestConvertToDisplayableData_MultipleTypesArguments(t *testing.T) { t.Parallel() callData := func() []byte { - b := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - b = append(b, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit - b = append(b, 0x00, 0x00, 0x00, 0x02) // numArguments - b = append(b, 0x00, 0x00, 0x00, 0x05) // Argument 0 length - b = append(b, bytes.Repeat([]byte{'A'}, 5)...) // Argument 0 data - b = append(b, 0x00, 0x00, 0x00, 0x32) // Argument 1 length - b = append(b, bytes.Repeat([]byte{'B'}, 50)...) // Argument 1 data + b := []byte{ + 1, + 0, 0, 0, 82, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + 0, 0, 0, 2, // numArguments + 0, 0, 0, 5, // argument 0 length + 'd', 'e', 'f', 'g', 'h', // argument 0 data + 0, 0, 0, 50, // /argument 1 length + } + b = append(b, bytes.Repeat([]byte{'B'}, 50)...) // argument 1 data + return b }() - want := "Endpoint: abc, Gas: 500000000, Arguments: AAAAA@BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + want := "Endpoint: abc, Gas: 500000000, Arguments: defgh@BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" got, err := ConvertToDisplayableData(callData) require.Equal(t, want, got) require.Nil(t, err) @@ -1879,11 +1890,16 @@ func TestConvertToDisplayableData_MultipleTypesArguments(t *testing.T) { func TestConvertToDisplayableData_TooShortForArgumentData(t *testing.T) { t.Parallel() callData := func() []byte { - b := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - b = append(b, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit length - b = append(b, 0x00, 0x00, 0x00, 0x01) // numArguments - b = append(b, 0x00, 0x00, 0x00, 0x04) // Argument 0 length - b = append(b, 0x00, 0x00, 0x04) // Bad Argument 0 data + b := []byte{ + 1, + 0, 0, 0, 26, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + 0, 0, 0, 1, // numArguments + 0, 0, 0, 4, // argument 0 length + 0, 0, 4, // bad argument 0 data + } + return b }() _, err := ConvertToDisplayableData(callData) diff --git a/bridges/ethMultiversX/interface.go b/bridges/ethMultiversX/interface.go index 8ebcaeed..cd2edca5 100644 --- a/bridges/ethMultiversX/interface.go +++ b/bridges/ethMultiversX/interface.go @@ -5,32 +5,32 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" "github.com/multiversx/mx-bridge-eth-go/clients/ethereum/contract" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" ) // MultiversXClient defines the behavior of the MultiversX client able to communicate with the MultiversX chain type MultiversXClient interface { - GetPendingBatch(ctx context.Context) (*clients.TransferBatch, error) - GetBatch(ctx context.Context, batchID uint64) (*clients.TransferBatch, error) + GetPendingBatch(ctx context.Context) (*bridgeCommon.TransferBatch, error) + GetBatch(ctx context.Context, batchID uint64) (*bridgeCommon.TransferBatch, error) GetCurrentBatchAsDataBytes(ctx context.Context) ([][]byte, error) - WasProposedTransfer(ctx context.Context, batch *clients.TransferBatch) (bool, error) + WasProposedTransfer(ctx context.Context, batch *bridgeCommon.TransferBatch) (bool, error) QuorumReached(ctx context.Context, actionID uint64) (bool, error) WasExecuted(ctx context.Context, actionID uint64) (bool, error) - GetActionIDForProposeTransfer(ctx context.Context, batch *clients.TransferBatch) (uint64, error) - WasProposedSetStatus(ctx context.Context, batch *clients.TransferBatch) (bool, error) + GetActionIDForProposeTransfer(ctx context.Context, batch *bridgeCommon.TransferBatch) (uint64, error) + WasProposedSetStatus(ctx context.Context, batch *bridgeCommon.TransferBatch) (bool, error) GetTransactionsStatuses(ctx context.Context, batchID uint64) ([]byte, error) - GetActionIDForSetStatusOnPendingTransfer(ctx context.Context, batch *clients.TransferBatch) (uint64, error) + GetActionIDForSetStatusOnPendingTransfer(ctx context.Context, batch *bridgeCommon.TransferBatch) (uint64, error) GetLastExecutedEthBatchID(ctx context.Context) (uint64, error) GetLastExecutedEthTxID(ctx context.Context) (uint64, error) GetCurrentNonce(ctx context.Context) (uint64, error) - ProposeSetStatus(ctx context.Context, batch *clients.TransferBatch) (string, error) - ProposeTransfer(ctx context.Context, batch *clients.TransferBatch) (string, error) + ProposeSetStatus(ctx context.Context, batch *bridgeCommon.TransferBatch) (string, error) + ProposeTransfer(ctx context.Context, batch *bridgeCommon.TransferBatch) (string, error) Sign(ctx context.Context, actionID uint64) (string, error) WasSigned(ctx context.Context, actionID uint64) (bool, error) - PerformAction(ctx context.Context, actionID uint64, batch *clients.TransferBatch) (string, error) + PerformAction(ctx context.Context, actionID uint64, batch *bridgeCommon.TransferBatch) (string, error) CheckClientAvailability(ctx context.Context) error IsMintBurnToken(ctx context.Context, token []byte) (bool, error) IsNativeToken(ctx context.Context, token []byte) (bool, error) @@ -44,7 +44,7 @@ type MultiversXClient interface { // EthereumClient defines the behavior of the Ethereum client able to communicate with the Ethereum chain type EthereumClient interface { - GetBatch(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) + GetBatch(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) WasExecuted(ctx context.Context, batchID uint64) (bool, error) GenerateMessageHash(batch *batchProcessor.ArgListsBatch, batchId uint64) (common.Hash, error) diff --git a/bridges/ethMultiversX/steps/ethToMultiversX/semiIntegrated_test.go b/bridges/ethMultiversX/steps/ethToMultiversX/semiIntegrated_test.go index 1eab5041..0c6b1036 100644 --- a/bridges/ethMultiversX/steps/ethToMultiversX/semiIntegrated_test.go +++ b/bridges/ethMultiversX/steps/ethToMultiversX/semiIntegrated_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX/steps" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/multiversx/mx-bridge-eth-go/testsCommon/stateMachine" @@ -79,8 +79,8 @@ func createMockBridge(args argsBridgeStub) (*bridgeTests.BridgeExecutorStub, *er return errHandler.storeAndReturnError(nil) } - stub.GetStoredBatchCalled = func() *clients.TransferBatch { - return &clients.TransferBatch{} + stub.GetStoredBatchCalled = func() *common.TransferBatch { + return &common.TransferBatch{} } stub.GetLastExecutedEthBatchIDFromMultiversXCalled = func(ctx context.Context) (uint64, error) { if args.failingStep == getLastExecutedEthBatchIDFromMultiversX { diff --git a/bridges/ethMultiversX/steps/ethToMultiversX/step01GetPending_test.go b/bridges/ethMultiversX/steps/ethToMultiversX/step01GetPending_test.go index f652e75e..c25a7d56 100644 --- a/bridges/ethMultiversX/steps/ethToMultiversX/step01GetPending_test.go +++ b/bridges/ethMultiversX/steps/ethToMultiversX/step01GetPending_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" @@ -15,9 +15,9 @@ import ( ) var expectedError = errors.New("expected error") -var testBatch = &clients.TransferBatch{ +var testBatch = &bridgeCommon.TransferBatch{ ID: 112233, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: 0, ToBytes: []byte("to"), @@ -74,7 +74,7 @@ func TestExecuteGetPending(t *testing.T) { bridgeStub.GetAndStoreBatchFromEthereumCalled = func(ctx context.Context, nonce uint64) error { return nil } - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *bridgeCommon.TransferBatch { return nil } @@ -95,7 +95,7 @@ func TestExecuteGetPending(t *testing.T) { bridgeStub.GetAndStoreBatchFromEthereumCalled = func(ctx context.Context, nonce uint64) error { return nil } - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *bridgeCommon.TransferBatch { return testBatch } bridgeStub.VerifyLastDepositNonceExecutedOnEthereumBatchCalled = func(ctx context.Context) error { @@ -122,7 +122,7 @@ func TestExecuteGetPending(t *testing.T) { bridgeStub.GetAndStoreBatchFromEthereumCalled = func(ctx context.Context, nonce uint64) error { return nil } - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *bridgeCommon.TransferBatch { return testBatch } bridgeStub.VerifyLastDepositNonceExecutedOnEthereumBatchCalled = func(ctx context.Context) error { @@ -146,7 +146,7 @@ func TestExecuteGetPending(t *testing.T) { bridgeStub.GetAndStoreBatchFromEthereumCalled = func(ctx context.Context, nonce uint64) error { return nil } - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *bridgeCommon.TransferBatch { return testBatch } bridgeStub.VerifyLastDepositNonceExecutedOnEthereumBatchCalled = func(ctx context.Context) error { diff --git a/bridges/ethMultiversX/steps/ethToMultiversX/step02ProposeTransfer_test.go b/bridges/ethMultiversX/steps/ethToMultiversX/step02ProposeTransfer_test.go index ac03e6fa..bfa7927b 100644 --- a/bridges/ethMultiversX/steps/ethToMultiversX/step02ProposeTransfer_test.go +++ b/bridges/ethMultiversX/steps/ethToMultiversX/step02ProposeTransfer_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/stretchr/testify/assert" ) @@ -15,7 +15,7 @@ func TestExecuteProposeTransfer(t *testing.T) { t.Run("nil batch", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return nil } @@ -31,7 +31,7 @@ func TestExecuteProposeTransfer(t *testing.T) { t.Run("error on WasTransferProposedOnMultiversX", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasTransferProposedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -50,7 +50,7 @@ func TestExecuteProposeTransfer(t *testing.T) { t.Run("not leader", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasTransferProposedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -72,7 +72,7 @@ func TestExecuteProposeTransfer(t *testing.T) { t.Run("error on ProposeTransferOnMultiversX", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasTransferProposedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -97,7 +97,7 @@ func TestExecuteProposeTransfer(t *testing.T) { t.Run("should work - transfer already proposed", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasTransferProposedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -116,7 +116,7 @@ func TestExecuteProposeTransfer(t *testing.T) { t.Run("should work", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasTransferProposedOnMultiversXCalled = func(ctx context.Context) (bool, error) { diff --git a/bridges/ethMultiversX/steps/ethToMultiversX/step03SignProposedTransfer_test.go b/bridges/ethMultiversX/steps/ethToMultiversX/step03SignProposedTransfer_test.go index b0f2751d..1a6f24c6 100644 --- a/bridges/ethMultiversX/steps/ethToMultiversX/step03SignProposedTransfer_test.go +++ b/bridges/ethMultiversX/steps/ethToMultiversX/step03SignProposedTransfer_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/stretchr/testify/assert" ) @@ -17,7 +17,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Run("nil batch", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return nil } @@ -33,7 +33,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Run("error on WasProposedTransferSigned", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasActionSignedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -52,7 +52,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Run("error on SignProposedTransfer", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasActionSignedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -75,7 +75,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Parallel() expectedErr := errors.New("expected error") bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasActionSignedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -97,7 +97,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Run("invalid action ID", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasActionSignedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -119,7 +119,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Run("error on WasActionSignedOnMultiversX", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasActionSignedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -141,7 +141,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Run("should work - transfer was already signed", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasActionSignedOnMultiversXCalled = func(ctx context.Context) (bool, error) { @@ -163,7 +163,7 @@ func TestExecuteSignProposedTransferStep(t *testing.T) { t.Run("should work", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutor() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } bridgeStub.WasActionSignedOnMultiversXCalled = func(ctx context.Context) (bool, error) { diff --git a/bridges/ethMultiversX/steps/interface.go b/bridges/ethMultiversX/steps/interface.go index 235b5506..bc68e1ac 100644 --- a/bridges/ethMultiversX/steps/interface.go +++ b/bridges/ethMultiversX/steps/interface.go @@ -5,7 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" logger "github.com/multiversx/mx-chain-logger-go" ) @@ -15,9 +15,9 @@ type Executor interface { PrintInfo(logLevel logger.LogLevel, message string, extras ...interface{}) MyTurnAsLeader() bool - GetBatchFromMultiversX(ctx context.Context) (*clients.TransferBatch, error) - StoreBatchFromMultiversX(batch *clients.TransferBatch) error - GetStoredBatch() *clients.TransferBatch + GetBatchFromMultiversX(ctx context.Context) (*bridgeCommon.TransferBatch, error) + StoreBatchFromMultiversX(batch *bridgeCommon.TransferBatch) error + GetStoredBatch() *bridgeCommon.TransferBatch GetLastExecutedEthBatchIDFromMultiversX(ctx context.Context) (uint64, error) VerifyLastDepositNonceExecutedOnEthereumBatch(ctx context.Context) error diff --git a/bridges/ethMultiversX/steps/multiversxToEth/semiIntegrated_test.go b/bridges/ethMultiversX/steps/multiversxToEth/semiIntegrated_test.go index 99126422..df729c83 100644 --- a/bridges/ethMultiversX/steps/multiversxToEth/semiIntegrated_test.go +++ b/bridges/ethMultiversX/steps/multiversxToEth/semiIntegrated_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX/steps" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/multiversx/mx-bridge-eth-go/testsCommon/stateMachine" @@ -96,17 +96,17 @@ func createMockBridge(args argsBridgeStub) (*bridgeTests.BridgeExecutorStub, *er stub.GetStoredActionIDCalled = func() uint64 { return 2 } - stub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*clients.TransferBatch, error) { + stub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*common.TransferBatch, error) { if args.failingStep == getBatchFromMultiversX { - return &clients.TransferBatch{}, errHandler.storeAndReturnError(expectedErr) + return &common.TransferBatch{}, errHandler.storeAndReturnError(expectedErr) } - return &clients.TransferBatch{}, errHandler.storeAndReturnError(nil) + return &common.TransferBatch{}, errHandler.storeAndReturnError(nil) } - stub.StoreBatchFromMultiversXCalled = func(batch *clients.TransferBatch) error { + stub.StoreBatchFromMultiversXCalled = func(batch *common.TransferBatch) error { return nil } - stub.GetStoredBatchCalled = func() *clients.TransferBatch { - return &clients.TransferBatch{} + stub.GetStoredBatchCalled = func() *common.TransferBatch { + return &common.TransferBatch{} } stub.WasTransferPerformedOnEthereumCalled = func(ctx context.Context) (bool, error) { if args.failingStep == wasTransferPerformedOnEthereum { diff --git a/bridges/ethMultiversX/steps/multiversxToEth/step01GetPending_test.go b/bridges/ethMultiversX/steps/multiversxToEth/step01GetPending_test.go index 3cb880ba..908e8c4e 100644 --- a/bridges/ethMultiversX/steps/multiversxToEth/step01GetPending_test.go +++ b/bridges/ethMultiversX/steps/multiversxToEth/step01GetPending_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" @@ -15,7 +15,7 @@ import ( ) var expectedError = errors.New("expected error") -var testBatch = &clients.TransferBatch{ +var testBatch = &bridgeCommon.TransferBatch{ ID: 112233, Deposits: nil, Statuses: nil, @@ -27,7 +27,7 @@ func TestExecute_GetPending(t *testing.T) { t.Run("error on GetBatchFromMultiversX", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorGetPending() - bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*clients.TransferBatch, error) { + bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*bridgeCommon.TransferBatch, error) { return nil, expectedError } @@ -42,7 +42,7 @@ func TestExecute_GetPending(t *testing.T) { t.Run("nil batch on GetBatchFromMultiversX", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorGetPending() - bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*clients.TransferBatch, error) { + bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*bridgeCommon.TransferBatch, error) { return nil, nil } @@ -57,7 +57,7 @@ func TestExecute_GetPending(t *testing.T) { t.Run("error on StoreBatchFromMultiversX", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorGetPending() - bridgeStub.StoreBatchFromMultiversXCalled = func(batch *clients.TransferBatch) error { + bridgeStub.StoreBatchFromMultiversXCalled = func(batch *bridgeCommon.TransferBatch) error { return expectedError } @@ -153,10 +153,10 @@ func TestExecute_GetPending(t *testing.T) { func createStubExecutorGetPending() *bridgeTests.BridgeExecutorStub { stub := bridgeTests.NewBridgeExecutorStub() - stub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*clients.TransferBatch, error) { + stub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*bridgeCommon.TransferBatch, error) { return testBatch, nil } - stub.StoreBatchFromMultiversXCalled = func(batch *clients.TransferBatch) error { + stub.StoreBatchFromMultiversXCalled = func(batch *bridgeCommon.TransferBatch) error { return nil } return stub diff --git a/bridges/ethMultiversX/steps/multiversxToEth/step02SignProposedTransfer_test.go b/bridges/ethMultiversX/steps/multiversxToEth/step02SignProposedTransfer_test.go index 0163f6e9..50278c40 100644 --- a/bridges/ethMultiversX/steps/multiversxToEth/step02SignProposedTransfer_test.go +++ b/bridges/ethMultiversX/steps/multiversxToEth/step02SignProposedTransfer_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/stretchr/testify/assert" @@ -18,7 +18,7 @@ func TestExecute_SignProposedTransfer(t *testing.T) { t.Run("nil batch on GetStoredBatch", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorSignProposedTransfer() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return nil } @@ -63,7 +63,7 @@ func TestExecute_SignProposedTransfer(t *testing.T) { func createStubExecutorSignProposedTransfer() *bridgeTests.BridgeExecutorStub { stub := bridgeTests.NewBridgeExecutorStub() - stub.GetStoredBatchCalled = func() *clients.TransferBatch { + stub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } stub.SignTransferOnEthereumCalled = func() error { diff --git a/bridges/ethMultiversX/steps/multiversxToEth/step06ResolveSetStatus_test.go b/bridges/ethMultiversX/steps/multiversxToEth/step06ResolveSetStatus_test.go index efffb0ba..8ea76468 100644 --- a/bridges/ethMultiversX/steps/multiversxToEth/step06ResolveSetStatus_test.go +++ b/bridges/ethMultiversX/steps/multiversxToEth/step06ResolveSetStatus_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/stretchr/testify/assert" @@ -16,7 +16,7 @@ func TestExecute_ResolveSetStatus(t *testing.T) { t.Run("nil batch on GetStoredBatch", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorResolveSetStatus() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return nil } clearWasCalled := false @@ -35,7 +35,7 @@ func TestExecute_ResolveSetStatus(t *testing.T) { t.Run("error on GetStoredBatch", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorResolveSetStatus() - bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*clients.TransferBatch, error) { + bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*common.TransferBatch, error) { return nil, expectedError } clearWasCalled := false @@ -54,7 +54,7 @@ func TestExecute_ResolveSetStatus(t *testing.T) { t.Run("nil batch on GetBatchFromMultiversX", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorResolveSetStatus() - bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*clients.TransferBatch, error) { + bridgeStub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*common.TransferBatch, error) { return nil, nil } clearWasCalled := false @@ -101,7 +101,7 @@ func TestExecute_ResolveSetStatus(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorResolveSetStatus() bridgeStub.WaitAndReturnFinalBatchStatusesCalled = func(ctx context.Context) []byte { - return []byte{clients.Executed, clients.Rejected} + return []byte{common.Executed, common.Rejected} } wasCalled := false @@ -130,10 +130,10 @@ func TestExecute_ResolveSetStatus(t *testing.T) { func createStubExecutorResolveSetStatus() *bridgeTests.BridgeExecutorStub { stub := bridgeTests.NewBridgeExecutorStub() - stub.GetStoredBatchCalled = func() *clients.TransferBatch { + stub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } - stub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*clients.TransferBatch, error) { + stub.GetBatchFromMultiversXCalled = func(ctx context.Context) (*common.TransferBatch, error) { return testBatch, nil } return stub diff --git a/bridges/ethMultiversX/steps/multiversxToEth/step07ProposeSetStatus_test.go b/bridges/ethMultiversX/steps/multiversxToEth/step07ProposeSetStatus_test.go index f31e8564..74508060 100644 --- a/bridges/ethMultiversX/steps/multiversxToEth/step07ProposeSetStatus_test.go +++ b/bridges/ethMultiversX/steps/multiversxToEth/step07ProposeSetStatus_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/stretchr/testify/assert" @@ -15,7 +15,7 @@ func TestExecute_ProposeSetStatus(t *testing.T) { t.Run("nil batch on GetStoredBatch", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorProposeSetStatus() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return nil } @@ -127,7 +127,7 @@ func TestExecute_ProposeSetStatus(t *testing.T) { func createStubExecutorProposeSetStatus() *bridgeTests.BridgeExecutorStub { stub := bridgeTests.NewBridgeExecutorStub() - stub.GetStoredBatchCalled = func() *clients.TransferBatch { + stub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } stub.WasSetStatusProposedOnMultiversXCalled = func(ctx context.Context) (bool, error) { diff --git a/bridges/ethMultiversX/steps/multiversxToEth/step08SignProposedSetStatus_test.go b/bridges/ethMultiversX/steps/multiversxToEth/step08SignProposedSetStatus_test.go index 1e7e60f9..4fcf8b92 100644 --- a/bridges/ethMultiversX/steps/multiversxToEth/step08SignProposedSetStatus_test.go +++ b/bridges/ethMultiversX/steps/multiversxToEth/step08SignProposedSetStatus_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/stretchr/testify/assert" @@ -18,7 +18,7 @@ func TestExecute_SignProposedSetStatus(t *testing.T) { t.Run("nil batch on GetStoredBatch", func(t *testing.T) { t.Parallel() bridgeStub := createStubExecutorSignProposedSetStatus() - bridgeStub.GetStoredBatchCalled = func() *clients.TransferBatch { + bridgeStub.GetStoredBatchCalled = func() *common.TransferBatch { return nil } @@ -135,7 +135,7 @@ func TestExecute_SignProposedSetStatus(t *testing.T) { func createStubExecutorSignProposedSetStatus() *bridgeTests.BridgeExecutorStub { stub := bridgeTests.NewBridgeExecutorStub() - stub.GetStoredBatchCalled = func() *clients.TransferBatch { + stub.GetStoredBatchCalled = func() *common.TransferBatch { return testBatch } stub.GetAndStoreActionIDForProposeSetStatusFromMultiversXCalled = func(ctx context.Context) (uint64, error) { diff --git a/clients/balanceValidator/balanceValidator.go b/clients/balanceValidator/balanceValidator.go index 57ab1e23..70378908 100644 --- a/clients/balanceValidator/balanceValidator.go +++ b/clients/balanceValidator/balanceValidator.go @@ -9,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" "github.com/multiversx/mx-chain-core-go/core/check" logger "github.com/multiversx/mx-chain-logger-go" @@ -258,7 +259,7 @@ func (validator *balanceValidator) computeMvxAmount( return mvxAmount, nil } -func getTotalAmountFromBatch(batch *clients.TransferBatch, token []byte) *big.Int { +func getTotalAmountFromBatch(batch *bridgeCommon.TransferBatch, token []byte) *big.Int { amount := big.NewInt(0) for _, deposit := range batch.Deposits { if bytes.Equal(deposit.SourceTokenBytes, token) { @@ -312,7 +313,7 @@ func (validator *balanceValidator) getTotalTransferAmountInPendingEthBatches(ctx return nil, err } - var batch *clients.TransferBatch + var batch *bridgeCommon.TransferBatch amount := big.NewInt(0) for { batch, _, err = validator.ethereumClient.GetBatch(ctx, batchID+1) // we take all batches, regardless if they are final or not diff --git a/clients/balanceValidator/balanceValidator_test.go b/clients/balanceValidator/balanceValidator_test.go index 8fb4ee3b..a2550d57 100644 --- a/clients/balanceValidator/balanceValidator_test.go +++ b/clients/balanceValidator/balanceValidator_test.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/multiversx/mx-chain-go/testscommon" @@ -1516,20 +1517,20 @@ func validatorTester(cfg testConfiguration) testResult { return returnBigIntOrZeroIfNil(cfg.burnBalancesOnMvx), nil }, - GetPendingBatchCalled: func(ctx context.Context) (*clients.TransferBatch, error) { + GetPendingBatchCalled: func(ctx context.Context) (*bridgeCommon.TransferBatch, error) { err := cfg.errorsOnCalls["GetPendingBatchMvx"] if err != nil { return nil, err } - batch := &clients.TransferBatch{ + batch := &bridgeCommon.TransferBatch{ ID: cfg.pendingMvxBatchId, } applyDummyFromMvxDepositsToBatch(cfg, batch) return batch, nil }, - GetBatchCalled: func(ctx context.Context, batchID uint64) (*clients.TransferBatch, error) { + GetBatchCalled: func(ctx context.Context, batchID uint64) (*bridgeCommon.TransferBatch, error) { err := cfg.errorsOnCalls["GetBatchMvx"] if err != nil { return nil, err @@ -1538,7 +1539,7 @@ func validatorTester(cfg testConfiguration) testResult { if batchID > getMaxMvxPendingBatchID(cfg) { return nil, clients.ErrNoBatchAvailable } - batch := &clients.TransferBatch{ + batch := &bridgeCommon.TransferBatch{ ID: batchID, } applyDummyFromMvxDepositsToBatch(cfg, batch) @@ -1599,13 +1600,13 @@ func validatorTester(cfg testConfiguration) testResult { return returnBigIntOrZeroIfNil(cfg.burnBalancesOnEth), nil }, - GetBatchCalled: func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { + GetBatchCalled: func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { err := cfg.errorsOnCalls["GetBatchEth"] if err != nil { return nil, false, err } - batch := &clients.TransferBatch{ + batch := &bridgeCommon.TransferBatch{ ID: nonce, } applyDummyFromEthDepositsToBatch(cfg, batch) @@ -1632,14 +1633,14 @@ func validatorTester(cfg testConfiguration) testResult { return result } -func applyDummyFromMvxDepositsToBatch(cfg testConfiguration, batch *clients.TransferBatch) { +func applyDummyFromMvxDepositsToBatch(cfg testConfiguration, batch *bridgeCommon.TransferBatch) { if cfg.amountsOnMvxPendingBatches != nil { values, found := cfg.amountsOnMvxPendingBatches[batch.ID] if found { depositCounter := uint64(0) for _, deposit := range values { - batch.Deposits = append(batch.Deposits, &clients.DepositTransfer{ + batch.Deposits = append(batch.Deposits, &bridgeCommon.DepositTransfer{ Nonce: depositCounter, Amount: big.NewInt(0).Set(deposit), SourceTokenBytes: mvxToken, @@ -1649,14 +1650,14 @@ func applyDummyFromMvxDepositsToBatch(cfg testConfiguration, batch *clients.Tran } } -func applyDummyFromEthDepositsToBatch(cfg testConfiguration, batch *clients.TransferBatch) { +func applyDummyFromEthDepositsToBatch(cfg testConfiguration, batch *bridgeCommon.TransferBatch) { if cfg.amountsOnEthPendingBatches != nil { values, found := cfg.amountsOnEthPendingBatches[batch.ID] if found { depositCounter := uint64(0) for _, deposit := range values { - batch.Deposits = append(batch.Deposits, &clients.DepositTransfer{ + batch.Deposits = append(batch.Deposits, &bridgeCommon.DepositTransfer{ Nonce: depositCounter, Amount: big.NewInt(0).Set(deposit), SourceTokenBytes: ethToken.Bytes(), diff --git a/clients/balanceValidator/interface.go b/clients/balanceValidator/interface.go index 48062672..890cab13 100644 --- a/clients/balanceValidator/interface.go +++ b/clients/balanceValidator/interface.go @@ -5,13 +5,13 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" ) // MultiversXClient defines the behavior of the MultiversX client able to communicate with the MultiversX chain type MultiversXClient interface { - GetPendingBatch(ctx context.Context) (*clients.TransferBatch, error) - GetBatch(ctx context.Context, batchID uint64) (*clients.TransferBatch, error) + GetPendingBatch(ctx context.Context) (*bridgeCommon.TransferBatch, error) + GetBatch(ctx context.Context, batchID uint64) (*bridgeCommon.TransferBatch, error) GetLastExecutedEthBatchID(ctx context.Context) (uint64, error) IsMintBurnToken(ctx context.Context, token []byte) (bool, error) IsNativeToken(ctx context.Context, token []byte) (bool, error) @@ -24,7 +24,7 @@ type MultiversXClient interface { // EthereumClient defines the behavior of the Ethereum client able to communicate with the Ethereum chain type EthereumClient interface { - GetBatch(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) + GetBatch(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) TotalBalances(ctx context.Context, token common.Address) (*big.Int, error) MintBalances(ctx context.Context, token common.Address) (*big.Int, error) BurnBalances(ctx context.Context, token common.Address) (*big.Int, error) diff --git a/clients/ethereum/client.go b/clients/ethereum/client.go index ae9fccca..062fd05a 100644 --- a/clients/ethereum/client.go +++ b/clients/ethereum/client.go @@ -15,6 +15,7 @@ import ( "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX" "github.com/multiversx/mx-bridge-eth-go/clients" "github.com/multiversx/mx-bridge-eth-go/clients/ethereum/contract" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" chainCore "github.com/multiversx/mx-chain-core-go/core" @@ -144,7 +145,7 @@ func checkArgs(args ArgsEthereumClient) error { } // GetBatch returns the batch (if existing) from the Ethereum contract by providing the nonce -func (c *client) GetBatch(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { +func (c *client) GetBatch(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { c.log.Info("Getting batch", "nonce", nonce) nonceAsBigInt := big.NewInt(0).SetUint64(nonce) batch, isFinalBatch, err := c.clientWrapper.GetBatch(ctx, nonceAsBigInt) @@ -160,9 +161,9 @@ func (c *client) GetBatch(ctx context.Context, nonce uint64) (*clients.TransferB errDepositsAndBatchDepositsCountDiffer, batch.DepositsCount, len(deposits)) } - transferBatch := &clients.TransferBatch{ + transferBatch := &bridgeCommon.TransferBatch{ ID: batch.Nonce.Uint64(), - Deposits: make([]*clients.DepositTransfer, 0, batch.DepositsCount), + Deposits: make([]*bridgeCommon.DepositTransfer, 0, batch.DepositsCount), } cachedTokens := make(map[string][]byte) for i := range deposits { @@ -171,7 +172,7 @@ func (c *client) GetBatch(ctx context.Context, nonce uint64) (*clients.TransferB fromBytes := deposit.Depositor[:] tokenBytes := deposit.TokenAddress[:] - depositTransfer := &clients.DepositTransfer{ + depositTransfer := &bridgeCommon.DepositTransfer{ Nonce: deposit.Nonce.Uint64(), ToBytes: toBytes, DisplayableTo: c.addressConverter.ToBech32StringSilent(toBytes), diff --git a/clients/ethereum/client_test.go b/clients/ethereum/client_test.go index 65073a20..a6a214ce 100644 --- a/clients/ethereum/client_test.go +++ b/clients/ethereum/client_test.go @@ -17,6 +17,7 @@ import ( "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX" "github.com/multiversx/mx-bridge-eth-go/clients" "github.com/multiversx/mx-bridge-eth-go/clients/ethereum/contract" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" bridgeCore "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" "github.com/multiversx/mx-bridge-eth-go/core/converters" @@ -62,10 +63,10 @@ func createMockEthereumClientArgs() ArgsEthereumClient { } } -func createMockTransferBatch() *clients.TransferBatch { - return &clients.TransferBatch{ +func createMockTransferBatch() *bridgeCommon.TransferBatch { + return &bridgeCommon.TransferBatch{ ID: 332, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: 10, ToBytes: []byte("to1"), @@ -320,9 +321,9 @@ func TestClient_GetBatch(t *testing.T) { bech32Recipient1Address, _ := recipient1.AddressAsBech32String() bech32Recipient2Address, _ := recipient2.AddressAsBech32String() - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: 112243, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: 10, ToBytes: recipient1.AddressBytes(), @@ -394,9 +395,9 @@ func TestClient_GetBatch(t *testing.T) { bech32Recipient1Address, _ := recipient1.AddressAsBech32String() bech32Recipient2Address, _ := recipient2.AddressAsBech32String() - expectedBatch := &clients.TransferBatch{ + expectedBatch := &bridgeCommon.TransferBatch{ ID: 112243, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: 10, ToBytes: recipient1.AddressBytes(), @@ -621,7 +622,7 @@ func TestClient_ExecuteTransfer(t *testing.T) { }, } newBatch := batch.Clone() - newBatch.Deposits = append(newBatch.Deposits, &clients.DepositTransfer{ + newBatch.Deposits = append(newBatch.Deposits, &bridgeCommon.DepositTransfer{ Nonce: 40, ToBytes: []byte("to3"), DisplayableTo: "to3", diff --git a/clients/multiversx/client.go b/clients/multiversx/client.go index c95e17e3..a955cc53 100644 --- a/clients/multiversx/client.go +++ b/clients/multiversx/client.go @@ -11,6 +11,7 @@ import ( "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX" "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/config" bridgeCore "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/core/converters" @@ -54,6 +55,7 @@ type ClientArgs struct { // client represents the MultiversX Client implementation type client struct { *mxClientDataGetter + codec *parsers.MultiversxCodec txHandler txHandler tokensMapper TokensMapper relayerPublicKey crypto.PublicKey @@ -123,6 +125,7 @@ func NewClient(args ClientArgs) (*client, error) { } c := &client{ + codec: &parsers.MultiversxCodec{}, txHandler: &transactionHandler{ proxy: args.Proxy, relayerAddress: relayerAddress, @@ -205,7 +208,7 @@ func checkGasMapValues(gasMap config.MultiversXGasMapConfig) error { } // GetPendingBatch returns the pending batch -func (c *client) GetPendingBatch(ctx context.Context) (*clients.TransferBatch, error) { +func (c *client) GetPendingBatch(ctx context.Context) (*common.TransferBatch, error) { c.log.Info("getting pending batch...") responseData, err := c.GetCurrentBatchAsDataBytes(ctx) if err != nil { @@ -220,7 +223,7 @@ func (c *client) GetPendingBatch(ctx context.Context) (*clients.TransferBatch, e } // GetBatch returns the batch (if existing) -func (c *client) GetBatch(ctx context.Context, batchID uint64) (*clients.TransferBatch, error) { +func (c *client) GetBatch(ctx context.Context, batchID uint64) (*common.TransferBatch, error) { c.log.Debug("getting batch", "ID", batchID) responseData, err := c.GetBatchAsDataBytes(ctx, batchID) if err != nil { @@ -238,7 +241,7 @@ func emptyResponse(response [][]byte) bool { return len(response) == 0 || (len(response) == 1 && len(response[0]) == 0) } -func (c *client) createPendingBatchFromResponse(ctx context.Context, responseData [][]byte) (*clients.TransferBatch, error) { +func (c *client) createPendingBatchFromResponse(ctx context.Context, responseData [][]byte) (*common.TransferBatch, error) { numFieldsForTransaction := 6 dataLen := len(responseData) haveCorrectNumberOfArgs := (dataLen-1)%numFieldsForTransaction == 0 && dataLen > 1 @@ -251,7 +254,7 @@ func (c *client) createPendingBatchFromResponse(ctx context.Context, responseDat return nil, fmt.Errorf("%w while parsing batch ID", err) } - batch := &clients.TransferBatch{ + batch := &common.TransferBatch{ ID: batchID, } @@ -265,7 +268,7 @@ func (c *client) createPendingBatchFromResponse(ctx context.Context, responseDat } amount := big.NewInt(0).SetBytes(responseData[i+5]) - deposit := &clients.DepositTransfer{ + deposit := &common.DepositTransfer{ Nonce: depositNonce, FromBytes: responseData[i+2], DisplayableFrom: c.addressPublicKeyConverter.ToBech32StringSilent(responseData[i+2]), @@ -303,7 +306,7 @@ func (c *client) createCommonTxDataBuilder(funcName string, id int64) builders.T } // ProposeSetStatus will trigger the proposal of the ESDT safe set current transaction batch status operation -func (c *client) ProposeSetStatus(ctx context.Context, batch *clients.TransferBatch) (string, error) { +func (c *client) ProposeSetStatus(ctx context.Context, batch *common.TransferBatch) (string, error) { if batch == nil { return "", clients.ErrNilBatch } @@ -328,7 +331,7 @@ func (c *client) ProposeSetStatus(ctx context.Context, batch *clients.TransferBa } // ProposeTransfer will trigger the propose transfer operation -func (c *client) ProposeTransfer(ctx context.Context, batch *clients.TransferBatch) (string, error) { +func (c *client) ProposeTransfer(ctx context.Context, batch *common.TransferBatch) (string, error) { if batch == nil { return "", clients.ErrNilBatch } @@ -340,21 +343,19 @@ func (c *client) ProposeTransfer(ctx context.Context, batch *clients.TransferBat txBuilder := c.createCommonTxDataBuilder(proposeTransferFuncName, int64(batch.ID)) - for _, dt := range batch.Deposits { - txBuilder.ArgBytes(dt.FromBytes). - ArgBytes(dt.ToBytes). - ArgBytes(dt.DestinationTokenBytes). - ArgBigInt(dt.Amount). - ArgInt64(int64(dt.Nonce)). - ArgBytes(dt.Data) + depositsBytes, err := c.codec.EncodeDeposits(batch.Deposits) + if err != nil { + return "", err } + txBuilder.ArgBytes(depositsBytes) + gasLimit := c.gasMapConfig.ProposeTransferBase + uint64(len(batch.Deposits))*c.gasMapConfig.ProposeTransferForEach extraGasForScCalls := c.computeExtraGasForSCCallsBasic(batch, false) gasLimit += extraGasForScCalls hash, err := c.txHandler.SendTransactionReturnHash(ctx, txBuilder, gasLimit) if err == nil { - c.log.Info("proposed transfer"+batch.String(), "transaction hash", hash) + c.log.Info("proposed transfer "+batch.String(), "transaction hash", hash) } return hash, err @@ -378,7 +379,7 @@ func (c *client) Sign(ctx context.Context, actionID uint64) (string, error) { } // PerformAction will trigger the execution of the provided action ID -func (c *client) PerformAction(ctx context.Context, actionID uint64, batch *clients.TransferBatch) (string, error) { +func (c *client) PerformAction(ctx context.Context, actionID uint64, batch *common.TransferBatch) (string, error) { if batch == nil { return "", clients.ErrNilBatch } @@ -401,7 +402,7 @@ func (c *client) PerformAction(ctx context.Context, actionID uint64, batch *clie return hash, err } -func (c *client) computeExtraGasForSCCallsBasic(batch *clients.TransferBatch, performAction bool) uint64 { +func (c *client) computeExtraGasForSCCallsBasic(batch *common.TransferBatch, performAction bool) uint64 { gasLimit := uint64(0) for _, deposit := range batch.Deposits { if bytes.Equal(deposit.Data, []byte{parsers.MissingDataProtocolMarker}) { diff --git a/clients/multiversx/client_test.go b/clients/multiversx/client_test.go index ac0227f3..751dde73 100644 --- a/clients/multiversx/client_test.go +++ b/clients/multiversx/client_test.go @@ -3,6 +3,7 @@ package multiversx import ( "bytes" "context" + "encoding/binary" "encoding/hex" "errors" "fmt" @@ -12,6 +13,7 @@ import ( "github.com/multiversx/mx-bridge-eth-go/bridges/ethMultiversX" "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/config" bridgeCore "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/parsers" @@ -346,9 +348,9 @@ func TestClient_GetPendingBatch(t *testing.T) { tokenBytes1 := bytes.Repeat([]byte{3}, 32) tokenBytes2 := bytes.Repeat([]byte{6}, 32) - expectedBatch := &clients.TransferBatch{ + expectedBatch := &common.TransferBatch{ ID: 44562, - Deposits: []*clients.DepositTransfer{ + Deposits: []*common.DepositTransfer{ { Nonce: 5000, ToBytes: bytes.Repeat([]byte{2}, 20), @@ -503,9 +505,9 @@ func TestClient_GetBatch(t *testing.T) { tokenBytes1 := bytes.Repeat([]byte{3}, 32) tokenBytes2 := bytes.Repeat([]byte{6}, 32) - expectedBatch := &clients.TransferBatch{ + expectedBatch := &common.TransferBatch{ ID: 44562, - Deposits: []*clients.DepositTransfer{ + Deposits: []*common.DepositTransfer{ { Nonce: 5000, ToBytes: bytes.Repeat([]byte{2}, 20), @@ -569,7 +571,7 @@ func TestClient_ProposeSetStatus(t *testing.T) { } c, _ := NewClient(args) - hash, err := c.ProposeSetStatus(context.Background(), &clients.TransferBatch{}) + hash, err := c.ProposeSetStatus(context.Background(), &common.TransferBatch{}) assert.Empty(t, hash) assert.True(t, errors.Is(err, expectedErr)) }) @@ -589,7 +591,7 @@ func TestClient_ProposeSetStatus(t *testing.T) { } c, _ := NewClient(args) - hash, err := c.ProposeSetStatus(context.Background(), &clients.TransferBatch{}) + hash, err := c.ProposeSetStatus(context.Background(), &common.TransferBatch{}) assert.Empty(t, hash) assert.True(t, errors.Is(err, clients.ErrMultisigContractPaused)) }) @@ -612,7 +614,7 @@ func TestClient_ProposeSetStatus(t *testing.T) { proposeSetStatusFuncName, hex.EncodeToString(big.NewInt(112233).Bytes()), } - expectedStatus := []byte{clients.Rejected, clients.Executed} + expectedStatus := []byte{common.Rejected, common.Executed} for _, stat := range expectedStatus { expectedArgs = append(expectedArgs, hex.EncodeToString([]byte{stat})) } @@ -658,7 +660,7 @@ func TestClient_ProposeTransfer(t *testing.T) { } c, _ := NewClient(args) - hash, err := c.ProposeTransfer(context.Background(), &clients.TransferBatch{}) + hash, err := c.ProposeTransfer(context.Background(), &common.TransferBatch{}) assert.Empty(t, hash) assert.True(t, errors.Is(err, expectedErr)) }) @@ -678,7 +680,7 @@ func TestClient_ProposeTransfer(t *testing.T) { } c, _ := NewClient(args) - hash, err := c.ProposeTransfer(context.Background(), &clients.TransferBatch{}) + hash, err := c.ProposeTransfer(context.Background(), &common.TransferBatch{}) assert.Empty(t, hash) assert.True(t, errors.Is(err, clients.ErrMultisigContractPaused)) }) @@ -703,9 +705,11 @@ func TestClient_ProposeTransfer(t *testing.T) { proposeTransferFuncName, hex.EncodeToString(big.NewInt(int64(batch.ID)).Bytes()), } + depositsString := "" for _, dt := range batch.Deposits { - dataStrings = append(dataStrings, depositToStrings(dt)...) + depositsString = depositsString + depositToString(dt) } + dataStrings = append(dataStrings, depositsString) expectedDataField := strings.Join(dataStrings, "@") assert.Equal(t, expectedDataField, dataField) @@ -748,13 +752,15 @@ func TestClient_ProposeTransfer(t *testing.T) { hex.EncodeToString(big.NewInt(int64(batch.ID)).Bytes()), } extraGas := uint64(0) + depositsString := "" for _, dt := range batch.Deposits { - dataStrings = append(dataStrings, depositToStrings(dt)...) + depositsString = depositsString + depositToString(dt) if bytes.Equal(dt.Data, []byte{parsers.MissingDataProtocolMarker}) { continue } extraGas += (uint64(len(dt.Data))*2 + 1) * args.GasMapConfig.ScCallPerByte } + dataStrings = append(dataStrings, depositsString) expectedDataField := strings.Join(dataStrings, "@") assert.Equal(t, expectedDataField, dataField) @@ -773,19 +779,36 @@ func TestClient_ProposeTransfer(t *testing.T) { }) } -func depositToStrings(dt *clients.DepositTransfer) []string { - result := []string{ - hex.EncodeToString(dt.FromBytes), - hex.EncodeToString(dt.ToBytes), - hex.EncodeToString(dt.DestinationTokenBytes), - hex.EncodeToString(dt.Amount.Bytes()), - hex.EncodeToString(big.NewInt(int64(dt.Nonce)).Bytes()), - hex.EncodeToString(dt.Data), - } +func depositToString(dt *common.DepositTransfer) string { + result := hex.EncodeToString(dt.FromBytes) + result = result + hex.EncodeToString(dt.ToBytes) + + tokenLength := len(dt.DestinationTokenBytes) + result = result + encodeLenAsHex(tokenLength) + hex.EncodeToString(dt.DestinationTokenBytes) + + amountLength := len(dt.Amount.Bytes()) + result = result + encodeLenAsHex(amountLength) + hex.EncodeToString(dt.Amount.Bytes()) + + result = result + encodeUint64AsHex(dt.Nonce) + result = result + hex.EncodeToString(dt.Data) return result } +func encodeLenAsHex(length int) string { + buff := make([]byte, 4) + binary.BigEndian.PutUint32(buff, uint32(length)) + + return hex.EncodeToString(buff) +} + +func encodeUint64AsHex(value uint64) string { + buff := make([]byte, 8) + binary.BigEndian.PutUint64(buff, value) + + return hex.EncodeToString(buff) +} + func TestClient_Sign(t *testing.T) { t.Parallel() @@ -881,7 +904,7 @@ func TestClient_PerformAction(t *testing.T) { } c, _ := NewClient(args) - hash, err := c.PerformAction(context.Background(), actionID, &clients.TransferBatch{}) + hash, err := c.PerformAction(context.Background(), actionID, &common.TransferBatch{}) assert.Empty(t, hash) assert.True(t, errors.Is(err, expectedErr)) }) @@ -901,7 +924,7 @@ func TestClient_PerformAction(t *testing.T) { } c, _ := NewClient(args) - hash, err := c.PerformAction(context.Background(), actionID, &clients.TransferBatch{}) + hash, err := c.PerformAction(context.Background(), actionID, &common.TransferBatch{}) assert.Empty(t, hash) assert.True(t, errors.Is(err, clients.ErrMultisigContractPaused)) }) @@ -970,7 +993,6 @@ func TestClient_PerformAction(t *testing.T) { extraGas := uint64(0) for _, dt := range batch.Deposits { - dataStrings = append(dataStrings, depositToStrings(dt)...) if bytes.Equal(dt.Data, []byte{parsers.MissingDataProtocolMarker}) { continue } diff --git a/clients/multiversx/mxClientDataGetter.go b/clients/multiversx/mxClientDataGetter.go index ea57b7d0..9bd1dfa6 100644 --- a/clients/multiversx/mxClientDataGetter.go +++ b/clients/multiversx/mxClientDataGetter.go @@ -8,7 +8,9 @@ import ( "sync" "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/errors" + "github.com/multiversx/mx-bridge-eth-go/parsers" "github.com/multiversx/mx-chain-core-go/core/check" logger "github.com/multiversx/mx-chain-logger-go" "github.com/multiversx/mx-sdk-go/builders" @@ -52,6 +54,7 @@ type ArgsMXClientDataGetter struct { } type mxClientDataGetter struct { + codec *parsers.MultiversxCodec multisigContractAddress core.AddressHandler safeContractAddress core.AddressHandler bech32MultisigContractAddress string @@ -86,6 +89,7 @@ func NewMXClientDataGetter(args ArgsMXClientDataGetter) (*mxClientDataGetter, er } return &mxClientDataGetter{ + codec: &parsers.MultiversxCodec{}, multisigContractAddress: args.MultisigContractAddress, safeContractAddress: args.SafeContractAddress, bech32MultisigContractAddress: bech32Address, @@ -325,14 +329,17 @@ func (dataGetter *mxClientDataGetter) GetERC20AddressForTokenId(ctx context.Cont } // WasProposedTransfer returns true if the transfer action proposed was triggered -func (dataGetter *mxClientDataGetter) WasProposedTransfer(ctx context.Context, batch *clients.TransferBatch) (bool, error) { +func (dataGetter *mxClientDataGetter) WasProposedTransfer(ctx context.Context, batch *common.TransferBatch) (bool, error) { if batch == nil { return false, clients.ErrNilBatch } builder := dataGetter.createMultisigDefaultVmQueryBuilder() builder.Function(wasTransferActionProposedFuncName).ArgInt64(int64(batch.ID)) - addBatchInfo(builder, batch) + err := dataGetter.addBatchInfo(builder, batch) + if err != nil { + return false, err + } return dataGetter.executeQueryBoolFromBuilder(ctx, builder) } @@ -346,20 +353,23 @@ func (dataGetter *mxClientDataGetter) WasExecuted(ctx context.Context, actionID } // GetActionIDForProposeTransfer returns the action ID for the proposed transfer operation -func (dataGetter *mxClientDataGetter) GetActionIDForProposeTransfer(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { +func (dataGetter *mxClientDataGetter) GetActionIDForProposeTransfer(ctx context.Context, batch *common.TransferBatch) (uint64, error) { if batch == nil { return 0, clients.ErrNilBatch } builder := dataGetter.createMultisigDefaultVmQueryBuilder() builder.Function(getActionIdForTransferBatchFuncName).ArgInt64(int64(batch.ID)) - addBatchInfo(builder, batch) + err := dataGetter.addBatchInfo(builder, batch) + if err != nil { + return 0, err + } return dataGetter.executeQueryUint64FromBuilder(ctx, builder) } // WasProposedSetStatus returns true if the proposed set status was triggered -func (dataGetter *mxClientDataGetter) WasProposedSetStatus(ctx context.Context, batch *clients.TransferBatch) (bool, error) { +func (dataGetter *mxClientDataGetter) WasProposedSetStatus(ctx context.Context, batch *common.TransferBatch) (bool, error) { if batch == nil { return false, clients.ErrNilBatch } @@ -410,7 +420,7 @@ func (dataGetter *mxClientDataGetter) GetTransactionsStatuses(ctx context.Contex } // GetActionIDForSetStatusOnPendingTransfer returns the action ID for setting the status on the pending transfer batch -func (dataGetter *mxClientDataGetter) GetActionIDForSetStatusOnPendingTransfer(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { +func (dataGetter *mxClientDataGetter) GetActionIDForSetStatusOnPendingTransfer(ctx context.Context, batch *common.TransferBatch) (uint64, error) { if batch == nil { return 0, clients.ErrNilBatch } @@ -506,6 +516,17 @@ func (dataGetter *mxClientDataGetter) getBurnBalances(ctx context.Context, token return dataGetter.executeQueryBigIntFromBuilder(ctx, builder) } +func (dataGetter *mxClientDataGetter) addBatchInfo(builder builders.VMQueryBuilder, batch *common.TransferBatch) error { + depositsData, err := dataGetter.codec.EncodeDeposits(batch.Deposits) + if err != nil { + return err + } + + builder.ArgBytes(depositsData) + + return nil +} + func getStatusFromBuff(buff []byte) (byte, error) { if len(buff) == 0 { return 0, errMalformedBatchResponse @@ -514,17 +535,6 @@ func getStatusFromBuff(buff []byte) (byte, error) { return buff[len(buff)-1], nil } -func addBatchInfo(builder builders.VMQueryBuilder, batch *clients.TransferBatch) { - for _, dt := range batch.Deposits { - builder.ArgBytes(dt.FromBytes). - ArgBytes(dt.ToBytes). - ArgBytes(dt.DestinationTokenBytes). - ArgBigInt(dt.Amount). - ArgInt64(int64(dt.Nonce)). - ArgBytes(dt.Data) - } -} - // IsInterfaceNil returns true if there is no value under the interface func (dataGetter *mxClientDataGetter) IsInterfaceNil() bool { return dataGetter == nil diff --git a/clients/multiversx/mxClientDataGetter_test.go b/clients/multiversx/mxClientDataGetter_test.go index 4d3ad7cd..aaf074b8 100644 --- a/clients/multiversx/mxClientDataGetter_test.go +++ b/clients/multiversx/mxClientDataGetter_test.go @@ -11,8 +11,8 @@ import ( "testing" "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" bridgeErrors "github.com/multiversx/mx-bridge-eth-go/errors" - "github.com/multiversx/mx-bridge-eth-go/parsers" bridgeTests "github.com/multiversx/mx-bridge-eth-go/testsCommon/bridge" "github.com/multiversx/mx-bridge-eth-go/testsCommon/interactors" "github.com/multiversx/mx-chain-core-go/core/check" @@ -64,10 +64,10 @@ func createMockProxy(returningBytes [][]byte) *interactors.ProxyStub { } } -func createMockBatch() *clients.TransferBatch { - return &clients.TransferBatch{ +func createMockBatch() *common.TransferBatch { + return &common.TransferBatch{ ID: 112233, - Deposits: []*clients.DepositTransfer{ + Deposits: []*common.DepositTransfer{ { Nonce: 1, ToBytes: []byte("to1"), @@ -79,7 +79,7 @@ func createMockBatch() *clients.TransferBatch { DisplayableToken: "token1", Amount: big.NewInt(2), Data: []byte{0x00}, - DisplayableData: "", + DisplayableData: "00", }, { Nonce: 3, @@ -92,10 +92,10 @@ func createMockBatch() *clients.TransferBatch { DisplayableToken: "token2", Amount: big.NewInt(4), Data: []byte{0x00}, - DisplayableData: "", + DisplayableData: "00", }, }, - Statuses: []byte{clients.Rejected, clients.Executed}, + Statuses: []byte{common.Rejected, common.Executed}, } } @@ -588,6 +588,8 @@ func TestMXClientDataGetter_WasProposedTransfer(t *testing.T) { args := createMockArgsMXClientDataGetter() proxyCalled := false + batch := createMockBatch() + args.Proxy = &interactors.ProxyStub{ ExecuteVMQueryCalled: func(ctx context.Context, vmRequest *data.VmValueRequest) (*data.VmValuesResponseData, error) { proxyCalled = true @@ -596,22 +598,14 @@ func TestMXClientDataGetter_WasProposedTransfer(t *testing.T) { assert.Equal(t, "", vmRequest.CallValue) assert.Equal(t, wasTransferActionProposedFuncName, vmRequest.FuncName) + depositsString := "" + for _, dt := range batch.Deposits { + depositsString += depositToString(dt) + } + expectedArgs := []string{ hex.EncodeToString(big.NewInt(112233).Bytes()), - - hex.EncodeToString([]byte("from1")), - hex.EncodeToString([]byte("to1")), - hex.EncodeToString([]byte("converted_token1")), - hex.EncodeToString(big.NewInt(2).Bytes()), - hex.EncodeToString(big.NewInt(1).Bytes()), - hex.EncodeToString([]byte{parsers.MissingDataProtocolMarker}), - - hex.EncodeToString([]byte("from2")), - hex.EncodeToString([]byte("to2")), - hex.EncodeToString([]byte("converted_token2")), - hex.EncodeToString(big.NewInt(4).Bytes()), - hex.EncodeToString(big.NewInt(3).Bytes()), - hex.EncodeToString([]byte{parsers.MissingDataProtocolMarker}), + depositsString, } assert.Equal(t, expectedArgs, vmRequest.Args) @@ -627,8 +621,6 @@ func TestMXClientDataGetter_WasProposedTransfer(t *testing.T) { dg, _ := NewMXClientDataGetter(args) - batch := createMockBatch() - result, err := dg.WasProposedTransfer(context.Background(), batch) assert.True(t, result) assert.Nil(t, err) @@ -639,6 +631,9 @@ func TestMXClientDataGetter_WasProposedTransfer(t *testing.T) { args := createMockArgsMXClientDataGetter() proxyCalled := false + batch := createMockBatch() + batch.Deposits[0].Data = bridgeTests.CallDataMock + args.Proxy = &interactors.ProxyStub{ ExecuteVMQueryCalled: func(ctx context.Context, vmRequest *data.VmValueRequest) (*data.VmValuesResponseData, error) { proxyCalled = true @@ -647,22 +642,14 @@ func TestMXClientDataGetter_WasProposedTransfer(t *testing.T) { assert.Equal(t, "", vmRequest.CallValue) assert.Equal(t, wasTransferActionProposedFuncName, vmRequest.FuncName) + depositsString := "" + for _, dt := range batch.Deposits { + depositsString += depositToString(dt) + } + expectedArgs := []string{ hex.EncodeToString(big.NewInt(112233).Bytes()), - - hex.EncodeToString([]byte("from1")), - hex.EncodeToString([]byte("to1")), - hex.EncodeToString([]byte("converted_token1")), - hex.EncodeToString(big.NewInt(2).Bytes()), - hex.EncodeToString(big.NewInt(1).Bytes()), - hex.EncodeToString(bridgeTests.CallDataMock), - - hex.EncodeToString([]byte("from2")), - hex.EncodeToString([]byte("to2")), - hex.EncodeToString([]byte("converted_token2")), - hex.EncodeToString(big.NewInt(4).Bytes()), - hex.EncodeToString(big.NewInt(3).Bytes()), - hex.EncodeToString([]byte{parsers.MissingDataProtocolMarker}), + depositsString, } assert.Equal(t, expectedArgs, vmRequest.Args) @@ -678,9 +665,6 @@ func TestMXClientDataGetter_WasProposedTransfer(t *testing.T) { dg, _ := NewMXClientDataGetter(args) - batch := createMockBatch() - batch.Deposits[0].Data = bridgeTests.CallDataMock - result, err := dg.WasProposedTransfer(context.Background(), batch) assert.True(t, result) assert.Nil(t, err) @@ -763,6 +747,7 @@ func TestMXClientDataGetter_GetActionIDForProposeTransfer(t *testing.T) { args := createMockArgsMXClientDataGetter() proxyCalled := false + batch := createMockBatch() args.Proxy = &interactors.ProxyStub{ ExecuteVMQueryCalled: func(ctx context.Context, vmRequest *data.VmValueRequest) (*data.VmValuesResponseData, error) { proxyCalled = true @@ -771,22 +756,14 @@ func TestMXClientDataGetter_GetActionIDForProposeTransfer(t *testing.T) { assert.Equal(t, "", vmRequest.CallValue) assert.Equal(t, getActionIdForTransferBatchFuncName, vmRequest.FuncName) + depositsString := "" + for _, dt := range batch.Deposits { + depositsString += depositToString(dt) + } + expectedArgs := []string{ hex.EncodeToString(big.NewInt(112233).Bytes()), - - hex.EncodeToString([]byte("from1")), - hex.EncodeToString([]byte("to1")), - hex.EncodeToString([]byte("converted_token1")), - hex.EncodeToString(big.NewInt(2).Bytes()), - hex.EncodeToString(big.NewInt(1).Bytes()), - hex.EncodeToString([]byte{parsers.MissingDataProtocolMarker}), - - hex.EncodeToString([]byte("from2")), - hex.EncodeToString([]byte("to2")), - hex.EncodeToString([]byte("converted_token2")), - hex.EncodeToString(big.NewInt(4).Bytes()), - hex.EncodeToString(big.NewInt(3).Bytes()), - hex.EncodeToString([]byte{parsers.MissingDataProtocolMarker}), + depositsString, } assert.Equal(t, expectedArgs, vmRequest.Args) @@ -802,8 +779,6 @@ func TestMXClientDataGetter_GetActionIDForProposeTransfer(t *testing.T) { dg, _ := NewMXClientDataGetter(args) - batch := createMockBatch() - result, err := dg.GetActionIDForProposeTransfer(context.Background(), batch) assert.Equal(t, uint64(1234), result) assert.Nil(t, err) @@ -814,6 +789,8 @@ func TestMXClientDataGetter_GetActionIDForProposeTransfer(t *testing.T) { args := createMockArgsMXClientDataGetter() proxyCalled := false + batch := createMockBatch() + batch.Deposits[0].Data = bridgeTests.CallDataMock args.Proxy = &interactors.ProxyStub{ ExecuteVMQueryCalled: func(ctx context.Context, vmRequest *data.VmValueRequest) (*data.VmValuesResponseData, error) { proxyCalled = true @@ -822,22 +799,14 @@ func TestMXClientDataGetter_GetActionIDForProposeTransfer(t *testing.T) { assert.Equal(t, "", vmRequest.CallValue) assert.Equal(t, getActionIdForTransferBatchFuncName, vmRequest.FuncName) + depositsString := "" + for _, dt := range batch.Deposits { + depositsString += depositToString(dt) + } + expectedArgs := []string{ hex.EncodeToString(big.NewInt(112233).Bytes()), - - hex.EncodeToString([]byte("from1")), - hex.EncodeToString([]byte("to1")), - hex.EncodeToString([]byte("converted_token1")), - hex.EncodeToString(big.NewInt(2).Bytes()), - hex.EncodeToString(big.NewInt(1).Bytes()), - hex.EncodeToString(bridgeTests.CallDataMock), - - hex.EncodeToString([]byte("from2")), - hex.EncodeToString([]byte("to2")), - hex.EncodeToString([]byte("converted_token2")), - hex.EncodeToString(big.NewInt(4).Bytes()), - hex.EncodeToString(big.NewInt(3).Bytes()), - hex.EncodeToString([]byte{parsers.MissingDataProtocolMarker}), + depositsString, } assert.Equal(t, expectedArgs, vmRequest.Args) @@ -853,9 +822,6 @@ func TestMXClientDataGetter_GetActionIDForProposeTransfer(t *testing.T) { dg, _ := NewMXClientDataGetter(args) - batch := createMockBatch() - batch.Deposits[0].Data = bridgeTests.CallDataMock - result, err := dg.GetActionIDForProposeTransfer(context.Background(), batch) assert.Equal(t, uint64(1234), result) assert.Nil(t, err) diff --git a/cmd/bridge/flags.go b/cmd/bridge/flags.go index 25ceb47d..800742e9 100644 --- a/cmd/bridge/flags.go +++ b/cmd/bridge/flags.go @@ -30,7 +30,7 @@ var ( "all available routes for Rest API and options to enable or disable them.", Value: "config/api.toml", } - // logFile is used when the log output needs to be logged in a file + // logSaveFile is used when the log output needs to be logged in a file logSaveFile = cli.BoolFlag{ Name: "log-save", Usage: "Boolean option for enabling log saving. If set, it will automatically save all the logs into a file.", diff --git a/cmd/scCallsExecutor/config/config.toml b/cmd/scCallsExecutor/config/config.toml new file mode 100644 index 00000000..19b2ac33 --- /dev/null +++ b/cmd/scCallsExecutor/config/config.toml @@ -0,0 +1,19 @@ +ScProxyBech32Address = "erd1qqqqqqqqqqqqqpgqnef5f5aq32d63kljld8w5vnvz4gk5sy9hrrq2ld08s" +ExtraGasToExecute = 50000000 +NetworkAddress = "127.0.0.1:8085" +ProxyMaxNoncesDelta = 7 +ProxyFinalityCheck = true +ProxyCacherExpirationSeconds = 600 +ProxyRestAPIEntityType = "observer" +IntervalToResendTxsInSeconds = 60 +PrivateKeyFile = "keys/multiversx.pem" +PollingIntervalInMillis = 6000 + +[FilterConfig] + AllowedEthAddresses = ["*"] # execute SC calls from all ETH addresses + AllowedMvxAddresses = ["*"] # execute SC calls to all MvX contracts + AllowedTokens = ["*"] # execute SC calls for all tokens + +[Logs] + LogFileLifeSpanInSec = 86400 # 24h + LogFileLifeSpanInMB = 1024 # 1GB diff --git a/cmd/scCallsExecutor/flags.go b/cmd/scCallsExecutor/flags.go new file mode 100644 index 00000000..1605b65a --- /dev/null +++ b/cmd/scCallsExecutor/flags.go @@ -0,0 +1,98 @@ +package main + +import ( + "github.com/multiversx/mx-bridge-eth-go/config" + "github.com/multiversx/mx-chain-go/facade" + logger "github.com/multiversx/mx-chain-logger-go" + "github.com/urfave/cli" +) + +var ( + logLevel = cli.StringFlag{ + Name: "log-level", + Usage: "This flag specifies the logger `level(s)`. It can contain multiple comma-separated value. For example" + + ", if set to *:INFO the logs for all packages will have the INFO level. However, if set to *:INFO,api:DEBUG" + + " the logs for all packages will have the INFO level, excepting the api package which will receive a DEBUG" + + " log level.", + Value: "*:" + logger.LogDebug.String(), + } + // configurationFile defines a flag for the path to the main toml configuration file + configurationFile = cli.StringFlag{ + Name: "config", + Usage: "The `" + filePathPlaceholder + "` for the main configuration file. This TOML file contain the main " + + "configurations such as monitored SC, gateway URL, timings and so on", + Value: "config/config.toml", + } + // logFile is used when the log output needs to be logged in a file + logSaveFile = cli.BoolFlag{ + Name: "log-save", + Usage: "Boolean option for enabling log saving. If set, it will automatically save all the logs into a file.", + } + // profileMode defines a flag for profiling the binary + // If enabled, it will open the pprof routes over the default gin rest webserver. + // There are several routes that will be available for profiling (profiling can be analyzed with: go tool pprof): + // /debug/pprof/ (can be accessed in the browser, will list the available options) + // /debug/pprof/goroutine + // /debug/pprof/heap + // /debug/pprof/threadcreate + // /debug/pprof/block + // /debug/pprof/mutex + // /debug/pprof/profile (CPU profile) + // /debug/pprof/trace?seconds=5 (CPU trace) -> being a trace, can be analyzed with: go tool trace + // Usage: go tool pprof http(s)://ip.of.the.server/debug/pprof/xxxxx + profileMode = cli.BoolFlag{ + Name: "profile-mode", + Usage: "Boolean option for enabling the profiling mode. If set, the /debug/pprof routes will be available " + + "on the node for profiling the application.", + } + // restApiInterface defines a flag for the interface on which the rest API will try to bind with + restApiInterface = cli.StringFlag{ + Name: "rest-api-interface", + Usage: "The interface `address and port` to which the REST API will attempt to bind. " + + "To bind to all available interfaces, set this flag to :8080", + Value: facade.DefaultRestInterface, + } + // workingDirectory defines a flag for the path for the working directory. + workingDirectory = cli.StringFlag{ + Name: "working-directory", + Usage: "This flag specifies the `directory` where the node will store databases and logs.", + Value: "", + } + // disableAnsiColor defines if the logger subsystem should prevent displaying ANSI colors + disableAnsiColor = cli.BoolFlag{ + Name: "disable-ansi-color", + Usage: "Boolean option for disabling ANSI colors in the logging system.", + } + // logWithLoggerName is used to enable log correlation elements + logWithLoggerName = cli.BoolFlag{ + Name: "log-logger-name", + Usage: "Boolean option for logger name in the logs.", + } +) + +func getFlags() []cli.Flag { + return []cli.Flag{ + workingDirectory, + logLevel, + disableAnsiColor, + configurationFile, + logSaveFile, + logWithLoggerName, + profileMode, + restApiInterface, + } +} +func getFlagsConfig(ctx *cli.Context) config.ContextFlagsConfig { + flagsConfig := config.ContextFlagsConfig{} + + flagsConfig.WorkingDir = ctx.GlobalString(workingDirectory.Name) + flagsConfig.LogLevel = ctx.GlobalString(logLevel.Name) + flagsConfig.DisableAnsiColor = ctx.GlobalBool(disableAnsiColor.Name) + flagsConfig.ConfigurationFile = ctx.GlobalString(configurationFile.Name) + flagsConfig.SaveLogFile = ctx.GlobalBool(logSaveFile.Name) + flagsConfig.EnableLogName = ctx.GlobalBool(logWithLoggerName.Name) + flagsConfig.EnablePprof = ctx.GlobalBool(profileMode.Name) + flagsConfig.RestApiInterface = ctx.GlobalString(restApiInterface.Name) + + return flagsConfig +} diff --git a/cmd/scCallsExecutor/main.go b/cmd/scCallsExecutor/main.go new file mode 100644 index 00000000..abe4a413 --- /dev/null +++ b/cmd/scCallsExecutor/main.go @@ -0,0 +1,178 @@ +package main + +import ( + "fmt" + "os" + "os/signal" + "runtime" + "syscall" + "time" + + "github.com/multiversx/mx-bridge-eth-go/config" + "github.com/multiversx/mx-bridge-eth-go/executors/multiversx/module" + chainCore "github.com/multiversx/mx-chain-core-go/core" + "github.com/multiversx/mx-chain-core-go/core/check" + chainFactory "github.com/multiversx/mx-chain-go/cmd/node/factory" + chainCommon "github.com/multiversx/mx-chain-go/common" + logger "github.com/multiversx/mx-chain-logger-go" + "github.com/multiversx/mx-chain-logger-go/file" + "github.com/urfave/cli" +) + +const ( + filePathPlaceholder = "[path]" + defaultLogsPath = "logs" + logFilePrefix = "sc-calls-executor" +) + +var log = logger.GetOrCreate("main") + +// appVersion should be populated at build time using ldflags +// Usage examples: +// linux/mac: +// +// go build -i -v -ldflags="-X main.appVersion=$(git describe --tags --long --dirty)" +// +// windows: +// +// for /f %i in ('git describe --tags --long --dirty') do set VERS=%i +// go build -i -v -ldflags="-X main.appVersion=%VERS%" +var appVersion = chainCommon.UnVersionedAppString + +func main() { + app := cli.NewApp() + app.Name = "SC calls executor CLI app" + app.Usage = "This is the entry point for the module that periodically tries to execute SC calls" + app.Flags = getFlags() + machineID := chainCore.GetAnonymizedMachineID(app.Name) + app.Version = fmt.Sprintf("%s/%s/%s-%s/%s", appVersion, runtime.Version(), runtime.GOOS, runtime.GOARCH, machineID) + app.Authors = []cli.Author{ + { + Name: "The MultiversX Team", + Email: "contact@multiversx.com", + }, + } + + app.Action = func(c *cli.Context) error { + return startRelay(c, app.Version) + } + + err := app.Run(os.Args) + if err != nil { + log.Error(err.Error()) + os.Exit(1) + } +} + +func startRelay(ctx *cli.Context, version string) error { + flagsConfig := getFlagsConfig(ctx) + + fileLogging, errLogger := attachFileLogger(log, flagsConfig) + if errLogger != nil { + return errLogger + } + + log.Info("starting bridge node", "version", version, "pid", os.Getpid()) + + err := logger.SetLogLevel(flagsConfig.LogLevel) + if err != nil { + return err + } + + cfg, err := loadConfig(flagsConfig.ConfigurationFile) + if err != nil { + return err + } + + if !check.IfNil(fileLogging) { + timeLogLifeSpan := time.Second * time.Duration(cfg.Logs.LogFileLifeSpanInSec) + sizeLogLifeSpanInMB := uint64(cfg.Logs.LogFileLifeSpanInMB) + err = fileLogging.ChangeFileLifeSpan(timeLogLifeSpan, sizeLogLifeSpanInMB) + if err != nil { + return err + } + } + + if len(cfg.NetworkAddress) == 0 { + return fmt.Errorf("empty NetworkAddress in config file") + } + + args := config.ScCallsModuleConfig{ + ScProxyBech32Address: cfg.ScProxyBech32Address, + ExtraGasToExecute: cfg.ExtraGasToExecute, + NetworkAddress: cfg.NetworkAddress, + ProxyMaxNoncesDelta: cfg.ProxyMaxNoncesDelta, + ProxyFinalityCheck: cfg.ProxyFinalityCheck, + ProxyCacherExpirationSeconds: cfg.ProxyCacherExpirationSeconds, + ProxyRestAPIEntityType: cfg.ProxyRestAPIEntityType, + IntervalToResendTxsInSeconds: cfg.IntervalToResendTxsInSeconds, + PrivateKeyFile: cfg.PrivateKeyFile, + PollingIntervalInMillis: cfg.PollingIntervalInMillis, + FilterConfig: cfg.FilterConfig, + Logs: cfg.Logs, + } + + scCallsExecutor, err := module.NewScCallsModule(args, log) + if err != nil { + return err + } + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) + + <-sigs + + log.Info("application closing, calling Close on all subcomponents...") + + return scCallsExecutor.Close() +} + +func loadConfig(filepath string) (config.ScCallsModuleConfig, error) { + cfg := config.ScCallsModuleConfig{} + err := chainCore.LoadTomlFile(&cfg, filepath) + if err != nil { + return config.ScCallsModuleConfig{}, err + } + + return cfg, nil +} + +func attachFileLogger(log logger.Logger, flagsConfig config.ContextFlagsConfig) (chainFactory.FileLoggingHandler, error) { + var fileLogging chainFactory.FileLoggingHandler + var err error + if flagsConfig.SaveLogFile { + argsFileLogging := file.ArgsFileLogging{ + WorkingDir: flagsConfig.WorkingDir, + DefaultLogsPath: defaultLogsPath, + LogFilePrefix: logFilePrefix, + } + fileLogging, err = file.NewFileLogging(argsFileLogging) + if err != nil { + return nil, fmt.Errorf("%w creating a log file", err) + } + } + + err = logger.SetDisplayByteSlice(logger.ToHex) + log.LogIfError(err) + logger.ToggleLoggerName(flagsConfig.EnableLogName) + logLevelFlagValue := flagsConfig.LogLevel + err = logger.SetLogLevel(logLevelFlagValue) + if err != nil { + return nil, err + } + + if flagsConfig.DisableAnsiColor { + err = logger.RemoveLogObserver(os.Stdout) + if err != nil { + return nil, err + } + + err = logger.AddLogObserver(os.Stdout, &logger.PlainFormatter{}) + if err != nil { + return nil, err + } + } + log.Trace("logger updated", "level", logLevelFlagValue, "disable ANSI color", flagsConfig.DisableAnsiColor) + + return fileLogging, nil +} diff --git a/clients/batch.go b/common/batch.go similarity index 99% rename from clients/batch.go rename to common/batch.go index 8ec7c15e..eeeb817d 100644 --- a/clients/batch.go +++ b/common/batch.go @@ -1,4 +1,4 @@ -package clients +package common import ( "encoding/hex" diff --git a/clients/batch_test.go b/common/batch_test.go similarity index 99% rename from clients/batch_test.go rename to common/batch_test.go index 3927d6f5..421e6431 100644 --- a/clients/batch_test.go +++ b/common/batch_test.go @@ -1,4 +1,4 @@ -package clients +package common import ( "math/big" diff --git a/clients/constants.go b/common/constants.go similarity index 90% rename from clients/constants.go rename to common/constants.go index d03f2b2f..aa7b9dd8 100644 --- a/clients/constants.go +++ b/common/constants.go @@ -1,4 +1,4 @@ -package clients +package common const ( // Executed is the Executed with success status value diff --git a/config/config.go b/config/config.go index 08eda4c3..c653fe9d 100644 --- a/config/config.go +++ b/config/config.go @@ -195,4 +195,5 @@ type ScCallsModuleConfig struct { PrivateKeyFile string PollingIntervalInMillis uint64 FilterConfig PendingOperationsFilterConfig + Logs LogsConfig } diff --git a/config/tomlConfigs_test.go b/config/tomlConfigs_test.go index 465152bd..e5a8ba23 100644 --- a/config/tomlConfigs_test.go +++ b/config/tomlConfigs_test.go @@ -391,3 +391,59 @@ func TestConfigs(t *testing.T) { require.Nil(t, err) require.Equal(t, expectedConfig, cfg) } + +func TestScCallsExecutorConfigs(t *testing.T) { + t.Parallel() + + expectedConfig := ScCallsModuleConfig{ + ScProxyBech32Address: "erd1qqqqqqqqqqqqqpgqnef5f5aq32d63kljld8w5vnvz4gk5sy9hrrq2ld08s", + ExtraGasToExecute: 50000000, + NetworkAddress: "127.0.0.1:8085", + ProxyMaxNoncesDelta: 7, + ProxyFinalityCheck: true, + ProxyCacherExpirationSeconds: 600, + ProxyRestAPIEntityType: "observer", + IntervalToResendTxsInSeconds: 60, + PrivateKeyFile: "keys/multiversx.pem", + PollingIntervalInMillis: 6000, + FilterConfig: PendingOperationsFilterConfig{ + AllowedEthAddresses: []string{"*"}, + AllowedMvxAddresses: []string{"*"}, + AllowedTokens: []string{"MEME-a43fa1"}, + }, + Logs: LogsConfig{ + LogFileLifeSpanInSec: 86400, + LogFileLifeSpanInMB: 1024, + }, + } + + testString := ` +ScProxyBech32Address = "erd1qqqqqqqqqqqqqpgqnef5f5aq32d63kljld8w5vnvz4gk5sy9hrrq2ld08s" +ExtraGasToExecute = 50000000 +NetworkAddress = "127.0.0.1:8085" +ProxyMaxNoncesDelta = 7 +ProxyFinalityCheck = true +ProxyCacherExpirationSeconds = 600 +ProxyRestAPIEntityType = "observer" +IntervalToResendTxsInSeconds = 60 +PrivateKeyFile = "keys/multiversx.pem" +PollingIntervalInMillis = 6000 + +[FilterConfig] + AllowedEthAddresses = ["*"] # execute SC calls from all ETH addresses + AllowedMvxAddresses = ["*"] # execute SC calls to all MvX contracts + AllowedTokens = ["MEME-a43fa1"] # execute SC calls for this token only + +[Logs] + LogFileLifeSpanInSec = 86400 # 24h + LogFileLifeSpanInMB = 1024 # 1GB +` + + cfg := ScCallsModuleConfig{} + + err := toml.Unmarshal([]byte(testString), &cfg) + + require.Nil(t, err) + require.Equal(t, expectedConfig, cfg) + +} diff --git a/core/batchProcessor/batchProcessor.go b/core/batchProcessor/batchProcessor.go index f65cb56a..d7b4bea1 100644 --- a/core/batchProcessor/batchProcessor.go +++ b/core/batchProcessor/batchProcessor.go @@ -4,7 +4,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" ) // Direction is the direction of the transfer @@ -29,7 +29,7 @@ type ArgListsBatch struct { // ExtractListMvxToEth will extract the batch data into a format that is easy to use // The transfer is from MultiversX to Ethereum -func ExtractListMvxToEth(batch *clients.TransferBatch) *ArgListsBatch { +func ExtractListMvxToEth(batch *bridgeCommon.TransferBatch) *ArgListsBatch { arg := &ArgListsBatch{ Direction: FromMultiversX, } @@ -55,7 +55,7 @@ func ExtractListMvxToEth(batch *clients.TransferBatch) *ArgListsBatch { // ExtractListEthToMvx will extract the batch data into a format that is easy to use // The transfer is from Ehtereum to MultiversX -func ExtractListEthToMvx(batch *clients.TransferBatch) *ArgListsBatch { +func ExtractListEthToMvx(batch *bridgeCommon.TransferBatch) *ArgListsBatch { arg := &ArgListsBatch{ Direction: ToMultiversX, } diff --git a/core/batchProcessor/batchProcessor_test.go b/core/batchProcessor/batchProcessor_test.go index cb308032..48104fb0 100644 --- a/core/batchProcessor/batchProcessor_test.go +++ b/core/batchProcessor/batchProcessor_test.go @@ -5,16 +5,16 @@ import ( "testing" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/stretchr/testify/assert" ) func TestExtractListEthToMvx(t *testing.T) { t.Parallel() - testBatch := &clients.TransferBatch{ + testBatch := &bridgeCommon.TransferBatch{ ID: 37, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: 1, ToBytes: []byte("to 1"), @@ -71,9 +71,9 @@ func TestExtractListEthToMvx(t *testing.T) { func TestExtractListMvxToEth(t *testing.T) { t.Parallel() - testBatch := &clients.TransferBatch{ + testBatch := &bridgeCommon.TransferBatch{ ID: 37, - Deposits: []*clients.DepositTransfer{ + Deposits: []*bridgeCommon.DepositTransfer{ { Nonce: 1, ToBytes: []byte("to 1"), diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index a7b970f1..243e9a32 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -2,7 +2,7 @@ version: "3.9" services: multiversx: - image: multiversx/chainsimulator:v1.7.13-fix2 + image: multiversx/chainsimulator:v1.7.13-fix3 ports: - 8085:8085 volumes: diff --git a/integrationTests/mock/multiversXContractStateMock.go b/integrationTests/mock/multiversXContractStateMock.go index d6d11b17..8c69bd34 100644 --- a/integrationTests/mock/multiversXContractStateMock.go +++ b/integrationTests/mock/multiversXContractStateMock.go @@ -1,6 +1,7 @@ package mock import ( + "encoding/binary" "encoding/hex" "fmt" "math/big" @@ -8,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/multiversx/mx-bridge-eth-go/integrationTests" + "github.com/multiversx/mx-bridge-eth-go/parsers" "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-core-go/data/vm" @@ -15,6 +17,13 @@ import ( "github.com/multiversx/mx-sdk-go/data" ) +const ( + lenToField = 32 + lenFromField = 20 + lenUint32 = 4 + lenUint64 = 8 +) + type multiversXProposedStatus struct { BatchId *big.Int Statuses []byte @@ -170,46 +179,11 @@ func (mock *multiversXContractStateMock) createProposedTransfer(dataSplit []stri BatchId: big.NewInt(0).SetBytes(buff), } - currentIndex := 2 - for currentIndex < len(dataSplit) { - from, errDecode := hex.DecodeString(dataSplit[currentIndex]) - if errDecode != nil { - panic(errDecode) - } - - to, errDecode := hex.DecodeString(dataSplit[currentIndex+1]) - if errDecode != nil { - panic(errDecode) - } - - amountBytes, errDecode := hex.DecodeString(dataSplit[currentIndex+3]) - if errDecode != nil { - panic(errDecode) - } - - nonceBytes, errDecode := hex.DecodeString(dataSplit[currentIndex+4]) - if errDecode != nil { - panic(errDecode) - } - - dataBytes, errDecode := hex.DecodeString(dataSplit[currentIndex+5]) - if errDecode != nil { - panic(errDecode) - } - - t := Transfer{ - From: from, - To: to, - Token: dataSplit[currentIndex+2], - Amount: big.NewInt(0).SetBytes(amountBytes), - Nonce: big.NewInt(0).SetBytes(nonceBytes), - Data: dataBytes, - } - - indexIncrementValue := 6 - + depositsBuff, _ := hex.DecodeString(dataSplit[2]) + for len(depositsBuff) > 0 { + var t Transfer + t, depositsBuff = mock.decodeDeposit(depositsBuff) transfer.Transfers = append(transfer.Transfers, t) - currentIndex += indexIncrementValue } hash, err := core.CalculateHash(integrationTests.TestMarshalizer, integrationTests.TestHasher, transfer) @@ -223,6 +197,49 @@ func (mock *multiversXContractStateMock) createProposedTransfer(dataSplit []stri return transfer, string(hash) } +func (mock *multiversXContractStateMock) decodeDeposit(buff []byte) (Transfer, []byte) { + from := buff[:lenFromField] + buff = buff[lenFromField:] + + to := buff[:lenToField] + buff = buff[lenToField:] + + lenTokenBytes := buff[:lenUint32] + buff = buff[lenUint32:] + lenToken := int(binary.BigEndian.Uint32(lenTokenBytes)) + token := buff[:lenToken] + buff = buff[lenToken:] + + lenAmountBytes := buff[:lenUint32] + buff = buff[lenUint32:] + lenAmount := int(binary.BigEndian.Uint32(lenAmountBytes)) + amount := big.NewInt(0).SetBytes(buff[:lenAmount]) + buff = buff[lenAmount:] + + nonceBytes := buff[:lenUint64] + buff = buff[lenUint64:] + nonce := binary.BigEndian.Uint64(nonceBytes) + + codec := &parsers.MultiversxCodec{} + callData, _ := codec.DecodeCallData(buff) + var reconstructedCallData []byte + if callData.Type == parsers.MissingDataProtocolMarker { + reconstructedCallData = []byte{parsers.MissingDataProtocolMarker} + } else { + reconstructedCallData = codec.EncodeCallData(callData) + } + buff = buff[len(reconstructedCallData):] + + return Transfer{ + Nonce: big.NewInt(0).SetUint64(nonce), + To: to, + From: from, + Token: hex.EncodeToString(token), + Amount: amount, + Data: reconstructedCallData, + }, buff +} + func (mock *multiversXContractStateMock) processVmRequests(vmRequest *data.VmValueRequest) (*data.VmValuesResponseData, error) { if vmRequest == nil { panic("vmRequest is nil") diff --git a/integrationTests/relayers/ethToMultiversX_test.go b/integrationTests/relayers/ethToMultiversX_test.go index 0d9ac3fd..d9bbaabe 100644 --- a/integrationTests/relayers/ethToMultiversX_test.go +++ b/integrationTests/relayers/ethToMultiversX_test.go @@ -12,8 +12,8 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/multiversx/mx-bridge-eth-go/clients" "github.com/multiversx/mx-bridge-eth-go/clients/ethereum/contract" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/config" "github.com/multiversx/mx-bridge-eth-go/core" "github.com/multiversx/mx-bridge-eth-go/factory" @@ -131,7 +131,7 @@ func testRelayersShouldExecuteTransfersFromEthToMultiversX(t *testing.T, withNat multiversXChainMock.SetLastExecutedEthBatchID(batchNonceOnEthereum) multiversXChainMock.SetLastExecutedEthTxId(txNonceOnEthereum) multiversXChainMock.GetStatusesAfterExecutionHandler = func() []byte { - return []byte{clients.Executed, clients.Rejected} + return []byte{bridgeCommon.Executed, bridgeCommon.Rejected} } multiversXChainMock.SetQuorum(numRelayers) @@ -323,7 +323,7 @@ func testRelayersShouldExecuteTransferFromEthToMultiversXHavingTxsWithSCcalls(t multiversXChainMock.SetLastExecutedEthBatchID(batchNonceOnEthereum) multiversXChainMock.SetLastExecutedEthTxId(txNonceOnEthereum) multiversXChainMock.GetStatusesAfterExecutionHandler = func() []byte { - return []byte{clients.Executed, clients.Rejected, clients.Executed} + return []byte{bridgeCommon.Executed, bridgeCommon.Rejected, bridgeCommon.Executed} } multiversXChainMock.SetQuorum(numRelayers) diff --git a/integrationTests/relayers/multiversXToEth_test.go b/integrationTests/relayers/multiversXToEth_test.go index bc92d734..84afeb0d 100644 --- a/integrationTests/relayers/multiversXToEth_test.go +++ b/integrationTests/relayers/multiversXToEth_test.go @@ -12,7 +12,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/factory" "github.com/multiversx/mx-bridge-eth-go/integrationTests" "github.com/multiversx/mx-bridge-eth-go/integrationTests/mock" @@ -45,7 +45,7 @@ func TestRelayersShouldExecuteSimpleTransfersFromMultiversXToEth(t *testing.T) { numRelayers := 3 ethereumChainMock := mock.NewEthereumChainMock() ethereumChainMock.SetQuorum(numRelayers) - expectedStatuses := []byte{clients.Executed, clients.Rejected} + expectedStatuses := []byte{bridgeCommon.Executed, bridgeCommon.Rejected} ethereumChainMock.GetStatusesAfterExecutionHandler = func() ([]byte, bool) { if callIsFromBalanceValidator() { // statuses can not be final at this point as the batch was not executed yet @@ -142,7 +142,7 @@ func testRelayersShouldExecuteTransfersFromMultiversXToEthIfTransactionsAppearIn numRelayers := 3 ethereumChainMock := mock.NewEthereumChainMock() ethereumChainMock.SetQuorum(numRelayers) - expectedStatuses := []byte{clients.Executed, clients.Rejected} + expectedStatuses := []byte{bridgeCommon.Executed, bridgeCommon.Rejected} ethereumChainMock.GetStatusesAfterExecutionHandler = func() ([]byte, bool) { if callIsFromBalanceValidator() { // statuses can not be final at this point as the batch was not executed yet diff --git a/integrationTests/relayers/slowTests/common.go b/integrationTests/relayers/slowTests/common.go new file mode 100644 index 00000000..e05f3463 --- /dev/null +++ b/integrationTests/relayers/slowTests/common.go @@ -0,0 +1,107 @@ +//go:build slow + +package slowTests + +import ( + "math/big" + + "github.com/multiversx/mx-bridge-eth-go/integrationTests/relayers/slowTests/framework" +) + +// GenerateTestUSDCToken will generate a test USDC token +func GenerateTestUSDCToken() framework.TestTokenParams { + // USDC is ethNative = true, ethMintBurn = false, mvxNative = false, mvxMintBurn = true + return framework.TestTokenParams{ + IssueTokenParams: framework.IssueTokenParams{ + AbstractTokenIdentifier: "USDC", + NumOfDecimalsUniversal: 6, + NumOfDecimalsChainSpecific: 6, + MvxUniversalTokenTicker: "USDC", + MvxChainSpecificTokenTicker: "ETHUSDC", + MvxUniversalTokenDisplayName: "WrappedUSDC", + MvxChainSpecificTokenDisplayName: "EthereumWrappedUSDC", + ValueToMintOnMvx: "10000000000", + IsMintBurnOnMvX: true, + IsNativeOnMvX: false, + EthTokenName: "ETHTOKEN", + EthTokenSymbol: "ETHT", + ValueToMintOnEth: "10000000000", + IsMintBurnOnEth: false, + IsNativeOnEth: true, + }, + TestOperations: []framework.TokenOperations{ + { + ValueToTransferToMvx: big.NewInt(5000), + ValueToSendFromMvX: big.NewInt(2500), + MvxSCCallMethod: "", + MvxSCCallGasLimit: 0, + MvxSCCallArguments: nil, + }, + { + ValueToTransferToMvx: big.NewInt(7000), + ValueToSendFromMvX: big.NewInt(300), + MvxSCCallMethod: "", + MvxSCCallGasLimit: 0, + MvxSCCallArguments: nil, + }, + { + ValueToTransferToMvx: big.NewInt(1000), + ValueToSendFromMvX: nil, + MvxSCCallMethod: "callPayable", + MvxSCCallGasLimit: 50000000, + MvxSCCallArguments: nil, + }, + }, + ESDTSafeExtraBalance: big.NewInt(100), // extra is just for the fees for the 2 transfers mvx->eth + EthTestAddrExtraBalance: big.NewInt(-5000 + 2500 - 50 - 7000 + 300 - 50 - 1000), // -(eth->mvx) + (mvx->eth) - fees + } +} + +// GenerateTestMEMEToken will generate a test MEME token +func GenerateTestMEMEToken() framework.TestTokenParams { + //MEME is ethNative = false, ethMintBurn = true, mvxNative = true, mvxMintBurn = false + return framework.TestTokenParams{ + IssueTokenParams: framework.IssueTokenParams{ + AbstractTokenIdentifier: "MEME", + NumOfDecimalsUniversal: 1, + NumOfDecimalsChainSpecific: 1, + MvxUniversalTokenTicker: "MEME", + MvxChainSpecificTokenTicker: "ETHMEME", + MvxUniversalTokenDisplayName: "WrappedMEME", + MvxChainSpecificTokenDisplayName: "EthereumWrappedMEME", + ValueToMintOnMvx: "10000000000", + IsMintBurnOnMvX: false, + IsNativeOnMvX: true, + EthTokenName: "ETHMEME", + EthTokenSymbol: "ETHM", + ValueToMintOnEth: "10000000000", + IsMintBurnOnEth: true, + IsNativeOnEth: false, + }, + TestOperations: []framework.TokenOperations{ + { + ValueToTransferToMvx: big.NewInt(2400), + ValueToSendFromMvX: big.NewInt(4000), + MvxSCCallMethod: "", + MvxSCCallGasLimit: 0, + MvxSCCallArguments: nil, + }, + { + ValueToTransferToMvx: big.NewInt(200), + ValueToSendFromMvX: big.NewInt(6000), + MvxSCCallMethod: "", + MvxSCCallGasLimit: 0, + MvxSCCallArguments: nil, + }, + { + ValueToTransferToMvx: big.NewInt(1000), + ValueToSendFromMvX: big.NewInt(2000), + MvxSCCallMethod: "callPayable", + MvxSCCallGasLimit: 50000000, + MvxSCCallArguments: nil, + }, + }, + ESDTSafeExtraBalance: big.NewInt(4000 + 6000 + 2000), // everything is locked in the safe esdt contract + EthTestAddrExtraBalance: big.NewInt(4000 - 50 + 6000 - 50 + 2000 - 50), + } +} diff --git a/integrationTests/relayers/slowTests/ethToMultiversXWithChainSimulator_test.go b/integrationTests/relayers/slowTests/ethToMultiversXWithChainSimulator_test.go index b78271ff..4c155882 100644 --- a/integrationTests/relayers/slowTests/ethToMultiversXWithChainSimulator_test.go +++ b/integrationTests/relayers/slowTests/ethToMultiversXWithChainSimulator_test.go @@ -27,101 +27,15 @@ const ( var ( log = logger.GetOrCreate("integrationTests/relayers/slowTests") - //MEME is ethNative = false, ethMintBurn = true, mvxNative = true, mvxMintBurn = false - memeToken = framework.TestTokenParams{ - IssueTokenParams: framework.IssueTokenParams{ - AbstractTokenIdentifier: "MEME", - NumOfDecimalsUniversal: 1, - NumOfDecimalsChainSpecific: 1, - MvxUniversalTokenTicker: "MEME", - MvxChainSpecificTokenTicker: "ETHMEME", - MvxUniversalTokenDisplayName: "WrappedMEME", - MvxChainSpecificTokenDisplayName: "EthereumWrappedMEME", - ValueToMintOnMvx: "10000000000", - IsMintBurnOnMvX: false, - IsNativeOnMvX: true, - EthTokenName: "ETHMEME", - EthTokenSymbol: "ETHM", - ValueToMintOnEth: "10000000000", - IsMintBurnOnEth: true, - IsNativeOnEth: false, - }, - TestOperations: []framework.TokenOperations{ - { - ValueToTransferToMvx: big.NewInt(2400), - ValueToSendFromMvX: big.NewInt(4000), - MvxSCCallMethod: "", - MvxSCCallGasLimit: 0, - MvxSCCallArguments: nil, - }, - { - ValueToTransferToMvx: big.NewInt(200), - ValueToSendFromMvX: big.NewInt(6000), - MvxSCCallMethod: "", - MvxSCCallGasLimit: 0, - MvxSCCallArguments: nil, - }, - { - ValueToTransferToMvx: big.NewInt(1000), - ValueToSendFromMvX: big.NewInt(2000), - MvxSCCallMethod: "callPayable", - MvxSCCallGasLimit: 50000000, - MvxSCCallArguments: nil, - }, - }, - ESDTSafeExtraBalance: big.NewInt(4000 + 6000 + 2000), // everything is locked in the safe esdt contract - EthTestAddrExtraBalance: big.NewInt(4000 - 50 + 6000 - 50 + 2000 - 50), - } ) func TestRelayersShouldExecuteTransfers(t *testing.T) { - // USDC is ethNative = true, ethMintBurn = false, mvxNative = false, mvxMintBurn = true - usdcToken := framework.TestTokenParams{ - IssueTokenParams: framework.IssueTokenParams{ - AbstractTokenIdentifier: "USDC", - NumOfDecimalsUniversal: 6, - NumOfDecimalsChainSpecific: 6, - MvxUniversalTokenTicker: "USDC", - MvxChainSpecificTokenTicker: "ETHUSDC", - MvxUniversalTokenDisplayName: "WrappedUSDC", - MvxChainSpecificTokenDisplayName: "EthereumWrappedUSDC", - ValueToMintOnMvx: "10000000000", - IsMintBurnOnMvX: true, - IsNativeOnMvX: false, - EthTokenName: "ETHTOKEN", - EthTokenSymbol: "ETHT", - ValueToMintOnEth: "10000000000", - IsMintBurnOnEth: false, - IsNativeOnEth: true, - }, - TestOperations: []framework.TokenOperations{ - { - ValueToTransferToMvx: big.NewInt(5000), - ValueToSendFromMvX: big.NewInt(2500), - MvxSCCallMethod: "", - MvxSCCallGasLimit: 0, - MvxSCCallArguments: nil, - }, - { - ValueToTransferToMvx: big.NewInt(7000), - ValueToSendFromMvX: big.NewInt(300), - MvxSCCallMethod: "", - MvxSCCallGasLimit: 0, - MvxSCCallArguments: nil, - }, - { - ValueToTransferToMvx: big.NewInt(1000), - ValueToSendFromMvX: nil, - MvxSCCallMethod: "callPayable", - MvxSCCallGasLimit: 50000000, - MvxSCCallArguments: nil, - }, - }, - ESDTSafeExtraBalance: big.NewInt(100), // extra is just for the fees for the 2 transfers mvx->eth - EthTestAddrExtraBalance: big.NewInt(-5000 + 2500 - 50 - 7000 + 300 - 50 - 1000), // -(eth->mvx) + (mvx->eth) - fees - } - - testRelayersWithChainSimulatorAndTokens(t, make(chan error), usdcToken, memeToken) + testRelayersWithChainSimulatorAndTokens( + t, + make(chan error), + GenerateTestUSDCToken(), + GenerateTestMEMEToken(), + ) } func TestRelayerShouldExecuteTransfersAndNotCatchErrors(t *testing.T) { @@ -149,7 +63,11 @@ func TestRelayerShouldExecuteTransfersAndNotCatchErrors(t *testing.T) { } }() - testRelayersWithChainSimulatorAndTokens(t, stopChan, memeToken) + testRelayersWithChainSimulatorAndTokens( + t, + stopChan, + GenerateTestMEMEToken(), + ) } func testRelayersWithChainSimulatorAndTokens(tb testing.TB, manualStopChan chan error, tokens ...framework.TestTokenParams) { diff --git a/integrationTests/relayers/slowTests/framework/chainSimulatorWrapper.go b/integrationTests/relayers/slowTests/framework/chainSimulatorWrapper.go index 663aab11..1a9e027c 100644 --- a/integrationTests/relayers/slowTests/framework/chainSimulatorWrapper.go +++ b/integrationTests/relayers/slowTests/framework/chainSimulatorWrapper.go @@ -121,7 +121,7 @@ func (instance *chainSimulatorWrapper) GetNetworkAddress() string { } // DeploySC will deploy the provided smart contract and return its address -func (instance *chainSimulatorWrapper) DeploySC(ctx context.Context, wasmFilePath string, ownerSK []byte, parameters []string) (*MvxAddress, string, *data.TransactionOnNetwork) { +func (instance *chainSimulatorWrapper) DeploySC(ctx context.Context, wasmFilePath string, ownerSK []byte, gasLimit uint64, parameters []string) (*MvxAddress, string, *data.TransactionOnNetwork) { networkConfig, err := instance.proxyInstance.GetNetworkConfig(ctx) require.Nil(instance.TB, err) @@ -140,7 +140,7 @@ func (instance *chainSimulatorWrapper) DeploySC(ctx context.Context, wasmFilePat Receiver: emptyAddress, Sender: ownerPK, GasPrice: networkConfig.MinGasPrice, - GasLimit: 600000000, + GasLimit: gasLimit, Data: []byte(txData), ChainID: networkConfig.ChainID, Version: 1, @@ -204,16 +204,16 @@ func (instance *chainSimulatorWrapper) getTxInfoWithResultsIfTxProcessingFinishe } // ScCall will make the provided sc call -func (instance *chainSimulatorWrapper) ScCall(ctx context.Context, senderSK []byte, contract *MvxAddress, value string, function string, parameters []string) (string, *data.TransactionOnNetwork) { +func (instance *chainSimulatorWrapper) ScCall(ctx context.Context, senderSK []byte, contract *MvxAddress, value string, gasLimit uint64, function string, parameters []string) (string, *data.TransactionOnNetwork) { params := []string{function} params = append(params, parameters...) txData := strings.Join(params, "@") - return instance.SendTx(ctx, senderSK, contract, value, []byte(txData)) + return instance.SendTx(ctx, senderSK, contract, value, gasLimit, []byte(txData)) } // SendTx will build and send a transaction -func (instance *chainSimulatorWrapper) SendTx(ctx context.Context, senderSK []byte, receiver *MvxAddress, value string, dataField []byte) (string, *data.TransactionOnNetwork) { +func (instance *chainSimulatorWrapper) SendTx(ctx context.Context, senderSK []byte, receiver *MvxAddress, value string, gasLimit uint64, dataField []byte) (string, *data.TransactionOnNetwork) { networkConfig, err := instance.proxyInstance.GetNetworkConfig(ctx) require.Nil(instance, err) @@ -227,7 +227,7 @@ func (instance *chainSimulatorWrapper) SendTx(ctx context.Context, senderSK []by Receiver: receiver.Bech32(), Sender: senderPK, GasPrice: networkConfig.MinGasPrice, - GasLimit: 600000000, + GasLimit: gasLimit, Data: dataField, ChainID: networkConfig.ChainID, Version: 1, diff --git a/integrationTests/relayers/slowTests/framework/interface.go b/integrationTests/relayers/slowTests/framework/interface.go index d0c39dd5..b2638085 100644 --- a/integrationTests/relayers/slowTests/framework/interface.go +++ b/integrationTests/relayers/slowTests/framework/interface.go @@ -31,9 +31,9 @@ type Relayer interface { type ChainSimulatorWrapper interface { Proxy() multiversx.Proxy GetNetworkAddress() string - DeploySC(ctx context.Context, path string, ownerSK []byte, extraParams []string) (*MvxAddress, string, *data.TransactionOnNetwork) - ScCall(ctx context.Context, senderSK []byte, contract *MvxAddress, value string, function string, parameters []string) (string, *data.TransactionOnNetwork) - SendTx(ctx context.Context, senderSK []byte, receiver *MvxAddress, value string, dataField []byte) (string, *data.TransactionOnNetwork) + DeploySC(ctx context.Context, path string, ownerSK []byte, gasLimit uint64, extraParams []string) (*MvxAddress, string, *data.TransactionOnNetwork) + ScCall(ctx context.Context, senderSK []byte, contract *MvxAddress, value string, gasLimit uint64, function string, parameters []string) (string, *data.TransactionOnNetwork) + SendTx(ctx context.Context, senderSK []byte, receiver *MvxAddress, value string, gasLimit uint64, dataField []byte) (string, *data.TransactionOnNetwork) FundWallets(ctx context.Context, wallets []string) GenerateBlocksUntilEpochReached(ctx context.Context, epoch uint32) GenerateBlocks(ctx context.Context, numBlocks int) diff --git a/integrationTests/relayers/slowTests/framework/multiversxHandler.go b/integrationTests/relayers/slowTests/framework/multiversxHandler.go index 8464b163..3aabc2a7 100644 --- a/integrationTests/relayers/slowTests/framework/multiversxHandler.go +++ b/integrationTests/relayers/slowTests/framework/multiversxHandler.go @@ -27,6 +27,11 @@ const ( hexFalse = "00" gwei = "GWEI" maxBridgedAmountForToken = "500000" + deployGasLimit = 150000000 // 150 million + setCallsGasLimit = 80000000 // 80 million + issueTokenGasLimit = 70000000 // 70 million + createDepositGasLimit = 20000000 // 20 million + gasLimitPerDataByte = 1500 aggregatorContractPath = "testdata/contracts/mvx/aggregator.wasm" wrapperContractPath = "testdata/contracts/mvx/bridged-tokens-wrapper.wasm" @@ -40,6 +45,7 @@ const ( setWrappingContractAddressFunction = "setWrappingContractAddress" changeOwnerAddressFunction = "ChangeOwnerAddress" setEsdtSafeOnMultiTransferFunction = "setEsdtSafeOnMultiTransfer" + setEsdtSafeOnWrapperFunction = "setEsdtSafeContractAddress" stakeFunction = "stake" unpauseFunction = "unpause" unpauseEsdtSafeFunction = "unpauseEsdtSafe" @@ -59,6 +65,7 @@ const ( submitBatchFunction = "submitBatch" createTransactionFunction = "createTransaction" unwrapTokenFunction = "unwrapToken" + setupBridgedTokenWrapperFunction = "setBridgedTokensWrapper" ) var ( @@ -124,6 +131,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ctx, aggregatorContractPath, handler.OwnerKeys.MvxSk, + deployGasLimit, aggregatorDeployParams, ) require.NotEqual(handler, emptyAddress, handler.AggregatorAddress) @@ -134,6 +142,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ctx, wrapperContractPath, handler.OwnerKeys.MvxSk, + deployGasLimit, []string{}, ) require.NotEqual(handler, emptyAddress, handler.WrapperAddress) @@ -144,6 +153,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ctx, multiTransferContractPath, handler.OwnerKeys.MvxSk, + deployGasLimit, []string{}, ) require.NotEqual(handler, emptyAddress, multiTransferAddress) @@ -154,6 +164,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ctx, safeContractPath, handler.OwnerKeys.MvxSk, + deployGasLimit, []string{ handler.AggregatorAddress.Hex(), multiTransferAddress.Hex(), @@ -179,6 +190,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ctx, multisigContractPath, handler.OwnerKeys.MvxSk, + deployGasLimit, params, ) require.NotEqual(handler, emptyAddress, handler.MultisigAddress) @@ -189,6 +201,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ctx, bridgeProxyContractPath, handler.OwnerKeys.MvxSk, + deployGasLimit, []string{ multiTransferAddress.Hex(), }, @@ -201,6 +214,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ctx, testCallerContractPath, handler.OwnerKeys.MvxSk, + deployGasLimit, []string{}, ) require.NotEqual(handler, emptyAddress, handler.TestCallerAddress) @@ -212,6 +226,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { handler.OwnerKeys.MvxSk, multiTransferAddress, zeroStringValue, + setCallsGasLimit, setBridgeProxyContractAddressFunction, []string{ handler.ScProxyAddress.Hex(), @@ -225,6 +240,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { handler.OwnerKeys.MvxSk, multiTransferAddress, zeroStringValue, + setCallsGasLimit, setWrappingContractAddressFunction, []string{ handler.WrapperAddress.Hex(), @@ -232,12 +248,41 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { ) log.Info("setWrappingContractAddress tx executed", "hash", hash, "status", txResult.Status) + // setBridgedTokensWrapper in SC bridge proxy + hash, txResult = handler.ChainSimulator.ScCall( + ctx, + handler.OwnerKeys.MvxSk, + handler.ScProxyAddress, + zeroStringValue, + setCallsGasLimit, + setupBridgedTokenWrapperFunction, + []string{ + handler.WrapperAddress.Hex(), + }, + ) + log.Info("setupEsdtSafe in SC bridge proxy tx executed", "hash", hash, "status", txResult.Status) + + // setEsdtSafeOnWrapper + hash, txResult = handler.ChainSimulator.ScCall( + ctx, + handler.OwnerKeys.MvxSk, + handler.WrapperAddress, + zeroStringValue, + setCallsGasLimit, + setEsdtSafeOnWrapperFunction, + []string{ + handler.SafeAddress.Hex(), + }, + ) + log.Info("setEsdtSafeOnWrapper tx executed", "hash", hash, "status", txResult.Status) + // ChangeOwnerAddress for safe hash, txResult = handler.ChainSimulator.ScCall( ctx, handler.OwnerKeys.MvxSk, handler.SafeAddress, zeroStringValue, + setCallsGasLimit, changeOwnerAddressFunction, []string{ handler.MultisigAddress.Hex(), @@ -251,6 +296,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { handler.OwnerKeys.MvxSk, multiTransferAddress, zeroStringValue, + setCallsGasLimit, changeOwnerAddressFunction, []string{ handler.MultisigAddress.Hex(), @@ -268,6 +314,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { handler.OwnerKeys.MvxSk, handler.ScProxyAddress, zeroStringValue, + setCallsGasLimit, changeOwnerAddressFunction, []string{ handler.MultisigAddress.Hex(), @@ -281,6 +328,7 @@ func (handler *MultiversxHandler) DeployContracts(ctx context.Context) { handler.OwnerKeys.MvxSk, handler.MultisigAddress, zeroStringValue, + setCallsGasLimit, setEsdtSafeOnMultiTransferFunction, []string{}, ) @@ -355,6 +403,7 @@ func (handler *MultiversxHandler) callContractNoParams(ctx context.Context, cont handler.OwnerKeys.MvxSk, contract, zeroStringValue, + setCallsGasLimit, endpoint, []string{}, ) @@ -392,7 +441,14 @@ func (handler *MultiversxHandler) PauseContractsForTokenChanges(ctx context.Cont func (handler *MultiversxHandler) stakeAddressesOnContract(ctx context.Context, contract *MvxAddress, allKeys []KeysHolder) { for _, keys := range allKeys { - hash, txResult := handler.ChainSimulator.SendTx(ctx, keys.MvxSk, contract, minRelayerStake, []byte(stakeFunction)) + hash, txResult := handler.ChainSimulator.SendTx( + ctx, + keys.MvxSk, + contract, + minRelayerStake, + setCallsGasLimit, + []byte(stakeFunction), + ) log.Info(fmt.Sprintf("address %s staked on contract %s with hash %s, status %s", keys.MvxAddress, contract, hash, txResult.Status)) } } @@ -410,6 +466,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, esdtAddress, esdtIssueCost, + issueTokenGasLimit, issueFunction, []string{ hex.EncodeToString([]byte(params.MvxUniversalTokenDisplayName)), @@ -419,6 +476,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa hex.EncodeToString([]byte(canAddSpecialRoles)), hex.EncodeToString([]byte(trueStr))}) mvxUniversalToken := handler.getTokenNameFromResult(*txResult) + require.Greater(handler, len(mvxUniversalToken), 0) handler.TokensRegistry.RegisterUniversalToken(params.AbstractTokenIdentifier, mvxUniversalToken) log.Info("issue universal token tx executed", "hash", hash, "status", txResult.Status, "token", mvxUniversalToken, "owner", handler.OwnerKeys.MvxAddress) @@ -431,6 +489,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, esdtAddress, esdtIssueCost, + issueTokenGasLimit, issueFunction, []string{ hex.EncodeToString([]byte(params.MvxChainSpecificTokenDisplayName)), @@ -440,6 +499,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa hex.EncodeToString([]byte(canAddSpecialRoles)), hex.EncodeToString([]byte(trueStr))}) mvxChainSpecificToken := handler.getTokenNameFromResult(*txResult) + require.Greater(handler, len(mvxChainSpecificToken), 0) handler.TokensRegistry.RegisterChainSpecificToken(params.AbstractTokenIdentifier, mvxChainSpecificToken) log.Info("issue chain specific token tx executed", "hash", hash, "status", txResult.Status, "token", mvxChainSpecificToken, "owner", handler.OwnerKeys.MvxAddress) @@ -449,6 +509,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, esdtAddress, zeroStringValue, + setCallsGasLimit, setSpecialRoleFunction, []string{ hex.EncodeToString([]byte(mvxUniversalToken)), @@ -464,6 +525,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.WrapperAddress, zeroStringValue, + setCallsGasLimit, esdtTransferFunction, []string{ hex.EncodeToString([]byte(mvxChainSpecificToken)), @@ -477,6 +539,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.SafeAddress, zeroStringValue, + setCallsGasLimit, esdtTransferFunction, []string{ hex.EncodeToString([]byte(mvxChainSpecificToken)), @@ -489,6 +552,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.WrapperAddress, zeroStringValue, + setCallsGasLimit, addWrappedTokenFunction, []string{ hex.EncodeToString([]byte(mvxUniversalToken)), @@ -502,6 +566,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.WrapperAddress, zeroStringValue, + setCallsGasLimit, whitelistTokenFunction, []string{ hex.EncodeToString([]byte(mvxChainSpecificToken)), @@ -515,6 +580,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, esdtAddress, zeroStringValue, + setCallsGasLimit, setSpecialRoleFunction, []string{ hex.EncodeToString([]byte(mvxChainSpecificToken)), @@ -529,6 +595,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.MultisigAddress, zeroStringValue, + setCallsGasLimit, addMappingFunction, []string{ hex.EncodeToString(token.EthErc20Address.Bytes()), @@ -541,6 +608,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.MultisigAddress, zeroStringValue, + setCallsGasLimit, esdtSafeAddTokenToWhitelistFunction, []string{ hex.EncodeToString([]byte(mvxChainSpecificToken)), @@ -555,6 +623,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.AggregatorAddress, zeroStringValue, + setCallsGasLimit, setPairDecimalsFunction, []string{ hex.EncodeToString([]byte(gwei)), @@ -569,6 +638,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.MultisigAddress, zeroStringValue, + setCallsGasLimit, esdtSafeSetMaxBridgedAmountForTokenFunction, []string{ hex.EncodeToString([]byte(mvxChainSpecificToken)), @@ -581,6 +651,7 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa handler.OwnerKeys.MvxSk, handler.MultisigAddress, zeroStringValue, + setCallsGasLimit, multiTransferEsdtSetMaxBridgedAmountForTokenFunction, []string{ hex.EncodeToString([]byte(mvxChainSpecificToken)), @@ -589,16 +660,16 @@ func (handler *MultiversxHandler) IssueAndWhitelistToken(ctx context.Context, pa } func (handler *MultiversxHandler) getTokenNameFromResult(txResult data.TransactionOnNetwork) string { - resultData := txResult.ScResults[0].Data - splittedData := strings.Split(resultData, "@") - if len(splittedData) < 2 { - require.Fail(handler, fmt.Sprintf("received invalid data received while issuing: %s", resultData)) - } + for _, event := range txResult.Logs.Events { + if event.Identifier == issueFunction { + require.Greater(handler, len(event.Topics), 1) - newUniversalTokenBytes, err := hex.DecodeString(splittedData[1]) - require.NoError(handler, err) + return string(event.Topics[0]) + } + } - return string(newUniversalTokenBytes) + require.Fail(handler, "did not find the event with the issue identifier") + return "" } // SubmitAggregatorBatch will submit the aggregator batch @@ -613,6 +684,7 @@ func (handler *MultiversxHandler) SubmitAggregatorBatch(ctx context.Context, par handler.OwnerKeys.MvxSk, handler.AggregatorAddress, zeroStringValue, + setCallsGasLimit, submitBatchFunction, []string{ hex.EncodeToString([]byte(gwei)), @@ -645,6 +717,7 @@ func (handler *MultiversxHandler) CreateDepositsOnMultiversxForToken( handler.OwnerKeys.MvxSk, handler.TestKeys.MvxAddress, zeroStringValue, + createDepositGasLimit, esdtTransferFunction, []string{ hex.EncodeToString([]byte(token.MvxChainSpecificToken)), @@ -658,11 +731,14 @@ func (handler *MultiversxHandler) CreateDepositsOnMultiversxForToken( hex.EncodeToString([]byte(createTransactionFunction)), hex.EncodeToString(handler.TestKeys.EthAddress.Bytes()), } + dataField := strings.Join(scCallParams, "@") + hash, txResult = handler.ChainSimulator.ScCall( ctx, handler.TestKeys.MvxSk, handler.SafeAddress, zeroStringValue, + createDepositGasLimit+gasLimitPerDataByte*uint64(len(dataField)), esdtTransferFunction, scCallParams) log.Info("MultiversX->Ethereum transaction sent", "hash", hash, "status", txResult.Status) @@ -686,6 +762,7 @@ func (handler *MultiversxHandler) SendDepositTransactionFromMultiversx(ctx conte handler.TestKeys.MvxSk, handler.WrapperAddress, zeroStringValue, + createDepositGasLimit, esdtTransferFunction, paramsUnwrap, ) @@ -698,12 +775,14 @@ func (handler *MultiversxHandler) SendDepositTransactionFromMultiversx(ctx conte hex.EncodeToString([]byte(createTransactionFunction)), hex.EncodeToString(handler.TestKeys.EthAddress.Bytes()), } + dataField := strings.Join(params, "@") hash, txResult = handler.ChainSimulator.ScCall( ctx, handler.TestKeys.MvxSk, handler.SafeAddress, zeroStringValue, + createDepositGasLimit+gasLimitPerDataByte*uint64(len(dataField)), esdtTransferFunction, params) log.Info("MultiversX->Ethereum transaction sent", "hash", hash, "status", txResult.Status) diff --git a/integrationTests/relayers/slowTests/framework/testSetup.go b/integrationTests/relayers/slowTests/framework/testSetup.go index 3901d40e..afc2009c 100644 --- a/integrationTests/relayers/slowTests/framework/testSetup.go +++ b/integrationTests/relayers/slowTests/framework/testSetup.go @@ -45,6 +45,7 @@ type TestSetup struct { ethBalanceTestAddress map[string]*big.Int } +// NewTestSetup creates a new e2e test setup func NewTestSetup(tb testing.TB) *TestSetup { log.Info(fmt.Sprintf(LogStepMarker, "starting setup")) @@ -109,7 +110,7 @@ func (setup *TestSetup) StartRelayersAndScModule() { func (setup *TestSetup) startScCallerModule() { cfg := config.ScCallsModuleConfig{ ScProxyBech32Address: setup.MultiversxHandler.ScProxyAddress.Bech32(), - ExtraGasToExecute: 20_000_000, // 20 million + ExtraGasToExecute: 30_000_000, // 30 million (50 mil call -> provided + 20 mil callback + 10 mil extra) NetworkAddress: setup.ChainSimulator.GetNetworkAddress(), ProxyMaxNoncesDelta: 5, ProxyFinalityCheck: false, @@ -184,7 +185,9 @@ func (setup *TestSetup) isTransferDoneFromEthereumForToken(params TestTokenParam } if len(operation.MvxSCCallMethod) > 0 { - expectedValueOnContract.Add(expectedValueOnContract, operation.ValueToTransferToMvx) + if !operation.MvxFaultySCCall { + expectedValueOnContract.Add(expectedValueOnContract, operation.ValueToTransferToMvx) + } } else { expectedValueOnReceiver.Add(expectedValueOnReceiver, operation.ValueToTransferToMvx) } @@ -199,6 +202,45 @@ func (setup *TestSetup) isTransferDoneFromEthereumForToken(params TestTokenParam return contractBalance.String() == expectedValueOnContract.String() } +// IsTransferDoneFromEthereumWithRefund returns true if all provided tokens are bridged from Ethereum towards MultiversX including refunds +func (setup *TestSetup) IsTransferDoneFromEthereumWithRefund(tokens ...TestTokenParams) bool { + isDone := true + for _, params := range tokens { + isDone = isDone && setup.isTransferDoneFromEthereumWithRefundForToken(params) + } + + return isDone +} + +func (setup *TestSetup) isTransferDoneFromEthereumWithRefundForToken(params TestTokenParams) bool { + expectedValueOnReceiver := big.NewInt(0) + for _, operation := range params.TestOperations { + valueToTransferToMvx := big.NewInt(0) + if operation.ValueToTransferToMvx != nil { + valueToTransferToMvx.Set(operation.ValueToTransferToMvx) + } + + valueToSendFromMvX := big.NewInt(0) + if operation.ValueToSendFromMvX != nil { + valueToSendFromMvX.Set(operation.ValueToSendFromMvX) + // we subtract the fee also + expectedValueOnReceiver.Sub(expectedValueOnReceiver, feeInt) + } + + expectedValueOnReceiver.Add(expectedValueOnReceiver, big.NewInt(0).Sub(valueToSendFromMvX, valueToTransferToMvx)) + if len(operation.MvxSCCallMethod) > 0 { + if operation.MvxFaultySCCall { + // the balance should be bridged back to the receiver on Ethereum - fee + expectedValueOnReceiver.Add(expectedValueOnReceiver, valueToTransferToMvx) + expectedValueOnReceiver.Sub(expectedValueOnReceiver, feeInt) + } + } + } + + receiverBalance := setup.EthereumHandler.GetBalance(setup.TestKeys.EthAddress, params.AbstractTokenIdentifier) + return receiverBalance.String() == expectedValueOnReceiver.String() +} + // IsTransferDoneFromMultiversX returns true if all provided tokens are bridged from MultiversX towards Ethereum func (setup *TestSetup) IsTransferDoneFromMultiversX(tokens ...TestTokenParams) bool { isDone := true diff --git a/integrationTests/relayers/slowTests/framework/types.go b/integrationTests/relayers/slowTests/framework/types.go index 22f2b8a1..61697ba4 100644 --- a/integrationTests/relayers/slowTests/framework/types.go +++ b/integrationTests/relayers/slowTests/framework/types.go @@ -36,6 +36,7 @@ type TokenOperations struct { MvxSCCallMethod string MvxSCCallGasLimit uint64 MvxSCCallArguments []string + MvxFaultySCCall bool } // TestTokenParams defines a token collection of operations in one or 2 batches diff --git a/integrationTests/relayers/slowTests/refundWithChainSimulator_test.go b/integrationTests/relayers/slowTests/refundWithChainSimulator_test.go new file mode 100644 index 00000000..b582d94a --- /dev/null +++ b/integrationTests/relayers/slowTests/refundWithChainSimulator_test.go @@ -0,0 +1,68 @@ +//go:build slow + +// To run these slow tests, simply add the slow tag on the go test command. Also, provide a chain simulator instance on the 8085 port +// example: go test -tags slow + +package slowTests + +import ( + "math/big" + "testing" + + "github.com/multiversx/mx-bridge-eth-go/integrationTests/relayers/slowTests/framework" +) + +func TestRelayersShouldExecuteTransfersWithRefund(t *testing.T) { + usdcToken := GenerateTestUSDCToken() + usdcToken.TestOperations[2].MvxSCCallMethod = "unknownFunction" + usdcToken.TestOperations[2].MvxFaultySCCall = true + usdcToken.EthTestAddrExtraBalance = big.NewInt(-5000 + 2500 - 50 - 7000 + 300 - 50 - 1000 + 950) // -(eth->mvx) + (mvx->eth) - fees + revert after bad SC call + usdcToken.ESDTSafeExtraBalance = big.NewInt(150) // extra is just for the fees for the 2 transfers mvx->eth and the failed eth->mvx that needed refund + + memeToken := GenerateTestMEMEToken() + memeToken.TestOperations[2].MvxSCCallMethod = "unknownFunction" + memeToken.TestOperations[2].MvxFaultySCCall = true + + testRelayersWithChainSimulatorAndTokensAndRefund( + t, + make(chan error), + usdcToken, + memeToken, + ) +} + +func testRelayersWithChainSimulatorAndTokensAndRefund(tb testing.TB, manualStopChan chan error, tokens ...framework.TestTokenParams) { + startsFromEthFlow, startsFromMvXFlow := createFlowsBasedOnToken(tb, tokens...) + + setupFunc := func(tb testing.TB, setup *framework.TestSetup) { + startsFromMvXFlow.setup = setup + startsFromEthFlow.setup = setup + + setup.IssueAndConfigureTokens(tokens...) + setup.MultiversxHandler.CheckForZeroBalanceOnReceivers(setup.Ctx, tokens...) + if len(startsFromEthFlow.tokens) > 0 { + setup.EthereumHandler.CreateBatchOnEthereum(setup.Ctx, setup.MultiversxHandler.TestCallerAddress, startsFromEthFlow.tokens...) + } + if len(startsFromMvXFlow.tokens) > 0 { + setup.CreateBatchOnMultiversX(startsFromMvXFlow.tokens...) + } + } + + processFunc := func(tb testing.TB, setup *framework.TestSetup) bool { + if startsFromEthFlow.process() && startsFromMvXFlow.process() && startsFromMvXFlow.areTokensFullyRefunded() { + return true + } + + // commit blocks in order to execute incoming txs from relayers + setup.EthereumHandler.SimulatedChain.Commit() + setup.ChainSimulator.GenerateBlocks(setup.Ctx, 1) + + return false + } + + testRelayersWithChainSimulator(tb, + setupFunc, + processFunc, + manualStopChan, + ) +} diff --git a/integrationTests/relayers/slowTests/startsFromEthereumFlow.go b/integrationTests/relayers/slowTests/startsFromEthereumFlow.go index e61963b2..76c13fe1 100644 --- a/integrationTests/relayers/slowTests/startsFromEthereumFlow.go +++ b/integrationTests/relayers/slowTests/startsFromEthereumFlow.go @@ -3,6 +3,7 @@ package slowTests import ( + "fmt" "testing" "github.com/multiversx/mx-bridge-eth-go/integrationTests/relayers/slowTests/framework" @@ -27,7 +28,7 @@ func (flow *startsFromEthereumFlow) process() (finished bool) { isTransferDoneFromEthereum := flow.setup.IsTransferDoneFromEthereum(flow.tokens...) if !flow.ethToMvxDone && isTransferDoneFromEthereum { flow.ethToMvxDone = true - log.Info("Ethereum->MultiversX transfer finished, now sending back to Ethereum...") + log.Info(fmt.Sprintf(framework.LogStepMarker, "Ethereum->MultiversX transfer finished, now sending back to Ethereum...")) flow.setup.SendFromMultiversxToEthereum(flow.tokens...) } @@ -39,7 +40,7 @@ func (flow *startsFromEthereumFlow) process() (finished bool) { isTransferDoneFromMultiversX := flow.setup.IsTransferDoneFromMultiversX(flow.tokens...) if !flow.mvxToEthDone && isTransferDoneFromMultiversX { flow.mvxToEthDone = true - log.Info("MultiversX<->Ethereum transfers done") + log.Info(fmt.Sprintf(framework.LogStepMarker, "MultiversX<->Ethereum from Ethereum transfers done")) return true } diff --git a/integrationTests/relayers/slowTests/startsFromMultiversxFlow.go b/integrationTests/relayers/slowTests/startsFromMultiversxFlow.go index 85c8fea3..caa4dd06 100644 --- a/integrationTests/relayers/slowTests/startsFromMultiversxFlow.go +++ b/integrationTests/relayers/slowTests/startsFromMultiversxFlow.go @@ -3,6 +3,7 @@ package slowTests import ( + "fmt" "testing" "github.com/multiversx/mx-bridge-eth-go/integrationTests/relayers/slowTests/framework" @@ -27,7 +28,7 @@ func (flow *startsFromMultiversXFlow) process() (finished bool) { isTransferDoneFromMultiversX := flow.setup.IsTransferDoneFromMultiversX(flow.tokens...) if !flow.mvxToEthDone && isTransferDoneFromMultiversX { flow.mvxToEthDone = true - log.Info("MultiversX->Ethereum transfer finished, now sending back to MultiversX...") + log.Info(fmt.Sprintf(framework.LogStepMarker, "MultiversX->Ethereum transfer finished, now sending back to MultiversX...")) flow.setup.EthereumHandler.SendFromEthereumToMultiversX(flow.setup.Ctx, flow.setup.MultiversxHandler.TestCallerAddress, flow.tokens...) } @@ -39,9 +40,20 @@ func (flow *startsFromMultiversXFlow) process() (finished bool) { isTransferDoneFromEthereum := flow.setup.IsTransferDoneFromEthereum(flow.tokens...) if !flow.ethToMvxDone && isTransferDoneFromEthereum { flow.ethToMvxDone = true - log.Info("MultiversX<->Ethereum transfers done") + log.Info(fmt.Sprintf(framework.LogStepMarker, "MultiversX<->Ethereum from MultiversX transfers done")) return true } return false } + +func (flow *startsFromMultiversXFlow) areTokensFullyRefunded() bool { + if len(flow.tokens) == 0 { + return true + } + if !flow.ethToMvxDone { + return false // regular flow is not completed + } + + return flow.setup.IsTransferDoneFromEthereumWithRefund(flow.tokens...) +} diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.abi.json b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.abi.json index bbc15c4e..5db4331c 100644 --- a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.abi.json +++ b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.abi.json @@ -1,11 +1,11 @@ { "buildInfo": { "rustc": { - "version": "1.78.0", - "commitHash": "9b00956e56009bab2aa15d7bff10916599e3d6d6", - "commitDate": "2024-04-29", + "version": "1.80.0", + "commitHash": "051478957371ee0084a7c0913941d2a8c4757bb9", + "commitDate": "2024-07-21", "channel": "Stable", - "short": "rustc 1.78.0 (9b00956e5 2024-04-29)" + "short": "rustc 1.80.0 (051478957 2024-07-21)" }, "contractCrate": { "name": "bridge-proxy", @@ -13,7 +13,7 @@ }, "framework": { "name": "multiversx-sc", - "version": "0.51.1" + "version": "0.52.2" } }, "name": "BridgeProxyContract", @@ -97,12 +97,12 @@ "outputs": [] }, { - "name": "setupEsdtSafe", + "name": "setBridgedTokensWrapper", "onlyOwner": true, "mutability": "mutable", "inputs": [ { - "name": "opt_esdt_safe_address", + "name": "opt_address", "type": "optional
", "multi_arg": true } @@ -120,7 +120,7 @@ ] }, { - "name": "getEsdtSafeAddress", + "name": "getBridgedTokensWrapperAddress", "mutability": "readonly", "inputs": [], "outputs": [ @@ -160,23 +160,6 @@ "esdtAttributes": [], "hasCallback": false, "types": { - "CallData": { - "type": "struct", - "fields": [ - { - "name": "endpoint", - "type": "bytes" - }, - { - "name": "gas_limit", - "type": "u64" - }, - { - "name": "args", - "type": "List" - } - ] - }, "EthAddress": { "type": "struct", "docs": [ @@ -214,7 +197,7 @@ }, { "name": "call_data", - "type": "Option" + "type": "Option" } ] } diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.wasm b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.wasm index 7f7d4abe..3549ae01 100755 Binary files a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.wasm and b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridge-proxy.wasm differ diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.abi.json b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.abi.json index 50b78b7f..249c77c0 100644 --- a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.abi.json +++ b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.abi.json @@ -1,11 +1,11 @@ { "buildInfo": { "rustc": { - "version": "1.78.0", - "commitHash": "9b00956e56009bab2aa15d7bff10916599e3d6d6", - "commitDate": "2024-04-29", + "version": "1.80.0", + "commitHash": "051478957371ee0084a7c0913941d2a8c4757bb9", + "commitDate": "2024-07-21", "channel": "Stable", - "short": "rustc 1.78.0 (9b00956e5 2024-04-29)" + "short": "rustc 1.80.0 (051478957 2024-07-21)" }, "contractCrate": { "name": "bridged-tokens-wrapper", @@ -13,7 +13,7 @@ }, "framework": { "name": "multiversx-sc", - "version": "0.51.1" + "version": "0.52.2" } }, "name": "BridgedTokensWrapper", @@ -157,6 +157,37 @@ ], "outputs": [] }, + { + "name": "unwrapTokenCreateTransaction", + "mutability": "mutable", + "payableInTokens": [ + "*" + ], + "inputs": [ + { + "name": "requested_token", + "type": "TokenIdentifier" + }, + { + "name": "to", + "type": "EthAddress" + } + ], + "outputs": [] + }, + { + "name": "setEsdtSafeContractAddress", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [ + { + "name": "opt_new_address", + "type": "optional
", + "multi_arg": true + } + ], + "outputs": [] + }, { "name": "getUniversalBridgedTokenIds", "mutability": "readonly", @@ -214,6 +245,16 @@ } ] }, + { + "name": "getEsdtSafeContractAddress", + "mutability": "readonly", + "inputs": [], + "outputs": [ + { + "type": "Address" + } + ] + }, { "name": "pause", "onlyOwner": true, @@ -290,6 +331,18 @@ "type": "BigUint" } ] + }, + "EthAddress": { + "type": "struct", + "docs": [ + "Wrapper over a 20-byte array" + ], + "fields": [ + { + "name": "raw_addr", + "type": "array20" + } + ] } } } diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.wasm b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.wasm index c7035a99..615c5f77 100755 Binary files a/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.wasm and b/integrationTests/relayers/slowTests/testdata/contracts/mvx/bridged-tokens-wrapper.wasm differ diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.abi.json b/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.abi.json index 7287cf24..bef93d51 100644 --- a/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.abi.json +++ b/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.abi.json @@ -1,11 +1,11 @@ { "buildInfo": { "rustc": { - "version": "1.78.0", - "commitHash": "9b00956e56009bab2aa15d7bff10916599e3d6d6", - "commitDate": "2024-04-29", + "version": "1.80.0", + "commitHash": "051478957371ee0084a7c0913941d2a8c4757bb9", + "commitDate": "2024-07-21", "channel": "Stable", - "short": "rustc 1.78.0 (9b00956e5 2024-04-29)" + "short": "rustc 1.80.0 (051478957 2024-07-21)" }, "contractCrate": { "name": "esdt-safe", @@ -13,7 +13,7 @@ }, "framework": { "name": "multiversx-sc", - "version": "0.51.1" + "version": "0.52.2" } }, "name": "EsdtSafe", diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.wasm b/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.wasm index cc847201..95f39fe7 100755 Binary files a/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.wasm and b/integrationTests/relayers/slowTests/testdata/contracts/mvx/esdt-safe.wasm differ diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.abi.json b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.abi.json index b2952983..16b24e0f 100644 --- a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.abi.json +++ b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.abi.json @@ -1,11 +1,11 @@ { "buildInfo": { "rustc": { - "version": "1.78.0", - "commitHash": "9b00956e56009bab2aa15d7bff10916599e3d6d6", - "commitDate": "2024-04-29", + "version": "1.80.0", + "commitHash": "051478957371ee0084a7c0913941d2a8c4757bb9", + "commitDate": "2024-07-21", "channel": "Stable", - "short": "rustc 1.78.0 (9b00956e5 2024-04-29)" + "short": "rustc 1.80.0 (051478957 2024-07-21)" }, "contractCrate": { "name": "multi-transfer-esdt", @@ -13,7 +13,7 @@ }, "framework": { "name": "multiversx-sc", - "version": "0.51.1" + "version": "0.52.2" } }, "name": "MultiTransferEsdt", @@ -37,8 +37,7 @@ }, { "name": "transfers", - "type": "variadic", - "multi_arg": true + "type": "List" } ], "outputs": [] @@ -383,23 +382,6 @@ } ] }, - "CallData": { - "type": "struct", - "fields": [ - { - "name": "endpoint", - "type": "bytes" - }, - { - "name": "gas_limit", - "type": "u64" - }, - { - "name": "args", - "type": "List" - } - ] - }, "EthAddress": { "type": "struct", "docs": [ @@ -437,7 +419,7 @@ }, { "name": "call_data", - "type": "Option" + "type": "Option" } ] } diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.wasm b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.wasm index d342e28e..9a8de4ca 100755 Binary files a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.wasm and b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multi-transfer-esdt.wasm differ diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.abi.json b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.abi.json index 506b882f..efab9d6d 100644 --- a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.abi.json +++ b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.abi.json @@ -1,11 +1,11 @@ { "buildInfo": { "rustc": { - "version": "1.78.0", - "commitHash": "9b00956e56009bab2aa15d7bff10916599e3d6d6", - "commitDate": "2024-04-29", + "version": "1.80.0", + "commitHash": "051478957371ee0084a7c0913941d2a8c4757bb9", + "commitDate": "2024-07-21", "channel": "Stable", - "short": "rustc 1.78.0 (9b00956e5 2024-04-29)" + "short": "rustc 1.80.0 (051478957 2024-07-21)" }, "contractCrate": { "name": "multisig", @@ -13,7 +13,7 @@ }, "framework": { "name": "multiversx-sc", - "version": "0.51.1" + "version": "0.52.2" } }, "docs": [ @@ -144,8 +144,7 @@ }, { "name": "transfers", - "type": "variadic>>", - "multi_arg": true + "type": "List" } ], "outputs": [ @@ -848,8 +847,7 @@ }, { "name": "transfers", - "type": "variadic>>", - "multi_arg": true + "type": "List" } ], "outputs": [ @@ -873,8 +871,7 @@ }, { "name": "transfers", - "type": "variadic>>", - "multi_arg": true + "type": "List" } ], "outputs": [ @@ -1204,23 +1201,6 @@ } ] }, - "CallData": { - "type": "struct", - "fields": [ - { - "name": "endpoint", - "type": "bytes" - }, - { - "name": "gas_limit", - "type": "u64" - }, - { - "name": "args", - "type": "List" - } - ] - }, "EthAddress": { "type": "struct", "docs": [ @@ -1258,7 +1238,7 @@ }, { "name": "call_data", - "type": "Option" + "type": "Option" } ] }, diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.wasm b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.wasm index 23981a3c..779cdb07 100755 Binary files a/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.wasm and b/integrationTests/relayers/slowTests/testdata/contracts/mvx/multisig.wasm differ diff --git a/integrationTests/relayers/slowTests/testdata/contracts/mvx/test-caller.abi.json b/integrationTests/relayers/slowTests/testdata/contracts/mvx/test-caller.abi.json index 8bc2b7e0..43eeab2d 100644 --- a/integrationTests/relayers/slowTests/testdata/contracts/mvx/test-caller.abi.json +++ b/integrationTests/relayers/slowTests/testdata/contracts/mvx/test-caller.abi.json @@ -1,11 +1,11 @@ { "buildInfo": { "rustc": { - "version": "1.78.0", - "commitHash": "9b00956e56009bab2aa15d7bff10916599e3d6d6", - "commitDate": "2024-04-29", + "version": "1.80.0", + "commitHash": "051478957371ee0084a7c0913941d2a8c4757bb9", + "commitDate": "2024-07-21", "channel": "Stable", - "short": "rustc 1.78.0 (9b00956e5 2024-04-29)" + "short": "rustc 1.80.0 (051478957 2024-07-21)" }, "contractCrate": { "name": "test-caller", @@ -13,7 +13,7 @@ }, "framework": { "name": "multiversx-sc", - "version": "0.51.1" + "version": "0.52.2" } }, "name": "TestCallerContract", diff --git a/parsers/errors.go b/parsers/errors.go index 857d6d9a..05b04b2b 100644 --- a/parsers/errors.go +++ b/parsers/errors.go @@ -8,10 +8,11 @@ var ( errBufferTooShortForLength = errors.New("buffer too short while extracting the length") errBufferTooShortForString = errors.New("buffer too short while extracting the string data") errBufferTooShortForUint64 = errors.New("buffer too short for uint64") - errBufferTooShortForNumArgs = errors.New("buffer too short for numArguments length") + errBufferTooShortForUint32 = errors.New("buffer too short for uint32 length") errNilAddressHandler = errors.New("nil address handler") errNilAmount = errors.New("nil amount") errBufferTooShortForEthAddress = errors.New("buffer too short for Ethereum address") errBufferTooShortForMvxAddress = errors.New("buffer too short for MultiversX address") errBufferTooShortForBigInt = errors.New("buffer too short while extracting the big.Int value") + errBufferLenMismatch = errors.New("buffer length mismatch") ) diff --git a/parsers/multiversxCodec.go b/parsers/multiversxCodec.go index fc4f7149..414f4105 100644 --- a/parsers/multiversxCodec.go +++ b/parsers/multiversxCodec.go @@ -6,6 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-chain-core-go/core/check" "github.com/multiversx/mx-sdk-go/data" ) @@ -17,12 +18,27 @@ type MultiversxCodec struct { // EncodeCallData will provide a valid data byte slice with encoded call data parameters func (codec *MultiversxCodec) EncodeCallData(callData CallData) []byte { initialAlloc := 1024 * 1024 // 1MB initial buffer + result := make([]byte, 0, initialAlloc) buff32Bits := make([]byte, 4) - buff64Bits := make([]byte, 8) + result = append(result, DataPresentProtocolMarker) // marker + + callDataBuff := codec.encodeInnerCallData(callData) + binary.BigEndian.PutUint32(buff32Bits, uint32(len(callDataBuff))) + + result = append(result, buff32Bits...) + result = append(result, callDataBuff...) + + return result +} + +func (codec *MultiversxCodec) encodeInnerCallData(callData CallData) []byte { + initialAlloc := 1024 * 1024 // 1MB initial buffer result := make([]byte, 0, initialAlloc) - result = append(result, DataPresentProtocolMarker) // marker + buff32Bits := make([]byte, 4) + buff64Bits := make([]byte, 8) + funcLen := len(callData.Function) binary.BigEndian.PutUint32(buff32Bits, uint32(funcLen)) @@ -33,6 +49,13 @@ func (codec *MultiversxCodec) EncodeCallData(callData CallData) []byte { result = append(result, buff64Bits...) // append the gas limit as 8 bytes + if len(callData.Arguments) == 0 { + // in case of no arguments, the contract requires that the missing data protocol marker should be provided, not + // a 0 encoded on 4 bytes. + result = append(result, MissingDataProtocolMarker) + return result + } + binary.BigEndian.PutUint32(buff32Bits, uint32(len(callData.Arguments))) result = append(result, buff32Bits...) // append the number of arguments @@ -57,28 +80,46 @@ func (codec *MultiversxCodec) EncodeProxySCCompleteCallData(completeData ProxySC } initialAlloc := 1024 * 1024 // 1MB initial buffer - buff32Bits := make([]byte, 4) - buff64Bits := make([]byte, 8) result := make([]byte, 0, initialAlloc) - result = append(result, completeData.From.Bytes()...) // append To - result = append(result, completeData.To.AddressBytes()...) // append From + result = append(result, completeData.From.Bytes()...) + result = append(result, completeData.To.AddressBytes()...) + result = append(result, encodeToken([]byte(completeData.Token))...) + result = append(result, encodeAmount(completeData.Amount)...) + result = append(result, encodeNonce(completeData.Nonce)...) + result = append(result, codec.EncodeCallData(completeData.CallData)...) + + return result, nil +} + +func encodeToken(token []byte) []byte { + result := make([]byte, 0, len(token)+4) + buff32Bits := make([]byte, 4) - binary.BigEndian.PutUint32(buff32Bits, uint32(len(completeData.Token))) - result = append(result, buff32Bits...) // append len(token) - result = append(result, completeData.Token...) // append token + binary.BigEndian.PutUint32(buff32Bits, uint32(len(token))) + result = append(result, buff32Bits...) // append len(token) + result = append(result, token...) // append token + + return result +} + +func encodeAmount(amount *big.Int) []byte { + buff32Bits := make([]byte, 4) + + amountBytes := big.NewInt(0).Set(amount).Bytes() + result := make([]byte, 0, len(amountBytes)+4) - amountBytes := big.NewInt(0).Set(completeData.Amount).Bytes() binary.BigEndian.PutUint32(buff32Bits, uint32(len(amountBytes))) result = append(result, buff32Bits...) // append len(amount) result = append(result, amountBytes...) // append amount - binary.BigEndian.PutUint64(buff64Bits, completeData.Nonce) - result = append(result, buff64Bits...) // append nonce - - result = append(result, codec.EncodeCallData(completeData.CallData)...) + return result +} - return result, nil +func encodeNonce(nonce uint64) []byte { + buff64Bits := make([]byte, 8) + binary.BigEndian.PutUint64(buff64Bits, nonce) + return buff64Bits } // DecodeCallData will try to decode the provided bytes into a CallData struct @@ -103,6 +144,14 @@ func (codec *MultiversxCodec) DecodeCallData(buff []byte) (CallData, error) { } func decodeCallData(buff []byte, marker byte) (CallData, error) { + buff, numChars, err := extractUint32(buff) + if err != nil { + return CallData{}, fmt.Errorf("%w for len of call data", err) + } + if numChars != len(buff) { + return CallData{}, fmt.Errorf("%w: actual %d, declared %d", errBufferLenMismatch, len(buff), numChars) + } + buff, function, err := extractString(buff) if err != nil { return CallData{}, fmt.Errorf("%w for function", err) @@ -113,28 +162,45 @@ func decodeCallData(buff []byte, marker byte) (CallData, error) { return CallData{}, fmt.Errorf("%w for gas limit", err) } - buff, numArgumentsLength, err := extractArgumentsLen(buff) + arguments, err := extractArguments(buff) if err != nil { return CallData{}, err } + return CallData{ + Type: marker, + Function: function, + GasLimit: gasLimit, + Arguments: arguments, + }, nil +} + +func extractArguments(buff []byte) ([]string, error) { + if len(buff) == 0 { + return nil, errBufferTooShortForMarker + } + if len(buff) == 1 && buff[0] == MissingDataProtocolMarker { + // no arguments provided + return make([]string, 0), nil + } + + buff, numArgumentsLength, err := extractUint32(buff) + if err != nil { + return nil, err + } + arguments := make([]string, 0) for i := 0; i < numArgumentsLength; i++ { var argument string buff, argument, err = extractString(buff) if err != nil { - return CallData{}, fmt.Errorf("%w for argument %d", err, i) + return nil, fmt.Errorf("%w for argument %d", err, i) } arguments = append(arguments, argument) } - return CallData{ - Type: marker, - Function: function, - GasLimit: gasLimit, - Arguments: arguments, - }, nil + return arguments, nil } func extractString(buff []byte) ([]byte, string, error) { @@ -175,25 +241,26 @@ func extractBigInt(buff []byte) ([]byte, *big.Int, error) { } func extractUint64(buff []byte) ([]byte, uint64, error) { - if len(buff) < uint64ArgBytes { // 8 bytes for gas limit + // Ensure there's enough length for the 8 bytes + if len(buff) < uint64ArgBytes { return nil, 0, errBufferTooShortForUint64 } - gasLimit := binary.BigEndian.Uint64(buff[:uint64ArgBytes]) + value := binary.BigEndian.Uint64(buff[:uint64ArgBytes]) buff = buff[uint64ArgBytes:] - return buff, gasLimit, nil + return buff, value, nil } -func extractArgumentsLen(buff []byte) ([]byte, int, error) { - // Ensure there's enough length for the 4 bytes for endpoint name length +func extractUint32(buff []byte) ([]byte, int, error) { + // Ensure there's enough length for the 4 bytes if len(buff) < uint32ArgBytes { - return nil, 0, errBufferTooShortForNumArgs + return nil, 0, errBufferTooShortForUint32 } - length := int(binary.BigEndian.Uint32(buff[:uint32ArgBytes])) + value := int(binary.BigEndian.Uint32(buff[:uint32ArgBytes])) buff = buff[uint32ArgBytes:] // remove the len bytes - return buff, length, nil + return buff, value, nil } // DecodeProxySCCompleteCallData will try to decode the provided bytes into a ProxySCCompleteCallData struct @@ -239,6 +306,42 @@ func (codec *MultiversxCodec) DecodeProxySCCompleteCallData(buff []byte) (ProxyS return result, nil } +// EncodeDeposits will encode the provided deposits as a byte slice +func (codec *MultiversxCodec) EncodeDeposits(deposits []*bridgeCommon.DepositTransfer) ([]byte, error) { + initialAlloc := 1024 * 1024 // 1MB initial buffer + result := make([]byte, 0, initialAlloc) + + for _, dt := range deposits { + buff, err := codec.encodeDeposit(dt) + if err != nil { + return nil, err + } + + result = append(result, buff...) + } + + return result, nil +} + +// encodeDeposit will provide a valid byte slice with the encoded fields of a deposit transfer +func (codec *MultiversxCodec) encodeDeposit(deposit *bridgeCommon.DepositTransfer) ([]byte, error) { + if deposit.Amount == nil { + return nil, errNilAmount + } + + initialAlloc := 1024 * 1024 // 1MB initial buffer + result := make([]byte, 0, initialAlloc) + + result = append(result, deposit.FromBytes...) + result = append(result, deposit.ToBytes...) + result = append(result, encodeToken(deposit.DestinationTokenBytes)...) + result = append(result, encodeAmount(deposit.Amount)...) + result = append(result, encodeNonce(deposit.Nonce)...) + result = append(result, deposit.Data...) + + return result, nil +} + // IsInterfaceNil returns true if there is no value under the interface func (codec *MultiversxCodec) IsInterfaceNil() bool { return codec == nil diff --git a/parsers/multiversxCodec_test.go b/parsers/multiversxCodec_test.go index 6591b47d..0310958e 100644 --- a/parsers/multiversxCodec_test.go +++ b/parsers/multiversxCodec_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-sdk-go/data" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -65,9 +66,10 @@ func TestMultiversXCodec_EncodeDecodeCallData(t *testing.T) { localCallData.Arguments = make([]string, 0) buff := codec.EncodeCallData(localCallData) - expectedBuff := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit - expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x00) // numArguments + expectedBuff := []byte{0x01, 0x00, 0x00, 0x00, 0x10} // num bytes for call data + expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c') // function + expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // gas limit + expectedBuff = append(expectedBuff, 0x00) // no arguments assert.Equal(t, expectedBuff, buff) callData, err := codec.DecodeCallData(buff) @@ -78,7 +80,8 @@ func TestMultiversXCodec_EncodeDecodeCallData(t *testing.T) { t.Parallel() buff := codec.EncodeCallData(testCallData) - expectedBuff := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} + expectedBuff := []byte{0x01, 0x00, 0x00, 0x00, 0x52} // num bytes for call data + expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c') // function expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x02) // numArguments expectedBuff = append(expectedBuff, 0x00, 0x00, 0x00, 0x05) // Argument 0 length @@ -152,7 +155,7 @@ func TestMultiversxCodec_DecodeCallData(t *testing.T) { t.Run("buffer contains missing data marker should work", func(t *testing.T) { t.Parallel() - buff := []byte{0x00} + buff := []byte{0} expectedCallData := CallData{ Type: MissingDataProtocolMarker, } @@ -161,10 +164,34 @@ func TestMultiversxCodec_DecodeCallData(t *testing.T) { assert.Nil(t, err) assert.Equal(t, expectedCallData, callData) }) + t.Run("buffer to short for call data length should error", func(t *testing.T) { + t.Parallel() + + buff := []byte{1} + + callData, err := codec.DecodeCallData(buff) + assert.ErrorIs(t, err, errBufferTooShortForUint32) + assert.Contains(t, err.Error(), "for len of call data") + assert.Equal(t, emptyCallData, callData) + }) + t.Run("buffer len for call data mismatch should error", func(t *testing.T) { + t.Parallel() + + buff := []byte{ + 1, + 0, 0, 0, 1} + + callData, err := codec.DecodeCallData(buff) + assert.ErrorIs(t, err, errBufferLenMismatch) + assert.Contains(t, err.Error(), "actual 0, declared 1") + assert.Equal(t, emptyCallData, callData) + }) t.Run("buffer to short for function length should error", func(t *testing.T) { t.Parallel() - buff := []byte{0x01} + buff := []byte{ + 1, + 0, 0, 0, 0} callData, err := codec.DecodeCallData(buff) assert.ErrorIs(t, err, errBufferTooShortForLength) @@ -174,7 +201,10 @@ func TestMultiversxCodec_DecodeCallData(t *testing.T) { t.Run("buffer to short for function should error", func(t *testing.T) { t.Parallel() - buff := []byte{0x01, 0x00, 0x00, 0x00, 0x05} + buff := []byte{ + 1, + 0, 0, 0, 4, + 0, 0, 0, 5} callData, err := codec.DecodeCallData(buff) assert.ErrorIs(t, err, errBufferTooShortForString) @@ -184,32 +214,58 @@ func TestMultiversxCodec_DecodeCallData(t *testing.T) { t.Run("buffer to short for gas limit should error", func(t *testing.T) { t.Parallel() - buff := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - buff = append(buff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0) // malformed gas limit + buff := []byte{ + 1, + 0, 0, 0, 14, + 0, 0, 0, 3, 'a', 'b', 'c', + 0, 0, 0, 0, 0, 0, 0, // malformed gas limit (7 bytes for an uint64) + } callData, err := codec.DecodeCallData(buff) assert.ErrorIs(t, err, errBufferTooShortForUint64) assert.Contains(t, err.Error(), "for gas limit") assert.Equal(t, emptyCallData, callData) }) + t.Run("no num arguments should error", func(t *testing.T) { + t.Parallel() + + buff := []byte{ + 1, + 0, 0, 0, 15, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + } + + callData, err := codec.DecodeCallData(buff) + assert.ErrorIs(t, err, errBufferTooShortForMarker) + assert.Equal(t, emptyCallData, callData) + }) t.Run("buffer to short for num arguments should error", func(t *testing.T) { t.Parallel() - buff := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - buff = append(buff, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit - buff = append(buff, 0x00, 0x00, 0x03) // Bad numArgument + buff := []byte{ + 1, + 0, 0, 0, 18, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + 0, 0, 3, // bad numArgument + } callData, err := codec.DecodeCallData(buff) - assert.ErrorIs(t, err, errBufferTooShortForNumArgs) + assert.ErrorIs(t, err, errBufferTooShortForUint32) assert.Equal(t, emptyCallData, callData) }) t.Run("buffer to short for argument length should error", func(t *testing.T) { t.Parallel() - buff := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - buff = append(buff, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit - buff = append(buff, 0x00, 0x00, 0x00, 0x01) // numArguments - buff = append(buff, 0x00, 0x00, 0x04) // Bad Argument 0 length + buff := []byte{ + 1, + 0, 0, 0, 22, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + 0, 0, 0, 1, // numArguments + 0, 0, 4, // bad argument 0 length + } callData, err := codec.DecodeCallData(buff) assert.ErrorIs(t, err, errBufferTooShortForLength) @@ -219,11 +275,15 @@ func TestMultiversxCodec_DecodeCallData(t *testing.T) { t.Run("buffer to short for argument data should error", func(t *testing.T) { t.Parallel() - buff := []byte{0x01, 0x00, 0x00, 0x00, 0x03, 'a', 'b', 'c'} - buff = append(buff, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit length - buff = append(buff, 0x00, 0x00, 0x00, 0x01) // numArguments - buff = append(buff, 0x00, 0x00, 0x00, 0x04) // Argument 0 length - buff = append(buff, 0x00, 0x00, 0x04) // Bad Argument 0 data + buff := []byte{ + 1, + 0, 0, 0, 26, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + 0, 0, 0, 1, // numArguments + 0, 0, 0, 4, // argument 0 length + 0, 0, 4, // bad argument 0 data + } callData, err := codec.DecodeCallData(buff) assert.ErrorIs(t, err, errBufferTooShortForString) @@ -281,8 +341,8 @@ func TestMultiversxCodec_EncodeProxySCCompleteCallData(t *testing.T) { t.Run("should work with function and no arguments", func(t *testing.T) { t.Parallel() - // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|-len-f-|--func-callPayable---|-gas-limit-50M-|-no-arg| - hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e200000000000000001010000000b63616c6c50617961626c650000000002faf08000000000" + // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|--len--|-len-f-|--func-callPayable---|-gas-limit-50M-|-no-arg| + hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e20000000000000000101000000180000000b63616c6c50617961626c650000000002faf08000" ethUnhexed, err := hex.DecodeString("880ec53af800b5cd051531672ef4fc4de233bd5d") require.Nil(t, err) @@ -312,8 +372,8 @@ func TestMultiversxCodec_EncodeProxySCCompleteCallData(t *testing.T) { t.Run("should work with function and with 2 arguments", func(t *testing.T) { t.Parallel() - // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|-len-f-|--func-callPayable---|-gas-limit-50M-|-no-arg|-arg0-l|-ABC-|-arg1-l|-DEFG--| - hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e200000000000000001010000000b63616c6c50617961626c650000000002faf08000000002000000034142430000000444454647" + // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|--len--|-len-f-|--func-callPayable---|-gas-limit-50M-|-no-arg|-arg0-l|-ABC-|-arg1-l|-DEFG--| + hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e200000000000000001010000002a0000000b63616c6c50617961626c650000000002faf08000000002000000034142430000000444454647" ethUnhexed, err := hex.DecodeString("880ec53af800b5cd051531672ef4fc4de233bd5d") require.Nil(t, err) @@ -346,8 +406,8 @@ func TestMultiversxCodec_EncodeProxySCCompleteCallData(t *testing.T) { t.Run("should work with no function and no arguments", func(t *testing.T) { t.Parallel() - // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|-len-f-|-gas-limit-50M-|-no-arg| - hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e20000000000000000101000000000000000002faf08000000000" + // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|--len--|-len-f-|-gas-limit-50M-|-no-arg| + hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e200000000000000001010000000d000000000000000002faf08000" completeCallData := createTestProxySCCompleteCallData() buff, err := hex.DecodeString(hexedData) require.Nil(t, err) @@ -457,8 +517,8 @@ func TestMultiversxCodec_DecodeProxySCCompleteCallData(t *testing.T) { t.Run("should work", func(t *testing.T) { t.Parallel() - // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|-len-f-|-gas-limit-50M-|-no-arg| - hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e20000000000000000101000000000000000002faf08000000000" + // |--------------FROM---------------------|---------------------TO----------------------------------------|-len-TK|------ETHUSDC-0ae8ee-------|-len-A-|20k|--tx-nonce=1---|M|--len--|-len-f-|-gas-limit-50M-|-no-arg| + hexedData := "880ec53af800b5cd051531672ef4fc4de233bd5d00000000000000000500871bc8f6332939a55a80b23012564523bea3291fa4370000000e455448555344432d306165386565000000024e200000000000000001010000000d000000000000000002faf08000" buff, err := hex.DecodeString(hexedData) require.Nil(t, err) @@ -468,3 +528,95 @@ func TestMultiversxCodec_DecodeProxySCCompleteCallData(t *testing.T) { assert.Nil(t, err) }) } + +func TestMultiversxCodec_EncodeDeposits(t *testing.T) { + t.Parallel() + + codec := MultiversxCodec{} + + t.Run("nil amount should error", func(t *testing.T) { + t.Parallel() + + testDeposits := []*bridgeCommon.DepositTransfer{ + { + Nonce: 1, + ToBytes: []byte("to1"), + FromBytes: []byte("from1"), + SourceTokenBytes: []byte("source token 1"), + DestinationTokenBytes: []byte("tkn1"), + Amount: nil, + Data: nil, + }, + } + + depositBytes, err := codec.EncodeDeposits(testDeposits) + assert.Nil(t, depositBytes) + assert.ErrorIs(t, err, errNilAmount) + }) + t.Run("should work", func(t *testing.T) { + t.Parallel() + + testDeposits := []*bridgeCommon.DepositTransfer{ + { + Nonce: 1, + ToBytes: []byte("to1"), + FromBytes: []byte("from1"), + SourceTokenBytes: []byte("source token 1"), + DestinationTokenBytes: []byte("tkn1"), + Amount: big.NewInt(111), + Data: nil, + }, + { + Nonce: 2, + ToBytes: []byte("to2"), + FromBytes: []byte("from2"), + SourceTokenBytes: []byte("source token 2"), + DestinationTokenBytes: []byte("tkn2"), + Amount: big.NewInt(222), + Data: []byte("data 2"), + }, + { + Nonce: 3, + ToBytes: []byte("to3"), + FromBytes: []byte("from3"), + SourceTokenBytes: []byte("source token 3"), + DestinationTokenBytes: []byte("tkn3"), + Amount: big.NewInt(333), + Data: []byte("data 3"), + }, + } + + deposit1Bytes := []byte{ + 'f', 'r', 'o', 'm', '1', + 't', 'o', '1', + 0, 0, 0, 4, 't', 'k', 'n', '1', + 0, 0, 0, 1, 111, + 0, 0, 0, 0, 0, 0, 0, 1, + } + + deposit2Bytes := []byte{ + 'f', 'r', 'o', 'm', '2', + 't', 'o', '2', + 0, 0, 0, 4, 't', 'k', 'n', '2', + 0, 0, 0, 1, 222, + 0, 0, 0, 0, 0, 0, 0, 2, + 'd', 'a', 't', 'a', ' ', '2', + } + + deposit3Bytes := []byte{ + 'f', 'r', 'o', 'm', '3', + 't', 'o', '3', + 0, 0, 0, 4, 't', 'k', 'n', '3', + 0, 0, 0, 2, 0x01, 0x4d, + 0, 0, 0, 0, 0, 0, 0, 3, + 'd', 'a', 't', 'a', ' ', '3', + } + + expectedBytes := append(deposit1Bytes, deposit2Bytes...) + expectedBytes = append(expectedBytes, deposit3Bytes...) + + depositBytes, err := codec.EncodeDeposits(testDeposits) + assert.Nil(t, err) + assert.Equal(t, expectedBytes, depositBytes) + }) +} diff --git a/testsCommon/bridge/bridgeExecutorStub.go b/testsCommon/bridge/bridgeExecutorStub.go index 67357c44..39d7138e 100644 --- a/testsCommon/bridge/bridgeExecutorStub.go +++ b/testsCommon/bridge/bridgeExecutorStub.go @@ -9,7 +9,7 @@ import ( "sync" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" logger "github.com/multiversx/mx-chain-logger-go" ) @@ -22,9 +22,9 @@ type BridgeExecutorStub struct { PrintInfoCalled func(logLevel logger.LogLevel, message string, extras ...interface{}) MyTurnAsLeaderCalled func() bool - GetBatchFromMultiversXCalled func(ctx context.Context) (*clients.TransferBatch, error) - StoreBatchFromMultiversXCalled func(batch *clients.TransferBatch) error - GetStoredBatchCalled func() *clients.TransferBatch + GetBatchFromMultiversXCalled func(ctx context.Context) (*bridgeCommon.TransferBatch, error) + StoreBatchFromMultiversXCalled func(batch *bridgeCommon.TransferBatch) error + GetStoredBatchCalled func() *bridgeCommon.TransferBatch GetLastExecutedEthBatchIDFromMultiversXCalled func(ctx context.Context) (uint64, error) VerifyLastDepositNonceExecutedOnEthereumBatchCalled func(ctx context.Context) error GetAndStoreActionIDForProposeTransferOnMultiversXCalled func(ctx context.Context) (uint64, error) @@ -86,7 +86,7 @@ func (stub *BridgeExecutorStub) MyTurnAsLeader() bool { } // GetBatchFromMultiversX - -func (stub *BridgeExecutorStub) GetBatchFromMultiversX(ctx context.Context) (*clients.TransferBatch, error) { +func (stub *BridgeExecutorStub) GetBatchFromMultiversX(ctx context.Context) (*bridgeCommon.TransferBatch, error) { stub.incrementFunctionCounter() if stub.GetBatchFromMultiversXCalled != nil { return stub.GetBatchFromMultiversXCalled(ctx) @@ -95,7 +95,7 @@ func (stub *BridgeExecutorStub) GetBatchFromMultiversX(ctx context.Context) (*cl } // StoreBatchFromMultiversX - -func (stub *BridgeExecutorStub) StoreBatchFromMultiversX(batch *clients.TransferBatch) error { +func (stub *BridgeExecutorStub) StoreBatchFromMultiversX(batch *bridgeCommon.TransferBatch) error { stub.incrementFunctionCounter() if stub.StoreBatchFromMultiversXCalled != nil { return stub.StoreBatchFromMultiversXCalled(batch) @@ -104,7 +104,7 @@ func (stub *BridgeExecutorStub) StoreBatchFromMultiversX(batch *clients.Transfer } // GetStoredBatch - -func (stub *BridgeExecutorStub) GetStoredBatch() *clients.TransferBatch { +func (stub *BridgeExecutorStub) GetStoredBatch() *bridgeCommon.TransferBatch { stub.incrementFunctionCounter() if stub.GetStoredBatchCalled != nil { return stub.GetStoredBatchCalled() diff --git a/testsCommon/bridge/constants.go b/testsCommon/bridge/constants.go index 28c0ef3f..897540d1 100644 --- a/testsCommon/bridge/constants.go +++ b/testsCommon/bridge/constants.go @@ -1,7 +1,6 @@ package bridge import ( - "bytes" "errors" ) @@ -9,11 +8,15 @@ var notImplemented = errors.New("method not implemented") // CallDataMock - var CallDataMock = func() []byte { - b := []byte{0x01, 0x00, 0x00, 0x00, 0x03} - b = append(b, []byte("abc")...) - b = append(b, 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00) // Gas limit - b = append(b, 0x00, 0x00, 0x00, 0x01) // numArguments - b = append(b, 0x00, 0x00, 0x00, 0x05) // Argument 0 length - b = append(b, bytes.Repeat([]byte{'a'}, 5)...) // Argument 0 data + b := []byte{ + 1, + 0, 0, 0, 28, + 0, 0, 0, 3, 'a', 'b', 'c', + 0x00, 0x00, 0x00, 0x00, 0x1D, 0xCD, 0x65, 0x00, // gas limit + 0, 0, 0, 1, // numArguments + 0, 0, 0, 5, // argument 0 length + 'd', 'e', 'f', 'g', 'h', // argument 0 data + } + return b }() diff --git a/testsCommon/bridge/ethereumClientStub.go b/testsCommon/bridge/ethereumClientStub.go index 98319051..e545e243 100644 --- a/testsCommon/bridge/ethereumClientStub.go +++ b/testsCommon/bridge/ethereumClientStub.go @@ -5,14 +5,14 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/multiversx/mx-bridge-eth-go/clients" "github.com/multiversx/mx-bridge-eth-go/clients/ethereum/contract" + bridgeCommon "github.com/multiversx/mx-bridge-eth-go/common" "github.com/multiversx/mx-bridge-eth-go/core/batchProcessor" ) // EthereumClientStub - type EthereumClientStub struct { - GetBatchCalled func(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) + GetBatchCalled func(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) WasExecutedCalled func(ctx context.Context, batchID uint64) (bool, error) GenerateMessageHashCalled func(batch *batchProcessor.ArgListsBatch, batchID uint64) (common.Hash, error) BroadcastSignatureForMessageHashCalled func(msgHash common.Hash) @@ -32,7 +32,7 @@ type EthereumClientStub struct { } // GetBatch - -func (stub *EthereumClientStub) GetBatch(ctx context.Context, nonce uint64) (*clients.TransferBatch, bool, error) { +func (stub *EthereumClientStub) GetBatch(ctx context.Context, nonce uint64) (*bridgeCommon.TransferBatch, bool, error) { if stub.GetBatchCalled != nil { return stub.GetBatchCalled(ctx, nonce) } diff --git a/testsCommon/bridge/multiversxClientStub.go b/testsCommon/bridge/multiversxClientStub.go index 1904fdc2..a42f6eba 100644 --- a/testsCommon/bridge/multiversxClientStub.go +++ b/testsCommon/bridge/multiversxClientStub.go @@ -5,32 +5,32 @@ import ( "errors" "math/big" - "github.com/multiversx/mx-bridge-eth-go/clients" + "github.com/multiversx/mx-bridge-eth-go/common" ) var errNotImplemented = errors.New("not implemented") // MultiversXClientStub - type MultiversXClientStub struct { - GetPendingBatchCalled func(ctx context.Context) (*clients.TransferBatch, error) - GetBatchCalled func(ctx context.Context, batchID uint64) (*clients.TransferBatch, error) + GetPendingBatchCalled func(ctx context.Context) (*common.TransferBatch, error) + GetBatchCalled func(ctx context.Context, batchID uint64) (*common.TransferBatch, error) GetCurrentBatchAsDataBytesCalled func(ctx context.Context) ([][]byte, error) - WasProposedTransferCalled func(ctx context.Context, batch *clients.TransferBatch) (bool, error) + WasProposedTransferCalled func(ctx context.Context, batch *common.TransferBatch) (bool, error) QuorumReachedCalled func(ctx context.Context, actionID uint64) (bool, error) WasExecutedCalled func(ctx context.Context, actionID uint64) (bool, error) - GetActionIDForProposeTransferCalled func(ctx context.Context, batch *clients.TransferBatch) (uint64, error) - WasProposedSetStatusCalled func(ctx context.Context, batch *clients.TransferBatch) (bool, error) + GetActionIDForProposeTransferCalled func(ctx context.Context, batch *common.TransferBatch) (uint64, error) + WasProposedSetStatusCalled func(ctx context.Context, batch *common.TransferBatch) (bool, error) GetTransactionsStatusesCalled func(ctx context.Context, batchID uint64) ([]byte, error) - GetActionIDForSetStatusOnPendingTransferCalled func(ctx context.Context, batch *clients.TransferBatch) (uint64, error) + GetActionIDForSetStatusOnPendingTransferCalled func(ctx context.Context, batch *common.TransferBatch) (uint64, error) GetLastExecutedEthBatchIDCalled func(ctx context.Context) (uint64, error) GetLastExecutedEthTxIDCalled func(ctx context.Context) (uint64, error) GetCurrentNonceCalled func(ctx context.Context) (uint64, error) - ProposeSetStatusCalled func(ctx context.Context, batch *clients.TransferBatch) (string, error) - ResolveNewDepositsCalled func(ctx context.Context, batch *clients.TransferBatch) error - ProposeTransferCalled func(ctx context.Context, batch *clients.TransferBatch) (string, error) + ProposeSetStatusCalled func(ctx context.Context, batch *common.TransferBatch) (string, error) + ResolveNewDepositsCalled func(ctx context.Context, batch *common.TransferBatch) error + ProposeTransferCalled func(ctx context.Context, batch *common.TransferBatch) (string, error) SignCalled func(ctx context.Context, actionID uint64) (string, error) WasSignedCalled func(ctx context.Context, actionID uint64) (bool, error) - PerformActionCalled func(ctx context.Context, actionID uint64, batch *clients.TransferBatch) (string, error) + PerformActionCalled func(ctx context.Context, actionID uint64, batch *common.TransferBatch) (string, error) CheckClientAvailabilityCalled func(ctx context.Context) error IsMintBurnTokenCalled func(ctx context.Context, token []byte) (bool, error) IsNativeTokenCalled func(ctx context.Context, token []byte) (bool, error) @@ -42,7 +42,7 @@ type MultiversXClientStub struct { } // GetPendingBatch - -func (stub *MultiversXClientStub) GetPendingBatch(ctx context.Context) (*clients.TransferBatch, error) { +func (stub *MultiversXClientStub) GetPendingBatch(ctx context.Context) (*common.TransferBatch, error) { if stub.GetPendingBatchCalled != nil { return stub.GetPendingBatchCalled(ctx) } @@ -51,7 +51,7 @@ func (stub *MultiversXClientStub) GetPendingBatch(ctx context.Context) (*clients } // GetBatch - -func (stub *MultiversXClientStub) GetBatch(ctx context.Context, batchID uint64) (*clients.TransferBatch, error) { +func (stub *MultiversXClientStub) GetBatch(ctx context.Context, batchID uint64) (*common.TransferBatch, error) { if stub.GetBatchCalled != nil { return stub.GetBatchCalled(ctx, batchID) } @@ -69,7 +69,7 @@ func (stub *MultiversXClientStub) GetCurrentBatchAsDataBytes(ctx context.Context } // WasProposedTransfer - -func (stub *MultiversXClientStub) WasProposedTransfer(ctx context.Context, batch *clients.TransferBatch) (bool, error) { +func (stub *MultiversXClientStub) WasProposedTransfer(ctx context.Context, batch *common.TransferBatch) (bool, error) { if stub.WasProposedTransferCalled != nil { return stub.WasProposedTransferCalled(ctx, batch) } @@ -96,7 +96,7 @@ func (stub *MultiversXClientStub) WasExecuted(ctx context.Context, actionID uint } // GetActionIDForProposeTransfer - -func (stub *MultiversXClientStub) GetActionIDForProposeTransfer(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { +func (stub *MultiversXClientStub) GetActionIDForProposeTransfer(ctx context.Context, batch *common.TransferBatch) (uint64, error) { if stub.GetActionIDForProposeTransferCalled != nil { return stub.GetActionIDForProposeTransferCalled(ctx, batch) } @@ -105,7 +105,7 @@ func (stub *MultiversXClientStub) GetActionIDForProposeTransfer(ctx context.Cont } // WasProposedSetStatus - -func (stub *MultiversXClientStub) WasProposedSetStatus(ctx context.Context, batch *clients.TransferBatch) (bool, error) { +func (stub *MultiversXClientStub) WasProposedSetStatus(ctx context.Context, batch *common.TransferBatch) (bool, error) { if stub.WasProposedSetStatusCalled != nil { return stub.WasProposedSetStatusCalled(ctx, batch) } @@ -123,7 +123,7 @@ func (stub *MultiversXClientStub) GetTransactionsStatuses(ctx context.Context, b } // GetActionIDForSetStatusOnPendingTransfer - -func (stub *MultiversXClientStub) GetActionIDForSetStatusOnPendingTransfer(ctx context.Context, batch *clients.TransferBatch) (uint64, error) { +func (stub *MultiversXClientStub) GetActionIDForSetStatusOnPendingTransfer(ctx context.Context, batch *common.TransferBatch) (uint64, error) { if stub.GetActionIDForSetStatusOnPendingTransferCalled != nil { return stub.GetActionIDForSetStatusOnPendingTransferCalled(ctx, batch) } @@ -159,7 +159,7 @@ func (stub *MultiversXClientStub) GetCurrentNonce(ctx context.Context) (uint64, } // ProposeSetStatus - -func (stub *MultiversXClientStub) ProposeSetStatus(ctx context.Context, batch *clients.TransferBatch) (string, error) { +func (stub *MultiversXClientStub) ProposeSetStatus(ctx context.Context, batch *common.TransferBatch) (string, error) { if stub.ProposeSetStatusCalled != nil { return stub.ProposeSetStatusCalled(ctx, batch) } @@ -168,7 +168,7 @@ func (stub *MultiversXClientStub) ProposeSetStatus(ctx context.Context, batch *c } // ProposeTransfer - -func (stub *MultiversXClientStub) ProposeTransfer(ctx context.Context, batch *clients.TransferBatch) (string, error) { +func (stub *MultiversXClientStub) ProposeTransfer(ctx context.Context, batch *common.TransferBatch) (string, error) { if stub.ProposeTransferCalled != nil { return stub.ProposeTransferCalled(ctx, batch) } @@ -195,7 +195,7 @@ func (stub *MultiversXClientStub) WasSigned(ctx context.Context, actionID uint64 } // PerformAction - -func (stub *MultiversXClientStub) PerformAction(ctx context.Context, actionID uint64, batch *clients.TransferBatch) (string, error) { +func (stub *MultiversXClientStub) PerformAction(ctx context.Context, actionID uint64, batch *common.TransferBatch) (string, error) { if stub.PerformActionCalled != nil { return stub.PerformActionCalled(ctx, actionID, batch) }