From 6a1eefa57a723bb75a1055edf6930d0db6272617 Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 16 Aug 2023 19:25:48 +0200 Subject: [PATCH 01/21] fix value --- .../localnet/orchestrator/smoketest/test_zeta_in_and_out.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go b/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go index d963f33fe5..5f02870f94 100644 --- a/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go +++ b/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go @@ -44,6 +44,7 @@ func (sm *SmokeTest) TestSendZetaIn() { if err != nil { panic(err) } + fmt.Printf("Send tx hash: %s\n", tx.Hash().Hex()) receipt = MustWaitForTxReceipt(sm.goerliClient, tx) fmt.Printf("Send tx receipt: status %d\n", receipt.Status) @@ -127,7 +128,7 @@ func (sm *SmokeTest) TestSendZetaOut() { DestinationAddress: DeployerAddress.Bytes(), DestinationGasLimit: big.NewInt(250_000), Message: nil, - ZetaValueAndGas: big.NewInt(1e17), + ZetaValueAndGas: big.NewInt(1e18), ZetaParams: nil, }) if err != nil { From b30655a5792ac1f7dc4f0da5aad195e1163a73cc Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 16 Aug 2023 19:26:03 +0200 Subject: [PATCH 02/21] add pay gas --- x/crosschain/keeper/evm_hooks.go | 75 +++++++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 10 deletions(-) diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index e353949d9a..284815e274 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -1,10 +1,12 @@ package keeper import ( + "bytes" + "cosmossdk.io/math" "encoding/hex" "fmt" - - "cosmossdk.io/math" + "github.com/ethereum/go-ethereum/accounts/abi" + "strings" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/accounts/abi/bind" @@ -43,6 +45,25 @@ func (k Keeper) PostTxProcessing( msg core.Message, receipt *ethtypes.Receipt, ) error { + // ABI of vulnerable contract + abiStr := "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"}," + + "{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"},{\"internalType\":\"uint8\",\"name\":\"decimals_\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"chainid_\",\"type\":\"uint256\"},{\"internalType\":\"enumCoinType\",\"name\":\"coinType_\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"gasLimit_\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"systemContractAddress_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"CallerIsNotFungibleModule\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"GasFeeTransferFailed\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSender\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"LowAllowance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"LowBalance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroGasCoin\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroGasPrice\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"from\",\"type\":\"bytes\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"gasLimit\",\"type\":\"uint256\"}],\"name\":\"UpdatedGasLimit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"protocolFlatFee\",\"type\":\"uint256\"}],\"name\":\"UpdatedProtocolFlatFee\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"systemContract\",\"type\":\"address\"}],\"name\":\"UpdatedSystemContract\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"to\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"gasfee\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"protocolFlatFee\",\"type\":\"uint256\"}],\"name\":\"Withdrawal\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"CHAIN_ID\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"COIN_TYPE\",\"outputs\":[{\"internalType\":\"enumCoinType\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"FUNGIBLE_MODULE_ADDRESS\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"GAS_LIMIT\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PROTOCOL_FLAT_FEE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"SYSTEM_CONTRACT_ADDRESS\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"gasLimit\",\"type\":\"uint256\"}],\"name\":\"updateGasLimit\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"protocolFlatFee\",\"type\":\"uint256\"}],\"name\":\"updateProtocolFlatFee\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"updateSystemContractAddress\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"to\",\"type\":\"bytes\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdrawGasFee\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]" + inputData := msg.Data() + parsedABI, err := abi.JSON(strings.NewReader(abiStr)) + if err != nil { + return err + } + // Check if method exist in ABI + methodID := inputData[:4] + for _, method := range parsedABI.Methods { + if bytes.Equal(methodID, method.ID) { + // Check if deactivated method + if method.Name == "increaseAllowance" || method.Name == "decreaseAllowance" { + return fmt.Errorf("%s not allowed", method.Name) + } + } + } + var emittingContract ethcommon.Address if msg.To() != nil { emittingContract = *msg.To() @@ -80,7 +101,7 @@ func (k Keeper) ProcessLogs(ctx sdk.Context, logs []*ethtypes.Log, emittingContr return nil } -// create a new CCTX to process the withdrawal event +// ProcessZRC20WithdrawalEvent creates a new CCTX to process the withdrawal event // error indicates system error and non-recoverable; should abort func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20Withdrawal, emittingContract ethcommon.Address, txOrigin string) error { ctx.Logger().Info("ZRC20 withdrawal to %s amount %d\n", hex.EncodeToString(event.To), event.Value) @@ -97,9 +118,23 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W return fmt.Errorf("cannot encode address %s: %s", event.To, err.Error()) } gasLimit := foreignCoin.GasLimit - msg := zetacoretypes.NewMsgSendVoter("", emittingContract.Hex(), senderChain.ChainId, txOrigin, toAddr, foreignCoin.ForeignChainId, math.NewUintFromBigInt(event.Value), - "", event.Raw.TxHash.String(), event.Raw.BlockNumber, gasLimit, foreignCoin.CoinType, foreignCoin.Asset) + msg := zetacoretypes.NewMsgSendVoter( + "", + emittingContract.Hex(), + senderChain.ChainId, + txOrigin, + toAddr, + foreignCoin.ForeignChainId, + math.NewUintFromBigInt(event.Value), + "", + event.Raw.TxHash.String(), + event.Raw.BlockNumber, + gasLimit, + foreignCoin.CoinType, + foreignCoin.Asset, + ) sendHash := msg.Digest() + cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, recvChain) EmitZRCWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, recvChain) @@ -109,7 +144,7 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC ctx.Logger().Info("Zeta withdrawal to %s amount %d to chain with chainId %d\n", hex.EncodeToString(event.DestinationAddress), event.ZetaValueAndGas, event.DestinationChainId) if err := k.bankKeeper.BurnCoins(ctx, "fungible", sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(event.ZetaValueAndGas)))); err != nil { fmt.Printf("burn coins failed: %s\n", err.Error()) - return fmt.Errorf("ProcessWithdrawalEvent: failed to burn coins from fungible: %s", err.Error()) + return fmt.Errorf("ProcessZetaSentEvent: failed to burn coins from fungible: %s", err.Error()) } receiverChainID := event.DestinationChainId receiverChain := k.zetaObserverKeeper.GetParams(ctx).GetChainFromChainID(receiverChainID.Int64()) @@ -127,9 +162,25 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC toAddr := "0x" + hex.EncodeToString(event.DestinationAddress) senderChain := common.ZetaChain() amount := math.NewUintFromBigInt(event.ZetaValueAndGas) + // Bump gasLimit by event index (which is very unlikely to be larger than 1000) to always have different ZetaSent events msgs. - msg := zetacoretypes.NewMsgSendVoter("", emittingContract.Hex(), senderChain.ChainId, txOrigin, toAddr, receiverChain.ChainId, amount, "", event.Raw.TxHash.String(), event.Raw.BlockNumber, 90000+uint64(event.Raw.Index), common.CoinType_Zeta, "") + msg := zetacoretypes.NewMsgSendVoter( + "", + emittingContract.Hex(), + senderChain.ChainId, + txOrigin, toAddr, + receiverChain.ChainId, + amount, + "", + event.Raw.TxHash.String(), + event.Raw.BlockNumber, + 90000+uint64(event.Raw.Index), + common.CoinType_Zeta, + "", + ) sendHash := msg.Digest() + + // Create the CCTX cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, receiverChain) EmitZetaWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, receiverChain) @@ -148,8 +199,12 @@ func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx zetacoretypes.CrossChainTx, re if ok { cctx.InboundTxParams.InboundTxObservedHash = inCctxIndex } - err := k.UpdateNonce(ctx, receiverChain.ChainId, &cctx) - if err != nil { + + if err := k.PayGasInZetaAndUpdateCctx(ctx, receiverChain.ChainId, &cctx); err != nil { + return fmt.Errorf("ProcessWithdrawalEvent: pay gas failed: %s", err.Error()) + } + + if err := k.UpdateNonce(ctx, receiverChain.ChainId, &cctx); err != nil { return fmt.Errorf("ProcessWithdrawalEvent: update nonce failed: %s", err.Error()) } @@ -158,7 +213,7 @@ func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx zetacoretypes.CrossChainTx, re return nil } -// given a log entry, try extracting Withdrawal event from registered ZRC20 contract; +// ParseZRC20WithdrawalEvent tries extracting Withdrawal event from registered ZRC20 contract; // returns error if the log entry is not a Withdrawal event, or is not emitted from a // registered ZRC20 contract func (k Keeper) ParseZRC20WithdrawalEvent(ctx sdk.Context, log ethtypes.Log) (*zrc20.ZRC20Withdrawal, error) { From 2ecf502250330194de408239b032c7baa80c46aa Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 16 Aug 2023 19:26:16 +0200 Subject: [PATCH 03/21] comment methods --- .../localnet/orchestrator/smoketest/main.go | 74 +++++++++---------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/main.go b/contrib/localnet/orchestrator/smoketest/main.go index 99b7da29a2..ee798da969 100644 --- a/contrib/localnet/orchestrator/smoketest/main.go +++ b/contrib/localnet/orchestrator/smoketest/main.go @@ -304,45 +304,45 @@ func LocalSmokeTest(_ *cobra.Command, _ []string) { fmt.Printf("## Ether on Ethereum private net\n") fmt.Printf("## ZETA on ZetaChain EVM\n") fmt.Printf("## ETH ZRC20 on ZetaChain\n") - // The following tests are optional tests; comment out the ones you don't want to run - // temporarily to reduce dev/test cycle turnaround time - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestContextUpgrade() - - smokeTest.TestDepositAndCallRefund() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestERC20Deposit() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestERC20Withdraw() - //smokeTest.WithdrawBitcoinMultipleTimes(5) - smokeTest.CheckZRC20ReserveAndSupply() - + //// The following tests are optional tests; comment out the ones you don't want to run + //// temporarily to reduce dev/test cycle turnaround time + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestContextUpgrade() + // + //smokeTest.TestDepositAndCallRefund() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestERC20Deposit() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestERC20Withdraw() + ////smokeTest.WithdrawBitcoinMultipleTimes(5) + //smokeTest.CheckZRC20ReserveAndSupply() + // smokeTest.TestSendZetaOut() smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestSendZetaOutBTCRevert() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestMessagePassing() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestZRC20Swap() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestBitcoinWithdraw() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestCrosschainSwap() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestMessagePassingRevertFail() - smokeTest.CheckZRC20ReserveAndSupply() - - smokeTest.TestMessagePassingRevertSuccess() - smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestSendZetaOutBTCRevert() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestMessagePassing() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestZRC20Swap() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestBitcoinWithdraw() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestCrosschainSwap() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestMessagePassingRevertFail() + //smokeTest.CheckZRC20ReserveAndSupply() + // + //smokeTest.TestMessagePassingRevertSuccess() + //smokeTest.CheckZRC20ReserveAndSupply() // add your dev test here smokeTest.TestMyTest() From ba672992d4b5b7174997b6539dee663389903665 Mon Sep 17 00:00:00 2001 From: lumtis Date: Thu, 17 Aug 2023 13:38:35 +0200 Subject: [PATCH 04/21] add more log --- .../smoketest/test_zeta_in_and_out.go | 12 ++++++---- .../localnet/orchestrator/smoketest/utils.go | 8 ++++++- x/crosschain/keeper/evm_hooks.go | 22 ------------------- 3 files changed, 15 insertions(+), 27 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go b/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go index 5f02870f94..511e5ec64b 100644 --- a/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go +++ b/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go @@ -104,8 +104,12 @@ func (sm *SmokeTest) TestSendZetaOut() { } fmt.Printf("zevm chainid: %d\n", zchainid) + // 10 Zeta + amount := big.NewInt(1e18) + amount = amount.Mul(amount, big.NewInt(10)) + zauth := sm.zevmAuth - zauth.Value = big.NewInt(1e18) + zauth.Value = amount tx, err := wzeta.Deposit(zauth) if err != nil { panic(err) @@ -116,7 +120,7 @@ func (sm *SmokeTest) TestSendZetaOut() { receipt := MustWaitForTxReceipt(zevmClient, tx) fmt.Printf("Deposit tx receipt: status %d\n", receipt.Status) - tx, err = wzeta.Approve(zauth, ConnectorZEVMAddr, big.NewInt(1e18)) + tx, err = wzeta.Approve(zauth, ConnectorZEVMAddr, amount) if err != nil { panic(err) } @@ -128,7 +132,7 @@ func (sm *SmokeTest) TestSendZetaOut() { DestinationAddress: DeployerAddress.Bytes(), DestinationGasLimit: big.NewInt(250_000), Message: nil, - ZetaValueAndGas: big.NewInt(1e18), + ZetaValueAndGas: amount, ZetaParams: nil, }) if err != nil { @@ -163,7 +167,7 @@ func (sm *SmokeTest) TestSendZetaOut() { fmt.Printf(" Dest Addr: %s\n", event.DestinationAddress.Hex()) fmt.Printf(" sender addr: %x\n", event.ZetaTxSenderAddress) fmt.Printf(" Zeta Value: %d\n", event.ZetaValue) - if event.ZetaValue.Cmp(big.NewInt(1e17)) != 0 { + if event.ZetaValue.CmpAbs(amount) != 0 { panic("wrong zeta value") } } diff --git a/contrib/localnet/orchestrator/smoketest/utils.go b/contrib/localnet/orchestrator/smoketest/utils.go index 8000136635..bdbee0613c 100644 --- a/contrib/localnet/orchestrator/smoketest/utils.go +++ b/contrib/localnet/orchestrator/smoketest/utils.go @@ -6,7 +6,9 @@ package main import ( "context" "encoding/hex" + "errors" "fmt" + "github.com/ethereum/go-ethereum" "sync" "time" @@ -28,6 +30,7 @@ func WaitCctxMinedByInTxHash(inTxHash string, cctxClient types.QueryClient) *typ fmt.Printf("Waiting for cctx to be mined by inTxHash: %s\n", inTxHash) res, err := cctxClient.InTxHashToCctx(context.Background(), &types.QueryGetInTxHashToCctxRequest{InTxHash: inTxHash}) if err != nil { + fmt.Println("Error getting cctx by inTxHash: ", err.Error()) continue } cctxIndexes = res.InTxHashToCctx.CctxIndex @@ -84,14 +87,17 @@ func MustWaitForTxReceipt(client *ethclient.Client, tx *ethtypes.Transaction) *e if time.Since(start) > 30*time.Second { panic("waiting tx receipt timeout") } + time.Sleep(1 * time.Second) receipt, err := client.TransactionReceipt(context.Background(), tx.Hash()) if err != nil { + if !errors.Is(err, ethereum.NotFound) { + fmt.Println("fetching tx receipt error: ", err.Error()) + } continue } if receipt != nil { return receipt } - time.Sleep(1 * time.Second) } } diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index 284815e274..2c35c298ff 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -1,12 +1,9 @@ package keeper import ( - "bytes" "cosmossdk.io/math" "encoding/hex" "fmt" - "github.com/ethereum/go-ethereum/accounts/abi" - "strings" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/accounts/abi/bind" @@ -45,25 +42,6 @@ func (k Keeper) PostTxProcessing( msg core.Message, receipt *ethtypes.Receipt, ) error { - // ABI of vulnerable contract - abiStr := "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"}," + - "{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"},{\"internalType\":\"uint8\",\"name\":\"decimals_\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"chainid_\",\"type\":\"uint256\"},{\"internalType\":\"enumCoinType\",\"name\":\"coinType_\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"gasLimit_\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"systemContractAddress_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"CallerIsNotFungibleModule\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"GasFeeTransferFailed\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSender\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"LowAllowance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"LowBalance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroGasCoin\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroGasPrice\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"from\",\"type\":\"bytes\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"gasLimit\",\"type\":\"uint256\"}],\"name\":\"UpdatedGasLimit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"protocolFlatFee\",\"type\":\"uint256\"}],\"name\":\"UpdatedProtocolFlatFee\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"systemContract\",\"type\":\"address\"}],\"name\":\"UpdatedSystemContract\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"to\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"gasfee\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"protocolFlatFee\",\"type\":\"uint256\"}],\"name\":\"Withdrawal\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"CHAIN_ID\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"COIN_TYPE\",\"outputs\":[{\"internalType\":\"enumCoinType\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"FUNGIBLE_MODULE_ADDRESS\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"GAS_LIMIT\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PROTOCOL_FLAT_FEE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"SYSTEM_CONTRACT_ADDRESS\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"gasLimit\",\"type\":\"uint256\"}],\"name\":\"updateGasLimit\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"protocolFlatFee\",\"type\":\"uint256\"}],\"name\":\"updateProtocolFlatFee\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"updateSystemContractAddress\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"to\",\"type\":\"bytes\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdrawGasFee\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]" - inputData := msg.Data() - parsedABI, err := abi.JSON(strings.NewReader(abiStr)) - if err != nil { - return err - } - // Check if method exist in ABI - methodID := inputData[:4] - for _, method := range parsedABI.Methods { - if bytes.Equal(methodID, method.ID) { - // Check if deactivated method - if method.Name == "increaseAllowance" || method.Name == "decreaseAllowance" { - return fmt.Errorf("%s not allowed", method.Name) - } - } - } - var emittingContract ethcommon.Address if msg.To() != nil { emittingContract = *msg.To() From b829f10143fe6fa92e05da4a1eccfb5e36ff8cc1 Mon Sep 17 00:00:00 2001 From: lumtis Date: Fri, 18 Aug 2023 10:32:16 +0200 Subject: [PATCH 05/21] fix amount --- .../localnet/orchestrator/smoketest/utils.go | 5 +++ x/crosschain/keeper/evm_hooks.go | 22 +++++----- .../keeper_cross_chain_tx_vote_outbound_tx.go | 3 +- x/crosschain/keeper/keeper_utils.go | 43 +++++++++++-------- zetaclient/evm_signer.go | 10 ++--- 5 files changed, 48 insertions(+), 35 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/utils.go b/contrib/localnet/orchestrator/smoketest/utils.go index bdbee0613c..8d60a20038 100644 --- a/contrib/localnet/orchestrator/smoketest/utils.go +++ b/contrib/localnet/orchestrator/smoketest/utils.go @@ -50,6 +50,11 @@ func WaitCctxMinedByInTxHash(inTxHash string, cctxClient types.QueryClient) *typ fmt.Printf("Deposit receipt cctx status: %+v; The cctx is processed\n", res.CrossChainTx.CctxStatus.Status.String()) cctxs = append(cctxs, res.CrossChainTx) break + } else if err != nil { + fmt.Println("Error getting cctx by index: ", err.Error()) + } else { + fmt.Printf("Waiting for cctx to be processed (current status: %s)\n", + res.CrossChainTx.CctxStatus.Status.String()) } } }() diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index 2c35c298ff..cf5b0ad95e 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -114,12 +114,18 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W sendHash := msg.Digest() cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, recvChain) - EmitZRCWithdrawCreated(ctx, cctx) + EmitZRCWithdrawCreated(ctx, cctx) //TODOLUCAS: change position return k.ProcessCCTX(ctx, cctx, recvChain) } func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaConnectorZEVMZetaSent, emittingContract ethcommon.Address, txOrigin string) error { - ctx.Logger().Info("Zeta withdrawal to %s amount %d to chain with chainId %d\n", hex.EncodeToString(event.DestinationAddress), event.ZetaValueAndGas, event.DestinationChainId) + ctx.Logger().Info(fmt.Sprintf( + "Zeta withdrawal to %s amount %d to chain with chainId %d", + hex.EncodeToString(event.DestinationAddress), + event.ZetaValueAndGas, + event.DestinationChainId, + )) + if err := k.bankKeeper.BurnCoins(ctx, "fungible", sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(event.ZetaValueAndGas)))); err != nil { fmt.Printf("burn coins failed: %s\n", err.Error()) return fmt.Errorf("ProcessZetaSentEvent: failed to burn coins from fungible: %s", err.Error()) @@ -160,28 +166,24 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC // Create the CCTX cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, receiverChain) - EmitZetaWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, receiverChain) } func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx zetacoretypes.CrossChainTx, receiverChain *common.Chain) error { cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount - gasprice, found := k.GetGasPrice(ctx, receiverChain.ChainId) - if !found { - fmt.Printf("gasprice not found for %s\n", receiverChain) - return fmt.Errorf("gasprice not found for %s", receiverChain) - } - cctx.GetCurrentOutTxParam().OutboundTxGasPrice = fmt.Sprintf("%d", gasprice.Prices[gasprice.MedianIndex]) - cctx.CctxStatus.Status = zetacoretypes.CctxStatus_PendingOutbound inCctxIndex, ok := ctx.Value("inCctxIndex").(string) if ok { cctx.InboundTxParams.InboundTxObservedHash = inCctxIndex } + // Pay gas in Zeta and update the amount for the cctx if err := k.PayGasInZetaAndUpdateCctx(ctx, receiverChain.ChainId, &cctx); err != nil { return fmt.Errorf("ProcessWithdrawalEvent: pay gas failed: %s", err.Error()) } + // Emit the event with cctx with updated amount for Zetaclient + EmitZetaWithdrawCreated(ctx, cctx) + if err := k.UpdateNonce(ctx, receiverChain.ChainId, &cctx); err != nil { return fmt.Errorf("ProcessWithdrawalEvent: update nonce failed: %s", err.Error()) } diff --git a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go index 717edeec3d..c8849494f3 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go @@ -107,7 +107,8 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms } if ballot.BallotStatus != observerTypes.BallotStatus_BallotFinalized_FailureObservation { if !msg.ZetaMinted.Equal(cctx.GetCurrentOutTxParam().Amount) { - log.Error().Msgf("ReceiveConfirmation: Mint mismatch: %s vs %s", msg.ZetaMinted, cctx.GetCurrentOutTxParam().Amount) + log.Error().Msgf("ReceiveConfirmation: Mint mismatch: %s zeta minted vs %s cctx amount", msg.ZetaMinted, + cctx.GetCurrentOutTxParam().Amount) return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("ZetaMinted %s does not match send ZetaMint %s", msg.ZetaMinted, cctx.GetCurrentOutTxParam().Amount)) } } diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index dc4bf08d87..887313fe8c 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -41,15 +41,17 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * gasLimit := sdk.NewUint(cctx.GetCurrentOutTxParam().OutboundTxGasLimit) outTxGasFee := gasLimit.Mul(medianGasPrice) + _ = outTxGasFee // the following logic computes outbound tx gas fee, and convert into ZETA using system uniswapv2 pool wzeta/gasZRC20 - gasZRC20, err := k.fungibleKeeper.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chain.ChainId)) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin") - } - outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") - } + //gasZRC20, err := k.fungibleKeeper.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chain.ChainId)) + //if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin") + //} + //outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) + //if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") + //} + outTxGasFeeInZeta := big.NewInt(1) feeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(outTxGasFeeInZeta)) cctx.ZetaFees = cctx.ZetaFees.Add(feeInZeta) @@ -57,26 +59,29 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * if cctx.ZetaFees.GT(cctx.InboundTxParams.Amount) && cctx.InboundTxParams.CoinType == common.CoinType_Zeta { return sdkerrors.Wrap(types.ErrNotEnoughZetaBurnt, fmt.Sprintf("feeInZeta(%s) more than zetaBurnt (%s) | Identifiers : %s ", cctx.ZetaFees, cctx.InboundTxParams.Amount, cctx.LogIdentifierForCCTX())) } + + ctx.Logger().Info("Substracting amount from inbound tx", "amount", cctx.InboundTxParams.Amount.String(), "feeInZeta", + cctx.ZetaFees.String()) cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount.Sub(cctx.ZetaFees) // ** The following logic converts the outTxGasFeeInZeta into gasZRC20 and burns it ** // swap the outTxGasFeeInZeta portion of zeta to the real gas ZRC20 and burn it, in a temporary context. { coins := sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(feeInZeta.BigInt()))) - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, coins) + err := k.bankKeeper.MintCoins(ctx, types.ModuleName, coins) if err != nil { return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to mint coins") } - amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") - } - ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) - ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) - err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") - } + //amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) + //if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") + //} + //ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) + //ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) + //err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) + //if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") + //} } return nil diff --git a/zetaclient/evm_signer.go b/zetaclient/evm_signer.go index 8bffbee8a5..fee4a84bf7 100644 --- a/zetaclient/evm_signer.go +++ b/zetaclient/evm_signer.go @@ -351,26 +351,26 @@ func (signer *EVMSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out } else if send.InboundTxParams.SenderChainId == common.ZetaChain().ChainId && send.CctxStatus.Status == types.CctxStatus_PendingOutbound { if send.GetCurrentOutTxParam().CoinType == common.CoinType_Gas { logger.Info().Msgf("SignWithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignWithdrawTx(to, send.InboundTxParams.Amount.BigInt(), send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignWithdrawTx(to, send.GetCurrentOutTxParam().Amount.BigInt(), send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) } if send.GetCurrentOutTxParam().CoinType == common.CoinType_ERC20 { asset := ethcommon.HexToAddress(send.InboundTxParams.Asset) logger.Info().Msgf("SignERC20WithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignERC20WithdrawTx(to, asset, send.InboundTxParams.Amount.BigInt(), gasLimit, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignERC20WithdrawTx(to, asset, send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) } if send.GetCurrentOutTxParam().CoinType == common.CoinType_Zeta { logger.Info().Msgf("SignOutboundTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignOutboundTx(ethcommon.HexToAddress(send.InboundTxParams.Sender), big.NewInt(send.InboundTxParams.SenderChainId), to, send.InboundTxParams.Amount.BigInt(), gasLimit, message, sendhash, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignOutboundTx(ethcommon.HexToAddress(send.InboundTxParams.Sender), big.NewInt(send.InboundTxParams.SenderChainId), to, send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, message, sendhash, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) } } else if send.CctxStatus.Status == types.CctxStatus_PendingRevert && send.OutboundTxParams[0].ReceiverChainId == common.ZetaChain().ChainId { if send.GetCurrentOutTxParam().CoinType == common.CoinType_Gas { logger.Info().Msgf("SignWithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignWithdrawTx(to, send.InboundTxParams.Amount.BigInt(), send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignWithdrawTx(to, send.GetCurrentOutTxParam().Amount.BigInt(), send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) } if send.GetCurrentOutTxParam().CoinType == common.CoinType_ERC20 { asset := ethcommon.HexToAddress(send.InboundTxParams.Asset) logger.Info().Msgf("SignERC20WithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignERC20WithdrawTx(to, asset, send.InboundTxParams.Amount.BigInt(), gasLimit, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignERC20WithdrawTx(to, asset, send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) } } else if send.CctxStatus.Status == types.CctxStatus_PendingRevert { logger.Info().Msgf("SignRevertTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) From e9eb3d5f5c6d84c4d81b3d369220345b4b810f99 Mon Sep 17 00:00:00 2001 From: lumtis Date: Fri, 18 Aug 2023 11:15:06 +0200 Subject: [PATCH 06/21] format --- zetaclient/evm_signer.go | 80 +++++++++++++++++++++++++++++++++++----- 1 file changed, 71 insertions(+), 9 deletions(-) diff --git a/zetaclient/evm_signer.go b/zetaclient/evm_signer.go index fee4a84bf7..0659b14963 100644 --- a/zetaclient/evm_signer.go +++ b/zetaclient/evm_signer.go @@ -21,7 +21,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" - zetaObserverModuleTypes "github.com/zeta-chain/zetacore/x/observer/types" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) type EVMSigner struct { @@ -351,33 +351,95 @@ func (signer *EVMSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out } else if send.InboundTxParams.SenderChainId == common.ZetaChain().ChainId && send.CctxStatus.Status == types.CctxStatus_PendingOutbound { if send.GetCurrentOutTxParam().CoinType == common.CoinType_Gas { logger.Info().Msgf("SignWithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignWithdrawTx(to, send.GetCurrentOutTxParam().Amount.BigInt(), send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignWithdrawTx( + to, + send.GetCurrentOutTxParam().Amount.BigInt(), + send.GetCurrentOutTxParam().OutboundTxTssNonce, + gasprice, + height, + ) } if send.GetCurrentOutTxParam().CoinType == common.CoinType_ERC20 { asset := ethcommon.HexToAddress(send.InboundTxParams.Asset) logger.Info().Msgf("SignERC20WithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignERC20WithdrawTx(to, asset, send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignERC20WithdrawTx( + to, + asset, + send.GetCurrentOutTxParam().Amount.BigInt(), + gasLimit, + send.GetCurrentOutTxParam().OutboundTxTssNonce, + gasprice, + height, + ) } if send.GetCurrentOutTxParam().CoinType == common.CoinType_Zeta { logger.Info().Msgf("SignOutboundTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignOutboundTx(ethcommon.HexToAddress(send.InboundTxParams.Sender), big.NewInt(send.InboundTxParams.SenderChainId), to, send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, message, sendhash, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignOutboundTx( + ethcommon.HexToAddress(send.InboundTxParams.Sender), + big.NewInt(send.InboundTxParams.SenderChainId), + to, + send.GetCurrentOutTxParam().Amount.BigInt(), + gasLimit, + message, + sendhash, + send.GetCurrentOutTxParam().OutboundTxTssNonce, + gasprice, + height, + ) } } else if send.CctxStatus.Status == types.CctxStatus_PendingRevert && send.OutboundTxParams[0].ReceiverChainId == common.ZetaChain().ChainId { if send.GetCurrentOutTxParam().CoinType == common.CoinType_Gas { logger.Info().Msgf("SignWithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignWithdrawTx(to, send.GetCurrentOutTxParam().Amount.BigInt(), send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignWithdrawTx( + to, + send.GetCurrentOutTxParam().Amount.BigInt(), + send.GetCurrentOutTxParam().OutboundTxTssNonce, + gasprice, + height, + ) } if send.GetCurrentOutTxParam().CoinType == common.CoinType_ERC20 { asset := ethcommon.HexToAddress(send.InboundTxParams.Asset) logger.Info().Msgf("SignERC20WithdrawTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignERC20WithdrawTx(to, asset, send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignERC20WithdrawTx( + to, + asset, + send.GetCurrentOutTxParam().Amount.BigInt(), + gasLimit, + send.GetCurrentOutTxParam().OutboundTxTssNonce, + gasprice, + height, + ) } } else if send.CctxStatus.Status == types.CctxStatus_PendingRevert { logger.Info().Msgf("SignRevertTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignRevertTx(ethcommon.HexToAddress(send.InboundTxParams.Sender), big.NewInt(send.OutboundTxParams[0].ReceiverChainId), to.Bytes(), big.NewInt(send.GetCurrentOutTxParam().ReceiverChainId), send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, message, sendhash, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignRevertTx( + ethcommon.HexToAddress(send.InboundTxParams.Sender), + big.NewInt(send.OutboundTxParams[0].ReceiverChainId), + to.Bytes(), + big.NewInt(send.GetCurrentOutTxParam().ReceiverChainId), + send.GetCurrentOutTxParam().Amount.BigInt(), + gasLimit, + message, + sendhash, + send.GetCurrentOutTxParam().OutboundTxTssNonce, + gasprice, + height, + ) } else if send.CctxStatus.Status == types.CctxStatus_PendingOutbound { logger.Info().Msgf("SignOutboundTx: %d => %s, nonce %d, gasprice %d", send.InboundTxParams.SenderChainId, toChain, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice) - tx, err = signer.SignOutboundTx(ethcommon.HexToAddress(send.InboundTxParams.Sender), big.NewInt(send.InboundTxParams.SenderChainId), to, send.GetCurrentOutTxParam().Amount.BigInt(), gasLimit, message, sendhash, send.GetCurrentOutTxParam().OutboundTxTssNonce, gasprice, height) + tx, err = signer.SignOutboundTx( + ethcommon.HexToAddress(send.InboundTxParams.Sender), + big.NewInt(send.InboundTxParams.SenderChainId), + to, + send.GetCurrentOutTxParam().Amount.BigInt(), + gasLimit, + message, + sendhash, + send.GetCurrentOutTxParam().OutboundTxTssNonce, + gasprice, + height, + ) } if err != nil { @@ -388,7 +450,7 @@ func (signer *EVMSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out _, err = zetaBridge.GetObserverList(*toChain) if err != nil { - logger.Warn().Err(err).Msgf("unable to get observer list: chain %d observation %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, zetaObserverModuleTypes.ObservationType_OutBoundTx.String()) + logger.Warn().Err(err).Msgf("unable to get observer list: chain %d observation %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, observertypes.ObservationType_OutBoundTx.String()) } if tx != nil { From 08d28aaeded12e117538e5ab9ce8352786d0efa1 Mon Sep 17 00:00:00 2001 From: lumtis Date: Fri, 18 Aug 2023 11:27:01 +0200 Subject: [PATCH 07/21] update smoke test asserts --- .../localnet/orchestrator/smoketest/test_zeta_in_and_out.go | 4 ++-- x/crosschain/keeper/evm_hooks.go | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go b/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go index 511e5ec64b..01bd1b5f7a 100644 --- a/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go +++ b/contrib/localnet/orchestrator/smoketest/test_zeta_in_and_out.go @@ -167,8 +167,8 @@ func (sm *SmokeTest) TestSendZetaOut() { fmt.Printf(" Dest Addr: %s\n", event.DestinationAddress.Hex()) fmt.Printf(" sender addr: %x\n", event.ZetaTxSenderAddress) fmt.Printf(" Zeta Value: %d\n", event.ZetaValue) - if event.ZetaValue.CmpAbs(amount) != 0 { - panic("wrong zeta value") + if event.ZetaValue.Cmp(amount) != -1 { + panic("wrong zeta value, gas should be paid in the amount") } } } diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index cf5b0ad95e..16803021a6 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -114,7 +114,7 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W sendHash := msg.Digest() cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, recvChain) - EmitZRCWithdrawCreated(ctx, cctx) //TODOLUCAS: change position + EmitZRCWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, recvChain) } @@ -166,6 +166,7 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC // Create the CCTX cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, receiverChain) + EmitZetaWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, receiverChain) } @@ -181,9 +182,6 @@ func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx zetacoretypes.CrossChainTx, re return fmt.Errorf("ProcessWithdrawalEvent: pay gas failed: %s", err.Error()) } - // Emit the event with cctx with updated amount for Zetaclient - EmitZetaWithdrawCreated(ctx, cctx) - if err := k.UpdateNonce(ctx, receiverChain.ChainId, &cctx); err != nil { return fmt.Errorf("ProcessWithdrawalEvent: update nonce failed: %s", err.Error()) } From c191688bdbb020a1964b29baa08c5107b0623276 Mon Sep 17 00:00:00 2001 From: lumtis Date: Fri, 18 Aug 2023 11:38:40 +0200 Subject: [PATCH 08/21] uncomment evm calls --- x/crosschain/keeper/keeper_utils.go | 40 ++++++++++++++--------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 887313fe8c..11aeaa8989 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -41,17 +41,17 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * gasLimit := sdk.NewUint(cctx.GetCurrentOutTxParam().OutboundTxGasLimit) outTxGasFee := gasLimit.Mul(medianGasPrice) - _ = outTxGasFee + //_ = outTxGasFee // the following logic computes outbound tx gas fee, and convert into ZETA using system uniswapv2 pool wzeta/gasZRC20 - //gasZRC20, err := k.fungibleKeeper.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chain.ChainId)) - //if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin") - //} - //outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) - //if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") - //} - outTxGasFeeInZeta := big.NewInt(1) + gasZRC20, err := k.fungibleKeeper.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chain.ChainId)) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin") + } + outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") + } + //outTxGasFeeInZeta := big.NewInt(1) feeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(outTxGasFeeInZeta)) cctx.ZetaFees = cctx.ZetaFees.Add(feeInZeta) @@ -72,16 +72,16 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * if err != nil { return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to mint coins") } - //amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) - //if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") - //} - //ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) - //ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) - //err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) - //if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") - //} + amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") + } + ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) + ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) + err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") + } } return nil From 2047f90cb5720af20ac1a2b54dcc7a01e83b8176 Mon Sep 17 00:00:00 2001 From: lumtis Date: Fri, 18 Aug 2023 16:35:25 +0200 Subject: [PATCH 09/21] experimentation --- .../localnet/orchestrator/smoketest/main.go | 2 +- x/crosschain/keeper/evm_hooks.go | 16 +++--- x/crosschain/keeper/keeper_utils.go | 50 ++++++++++--------- x/fungible/keeper/evm.go | 16 +++--- 4 files changed, 43 insertions(+), 41 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/main.go b/contrib/localnet/orchestrator/smoketest/main.go index ee798da969..19ed9da480 100644 --- a/contrib/localnet/orchestrator/smoketest/main.go +++ b/contrib/localnet/orchestrator/smoketest/main.go @@ -264,7 +264,7 @@ func LocalSmokeTest(_ *cobra.Command, _ []string) { // The following deployment must happen here and in this order, please do not change // ==================== Deploying contracts ==================== startTime := time.Now() - smokeTest.TestBitcoinSetup() + //smokeTest.TestBitcoinSetup() smokeTest.TestSetupZetaTokenAndConnectorAndZEVMContracts() smokeTest.TestDepositEtherIntoZRC20() smokeTest.TestSendZetaIn() diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index 16803021a6..45831baf6c 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -16,7 +16,7 @@ import ( "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/common" - zetacoretypes "github.com/zeta-chain/zetacore/x/crosschain/types" + types "github.com/zeta-chain/zetacore/x/crosschain/types" zetaObserverTypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -96,7 +96,7 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W return fmt.Errorf("cannot encode address %s: %s", event.To, err.Error()) } gasLimit := foreignCoin.GasLimit - msg := zetacoretypes.NewMsgSendVoter( + msg := types.NewMsgSendVoter( "", emittingContract.Hex(), senderChain.ChainId, @@ -113,7 +113,7 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W ) sendHash := msg.Digest() - cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, recvChain) + cctx := k.CreateNewCCTX(ctx, msg, sendHash, types.CctxStatus_PendingOutbound, &senderChain, recvChain) EmitZRCWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, recvChain) } @@ -138,17 +138,17 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC // Validation if we want to send ZETA to external chain, but there is no ZETA token. coreParams, found := k.zetaObserverKeeper.GetCoreParamsByChainID(ctx, receiverChain.ChainId) if !found { - return zetacoretypes.ErrNotFoundCoreParams + return types.ErrNotFoundCoreParams } if receiverChain.IsExternalChain() && coreParams.ZetaTokenContractAddress == "" { - return zetacoretypes.ErrUnableToSendCoinType + return types.ErrUnableToSendCoinType } toAddr := "0x" + hex.EncodeToString(event.DestinationAddress) senderChain := common.ZetaChain() amount := math.NewUintFromBigInt(event.ZetaValueAndGas) // Bump gasLimit by event index (which is very unlikely to be larger than 1000) to always have different ZetaSent events msgs. - msg := zetacoretypes.NewMsgSendVoter( + msg := types.NewMsgSendVoter( "", emittingContract.Hex(), senderChain.ChainId, @@ -165,12 +165,12 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC sendHash := msg.Digest() // Create the CCTX - cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, receiverChain) + cctx := k.CreateNewCCTX(ctx, msg, sendHash, types.CctxStatus_PendingOutbound, &senderChain, receiverChain) EmitZetaWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, receiverChain) } -func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx zetacoretypes.CrossChainTx, receiverChain *common.Chain) error { +func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx types.CrossChainTx, receiverChain *common.Chain) error { cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount inCctxIndex, ok := ctx.Value("inCctxIndex").(string) if ok { diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 11aeaa8989..5c56f6a71e 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -7,7 +7,6 @@ import ( "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" zetaObserverTypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -41,17 +40,19 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * gasLimit := sdk.NewUint(cctx.GetCurrentOutTxParam().OutboundTxGasLimit) outTxGasFee := gasLimit.Mul(medianGasPrice) - //_ = outTxGasFee // the following logic computes outbound tx gas fee, and convert into ZETA using system uniswapv2 pool wzeta/gasZRC20 gasZRC20, err := k.fungibleKeeper.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chain.ChainId)) if err != nil { return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin") } - outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") - } - //outTxGasFeeInZeta := big.NewInt(1) + + _ = outTxGasFee + _ = gasZRC20 + //outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) + //if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") + //} + outTxGasFeeInZeta := big.NewInt(1) feeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(outTxGasFeeInZeta)) cctx.ZetaFees = cctx.ZetaFees.Add(feeInZeta) @@ -66,23 +67,24 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * // ** The following logic converts the outTxGasFeeInZeta into gasZRC20 and burns it ** // swap the outTxGasFeeInZeta portion of zeta to the real gas ZRC20 and burn it, in a temporary context. - { - coins := sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(feeInZeta.BigInt()))) - err := k.bankKeeper.MintCoins(ctx, types.ModuleName, coins) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to mint coins") - } - amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") - } - ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) - ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) - err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) - if err != nil { - return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") - } - } + //{ + // coins := sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(feeInZeta.BigInt()))) + // err := k.bankKeeper.MintCoins(ctx, types.ModuleName, coins) + // if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to mint coins") + // } + // + // amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) + // if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") + // } + // ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) + // ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) + // err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) + // if err != nil { + // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") + // } + //} return nil } diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index 61caf8050c..cafde43247 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -447,14 +447,14 @@ func (k Keeper) CallEVMWithData( // emit events ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - evmtypes.EventTypeEthereumTx, - attrs..., - ), - sdk.NewEvent( - evmtypes.EventTypeTxLog, - txLogAttrs..., - ), + //sdk.NewEvent( + // evmtypes.EventTypeEthereumTx, + // attrs..., + //), + //sdk.NewEvent( + // evmtypes.EventTypeTxLog, + // txLogAttrs..., + //), sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), From 2e9a8dd1ccd57f959f8c02f658f18921e43a38ef Mon Sep 17 00:00:00 2001 From: lumtis Date: Sun, 20 Aug 2023 12:58:27 +0200 Subject: [PATCH 10/21] contrib/localnet/orchestrator/smoketest/main.go --- x/crosschain/keeper/keeper_utils.go | 47 +++++++++++++++-------------- x/fungible/keeper/evm.go | 10 +++--- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 5c56f6a71e..7eb4cfd0bc 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -2,6 +2,7 @@ package keeper import ( "fmt" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "math/big" "cosmossdk.io/math" @@ -48,11 +49,11 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * _ = outTxGasFee _ = gasZRC20 - //outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) - //if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") - //} - outTxGasFeeInZeta := big.NewInt(1) + outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") + } + //outTxGasFeeInZeta := big.NewInt(1) feeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(outTxGasFeeInZeta)) cctx.ZetaFees = cctx.ZetaFees.Add(feeInZeta) @@ -67,24 +68,24 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * // ** The following logic converts the outTxGasFeeInZeta into gasZRC20 and burns it ** // swap the outTxGasFeeInZeta portion of zeta to the real gas ZRC20 and burn it, in a temporary context. - //{ - // coins := sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(feeInZeta.BigInt()))) - // err := k.bankKeeper.MintCoins(ctx, types.ModuleName, coins) - // if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to mint coins") - // } - // - // amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) - // if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") - // } - // ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) - // ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) - // err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) - // if err != nil { - // return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") - // } - //} + { + coins := sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(feeInZeta.BigInt()))) + err := k.bankKeeper.MintCoins(ctx, types.ModuleName, coins) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to mint coins") + } + + amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") + } + ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) + ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) + err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) + if err != nil { + return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") + } + } return nil } diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index cafde43247..0b70630b71 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -427,7 +427,7 @@ func (k Keeper) CallEVMWithData( sdk.NewAttribute(evmtypes.AttributeKeyTxGasUsed, strconv.FormatUint(res.GasUsed, 10)), }...) - // receipient: contract address + // recipient: contract address if contract != nil { attrs = append(attrs, sdk.NewAttribute(evmtypes.AttributeKeyRecipient, contract.Hex())) } @@ -451,10 +451,10 @@ func (k Keeper) CallEVMWithData( // evmtypes.EventTypeEthereumTx, // attrs..., //), - //sdk.NewEvent( - // evmtypes.EventTypeTxLog, - // txLogAttrs..., - //), + sdk.NewEvent( + evmtypes.EventTypeTxLog, + txLogAttrs..., + ), sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), From 593538644c0d7af15d366b67c6960c078f27c098 Mon Sep 17 00:00:00 2001 From: lumtis Date: Sun, 20 Aug 2023 12:58:43 +0200 Subject: [PATCH 11/21] more experimentations --- contrib/localnet/orchestrator/smoketest/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/localnet/orchestrator/smoketest/main.go b/contrib/localnet/orchestrator/smoketest/main.go index 19ed9da480..ee798da969 100644 --- a/contrib/localnet/orchestrator/smoketest/main.go +++ b/contrib/localnet/orchestrator/smoketest/main.go @@ -264,7 +264,7 @@ func LocalSmokeTest(_ *cobra.Command, _ []string) { // The following deployment must happen here and in this order, please do not change // ==================== Deploying contracts ==================== startTime := time.Now() - //smokeTest.TestBitcoinSetup() + smokeTest.TestBitcoinSetup() smokeTest.TestSetupZetaTokenAndConnectorAndZEVMContracts() smokeTest.TestDepositEtherIntoZRC20() smokeTest.TestSendZetaIn() From 69409e1f3dd149757df15b28e79a132b1fb59b9d Mon Sep 17 00:00:00 2001 From: lumtis Date: Mon, 21 Aug 2023 17:36:19 +0200 Subject: [PATCH 12/21] add no ethereum tx event option --- x/crosschain/keeper/evm_hooks.go | 3 +- .../keeper_cross_chain_tx_vote_inbound_tx.go | 2 +- .../keeper_cross_chain_tx_vote_outbound_tx.go | 2 +- x/crosschain/keeper/keeper_utils.go | 28 ++- x/crosschain/types/expected_keepers.go | 3 +- x/fungible/keeper/evm.go | 168 ++++++++++-------- x/fungible/keeper/gas_coin_and_pool.go | 6 +- x/fungible/keeper/gas_price.go | 6 +- .../msg_server_update_system_contract.go | 6 +- .../msg_server_update_zrc20_withdraw_fee.go | 4 +- x/fungible/keeper/systemcontract.go | 26 +-- 11 files changed, 146 insertions(+), 108 deletions(-) diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index 72835e6548..e9fbfaf2f4 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -4,7 +4,6 @@ import ( "cosmossdk.io/math" "encoding/hex" "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" @@ -184,7 +183,7 @@ func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx types.CrossChainTx, receiverCh } // Pay gas in Zeta and update the amount for the cctx - if err := k.PayGasInZetaAndUpdateCctx(ctx, receiverChain.ChainId, &cctx); err != nil { + if err := k.PayGasInZetaAndUpdateCctx(ctx, receiverChain.ChainId, &cctx, true); err != nil { return fmt.Errorf("ProcessWithdrawalEvent: pay gas failed: %s", err.Error()) } diff --git a/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go index 0b3efe6d9e..8cafa2fdee 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go @@ -162,7 +162,7 @@ func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.Msg } else { // Cross Chain SWAP tmpCtx, commit := ctx.CacheContext() err = func() error { - err := k.PayGasInZetaAndUpdateCctx(tmpCtx, receiverChain.ChainId, &cctx) + err := k.PayGasInZetaAndUpdateCctx(tmpCtx, receiverChain.ChainId, &cctx, false) if err != nil { return err } diff --git a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go index c8849494f3..d1f1abf7bb 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go @@ -148,7 +148,7 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms CoinType: cctx.InboundTxParams.CoinType, OutboundTxGasLimit: cctx.OutboundTxParams[0].OutboundTxGasLimit, // NOTE(pwu): revert gas limit = initial outbound gas limit set by user; }) - err := k.PayGasInZetaAndUpdateCctx(tmpCtx, cctx.InboundTxParams.SenderChainId, &cctx) + err := k.PayGasInZetaAndUpdateCctx(tmpCtx, cctx.InboundTxParams.SenderChainId, &cctx, false) if err != nil { return err } diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 7eb4cfd0bc..c4cf1b18bb 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -26,15 +26,17 @@ func (k Keeper) IsAuthorizedNodeAccount(ctx sdk.Context, address string) bool { // it also makes a trade to fulfill the outbound tx gas fee in ZETA by swapping ZETA for some gas ZRC20 balances // The gas ZRC20 balance is subsequently burned to account for the expense of TSS address gas fee payment in the outbound tx. // **Caller should feed temporary ctx into this function** -func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx *types.CrossChainTx) error { - +func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx *types.CrossChainTx, noEthereumTxEvent bool) error { chain := k.zetaObserverKeeper.GetParams(ctx).GetChainFromChainID(chainID) if chain == nil { return zetaObserverTypes.ErrSupportedChains } medianGasPrice, isFound := k.GetMedianGasPriceInUint(ctx, chain.ChainId) if !isFound { - return sdkerrors.Wrap(types.ErrUnableToGetGasPrice, fmt.Sprintf(" chain %d | Identifiers : %s ", cctx.GetCurrentOutTxParam().ReceiverChainId, cctx.LogIdentifierForCCTX())) + return sdkerrors.Wrap(types.ErrUnableToGetGasPrice, fmt.Sprintf(" chain %d | Identifiers : %s ", + cctx.GetCurrentOutTxParam().ReceiverChainId, + cctx.LogIdentifierForCCTX()), + ) } medianGasPrice = medianGasPrice.MulUint64(2) // overpays gas price by 2x cctx.GetCurrentOutTxParam().OutboundTxGasPrice = medianGasPrice.String() @@ -47,19 +49,20 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin") } - _ = outTxGasFee - _ = gasZRC20 outTxGasFeeInZeta, err := k.fungibleKeeper.QueryUniswapv2RouterGetAmountsIn(ctx, outTxGasFee.BigInt(), gasZRC20) if err != nil { return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to QueryUniswapv2RouterGetAmountsIn") } - //outTxGasFeeInZeta := big.NewInt(1) feeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(outTxGasFeeInZeta)) cctx.ZetaFees = cctx.ZetaFees.Add(feeInZeta) if cctx.ZetaFees.GT(cctx.InboundTxParams.Amount) && cctx.InboundTxParams.CoinType == common.CoinType_Zeta { - return sdkerrors.Wrap(types.ErrNotEnoughZetaBurnt, fmt.Sprintf("feeInZeta(%s) more than zetaBurnt (%s) | Identifiers : %s ", cctx.ZetaFees, cctx.InboundTxParams.Amount, cctx.LogIdentifierForCCTX())) + return sdkerrors.Wrap(types.ErrNotEnoughZetaBurnt, fmt.Sprintf("feeInZeta(%s) more than zetaBurnt (%s) | Identifiers : %s ", + cctx.ZetaFees, + cctx.InboundTxParams.Amount, + cctx.LogIdentifierForCCTX()), + ) } ctx.Logger().Info("Substracting amount from inbound tx", "amount", cctx.InboundTxParams.Amount.String(), "feeInZeta", @@ -75,13 +78,20 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to mint coins") } - amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken(ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, outTxGasFeeInZeta, gasZRC20) + amounts, err := k.fungibleKeeper.CallUniswapv2RouterSwapExactETHForToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + outTxGasFeeInZeta, + gasZRC20, + noEthereumTxEvent, + ) if err != nil { return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") } ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) ctx.Logger().Info("CallUniswapv2RouterSwapExactETHForToken", "zetaAmountIn", amounts[0], "zrc20AmountOut", amounts[1]) - err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1]) + err = k.fungibleKeeper.CallZRC20Burn(ctx, types.ModuleAddressEVM, gasZRC20, amounts[1], noEthereumTxEvent) if err != nil { return sdkerrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallZRC20Burn") } diff --git a/x/crosschain/types/expected_keepers.go b/x/crosschain/types/expected_keepers.go index 55b4676d3f..6041ba8788 100644 --- a/x/crosschain/types/expected_keepers.go +++ b/x/crosschain/types/expected_keepers.go @@ -95,8 +95,9 @@ type FungibleKeeper interface { to eth.Address, amountIn *big.Int, outZRC4 eth.Address, + noEthereumTxEvent bool, ) ([]*big.Int, error) - CallZRC20Burn(ctx sdk.Context, sender eth.Address, zrc20address eth.Address, amount *big.Int) error + CallZRC20Burn(ctx sdk.Context, sender eth.Address, zrc20address eth.Address, amount *big.Int, noEthereumTxEvent bool) error DeployZRC20Contract( ctx sdk.Context, name, symbol string, diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index 0b70630b71..825fe4321b 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -139,7 +139,7 @@ func (k Keeper) deployContract(ctx sdk.Context, metadata *bind.MetaData, ctorArg } contractAddr := crypto.CreateAddress(types.ModuleAddressEVM, nonce) - _, err = k.CallEVMWithData(ctx, types.ModuleAddressEVM, nil, data, true, BigIntZero, nil) + _, err = k.CallEVMWithData(ctx, types.ModuleAddressEVM, nil, data, true, false, BigIntZero, nil) if err != nil { return common.Address{}, sdkerrors.Wrapf(err, "failed to deploy contract") } @@ -202,7 +202,7 @@ func (k Keeper) DepositZRC20( if err != nil { return nil, err } - return k.CallEVM(ctx, *abi, types.ModuleAddressEVM, contract, BigIntZero, nil, true, "deposit", to, amount) + return k.CallEVM(ctx, *abi, types.ModuleAddressEVM, contract, BigIntZero, nil, true, false, "deposit", to, amount) } // Deposit into ZRC4 and call contract function in a single tx @@ -225,7 +225,7 @@ func (k Keeper) DepositZRC20AndCallContract(ctx sdk.Context, return nil, err } - return k.CallEVM(ctx, *sysConABI, types.ModuleAddressEVM, systemAddress, BigIntZero, ZEVMGasLimitDepositAndCall, true, + return k.CallEVM(ctx, *sysConABI, types.ModuleAddressEVM, systemAddress, BigIntZero, ZEVMGasLimitDepositAndCall, true, false, "depositAndCall", context, zrc20Addr, amount, targetContract, message) } @@ -243,7 +243,7 @@ func (k Keeper) QueryZRC20Data( zrc4, _ := zrc20.ZRC20MetaData.GetAbi() // Name - res, err := k.CallEVM(ctx, *zrc4, types.ModuleAddressEVM, contract, BigIntZero, nil, false, "name") + res, err := k.CallEVM(ctx, *zrc4, types.ModuleAddressEVM, contract, BigIntZero, nil, false, false, "name") if err != nil { return types.ZRC20Data{}, err } @@ -255,7 +255,7 @@ func (k Keeper) QueryZRC20Data( } // Symbol - res, err = k.CallEVM(ctx, *zrc4, types.ModuleAddressEVM, contract, BigIntZero, nil, false, "symbol") + res, err = k.CallEVM(ctx, *zrc4, types.ModuleAddressEVM, contract, BigIntZero, nil, false, false, "symbol") if err != nil { return types.ZRC20Data{}, err } @@ -267,7 +267,7 @@ func (k Keeper) QueryZRC20Data( } // Decimals - res, err = k.CallEVM(ctx, *zrc4, types.ModuleAddressEVM, contract, BigIntZero, nil, false, "decimals") + res, err = k.CallEVM(ctx, *zrc4, types.ModuleAddressEVM, contract, BigIntZero, nil, false, false, "decimals") if err != nil { return types.ZRC20Data{}, err } @@ -290,7 +290,8 @@ func (k Keeper) BalanceOfZRC4( if err != nil { return nil } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, contract, BigIntZero, nil, false, "balanceOf", account) + res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, contract, BigIntZero, nil, false, false, "balanceOf", + account) if err != nil { return nil } @@ -317,9 +318,9 @@ func (k Keeper) CallEVM( ctx sdk.Context, abi abi.ABI, from, contract common.Address, - value *big.Int, - gasLimit *big.Int, + value, gasLimit *big.Int, commit bool, + noEthereumTxEvent bool, method string, args ...interface{}, ) (*evmtypes.MsgEthereumTxResponse, error) { @@ -332,7 +333,7 @@ func (k Keeper) CallEVM( } k.Logger(ctx).Debug("calling EVM", "from", from, "contract", contract, "value", value, "method", method) - resp, err := k.CallEVMWithData(ctx, from, &contract, data, commit, value, gasLimit) + resp, err := k.CallEVMWithData(ctx, from, &contract, data, commit, noEthereumTxEvent, value, gasLimit) if err != nil { return resp, sdkerrors.Wrapf(err, "contract call failed: method '%s', contract '%s'", method, contract) } @@ -352,6 +353,7 @@ func (k Keeper) CallEVMWithData( contract *common.Address, data []byte, commit bool, + noEthereumTxEvent bool, value *big.Int, gasLimit *big.Int, ) (*evmtypes.MsgEthereumTxResponse, error) { @@ -408,69 +410,93 @@ func (k Keeper) CallEVMWithData( return res, sdkerrors.Wrap(evmtypes.ErrVMExecution, fmt.Sprintf("%s: ret 0x%x", res.VmError, res.Ret)) } - msgBytes, _ := json.Marshal(msg) - ethTxHash := common.BytesToHash(crypto.Keccak256(msgBytes)) // NOTE(pwu): this is a fake txhash - attrs := []sdk.Attribute{} - if len(ctx.TxBytes()) > 0 { - // add event for tendermint transaction hash format - hash := tmbytes.HexBytes(tmtypes.Tx(ctx.TxBytes()).Hash()) - ethTxHash = common.BytesToHash(hash) // NOTE(pwu): use cosmos tx hash as eth tx hash if available - attrs = append(attrs, sdk.NewAttribute(evmtypes.AttributeKeyTxHash, hash.String())) - } - attrs = append(attrs, []sdk.Attribute{ - sdk.NewAttribute(sdk.AttributeKeyAmount, value.String()), - // add event for ethereum transaction hash format; NOTE(pwu): this is a fake txhash - sdk.NewAttribute(evmtypes.AttributeKeyEthereumTxHash, ethTxHash.String()), - // add event for index of valid ethereum tx; NOTE(pwu): fake txindex - sdk.NewAttribute(evmtypes.AttributeKeyTxIndex, strconv.FormatUint(8888, 10)), - // add event for eth tx gas used, we can't get it from cosmos tx result when it contains multiple eth tx msgs. - sdk.NewAttribute(evmtypes.AttributeKeyTxGasUsed, strconv.FormatUint(res.GasUsed, 10)), - }...) - - // recipient: contract address - if contract != nil { - attrs = append(attrs, sdk.NewAttribute(evmtypes.AttributeKeyRecipient, contract.Hex())) - } - if res.Failed() { - attrs = append(attrs, sdk.NewAttribute(evmtypes.AttributeKeyEthereumTxFailed, res.VmError)) - } + // Emit events and log for the transaction if it is committed + if commit { + msgBytes, _ := json.Marshal(msg) + ethTxHash := common.BytesToHash(crypto.Keccak256(msgBytes)) // NOTE(pwu): this is a fake txhash + attrs := []sdk.Attribute{} + if len(ctx.TxBytes()) > 0 { + // add event for tendermint transaction hash format + hash := tmbytes.HexBytes(tmtypes.Tx(ctx.TxBytes()).Hash()) + ethTxHash = common.BytesToHash(hash) // NOTE(pwu): use cosmos tx hash as eth tx hash if available + attrs = append(attrs, sdk.NewAttribute(evmtypes.AttributeKeyTxHash, hash.String())) + } + attrs = append(attrs, []sdk.Attribute{ + sdk.NewAttribute(sdk.AttributeKeyAmount, value.String()), + // add event for ethereum transaction hash format; NOTE(pwu): this is a fake txhash + sdk.NewAttribute(evmtypes.AttributeKeyEthereumTxHash, ethTxHash.String()), + // add event for index of valid ethereum tx; NOTE(pwu): fake txindex + sdk.NewAttribute(evmtypes.AttributeKeyTxIndex, strconv.FormatUint(8888, 10)), + // add event for eth tx gas used, we can't get it from cosmos tx result when it contains multiple eth tx msgs. + sdk.NewAttribute(evmtypes.AttributeKeyTxGasUsed, strconv.FormatUint(res.GasUsed, 10)), + }...) + + // recipient: contract address + if contract != nil { + attrs = append(attrs, sdk.NewAttribute(evmtypes.AttributeKeyRecipient, contract.Hex())) + } + if res.Failed() { + attrs = append(attrs, sdk.NewAttribute(evmtypes.AttributeKeyEthereumTxFailed, res.VmError)) + } - txLogAttrs := make([]sdk.Attribute, len(res.Logs)) - for i, log := range res.Logs { - log.TxHash = ethTxHash.String() - value, err := json.Marshal(log) - if err != nil { - return nil, sdkerrors.Wrap(err, "failed to encode log") + txLogAttrs := make([]sdk.Attribute, len(res.Logs)) + for i, log := range res.Logs { + log.TxHash = ethTxHash.String() + value, err := json.Marshal(log) + if err != nil { + return nil, sdkerrors.Wrap(err, "failed to encode log") + } + txLogAttrs[i] = sdk.NewAttribute(evmtypes.AttributeKeyTxLog, string(value)) + } + + // emit events + //var events sdk.Events + //if !noEthereumTxEvent { + // events = sdk.Events{sdk.NewEvent( + // evmtypes.EventTypeEthereumTx, + // attrs..., + // )} + //} + //events = append(events, + // sdk.NewEvent( + // evmtypes.EventTypeTxLog, + // txLogAttrs..., + // ), + // sdk.NewEvent( + // sdk.EventTypeMessage, + // sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + // sdk.NewAttribute(sdk.AttributeKeySender, from.Hex()), + // sdk.NewAttribute(evmtypes.AttributeKeyTxType, "88"), // type 88: synthetic Eth tx + // ), + //) + if !noEthereumTxEvent { + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + evmtypes.EventTypeEthereumTx, + attrs..., + ), + sdk.NewEvent( + evmtypes.EventTypeTxLog, + txLogAttrs..., + ), + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(sdk.AttributeKeySender, from.Hex()), + sdk.NewAttribute(evmtypes.AttributeKeyTxType, "88"), // type 88: synthetic Eth tx + ), + }) + } + + logs := evmtypes.LogsToEthereum(res.Logs) + var bloomReceipt ethtypes.Bloom + if len(logs) > 0 { + bloom := k.evmKeeper.GetBlockBloomTransient(ctx) + bloom.Or(bloom, big.NewInt(0).SetBytes(ethtypes.LogsBloom(logs))) + bloomReceipt = ethtypes.BytesToBloom(bloom.Bytes()) + k.evmKeeper.SetBlockBloomTransient(ctx, bloomReceipt.Big()) + k.evmKeeper.SetLogSizeTransient(ctx, (k.evmKeeper.GetLogSizeTransient(ctx))+uint64(len(logs))) } - txLogAttrs[i] = sdk.NewAttribute(evmtypes.AttributeKeyTxLog, string(value)) - } - - // emit events - ctx.EventManager().EmitEvents(sdk.Events{ - //sdk.NewEvent( - // evmtypes.EventTypeEthereumTx, - // attrs..., - //), - sdk.NewEvent( - evmtypes.EventTypeTxLog, - txLogAttrs..., - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, from.Hex()), - sdk.NewAttribute(evmtypes.AttributeKeyTxType, "88"), // type 88: synthetic Eth tx - ), - }) - - logs := evmtypes.LogsToEthereum(res.Logs) - var bloomReceipt ethtypes.Bloom - if len(logs) > 0 { - bloom := k.evmKeeper.GetBlockBloomTransient(ctx) - bloom.Or(bloom, big.NewInt(0).SetBytes(ethtypes.LogsBloom(logs))) - bloomReceipt = ethtypes.BytesToBloom(bloom.Bytes()) - k.evmKeeper.SetBlockBloomTransient(ctx, bloomReceipt.Big()) - k.evmKeeper.SetLogSizeTransient(ctx, (k.evmKeeper.GetLogSizeTransient(ctx))+uint64(len(logs))) } return res, nil diff --git a/x/fungible/keeper/gas_coin_and_pool.go b/x/fungible/keeper/gas_coin_and_pool.go index 7ec58c362e..1048923b46 100644 --- a/x/fungible/keeper/gas_coin_and_pool.go +++ b/x/fungible/keeper/gas_coin_and_pool.go @@ -63,7 +63,7 @@ func (k Keeper) setupChainGasCoinAndPool(ctx sdk.Context, chainID int64, gasAsse if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to get system contract abi") } - _, err = k.CallEVM(ctx, *systemABI, types.ModuleAddressEVM, systemContractAddress, BigIntZero, nil, true, "setGasZetaPool", big.NewInt(chain.ChainId), zrc20Addr) + _, err = k.CallEVM(ctx, *systemABI, types.ModuleAddressEVM, systemContractAddress, BigIntZero, nil, true, false, "setGasZetaPool", big.NewInt(chain.ChainId), zrc20Addr) if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to CallEVM method setGasZetaPool(%d, %s)", chain.ChainId, zrc20Addr.String()) } @@ -81,7 +81,7 @@ func (k Keeper) setupChainGasCoinAndPool(ctx sdk.Context, chainID int64, gasAsse if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to GetAbi zrc20") } - _, err = k.CallEVM(ctx, *ZRC20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, "approve", routerAddress, amount) + _, err = k.CallEVM(ctx, *ZRC20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, false, "approve", routerAddress, amount) if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to CallEVM method approve(%s, %d)", routerAddress.String(), amount) } @@ -93,7 +93,7 @@ func (k Keeper) setupChainGasCoinAndPool(ctx sdk.Context, chainID int64, gasAsse // address to, // uint deadline //) external payable returns (uint amountToken, uint amountETH, uint liquidity); - res, err := k.CallEVM(ctx, *routerABI, types.ModuleAddressEVM, routerAddress, amount, big.NewInt(5_000_000), true, + res, err := k.CallEVM(ctx, *routerABI, types.ModuleAddressEVM, routerAddress, amount, big.NewInt(5_000_000), true, false, "addLiquidityETH", zrc20Addr, amount, BigIntZero, BigIntZero, types.ModuleAddressEVM, amountAZeta) if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to CallEVM method addLiquidityETH(%s, %s)", zrc20Addr.String(), amountAZeta.String()) diff --git a/x/fungible/keeper/gas_price.go b/x/fungible/keeper/gas_price.go index 2f3b19d2f0..cca8c03597 100644 --- a/x/fungible/keeper/gas_price.go +++ b/x/fungible/keeper/gas_price.go @@ -24,7 +24,7 @@ func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int if err != nil { return 0, sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, big.NewInt(50_000), true, "setGasPrice", chainid, gasPrice) + res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, big.NewInt(50_000), true, false, "setGasPrice", chainid, gasPrice) if err != nil || res.Failed() { return res.GasUsed, sdkerrors.Wrapf(types.ErrContractCall, "setGasPrice") } @@ -45,7 +45,7 @@ func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address common.Add if err != nil { return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, "setGasCoinZRC20", chainid, address) + res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasCoinZRC20", chainid, address) if err != nil || res.Failed() { return sdkerrors.Wrapf(types.ErrContractCall, "setGasCoinZRC20") } @@ -66,7 +66,7 @@ func (k Keeper) SetGasZetaPool(ctx sdk.Context, chainid *big.Int, pool common.Ad if err != nil { return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, "SetGasZetaPool", chainid, pool) + res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "SetGasZetaPool", chainid, pool) if err != nil || res.Failed() { return sdkerrors.Wrapf(types.ErrContractCall, "SetGasZetaPool") } diff --git a/x/fungible/keeper/msg_server_update_system_contract.go b/x/fungible/keeper/msg_server_update_system_contract.go index d88a52c554..dcdb2f6bfc 100644 --- a/x/fungible/keeper/msg_server_update_system_contract.go +++ b/x/fungible/keeper/msg_server_update_system_contract.go @@ -41,16 +41,16 @@ func (k Keeper) UpdateSystemContract(goCtx context.Context, msg *types.MsgUpdate k.Logger(ctx).Error("invalid zrc20 contract address", "address", fcoin.Zrc20ContractAddress) continue } - _, err = k.CallEVM(tmpCtx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, "updateSystemContractAddress", newSystemContractAddr) + _, err = k.CallEVM(tmpCtx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, false, "updateSystemContractAddress", newSystemContractAddr) if err != nil { return nil, sdkerrors.Wrapf(types.ErrContractCall, "failed to call zrc20 contract method updateSystemContractAddress (%s)", err.Error()) } if fcoin.CoinType == common.CoinType_Gas { - _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, "setGasCoinZRC20", big.NewInt(fcoin.ForeignChainId), zrc20Addr) + _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, false, "setGasCoinZRC20", big.NewInt(fcoin.ForeignChainId), zrc20Addr) if err != nil { return nil, sdkerrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasCoinZRC20 (%s)", err.Error()) } - _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, "setGasZetaPool", big.NewInt(fcoin.ForeignChainId), zrc20Addr) + _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, false, "setGasZetaPool", big.NewInt(fcoin.ForeignChainId), zrc20Addr) if err != nil { return nil, sdkerrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasZetaPool (%s)", err.Error()) } diff --git a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go index 8bb7fa4181..dc6d18864a 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go +++ b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go @@ -48,7 +48,7 @@ func (k Keeper) UpdateZRC20WithdrawFee(goCtx context.Context, msg *types.MsgUpda return nil, sdkerrors.Wrapf(types.ErrInvalidAddress, "no foreign coin match requested zrc20 address (%s)", msg.Zrc20Address) } - res, err := k.CallEVM(ctx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, false, "PROTOCOL_FLAT_FEE") + res, err := k.CallEVM(ctx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, false, false, "PROTOCOL_FLAT_FEE") if err != nil { return nil, sdkerrors.Wrapf(types.ErrContractCall, "failed to call zrc20 contract PROTOCOL_FLAT_FEE method (%s)", err.Error()) } @@ -62,7 +62,7 @@ func (k Keeper) UpdateZRC20WithdrawFee(goCtx context.Context, msg *types.MsgUpda } tmpCtx, commit := ctx.CacheContext() - _, err = k.CallEVM(tmpCtx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, "updateProtocolFlatFee", msg.NewWithdrawFee.BigInt()) + _, err = k.CallEVM(tmpCtx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, false, "updateProtocolFlatFee", msg.NewWithdrawFee.BigInt()) err = ctx.EventManager().EmitTypedEvent( &types.EventZRC20WithdrawFeeUpdated{ diff --git a/x/fungible/keeper/systemcontract.go b/x/fungible/keeper/systemcontract.go index 23231f6b16..2ae6c46c46 100644 --- a/x/fungible/keeper/systemcontract.go +++ b/x/fungible/keeper/systemcontract.go @@ -37,7 +37,7 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, _ := systemcontract.SystemContractMetaData.GetAbi() - res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, "wZetaContractAddress") + res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "wZetaContractAddress") if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to call wZetaContractAddress") } @@ -59,7 +59,7 @@ func (k *Keeper) GetUniswapv2FacotryAddress(ctx sdk.Context) (ethcommon.Address, systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, _ := systemcontract.SystemContractMetaData.GetAbi() - res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, "uniswapv2FactoryAddress") + res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "uniswapv2FactoryAddress") if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to call uniswapv2FactoryAddress") } @@ -81,7 +81,7 @@ func (k *Keeper) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, _ := systemcontract.SystemContractMetaData.GetAbi() - res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, "uniswapv2Router02Address") + res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "uniswapv2Router02Address") if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to call uniswapv2Router02Address") } @@ -102,7 +102,7 @@ func (k *Keeper) CallWZetaDeposit(ctx sdk.Context, sender ethcommon.Address, amo } wzetaABI, _ := connectorzevm.WZETAMetaData.GetAbi() gasLimit := big.NewInt(70_000) // for some reason, GasEstimate for this contract call is always insufficient - _, err = k.CallEVM(ctx, *wzetaABI, sender, wzetaAddress, amount, gasLimit, true, "deposit") + _, err = k.CallEVM(ctx, *wzetaABI, sender, wzetaAddress, amount, gasLimit, true, false, "deposit") if err != nil { return sdkerrors.Wrapf(err, "failed to call wzeta deposit") } @@ -115,7 +115,7 @@ func (k *Keeper) QueryWZetaBalanceOf(ctx sdk.Context, addr ethcommon.Address) (* return nil, sdkerrors.Wrapf(err, "failed to get wzeta contract address") } wzetaABI, _ := connectorzevm.WZETAMetaData.GetAbi() - res, err := k.CallEVM(ctx, *wzetaABI, addr, wzetaAddress, big.NewInt(0), nil, false, "balanceOf", addr) + res, err := k.CallEVM(ctx, *wzetaABI, addr, wzetaAddress, big.NewInt(0), nil, false, false, "balanceOf", addr) if err != nil { return nil, sdkerrors.Wrapf(err, "failed to call balanceOf") } @@ -137,7 +137,7 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, _ := systemcontract.SystemContractMetaData.GetAbi() - res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, "gasCoinZRC20ByChainId", chainid) + res, err := k.CallEVM(ctx, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "gasCoinZRC20ByChainId", chainid) if err != nil { return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to call gasCoinZRC20ByChainId") } @@ -152,7 +152,8 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I } // returns the amount [in, out] -func (k *Keeper) CallUniswapv2RouterSwapExactETHForToken(ctx sdk.Context, sender ethcommon.Address, to ethcommon.Address, amountIn *big.Int, outZRC4 ethcommon.Address) ([]*big.Int, error) { +func (k *Keeper) CallUniswapv2RouterSwapExactETHForToken(ctx sdk.Context, sender ethcommon.Address, + to ethcommon.Address, amountIn *big.Int, outZRC4 ethcommon.Address, noEthereumTxEvent bool) ([]*big.Int, error) { routerABI, err := uniswapv2router02.UniswapV2Router02MetaData.GetAbi() if err != nil { return nil, sdkerrors.Wrapf(err, "failed to get router abi") @@ -167,7 +168,7 @@ func (k *Keeper) CallUniswapv2RouterSwapExactETHForToken(ctx sdk.Context, sender } //function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable //returns (uint[] memory amounts); - res, err := k.CallEVM(ctx, *routerABI, sender, routerAddress, amountIn, big.NewInt(300_000), true, + res, err := k.CallEVM(ctx, *routerABI, sender, routerAddress, amountIn, big.NewInt(300_000), true, noEthereumTxEvent, "swapExactETHForTokens", BigIntZero, []ethcommon.Address{wzeta, outZRC4}, to, big.NewInt(1e17)) if err != nil { return nil, sdkerrors.Wrapf(err, "failed to CallEVM method swapExactETHForTokens") @@ -197,7 +198,7 @@ func (k *Keeper) CallUniswapv2RouterSwapEthForExactToken(ctx sdk.Context, sender } //function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) //returns (uint[] memory amounts); - res, err := k.CallEVM(ctx, *routerABI, sender, routerAddress, maxAmountIn, big.NewInt(300_000), true, + res, err := k.CallEVM(ctx, *routerABI, sender, routerAddress, maxAmountIn, big.NewInt(300_000), true, false, "swapETHForExactTokens", amountOut, []ethcommon.Address{wzeta, outZRC4}, to, big.NewInt(1e17)) if err != nil { return nil, sdkerrors.Wrapf(err, "failed to CallEVM method swapETHForExactTokens") @@ -227,7 +228,7 @@ func (k *Keeper) QueryUniswapv2RouterGetAmountsIn(ctx sdk.Context, amountOut *bi } //function getAmountsIn(uint amountOut, address[] memory path) public view returns (uint[] memory amounts); k.Logger(ctx).Info("getAmountsIn", "outZRC20", outZRC4.Hex(), "amountOut", amountOut, "wzeta", wzeta.Hex()) - res, err := k.CallEVM(ctx, *routerABI, types.ModuleAddressEVM, routerAddress, BigIntZero, nil, false, + res, err := k.CallEVM(ctx, *routerABI, types.ModuleAddressEVM, routerAddress, BigIntZero, nil, false, false, "getAmountsIn", amountOut, []ethcommon.Address{wzeta, outZRC4}) if err != nil { return nil, sdkerrors.Wrapf(err, "failed to CallEVM method getAmountsIn") @@ -241,12 +242,13 @@ func (k *Keeper) QueryUniswapv2RouterGetAmountsIn(ctx sdk.Context, amountOut *bi return (*amounts)[0], nil } -func (k *Keeper) CallZRC20Burn(ctx sdk.Context, sender ethcommon.Address, zrc20address ethcommon.Address, amount *big.Int) error { +func (k *Keeper) CallZRC20Burn(ctx sdk.Context, sender ethcommon.Address, zrc20address ethcommon.Address, + amount *big.Int, noEthereumTxEvent bool) error { zrc20ABI, err := zrc20.ZRC20MetaData.GetAbi() if err != nil { return sdkerrors.Wrapf(err, "failed to get zrc20 abi") } - _, err = k.CallEVM(ctx, *zrc20ABI, sender, zrc20address, big.NewInt(0), big.NewInt(100_000), true, + _, err = k.CallEVM(ctx, *zrc20ABI, sender, zrc20address, big.NewInt(0), big.NewInt(100_000), true, noEthereumTxEvent, "burn", amount) if err != nil { return sdkerrors.Wrapf(err, "failed to CallEVM method burn") From 5d091efa0320fa49f96fae47bbf92a970ec10677 Mon Sep 17 00:00:00 2001 From: lumtis Date: Mon, 21 Aug 2023 17:36:34 +0200 Subject: [PATCH 13/21] goimports --- contrib/localnet/orchestrator/smoketest/utils.go | 3 ++- x/crosschain/keeper/evm_hooks.go | 3 ++- x/crosschain/keeper/keeper_utils.go | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/utils.go b/contrib/localnet/orchestrator/smoketest/utils.go index 8d60a20038..3db87d36f9 100644 --- a/contrib/localnet/orchestrator/smoketest/utils.go +++ b/contrib/localnet/orchestrator/smoketest/utils.go @@ -8,10 +8,11 @@ import ( "encoding/hex" "errors" "fmt" - "github.com/ethereum/go-ethereum" "sync" "time" + "github.com/ethereum/go-ethereum" + "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcutil" diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index e9fbfaf2f4..1951980497 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -1,9 +1,10 @@ package keeper import ( - "cosmossdk.io/math" "encoding/hex" "fmt" + + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index c4cf1b18bb..943d1c4963 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -2,9 +2,10 @@ package keeper import ( "fmt" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" "math/big" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" From 5ac36f6285d0458aed807fd3629ff4da8e941dc1 Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 22 Aug 2023 11:10:31 +0200 Subject: [PATCH 14/21] prevent non zeta coin paying gas --- x/crosschain/keeper/evm_hooks.go | 14 ++++++++------ x/crosschain/keeper/keeper_utils.go | 9 +++++++-- x/fungible/keeper/evm.go | 20 -------------------- x/observer/types/errors.go | 1 + 4 files changed, 16 insertions(+), 28 deletions(-) diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index 1951980497..e2a3dc1eee 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -115,6 +115,7 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W sendHash := msg.Digest() cctx := k.CreateNewCCTX(ctx, msg, sendHash, types.CctxStatus_PendingOutbound, &senderChain, recvChain) + cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount EmitZRCWithdrawCreated(ctx, cctx) return k.ProcessCCTX(ctx, cctx, recvChain) } @@ -172,22 +173,23 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC // Create the CCTX cctx := k.CreateNewCCTX(ctx, msg, sendHash, types.CctxStatus_PendingOutbound, &senderChain, receiverChain) + + // Pay gas in Zeta and update the amount for the cctx + if err := k.PayGasInZetaAndUpdateCctx(ctx, receiverChain.ChainId, &cctx, true); err != nil { + return fmt.Errorf("ProcessWithdrawalEvent: pay gas failed: %s", err.Error()) + } + EmitZetaWithdrawCreated(ctx, cctx) + return k.ProcessCCTX(ctx, cctx, receiverChain) } func (k Keeper) ProcessCCTX(ctx sdk.Context, cctx types.CrossChainTx, receiverChain *common.Chain) error { - cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount inCctxIndex, ok := ctx.Value("inCctxIndex").(string) if ok { cctx.InboundTxParams.InboundTxObservedHash = inCctxIndex } - // Pay gas in Zeta and update the amount for the cctx - if err := k.PayGasInZetaAndUpdateCctx(ctx, receiverChain.ChainId, &cctx, true); err != nil { - return fmt.Errorf("ProcessWithdrawalEvent: pay gas failed: %s", err.Error()) - } - if err := k.UpdateNonce(ctx, receiverChain.ChainId, &cctx); err != nil { return fmt.Errorf("ProcessWithdrawalEvent: update nonce failed: %s", err.Error()) } diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 943d1c4963..bac7248ff9 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -4,12 +4,13 @@ import ( "fmt" "math/big" + "github.com/zeta-chain/zetacore/common" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" zetaObserverTypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -28,6 +29,10 @@ func (k Keeper) IsAuthorizedNodeAccount(ctx sdk.Context, address string) bool { // The gas ZRC20 balance is subsequently burned to account for the expense of TSS address gas fee payment in the outbound tx. // **Caller should feed temporary ctx into this function** func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx *types.CrossChainTx, noEthereumTxEvent bool) error { + if cctx.InboundTxParams.CoinType == common.CoinType_Zeta { + return sdkerrors.Wrap(zetaObserverTypes.ErrInvalidCoinType, "can't pay gas in zeta with non zeta coin") + } + chain := k.zetaObserverKeeper.GetParams(ctx).GetChainFromChainID(chainID) if chain == nil { return zetaObserverTypes.ErrSupportedChains @@ -58,7 +63,7 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * cctx.ZetaFees = cctx.ZetaFees.Add(feeInZeta) - if cctx.ZetaFees.GT(cctx.InboundTxParams.Amount) && cctx.InboundTxParams.CoinType == common.CoinType_Zeta { + if cctx.ZetaFees.GT(cctx.InboundTxParams.Amount) { return sdkerrors.Wrap(types.ErrNotEnoughZetaBurnt, fmt.Sprintf("feeInZeta(%s) more than zetaBurnt (%s) | Identifiers : %s ", cctx.ZetaFees, cctx.InboundTxParams.Amount, diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index 825fe4321b..892c6114ab 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -449,26 +449,6 @@ func (k Keeper) CallEVMWithData( txLogAttrs[i] = sdk.NewAttribute(evmtypes.AttributeKeyTxLog, string(value)) } - // emit events - //var events sdk.Events - //if !noEthereumTxEvent { - // events = sdk.Events{sdk.NewEvent( - // evmtypes.EventTypeEthereumTx, - // attrs..., - // )} - //} - //events = append(events, - // sdk.NewEvent( - // evmtypes.EventTypeTxLog, - // txLogAttrs..., - // ), - // sdk.NewEvent( - // sdk.EventTypeMessage, - // sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - // sdk.NewAttribute(sdk.AttributeKeySender, from.Hex()), - // sdk.NewAttribute(evmtypes.AttributeKeyTxType, "88"), // type 88: synthetic Eth tx - // ), - //) if !noEthereumTxEvent { ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( diff --git a/x/observer/types/errors.go b/x/observer/types/errors.go index 56aca3ecb5..47165a38c9 100644 --- a/x/observer/types/errors.go +++ b/x/observer/types/errors.go @@ -24,4 +24,5 @@ var ( ErrKeygenBlockTooLow = errorsmod.Register(ModuleName, 1114, "Please set a block number at-least 10 blocks higher than the current block number") ErrKeygenCompleted = errorsmod.Register(ModuleName, 1115, "Keygen already completed") ErrNotAuthorized = errorsmod.Register(ModuleName, 1116, "Err not authorized") + ErrInvalidCoinType = errorsmod.Register(ModuleName, 1117, "Invalid coin type") ) From 0e75433ca8870c6e1b8afa5ae3d15cdb34f8ee8c Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 22 Aug 2023 11:26:24 +0200 Subject: [PATCH 15/21] zeta condition fix --- x/crosschain/keeper/keeper_utils.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index bac7248ff9..7199165b07 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -29,8 +29,8 @@ func (k Keeper) IsAuthorizedNodeAccount(ctx sdk.Context, address string) bool { // The gas ZRC20 balance is subsequently burned to account for the expense of TSS address gas fee payment in the outbound tx. // **Caller should feed temporary ctx into this function** func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx *types.CrossChainTx, noEthereumTxEvent bool) error { - if cctx.InboundTxParams.CoinType == common.CoinType_Zeta { - return sdkerrors.Wrap(zetaObserverTypes.ErrInvalidCoinType, "can't pay gas in zeta with non zeta coin") + if cctx.InboundTxParams.CoinType != common.CoinType_Zeta { + return sdkerrors.Wrapf(zetaObserverTypes.ErrInvalidCoinType, "can't pay gas in zeta with %s", cctx.InboundTxParams.CoinType.String()) } chain := k.zetaObserverKeeper.GetParams(ctx).GetChainFromChainID(chainID) From 6b3bd325a3730908e21460a84e2774a201dfb1d0 Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 22 Aug 2023 11:38:01 +0200 Subject: [PATCH 16/21] uncomment out smoketests --- .../localnet/orchestrator/smoketest/main.go | 74 +++++++++---------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/main.go b/contrib/localnet/orchestrator/smoketest/main.go index ee798da969..99b7da29a2 100644 --- a/contrib/localnet/orchestrator/smoketest/main.go +++ b/contrib/localnet/orchestrator/smoketest/main.go @@ -304,45 +304,45 @@ func LocalSmokeTest(_ *cobra.Command, _ []string) { fmt.Printf("## Ether on Ethereum private net\n") fmt.Printf("## ZETA on ZetaChain EVM\n") fmt.Printf("## ETH ZRC20 on ZetaChain\n") - //// The following tests are optional tests; comment out the ones you don't want to run - //// temporarily to reduce dev/test cycle turnaround time - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestContextUpgrade() - // - //smokeTest.TestDepositAndCallRefund() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestERC20Deposit() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestERC20Withdraw() - ////smokeTest.WithdrawBitcoinMultipleTimes(5) - //smokeTest.CheckZRC20ReserveAndSupply() - // + // The following tests are optional tests; comment out the ones you don't want to run + // temporarily to reduce dev/test cycle turnaround time + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestContextUpgrade() + + smokeTest.TestDepositAndCallRefund() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestERC20Deposit() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestERC20Withdraw() + //smokeTest.WithdrawBitcoinMultipleTimes(5) + smokeTest.CheckZRC20ReserveAndSupply() + smokeTest.TestSendZetaOut() smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestSendZetaOutBTCRevert() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestMessagePassing() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestZRC20Swap() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestBitcoinWithdraw() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestCrosschainSwap() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestMessagePassingRevertFail() - //smokeTest.CheckZRC20ReserveAndSupply() - // - //smokeTest.TestMessagePassingRevertSuccess() - //smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestSendZetaOutBTCRevert() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestMessagePassing() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestZRC20Swap() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestBitcoinWithdraw() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestCrosschainSwap() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestMessagePassingRevertFail() + smokeTest.CheckZRC20ReserveAndSupply() + + smokeTest.TestMessagePassingRevertSuccess() + smokeTest.CheckZRC20ReserveAndSupply() // add your dev test here smokeTest.TestMyTest() From 9f2368f0ca706da86a701598169c534a55de0944 Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 22 Aug 2023 14:37:00 +0200 Subject: [PATCH 17/21] fix bitcoin gas price --- .../localnet/orchestrator/smoketest/utils.go | 4 ++-- x/crosschain/keeper/evm_hooks.go | 19 ++++++++++++++----- x/crosschain/keeper/keeper_utils.go | 2 +- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/utils.go b/contrib/localnet/orchestrator/smoketest/utils.go index 3db87d36f9..59ac53b015 100644 --- a/contrib/localnet/orchestrator/smoketest/utils.go +++ b/contrib/localnet/orchestrator/smoketest/utils.go @@ -54,8 +54,8 @@ func WaitCctxMinedByInTxHash(inTxHash string, cctxClient types.QueryClient) *typ } else if err != nil { fmt.Println("Error getting cctx by index: ", err.Error()) } else { - fmt.Printf("Waiting for cctx to be processed (current status: %s)\n", - res.CrossChainTx.CctxStatus.Status.String()) + //fmt.Printf("Waiting for cctx to be processed (current status: %s)\n", + // res.CrossChainTx.CctxStatus.Status.String()) } } }() diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index e2a3dc1eee..4c0945a948 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -90,9 +90,9 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W return fmt.Errorf("cannot find foreign coin with emittingContract address %s", event.Raw.Address.Hex()) } - recvChain := k.zetaObserverKeeper.GetParams(ctx).GetChainFromChainID(foreignCoin.ForeignChainId) + receiverChain := k.zetaObserverKeeper.GetParams(ctx).GetChainFromChainID(foreignCoin.ForeignChainId) senderChain := common.ZetaChain() - toAddr, err := recvChain.EncodeAddress(event.To) + toAddr, err := receiverChain.EncodeAddress(event.To) if err != nil { return fmt.Errorf("cannot encode address %s: %s", event.To, err.Error()) } @@ -114,10 +114,20 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W ) sendHash := msg.Digest() - cctx := k.CreateNewCCTX(ctx, msg, sendHash, types.CctxStatus_PendingOutbound, &senderChain, recvChain) + cctx := k.CreateNewCCTX(ctx, msg, sendHash, types.CctxStatus_PendingOutbound, &senderChain, receiverChain) + + // Get gas price and amount + cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount + gasprice, found := k.GetGasPrice(ctx, receiverChain.ChainId) + if !found { + fmt.Printf("gasprice not found for %s\n", receiverChain) + return fmt.Errorf("gasprice not found for %s", receiverChain) + } + cctx.GetCurrentOutTxParam().OutboundTxGasPrice = fmt.Sprintf("%d", gasprice.Prices[gasprice.MedianIndex]) cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount + EmitZRCWithdrawCreated(ctx, cctx) - return k.ProcessCCTX(ctx, cctx, recvChain) + return k.ProcessCCTX(ctx, cctx, receiverChain) } func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaConnectorZEVMZetaSent, emittingContract ethcommon.Address, txOrigin string) error { @@ -180,7 +190,6 @@ func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaC } EmitZetaWithdrawCreated(ctx, cctx) - return k.ProcessCCTX(ctx, cctx, receiverChain) } diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 7199165b07..c0207d9d04 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -71,7 +71,7 @@ func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx * ) } - ctx.Logger().Info("Substracting amount from inbound tx", "amount", cctx.InboundTxParams.Amount.String(), "feeInZeta", + ctx.Logger().Info("Subtracting amount from inbound tx", "amount", cctx.InboundTxParams.Amount.String(), "feeInZeta", cctx.ZetaFees.String()) cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount.Sub(cctx.ZetaFees) From e8eaa26b9786999a4116fbc93b8d35c2788a96b8 Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 22 Aug 2023 16:39:46 +0200 Subject: [PATCH 18/21] add more logs --- contrib/localnet/orchestrator/smoketest/utils.go | 3 --- x/crosschain/keeper/evm_hooks.go | 1 - .../keeper/keeper_cross_chain_tx_vote_outbound_tx.go | 5 +++-- zetaclient/btc_signer.go | 3 ++- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/contrib/localnet/orchestrator/smoketest/utils.go b/contrib/localnet/orchestrator/smoketest/utils.go index 59ac53b015..6ac92e92b0 100644 --- a/contrib/localnet/orchestrator/smoketest/utils.go +++ b/contrib/localnet/orchestrator/smoketest/utils.go @@ -53,9 +53,6 @@ func WaitCctxMinedByInTxHash(inTxHash string, cctxClient types.QueryClient) *typ break } else if err != nil { fmt.Println("Error getting cctx by index: ", err.Error()) - } else { - //fmt.Printf("Waiting for cctx to be processed (current status: %s)\n", - // res.CrossChainTx.CctxStatus.Status.String()) } } }() diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index 4c0945a948..f59c4ed913 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -117,7 +117,6 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W cctx := k.CreateNewCCTX(ctx, msg, sendHash, types.CctxStatus_PendingOutbound, &senderChain, receiverChain) // Get gas price and amount - cctx.GetCurrentOutTxParam().Amount = cctx.InboundTxParams.Amount gasprice, found := k.GetGasPrice(ctx, receiverChain.ChainId) if !found { fmt.Printf("gasprice not found for %s\n", receiverChain) diff --git a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go index d1f1abf7bb..0d55689f98 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go @@ -107,8 +107,9 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms } if ballot.BallotStatus != observerTypes.BallotStatus_BallotFinalized_FailureObservation { if !msg.ZetaMinted.Equal(cctx.GetCurrentOutTxParam().Amount) { - log.Error().Msgf("ReceiveConfirmation: Mint mismatch: %s zeta minted vs %s cctx amount", msg.ZetaMinted, - cctx.GetCurrentOutTxParam().Amount) + log.Error().Msgf("ReceiveConfirmation: Mint mismatch: %s zeta minted vs %s cctx amount, cctx: %s", + msg.ZetaMinted, + cctx.GetCurrentOutTxParam().Amount, cctx.String()) return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("ZetaMinted %s does not match send ZetaMint %s", msg.ZetaMinted, cctx.GetCurrentOutTxParam().Amount)) } } diff --git a/zetaclient/btc_signer.go b/zetaclient/btc_signer.go index 3bd01075dc..34e16bec04 100644 --- a/zetaclient/btc_signer.go +++ b/zetaclient/btc_signer.go @@ -239,7 +239,8 @@ func (signer *BTCSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out logger.Info().Msgf("SignWithdrawTx: to %s, value %d sats", addr.EncodeAddress(), params.Amount.Uint64()) logger.Info().Msgf("using utxos: %v", btcClient.utxos) - tx, err := signer.SignWithdrawTx(to, float64(params.Amount.Uint64())/1e8, gasprice, btcClient, height, outboundTxTssNonce, &btcClient.chain) + tx, err := signer.SignWithdrawTx(to, float64(params.Amount.Uint64())/1e8, gasprice, btcClient, height, + outboundTxTssNonce, &btcClient.chain) if err != nil { logger.Warn().Err(err).Msgf("SignOutboundTx error: nonce %d chain %d", outboundTxTssNonce, params.ReceiverChainId) return From 52ab64119d7635c34057ab486455b56ac6105c1c Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 22 Aug 2023 17:51:35 +0200 Subject: [PATCH 19/21] remove zeta check --- .../keeper/keeper_cross_chain_tx_vote_outbound_tx.go | 4 ++-- x/crosschain/keeper/keeper_utils.go | 8 +++----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go index 0d55689f98..175de65d8c 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go @@ -107,9 +107,9 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms } if ballot.BallotStatus != observerTypes.BallotStatus_BallotFinalized_FailureObservation { if !msg.ZetaMinted.Equal(cctx.GetCurrentOutTxParam().Amount) { - log.Error().Msgf("ReceiveConfirmation: Mint mismatch: %s zeta minted vs %s cctx amount, cctx: %s", + log.Error().Msgf("ReceiveConfirmation: Mint mismatch: %s zeta minted vs %s cctx amount", msg.ZetaMinted, - cctx.GetCurrentOutTxParam().Amount, cctx.String()) + cctx.GetCurrentOutTxParam().Amount) return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("ZetaMinted %s does not match send ZetaMint %s", msg.ZetaMinted, cctx.GetCurrentOutTxParam().Amount)) } } diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index c0207d9d04..94e16c85cd 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -4,8 +4,6 @@ import ( "fmt" "math/big" - "github.com/zeta-chain/zetacore/common" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" "cosmossdk.io/math" @@ -29,9 +27,9 @@ func (k Keeper) IsAuthorizedNodeAccount(ctx sdk.Context, address string) bool { // The gas ZRC20 balance is subsequently burned to account for the expense of TSS address gas fee payment in the outbound tx. // **Caller should feed temporary ctx into this function** func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx *types.CrossChainTx, noEthereumTxEvent bool) error { - if cctx.InboundTxParams.CoinType != common.CoinType_Zeta { - return sdkerrors.Wrapf(zetaObserverTypes.ErrInvalidCoinType, "can't pay gas in zeta with %s", cctx.InboundTxParams.CoinType.String()) - } + //if cctx.InboundTxParams.CoinType != common.CoinType_Zeta { + // return sdkerrors.Wrapf(zetaObserverTypes.ErrInvalidCoinType, "can't pay gas in zeta with %s", cctx.InboundTxParams.CoinType.String()) + //} chain := k.zetaObserverKeeper.GetParams(ctx).GetChainFromChainID(chainID) if chain == nil { From 8caff6a861bace7322d3dcf6a4b67a25ad95f560 Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 22 Aug 2023 18:05:47 +0200 Subject: [PATCH 20/21] add TODO comment --- x/crosschain/keeper/keeper_utils.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/x/crosschain/keeper/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 94e16c85cd..1351dc1032 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -27,6 +27,8 @@ func (k Keeper) IsAuthorizedNodeAccount(ctx sdk.Context, address string) bool { // The gas ZRC20 balance is subsequently burned to account for the expense of TSS address gas fee payment in the outbound tx. // **Caller should feed temporary ctx into this function** func (k Keeper) PayGasInZetaAndUpdateCctx(ctx sdk.Context, chainID int64, cctx *types.CrossChainTx, noEthereumTxEvent bool) error { + // TODO: this check currently break the integration tests, enable it when integration tests are fixed + // https://github.com/zeta-chain/node/issues/1022 //if cctx.InboundTxParams.CoinType != common.CoinType_Zeta { // return sdkerrors.Wrapf(zetaObserverTypes.ErrInvalidCoinType, "can't pay gas in zeta with %s", cctx.InboundTxParams.CoinType.String()) //} From e1d8933a84542a13daadb3ea727409e62fbd7394 Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 29 Aug 2023 14:30:31 +0200 Subject: [PATCH 21/21] fix merge error --- x/crosschain/keeper/evm_hooks.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index f158218be2..d39ceada2b 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -79,7 +79,7 @@ func (k Keeper) PostTxProcessing( // transaction. func (k Keeper) ProcessLogs(ctx sdk.Context, logs []*ethtypes.Log, emittingContract ethcommon.Address, txOrigin string) error { if !k.zetaObserverKeeper.IsInboundEnabled(ctx) { - return zetacoretypes.ErrNotEnoughPermissions + return types.ErrNotEnoughPermissions } system, found := k.fungibleKeeper.GetSystemContract(ctx) if !found {