diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 3c451f402..a63dc9014 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -1,19 +1,26 @@ name: goreleaser permissions: - # github releases contents: write on: push: tags: - "v*.*.*" + # Validate on develop, main, and master branches that the releaser + # is working as expected. + pull_request: + branches: + - develop + - main + - master + jobs: goreleaser: runs-on: ubuntu-latest - environment: release steps: - - uses: actions/checkout@v4 + - name: Checkout code + uses: actions/checkout@v4 with: submodules: true - name: Set up Go @@ -21,12 +28,11 @@ jobs: with: go-version: '1.21.11' check-latest: true - - name: release dry run + - name: Release dry run run: make release-dry-run - - name: setup release environment + - name: Release publish + # Do not publish the release for pull requests. + if: github.event_name != 'pull_request' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: |- - echo 'GITHUB_TOKEN=${{secrets.GITHUB_TOKEN}}' > .release-env - - name: release publish run: make release diff --git a/.goreleaser.yml b/.goreleaser.yml index 3d97ef717..bddc88dfe 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -1,3 +1,5 @@ +version: 2 + before: hooks: - go mod download diff --git a/Makefile b/Makefile index 943e9a275..145e30bd7 100644 --- a/Makefile +++ b/Makefile @@ -525,7 +525,9 @@ localnet-show-logstream: ############################################################################### PACKAGE_NAME:=github.com/ExocoreNetwork/exocore -GOLANG_CROSS_VERSION = v1.21.11 +# There is no `goreleaser-cross` package for 1.21.11, so we use the next +# available version of v1.22 with goreleaser version 2.0.0 +GOLANG_CROSS_VERSION = v1.22-v2.0.0 GOPATH ?= '$(HOME)/go' release-dry-run: docker run \ @@ -537,7 +539,7 @@ release-dry-run: -v ${GOPATH}/pkg:/go/pkg \ -w /go/src/$(PACKAGE_NAME) \ ghcr.io/goreleaser/goreleaser-cross:${GOLANG_CROSS_VERSION} \ - --clean --skip-validate --skip-publish --snapshot + --clean --skip validate,publish --snapshot release: @if [ ! -f ".release-env" ]; then \ diff --git a/app/ante/cosmos/fees.go b/app/ante/cosmos/fees.go index 90ef5d691..c53d9dcb8 100644 --- a/app/ante/cosmos/fees.go +++ b/app/ante/cosmos/fees.go @@ -6,6 +6,7 @@ import ( errorsmod "cosmossdk.io/errors" anteutils "github.com/ExocoreNetwork/exocore/app/ante/utils" + oracletypes "github.com/ExocoreNetwork/exocore/x/oracle/types" sdk "github.com/cosmos/cosmos-sdk/types" errortypes "github.com/cosmos/cosmos-sdk/types/errors" authante "github.com/cosmos/cosmos-sdk/x/auth/ante" @@ -68,6 +69,19 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bo err error ) + msgs := tx.GetMsgs() + allOracleMsgs := true + for _, msg := range msgs { + if _, ok := msg.(*oracletypes.MsgCreatePrice); !ok { + allOracleMsgs = false + break + } + } + // skip deductgas if this is a oracle price message + if allOracleMsgs { + return next(ctx, tx, simulate) + } + fee := feeTx.GetFee() if !simulate { fee, priority, err = dfd.txFeeChecker(ctx, feeTx) diff --git a/app/ante/cosmos/sigverify.go b/app/ante/cosmos/sigverify.go new file mode 100644 index 000000000..92338c9ff --- /dev/null +++ b/app/ante/cosmos/sigverify.go @@ -0,0 +1,584 @@ +package cosmos + +import ( + "bytes" + "encoding/base64" + "encoding/hex" + "fmt" + + oracletypes "github.com/ExocoreNetwork/exocore/x/oracle/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256r1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/crypto/types/multisig" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authante "github.com/cosmos/cosmos-sdk/x/auth/ante" + "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" + authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var ( + // simulation signature values used to estimate gas consumption + key = make([]byte, secp256k1.PubKeySize) + simSecp256k1Pubkey = &secp256k1.PubKey{Key: key} + _ authsigning.SigVerifiableTx = (*legacytx.StdTx)(nil) // assert StdTx implements SigVerifiableTx +) + +func init() { + // This decodes a valid hex string into a sepc256k1Pubkey for use in transaction simulation + bz, _ := hex.DecodeString("035AD6810A47F073553FF30D2FCC7E0D3B1C0B74B61A1AAA2582344037151E143A") + copy(key, bz) + simSecp256k1Pubkey.Key = key +} + +// SignatureVerificationGasConsumer is the type of function that is used to both +// consume gas when verifying signatures and also to accept or reject different types of pubkeys +// This is where apps can define their own PubKey +type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig signing.SignatureV2, params types.Params) error + +// SetPubKeyDecorator sets PubKeys in context for any signer which does not already have pubkey set +// PubKeys must be set in context for all signers before any other sigverify decorators run +// CONTRACT: Tx must implement SigVerifiableTx interface +type SetPubKeyDecorator struct { + ak authante.AccountKeeper +} + +func NewSetPubKeyDecorator(ak authante.AccountKeeper) SetPubKeyDecorator { + return SetPubKeyDecorator{ + ak: ak, + } +} + +func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { + // skip publickkey set for oracle create-price message + if isOracleCreatePriceTx(tx) { + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("invalid transaction type, expected SigVerifiableTx") + } + signers := sigTx.GetSigners() + pubKeys, err := sigTx.GetPubKeys() + if err != nil { + return ctx, err + } + for i, pk := range pubKeys { + // addrFromPubk, err := sdk.AccAddressFromBech32(sdk.AccAddress(pk).String()) + if !bytes.Equal(signers[i], pk.Address()) { + return ctx, sdkerrors.ErrInvalidPubKey.Wrapf("pubKey does not match signer address %s with signer index: %d", signers[i], i) + } + } + return next(ctx, tx, simulate) + } + + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("invalid transaction type, expected SigVerifiableTx") + } + + pubkeys, err := sigTx.GetPubKeys() + if err != nil { + return ctx, err + } + signers := sigTx.GetSigners() + + for i, pk := range pubkeys { + // PublicKey was omitted from slice since it has already been set in context + if pk == nil { + if !simulate { + continue + } + pk = simSecp256k1Pubkey + } + // Only make check if simulate=false + if !simulate && !bytes.Equal(pk.Address(), signers[i]) { + return ctx, sdkerrors.ErrInvalidPubKey.Wrapf("pubKey does not match signer address %s with signer index: %d", signers[i], i) + } + + acc, err := GetSignerAcc(ctx, spkd.ak, signers[i]) + if err != nil { + return ctx, err + } + // account already has pubkey set,no need to reset + if acc.GetPubKey() != nil { + continue + } + err = acc.SetPubKey(pk) + if err != nil { + return ctx, sdkerrors.ErrInvalidPubKey.Wrap(err.Error()) + } + spkd.ak.SetAccount(ctx, acc) + } + + // Also emit the following events, so that txs can be indexed by these + // indices: + // - signature (via `tx.signature=''`), + // - concat(address,"/",sequence) (via `tx.acc_seq='cosmos1abc...def/42'`). + sigs, err := sigTx.GetSignaturesV2() + if err != nil { + return ctx, err + } + + var events sdk.Events + for i, sig := range sigs { + events = append(events, sdk.NewEvent(sdk.EventTypeTx, + sdk.NewAttribute(sdk.AttributeKeyAccountSequence, fmt.Sprintf("%s/%d", signers[i], sig.Sequence)), + )) + + sigBzs, err := signatureDataToBz(sig.Data) + if err != nil { + return ctx, err + } + for _, sigBz := range sigBzs { + events = append(events, sdk.NewEvent(sdk.EventTypeTx, + sdk.NewAttribute(sdk.AttributeKeySignature, base64.StdEncoding.EncodeToString(sigBz)), + )) + } + } + + ctx.EventManager().EmitEvents(events) + + return next(ctx, tx, simulate) +} + +// Consume parameter-defined amount of gas for each signature according to the passed-in SignatureVerificationGasConsumer function +// before calling the next AnteHandler +// CONTRACT: Pubkeys are set in context for all signers before this decorator runs +// CONTRACT: Tx must implement SigVerifiableTx interface +type SigGasConsumeDecorator struct { + ak authante.AccountKeeper + sigGasConsumer SignatureVerificationGasConsumer +} + +func NewSigGasConsumeDecorator(ak authante.AccountKeeper, sigGasConsumer SignatureVerificationGasConsumer) SigGasConsumeDecorator { + if sigGasConsumer == nil { + sigGasConsumer = DefaultSigVerificationGasConsumer + } + + return SigGasConsumeDecorator{ + ak: ak, + sigGasConsumer: sigGasConsumer, + } +} + +func (sgcd SigGasConsumeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + if isOracleCreatePriceTx(tx) { + // TODO: update gasConsume for create-price message,(actually not necessaray since this message dont actually consume no gas, to be confirmed) + return next(ctx, tx, simulate) + } + + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("invalid transaction type, expected SigVerifiableTx") + } + + params := sgcd.ak.GetParams(ctx) + sigs, err := sigTx.GetSignaturesV2() + if err != nil { + return ctx, err + } + + // stdSigs contains the sequence number, account number, and signatures. + // When simulating, this would just be a 0-length slice. + signerAddrs := sigTx.GetSigners() + + for i, sig := range sigs { + signerAcc, err := GetSignerAcc(ctx, sgcd.ak, signerAddrs[i]) + if err != nil { + return ctx, err + } + + pubKey := signerAcc.GetPubKey() + + // In simulate mode the transaction comes with no signatures, thus if the + // account's pubkey is nil, both signature verification and gasKVStore.Set() + // shall consume the largest amount, i.e. it takes more gas to verify + // secp256k1 keys than ed25519 ones. + if simulate && pubKey == nil { + pubKey = simSecp256k1Pubkey // gitleaks:allow + } + + // make a SignatureV2 with PubKey filled in from above + sig = signing.SignatureV2{ + PubKey: pubKey, + Data: sig.Data, + Sequence: sig.Sequence, + } + + err = sgcd.sigGasConsumer(ctx.GasMeter(), sig, params) + if err != nil { + return ctx, err + } + } + + return next(ctx, tx, simulate) +} + +// Verify all signatures for a tx and return an error if any are invalid. Note, +// the SigVerificationDecorator will not check signatures on ReCheck. +// +// CONTRACT: Pubkeys are set in context for all signers before this decorator runs +// CONTRACT: Tx must implement SigVerifiableTx interface +type SigVerificationDecorator struct { + ak authante.AccountKeeper + signModeHandler authsigning.SignModeHandler +} + +func NewSigVerificationDecorator(ak authante.AccountKeeper, signModeHandler authsigning.SignModeHandler) SigVerificationDecorator { + return SigVerificationDecorator{ + ak: ak, + signModeHandler: signModeHandler, + } +} + +// OnlyLegacyAminoSigners checks SignatureData to see if all +// signers are using SIGN_MODE_LEGACY_AMINO_JSON. If this is the case +// then the corresponding SignatureV2 struct will not have account sequence +// explicitly set, and we should skip the explicit verification of sig.Sequence +// in the SigVerificationDecorator's AnteHandler function. +func OnlyLegacyAminoSigners(sigData signing.SignatureData) bool { + switch v := sigData.(type) { + case *signing.SingleSignatureData: + return v.SignMode == signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON + case *signing.MultiSignatureData: + for _, s := range v.Signatures { + if !OnlyLegacyAminoSigners(s) { + return false + } + } + return true + default: + return false + } +} + +func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + if isOracleCreatePriceTx(tx) { + // TODO: verify ed25519 signature for create-price message which is signed by consensusKey + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("invalid transaction type, expected SigVerifiableTx") + } + + // stdSigs contains the sequence number, account number, and signatures. + // When simulating, this would just be a 0-length slice. + sigs, err := sigTx.GetSignaturesV2() + if err != nil { + return ctx, err + } + pubKeys, err := sigTx.GetPubKeys() + if err != nil { + return ctx, err + } + for i, sig := range sigs { + pubKey := pubKeys[i] + // TODO: is it necessary to support multi-sign ? + data, ok := sig.Data.(*signing.SingleSignatureData) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("invalid signature type, expected SignleSignatureData") + } + bytesToSign, err := svd.signModeHandler.GetSignBytes(data.SignMode, authsigning.SignerData{ChainID: ctx.ChainID()}, tx) + if err != nil { + return ctx, err + } + pubKey.VerifySignature(bytesToSign, data.Signature) + } + + return next(ctx, tx, simulate) + } + + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("invalid transaction type, expected SigVerifiableTx") + } + + // stdSigs contains the sequence number, account number, and signatures. + // When simulating, this would just be a 0-length slice. + sigs, err := sigTx.GetSignaturesV2() + if err != nil { + return ctx, err + } + + signerAddrs := sigTx.GetSigners() + + // check that signer length and signature length are the same + if len(sigs) != len(signerAddrs) { + return ctx, sdkerrors.ErrUnauthorized.Wrapf("invalid number of signer; expected: %d, got %d", len(signerAddrs), len(sigs)) + } + + for i, sig := range sigs { + acc, err := GetSignerAcc(ctx, svd.ak, signerAddrs[i]) + if err != nil { + return ctx, err + } + + // retrieve pubkey + pubKey := acc.GetPubKey() + if !simulate && pubKey == nil { + return ctx, sdkerrors.ErrInvalidPubKey.Wrap("pubkey on account is not set") + } + + // Check account sequence number. + if sig.Sequence != acc.GetSequence() { + return ctx, sdkerrors.ErrWrongSequence.Wrapf("account sequence mismatch, expected %d, got %d", acc.GetSequence(), sig.Sequence) + } + + // TODO: skip all these values assignments if simulate or recheck + // retrieve signer data + genesis := ctx.BlockHeight() == 0 + chainID := ctx.ChainID() + var accNum uint64 + if !genesis { + accNum = acc.GetAccountNumber() + } + signerData := authsigning.SignerData{ + Address: acc.GetAddress().String(), + ChainID: chainID, + AccountNumber: accNum, + Sequence: acc.GetSequence(), + PubKey: pubKey, + } + + // no need to verify signatures on recheck tx + if !simulate && !ctx.IsReCheckTx() { + err := authsigning.VerifySignature(pubKey, signerData, sig.Data, svd.signModeHandler, tx) + if err != nil { + var errMsg string + if OnlyLegacyAminoSigners(sig.Data) { + // If all signers are using SIGN_MODE_LEGACY_AMINO, we rely on VerifySignature to check account sequence number, + // and therefore communicate sequence number as a potential cause of error. + errMsg = fmt.Sprintf("signature verification failed; please verify account number (%d), sequence (%d) and chain-id (%s)", accNum, acc.GetSequence(), chainID) + } else { + errMsg = fmt.Sprintf("signature verification failed; please verify account number (%d) and chain-id (%s)", accNum, chainID) + } + return ctx, sdkerrors.ErrUnauthorized.Wrap(errMsg) + } + } + } + + return next(ctx, tx, simulate) +} + +// IncrementSequenceDecorator handles incrementing sequences of all signers. +// Use the IncrementSequenceDecorator decorator to prevent replay attacks. Note, +// there is need to execute IncrementSequenceDecorator on RecheckTx since +// BaseApp.Commit() will set the check state based on the latest header. +// +// NOTE: Since CheckTx and DeliverTx state are managed separately, subsequent and +// sequential txs orginating from the same account cannot be handled correctly in +// a reliable way unless sequence numbers are managed and tracked manually by a +// client. It is recommended to instead use multiple messages in a tx. +type IncrementSequenceDecorator struct { + ak authante.AccountKeeper +} + +func NewIncrementSequenceDecorator(ak authante.AccountKeeper) IncrementSequenceDecorator { + return IncrementSequenceDecorator{ + ak: ak, + } +} + +func (isd IncrementSequenceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { + // oracle create-price message don't need to update sequence + if isOracleCreatePriceTx(tx) { + return next(ctx, tx, simulate) + } + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("invalid transaction type, expected SigVerifiableTx") + } + + // increment sequence of all signers + for _, addr := range sigTx.GetSigners() { + acc := isd.ak.GetAccount(ctx, addr) + if err := acc.SetSequence(acc.GetSequence() + 1); err != nil { + panic(err) + } + + isd.ak.SetAccount(ctx, acc) + } + + return next(ctx, tx, simulate) +} + +// ValidateSigCountDecorator takes in Params and returns errors if there are too many signatures in the tx for the given params +// otherwise it calls next AnteHandler +// Use this decorator to set parameterized limit on number of signatures in tx +// CONTRACT: Tx must implement SigVerifiableTx interface +type ValidateSigCountDecorator struct { + ak authante.AccountKeeper +} + +func NewValidateSigCountDecorator(ak authante.AccountKeeper) ValidateSigCountDecorator { + return ValidateSigCountDecorator{ + ak: ak, + } +} + +func (vscd ValidateSigCountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.ErrTxDecode.Wrap("Tx must be a sigTx") + } + + params := vscd.ak.GetParams(ctx) + pubKeys, err := sigTx.GetPubKeys() + if err != nil { + return ctx, err + } + + sigCount := 0 + for _, pk := range pubKeys { + sigCount += CountSubKeys(pk) + if uint64(sigCount) > params.TxSigLimit { + return ctx, sdkerrors.ErrTooManySignatures.Wrapf("signatures: %d, limit: %d", sigCount, params.TxSigLimit) + } + } + + return next(ctx, tx, simulate) +} + +// DefaultSigVerificationGasConsumer is the default implementation of SignatureVerificationGasConsumer. It consumes gas +// for signature verification based upon the public key type. The cost is fetched from the given params and is matched +// by the concrete type. +func DefaultSigVerificationGasConsumer( + meter sdk.GasMeter, sig signing.SignatureV2, params types.Params, +) error { + pubkey := sig.PubKey + switch pubkey := pubkey.(type) { + case *ed25519.PubKey: + meter.ConsumeGas(params.SigVerifyCostED25519, "ante verify: ed25519") + return sdkerrors.ErrInvalidPubKey.Wrap("ED25519 public keys are unsupported") + + case *secp256k1.PubKey: + meter.ConsumeGas(params.SigVerifyCostSecp256k1, "ante verify: secp256k1") + return nil + + case *secp256r1.PubKey: + meter.ConsumeGas(params.SigVerifyCostSecp256r1(), "ante verify: secp256r1") + return nil + + case multisig.PubKey: + multisignature, ok := sig.Data.(*signing.MultiSignatureData) + if !ok { + return fmt.Errorf("expected %T, got, %T", &signing.MultiSignatureData{}, sig.Data) + } + err := ConsumeMultisignatureVerificationGas(meter, multisignature, pubkey, params, sig.Sequence) + if err != nil { + return err + } + return nil + + default: + return sdkerrors.ErrInvalidPubKey.Wrapf("unrecognized public key type: %T", pubkey) + } +} + +// ConsumeMultisignatureVerificationGas consumes gas from a GasMeter for verifying a multisig pubkey signature +func ConsumeMultisignatureVerificationGas( + meter sdk.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, + params types.Params, accSeq uint64, +) error { + size := sig.BitArray.Count() + sigIndex := 0 + + for i := 0; i < size; i++ { + if !sig.BitArray.GetIndex(i) { + continue + } + sigV2 := signing.SignatureV2{ + PubKey: pubkey.GetPubKeys()[i], + Data: sig.Signatures[sigIndex], + Sequence: accSeq, + } + err := DefaultSigVerificationGasConsumer(meter, sigV2, params) + if err != nil { + return err + } + sigIndex++ + } + + return nil +} + +// GetSignerAcc returns an account for a given address that is expected to sign +// a transaction. +func GetSignerAcc(ctx sdk.Context, ak authante.AccountKeeper, addr sdk.AccAddress) (types.AccountI, error) { + if acc := ak.GetAccount(ctx, addr); acc != nil { + return acc, nil + } + + return nil, sdkerrors.ErrUnknownAddress.Wrapf("account %s does not exist", addr) +} + +// CountSubKeys counts the total number of keys for a multi-sig public key. +func CountSubKeys(pub cryptotypes.PubKey) int { + v, ok := pub.(*kmultisig.LegacyAminoPubKey) + if !ok { + return 1 + } + + numKeys := 0 + for _, subkey := range v.GetPubKeys() { + numKeys += CountSubKeys(subkey) + } + + return numKeys +} + +// signatureDataToBz converts a SignatureData into raw bytes signature. +// For SingleSignatureData, it returns the signature raw bytes. +// For MultiSignatureData, it returns an array of all individual signatures, +// as well as the aggregated signature. +func signatureDataToBz(data signing.SignatureData) ([][]byte, error) { + if data == nil { + return nil, fmt.Errorf("got empty SignatureData") + } + + switch data := data.(type) { + case *signing.SingleSignatureData: + return [][]byte{data.Signature}, nil + case *signing.MultiSignatureData: + sigs := [][]byte{} + var err error + + for _, d := range data.Signatures { + nestedSigs, err := signatureDataToBz(d) + if err != nil { + return nil, err + } + sigs = append(sigs, nestedSigs...) + } + + multisig := cryptotypes.MultiSignature{ + Signatures: sigs, + } + aggregatedSig, err := multisig.Marshal() + if err != nil { + return nil, err + } + sigs = append(sigs, aggregatedSig) + + return sigs, nil + default: + return nil, sdkerrors.ErrInvalidType.Wrapf("unexpected signature data type %T", data) + } +} + +func isOracleCreatePriceTx(tx sdk.Tx) bool { + msgs := tx.GetMsgs() + if len(msgs) == 0 { + return false + } + for _, msg := range msgs { + if _, ok := msg.(*oracletypes.MsgCreatePrice); ok { + continue + } + return false + } + return true +} diff --git a/app/ante/handler_options.go b/app/ante/handler_options.go index 3b42c6240..84876332d 100644 --- a/app/ante/handler_options.go +++ b/app/ante/handler_options.go @@ -112,11 +112,11 @@ func newCosmosAnteHandler(options HandlerOptions) sdk.AnteHandler { ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), cosmosante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.DistributionKeeper, options.FeegrantKeeper, options.StakingKeeper, options.TxFeeChecker), // SetPubKeyDecorator must be called before all signature verification decorators - ante.NewSetPubKeyDecorator(options.AccountKeeper), + cosmosante.NewSetPubKeyDecorator(options.AccountKeeper), ante.NewValidateSigCountDecorator(options.AccountKeeper), - ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer), - ante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler), - ante.NewIncrementSequenceDecorator(options.AccountKeeper), + cosmosante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer), + cosmosante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler), + cosmosante.NewIncrementSequenceDecorator(options.AccountKeeper), ibcante.NewRedundantRelayDecorator(options.IBCKeeper), evmante.NewGasWantedDecorator(options.EvmKeeper, options.FeeMarketKeeper), ) diff --git a/app/app.go b/app/app.go index f6ea8f8fb..a8b8cd6c1 100644 --- a/app/app.go +++ b/app/app.go @@ -47,20 +47,12 @@ import ( delegationKeeper "github.com/ExocoreNetwork/exocore/x/delegation/keeper" delegationTypes "github.com/ExocoreNetwork/exocore/x/delegation/types" - "github.com/ExocoreNetwork/exocore/x/deposit" - depositKeeper "github.com/ExocoreNetwork/exocore/x/deposit/keeper" - depositTypes "github.com/ExocoreNetwork/exocore/x/deposit/types" - operatorTypes "github.com/ExocoreNetwork/exocore/x/operator/types" "github.com/ExocoreNetwork/exocore/x/reward" rewardKeeper "github.com/ExocoreNetwork/exocore/x/reward/keeper" rewardTypes "github.com/ExocoreNetwork/exocore/x/reward/types" - "github.com/ExocoreNetwork/exocore/x/withdraw" - withdrawKeeper "github.com/ExocoreNetwork/exocore/x/withdraw/keeper" - withdrawTypes "github.com/ExocoreNetwork/exocore/x/withdraw/types" - // increases or decreases block gas limit based on usage "github.com/evmos/evmos/v14/x/feemarket" feemarketkeeper "github.com/evmos/evmos/v14/x/feemarket/keeper" @@ -275,10 +267,8 @@ var ( consensus.AppModuleBasic{}, // Exocore modules assets.AppModuleBasic{}, - deposit.AppModuleBasic{}, operator.AppModuleBasic{}, delegation.AppModuleBasic{}, - withdraw.AppModuleBasic{}, reward.AppModuleBasic{}, exoslash.AppModuleBasic{}, avs.AppModuleBasic{}, @@ -360,9 +350,7 @@ type ExocoreApp struct { // exocore assets module keepers AssetsKeeper assetsKeeper.Keeper - DepositKeeper depositKeeper.Keeper DelegationKeeper delegationKeeper.Keeper - WithdrawKeeper withdrawKeeper.Keeper RewardKeeper rewardKeeper.Keeper OperatorKeeper operatorKeeper.Keeper ExoSlashKeeper slashKeeper.Keeper @@ -447,8 +435,6 @@ func NewExocoreApp( // exoCore module keys assetsTypes.StoreKey, delegationTypes.StoreKey, - depositTypes.StoreKey, - withdrawTypes.StoreKey, rewardTypes.StoreKey, exoslashTypes.StoreKey, operatorTypes.StoreKey, @@ -550,18 +536,6 @@ func NewExocoreApp( // asset and client chain registry. app.AssetsKeeper = assetsKeeper.NewKeeper(keys[assetsTypes.StoreKey], appCodec) - // handles deposits but most of the information is stored in the assets keeper. - app.DepositKeeper = depositKeeper.NewKeeper( - keys[depositTypes.StoreKey], appCodec, app.AssetsKeeper, - ) - - // withdrawals - validates from assets and deposits keepers and executes them. - // could potentially be merged with the assets keeper. - app.WithdrawKeeper = withdrawKeeper.NewKeeper( - appCodec, keys[withdrawTypes.StoreKey], - app.AssetsKeeper, app.DepositKeeper, - ) - // operator registry, which handles vote power (and this requires delegation keeper). app.OperatorKeeper = operatorKeeper.NewKeeper( keys[operatorTypes.StoreKey], appCodec, @@ -575,7 +549,7 @@ func NewExocoreApp( // handles delegations by stakers, and must know if the delegatee operator is registered. app.DelegationKeeper = delegationKeeper.NewKeeper( - keys[depositTypes.StoreKey], appCodec, + keys[delegationTypes.StoreKey], appCodec, app.AssetsKeeper, delegationTypes.VirtualSlashKeeper{}, app.OperatorKeeper, @@ -723,10 +697,8 @@ func NewExocoreApp( app.AuthzKeeper, app.TransferKeeper, app.IBCKeeper.ChannelKeeper, - app.DepositKeeper, app.DelegationKeeper, app.AssetsKeeper, - app.WithdrawKeeper, app.ExoSlashKeeper, app.RewardKeeper, app.AVSManagerKeeper, @@ -895,10 +867,8 @@ func NewExocoreApp( app.GetSubspace(recoverytypes.ModuleName)), // exoCore app modules assets.NewAppModule(appCodec, app.AssetsKeeper), - deposit.NewAppModule(appCodec, app.DepositKeeper), operator.NewAppModule(appCodec, app.OperatorKeeper), delegation.NewAppModule(appCodec, app.DelegationKeeper), - withdraw.NewAppModule(appCodec, app.WithdrawKeeper), reward.NewAppModule(appCodec, app.RewardKeeper), exoslash.NewAppModule(appCodec, app.ExoSlashKeeper), avs.NewAppModule(appCodec, app.AVSManagerKeeper), @@ -934,10 +904,8 @@ func NewExocoreApp( erc20types.ModuleName, recoverytypes.ModuleName, assetsTypes.ModuleName, - depositTypes.ModuleName, operatorTypes.ModuleName, delegationTypes.ModuleName, - withdrawTypes.ModuleName, rewardTypes.ModuleName, exoslashTypes.ModuleName, avsManagerTypes.ModuleName, @@ -972,8 +940,6 @@ func NewExocoreApp( recoverytypes.ModuleName, consensusparamtypes.ModuleName, assetsTypes.ModuleName, - depositTypes.ModuleName, - withdrawTypes.ModuleName, rewardTypes.ModuleName, exoslashTypes.ModuleName, avsManagerTypes.ModuleName, @@ -1015,8 +981,6 @@ func NewExocoreApp( paramstypes.ModuleName, consensusparamtypes.ModuleName, upgradetypes.ModuleName, // no-op since we don't call SetInitVersionMap - depositTypes.ModuleName, // state handled by x/assets - withdrawTypes.ModuleName, // state handled by x/assets rewardTypes.ModuleName, // not fully implemented yet exoslashTypes.ModuleName, // not fully implemented yet avsManagerTypes.ModuleName, diff --git a/local_node.sh b/local_node.sh index a9446c33a..ab3c2105b 100755 --- a/local_node.sh +++ b/local_node.sh @@ -167,6 +167,7 @@ if [[ $overwrite == "y" || $overwrite == "Y" ]]; then sed -i '' 's/prometheus = false/prometheus = true/' "$CONFIG" sed -i '' 's/prometheus-retention-time = 0/prometheus-retention-time = 1000000000000/g' "$APP_TOML" sed -i '' 's/enabled = false/enabled = true/g' "$APP_TOML" + sed -i '' 's/enable = false/enable = true/g' "$APP_TOML" else sed -i 's/prometheus = false/prometheus = true/' "$CONFIG" sed -i 's/prometheus-retention-time = "0"/prometheus-retention-time = "1000000000000"/g' "$APP_TOML" diff --git a/precompiles/assets/IAssets.sol b/precompiles/assets/IAssets.sol new file mode 100644 index 000000000..14da53042 --- /dev/null +++ b/precompiles/assets/IAssets.sol @@ -0,0 +1,49 @@ +pragma solidity >=0.8.17; + +/// @dev The Assets contract's address. +address constant ASSETS_PRECOMPILE_ADDRESS = 0x0000000000000000000000000000000000000804; + +/// @dev The Assets contract's instance. +IAssets constant ASSETS_CONTRACT = IAssets( + ASSETS_PRECOMPILE_ADDRESS +); + +/// @author Exocore Team +/// @title Assets Precompile Contract +/// @dev The interface through which solidity contracts will interact with assets module +/// @custom:address 0x0000000000000000000000000000000000000804 +interface IAssets { +/// TRANSACTIONS +/// @dev deposit the client chain assets for the staker, +/// that will change the state in deposit module +/// Note that this address cannot be a module account. +/// @param clientChainLzID The LzID of client chain +/// @param assetsAddress The client chain asset address +/// @param stakerAddress The staker address +/// @param opAmount The amount to deposit + function depositTo( + uint32 clientChainLzID, + bytes memory assetsAddress, + bytes memory stakerAddress, + uint256 opAmount + ) external returns (bool success, uint256 latestAssetState); + +/// TRANSACTIONS +/// @dev withdraw To the staker, that will change the state in withdraw module +/// Note that this address cannot be a module account. +/// @param clientChainLzID The LzID of client chain +/// @param assetsAddress The client chain asset Address +/// @param withdrawAddress The withdraw address +/// @param opAmount The withdraw amount + function withdrawPrincipal( + uint32 clientChainLzID, + bytes memory assetsAddress, + bytes memory withdrawAddress, + uint256 opAmount + ) external returns (bool success, uint256 latestAssetState); + +/// QUERIES +/// @dev Returns the chain indices of the client chains. + function getClientChains() external view returns (bool, uint32[] memory); +} + diff --git a/precompiles/assets/abi.json b/precompiles/assets/abi.json new file mode 100644 index 000000000..6144bd275 --- /dev/null +++ b/precompiles/assets/abi.json @@ -0,0 +1,98 @@ +[ + { + "type": "function", + "name": "depositTo", + "inputs": [ + { + "name": "clientChainLzID", + "type": "uint32", + "internalType": "uint32" + }, + { + "name": "assetsAddress", + "type": "bytes", + "internalType": "bytes" + }, + { + "name": "stakerAddress", + "type": "bytes", + "internalType": "bytes" + }, + { + "name": "opAmount", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "success", + "type": "bool", + "internalType": "bool" + }, + { + "name": "latestAssetState", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "getClientChains", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bool", + "internalType": "bool" + }, + { + "name": "", + "type": "uint32[]", + "internalType": "uint32[]" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "withdrawPrincipal", + "inputs": [ + { + "name": "clientChainLzID", + "type": "uint32", + "internalType": "uint32" + }, + { + "name": "assetsAddress", + "type": "bytes", + "internalType": "bytes" + }, + { + "name": "withdrawAddress", + "type": "bytes", + "internalType": "bytes" + }, + { + "name": "opAmount", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "success", + "type": "bool", + "internalType": "bool" + }, + { + "name": "latestAssetState", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "nonpayable" + } +] diff --git a/precompiles/deposit/deposit.go b/precompiles/assets/assets.go similarity index 73% rename from precompiles/deposit/deposit.go rename to precompiles/assets/assets.go index b0877130f..3fae7bd6c 100644 --- a/precompiles/deposit/deposit.go +++ b/precompiles/assets/assets.go @@ -1,12 +1,12 @@ -package deposit +package assets import ( "bytes" "embed" "fmt" + "math/big" assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" - depositKeeper "github.com/ExocoreNetwork/exocore/x/deposit/keeper" storetypes "github.com/cosmos/cosmos-sdk/store/types" authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" "github.com/ethereum/go-ethereum/accounts/abi" @@ -26,15 +26,13 @@ var f embed.FS // Precompile defines the precompiled contract for deposit. type Precompile struct { cmn.Precompile - assetsKeeper assetskeeper.Keeper - depositKeeper depositKeeper.Keeper + assetsKeeper assetskeeper.Keeper } // NewPrecompile creates a new deposit Precompile instance as a // PrecompiledContract interface. func NewPrecompile( - stakingStateKeeper assetskeeper.Keeper, - depositKeeper depositKeeper.Keeper, + assetsKeeper assetskeeper.Keeper, authzKeeper authzkeeper.Keeper, ) (*Precompile, error) { abiBz, err := f.ReadFile("abi.json") @@ -55,8 +53,7 @@ func NewPrecompile( TransientKVGasConfig: storetypes.TransientGasConfig(), ApprovalExpiration: cmn.DefaultExpirationDuration, // should be configurable in the future. }, - depositKeeper: depositKeeper, - assetsKeeper: stakingStateKeeper, + assetsKeeper: assetsKeeper, }, nil } @@ -89,12 +86,26 @@ func (p Precompile) Run(evm *vm.EVM, contract *vm.Contract, readOnly bool) (bz [ // It avoids panics and returns the out of gas error so the EVM can continue gracefully. defer cmn.HandleGasError(ctx, contract, initialGas, &err)() - if method.Name == MethodDepositTo { - bz, err = p.DepositTo(ctx, evm.Origin, contract, stateDB, method, args) + switch method.Name { + // transactions + case MethodDepositTo, MethodWithdraw: + bz, err = p.DepositAndWithdraw(ctx, evm.Origin, contract, stateDB, method, args) + if err != nil { + // for failed cases we expect it returns bool value instead of error + // this is a workaround because the error returned by precompile can not be caught in EVM + // see https://github.com/ExocoreNetwork/exocore/issues/70 + // TODO: we should figure out root cause and fix this issue to make precompiles work normally + return method.Outputs.Pack(false, new(big.Int)) + } + // queries + case MethodGetClientChains: + bz, err = p.GetClientChains(ctx, method, args) + default: + return nil, fmt.Errorf(cmn.ErrUnknownMethod, method.Name) } if err != nil { - ctx.Logger().Error("call deposit precompile error", "module", "deposit precompile", "err", err) + ctx.Logger().Error("call assets precompile error", "module", "assets precompile", "method", method.Name, "err", err) return nil, err } @@ -109,11 +120,12 @@ func (p Precompile) Run(evm *vm.EVM, contract *vm.Contract, readOnly bool) (bz [ // IsTransaction checks if the given methodID corresponds to a transaction or query. // -// Available deposit transactions are: -// - DepositTo +// Available assets transactions are: +// - depositTo +// - withdrawPrincipal func (Precompile) IsTransaction(methodID string) bool { switch methodID { - case MethodDepositTo: + case MethodDepositTo, MethodWithdraw: return true default: return false diff --git a/precompiles/deposit/deposit_integrate_test.go b/precompiles/assets/assets_integrate_test.go similarity index 63% rename from precompiles/deposit/deposit_integrate_test.go rename to precompiles/assets/assets_integrate_test.go index 6888442d7..f3b9426a0 100644 --- a/precompiles/deposit/deposit_integrate_test.go +++ b/precompiles/assets/assets_integrate_test.go @@ -1,9 +1,10 @@ -package deposit_test +package assets_test import ( "math/big" - "github.com/ExocoreNetwork/exocore/precompiles/deposit" + "github.com/ExocoreNetwork/exocore/precompiles/assets" + "github.com/ExocoreNetwork/exocore/precompiles/testutil" "github.com/ExocoreNetwork/exocore/precompiles/testutil/contracts" assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" @@ -24,7 +25,7 @@ var ( passCheck testutil.LogCheckArgs ) -func (s *DepositPrecompileSuite) TestCallDepositToFromEOA() { +func (s *AssetsPrecompileSuite) TestCallDepositToFromEOA() { // deposit params for test exocoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" exocoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" @@ -32,11 +33,11 @@ func (s *DepositPrecompileSuite) TestCallDepositToFromEOA() { ExocoreLzAppAddress: exocoreLzAppAddress, ExocoreLzAppEventTopic: exocoreLzAppEventTopic, } - usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), assetstype.GeneralClientChainAddrLength) + assetAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") + paddingAssetAddress := paddingClientChainAddress(assetAddress, assetstype.GeneralClientChainAddrLength) clientChainLzID := 101 stakerAddr := paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength) opAmount := big.NewInt(100) - assetAddr := usdtAddress method := "depositTo" beforeEach := func() { @@ -60,7 +61,7 @@ func (s *DepositPrecompileSuite) TestCallDepositToFromEOA() { defaultDepositArgs := defaultCallArgs.WithMethodName(method) return defaultDepositArgs.WithArgs( uint32(clientChainLzID), - assetAddr, + paddingAssetAddress, stakerAddr, opAmount) } @@ -68,20 +69,26 @@ func (s *DepositPrecompileSuite) TestCallDepositToFromEOA() { // test caller error beforeEach() setDepositToArgs := prepareFunc(&depositParams, method) - _, _, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) - s.Require().ErrorContains(err, assetstype.ErrNotEqualToLzAppAddr.Error()) + _, response, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) + // s.Require().ErrorContains(err, assetstype.ErrNotEqualToLzAppAddr.Error()) + result, err := s.precompile.ABI.Unpack(assets.MethodDepositTo, response.Ret) + s.Require().NoError(err) + s.Require().Equal(len(result), 2) + success, ok := result[0].(bool) + s.Require().True(ok) + s.Require().False(success) // test success beforeEach() depositParams.ExocoreLzAppAddress = s.Address.String() setDepositToArgs = prepareFunc(&depositParams, method) _, ethRes, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) - successRet, err := s.precompile.Methods[deposit.MethodDepositTo].Outputs.Pack(true, opAmount) + successRet, err := s.precompile.Methods[assets.MethodDepositTo].Outputs.Pack(true, opAmount) s.Require().NoError(err) s.Require().Equal(successRet, ethRes.Ret) } -func (s *DepositPrecompileSuite) TestCallDepositToFromContract() { +func (s *AssetsPrecompileSuite) TestCallDepositToFromContract() { // deposit params for test exoCoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" @@ -89,11 +96,12 @@ func (s *DepositPrecompileSuite) TestCallDepositToFromContract() { ExocoreLzAppAddress: exoCoreLzAppAddress, ExocoreLzAppEventTopic: exoCoreLzAppEventTopic, } - usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), assetstype.GeneralClientChainAddrLength) + + assetAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") + paddingAssetAddress := paddingClientChainAddress(assetAddress, assetstype.GeneralClientChainAddrLength) clientChainLzID := 101 stakerAddr := paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength) opAmount := big.NewInt(100) - assetAddr := usdtAddress // contractAddr is the address of the smart contract that will be deployed var contractAddr common.Address @@ -131,7 +139,7 @@ func (s *DepositPrecompileSuite) TestCallDepositToFromContract() { defaultDepositArgs := defaultCallArgs.WithMethodName(method) return defaultDepositArgs.WithArgs( uint32(clientChainLzID), - assetAddr, + paddingAssetAddress, stakerAddr, opAmount) } @@ -170,3 +178,71 @@ func (s *DepositPrecompileSuite) TestCallDepositToFromContract() { s.Require().NoError(err) s.Require().Equal(successRet, ethRes.Ret)*/ } + +func (s *AssetsPrecompileSuite) TestCallWithdrawFromEOA() { + // withdraw params for test + exocoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" + exocoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" + params := assetstype.Params{ + ExocoreLzAppAddress: exocoreLzAppAddress, + ExocoreLzAppEventTopic: exocoreLzAppEventTopic, + } + usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), assetstype.GeneralClientChainAddrLength) + clientChainLzID := 101 + stakerAddr := paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength) + opAmount := big.NewInt(100) + assetAddr := usdtAddress + method := "withdrawPrincipal" + + beforeEach := func() { + s.SetupTest() + // set the default call arguments + defaultCallArgs = contracts.CallArgs{ + ContractAddr: s.precompile.Address(), + ContractABI: s.precompile.ABI, + PrivKey: s.PrivKey, + } + + defaultLogCheck = testutil.LogCheckArgs{ + ABIEvents: s.precompile.ABI.Events, + } + passCheck = defaultLogCheck.WithExpPass(true) + } + + prepareFunc := func(params *assetstype.Params, method string) contracts.CallArgs { + err := s.App.AssetsKeeper.SetParams(s.Ctx, params) + s.Require().NoError(err) + defaultWithdrawArgs := defaultCallArgs.WithMethodName(method) + return defaultWithdrawArgs.WithArgs( + uint32(clientChainLzID), + assetAddr, + stakerAddr, + opAmount) + } + + beforeEach() + setWithdrawArgs := prepareFunc(¶ms, method) + _, response, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setWithdrawArgs, passCheck) + + // for failed cases we expect it returns bool value instead of error + // this is a workaround because the error returned by precompile can not be caught in EVM + // see https://github.com/ExocoreNetwork/exocore/issues/70 + // TODO: we should figure out root cause and fix this issue to make precompiles work normally + s.Require().NoError(err) + + result, err := setWithdrawArgs.ContractABI.Unpack(method, response.Ret) + s.Require().NoError((err)) + + // solidity: function withdraw(...) returns (bool success, uint256 updatedBalance) + s.Require().Equal(len(result), 2) + + // the first element should be bool value that indicates whether the withdrawal is successful + success, ok := result[0].(bool) + s.Require().True(ok) + s.Require().False(success) + + // the second element represents updatedBalance and should be 0 since success is false and withdrawal has failed + updatedBalance, ok := result[1].(*big.Int) + s.Require().True(ok) + s.Require().Zero(updatedBalance.Cmp(new(big.Int))) +} diff --git a/precompiles/assets/assets_test.go b/precompiles/assets/assets_test.go new file mode 100644 index 000000000..8ae156f5f --- /dev/null +++ b/precompiles/assets/assets_test.go @@ -0,0 +1,418 @@ +package assets_test + +import ( + "math/big" + + sdkmath "cosmossdk.io/math" + assetsprecompile "github.com/ExocoreNetwork/exocore/precompiles/assets" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" + "github.com/evmos/evmos/v14/x/evm/statedb" + + "github.com/ExocoreNetwork/exocore/app" + assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/core/vm" + evmtypes "github.com/evmos/evmos/v14/x/evm/types" +) + +func (s *AssetsPrecompileSuite) TestIsTransaction() { + testCases := []struct { + name string + method string + isTx bool + }{ + { + assetsprecompile.MethodDepositTo, + s.precompile.Methods[assetsprecompile.MethodDepositTo].Name, + true, + }, + { + assetsprecompile.MethodWithdraw, + s.precompile.Methods[assetsprecompile.MethodWithdraw].Name, + true, + }, + { + assetsprecompile.MethodGetClientChains, + s.precompile.Methods[assetsprecompile.MethodGetClientChains].Name, + false, + }, + { + "invalid", + "invalid", + false, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + s.Require().Equal(s.precompile.IsTransaction(tc.method), tc.isTx) + }) + } +} + +func paddingClientChainAddress(input []byte, outputLength int) []byte { + if len(input) < outputLength { + padding := make([]byte, outputLength-len(input)) + return append(input, padding...) + } + return input +} + +// TestRunDepositTo tests DepositAndWithdraw method through calling Run function.. +func (s *AssetsPrecompileSuite) TestRunDepositTo() { + // assetsprecompile params for test + exocoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" + exocoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" + usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), assetstype.GeneralClientChainAddrLength) + usdcAddress := paddingClientChainAddress(common.FromHex("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), assetstype.GeneralClientChainAddrLength) + clientChainLzID := 101 + stakerAddr := paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength) + opAmount := big.NewInt(100) + assetAddr := usdtAddress + commonMalleate := func() (common.Address, []byte) { + input, err := s.precompile.Pack( + assetsprecompile.MethodDepositTo, + uint32(clientChainLzID), + assetAddr, + stakerAddr, + opAmount, + ) + s.Require().NoError(err, "failed to pack input") + return s.Address, input + } + successRet, err := s.precompile.Methods[assetsprecompile.MethodDepositTo].Outputs.Pack(true, opAmount) + s.Require().NoError(err) + + testcases := []struct { + name string + malleate func() (common.Address, []byte) + readOnly bool + expPass bool + errContains string + returnBytes []byte + }{ + { + name: "fail - depositTo transaction will fail because the exocoreLzAppAddress is mismatched", + malleate: func() (common.Address, []byte) { + return commonMalleate() + }, + readOnly: false, + expPass: false, + errContains: assetstype.ErrNotEqualToLzAppAddr.Error(), + }, + { + name: "fail - depositTo transaction will fail because the contract caller isn't the exoCoreLzAppAddr", + malleate: func() (common.Address, []byte) { + depositModuleParam := &assetstype.Params{ + ExocoreLzAppAddress: exocoreLzAppAddress, + ExocoreLzAppEventTopic: exocoreLzAppEventTopic, + } + err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) + s.Require().NoError(err) + return commonMalleate() + }, + readOnly: false, + expPass: false, + errContains: assetstype.ErrNotEqualToLzAppAddr.Error(), + }, + { + name: "fail - depositTo transaction will fail because the staked assetsprecompile hasn't been registered", + malleate: func() (common.Address, []byte) { + depositModuleParam := &assetstype.Params{ + ExocoreLzAppAddress: s.Address.String(), + ExocoreLzAppEventTopic: exocoreLzAppEventTopic, + } + err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) + s.Require().NoError(err) + assetAddr = usdcAddress + return commonMalleate() + }, + readOnly: false, + expPass: false, + errContains: assetstype.ErrNoClientChainAssetKey.Error(), + }, + { + name: "pass - depositTo transaction", + malleate: func() (common.Address, []byte) { + depositModuleParam := &assetstype.Params{ + ExocoreLzAppAddress: s.Address.String(), + ExocoreLzAppEventTopic: exocoreLzAppEventTopic, + } + assetAddr = usdtAddress + err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) + s.Require().NoError(err) + return commonMalleate() + }, + returnBytes: successRet, + readOnly: false, + expPass: true, + }, + } + + for _, tc := range testcases { + tc := tc + s.Run(tc.name, func() { + // setup basic test suite + s.SetupTest() + + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) + + // malleate testcase + caller, input := tc.malleate() + + contract := vm.NewPrecompile(vm.AccountRef(caller), s.precompile, big.NewInt(0), uint64(1e6)) + contract.Input = input + + contractAddr := contract.Address() + // Build and sign Ethereum transaction + txArgs := evmtypes.EvmTxArgs{ + ChainID: s.App.EvmKeeper.ChainID(), + Nonce: 0, + To: &contractAddr, + Amount: nil, + GasLimit: 100000, + GasPrice: app.MainnetMinGasPrices.BigInt(), + GasFeeCap: baseFee, + GasTipCap: big.NewInt(1), + Accesses: ðtypes.AccessList{}, + } + msgEthereumTx := evmtypes.NewTx(&txArgs) + + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) + s.Require().NoError(err, "failed to sign Ethereum message") + + // Instantiate config + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) + s.Require().NoError(err, "failed to instantiate EVM config") + + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) + s.Require().NoError(err, "failed to instantiate Ethereum message") + + // Instantiate EVM + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, + ) + + params := s.App.EvmKeeper.GetParams(s.Ctx) + activePrecompiles := params.GetActivePrecompilesAddrs() + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) + err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) + s.Require().NoError(err, "invalid precompiles", activePrecompiles) + evm.WithPrecompiles(precompileMap, activePrecompiles) + + // Run precompiled contract + bz, err := s.precompile.Run(evm, contract, tc.readOnly) + + // Check results + if tc.expPass { + s.Require().NoError(err, "expected no error when running the precompile") + s.Require().Equal(tc.returnBytes, bz, "the return doesn't match the expected result") + } else { + /* s.Require().Error(err, "expected error to be returned when running the precompile") + s.Require().Nil(bz, "expected returned bytes to be nil") + s.Require().ErrorContains(err, tc.errContains)*/ + // for failed cases we expect it returns bool value instead of error + // this is a workaround because the error returned by precompile can not be caught in EVM + // see https://github.com/ExocoreNetwork/exocore/issues/70 + // TODO: we should figure out root cause and fix this issue to make precompiles work normally + result, err := s.precompile.ABI.Unpack(assetsprecompile.MethodDepositTo, bz) + s.Require().NoError(err) + s.Require().Equal(len(result), 2) + success, ok := result[0].(bool) + s.Require().True(ok) + s.Require().False(success) + } + }) + } +} + +// TestRun tests the precompiled Run method withdraw. +func (s *AssetsPrecompileSuite) TestRunWithdrawThroughClientChain() { + // deposit params for test + exocoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" + usdtAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") + clientChainLzID := 101 + withdrawAmount := big.NewInt(10) + depositAmount := big.NewInt(100) + assetAddr := paddingClientChainAddress(usdtAddress, assetstype.GeneralClientChainAddrLength) + depositAsset := func(staker []byte, depositAmount sdkmath.Int) { + // deposit asset for withdraw test + params := &assetskeeper.DepositWithdrawParams{ + ClientChainLzID: 101, + Action: assetstype.Deposit, + StakerAddress: staker, + AssetsAddress: usdtAddress, + OpAmount: depositAmount, + } + err := s.App.AssetsKeeper.PerformDepositOrWithdraw(s.Ctx, params) + s.Require().NoError(err) + } + + commonMalleate := func() (common.Address, []byte) { + // Prepare the call input for withdraw test + input, err := s.precompile.Pack( + assetsprecompile.MethodWithdraw, + uint32(clientChainLzID), + assetAddr, + paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength), + withdrawAmount, + ) + s.Require().NoError(err, "failed to pack input") + return s.Address, input + } + successRet, err := s.precompile.Methods[assetsprecompile.MethodWithdraw].Outputs.Pack(true, new(big.Int).Sub(depositAmount, withdrawAmount)) + s.Require().NoError(err) + testcases := []struct { + name string + malleate func() (common.Address, []byte) + readOnly bool + expPass bool + errContains string + returnBytes []byte + }{ + { + name: "pass - withdraw via pre-compiles", + malleate: func() (common.Address, []byte) { + depositModuleParam := &assetstype.Params{ + ExocoreLzAppAddress: s.Address.String(), + ExocoreLzAppEventTopic: exocoreLzAppEventTopic, + } + err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) + s.Require().NoError(err) + depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) + return commonMalleate() + }, + returnBytes: successRet, + readOnly: false, + expPass: true, + }, + } + for _, tc := range testcases { + tc := tc + s.Run(tc.name, func() { + // setup basic test suite + s.SetupTest() + + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) + + // malleate testcase + caller, input := tc.malleate() + + contract := vm.NewPrecompile(vm.AccountRef(caller), s.precompile, big.NewInt(0), uint64(1e6)) + contract.Input = input + + contractAddr := contract.Address() + // Build and sign Ethereum transaction + txArgs := evmtypes.EvmTxArgs{ + ChainID: s.App.EvmKeeper.ChainID(), + Nonce: 0, + To: &contractAddr, + Amount: nil, + GasLimit: 100000, + GasPrice: app.MainnetMinGasPrices.BigInt(), + GasFeeCap: baseFee, + GasTipCap: big.NewInt(1), + Accesses: ðtypes.AccessList{}, + } + msgEthereumTx := evmtypes.NewTx(&txArgs) + + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) + s.Require().NoError(err, "failed to sign Ethereum message") + + // Instantiate config + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) + s.Require().NoError(err, "failed to instantiate EVM config") + + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) + s.Require().NoError(err, "failed to instantiate Ethereum message") + + // Create StateDB + s.StateDB = statedb.New(s.Ctx, s.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.Ctx.HeaderHash().Bytes()))) + // Instantiate EVM + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, + ) + params := s.App.EvmKeeper.GetParams(s.Ctx) + activePrecompiles := params.GetActivePrecompilesAddrs() + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) + err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) + s.Require().NoError(err, "invalid precompiles", activePrecompiles) + evm.WithPrecompiles(precompileMap, activePrecompiles) + + // Run precompiled contract + bz, err := s.precompile.Run(evm, contract, tc.readOnly) + + // Check results + if tc.expPass { + s.Require().NoError(err, "expected no error when running the precompile") + s.Require().Equal(tc.returnBytes, bz, "the return doesn't match the expected result") + } else { + s.Require().Error(err, "expected error to be returned when running the precompile") + s.Require().Nil(bz, "expected returned bytes to be nil") + s.Require().ErrorContains(err, tc.errContains) + } + }) + } +} + +func (s *AssetsPrecompileSuite) TestGetClientChains() { + input, err := s.precompile.Pack("getClientChains") + s.Require().NoError(err, "failed to pack input") + output, err := s.precompile.Methods["getClientChains"].Outputs.Pack(true, []uint32{101}) + s.Require().NoError(err, "failed to pack output") + s.Run("get client chains", func() { + s.SetupTest() + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) + contract := vm.NewPrecompile( + vm.AccountRef(s.Address), + s.precompile, + big.NewInt(0), + uint64(1e6), + ) + contract.Input = input + contractAddr := contract.Address() + txArgs := evmtypes.EvmTxArgs{ + ChainID: s.App.EvmKeeper.ChainID(), + Nonce: 0, + To: &contractAddr, + Amount: nil, + GasLimit: 100000, + GasPrice: app.MainnetMinGasPrices.BigInt(), + GasFeeCap: baseFee, + GasTipCap: big.NewInt(1), + Accesses: ðtypes.AccessList{}, + } + msgEthereumTx := evmtypes.NewTx(&txArgs) + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) + s.Require().NoError(err, "failed to sign Ethereum message") + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig( + s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID(), + ) + s.Require().NoError(err, "failed to instantiate EVM config") + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) + s.Require().NoError(err, "failed to instantiate Ethereum message") + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, + ) + params := s.App.EvmKeeper.GetParams(s.Ctx) + activePrecompiles := params.GetActivePrecompilesAddrs() + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) + err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) + s.Require().NoError(err, "invalid precompiles", activePrecompiles) + evm.WithPrecompiles(precompileMap, activePrecompiles) + bz, err := s.precompile.Run(evm, contract, true) + s.Require().NoError( + err, "expected no error when running the precompile", + ) + s.Require().Equal( + output, bz, "the return doesn't match the expected result", + ) + }) +} diff --git a/precompiles/assets/setup_test.go b/precompiles/assets/setup_test.go new file mode 100644 index 000000000..bb195127a --- /dev/null +++ b/precompiles/assets/setup_test.go @@ -0,0 +1,38 @@ +package assets_test + +import ( + "testing" + + "github.com/ExocoreNetwork/exocore/precompiles/assets" + + "github.com/ExocoreNetwork/exocore/testutil" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/stretchr/testify/suite" +) + +var s *AssetsPrecompileSuite + +type AssetsPrecompileSuite struct { + testutil.BaseTestSuite + + precompile *assets.Precompile +} + +func TestPrecompileTestSuite(t *testing.T) { + s = new(AssetsPrecompileSuite) + suite.Run(t, s) + + // Run Ginkgo integration tests + RegisterFailHandler(Fail) + RunSpecs(t, "assets Precompile Suite") +} + +func (s *AssetsPrecompileSuite) SetupTest() { + s.DoSetupTest() + precompile, err := assets.NewPrecompile(s.App.AssetsKeeper, s.App.AuthzKeeper) + s.Require().NoError(err) + s.precompile = precompile +} diff --git a/precompiles/assets/tx.go b/precompiles/assets/tx.go new file mode 100644 index 000000000..3d25c1cff --- /dev/null +++ b/precompiles/assets/tx.go @@ -0,0 +1,101 @@ +package assets + +import ( + "fmt" + + errorsmod "cosmossdk.io/errors" + + exocmn "github.com/ExocoreNetwork/exocore/precompiles/common" + assetstypes "github.com/ExocoreNetwork/exocore/x/assets/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + cmn "github.com/evmos/evmos/v14/precompiles/common" +) + +const ( + // MethodDepositTo defines the ABI method name for the deposit + // DepositAndWithdraw transaction. + MethodDepositTo = "depositTo" + MethodWithdraw = "withdrawPrincipal" + + MethodGetClientChains = "getClientChains" +) + +// DepositAndWithdraw deposit and withdraw the client chain assets for the staker, +// that will change the state in assets module. +func (p Precompile) DepositAndWithdraw( + ctx sdk.Context, + _ common.Address, + contract *vm.Contract, + _ vm.StateDB, + method *abi.Method, + args []interface{}, +) ([]byte, error) { + // check the invalidation of caller contract,the caller must be exoCore LzApp contract + err := p.assetsKeeper.CheckExocoreLzAppAddr(ctx, contract.CallerAddress) + if err != nil { + return nil, errorsmod.Wrap(err, exocmn.ErrContractCaller) + } + // parse the depositTo input params + depositWithdrawParams, err := p.GetDepositWithdrawParamsFromInputs(ctx, args) + if err != nil { + return nil, err + } + + // call assets keeper to perform the deposit or withdraw action + switch method.Name { + // deposit transactions + case MethodDepositTo: + depositWithdrawParams.Action = assetstypes.Deposit + case MethodWithdraw: + depositWithdrawParams.Action = assetstypes.WithdrawPrincipal + default: + return nil, fmt.Errorf(cmn.ErrUnknownMethod, method.Name) + } + err = p.assetsKeeper.PerformDepositOrWithdraw(ctx, depositWithdrawParams) + if err != nil { + return nil, err + } + + // get the latest asset state of staker to return. + stakerID, assetID := assetstypes.GetStakeIDAndAssetID(depositWithdrawParams.ClientChainLzID, depositWithdrawParams.StakerAddress, depositWithdrawParams.AssetsAddress) + info, err := p.assetsKeeper.GetStakerSpecifiedAssetInfo(ctx, stakerID, assetID) + if err != nil { + return nil, err + } + + return method.Outputs.Pack(true, info.TotalDepositAmount.BigInt()) +} + +func (p Precompile) GetClientChains( + ctx sdk.Context, + method *abi.Method, + args []interface{}, +) ([]byte, error) { + if len(args) > 0 { + ctx.Logger().Error( + "GetClientChains", + "err", errorsmod.Wrapf( + assetstypes.ErrInvalidInputParameter, "no input is required", + ), + ) + return method.Outputs.Pack(false, nil) + } + infos, err := p.assetsKeeper.GetAllClientChainInfo(ctx) + if err != nil { + ctx.Logger().Error( + "GetClientChains", + "err", err, + ) + return method.Outputs.Pack(false, nil) + } + ids := make([]uint32, 0, len(infos)) + for id := range infos { + // #nosec G701 // already checked + convID := uint32(id) + ids = append(ids, convID) + } + return method.Outputs.Pack(true, ids) +} diff --git a/precompiles/deposit/types.go b/precompiles/assets/types.go similarity index 72% rename from precompiles/deposit/types.go rename to precompiles/assets/types.go index 20f231ebe..482149eef 100644 --- a/precompiles/deposit/types.go +++ b/precompiles/assets/types.go @@ -1,29 +1,29 @@ -package deposit +package assets import ( "math/big" sdkmath "cosmossdk.io/math" exocmn "github.com/ExocoreNetwork/exocore/precompiles/common" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" sdk "github.com/cosmos/cosmos-sdk/types" cmn "github.com/evmos/evmos/v14/precompiles/common" "golang.org/x/xerrors" ) -func (p Precompile) GetDepositToParamsFromInputs(ctx sdk.Context, args []interface{}) (*keeper.DepositParams, error) { +func (p Precompile) GetDepositWithdrawParamsFromInputs(ctx sdk.Context, args []interface{}) (*assetskeeper.DepositWithdrawParams, error) { if len(args) != 4 { return nil, xerrors.Errorf(cmn.ErrInvalidNumberOfArgs, 4, len(args)) } - depositParams := &keeper.DepositParams{} + depositWithdrawParams := &assetskeeper.DepositWithdrawParams{} clientChainLzID, ok := args[0].(uint32) if !ok { return nil, xerrors.Errorf(exocmn.ErrContractInputParaOrType, 0, "uint16", clientChainLzID) } - depositParams.ClientChainLzID = uint64(clientChainLzID) + depositWithdrawParams.ClientChainLzID = uint64(clientChainLzID) - info, err := p.assetsKeeper.GetClientChainInfoByIndex(ctx, depositParams.ClientChainLzID) + info, err := p.assetsKeeper.GetClientChainInfoByIndex(ctx, depositWithdrawParams.ClientChainLzID) if err != nil { return nil, err } @@ -37,7 +37,7 @@ func (p Precompile) GetDepositToParamsFromInputs(ctx sdk.Context, args []interfa if len(assetAddr) != types.GeneralAssetsAddrLength { return nil, xerrors.Errorf(exocmn.ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) } - depositParams.AssetsAddress = assetAddr[:clientChainAddrLength] + depositWithdrawParams.AssetsAddress = assetAddr[:clientChainAddrLength] stakerAddr, ok := args[2].([]byte) if !ok || stakerAddr == nil { @@ -46,13 +46,13 @@ func (p Precompile) GetDepositToParamsFromInputs(ctx sdk.Context, args []interfa if len(stakerAddr) != types.GeneralClientChainAddrLength { return nil, xerrors.Errorf(exocmn.ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) } - depositParams.StakerAddress = stakerAddr[:clientChainAddrLength] + depositWithdrawParams.StakerAddress = stakerAddr[:clientChainAddrLength] opAmount, ok := args[3].(*big.Int) if !ok || opAmount == nil || opAmount.Cmp(big.NewInt(0)) == 0 { return nil, xerrors.Errorf(exocmn.ErrContractInputParaOrType, 3, "*big.Int", opAmount) } - depositParams.OpAmount = sdkmath.NewIntFromBigInt(opAmount) + depositWithdrawParams.OpAmount = sdkmath.NewIntFromBigInt(opAmount) - return depositParams, nil + return depositWithdrawParams, nil } diff --git a/precompiles/clientchains/abi.json b/precompiles/clientchains/abi.json deleted file mode 100644 index eeb2160b7..000000000 --- a/precompiles/clientchains/abi.json +++ /dev/null @@ -1,21 +0,0 @@ -[ - { - "name": "getClientChains", - "type": "function", - "inputs": [], - "outputs": [ - { - "name": "success", - "type": "bool", - "internalType": "bool" - }, - { - "name": "chainIds", - "type": "uint16[]", - "internalType": "uint16[]" - } - ], - "stateMutability": "view", - "payable": false - } -] \ No newline at end of file diff --git a/precompiles/clientchains/clientchains.go b/precompiles/clientchains/clientchains.go deleted file mode 100644 index adf8460ec..000000000 --- a/precompiles/clientchains/clientchains.go +++ /dev/null @@ -1,119 +0,0 @@ -package clientchains - -import ( - "bytes" - "embed" - "fmt" - - assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - "github.com/ethereum/go-ethereum/accounts/abi" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - cmn "github.com/evmos/evmos/v14/precompiles/common" -) - -var _ vm.PrecompiledContract = &Precompile{} - -// Embed abi json file to the executable binary. Needed when importing as dependency. -// -//go:embed abi.json -var f embed.FS - -// Precompile defines the precompiled contract for deposit. -type Precompile struct { - cmn.Precompile - assetsKeeper assetskeeper.Keeper -} - -// NewPrecompile creates a new deposit Precompile instance as a -// PrecompiledContract interface. -func NewPrecompile( - assetsKeeper assetskeeper.Keeper, - authzKeeper authzkeeper.Keeper, -) (*Precompile, error) { - abiBz, err := f.ReadFile("abi.json") - if err != nil { - return nil, fmt.Errorf("error loading the client chains ABI %s", err) - } - - newAbi, err := abi.JSON(bytes.NewReader(abiBz)) - if err != nil { - return nil, fmt.Errorf(cmn.ErrInvalidABI, err) - } - - return &Precompile{ - Precompile: cmn.Precompile{ - ABI: newAbi, - AuthzKeeper: authzKeeper, - KvGasConfig: storetypes.KVGasConfig(), - TransientKVGasConfig: storetypes.TransientGasConfig(), - // should be configurable in the future. - ApprovalExpiration: cmn.DefaultExpirationDuration, - }, - assetsKeeper: assetsKeeper, - }, nil -} - -// Address defines the address of the client chains precompile contract. -// address: 0x0000000000000000000000000000000000000801 -func (p Precompile) Address() common.Address { - return common.HexToAddress("0x0000000000000000000000000000000000000801") -} - -// RequiredGas calculates the precompiled contract's base gas rate. -func (p Precompile) RequiredGas(input []byte) uint64 { - methodID := input[:4] - - method, err := p.MethodById(methodID) - if err != nil { - // This should never happen since this method is going to fail during Run - return 0 - } - return p.Precompile.RequiredGas(input, p.IsTransaction(method.Name)) -} - -// Run executes the precompiled contract client chain methods defined in the ABI. -func (p Precompile) Run( - evm *vm.EVM, contract *vm.Contract, readOnly bool, -) (bz []byte, err error) { - // if the user calls instead of staticcalls, it is their problem. we don't validate that. - ctx, _, method, initialGas, args, err := p.RunSetup( - evm, contract, readOnly, p.IsTransaction, - ) - if err != nil { - return nil, err - } - - // This handles any out of gas errors that may occur during the execution of a precompile tx - // or query. It avoids panics and returns the out of gas error so the EVM can continue - // gracefully. - defer cmn.HandleGasError(ctx, contract, initialGas, &err)() - - bz, err = p.GetClientChains(ctx, method, args) - if err != nil { - ctx.Logger().Error( - "call client chains precompile error", - "module", "client chains precompile", - "err", err, - ) - return nil, err - } - - cost := ctx.GasMeter().GasConsumed() - initialGas - - if !contract.UseGas(cost) { - return nil, vm.ErrOutOfGas - } - - return bz, nil -} - -// IsTransaction checks if the given methodID corresponds to a transaction (true) -// or query (false). -func (Precompile) IsTransaction(string) bool { - // there are no transaction methods in this precompile, only queries. - return false -} diff --git a/precompiles/clientchains/clientchains.sol b/precompiles/clientchains/clientchains.sol deleted file mode 100644 index e687ff062..000000000 --- a/precompiles/clientchains/clientchains.sol +++ /dev/null @@ -1,19 +0,0 @@ -pragma solidity >=0.8.17; - -/// @dev The CLIENT_CHAINS contract's address. -address constant CLIENT_CHAINS_PRECOMPILE_ADDRESS = 0x0000000000000000000000000000000000000801; - -/// @dev The CLIENT_CHAINS contract's instance. -IClientChains constant CLIENT_CHAINS_CONTRACT = IClientChains( - CLIENT_CHAINS_PRECOMPILE_ADDRESS -); - -/// @author Exocore Team -/// @title Client Chains Precompile Contract -/// @dev The interface through which solidity contracts will interact with ClientChains -/// @custom:address 0x0000000000000000000000000000000000000801 -interface IClientChains { - /// @dev Returns the chain indices of the client chains. - function getClientChains() external view returns (bool, uint16[] memory); -} - diff --git a/precompiles/clientchains/clientchains_test.go b/precompiles/clientchains/clientchains_test.go deleted file mode 100644 index 2bd3b6b1d..000000000 --- a/precompiles/clientchains/clientchains_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package clientchains_test - -import ( - "math/big" - - "github.com/ExocoreNetwork/exocore/app" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" -) - -func (s *ClientChainsPrecompileSuite) TestIsTransaction() { - testCases := []struct { - name string - method string - isTx bool - }{ - { - "non existant method", - "HelloFakeMethod", - false, - }, - { - "actual method", - "getClientChains", - false, - }, - } - - for _, tc := range testCases { - s.Run(tc.name, func() { - s.Require().Equal(s.precompile.IsTransaction(tc.method), tc.isTx) - }) - } -} - -func paddingClientChainAddress(input []byte, outputLength int) []byte { - if len(input) < outputLength { - padding := make([]byte, outputLength-len(input)) - return append(input, padding...) - } - return input -} - -func (s *ClientChainsPrecompileSuite) TestGetClientChains() { - input, err := s.precompile.Pack("getClientChains") - s.Require().NoError(err, "failed to pack input") - output, err := s.precompile.Methods["getClientChains"].Outputs.Pack(true, []uint16{101}) - s.Require().NoError(err, "failed to pack output") - s.Run("get client chains", func() { - s.SetupTest() - baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) - contract := vm.NewPrecompile( - vm.AccountRef(s.Address), - s.precompile, - big.NewInt(0), - uint64(1e6), - ) - contract.Input = input - contractAddr := contract.Address() - txArgs := evmtypes.EvmTxArgs{ - ChainID: s.App.EvmKeeper.ChainID(), - Nonce: 0, - To: &contractAddr, - Amount: nil, - GasLimit: 100000, - GasPrice: app.MainnetMinGasPrices.BigInt(), - GasFeeCap: baseFee, - GasTipCap: big.NewInt(1), - Accesses: ðtypes.AccessList{}, - } - msgEthereumTx := evmtypes.NewTx(&txArgs) - msgEthereumTx.From = s.Address.String() - err := msgEthereumTx.Sign(s.EthSigner, s.Signer) - s.Require().NoError(err, "failed to sign Ethereum message") - proposerAddress := s.Ctx.BlockHeader().ProposerAddress - cfg, err := s.App.EvmKeeper.EVMConfig( - s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID(), - ) - s.Require().NoError(err, "failed to instantiate EVM config") - msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) - s.Require().NoError(err, "failed to instantiate Ethereum message") - evm := s.App.EvmKeeper.NewEVM( - s.Ctx, msg, cfg, nil, s.StateDB, - ) - params := s.App.EvmKeeper.GetParams(s.Ctx) - activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) - err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) - s.Require().NoError(err, "invalid precompiles", activePrecompiles) - evm.WithPrecompiles(precompileMap, activePrecompiles) - bz, err := s.precompile.Run(evm, contract, true) - s.Require().NoError( - err, "expected no error when running the precompile", - ) - s.Require().Equal( - output, bz, "the return doesn't match the expected result", - ) - }) -} diff --git a/precompiles/clientchains/setup_test.go b/precompiles/clientchains/setup_test.go deleted file mode 100644 index 2ca76b016..000000000 --- a/precompiles/clientchains/setup_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package clientchains_test - -import ( - "testing" - - "github.com/ExocoreNetwork/exocore/precompiles/clientchains" - "github.com/ExocoreNetwork/exocore/testutil" - - "github.com/stretchr/testify/suite" -) - -var s *ClientChainsPrecompileSuite - -type ClientChainsPrecompileSuite struct { - testutil.BaseTestSuite - - precompile *clientchains.Precompile -} - -func TestPrecompileTestSuite(t *testing.T) { - s = new(ClientChainsPrecompileSuite) - suite.Run(t, s) -} - -func (s *ClientChainsPrecompileSuite) SetupTest() { - s.DoSetupTest() - precompile, err := clientchains.NewPrecompile( - s.App.AssetsKeeper, s.App.AuthzKeeper, - ) - s.Require().NoError(err) - s.precompile = precompile -} diff --git a/precompiles/clientchains/tx.go b/precompiles/clientchains/tx.go deleted file mode 100644 index 9ce49bdcf..000000000 --- a/precompiles/clientchains/tx.go +++ /dev/null @@ -1,53 +0,0 @@ -package clientchains - -import ( - "math" - - errorsmod "cosmossdk.io/errors" - assetstypes "github.com/ExocoreNetwork/exocore/x/assets/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/accounts/abi" -) - -func (p Precompile) GetClientChains( - ctx sdk.Context, - method *abi.Method, - args []interface{}, -) ([]byte, error) { - if len(args) > 0 { - ctx.Logger().Error( - "GetClientChains", - "err", errorsmod.Wrapf( - assetstypes.ErrInvalidInputParameter, "no input is required", - ), - ) - return method.Outputs.Pack(false, nil) - } - infos, err := p.assetsKeeper.GetAllClientChainInfo(ctx) - if err != nil { - ctx.Logger().Error( - "GetClientChains", - "err", err, - ) - return method.Outputs.Pack(false, nil) - } - ids := make([]uint16, 0, len(infos)) - for id := range infos { - // technically LZ supports uint32, but unfortunately all the precompiles - // based it on uint16, so we have to stick with it. - // TODO: change it to uint32 here and in other precompiles. - if id > math.MaxUint16 { - ctx.Logger().Error( - "GetClientChains", - "err", errorsmod.Wrapf( - assetstypes.ErrInvalidInputParameter, "client chain id is too large", - ), - ) - return method.Outputs.Pack(false, nil) - } - // #nosec G701 // already checked - convID := uint16(id) - ids = append(ids, convID) - } - return method.Outputs.Pack(true, ids) -} diff --git a/precompiles/delegation/delegation.sol b/precompiles/delegation/IDelegation.sol similarity index 100% rename from precompiles/delegation/delegation.sol rename to precompiles/delegation/IDelegation.sol diff --git a/precompiles/delegation/delegation.go b/precompiles/delegation/delegation.go index 24fa84cf5..77c59ab59 100644 --- a/precompiles/delegation/delegation.go +++ b/precompiles/delegation/delegation.go @@ -90,11 +90,13 @@ func (p Precompile) Run(evm *vm.EVM, contract *vm.Contract, readOnly bool) (bz [ // It avoids panics and returns the out of gas error so the EVM can continue gracefully. defer cmn.HandleGasError(ctx, contract, initialGas, &err)() switch method.Name { - // deposit transactions + // delegation transactions case MethodDelegateToThroughClientChain: bz, err = p.DelegateToThroughClientChain(ctx, evm.Origin, contract, stateDB, method, args) case MethodUndelegateFromThroughClientChain: bz, err = p.UndelegateFromThroughClientChain(ctx, evm.Origin, contract, stateDB, method, args) + default: + return nil, fmt.Errorf(cmn.ErrUnknownMethod, method.Name) } if err != nil { @@ -118,7 +120,7 @@ func (p Precompile) Run(evm *vm.EVM, contract *vm.Contract, readOnly bool) (bz [ // IsTransaction checks if the given methodID corresponds to a transaction or query. // // Available deposit transactions are: -// - DepositTo +// - DepositAndWithdraw func (Precompile) IsTransaction(methodID string) bool { switch methodID { case MethodDelegateToThroughClientChain, diff --git a/precompiles/delegation/delegation_test.go b/precompiles/delegation/delegation_test.go index 482b3c83a..3a5b6ff28 100644 --- a/precompiles/delegation/delegation_test.go +++ b/precompiles/delegation/delegation_test.go @@ -3,6 +3,8 @@ package delegation_test import ( "math/big" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" + operatortypes "github.com/ExocoreNetwork/exocore/x/operator/types" sdkmath "cosmossdk.io/math" @@ -12,7 +14,6 @@ import ( "github.com/ExocoreNetwork/exocore/x/assets/types" assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" delegationtype "github.com/ExocoreNetwork/exocore/x/delegation/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" @@ -74,14 +75,14 @@ func (s *DelegationPrecompileSuite) TestRunDelegateToThroughClientChain() { assetAddr := paddingClientChainAddress(usdtAddress, types.GeneralClientChainAddrLength) depositAsset := func(staker []byte, depositAmount sdkmath.Int) { // deposit asset for delegation test - params := &keeper.DepositParams{ + params := &assetskeeper.DepositWithdrawParams{ ClientChainLzID: 101, Action: types.Deposit, StakerAddress: staker, AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.App.DepositKeeper.Deposit(s.Ctx, params) + err := s.App.AssetsKeeper.PerformDepositOrWithdraw(s.Ctx, params) s.Require().NoError(err) } registerOperator := func() { @@ -300,14 +301,14 @@ func (s *DelegationPrecompileSuite) TestRunUnDelegateFromThroughClientChain() { assetAddr := paddingClientChainAddress(usdtAddress, types.GeneralClientChainAddrLength) depositAsset := func(staker []byte, depositAmount sdkmath.Int) { // deposit asset for delegation test - params := &keeper.DepositParams{ + params := &assetskeeper.DepositWithdrawParams{ ClientChainLzID: 101, Action: types.Deposit, StakerAddress: staker, AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.App.DepositKeeper.Deposit(s.Ctx, params) + err := s.App.AssetsKeeper.PerformDepositOrWithdraw(s.Ctx, params) s.Require().NoError(err) } diff --git a/precompiles/deposit/abi.json b/precompiles/deposit/abi.json deleted file mode 100644 index 385f4231c..000000000 --- a/precompiles/deposit/abi.json +++ /dev/null @@ -1,43 +0,0 @@ -[ - { - "inputs": - [ - { - "internalType": "uint32", - "name": "clientChainLzID", - "type": "uint32" - }, - { - "internalType": "bytes", - "name": "assetsAddress", - "type": "bytes" - }, - { - "internalType": "bytes", - "name": "stakerAddress", - "type": "bytes" - }, - { - "internalType": "uint256", - "name": "opAmount", - "type": "uint256" - } - ], - "name": "depositTo", - "outputs": - [ - { - "internalType": "bool", - "name": "success", - "type": "bool" - }, - { - "internalType": "uint256", - "name": "latestAssetState", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } -] \ No newline at end of file diff --git a/precompiles/deposit/deposit.sol b/precompiles/deposit/deposit.sol deleted file mode 100644 index 4713d5f64..000000000 --- a/precompiles/deposit/deposit.sol +++ /dev/null @@ -1,30 +0,0 @@ -pragma solidity >=0.8.17; - -/// @dev The DEPOSIT contract's address. -address constant DEPOSIT_PRECOMPILE_ADDRESS = 0x0000000000000000000000000000000000000804; - -/// @dev The DEPOSIT contract's instance. -IDeposit constant DEPOSIT_CONTRACT = IDeposit( - DEPOSIT_PRECOMPILE_ADDRESS -); - -/// @author Exocore Team -/// @title Deposit Precompile Contract -/// @dev The interface through which solidity contracts will interact with Deposit -/// @custom:address 0x0000000000000000000000000000000000000804 -interface IDeposit { -/// TRANSACTIONS -/// @dev deposit the client chain assets to the staker, that will change the state in deposit module -/// Note that this address cannot be a module account. -/// @param clientChainLzID The LzID of client chain -/// @param assetsAddress The client chain asset address -/// @param stakerAddress The staker address -/// @param opAmount The deposit amount - function depositTo( - uint32 clientChainLzID, - bytes memory assetsAddress, - bytes memory stakerAddress, - uint256 opAmount - ) external returns (bool success,uint256 latestAssetState); -} - diff --git a/precompiles/deposit/deposit_test.go b/precompiles/deposit/deposit_test.go deleted file mode 100644 index 359dfce4a..000000000 --- a/precompiles/deposit/deposit_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package deposit_test - -import ( - "math/big" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/precompiles/deposit" - assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" -) - -func (s *DepositPrecompileSuite) TestIsTransaction() { - testCases := []struct { - name string - method string - isTx bool - }{ - { - deposit.MethodDepositTo, - s.precompile.Methods[deposit.MethodDepositTo].Name, - true, - }, - { - "invalid", - "invalid", - false, - }, - } - - for _, tc := range testCases { - s.Run(tc.name, func() { - s.Require().Equal(s.precompile.IsTransaction(tc.method), tc.isTx) - }) - } -} - -func paddingClientChainAddress(input []byte, outputLength int) []byte { - if len(input) < outputLength { - padding := make([]byte, outputLength-len(input)) - return append(input, padding...) - } - return input -} - -// TestRunDepositTo tests DepositTo method through calling Run function.. -func (s *DepositPrecompileSuite) TestRunDepositTo() { - // deposit params for test - exocoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" - exocoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" - usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), assetstype.GeneralClientChainAddrLength) - usdcAddress := paddingClientChainAddress(common.FromHex("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), assetstype.GeneralClientChainAddrLength) - clientChainLzID := 101 - stakerAddr := paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength) - opAmount := big.NewInt(100) - assetAddr := usdtAddress - commonMalleate := func() (common.Address, []byte) { - input, err := s.precompile.Pack( - deposit.MethodDepositTo, - uint32(clientChainLzID), - assetAddr, - stakerAddr, - opAmount, - ) - s.Require().NoError(err, "failed to pack input") - return s.Address, input - } - successRet, err := s.precompile.Methods[deposit.MethodDepositTo].Outputs.Pack(true, opAmount) - s.Require().NoError(err) - - testcases := []struct { - name string - malleate func() (common.Address, []byte) - readOnly bool - expPass bool - errContains string - returnBytes []byte - }{ - { - name: "fail - depositTo transaction will fail because the exocoreLzAppAddress is mismatched", - malleate: func() (common.Address, []byte) { - return commonMalleate() - }, - readOnly: false, - expPass: false, - errContains: assetstype.ErrNotEqualToLzAppAddr.Error(), - }, - { - name: "fail - depositTo transaction will fail because the contract caller isn't the exoCoreLzAppAddr", - malleate: func() (common.Address, []byte) { - depositModuleParam := &assetstype.Params{ - ExocoreLzAppAddress: exocoreLzAppAddress, - ExocoreLzAppEventTopic: exocoreLzAppEventTopic, - } - err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) - s.Require().NoError(err) - return commonMalleate() - }, - readOnly: false, - expPass: false, - errContains: assetstype.ErrNotEqualToLzAppAddr.Error(), - }, - { - name: "fail - depositTo transaction will fail because the staked asset hasn't been registered", - malleate: func() (common.Address, []byte) { - depositModuleParam := &assetstype.Params{ - ExocoreLzAppAddress: s.Address.String(), - ExocoreLzAppEventTopic: exocoreLzAppEventTopic, - } - err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) - s.Require().NoError(err) - assetAddr = usdcAddress - return commonMalleate() - }, - readOnly: false, - expPass: false, - errContains: assetstype.ErrNoClientChainAssetKey.Error(), - }, - { - name: "pass - depositTo transaction", - malleate: func() (common.Address, []byte) { - depositModuleParam := &assetstype.Params{ - ExocoreLzAppAddress: s.Address.String(), - ExocoreLzAppEventTopic: exocoreLzAppEventTopic, - } - assetAddr = usdtAddress - err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) - s.Require().NoError(err) - return commonMalleate() - }, - returnBytes: successRet, - readOnly: false, - expPass: true, - }, - } - - for _, tc := range testcases { - tc := tc - s.Run(tc.name, func() { - // setup basic test suite - s.SetupTest() - - baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) - - // malleate testcase - caller, input := tc.malleate() - - contract := vm.NewPrecompile(vm.AccountRef(caller), s.precompile, big.NewInt(0), uint64(1e6)) - contract.Input = input - - contractAddr := contract.Address() - // Build and sign Ethereum transaction - txArgs := evmtypes.EvmTxArgs{ - ChainID: s.App.EvmKeeper.ChainID(), - Nonce: 0, - To: &contractAddr, - Amount: nil, - GasLimit: 100000, - GasPrice: app.MainnetMinGasPrices.BigInt(), - GasFeeCap: baseFee, - GasTipCap: big.NewInt(1), - Accesses: ðtypes.AccessList{}, - } - msgEthereumTx := evmtypes.NewTx(&txArgs) - - msgEthereumTx.From = s.Address.String() - err := msgEthereumTx.Sign(s.EthSigner, s.Signer) - s.Require().NoError(err, "failed to sign Ethereum message") - - // Instantiate config - proposerAddress := s.Ctx.BlockHeader().ProposerAddress - cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) - s.Require().NoError(err, "failed to instantiate EVM config") - - msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) - s.Require().NoError(err, "failed to instantiate Ethereum message") - - // Instantiate EVM - evm := s.App.EvmKeeper.NewEVM( - s.Ctx, msg, cfg, nil, s.StateDB, - ) - - params := s.App.EvmKeeper.GetParams(s.Ctx) - activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) - err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) - s.Require().NoError(err, "invalid precompiles", activePrecompiles) - evm.WithPrecompiles(precompileMap, activePrecompiles) - - // Run precompiled contract - bz, err := s.precompile.Run(evm, contract, tc.readOnly) - - // Check results - if tc.expPass { - s.Require().NoError(err, "expected no error when running the precompile") - s.Require().Equal(tc.returnBytes, bz, "the return doesn't match the expected result") - } else { - s.Require().Error(err, "expected error to be returned when running the precompile") - s.Require().Nil(bz, "expected returned bytes to be nil") - s.Require().ErrorContains(err, tc.errContains) - } - }) - } -} diff --git a/precompiles/deposit/setup_test.go b/precompiles/deposit/setup_test.go deleted file mode 100644 index df09c3a8a..000000000 --- a/precompiles/deposit/setup_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package deposit_test - -import ( - "testing" - - "github.com/ExocoreNetwork/exocore/testutil" - - "github.com/ExocoreNetwork/exocore/precompiles/deposit" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "github.com/stretchr/testify/suite" -) - -var s *DepositPrecompileSuite - -type DepositPrecompileSuite struct { - testutil.BaseTestSuite - - precompile *deposit.Precompile -} - -func TestPrecompileTestSuite(t *testing.T) { - s = new(DepositPrecompileSuite) - suite.Run(t, s) - - // Run Ginkgo integration tests - RegisterFailHandler(Fail) - RunSpecs(t, "Distribution Precompile Suite") -} - -func (s *DepositPrecompileSuite) SetupTest() { - s.DoSetupTest() - precompile, err := deposit.NewPrecompile(s.App.AssetsKeeper, s.App.DepositKeeper, s.App.AuthzKeeper) - s.Require().NoError(err) - s.precompile = precompile -} diff --git a/precompiles/deposit/tx.go b/precompiles/deposit/tx.go deleted file mode 100644 index 83a9fe114..000000000 --- a/precompiles/deposit/tx.go +++ /dev/null @@ -1,53 +0,0 @@ -package deposit - -import ( - errorsmod "cosmossdk.io/errors" - exocmn "github.com/ExocoreNetwork/exocore/precompiles/common" - "github.com/ExocoreNetwork/exocore/x/assets/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" -) - -const ( - // MethodDepositTo defines the ABI method name for the deposit - // DepositTo transaction. - MethodDepositTo = "depositTo" -) - -// DepositTo deposit the client chain assets to the staker, that will change the state in deposit module. -func (p Precompile) DepositTo( - ctx sdk.Context, - _ common.Address, - contract *vm.Contract, - _ vm.StateDB, - method *abi.Method, - args []interface{}, -) ([]byte, error) { - // check the invalidation of caller contract,the caller must be exoCore LzApp contract - err := p.assetsKeeper.CheckExocoreLzAppAddr(ctx, contract.CallerAddress) - if err != nil { - return nil, errorsmod.Wrap(err, exocmn.ErrContractCaller) - } - // parse the depositTo input params - depositParams, err := p.GetDepositToParamsFromInputs(ctx, args) - if err != nil { - return nil, err - } - - // call depositKeeper to execute the deposit action - err = p.depositKeeper.Deposit(ctx, depositParams) - if err != nil { - return nil, err - } - - // get the latest asset state of staker to return. - stakerID, assetID := types.GetStakeIDAndAssetID(depositParams.ClientChainLzID, depositParams.StakerAddress, depositParams.AssetsAddress) - info, err := p.assetsKeeper.GetStakerSpecifiedAssetInfo(ctx, stakerID, assetID) - if err != nil { - return nil, err - } - - return method.Outputs.Pack(true, info.TotalDepositAmount.BigInt()) -} diff --git a/precompiles/reward/reward_test.go b/precompiles/reward/reward_test.go index e40131244..cb1c0e055 100644 --- a/precompiles/reward/reward_test.go +++ b/precompiles/reward/reward_test.go @@ -3,11 +3,12 @@ package reward_test import ( "math/big" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" + sdkmath "cosmossdk.io/math" "github.com/ExocoreNetwork/exocore/app" "github.com/ExocoreNetwork/exocore/precompiles/reward" assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" @@ -59,14 +60,14 @@ func (s *RewardPrecompileTestSuite) TestRunRewardThroughClientChain() { assetAddr := paddingClientChainAddress(usdtAddress, assetstype.GeneralClientChainAddrLength) depositAsset := func(staker []byte, depositAmount sdkmath.Int) { // deposit asset for reward test - params := &keeper.DepositParams{ + params := &assetskeeper.DepositWithdrawParams{ ClientChainLzID: 101, Action: assetstype.Deposit, StakerAddress: staker, AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.App.DepositKeeper.Deposit(s.Ctx, params) + err := s.App.AssetsKeeper.PerformDepositOrWithdraw(s.Ctx, params) s.Require().NoError(err) } diff --git a/precompiles/slash/slash_test.go b/precompiles/slash/slash_test.go index 04b8779fe..8f806b8ba 100644 --- a/precompiles/slash/slash_test.go +++ b/precompiles/slash/slash_test.go @@ -3,11 +3,12 @@ package slash_test import ( "math/big" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" + sdkmath "cosmossdk.io/math" "github.com/ExocoreNetwork/exocore/app" "github.com/ExocoreNetwork/exocore/precompiles/slash" assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" @@ -59,14 +60,14 @@ func (s *SlashPrecompileTestSuite) TestRunSlash() { assetAddr := paddingClientChainAddress(usdtAddress, assetstype.GeneralClientChainAddrLength) depositAsset := func(staker []byte, depositAmount sdkmath.Int) { // deposit asset for slash test - params := &keeper.DepositParams{ + params := &assetskeeper.DepositWithdrawParams{ ClientChainLzID: 101, Action: assetstype.Deposit, StakerAddress: staker, AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.App.DepositKeeper.Deposit(s.Ctx, params) + err := s.App.AssetsKeeper.PerformDepositOrWithdraw(s.Ctx, params) s.Require().NoError(err) } diff --git a/precompiles/withdraw/abi.json b/precompiles/withdraw/abi.json deleted file mode 100644 index 232d7c3f7..000000000 --- a/precompiles/withdraw/abi.json +++ /dev/null @@ -1,43 +0,0 @@ -[ - { - "inputs": - [ - { - "internalType": "uint32", - "name": "clientChainLzID", - "type": "uint32" - }, - { - "internalType": "bytes", - "name": "assetsAddress", - "type": "bytes" - }, - { - "internalType": "bytes", - "name": "withdrawAddress", - "type": "bytes" - }, - { - "internalType": "uint256", - "name": "opAmount", - "type": "uint256" - } - ], - "name": "withdrawPrinciple", - "outputs": - [ - { - "internalType": "bool", - "name": "success", - "type": "bool" - }, - { - "internalType": "uint256", - "name": "latestAssetState", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } -] \ No newline at end of file diff --git a/precompiles/withdraw/methods.go b/precompiles/withdraw/methods.go deleted file mode 100644 index d94970f2a..000000000 --- a/precompiles/withdraw/methods.go +++ /dev/null @@ -1,49 +0,0 @@ -package withdraw - -import ( - errorsmod "cosmossdk.io/errors" - exocmn "github.com/ExocoreNetwork/exocore/precompiles/common" - "github.com/ExocoreNetwork/exocore/x/assets/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" -) - -const ( - // MethodWithdraw defines the ABI method name for the withdrawal transaction. - MethodWithdraw = "withdrawPrinciple" -) - -// Withdraw assets to the staker, that will change the state in withdraw module. -func (p Precompile) Withdraw( - ctx sdk.Context, - _ common.Address, - contract *vm.Contract, - _ vm.StateDB, - method *abi.Method, - args []interface{}, -) ([]byte, error) { - // check the invalidation of caller contract - err := p.assetsKeeper.CheckExocoreLzAppAddr(ctx, contract.CallerAddress) - if err != nil { - return nil, errorsmod.Wrap(err, exocmn.ErrContractCaller) - } - - withdrawParam, err := p.GetWithdrawParamsFromInputs(ctx, args) - if err != nil { - return nil, err - } - - err = p.withdrawKeeper.Withdraw(ctx, withdrawParam) - if err != nil { - return nil, err - } - // get the latest asset state of staker to return. - stakerID, assetID := types.GetStakeIDAndAssetID(withdrawParam.ClientChainLzID, withdrawParam.WithdrawAddress, withdrawParam.AssetsAddress) - info, err := p.assetsKeeper.GetStakerSpecifiedAssetInfo(ctx, stakerID, assetID) - if err != nil { - return nil, err - } - return method.Outputs.Pack(true, info.TotalDepositAmount.BigInt()) -} diff --git a/precompiles/withdraw/parser.go b/precompiles/withdraw/parser.go deleted file mode 100644 index abeb2519e..000000000 --- a/precompiles/withdraw/parser.go +++ /dev/null @@ -1,60 +0,0 @@ -package withdraw - -import ( - "fmt" - "math/big" - "reflect" - - exocmn "github.com/ExocoreNetwork/exocore/precompiles/common" - - sdkmath "cosmossdk.io/math" - "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ExocoreNetwork/exocore/x/withdraw/keeper" - sdk "github.com/cosmos/cosmos-sdk/types" - cmn "github.com/evmos/evmos/v14/precompiles/common" -) - -func (p Precompile) GetWithdrawParamsFromInputs(ctx sdk.Context, args []interface{}) (*keeper.WithdrawParams, error) { - if len(args) != 4 { - return nil, fmt.Errorf(cmn.ErrInvalidNumberOfArgs, 4, len(args)) - } - withdrawParams := &keeper.WithdrawParams{} - clientChainLzID, ok := args[0].(uint32) - if !ok { - return nil, fmt.Errorf(exocmn.ErrContractInputParaOrType, 0, reflect.TypeOf(args[0]), clientChainLzID) - } - withdrawParams.ClientChainLzID = uint64(clientChainLzID) - - info, err := p.assetsKeeper.GetClientChainInfoByIndex(ctx, withdrawParams.ClientChainLzID) - if err != nil { - return nil, err - } - clientChainAddrLength := info.AddressLength - - // the length of client chain address inputted by caller is 32, so we need to check the length and remove the padding according to the actual length. - assetAddr, ok := args[1].([]byte) - if !ok || assetAddr == nil { - return nil, fmt.Errorf(exocmn.ErrContractInputParaOrType, 1, reflect.TypeOf(args[0]), assetAddr) - } - if len(assetAddr) != types.GeneralAssetsAddrLength { - return nil, fmt.Errorf(exocmn.ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) - } - withdrawParams.AssetsAddress = assetAddr[:clientChainAddrLength] - - stakerAddr, ok := args[2].([]byte) - if !ok || stakerAddr == nil { - return nil, fmt.Errorf(exocmn.ErrContractInputParaOrType, 2, reflect.TypeOf(args[0]), stakerAddr) - } - if len(stakerAddr) != types.GeneralClientChainAddrLength { - return nil, fmt.Errorf(exocmn.ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) - } - withdrawParams.WithdrawAddress = stakerAddr[:clientChainAddrLength] - - opAmount, ok := args[3].(*big.Int) - if !ok || opAmount == nil || opAmount.Cmp(big.NewInt(0)) == 0 { - return nil, fmt.Errorf(exocmn.ErrContractInputParaOrType, 3, reflect.TypeOf(args[0]), opAmount) - } - - withdrawParams.OpAmount = sdkmath.NewIntFromBigInt(opAmount) - return withdrawParams, nil -} diff --git a/precompiles/withdraw/setup_test.go b/precompiles/withdraw/setup_test.go deleted file mode 100644 index befb1fc66..000000000 --- a/precompiles/withdraw/setup_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package withdraw_test - -import ( - "testing" - - "github.com/ExocoreNetwork/exocore/testutil" - - "github.com/ExocoreNetwork/exocore/precompiles/withdraw" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "github.com/stretchr/testify/suite" -) - -var s *WithdrawPrecompileTestSuite - -type WithdrawPrecompileTestSuite struct { - testutil.BaseTestSuite - precompile *withdraw.Precompile -} - -func TestPrecompileTestSuite(t *testing.T) { - s = new(WithdrawPrecompileTestSuite) - suite.Run(t, s) - - // Run Ginkgo integration tests - RegisterFailHandler(Fail) - RunSpecs(t, "Withdraw Precompile Suite") -} - -func (s *WithdrawPrecompileTestSuite) SetupTest() { - s.DoSetupTest() - precompile, err := withdraw.NewPrecompile(s.App.AssetsKeeper, s.App.WithdrawKeeper, s.App.AuthzKeeper) - s.Require().NoError(err) - s.precompile = precompile -} diff --git a/precompiles/withdraw/withdraw.go b/precompiles/withdraw/withdraw.go deleted file mode 100644 index c5578b705..000000000 --- a/precompiles/withdraw/withdraw.go +++ /dev/null @@ -1,132 +0,0 @@ -package withdraw - -import ( - "bytes" - "embed" - "fmt" - "math/big" - - assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" - withdrawkeeper "github.com/ExocoreNetwork/exocore/x/withdraw/keeper" - "github.com/cometbft/cometbft/libs/log" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - cmn "github.com/evmos/evmos/v14/precompiles/common" -) - -var _ vm.PrecompiledContract = &Precompile{} - -// Embed abi json file to the executable binary. Needed when importing as dependency. -// -//go:embed abi.json -var f embed.FS - -// Precompile defines the precompiled contract for Withdraw. -type Precompile struct { - cmn.Precompile - assetsKeeper assetskeeper.Keeper - withdrawKeeper withdrawkeeper.Keeper -} - -// NewPrecompile creates a new Withdraw Precompile instance as a -// PrecompiledContract interface. -func NewPrecompile( - stakingStateKeeper assetskeeper.Keeper, - withdrawKeeper withdrawkeeper.Keeper, - authzKeeper authzkeeper.Keeper, -) (*Precompile, error) { - abiBz, err := f.ReadFile("abi.json") - if err != nil { - return nil, fmt.Errorf("error loading the Withdraw ABI %s", err) - } - - newAbi, err := abi.JSON(bytes.NewReader(abiBz)) - if err != nil { - return nil, fmt.Errorf(cmn.ErrInvalidABI, err) - } - - return &Precompile{ - Precompile: cmn.Precompile{ - ABI: newAbi, - AuthzKeeper: authzKeeper, - KvGasConfig: storetypes.KVGasConfig(), - TransientKVGasConfig: storetypes.TransientGasConfig(), - ApprovalExpiration: cmn.DefaultExpirationDuration, // should be configurable in the future. - }, - withdrawKeeper: withdrawKeeper, - assetsKeeper: stakingStateKeeper, - }, nil -} - -// Address defines the address of the Withdrawal compile contract. -// address: 0x0000000000000000000000000000000000000808 -func (p Precompile) Address() common.Address { - return common.HexToAddress("0x0000000000000000000000000000000000000808") -} - -// RequiredGas calculates the precompiled contract's base gas rate. -func (p Precompile) RequiredGas(input []byte) uint64 { - methodID := input[:4] - - method, err := p.MethodById(methodID) - if err != nil { - // This should never happen since this method is going to fail during Run - return 0 - } - - return p.Precompile.RequiredGas(input, p.IsTransaction(method.Name)) -} - -// Run executes the precompiled contract Withdraw methods defined in the ABI. -func (p Precompile) Run(evm *vm.EVM, contract *vm.Contract, readOnly bool) (bz []byte, err error) { - ctx, stateDB, method, initialGas, args, err := p.RunSetup(evm, contract, readOnly, p.IsTransaction) - if err != nil { - return nil, err - } - - // This handles any out of gas errors that may occur during the execution of a precompile tx or query. - // It avoids panics and returns the out of gas error so the EVM can continue gracefully. - defer cmn.HandleGasError(ctx, contract, initialGas, &err)() - - if method.Name == MethodWithdraw { - bz, err = p.Withdraw(ctx, evm.Origin, contract, stateDB, method, args) - } - - if err != nil { - // for failed cases we expect it returns bool value instead of error - // this is a workaround because the error returned by precompile can not be caught in EVM - // see https://github.com/ExocoreNetwork/exocore/issues/70 - // TODO: we should figure out root cause and fix this issue to make precompiles work normally - return method.Outputs.Pack(false, new(big.Int)) - } - - cost := ctx.GasMeter().GasConsumed() - initialGas - - if !contract.UseGas(cost) { - return nil, vm.ErrOutOfGas - } - - return bz, nil -} - -// IsTransaction checks if the given methodID corresponds to a transaction or query. -// -// Available Withdraw transactions are: -// - Withdraw -func (Precompile) IsTransaction(methodID string) bool { - switch methodID { - case MethodWithdraw: - return true - default: - return false - } -} - -// Logger returns a precompile-specific logger. -func (p Precompile) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("ExoCore module", "withdraw") -} diff --git a/precompiles/withdraw/withdraw.sol b/precompiles/withdraw/withdraw.sol deleted file mode 100644 index 7ad8de818..000000000 --- a/precompiles/withdraw/withdraw.sol +++ /dev/null @@ -1,29 +0,0 @@ -pragma solidity >=0.8.17 .0; - -/// @dev The WITHDRAW contract's address. -address constant WITHDRAW_PRECOMPILE_ADDRESS = 0x0000000000000000000000000000000000000808; - -/// @dev The WITHDRAW contract's instance. -IWithdraw constant WITHDRAW_CONTRACT = IWithdraw( - WITHDRAW_PRECOMPILE_ADDRESS -); - -/// @author Exocore Team -/// @title WITHDRAW Precompile Contract -/// @dev The interface through which solidity contracts will interact with WITHDRAW -/// @custom:address 0x0000000000000000000000000000000000000808 -interface IWithdraw { -/// TRANSACTIONS -/// @dev withdraw To the staker, that will change the state in withdraw module -/// Note that this address cannot be a module account. -/// @param clientChainLzID The LzID of client chain -/// @param assetsAddress The client chain asset Address -/// @param withdrawAddress The withdraw address -/// @param opAmount The withdraw amount - function withdrawPrinciple( - uint32 clientChainLzID, - bytes memory assetsAddress, - bytes memory withdrawAddress, - uint256 opAmount - ) external returns (bool success, uint256 latestAssetState); -} \ No newline at end of file diff --git a/precompiles/withdraw/withdraw_integrate_test.go b/precompiles/withdraw/withdraw_integrate_test.go deleted file mode 100644 index 9864304ef..000000000 --- a/precompiles/withdraw/withdraw_integrate_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package withdraw_test - -import ( - "math/big" - - "github.com/ExocoreNetwork/exocore/precompiles/testutil" - "github.com/ExocoreNetwork/exocore/precompiles/testutil/contracts" - assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ethereum/go-ethereum/common" -) - -// General variables used for integration tests -var ( - // defaultCallArgs are the default arguments for calling the smart contract - // - // NOTE: this has to be populated in a BeforeEach block because the contractAddr would otherwise be a nil address. - defaultCallArgs contracts.CallArgs - - // defaultLogCheck instantiates a log check arguments struct with the precompile ABI events populated. - defaultLogCheck testutil.LogCheckArgs - - // passCheck defines the arguments to check if the precompile returns no error - passCheck testutil.LogCheckArgs -) - -func (s *WithdrawPrecompileTestSuite) TestCallWithdrawFromEOA() { - // withdraw params for test - exocoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" - exocoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" - params := assetstype.Params{ - ExocoreLzAppAddress: exocoreLzAppAddress, - ExocoreLzAppEventTopic: exocoreLzAppEventTopic, - } - usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), assetstype.GeneralClientChainAddrLength) - clientChainLzID := 101 - stakerAddr := paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength) - opAmount := big.NewInt(100) - assetAddr := usdtAddress - method := "withdrawPrinciple" - - beforeEach := func() { - s.SetupTest() - // set the default call arguments - defaultCallArgs = contracts.CallArgs{ - ContractAddr: s.precompile.Address(), - ContractABI: s.precompile.ABI, - PrivKey: s.PrivKey, - } - - defaultLogCheck = testutil.LogCheckArgs{ - ABIEvents: s.precompile.ABI.Events, - } - passCheck = defaultLogCheck.WithExpPass(true) - } - - prepareFunc := func(params *assetstype.Params, method string) contracts.CallArgs { - err := s.App.AssetsKeeper.SetParams(s.Ctx, params) - s.Require().NoError(err) - defaultWithdrawArgs := defaultCallArgs.WithMethodName(method) - return defaultWithdrawArgs.WithArgs( - uint32(clientChainLzID), - assetAddr, - stakerAddr, - opAmount) - } - - beforeEach() - setWithdrawArgs := prepareFunc(¶ms, method) - _, response, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setWithdrawArgs, passCheck) - - // for failed cases we expect it returns bool value instead of error - // this is a workaround because the error returned by precompile can not be caught in EVM - // see https://github.com/ExocoreNetwork/exocore/issues/70 - // TODO: we should figure out root cause and fix this issue to make precompiles work normally - s.Require().NoError(err) - - result, err := setWithdrawArgs.ContractABI.Unpack(method, response.Ret) - s.Require().NoError((err)) - - // solidity: function withdraw(...) returns (bool success, uint256 updatedBalance) - s.Require().Equal(len(result), 2) - - // the first element should be bool value that indicates whether the withdrawal is successful - success, ok := result[0].(bool) - s.Require().True(ok) - s.Require().False(success) - - // the second element represents updatedBalance and should be 0 since success is false and withdrawal has failed - updatedBalance, ok := result[1].(*big.Int) - s.Require().True(ok) - s.Require().Zero(updatedBalance.Cmp(new(big.Int))) -} diff --git a/precompiles/withdraw/withdraw_test.go b/precompiles/withdraw/withdraw_test.go deleted file mode 100644 index e5ecb0d89..000000000 --- a/precompiles/withdraw/withdraw_test.go +++ /dev/null @@ -1,222 +0,0 @@ -package withdraw_test - -import ( - "math/big" - - sdkmath "cosmossdk.io/math" - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/precompiles/withdraw" - assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/evmos/evmos/v14/x/evm/statedb" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" -) - -func (s *WithdrawPrecompileTestSuite) TestIsTransaction() { - testCases := []struct { - name string - method string - isTx bool - }{ - { - withdraw.MethodWithdraw, - s.precompile.Methods[withdraw.MethodWithdraw].Name, - true, - }, - { - "invalid", - "invalid", - false, - }, - } - - for _, tc := range testCases { - s.Run(tc.name, func() { - s.Require().Equal(s.precompile.IsTransaction(tc.method), tc.isTx) - }) - } -} - -func paddingClientChainAddress(input []byte, outputLength int) []byte { - if len(input) < outputLength { - padding := make([]byte, outputLength-len(input)) - return append(input, padding...) - } - return input -} - -func (s *WithdrawPrecompileTestSuite) TestRequiredGas() { - clientChainLzID := 101 - usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), assetstype.GeneralClientChainAddrLength) - withdrawAddr := paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength) - opAmount := big.NewInt(100) - assetAddr := usdtAddress - - testcases := []struct { - name string - malleate func() []byte - expGas uint64 - }{ - { - "success - withdraw transaction with correct gas estimation", - func() []byte { - input, err := s.precompile.Pack( - withdraw.MethodWithdraw, - uint32(clientChainLzID), - assetAddr, - withdrawAddr, - opAmount, - ) - s.Require().NoError(err) - return input - }, - 9680, - }, - } - - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() - - // malleate contract input - input := tc.malleate() - gas := s.precompile.RequiredGas(input) - - s.Require().Equal(gas, tc.expGas) - }) - } -} - -// TestRun tests the precompiled Run method withdraw. -func (s *WithdrawPrecompileTestSuite) TestRunWithdrawThroughClientChain() { - // deposit params for test - exocoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" - usdtAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") - clientChainLzID := 101 - withdrawAmount := big.NewInt(10) - depositAmount := big.NewInt(100) - assetAddr := paddingClientChainAddress(usdtAddress, assetstype.GeneralClientChainAddrLength) - depositAsset := func(staker []byte, depositAmount sdkmath.Int) { - // deposit asset for withdraw test - params := &keeper.DepositParams{ - ClientChainLzID: 101, - Action: assetstype.Deposit, - StakerAddress: staker, - AssetsAddress: usdtAddress, - OpAmount: depositAmount, - } - err := s.App.DepositKeeper.Deposit(s.Ctx, params) - s.Require().NoError(err) - } - - commonMalleate := func() (common.Address, []byte) { - // Prepare the call input for withdraw test - input, err := s.precompile.Pack( - withdraw.MethodWithdraw, - uint32(clientChainLzID), - assetAddr, - paddingClientChainAddress(s.Address.Bytes(), assetstype.GeneralClientChainAddrLength), - withdrawAmount, - ) - s.Require().NoError(err, "failed to pack input") - return s.Address, input - } - successRet, err := s.precompile.Methods[withdraw.MethodWithdraw].Outputs.Pack(true, new(big.Int).Sub(depositAmount, withdrawAmount)) - s.Require().NoError(err) - testcases := []struct { - name string - malleate func() (common.Address, []byte) - readOnly bool - expPass bool - errContains string - returnBytes []byte - }{ - { - name: "pass - withdraw via pre-compiles", - malleate: func() (common.Address, []byte) { - depositModuleParam := &assetstype.Params{ - ExocoreLzAppAddress: s.Address.String(), - ExocoreLzAppEventTopic: exocoreLzAppEventTopic, - } - err := s.App.AssetsKeeper.SetParams(s.Ctx, depositModuleParam) - s.Require().NoError(err) - depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) - return commonMalleate() - }, - returnBytes: successRet, - readOnly: false, - expPass: true, - }, - } - for _, tc := range testcases { - tc := tc - s.Run(tc.name, func() { - // setup basic test suite - s.SetupTest() - - baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) - - // malleate testcase - caller, input := tc.malleate() - - contract := vm.NewPrecompile(vm.AccountRef(caller), s.precompile, big.NewInt(0), uint64(1e6)) - contract.Input = input - - contractAddr := contract.Address() - // Build and sign Ethereum transaction - txArgs := evmtypes.EvmTxArgs{ - ChainID: s.App.EvmKeeper.ChainID(), - Nonce: 0, - To: &contractAddr, - Amount: nil, - GasLimit: 100000, - GasPrice: app.MainnetMinGasPrices.BigInt(), - GasFeeCap: baseFee, - GasTipCap: big.NewInt(1), - Accesses: ðtypes.AccessList{}, - } - msgEthereumTx := evmtypes.NewTx(&txArgs) - - msgEthereumTx.From = s.Address.String() - err := msgEthereumTx.Sign(s.EthSigner, s.Signer) - s.Require().NoError(err, "failed to sign Ethereum message") - - // Instantiate config - proposerAddress := s.Ctx.BlockHeader().ProposerAddress - cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) - s.Require().NoError(err, "failed to instantiate EVM config") - - msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) - s.Require().NoError(err, "failed to instantiate Ethereum message") - - // Create StateDB - s.StateDB = statedb.New(s.Ctx, s.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.Ctx.HeaderHash().Bytes()))) - // Instantiate EVM - evm := s.App.EvmKeeper.NewEVM( - s.Ctx, msg, cfg, nil, s.StateDB, - ) - params := s.App.EvmKeeper.GetParams(s.Ctx) - activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) - err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) - s.Require().NoError(err, "invalid precompiles", activePrecompiles) - evm.WithPrecompiles(precompileMap, activePrecompiles) - - // Run precompiled contract - bz, err := s.precompile.Run(evm, contract, tc.readOnly) - - // Check results - if tc.expPass { - s.Require().NoError(err, "expected no error when running the precompile") - s.Require().Equal(tc.returnBytes, bz, "the return doesn't match the expected result") - } else { - s.Require().Error(err, "expected error to be returned when running the precompile") - s.Require().Nil(bz, "expected returned bytes to be nil") - s.Require().ErrorContains(err, tc.errContains) - } - }) - } -} diff --git a/proto/exocore/deposit/v1/deposit.proto b/proto/exocore/deposit/v1/deposit.proto deleted file mode 100644 index e33809a06..000000000 --- a/proto/exocore/deposit/v1/deposit.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto3"; -package exocore.deposit.v1; - -option go_package = "github.com/ExocoreNetwork/exocore/x/deposit/types"; - -// GenesisState defines the deposit module's genesis state. -message Params {} diff --git a/proto/exocore/deposit/v1/query.proto b/proto/exocore/deposit/v1/query.proto deleted file mode 100644 index 4a02b57c5..000000000 --- a/proto/exocore/deposit/v1/query.proto +++ /dev/null @@ -1,27 +0,0 @@ - -syntax = "proto3"; -package exocore.deposit.v1; - -import "exocore/deposit/v1/deposit.proto"; -import "google/api/annotations.proto"; - -option go_package = "github.com/ExocoreNetwork/exocore/x/deposit/types"; - -// QueryParamsRequest is the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse is the response type for the Query/Params RPC -// method. -message QueryParamsResponse { - // params defines the parameters for this module. - Params params = 1 ; -} - -// Query defines the gRPC querier service. -service Query { - // Params retrieves the deposit module params - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/exocore/deposit/v1/Params"; - } -} - diff --git a/proto/exocore/deposit/v1/tx.proto b/proto/exocore/deposit/v1/tx.proto deleted file mode 100644 index ecb78738f..000000000 --- a/proto/exocore/deposit/v1/tx.proto +++ /dev/null @@ -1,33 +0,0 @@ - -syntax = "proto3"; -package exocore.deposit.v1; - -import "cosmos/msg/v1/msg.proto"; -import "cosmos_proto/cosmos.proto"; -import "exocore/deposit/v1/deposit.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/ExocoreNetwork/exocore/x/deposit/types"; - -// MsgUpdateParams is the Msg/UpdateParams request type for Erc20 parameters. -message MsgUpdateParams { - // todo: temporarily not update configuration through gov module - option (cosmos.msg.v1.signer) = "authority"; - // authority is the address of the governance account. - string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // params defines the x/evm parameters to update. - // NOTE: All parameters must be supplied. - Params params = 2 [(gogoproto.nullable) = false]; -} - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -message MsgUpdateParamsResponse {} - -// Msg defines the deposit Msg service. -service Msg { - option (cosmos.msg.v1.service) = true; - // UpdateParams updates the parameters of the deposit module. - rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); -} diff --git a/proto/exocore/native_token/v1/tx.proto b/proto/exocore/native_token/v1/tx.proto deleted file mode 100644 index 03bd89105..000000000 --- a/proto/exocore/native_token/v1/tx.proto +++ /dev/null @@ -1,63 +0,0 @@ - -syntax = "proto3"; -package exocore.native_token.v1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/ExocoreNetwork/exocore/x/native_token/types"; - -// ValidatorInfo is the information about a validator. -message ValidatorInfo { - // ValidatorStatus is the status of the validator. - enum ValidatorStatus { - // UNSPECIFIED is the default status of a validator. - VALIDATOR_STATUS_UNSPECIFIED = 0 [ (gogoproto.enumvalue_customname) = "ValidatorInfo_UNSPECIFIED" ]; - // ACTIVE is the status of a validator that is currently validating. - VALIDATOR_STATUS_ACTIVE = 1[ (gogoproto.enumvalue_customname) = "ValidatorInfo_ACTIVE" ]; - // INACTIVE is the status of a validator that is not currently validating. - VALIDATOR_STATUS_INACTIVE = 2[ (gogoproto.enumvalue_customname) = "ValidatorInfo_INACTIVE" ]; - // WITHDRAWN is the status of a validator that has withdrawn from the network. - VALIDATOR_STATUS_WITHDRAWN = 3[ (gogoproto.enumvalue_customname) = "ValidatorInfo_WITHDRAWN" ]; - } - // status is the validator's status as an enum. - ValidatorStatus status = 1; - // validator_index is the index of the validator in the set of validators. - uint64 validator_index = 2; - // staked_balance_gwei is the amount of native token staked by the validator in gwei. - string staked_balance_gwei = 3 - [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // most_recent_balance_update_block_number is the block number at which the - // validator's balance was last updated. - uint64 most_recent_balance_update_block_number = 4; -} - -// NativeTokenStakerInfo is the information about a native token staker. -message NativeTokenStakerInfo { - // total_validator_balances is the total amount of native token staked. - string total_validator_balances = 1 - [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // unstaked_value_from_pod is the value unstaked from the pod. - string unstaked_value_from_pod = 2 - [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // pod_address is the pod address. - string pod_address = 3; - // validators_info is the information about the validators, indexed by address. - map validators_info = 4; -} - - - - diff --git a/testutil/keeper/oracle.go b/testutil/keeper/oracle.go index de2877e8f..4e8711221 100644 --- a/testutil/keeper/oracle.go +++ b/testutil/keeper/oracle.go @@ -14,7 +14,8 @@ import ( storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" typesparams "github.com/cosmos/cosmos-sdk/x/params/types" - stakingKeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + + dogfoodkeeper "github.com/ExocoreNetwork/exocore/x/dogfood/keeper" "github.com/stretchr/testify/require" ) @@ -42,7 +43,7 @@ func OracleKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { storeKey, memStoreKey, paramsSubspace, - stakingKeeper.Keeper{}, + dogfoodkeeper.Keeper{}, ) ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) diff --git a/x/assets/keeper/bank.go b/x/assets/keeper/bank.go new file mode 100644 index 000000000..576ceded1 --- /dev/null +++ b/x/assets/keeper/bank.go @@ -0,0 +1,62 @@ +package keeper + +import ( + "fmt" + + errorsmod "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" + + assetstypes "github.com/ExocoreNetwork/exocore/x/assets/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type DepositWithdrawParams struct { + ClientChainLzID uint64 + Action assetstypes.CrossChainOpType + AssetsAddress []byte + StakerAddress []byte + OpAmount sdkmath.Int +} + +// PerformDepositOrWithdraw the assets precompile contract will call this function to update asset state +// when there is a deposit or withdraw. +func (k Keeper) PerformDepositOrWithdraw(ctx sdk.Context, params *DepositWithdrawParams) error { + // check params parameter before executing deposit operation + if params.OpAmount.IsNegative() { + return errorsmod.Wrap(assetstypes.ErrInvalidDepositAmount, fmt.Sprintf("negative deposit amount:%s", params.OpAmount)) + } + stakeID, assetID := assetstypes.GetStakeIDAndAssetID(params.ClientChainLzID, params.StakerAddress, params.AssetsAddress) + assetsInfo, err := k.GetStakingAssetInfo(ctx, assetID) + if err != nil { + return errorsmod.Wrapf(err, "the assetID is:%s", assetID) + } + + actualOpAmount := params.OpAmount + switch params.Action { + case assetstypes.Deposit: + if params.OpAmount.Add(assetsInfo.StakingTotalAmount).GT(assetsInfo.AssetBasicInfo.TotalSupply) { + return errorsmod.Wrapf(assetstypes.ErrInvalidDepositAmount, "deposit amount will make the total staking amount greater than the total supply, amount:%s,totalStakingAmount:%s, totalSupply:%s", params.OpAmount, assetsInfo.StakingTotalAmount, assetsInfo.AssetBasicInfo.TotalSupply) + } + case assetstypes.WithdrawPrincipal: + actualOpAmount = actualOpAmount.Neg() + default: + return errorsmod.Wrapf(assetstypes.ErrInvalidOperationType, "the operation type is: %v", params.Action) + } + + changeAmount := assetstypes.DeltaStakerSingleAsset{ + TotalDepositAmount: actualOpAmount, + WithdrawableAmount: actualOpAmount, + } + // update asset state of the specified staker + err = k.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount) + if err != nil { + return errorsmod.Wrapf(err, "stakeID:%s assetID:%s", stakeID, assetID) + } + + // update total amount of the deposited asset + err = k.UpdateStakingAssetTotalAmount(ctx, assetID, actualOpAmount) + if err != nil { + return errorsmod.Wrapf(err, "assetID:%s", assetID) + } + return nil +} diff --git a/x/assets/keeper/keeper.go b/x/assets/keeper/keeper.go index 228f1b22b..5e95d5b01 100644 --- a/x/assets/keeper/keeper.go +++ b/x/assets/keeper/keeper.go @@ -1,8 +1,6 @@ package keeper import ( - "context" - assetstype "github.com/ExocoreNetwork/exocore/x/assets/types" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" @@ -36,8 +34,8 @@ func (k Keeper) SetOperatorAssetOptedInMiddleWare(sdk.Address, map[string]sdk.Ad panic("implement me") } -// IRestakingAssetsManage interface will be implemented by assets keeper -type IRestakingAssetsManage interface { +// IAssets interface will be implemented by assets keeper +type IAssets interface { SetClientChainInfo(ctx sdk.Context, info *assetstype.ClientChainInfo) (err error) GetClientChainInfoByIndex(ctx sdk.Context, index uint64) (info *assetstype.ClientChainInfo, err error) GetAllClientChainInfo(ctx sdk.Context) (infos map[uint64]*assetstype.ClientChainInfo, err error) @@ -50,16 +48,7 @@ type IRestakingAssetsManage interface { GetStakerSpecifiedAssetInfo(ctx sdk.Context, stakerID string, assetID string) (info *assetstype.StakerAssetInfo, err error) UpdateStakerAssetState(ctx sdk.Context, stakerID string, assetID string, changeAmount assetstype.DeltaStakerSingleAsset) (err error) - GetOperatorAssetInfos(ctx sdk.Context, operatorAddr sdk.Address) (assetsInfo map[string]*assetstype.OperatorAssetInfo, err error) + GetOperatorAssetInfos(ctx sdk.Context, operatorAddr sdk.Address, assetsFilter map[string]interface{}) (assetsInfo map[string]*assetstype.OperatorAssetInfo, err error) GetOperatorSpecifiedAssetInfo(ctx sdk.Context, operatorAddr sdk.Address, assetID string) (info *assetstype.OperatorAssetInfo, err error) UpdateOperatorAssetState(ctx sdk.Context, operatorAddr sdk.Address, assetID string, changeAmount assetstype.DeltaOperatorSingleAsset) (err error) - - // SetStakerExoCoreAddr handle the SetStakerExoCoreAddr txs from msg service - SetStakerExoCoreAddr(ctx context.Context, addr *assetstype.MsgSetExoCoreAddr) (*assetstype.MsgSetExoCoreAddrResponse, error) - GetStakerExoCoreAddr(ctx sdk.Context, stakerID string) (string, error) - - // GetOperatorAssetOptedInMiddleWare :the following three interfaces should be implemented in operator opt-in module - GetOperatorAssetOptedInMiddleWare(operatorAddr sdk.Address, assetID string) (middleWares []sdk.Address, err error) - GetAllOperatorAssetOptedInMiddleWare(operatorAddr sdk.Address) (optedInInfos map[string][]sdk.Address, err error) - SetOperatorAssetOptedInMiddleWare(operatorAddr sdk.Address, setInfo map[string]sdk.Address) (middleWares []sdk.Address, err error) } diff --git a/x/assets/keeper/staker_asset.go b/x/assets/keeper/staker_asset.go index 7f10b1811..dd5474af5 100644 --- a/x/assets/keeper/staker_asset.go +++ b/x/assets/keeper/staker_asset.go @@ -62,7 +62,7 @@ func (k Keeper) UpdateStakerAssetState(ctx sdk.Context, stakerID string, assetID // update all states of the specified restaker asset err = assetstype.UpdateAssetValue(&assetState.TotalDepositAmount, &changeAmount.TotalDepositAmount) if err != nil { - return errorsmod.Wrap(err, "UpdateStakerAssetState TotalDepositAmountOrWantChangeValue error") + return errorsmod.Wrap(err, "UpdateStakerAssetState TotalDepositAmount error") } err = assetstype.UpdateAssetValue(&assetState.WithdrawableAmount, &changeAmount.WithdrawableAmount) if err != nil { diff --git a/x/assets/types/errors.go b/x/assets/types/errors.go index d7670b0d0..d47333137 100644 --- a/x/assets/types/errors.go +++ b/x/assets/types/errors.go @@ -77,7 +77,15 @@ var ( ) ErrInvalidInputParameter = errorsmod.Register( - ModuleName, 15, + ModuleName, 14, "the input parameter is invalid", ) + + ErrInvalidDepositAmount = errorsmod.Register( + ModuleName, 15, + "the deposit amount is invalid") + + ErrInvalidOperationType = errorsmod.Register( + ModuleName, 16, + "the operation type is invalid") ) diff --git a/x/assets/types/general.go b/x/assets/types/general.go index e3e2c3162..56d8c6ca7 100644 --- a/x/assets/types/general.go +++ b/x/assets/types/general.go @@ -27,7 +27,7 @@ const ( const ( Deposit CrossChainOpType = iota - WithdrawPrinciple + WithdrawPrincipal WithDrawReward DelegateTo UndelegateFrom diff --git a/x/assets/types/params.go b/x/assets/types/params.go index 79c242ad2..b6ad7e36c 100644 --- a/x/assets/types/params.go +++ b/x/assets/types/params.go @@ -3,13 +3,9 @@ package types import ( "fmt" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/ethereum/go-ethereum/common" ) -var _ paramtypes.ParamSet = (*Params)(nil) - const ( // DefaultExocoreLzAppAddress is the default address of ExocoreGateway.sol. // When it is automatically deployed within the genesis block (along with @@ -21,17 +17,6 @@ const ( DefaultExocoreLzAppEventTopic = "0x000000000000000000000000000000000000000000000000000000000000000" ) -// Reflection based keys for params subspace. -var ( - KeyExocoreLzAppAddress = []byte("ExocoreLzAppAddress") - KeyExocoreLzAppEventTopic = []byte("ExocoreLzAppEventTopic") -) - -// ParamKeyTable returns a key table with the necessary registered params. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - // NewParams creates a new Params instance. func NewParams( exocoreLzAppAddress string, @@ -51,22 +36,6 @@ func DefaultParams() Params { ) } -// ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair( - KeyExocoreLzAppAddress, - &p.ExocoreLzAppAddress, - ValidateHexAddress, - ), - paramtypes.NewParamSetPair( - KeyExocoreLzAppEventTopic, - &p.ExocoreLzAppEventTopic, - ValidateHexHash, - ), - } -} - // Validate validates the set of params. func (p Params) Validate() error { if err := ValidateHexAddress(p.ExocoreLzAppAddress); err != nil { diff --git a/x/delegation/keeper/delegation_op_test.go b/x/delegation/keeper/delegation_op_test.go index dcdb52f61..d4336777b 100644 --- a/x/delegation/keeper/delegation_op_test.go +++ b/x/delegation/keeper/delegation_op_test.go @@ -3,12 +3,13 @@ package keeper_test import ( "fmt" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" + errorsmod "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" "github.com/ExocoreNetwork/exocore/x/assets/types" delegationtype "github.com/ExocoreNetwork/exocore/x/delegation/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" operatortype "github.com/ExocoreNetwork/exocore/x/operator/types" abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -25,16 +26,16 @@ func (suite *DelegationTestSuite) prepare() { suite.delegationAmount = sdkmath.NewInt(50) } -func (suite *DelegationTestSuite) prepareDeposit() *keeper.DepositParams { +func (suite *DelegationTestSuite) prepareDeposit() *assetskeeper.DepositWithdrawParams { suite.prepare() - depositEvent := &keeper.DepositParams{ + depositEvent := &assetskeeper.DepositWithdrawParams{ ClientChainLzID: suite.clientChainLzID, Action: types.Deposit, StakerAddress: suite.Address[:], OpAmount: suite.depositAmount, } depositEvent.AssetsAddress = suite.assetAddr[:] - err := suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) + err := suite.App.AssetsKeeper.PerformDepositOrWithdraw(suite.Ctx, depositEvent) suite.NoError(err) return depositEvent } diff --git a/x/delegation/keeper/keeper.go b/x/delegation/keeper/keeper.go index cb189d5a7..170d901f2 100644 --- a/x/delegation/keeper/keeper.go +++ b/x/delegation/keeper/keeper.go @@ -7,8 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/core" - ethtypes "github.com/ethereum/go-ethereum/core/types" ) type Keeper struct { @@ -58,11 +56,8 @@ func (k *Keeper) Hooks() delegationtype.DelegationHooks { return k.hooks } -// IDelegation interface will be implemented by deposit keeper +// IDelegation interface will be implemented by delegation keeper type IDelegation interface { - // PostTxProcessing automatically call PostTxProcessing to update delegation state after receiving delegation event tx from layerZero protocol - PostTxProcessing(ctx sdk.Context, msg core.Message, receipt *ethtypes.Receipt) error - // DelegateAssetToOperator handle the DelegateAssetToOperator txs from msg service DelegateAssetToOperator(ctx context.Context, delegation *delegationtype.MsgDelegation) (*delegationtype.DelegationResponse, error) // UndelegateAssetFromOperator handle the UndelegateAssetFromOperator txs from msg service diff --git a/x/delegation/types/errors.go b/x/delegation/types/errors.go index 3d09704c4..ca154dc0c 100644 --- a/x/delegation/types/errors.go +++ b/x/delegation/types/errors.go @@ -83,4 +83,9 @@ var ( ErrInsufficientAssetAmount = errorsmod.Register( ModuleName, 16, "insufficient asset amount") + + ErrInvalidHash = errorsmod.Register( + ModuleName, 17, + "invalid hash", + ) ) diff --git a/x/delegation/types/keys.go b/x/delegation/types/keys.go index 1bd4ab109..39d3340bf 100644 --- a/x/delegation/types/keys.go +++ b/x/delegation/types/keys.go @@ -105,12 +105,18 @@ func ParseUndelegationRecordKey(key []byte) (field *UndelegationKeyFields, err e if err != nil { return nil, err } + hash := stringList[3] + // when a key is originally made, it is created with hash.Hex(), which + // we reverse by using common.HexToHash. to that end, this validation + // is accurate. + if len(common.HexToHash(hash)) != common.HashLength { + return nil, ErrInvalidHash + } return &UndelegationKeyFields{ OperatorAddr: operatorAccAddr.String(), BlockHeight: height, LzNonce: lzNonce, - // TODO: validate the TxHash? - TxHash: stringList[3], + TxHash: hash, }, nil } diff --git a/x/deposit/client/cli/query.go b/x/deposit/client/cli/query.go deleted file mode 100644 index ef7e31170..000000000 --- a/x/deposit/client/cli/query.go +++ /dev/null @@ -1,22 +0,0 @@ -package cli - -import ( - deposittype "github.com/ExocoreNetwork/exocore/x/deposit/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/spf13/cobra" -) - -// GetQueryCmd returns the parent command for all incentives CLI query commands. -func GetQueryCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: deposittype.ModuleName, - Short: "Querying commands for the deposit module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand() - return cmd -} diff --git a/x/deposit/client/cli/tx.go b/x/deposit/client/cli/tx.go deleted file mode 100644 index b536ceb5a..000000000 --- a/x/deposit/client/cli/tx.go +++ /dev/null @@ -1,22 +0,0 @@ -package cli - -import ( - deposittype "github.com/ExocoreNetwork/exocore/x/deposit/types" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" -) - -// NewTxCmd returns a root CLI command handler for deposit commands -func NewTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: deposittype.ModuleName, - Short: "deposit subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - txCmd.AddCommand() - return txCmd -} diff --git a/x/deposit/keeper/cross_chain_tx_process.go b/x/deposit/keeper/cross_chain_tx_process.go deleted file mode 100644 index 7d7957c4f..000000000 --- a/x/deposit/keeper/cross_chain_tx_process.go +++ /dev/null @@ -1,53 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - assetstypes "github.com/ExocoreNetwork/exocore/x/assets/types" - deposittypes "github.com/ExocoreNetwork/exocore/x/deposit/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type DepositParams struct { - ClientChainLzID uint64 - // The action field might need to be removed,it will be used when called from event hook. - Action assetstypes.CrossChainOpType - AssetsAddress []byte - StakerAddress []byte - OpAmount sdkmath.Int -} - -// Deposit the deposit precompile contract will call this function to update asset state when there is a deposit. -func (k Keeper) Deposit(ctx sdk.Context, params *DepositParams) error { - // check params parameter before executing deposit operation - if params.OpAmount.IsNegative() { - return errorsmod.Wrap(deposittypes.ErrInvalidDepositAmount, fmt.Sprintf("negative deposit amount:%s", params.OpAmount)) - } - stakeID, assetID := assetstypes.GetStakeIDAndAssetID(params.ClientChainLzID, params.StakerAddress, params.AssetsAddress) - assetsInfo, err := k.assetsKeeper.GetStakingAssetInfo(ctx, assetID) - if err != nil { - return err - } - if params.OpAmount.Add(assetsInfo.StakingTotalAmount).GT(assetsInfo.AssetBasicInfo.TotalSupply) { - return errorsmod.Wrap(deposittypes.ErrInvalidDepositAmount, fmt.Sprintf("deposit amount will make the total staking amount greater than the total supply, amount:%s,totalStakingAmount:%s, totalSupply:%s", params.OpAmount, assetsInfo.StakingTotalAmount, assetsInfo.AssetBasicInfo.TotalSupply)) - } - - changeAmount := assetstypes.DeltaStakerSingleAsset{ - TotalDepositAmount: params.OpAmount, - WithdrawableAmount: params.OpAmount, - } - // update asset state of the specified staker - err = k.assetsKeeper.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount) - if err != nil { - return err - } - - // update total amount of the deposited asset - err = k.assetsKeeper.UpdateStakingAssetTotalAmount(ctx, assetID, params.OpAmount) - if err != nil { - return err - } - return nil -} diff --git a/x/deposit/keeper/deposit_test.go b/x/deposit/keeper/deposit_test.go deleted file mode 100644 index f37f5a014..000000000 --- a/x/deposit/keeper/deposit_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - assetstypes "github.com/ExocoreNetwork/exocore/x/assets/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" - "github.com/ethereum/go-ethereum/common" -) - -func (suite *DepositTestSuite) TestDeposit() { - usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") - usdcAddress := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") - params := &keeper.DepositParams{ - ClientChainLzID: 101, - Action: assetstypes.Deposit, - StakerAddress: suite.Address[:], - OpAmount: sdkmath.NewInt(100), - } - - // test the case that the deposit asset hasn't registered - params.AssetsAddress = usdcAddress[:] - err := suite.App.DepositKeeper.Deposit(suite.Ctx, params) - suite.ErrorContains(err, assetstypes.ErrNoClientChainAssetKey.Error()) - - assets, err := suite.App.AssetsKeeper.GetAllStakingAssetsInfo(suite.Ctx) - suite.NoError(err) - suite.App.Logger().Info("the assets is:", "assets", assets) - - // test the normal case - params.AssetsAddress = usdtAddress[:] - err = suite.App.DepositKeeper.Deposit(suite.Ctx, params) - suite.NoError(err) - - // check state after deposit - stakerID, assetID := assetstypes.GetStakeIDAndAssetID(params.ClientChainLzID, params.StakerAddress, params.AssetsAddress) - info, err := suite.App.AssetsKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) - suite.NoError(err) - suite.Equal(assetstypes.StakerAssetInfo{ - TotalDepositAmount: params.OpAmount, - WithdrawableAmount: params.OpAmount, - WaitUnbondingAmount: sdkmath.NewInt(0), - }, *info) - - assetInfo, err := suite.App.AssetsKeeper.GetStakingAssetInfo(suite.Ctx, assetID) - suite.NoError(err) - suite.Equal(params.OpAmount.Add(assets[assetID].StakingTotalAmount), assetInfo.StakingTotalAmount) -} diff --git a/x/deposit/keeper/grpc_query.go b/x/deposit/keeper/grpc_query.go deleted file mode 100644 index bf84caad8..000000000 --- a/x/deposit/keeper/grpc_query.go +++ /dev/null @@ -1,19 +0,0 @@ -package keeper - -import ( - "context" - - "github.com/ExocoreNetwork/exocore/x/deposit/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (k Keeper) Params(ctx context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - c := sdk.UnwrapSDKContext(ctx) - params, err := k.GetParams(c) - if err != nil { - return nil, err - } - return &types.QueryParamsResponse{ - Params: params, - }, nil -} diff --git a/x/deposit/keeper/keeper.go b/x/deposit/keeper/keeper.go deleted file mode 100644 index 7caa6de57..000000000 --- a/x/deposit/keeper/keeper.go +++ /dev/null @@ -1,41 +0,0 @@ -package keeper - -import ( - "github.com/ExocoreNetwork/exocore/x/assets/keeper" - deposittype "github.com/ExocoreNetwork/exocore/x/deposit/types" - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.BinaryCodec - - // other keepers - assetsKeeper keeper.Keeper -} - -func NewKeeper( - storeKey storetypes.StoreKey, - cdc codec.BinaryCodec, - assetsKeeper keeper.Keeper, -) Keeper { - return Keeper{ - storeKey: storeKey, - cdc: cdc, - assetsKeeper: assetsKeeper, - } -} - -// IDeposit interface will be implemented by deposit keeper -type IDeposit interface { - // PostTxProcessing automatically call PostTxProcessing to update deposit state after receiving deposit event tx from layerZero protocol - // PostTxProcessing(ctx sdk.Context, msg core.Message, receipt *ethtypes.Receipt) error - - // Deposit internal func for PostTxProcessing - Deposit(ctx sdk.Context, event *DepositParams) error - - SetParams(ctx sdk.Context, params *deposittype.Params) error - GetParams(ctx sdk.Context) (*deposittype.Params, error) -} diff --git a/x/deposit/keeper/msg_server.go b/x/deposit/keeper/msg_server.go deleted file mode 100644 index 3096a82af..000000000 --- a/x/deposit/keeper/msg_server.go +++ /dev/null @@ -1,20 +0,0 @@ -package keeper - -import ( - "context" - - deposittype "github.com/ExocoreNetwork/exocore/x/deposit/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var _ deposittype.MsgServer = &Keeper{} - -// UpdateParams This function should be triggered by the governance in the future -func (k Keeper) UpdateParams(ctx context.Context, params *deposittype.MsgUpdateParams) (*deposittype.MsgUpdateParamsResponse, error) { - c := sdk.UnwrapSDKContext(ctx) - err := k.SetParams(c, ¶ms.Params) - if err != nil { - return nil, err - } - return nil, nil -} diff --git a/x/deposit/keeper/params.go b/x/deposit/keeper/params.go deleted file mode 100644 index 05aadc232..000000000 --- a/x/deposit/keeper/params.go +++ /dev/null @@ -1,30 +0,0 @@ -package keeper - -import ( - "github.com/ExocoreNetwork/exocore/x/deposit/types" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// SetParams The function related to module parameter should be deleted -// if no parameters need to be stored in the future. -func (k Keeper) SetParams(ctx sdk.Context, params *types.Params) error { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixParams) - bz := k.cdc.MustMarshal(params) - store.Set(types.ParamsKey, bz) - return nil -} - -func (k Keeper) GetParams(ctx sdk.Context) (*types.Params, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixParams) - ifExist := store.Has(types.ParamsKey) - if !ifExist { - return nil, types.ErrNoParamsKey - } - - value := store.Get(types.ParamsKey) - - ret := &types.Params{} - k.cdc.MustUnmarshal(value, ret) - return ret, nil -} diff --git a/x/deposit/keeper/params_test.go b/x/deposit/keeper/params_test.go deleted file mode 100644 index 3d4560496..000000000 --- a/x/deposit/keeper/params_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package keeper_test - -import ( - deposittype "github.com/ExocoreNetwork/exocore/x/deposit/types" -) - -func (suite *DepositTestSuite) TestParams() { - params := &deposittype.Params{} - err := suite.App.DepositKeeper.SetParams(suite.Ctx, params) - suite.NoError(err) - - getParams, err := suite.App.DepositKeeper.GetParams(suite.Ctx) - suite.NoError(err) - suite.Equal(*params, *getParams) -} diff --git a/x/deposit/keeper/setup_test.go b/x/deposit/keeper/setup_test.go deleted file mode 100644 index cc891fe42..000000000 --- a/x/deposit/keeper/setup_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/ExocoreNetwork/exocore/testutil" - - "github.com/stretchr/testify/suite" -) - -type DepositTestSuite struct { - testutil.BaseTestSuite -} - -var s *DepositTestSuite - -func TestKeeperTestSuite(t *testing.T) { - s = new(DepositTestSuite) - suite.Run(t, s) -} - -func (suite *DepositTestSuite) SetupTest() { - suite.DoSetupTest() -} diff --git a/x/deposit/module.go b/x/deposit/module.go deleted file mode 100644 index 177725127..000000000 --- a/x/deposit/module.go +++ /dev/null @@ -1,89 +0,0 @@ -package deposit - -import ( - "context" - - "github.com/ExocoreNetwork/exocore/x/deposit/client/cli" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" - "github.com/ExocoreNetwork/exocore/x/deposit/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" -) - -// type check to ensure the interface is properly implemented -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} -) - -type AppModuleBasic struct{} - -func (b AppModuleBasic) Name() string { - return types.ModuleName -} - -func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(amino) -} - -func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil { - panic(err) - } -} - -func (b AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.NewTxCmd() -} - -func (b AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -type AppModule struct { - AppModuleBasic - keeper keeper.Keeper -} - -func NewAppModule(_ codec.Codec, keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// IsOnePerModuleType implements the depinject.OnePerModuleType interface. -func (am AppModule) IsOnePerModuleType() {} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), &am.keeper) - types.RegisterQueryServer(cfg.QueryServer(), am.keeper) -} - -// GenerateGenesisState creates a randomized GenState of the inflation module. -func (am AppModule) GenerateGenesisState(_ *module.SimulationState) { -} - -// RegisterStoreDecoder registers a decoder for inflation module's types. -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { -} - -// WeightedOperations doesn't return any inflation module operation. -func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { - return []simtypes.WeightedOperation{} -} diff --git a/x/deposit/types/codec.go b/x/deposit/types/codec.go deleted file mode 100644 index b1789ef2a..000000000 --- a/x/deposit/types/codec.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" -) - -var ( - amino = codec.NewLegacyAmino() - - // ModuleCdc references the global module codec. Note, the codec should - // ONLY be used in certain instances of tests and for JSON encoding. - // - // The actual codec used for serialization should be provided to modules and - // defined at the application level. - ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) - - // AminoCdc is a amino codec created to support amino JSON compatible msgs. - AminoCdc = codec.NewAminoCodec(amino) -) - -const ( - // Amino names - updateParamsName = "exocore/MsgUpdateParams" -) - -// NOTE: This is required for the GetSignBytes function -func init() { - RegisterLegacyAminoCodec(amino) - amino.Seal() -} - -// RegisterInterfaces register implementations -func RegisterInterfaces(registry codectypes.InterfaceRegistry) { - registry.RegisterImplementations( - (*sdk.Msg)(nil), - &MsgUpdateParams{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -// RegisterLegacyAminoCodec registers the necessary x/revenue interfaces and -// concrete types on the provided LegacyAmino codec. These types are used for -// Amino JSON serialization and EIP-712 compatibility. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgUpdateParams{}, updateParamsName, nil) -} diff --git a/x/deposit/types/deposit.pb.go b/x/deposit/types/deposit.pb.go deleted file mode 100644 index 67be1c029..000000000 --- a/x/deposit/types/deposit.pb.go +++ /dev/null @@ -1,263 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: exocore/deposit/v1/deposit.proto - -package types - -import ( - fmt "fmt" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the deposit module's genesis state. -type Params struct { -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_bb743e1548b62476, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "exocore.deposit.v1.Params") -} - -func init() { proto.RegisterFile("exocore/deposit/v1/deposit.proto", fileDescriptor_bb743e1548b62476) } - -var fileDescriptor_bb743e1548b62476 = []byte{ - // 138 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xad, 0xc8, 0x4f, - 0xce, 0x2f, 0x4a, 0xd5, 0x4f, 0x49, 0x2d, 0xc8, 0x2f, 0xce, 0x2c, 0xd1, 0x2f, 0x33, 0x84, 0x31, - 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x84, 0xa0, 0x2a, 0xf4, 0x60, 0xc2, 0x65, 0x86, 0x4a, - 0x1c, 0x5c, 0x6c, 0x01, 0x89, 0x45, 0x89, 0xb9, 0xc5, 0x4e, 0xde, 0x27, 0x1e, 0xc9, 0x31, 0x5e, - 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, - 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0x65, 0x98, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, - 0xab, 0xef, 0x0a, 0x31, 0xc2, 0x2f, 0xb5, 0xa4, 0x3c, 0xbf, 0x28, 0x5b, 0x1f, 0x66, 0x67, 0x05, - 0xdc, 0xd6, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0xb0, 0x8d, 0xc6, 0x80, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x16, 0x0b, 0x5f, 0x01, 0x95, 0x00, 0x00, 0x00, -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintDeposit(dAtA []byte, offset int, v uint64) int { - offset -= sovDeposit(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovDeposit(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozDeposit(x uint64) (n int) { - return sovDeposit(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDeposit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipDeposit(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDeposit - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipDeposit(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDeposit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDeposit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDeposit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthDeposit - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupDeposit - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthDeposit - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthDeposit = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowDeposit = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupDeposit = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/deposit/types/errors.go b/x/deposit/types/errors.go deleted file mode 100644 index 7f1c31e29..000000000 --- a/x/deposit/types/errors.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" -) - -// errors -var ( - ErrNoParamsKey = errorsmod.Register(ModuleName, 1, "there is no stored key for deposit module params") - ErrInvalidDepositAmount = errorsmod.Register(ModuleName, 2, "the deposit amount is invalid") -) diff --git a/x/deposit/types/expected_keepers.go b/x/deposit/types/expected_keepers.go deleted file mode 100644 index ab1254f4c..000000000 --- a/x/deposit/types/expected_keepers.go +++ /dev/null @@ -1 +0,0 @@ -package types diff --git a/x/deposit/types/keys.go b/x/deposit/types/keys.go deleted file mode 100644 index 97dde7be4..000000000 --- a/x/deposit/types/keys.go +++ /dev/null @@ -1,34 +0,0 @@ -package types - -import ( - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/ethereum/go-ethereum/common" -) - -// constants -const ( - // ModuleName module name - ModuleName = "deposit" - - // StoreKey to be used when creating the KVStore - StoreKey = ModuleName - - // RouterKey to be used for message routing - RouterKey = ModuleName -) - -// ModuleAddress is the native module address for EVM -var ModuleAddress common.Address - -func init() { - ModuleAddress = common.BytesToAddress(authtypes.NewModuleAddress(ModuleName).Bytes()) -} - -const ( - prefixParams = iota + 1 -) - -var ( - KeyPrefixParams = []byte{prefixParams} - ParamsKey = []byte("Params") -) diff --git a/x/deposit/types/msg.go b/x/deposit/types/msg.go deleted file mode 100644 index bc29c4af4..000000000 --- a/x/deposit/types/msg.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var _ sdk.Msg = &MsgUpdateParams{} - -// GetSigners returns the expected signers for a MsgUpdateParams message. -func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { - addr := sdk.MustAccAddressFromBech32(m.Authority) - return []sdk.AccAddress{addr} -} - -// ValidateBasic does a sanity check of the provided data -func (m *MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { - return errorsmod.Wrap(err, "invalid from address") - } - return nil -} - -// GetSignBytes implements the LegacyMsg interface. -func (m *MsgUpdateParams) GetSignBytes() []byte { - return nil -} diff --git a/x/deposit/types/query.pb.go b/x/deposit/types/query.pb.go deleted file mode 100644 index becbd9a79..000000000 --- a/x/deposit/types/query.pb.go +++ /dev/null @@ -1,541 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: exocore/deposit/v1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest is the request type for the Query/Params RPC method. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_715f16e6b5833923, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse is the response type for the Query/Params RPC -// method. -type QueryParamsResponse struct { - // params defines the parameters for this module. - Params *Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params,omitempty"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_715f16e6b5833923, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() *Params { - if m != nil { - return m.Params - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "exocore.deposit.v1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "exocore.deposit.v1.QueryParamsResponse") -} - -func init() { proto.RegisterFile("exocore/deposit/v1/query.proto", fileDescriptor_715f16e6b5833923) } - -var fileDescriptor_715f16e6b5833923 = []byte{ - // 263 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xad, 0xc8, 0x4f, - 0xce, 0x2f, 0x4a, 0xd5, 0x4f, 0x49, 0x2d, 0xc8, 0x2f, 0xce, 0x2c, 0xd1, 0x2f, 0x33, 0xd4, 0x2f, - 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x82, 0xca, 0xeb, 0x41, - 0xe5, 0xf5, 0xca, 0x0c, 0xa5, 0x14, 0xb0, 0xe8, 0x81, 0x49, 0x83, 0x75, 0x49, 0xc9, 0xa4, 0xe7, - 0xe7, 0xa7, 0xe7, 0xa4, 0xea, 0x27, 0x16, 0x64, 0xea, 0x27, 0xe6, 0xe5, 0xe5, 0x97, 0x24, 0x96, - 0x64, 0xe6, 0xe7, 0x15, 0x43, 0x64, 0x95, 0x44, 0xb8, 0x84, 0x02, 0x41, 0x56, 0x04, 0x24, 0x16, - 0x25, 0xe6, 0x16, 0x07, 0xa5, 0x16, 0x96, 0xa6, 0x16, 0x97, 0x28, 0x79, 0x72, 0x09, 0xa3, 0x88, - 0x16, 0x17, 0xe4, 0xe7, 0x15, 0xa7, 0x0a, 0x19, 0x71, 0xb1, 0x15, 0x80, 0x45, 0x24, 0x18, 0x15, - 0x18, 0x35, 0xb8, 0x8d, 0xa4, 0xf4, 0x30, 0x5d, 0xa4, 0x07, 0xd5, 0x03, 0x55, 0x69, 0xd4, 0xc6, - 0xc8, 0xc5, 0x0a, 0x36, 0x4b, 0xa8, 0x96, 0x8b, 0x0d, 0x22, 0x27, 0xa4, 0x86, 0x4d, 0x1f, 0xa6, - 0x33, 0xa4, 0xd4, 0x09, 0xaa, 0x83, 0x38, 0x4c, 0x49, 0xa9, 0xe9, 0xf2, 0x93, 0xc9, 0x4c, 0x32, - 0x42, 0x52, 0xfa, 0x58, 0x82, 0x03, 0xa2, 0xd6, 0xc9, 0xfb, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, - 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, - 0x8f, 0xe5, 0x18, 0xa2, 0x0c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, - 0x5d, 0x21, 0xfa, 0xfd, 0x52, 0x4b, 0xca, 0xf3, 0x8b, 0xb2, 0xe1, 0xc6, 0x55, 0xc0, 0x0d, 0x2c, - 0xa9, 0x2c, 0x48, 0x2d, 0x4e, 0x62, 0x03, 0x87, 0x9e, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x59, - 0x1e, 0x95, 0x6f, 0xb3, 0x01, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params retrieves the deposit module params - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/exocore.deposit.v1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params retrieves the deposit module params - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/exocore.deposit.v1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "exocore.deposit.v1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "exocore/deposit/v1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Params != nil { - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Params != nil { - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Params == nil { - m.Params = &Params{} - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/deposit/types/query.pb.gw.go b/x/deposit/types/query.pb.gw.go deleted file mode 100644 index 4e143091e..000000000 --- a/x/deposit/types/query.pb.gw.go +++ /dev/null @@ -1,153 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: exocore/deposit/v1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"exocore", "deposit", "v1", "Params"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage -) diff --git a/x/deposit/types/tx.pb.go b/x/deposit/types/tx.pb.go deleted file mode 100644 index 43ba9bf7b..000000000 --- a/x/deposit/types/tx.pb.go +++ /dev/null @@ -1,593 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: exocore/deposit/v1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/cosmos-sdk/types/msgservice" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgUpdateParams is the Msg/UpdateParams request type for Erc20 parameters. -type MsgUpdateParams struct { - // authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // params defines the x/evm parameters to update. - // NOTE: All parameters must be supplied. - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` -} - -func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } -func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParams) ProtoMessage() {} -func (*MsgUpdateParams) Descriptor() ([]byte, []int) { - return fileDescriptor_d4939a0226905392, []int{0} -} -func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParams.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgUpdateParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParams.Merge(m, src) -} -func (m *MsgUpdateParams) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParams) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo - -func (m *MsgUpdateParams) GetAuthority() string { - if m != nil { - return m.Authority - } - return "" -} - -func (m *MsgUpdateParams) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -type MsgUpdateParamsResponse struct { -} - -func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } -func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParamsResponse) ProtoMessage() {} -func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_d4939a0226905392, []int{1} -} -func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) -} -func (m *MsgUpdateParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgUpdateParams)(nil), "exocore.deposit.v1.MsgUpdateParams") - proto.RegisterType((*MsgUpdateParamsResponse)(nil), "exocore.deposit.v1.MsgUpdateParamsResponse") -} - -func init() { proto.RegisterFile("exocore/deposit/v1/tx.proto", fileDescriptor_d4939a0226905392) } - -var fileDescriptor_d4939a0226905392 = []byte{ - // 329 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xad, 0xc8, 0x4f, - 0xce, 0x2f, 0x4a, 0xd5, 0x4f, 0x49, 0x2d, 0xc8, 0x2f, 0xce, 0x2c, 0xd1, 0x2f, 0x33, 0xd4, 0x2f, - 0xa9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x82, 0x4a, 0xea, 0x41, 0x25, 0xf5, 0xca, - 0x0c, 0xa5, 0xc4, 0x93, 0xf3, 0x8b, 0x73, 0xf3, 0x8b, 0xf5, 0x73, 0x8b, 0xd3, 0x41, 0x6a, 0x73, - 0x8b, 0xd3, 0x21, 0x8a, 0xa5, 0x24, 0x21, 0x12, 0xf1, 0x60, 0x9e, 0x3e, 0x84, 0x03, 0x95, 0x52, - 0xc0, 0x62, 0x09, 0xcc, 0x48, 0x88, 0x0a, 0x91, 0xf4, 0xfc, 0xf4, 0x7c, 0x88, 0x4e, 0x10, 0x0b, - 0x22, 0xaa, 0x34, 0x99, 0x91, 0x8b, 0xdf, 0xb7, 0x38, 0x3d, 0xb4, 0x20, 0x25, 0xb1, 0x24, 0x35, - 0x20, 0xb1, 0x28, 0x31, 0xb7, 0x58, 0xc8, 0x8c, 0x8b, 0x33, 0xb1, 0xb4, 0x24, 0x23, 0xbf, 0x28, - 0xb3, 0xa4, 0x52, 0x82, 0x51, 0x81, 0x51, 0x83, 0xd3, 0x49, 0xe2, 0xd2, 0x16, 0x5d, 0x11, 0xa8, - 0x85, 0x8e, 0x29, 0x29, 0x45, 0xa9, 0xc5, 0xc5, 0xc1, 0x25, 0x45, 0x99, 0x79, 0xe9, 0x41, 0x08, - 0xa5, 0x42, 0x16, 0x5c, 0x6c, 0x05, 0x60, 0x13, 0x24, 0x98, 0x14, 0x18, 0x35, 0xb8, 0x8d, 0xa4, - 0xf4, 0x30, 0x3d, 0xa7, 0x07, 0xb1, 0xc3, 0x89, 0xe5, 0xc4, 0x3d, 0x79, 0x86, 0x20, 0xa8, 0x7a, - 0x2b, 0xbe, 0xa6, 0xe7, 0x1b, 0xb4, 0x10, 0x26, 0x29, 0x49, 0x72, 0x89, 0xa3, 0x39, 0x2a, 0x28, - 0xb5, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0xd5, 0x28, 0x8f, 0x8b, 0xd9, 0xb7, 0x38, 0x5d, 0x28, 0x81, - 0x8b, 0x07, 0xc5, 0xcd, 0xca, 0xd8, 0xec, 0x42, 0x33, 0x43, 0x4a, 0x9b, 0x08, 0x45, 0x30, 0x8b, - 0xa4, 0x58, 0x1b, 0x9e, 0x6f, 0xd0, 0x62, 0x74, 0xf2, 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, - 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, - 0x63, 0x39, 0x86, 0x28, 0xc3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, - 0x57, 0x88, 0xb9, 0x7e, 0xa9, 0x25, 0xe5, 0xf9, 0x45, 0xd9, 0xfa, 0xb0, 0xc8, 0xa8, 0x80, 0x47, - 0x47, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0x38, 0xd0, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, - 0xff, 0x1b, 0x3a, 0x48, 0x09, 0x13, 0x02, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // UpdateParams updates the parameters of the deposit module. - UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { - out := new(MsgUpdateParamsResponse) - err := c.cc.Invoke(ctx, "/exocore.deposit.v1.Msg/UpdateParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // UpdateParams updates the parameters of the deposit module. - UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/exocore.deposit.v1.Msg/UpdateParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "exocore.deposit.v1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UpdateParams", - Handler: _Msg_UpdateParams_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "exocore/deposit/v1/tx.proto", -} - -func (m *MsgUpdateParams) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgUpdateParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Params.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgUpdateParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/dogfood/keeper/abci.go b/x/dogfood/keeper/abci.go index a2c8b7295..ca2e3506f 100644 --- a/x/dogfood/keeper/abci.go +++ b/x/dogfood/keeper/abci.go @@ -90,7 +90,7 @@ func (k Keeper) EndBlock(ctx sdk.Context) []abci.ValidatorUpdate { res := make([]abci.ValidatorUpdate, 0, maxVals*2) for i := range operators { // #nosec G701 // ok on 64-bit systems. - if i > int(maxVals) { + if i >= int(maxVals) { // we have reached the maximum number of validators, amongst all the validators. // even if there are intersections with the previous validator set, this will // only be reached if we exceed the threshold. diff --git a/x/evm/keeper/precompiles.go b/x/evm/keeper/precompiles.go index 61b4bc069..af5a13d48 100644 --- a/x/evm/keeper/precompiles.go +++ b/x/evm/keeper/precompiles.go @@ -3,23 +3,19 @@ package keeper import ( "fmt" + assetsprecompile "github.com/ExocoreNetwork/exocore/precompiles/assets" avsManagerPrecompile "github.com/ExocoreNetwork/exocore/precompiles/avs" taskPrecompile "github.com/ExocoreNetwork/exocore/precompiles/avsTask" blsPrecompile "github.com/ExocoreNetwork/exocore/precompiles/bls" - clientchainsprecompile "github.com/ExocoreNetwork/exocore/precompiles/clientchains" delegationprecompile "github.com/ExocoreNetwork/exocore/precompiles/delegation" - depositprecompile "github.com/ExocoreNetwork/exocore/precompiles/deposit" rewardPrecompile "github.com/ExocoreNetwork/exocore/precompiles/reward" slashPrecompile "github.com/ExocoreNetwork/exocore/precompiles/slash" - withdrawPrecompile "github.com/ExocoreNetwork/exocore/precompiles/withdraw" stakingStateKeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" avsManagerKeeper "github.com/ExocoreNetwork/exocore/x/avs/keeper" taskKeeper "github.com/ExocoreNetwork/exocore/x/avstask/keeper" delegationKeeper "github.com/ExocoreNetwork/exocore/x/delegation/keeper" - depositKeeper "github.com/ExocoreNetwork/exocore/x/deposit/keeper" rewardKeeper "github.com/ExocoreNetwork/exocore/x/reward/keeper" exoslashKeeper "github.com/ExocoreNetwork/exocore/x/slash/keeper" - withdrawKeeper "github.com/ExocoreNetwork/exocore/x/withdraw/keeper" authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" channelkeeper "github.com/cosmos/ibc-go/v7/modules/core/04-channel/keeper" "github.com/ethereum/go-ethereum/common" @@ -39,10 +35,8 @@ func AvailablePrecompiles( authzKeeper authzkeeper.Keeper, transferKeeper transferkeeper.Keeper, channelKeeper channelkeeper.Keeper, - depositKeeper depositKeeper.Keeper, delegationKeeper delegationKeeper.Keeper, - stakingStateKeeper stakingStateKeeper.Keeper, - withdrawKeeper withdrawKeeper.Keeper, + assetskeeper stakingStateKeeper.Keeper, slashKeeper exoslashKeeper.Keeper, rewardKeeper rewardKeeper.Keeper, avsManagerKeeper avsManagerKeeper.Keeper, @@ -60,41 +54,24 @@ func AvailablePrecompiles( panic(fmt.Errorf("failed to load ICS20 precompile: %w", err)) } - // add exoCore chain preCompiles - clientChainsPrecompile, err := clientchainsprecompile.NewPrecompile( - stakingStateKeeper, - authzKeeper, - ) - if err != nil { - panic(fmt.Errorf("failed to load client chains precompile: %w", err)) - } - - depositPrecompile, err := depositprecompile.NewPrecompile( - stakingStateKeeper, - depositKeeper, + assetsPrecompile, err := assetsprecompile.NewPrecompile( + assetskeeper, authzKeeper, ) if err != nil { panic(fmt.Errorf("failed to load deposit precompile: %w", err)) } delegationPrecompile, err := delegationprecompile.NewPrecompile( - stakingStateKeeper, + assetskeeper, delegationKeeper, authzKeeper, ) if err != nil { panic(fmt.Errorf("failed to load delegation precompile: %w", err)) } - withdrawPrecompile, err := withdrawPrecompile.NewPrecompile( - stakingStateKeeper, - withdrawKeeper, - authzKeeper, - ) - if err != nil { - panic(fmt.Errorf("failed to load withdraw precompile: %w", err)) - } + slashPrecompile, err := slashPrecompile.NewPrecompile( - stakingStateKeeper, + assetskeeper, slashKeeper, authzKeeper, ) @@ -102,7 +79,7 @@ func AvailablePrecompiles( panic(fmt.Errorf("failed to load slash precompile: %w", err)) } rewardPrecompile, err := rewardPrecompile.NewPrecompile( - stakingStateKeeper, + assetskeeper, rewardKeeper, authzKeeper, ) @@ -123,9 +100,7 @@ func AvailablePrecompiles( } precompiles[slashPrecompile.Address()] = slashPrecompile precompiles[rewardPrecompile.Address()] = rewardPrecompile - precompiles[withdrawPrecompile.Address()] = withdrawPrecompile - precompiles[clientChainsPrecompile.Address()] = clientChainsPrecompile - precompiles[depositPrecompile.Address()] = depositPrecompile + precompiles[assetsPrecompile.Address()] = assetsPrecompile precompiles[delegationPrecompile.Address()] = delegationPrecompile precompiles[avsManagerPrecompile.Address()] = avsManagerPrecompile precompiles[taskPrecompile.Address()] = taskPrecompile diff --git a/x/evm/types/params.go b/x/evm/types/params.go index d599882a1..41a9ce820 100644 --- a/x/evm/types/params.go +++ b/x/evm/types/params.go @@ -10,13 +10,14 @@ var ( // DefaultEVMDenom defines the default EVM denomination on Exocore DefaultEVMDenom = utils.BaseDenom ExocoreAvailableEVMExtensions = []string{ - "0x0000000000000000000000000000000000000801", // client chains precompile + // 0x0000000000000000000000000000000000000801 client chains precompile has been merged to assets. "0x0000000000000000000000000000000000000802", // ICS20 transfer precompile - "0x0000000000000000000000000000000000000804", // deposit precompile + "0x0000000000000000000000000000000000000804", // assets precompile "0x0000000000000000000000000000000000000805", // delegation precompile "0x0000000000000000000000000000000000000806", // reward precompile "0x0000000000000000000000000000000000000807", // slash precompile - "0x0000000000000000000000000000000000000808", // withdraw precompile + // 0x0000000000000000000000000000000000000808 withdraw precompile has been merged to assets. + // the function has been merged to the assets precompile "0x0000000000000000000000000000000000000809", // bls precompile "0x0000000000000000000000000000000000000901", // avsTask precompile "0x0000000000000000000000000000000000000902", // avs precompile diff --git a/x/native_token/keeper/keeper.go b/x/native_token/keeper/keeper.go deleted file mode 100644 index d22a73952..000000000 --- a/x/native_token/keeper/keeper.go +++ /dev/null @@ -1,3 +0,0 @@ -package keeper - -type Keeper struct{} diff --git a/x/native_token/module.go b/x/native_token/module.go deleted file mode 100644 index 8dff94c29..000000000 --- a/x/native_token/module.go +++ /dev/null @@ -1,93 +0,0 @@ -// nolint: all // this package is not implemented yet. -package native_token - -import ( - "context" - - "cosmossdk.io/math" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" - "github.com/ExocoreNetwork/exocore/x/native_token/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/ethereum/go-ethereum/core" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" -) - -const consensusVersion = 0 - -// type check to ensure the interface is properly implemented -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} -) - -type AppModuleBasic struct{} - -func (b AppModuleBasic) Name() string { - return types.ModuleName -} - -func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { - // TODO implement me - panic("implement me") -} - -func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - // TODO implement me - panic("implement me") -} - -func (b AppModuleBasic) RegisterGRPCGatewayRoutes(context client.Context, mux *runtime.ServeMux) { - // TODO implement me - panic("implement me") -} - -func (b AppModuleBasic) GetTxCmd() *cobra.Command { - // TODO implement me - panic("implement me") -} - -func (b AppModuleBasic) GetQueryCmd() *cobra.Command { - // TODO implement me - panic("implement me") -} - -type AppModule struct { - AppModuleBasic - keeper *keeper.Keeper -} - -func (am AppModule) GenerateGenesisState(input *module.SimulationState) { - // TODO implement me - panic("implement me") -} - -func (am AppModule) RegisterStoreDecoder(registry sdk.StoreDecoderRegistry) { - // TODO implement me - panic("implement me") -} - -func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - // TODO implement me - panic("implement me") -} - -// IDeposit interface will be implemented by deposit keeper -type IDeposit interface { - // PostTxProcessing automatically call PostTxProcessing to update deposit state after receiving deposit event tx from layerZero protocol - PostTxProcessing(ctx sdk.Context, msg core.Message, receipt *ethtypes.Receipt) error - - // SetReStakerExoCoreAddr handle the SetReStakerExoCoreAddr txs from msg service - SetReStakerExoCoreAddr(ctx context.Context, restakerID string) (err error) - GetReStakerExoCoreAddr(restakerID string) (addr sdk.Address, err error) - - // Deposit internal func for PostTxProcessing - Deposit(restakerID string, assetsInfo map[string]math.Uint) error -} diff --git a/x/native_token/types/expected_keepers.go b/x/native_token/types/expected_keepers.go deleted file mode 100644 index ab1254f4c..000000000 --- a/x/native_token/types/expected_keepers.go +++ /dev/null @@ -1 +0,0 @@ -package types diff --git a/x/native_token/types/keys.go b/x/native_token/types/keys.go deleted file mode 100644 index 1a74b9734..000000000 --- a/x/native_token/types/keys.go +++ /dev/null @@ -1,33 +0,0 @@ -package types - -import ( - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/ethereum/go-ethereum/common" -) - -// constants -const ( - // module name - ModuleName = "native_token" - - // StoreKey to be used when creating the KVStore - StoreKey = ModuleName - - // RouterKey to be used for message routing - RouterKey = ModuleName -) - -// ModuleAddress is the native module address for EVM -var ModuleAddress common.Address - -func init() { - ModuleAddress = common.BytesToAddress(authtypes.NewModuleAddress(ModuleName).Bytes()) -} - -const ( - prefixReStakerExocoreAddr = iota + 1 -) - -// KeyPrefixReStakerExoCoreAddr restakerID = clientChainAddr+'_'+ExoCoreChainIndex -// KeyPrefixReStakerExoCoreAddr key-value: restakerID->exoCoreAddr -var KeyPrefixReStakerExoCoreAddr = []byte{prefixReStakerExocoreAddr} diff --git a/x/native_token/types/tx.pb.go b/x/native_token/types/tx.pb.go deleted file mode 100644 index e373d9728..000000000 --- a/x/native_token/types/tx.pb.go +++ /dev/null @@ -1,939 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: exocore/native_token/v1/tx.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// ValidatorStatus is the status of the validator. -type ValidatorInfo_ValidatorStatus int32 - -const ( - // UNSPECIFIED is the default status of a validator. - ValidatorInfo_ValidatorInfo_UNSPECIFIED ValidatorInfo_ValidatorStatus = 0 - // ACTIVE is the status of a validator that is currently validating. - ValidatorInfo_ValidatorInfo_ACTIVE ValidatorInfo_ValidatorStatus = 1 - // INACTIVE is the status of a validator that is not currently validating. - ValidatorInfo_ValidatorInfo_INACTIVE ValidatorInfo_ValidatorStatus = 2 - // WITHDRAWN is the status of a validator that has withdrawn from the network. - ValidatorInfo_ValidatorInfo_WITHDRAWN ValidatorInfo_ValidatorStatus = 3 -) - -var ValidatorInfo_ValidatorStatus_name = map[int32]string{ - 0: "VALIDATOR_STATUS_UNSPECIFIED", - 1: "VALIDATOR_STATUS_ACTIVE", - 2: "VALIDATOR_STATUS_INACTIVE", - 3: "VALIDATOR_STATUS_WITHDRAWN", -} - -var ValidatorInfo_ValidatorStatus_value = map[string]int32{ - "VALIDATOR_STATUS_UNSPECIFIED": 0, - "VALIDATOR_STATUS_ACTIVE": 1, - "VALIDATOR_STATUS_INACTIVE": 2, - "VALIDATOR_STATUS_WITHDRAWN": 3, -} - -func (x ValidatorInfo_ValidatorStatus) String() string { - return proto.EnumName(ValidatorInfo_ValidatorStatus_name, int32(x)) -} - -func (ValidatorInfo_ValidatorStatus) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_769c53c072051eb9, []int{0, 0} -} - -// ValidatorInfo is the information about a validator. -type ValidatorInfo struct { - // status is the validator's status as an enum. - Status ValidatorInfo_ValidatorStatus `protobuf:"varint,1,opt,name=status,proto3,enum=exocore.native_token.v1.ValidatorInfo_ValidatorStatus" json:"status,omitempty"` - // validator_index is the index of the validator in the set of validators. - ValidatorIndex uint64 `protobuf:"varint,2,opt,name=validator_index,json=validatorIndex,proto3" json:"validator_index,omitempty"` - // staked_balance_gwei is the amount of native token staked by the validator in gwei. - StakedBalanceGwei github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=staked_balance_gwei,json=stakedBalanceGwei,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"staked_balance_gwei"` - // most_recent_balance_update_block_number is the block number at which the - // validator's balance was last updated. - MostRecentBalanceUpdateBlockNumber uint64 `protobuf:"varint,4,opt,name=most_recent_balance_update_block_number,json=mostRecentBalanceUpdateBlockNumber,proto3" json:"most_recent_balance_update_block_number,omitempty"` -} - -func (m *ValidatorInfo) Reset() { *m = ValidatorInfo{} } -func (m *ValidatorInfo) String() string { return proto.CompactTextString(m) } -func (*ValidatorInfo) ProtoMessage() {} -func (*ValidatorInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_769c53c072051eb9, []int{0} -} -func (m *ValidatorInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorInfo.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ValidatorInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorInfo.Merge(m, src) -} -func (m *ValidatorInfo) XXX_Size() int { - return m.Size() -} -func (m *ValidatorInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorInfo proto.InternalMessageInfo - -func (m *ValidatorInfo) GetStatus() ValidatorInfo_ValidatorStatus { - if m != nil { - return m.Status - } - return ValidatorInfo_ValidatorInfo_UNSPECIFIED -} - -func (m *ValidatorInfo) GetValidatorIndex() uint64 { - if m != nil { - return m.ValidatorIndex - } - return 0 -} - -func (m *ValidatorInfo) GetMostRecentBalanceUpdateBlockNumber() uint64 { - if m != nil { - return m.MostRecentBalanceUpdateBlockNumber - } - return 0 -} - -// NativeTokenStakerInfo is the information about a native token staker. -type NativeTokenStakerInfo struct { - // total_validator_balances is the total amount of native token staked. - TotalValidatorBalances github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,1,opt,name=total_validator_balances,json=totalValidatorBalances,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_validator_balances"` - // unstaked_value_from_pod is the value unstaked from the pod. - UnstakedValueFromPod github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=unstaked_value_from_pod,json=unstakedValueFromPod,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"unstaked_value_from_pod"` - // pod_address is the pod address. - PodAddress string `protobuf:"bytes,3,opt,name=pod_address,json=podAddress,proto3" json:"pod_address,omitempty"` - // validators_info is the information about the validators, indexed by address. - ValidatorsInfo map[string]*ValidatorInfo `protobuf:"bytes,4,rep,name=validators_info,json=validatorsInfo,proto3" json:"validators_info,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` -} - -func (m *NativeTokenStakerInfo) Reset() { *m = NativeTokenStakerInfo{} } -func (m *NativeTokenStakerInfo) String() string { return proto.CompactTextString(m) } -func (*NativeTokenStakerInfo) ProtoMessage() {} -func (*NativeTokenStakerInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_769c53c072051eb9, []int{1} -} -func (m *NativeTokenStakerInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *NativeTokenStakerInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_NativeTokenStakerInfo.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *NativeTokenStakerInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_NativeTokenStakerInfo.Merge(m, src) -} -func (m *NativeTokenStakerInfo) XXX_Size() int { - return m.Size() -} -func (m *NativeTokenStakerInfo) XXX_DiscardUnknown() { - xxx_messageInfo_NativeTokenStakerInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_NativeTokenStakerInfo proto.InternalMessageInfo - -func (m *NativeTokenStakerInfo) GetPodAddress() string { - if m != nil { - return m.PodAddress - } - return "" -} - -func (m *NativeTokenStakerInfo) GetValidatorsInfo() map[string]*ValidatorInfo { - if m != nil { - return m.ValidatorsInfo - } - return nil -} - -func init() { - proto.RegisterEnum("exocore.native_token.v1.ValidatorInfo_ValidatorStatus", ValidatorInfo_ValidatorStatus_name, ValidatorInfo_ValidatorStatus_value) - proto.RegisterType((*ValidatorInfo)(nil), "exocore.native_token.v1.ValidatorInfo") - proto.RegisterType((*NativeTokenStakerInfo)(nil), "exocore.native_token.v1.NativeTokenStakerInfo") - proto.RegisterMapType((map[string]*ValidatorInfo)(nil), "exocore.native_token.v1.NativeTokenStakerInfo.ValidatorsInfoEntry") -} - -func init() { proto.RegisterFile("exocore/native_token/v1/tx.proto", fileDescriptor_769c53c072051eb9) } - -var fileDescriptor_769c53c072051eb9 = []byte{ - // 661 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0xcd, 0x4e, 0xdb, 0x4c, - 0x14, 0x8d, 0x93, 0x7c, 0x48, 0xdf, 0xa0, 0x42, 0x3a, 0x50, 0x62, 0xdc, 0x36, 0x58, 0x59, 0x40, - 0x36, 0x38, 0x82, 0xaa, 0xa8, 0x3f, 0x48, 0x55, 0x02, 0xa1, 0xb5, 0x54, 0xb9, 0xc8, 0x09, 0x41, - 0xea, 0x66, 0xe4, 0xc4, 0x43, 0x6a, 0x39, 0x99, 0x89, 0x3c, 0x13, 0x13, 0x96, 0xdd, 0x66, 0xd5, - 0x17, 0xc8, 0x5b, 0xf4, 0x21, 0xd8, 0x15, 0x75, 0x55, 0x75, 0x81, 0x2a, 0x78, 0x8e, 0x4a, 0x95, - 0x67, 0x1c, 0x92, 0x34, 0x20, 0x55, 0x62, 0x65, 0xcf, 0xbd, 0xe7, 0x9c, 0xb1, 0xcf, 0x9c, 0x3b, - 0x40, 0xc7, 0x7d, 0xda, 0xa4, 0x01, 0x2e, 0x12, 0x87, 0x7b, 0x21, 0x46, 0x9c, 0xfa, 0x98, 0x14, - 0xc3, 0xad, 0x22, 0xef, 0x1b, 0xdd, 0x80, 0x72, 0x0a, 0xb3, 0x31, 0xc2, 0x98, 0x44, 0x18, 0xe1, - 0x96, 0xb6, 0xda, 0xa4, 0xac, 0x43, 0x19, 0x12, 0xb0, 0xa2, 0x5c, 0x48, 0x8e, 0xb6, 0xdc, 0xa2, - 0x2d, 0x2a, 0xeb, 0xd1, 0x9b, 0xac, 0xe6, 0xbf, 0xa5, 0xc1, 0x83, 0xba, 0xd3, 0xf6, 0x5c, 0x87, - 0xd3, 0xc0, 0x24, 0x27, 0x14, 0x5a, 0x60, 0x8e, 0x71, 0x87, 0xf7, 0x98, 0xaa, 0xe8, 0x4a, 0x61, - 0x61, 0x7b, 0xc7, 0xb8, 0x63, 0x33, 0x63, 0x8a, 0x37, 0x5e, 0x55, 0x05, 0xdb, 0x8e, 0x55, 0xe0, - 0x06, 0x58, 0x0c, 0x47, 0x2d, 0xe4, 0x11, 0x17, 0xf7, 0xd5, 0xa4, 0xae, 0x14, 0xd2, 0xf6, 0x42, - 0x38, 0xe6, 0xbb, 0xb8, 0x0f, 0xdb, 0x60, 0x89, 0x71, 0xc7, 0xc7, 0x2e, 0x6a, 0x38, 0x6d, 0x87, - 0x34, 0x31, 0x6a, 0x9d, 0x62, 0x4f, 0x4d, 0xe9, 0x4a, 0xe1, 0xff, 0xf2, 0xee, 0xf9, 0xe5, 0x5a, - 0xe2, 0xe7, 0xe5, 0xda, 0x7a, 0xcb, 0xe3, 0x9f, 0x7a, 0x0d, 0xa3, 0x49, 0x3b, 0xf1, 0xef, 0xc5, - 0x8f, 0x4d, 0xe6, 0xfa, 0x45, 0x7e, 0xd6, 0xc5, 0xcc, 0x30, 0x09, 0xff, 0xfe, 0x75, 0x13, 0xc4, - 0x7f, 0x6f, 0x12, 0x6e, 0x3f, 0x94, 0xc2, 0x65, 0xa9, 0xfb, 0xf6, 0x14, 0x7b, 0xb0, 0x0a, 0x36, - 0x3a, 0x94, 0x71, 0x14, 0xe0, 0x26, 0x26, 0xfc, 0x66, 0xcb, 0x5e, 0xd7, 0x75, 0x38, 0x46, 0x8d, - 0x36, 0x6d, 0xfa, 0x88, 0xf4, 0x3a, 0x0d, 0x1c, 0xa8, 0x69, 0xf1, 0xb9, 0xf9, 0x08, 0x6e, 0x0b, - 0x74, 0xac, 0x73, 0x24, 0xb0, 0xe5, 0x08, 0x6a, 0x09, 0x64, 0xfe, 0x73, 0x12, 0x2c, 0xfe, 0xe5, - 0x03, 0x7c, 0x03, 0x9e, 0xd4, 0x4b, 0xef, 0xcd, 0xfd, 0x52, 0xed, 0x83, 0x8d, 0xaa, 0xb5, 0x52, - 0xed, 0xa8, 0x8a, 0x8e, 0xac, 0xea, 0x61, 0x65, 0xcf, 0x3c, 0x30, 0x2b, 0xfb, 0x99, 0x84, 0xf6, - 0x74, 0x30, 0xd4, 0x57, 0xa7, 0xcc, 0x9c, 0x04, 0xc0, 0xe7, 0x20, 0x3b, 0x23, 0x50, 0xda, 0xab, - 0x99, 0xf5, 0x4a, 0x46, 0xd1, 0xd4, 0xc1, 0x50, 0x5f, 0x9e, 0xe6, 0xca, 0x1e, 0x7c, 0x09, 0x56, - 0x67, 0x68, 0xa6, 0x15, 0x13, 0x93, 0x9a, 0x36, 0x18, 0xea, 0x2b, 0xd3, 0xc4, 0x51, 0x17, 0xbe, - 0x06, 0xda, 0x0c, 0xf5, 0xd8, 0xac, 0xbd, 0xdb, 0xb7, 0x4b, 0xc7, 0x56, 0x26, 0xa5, 0x3d, 0x1e, - 0x0c, 0xf5, 0xec, 0x34, 0xf7, 0xa6, 0x9d, 0xff, 0x9d, 0x02, 0x8f, 0x2c, 0x91, 0x94, 0x5a, 0x14, - 0x94, 0x6a, 0xe4, 0xbc, 0x4c, 0x56, 0x08, 0x54, 0x4e, 0xb9, 0xd3, 0x46, 0xe3, 0x3c, 0xc4, 0xb6, - 0xcb, 0xac, 0xdd, 0xf7, 0x94, 0x57, 0x84, 0xfa, 0xcd, 0x77, 0xc5, 0xa7, 0xc4, 0x20, 0x03, 0xd9, - 0x1e, 0x89, 0xa3, 0x15, 0x3a, 0xed, 0x1e, 0x46, 0x27, 0x01, 0xed, 0xa0, 0x2e, 0x75, 0x45, 0x12, - 0xef, 0xbb, 0xed, 0xf2, 0x48, 0xbc, 0x1e, 0x69, 0x1f, 0x04, 0xb4, 0x73, 0x48, 0x5d, 0xb8, 0x06, - 0xe6, 0xbb, 0xd4, 0x45, 0x8e, 0xeb, 0x06, 0x98, 0x31, 0x99, 0x62, 0x1b, 0x74, 0xa9, 0x5b, 0x92, - 0x15, 0xe8, 0x4f, 0xcc, 0x05, 0x43, 0x1e, 0x39, 0xa1, 0x6a, 0x5a, 0x4f, 0x15, 0xe6, 0xb7, 0xcb, - 0x77, 0x0e, 0xdc, 0xad, 0xb6, 0x8e, 0x07, 0x8f, 0x45, 0xcb, 0x0a, 0xe1, 0xc1, 0xd9, 0xc4, 0x6c, - 0x89, 0xa2, 0xe6, 0x81, 0xa5, 0x5b, 0x60, 0x30, 0x03, 0x52, 0x3e, 0x3e, 0x93, 0xe6, 0xdb, 0xd1, - 0x2b, 0xdc, 0x05, 0xff, 0x09, 0x8b, 0x84, 0x33, 0xf3, 0xdb, 0xeb, 0xff, 0x36, 0xfc, 0xb6, 0x24, - 0xbd, 0x4a, 0xbe, 0x50, 0xca, 0x87, 0xe7, 0x57, 0x39, 0xe5, 0xe2, 0x2a, 0xa7, 0xfc, 0xba, 0xca, - 0x29, 0x5f, 0xae, 0x73, 0x89, 0x8b, 0xeb, 0x5c, 0xe2, 0xc7, 0x75, 0x2e, 0xf1, 0x71, 0x67, 0xc2, - 0xde, 0x8a, 0x94, 0xb5, 0x30, 0x3f, 0xa5, 0x81, 0x5f, 0x1c, 0xdd, 0x78, 0xfd, 0xe9, 0x3b, 0x4f, - 0x58, 0xde, 0x98, 0x13, 0x57, 0xd5, 0xb3, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x92, 0xf9, 0xbe, - 0xe1, 0x18, 0x05, 0x00, 0x00, -} - -func (m *ValidatorInfo) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ValidatorInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.MostRecentBalanceUpdateBlockNumber != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.MostRecentBalanceUpdateBlockNumber)) - i-- - dAtA[i] = 0x20 - } - { - size := m.StakedBalanceGwei.Size() - i -= size - if _, err := m.StakedBalanceGwei.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.ValidatorIndex != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.ValidatorIndex)) - i-- - dAtA[i] = 0x10 - } - if m.Status != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Status)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *NativeTokenStakerInfo) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *NativeTokenStakerInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *NativeTokenStakerInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorsInfo) > 0 { - for k := range m.ValidatorsInfo { - v := m.ValidatorsInfo[k] - baseI := i - if v != nil { - { - size, err := v.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - i -= len(k) - copy(dAtA[i:], k) - i = encodeVarintTx(dAtA, i, uint64(len(k))) - i-- - dAtA[i] = 0xa - i = encodeVarintTx(dAtA, i, uint64(baseI-i)) - i-- - dAtA[i] = 0x22 - } - } - if len(m.PodAddress) > 0 { - i -= len(m.PodAddress) - copy(dAtA[i:], m.PodAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.PodAddress))) - i-- - dAtA[i] = 0x1a - } - { - size := m.UnstakedValueFromPod.Size() - i -= size - if _, err := m.UnstakedValueFromPod.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.TotalValidatorBalances.Size() - i -= size - if _, err := m.TotalValidatorBalances.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *ValidatorInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Status != 0 { - n += 1 + sovTx(uint64(m.Status)) - } - if m.ValidatorIndex != 0 { - n += 1 + sovTx(uint64(m.ValidatorIndex)) - } - l = m.StakedBalanceGwei.Size() - n += 1 + l + sovTx(uint64(l)) - if m.MostRecentBalanceUpdateBlockNumber != 0 { - n += 1 + sovTx(uint64(m.MostRecentBalanceUpdateBlockNumber)) - } - return n -} - -func (m *NativeTokenStakerInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TotalValidatorBalances.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.UnstakedValueFromPod.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.PodAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.ValidatorsInfo) > 0 { - for k, v := range m.ValidatorsInfo { - _ = k - _ = v - l = 0 - if v != nil { - l = v.Size() - l += 1 + sovTx(uint64(l)) - } - mapEntrySize := 1 + len(k) + sovTx(uint64(len(k))) + l - n += mapEntrySize + 1 + sovTx(uint64(mapEntrySize)) - } - } - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ValidatorInfo) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ValidatorInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) - } - m.Status = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Status |= ValidatorInfo_ValidatorStatus(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorIndex", wireType) - } - m.ValidatorIndex = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ValidatorIndex |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StakedBalanceGwei", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StakedBalanceGwei.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MostRecentBalanceUpdateBlockNumber", wireType) - } - m.MostRecentBalanceUpdateBlockNumber = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MostRecentBalanceUpdateBlockNumber |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *NativeTokenStakerInfo) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: NativeTokenStakerInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: NativeTokenStakerInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalValidatorBalances", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalValidatorBalances.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UnstakedValueFromPod", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.UnstakedValueFromPod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PodAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PodAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsInfo", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.ValidatorsInfo == nil { - m.ValidatorsInfo = make(map[string]*ValidatorInfo) - } - var mapkey string - var mapvalue *ValidatorInfo - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthTx - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthTx - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var mapmsglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - mapmsglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if mapmsglen < 0 { - return ErrInvalidLengthTx - } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { - return ErrInvalidLengthTx - } - if postmsgIndex > l { - return io.ErrUnexpectedEOF - } - mapvalue = &ValidatorInfo{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex - } else { - iNdEx = entryPreIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - m.ValidatorsInfo[mapkey] = mapvalue - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/operator/keeper/opt_test.go b/x/operator/keeper/opt_test.go index 3b2ea59ed..b878fb7d0 100644 --- a/x/operator/keeper/opt_test.go +++ b/x/operator/keeper/opt_test.go @@ -4,12 +4,13 @@ import ( "fmt" "strings" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" + abci "github.com/cometbft/cometbft/abci/types" sdkmath "cosmossdk.io/math" assetstypes "github.com/ExocoreNetwork/exocore/x/assets/types" delegationtype "github.com/ExocoreNetwork/exocore/x/delegation/types" - "github.com/ExocoreNetwork/exocore/x/deposit/keeper" operatorKeeper "github.com/ExocoreNetwork/exocore/x/operator/keeper" operatorTypes "github.com/ExocoreNetwork/exocore/x/operator/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -50,14 +51,14 @@ func (suite *OperatorTestSuite) prepareDeposit(assetAddr common.Address, amount suite.updatedAmountForOptIn = sdkmath.NewInt(20) suite.stakerID, suite.assetID = assetstypes.GetStakeIDAndAssetID(suite.clientChainLzID, suite.Address[:], suite.assetAddr[:]) // staking assets - depositParam := &keeper.DepositParams{ + depositParam := &assetskeeper.DepositWithdrawParams{ ClientChainLzID: suite.clientChainLzID, Action: assetstypes.Deposit, StakerAddress: suite.Address[:], OpAmount: suite.depositAmount, AssetsAddress: assetAddr[:], } - err := suite.App.DepositKeeper.Deposit(suite.Ctx, depositParam) + err := suite.App.AssetsKeeper.PerformDepositOrWithdraw(suite.Ctx, depositParam) suite.NoError(err) } diff --git a/x/oracle/keeper/common/expected_keepers.go b/x/oracle/keeper/common/expected_keepers.go index 7a3c91a29..36fc46be3 100644 --- a/x/oracle/keeper/common/expected_keepers.go +++ b/x/oracle/keeper/common/expected_keepers.go @@ -2,7 +2,8 @@ package common import ( "cosmossdk.io/math" - stakingkeeper "github.com/ExocoreNetwork/exocore/x/dogfood/keeper" + dogfoodkeeper "github.com/ExocoreNetwork/exocore/x/dogfood/keeper" + dogfoodtypes "github.com/ExocoreNetwork/exocore/x/dogfood/types" "github.com/ExocoreNetwork/exocore/x/oracle/types" abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -10,7 +11,7 @@ import ( ) type KeeperOracle interface { - KeeperStaking + KeeperDogfood GetParams(sdk.Context) types.Params @@ -34,11 +35,13 @@ type KeeperOracle interface { RemoveRecentMsg(sdk.Context, uint64) } -var _ KeeperStaking = stakingkeeper.Keeper{} +var _ KeeperDogfood = dogfoodkeeper.Keeper{} -type KeeperStaking interface { +type KeeperDogfood = interface { GetLastTotalPower(ctx sdk.Context) math.Int IterateBondedValidatorsByPower(ctx sdk.Context, fn func(index int64, validator stakingTypes.ValidatorI) (stop bool)) GetValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) (validator stakingTypes.Validator, found bool) + + GetAllExocoreValidators(ctx sdk.Context) (validators []dogfoodtypes.ExocoreValidator) } diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index f367e14de..443d365c5 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -20,7 +20,7 @@ type ( memKey storetypes.StoreKey paramstore paramtypes.Subspace authority string - common.KeeperStaking + common.KeeperDogfood } ) @@ -31,7 +31,7 @@ func NewKeeper( storeKey storetypes.StoreKey, memKey storetypes.StoreKey, ps paramtypes.Subspace, - sKeeper common.KeeperStaking, + sKeeper common.KeeperDogfood, ) Keeper { // set KeyTable if it has not already been set if !ps.HasKeyTable() { @@ -43,7 +43,7 @@ func NewKeeper( storeKey: storeKey, memKey: memKey, paramstore: ps, - KeeperStaking: sKeeper, + KeeperDogfood: sKeeper, } } diff --git a/x/oracle/keeper/msg_server_create_price_test.go b/x/oracle/keeper/msg_server_create_price_test.go index b806f8750..46a8d912e 100644 --- a/x/oracle/keeper/msg_server_create_price_test.go +++ b/x/oracle/keeper/msg_server_create_price_test.go @@ -4,6 +4,8 @@ import ( reflect "reflect" math "cosmossdk.io/math" + dogfoodkeeper "github.com/ExocoreNetwork/exocore/x/dogfood/keeper" + dogfoodtypes "github.com/ExocoreNetwork/exocore/x/dogfood/types" "github.com/ExocoreNetwork/exocore/x/oracle/keeper" "github.com/ExocoreNetwork/exocore/x/oracle/keeper/cache" "github.com/ExocoreNetwork/exocore/x/oracle/keeper/common" @@ -12,9 +14,6 @@ import ( . "github.com/agiledragon/gomonkey/v2" "github.com/cosmos/cosmos-sdk/testutil/mock" sdk "github.com/cosmos/cosmos-sdk/types" - stakingKeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - gomock "go.uber.org/mock/gomock" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -23,42 +22,45 @@ import ( //go:generate mockgen -destination mock_validator_test.go -package keeper_test github.com/cosmos/cosmos-sdk/x/staking/types ValidatorI var _ = Describe("MsgCreatePrice", func() { - var operator1, operator2, operator3 sdk.ValAddress + // var operator1, operator2, operator3 sdk.ValAddress + var consKey1, consKey2, consKey3 sdk.AccAddress var c *cache.Cache var p *Patches BeforeEach(func() { ks.Reset() Expect(ks.ms).ToNot(BeNil()) - validatorC := NewMockValidatorI(ks.ctrl) - - validatorC.EXPECT().GetConsensusPower(gomock.Any()).Return(int64(1)) - validatorC.EXPECT().GetConsensusPower(gomock.Any()).Return(int64(1)) - validatorC.EXPECT().GetConsensusPower(gomock.Any()).Return(int64(1)) - privVal1 := mock.NewPV() pubKey1, _ := privVal1.GetPubKey() - operator1 = sdk.ValAddress(pubKey1.Address()) + // operator1 = sdk.ValAddress(pubKey1.Address()) + consKey1 = sdk.AccAddress(pubKey1.Address()) privVal2 := mock.NewPV() pubKey2, _ := privVal2.GetPubKey() - operator2 = sdk.ValAddress(pubKey2.Address()) + consKey2 = sdk.AccAddress(pubKey2.Address()) privVal3 := mock.NewPV() pubKey3, _ := privVal3.GetPubKey() - operator3 = sdk.ValAddress(pubKey3.Address()) - - validatorC.EXPECT().GetOperator().Return(operator1) - validatorC.EXPECT().GetOperator().Return(operator2) - validatorC.EXPECT().GetOperator().Return(operator3) + consKey3 = sdk.AccAddress(pubKey3.Address()) // TODO: remove monkey patch for test - p = ApplyMethod(reflect.TypeOf(stakingKeeper.Keeper{}), "IterateBondedValidatorsByPower", func(k stakingKeeper.Keeper, ctx sdk.Context, f func(index int64, validator stakingtypes.ValidatorI) bool) { - f(0, validatorC) - f(0, validatorC) - f(0, validatorC) + p = ApplyMethod(reflect.TypeOf(dogfoodkeeper.Keeper{}), "GetLastTotalPower", func(k dogfoodkeeper.Keeper, ctx sdk.Context) math.Int { return math.NewInt(3) }) + p.ApplyMethod(reflect.TypeOf(dogfoodkeeper.Keeper{}), "GetAllExocoreValidators", func(k dogfoodkeeper.Keeper, ctx sdk.Context) []dogfoodtypes.ExocoreValidator { + return []dogfoodtypes.ExocoreValidator{ + { + Address: pubKey1.Address(), + Power: 1, + }, + { + Address: pubKey2.Address(), + Power: 1, + }, + { + Address: pubKey3.Address(), + Power: 1, + }, + } }) - p.ApplyMethod(reflect.TypeOf(stakingKeeper.Keeper{}), "GetLastTotalPower", func(k stakingKeeper.Keeper, ctx sdk.Context) math.Int { return math.NewInt(3) }) Expect(ks.ctx.BlockHeight()).To(Equal(int64(2))) }) @@ -73,7 +75,8 @@ var _ = Describe("MsgCreatePrice", func() { Context("3 validators with 1 voting power each", func() { BeforeEach(func() { ks.ms.CreatePrice(ks.ctx, &types.MsgCreatePrice{ - Creator: operator1.String(), + // Creator: operator1.String(), + Creator: consKey1.String(), FeederID: 1, Prices: testdata.PS1, BasedBlock: 1, @@ -91,10 +94,10 @@ var _ = Describe("MsgCreatePrice", func() { It("success on 3rd message", func() { iRes := make([]*cache.ItemM, 0) c.GetCache(&iRes) - Expect(iRes[0].Validator).Should(Equal(operator1.String())) + Expect(iRes[0].Validator).Should(Equal(consKey1.String())) ks.ms.CreatePrice(ks.ctx, &types.MsgCreatePrice{ - Creator: operator2.String(), + Creator: consKey2.String(), FeederID: 1, Prices: testdata.PS2, BasedBlock: 1, @@ -106,7 +109,7 @@ var _ = Describe("MsgCreatePrice", func() { Expect(len(iRes)).Should(Equal(2)) ks.ms.CreatePrice(ks.ctx, &types.MsgCreatePrice{ - Creator: operator3.String(), + Creator: consKey3.String(), FeederID: 1, Prices: testdata.PS4, BasedBlock: 1, diff --git a/x/oracle/keeper/single.go b/x/oracle/keeper/single.go index 927a55fb5..dccec0100 100644 --- a/x/oracle/keeper/single.go +++ b/x/oracle/keeper/single.go @@ -8,7 +8,6 @@ import ( "github.com/ExocoreNetwork/exocore/x/oracle/keeper/common" "github.com/ExocoreNetwork/exocore/x/oracle/types" sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var cs *cache.Cache @@ -77,17 +76,15 @@ func recacheAggregatorContext(ctx sdk.Context, agc *aggregator.AggregatorContext totalPower := big.NewInt(0) validatorPowers := make(map[string]*big.Int) - k.IterateBondedValidatorsByPower(ctx, func(_ int64, validator stakingtypes.ValidatorI) bool { - power := big.NewInt(validator.GetConsensusPower(sdk.DefaultPowerReduction)) - addr := validator.GetOperator().String() - validatorPowers[addr] = power - totalPower = new(big.Int).Add(totalPower, power) - return false - }) + validatorSet := k.GetAllExocoreValidators(ctx) + for _, v := range validatorSet { + validatorPowers[sdk.AccAddress(v.Address).String()] = big.NewInt(v.Power) + totalPower = new(big.Int).Add(totalPower, big.NewInt(v.Power)) + } agc.SetValidatorPowers(validatorPowers) // TODO: test only if k.GetLastTotalPower(ctx).BigInt().Cmp(totalPower) != 0 { - ctx.Logger().Error("something wrong when get validatorsPower from staking module") + ctx.Logger().Error("something wrong when get validatorsPower from dogfood module") } // reset validators @@ -157,15 +154,17 @@ func initAggregatorContext(ctx sdk.Context, agc *aggregator.AggregatorContext, k setCommonParams(p) totalPower := big.NewInt(0) validatorPowers := make(map[string]*big.Int) - k.IterateBondedValidatorsByPower(ctx, func(_ int64, validator stakingtypes.ValidatorI) bool { - power := big.NewInt(validator.GetConsensusPower(sdk.DefaultPowerReduction)) - addr := validator.GetOperator().String() - validatorPowers[addr] = power - totalPower = new(big.Int).Add(totalPower, power) - return false - }) - agc.SetValidatorPowers(validatorPowers) + validatorSet := k.GetAllExocoreValidators(ctx) + for _, v := range validatorSet { + validatorPowers[sdk.AccAddress(v.Address).String()] = big.NewInt(v.Power) + totalPower = new(big.Int).Add(totalPower, big.NewInt(v.Power)) + } + agc.SetValidatorPowers(validatorPowers) + // TODO: test only + if k.GetLastTotalPower(ctx).BigInt().Cmp(totalPower) != 0 { + ctx.Logger().Error("something wrong when get validatorsPower from dogfood module") + } // set validatorPower cache c.AddCache(cache.ItemV(validatorPowers)) diff --git a/x/oracle/types/message_create_price.go b/x/oracle/types/message_create_price.go index 0ce3452af..9a98da606 100644 --- a/x/oracle/types/message_create_price.go +++ b/x/oracle/types/message_create_price.go @@ -29,11 +29,11 @@ func (msg *MsgCreatePrice) Type() string { } func (msg *MsgCreatePrice) GetSigners() []sdk.AccAddress { - creator, err := sdk.ValAddressFromBech32(msg.Creator) + creator, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { panic(err) } - return []sdk.AccAddress{sdk.AccAddress(creator)} + return []sdk.AccAddress{creator} } func (msg *MsgCreatePrice) GetSignBytes() []byte { @@ -42,7 +42,7 @@ func (msg *MsgCreatePrice) GetSignBytes() []byte { } func (msg *MsgCreatePrice) ValidateBasic() error { - _, err := sdk.ValAddressFromBech32(msg.Creator) + _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid creator address (%s)", err) } diff --git a/x/oracle/types/message_create_price_test.go b/x/oracle/types/message_create_price_test.go index 705b710f9..8b53e6aeb 100644 --- a/x/oracle/types/message_create_price_test.go +++ b/x/oracle/types/message_create_price_test.go @@ -25,7 +25,7 @@ func TestMsgCreatePrice_ValidateBasic(t *testing.T) { }, { name: "valid address", msg: MsgCreatePrice{ - Creator: sample.ValAddress(), + Creator: sample.AccAddress(), }, }, } diff --git a/x/slash/keeper/execute_slash_test.go b/x/slash/keeper/execute_slash_test.go index 775167cc3..e642dea7b 100644 --- a/x/slash/keeper/execute_slash_test.go +++ b/x/slash/keeper/execute_slash_test.go @@ -2,8 +2,8 @@ package keeper_test import ( sdkmath "cosmossdk.io/math" + assetskeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" "github.com/ExocoreNetwork/exocore/x/assets/types" - depositKeeper "github.com/ExocoreNetwork/exocore/x/deposit/keeper" "github.com/ExocoreNetwork/exocore/x/slash/keeper" slashtype "github.com/ExocoreNetwork/exocore/x/slash/types" "github.com/ethereum/go-ethereum/common" @@ -19,7 +19,7 @@ func (suite *SlashTestSuite) TestSlash() { OpAmount: sdkmath.NewInt(90), } - depositEvent := &depositKeeper.DepositParams{ + depositEvent := &assetskeeper.DepositWithdrawParams{ ClientChainLzID: 101, Action: types.Deposit, StakerAddress: suite.Address[:], @@ -32,7 +32,7 @@ func (suite *SlashTestSuite) TestSlash() { // deposit firstly depositEvent.AssetsAddress = usdtAddress[:] - err = suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) + err = suite.App.AssetsKeeper.PerformDepositOrWithdraw(suite.Ctx, depositEvent) suite.NoError(err) // test the case that the slash hasn't registered diff --git a/x/withdraw/client/cli/query.go b/x/withdraw/client/cli/query.go deleted file mode 100644 index 523254dd8..000000000 --- a/x/withdraw/client/cli/query.go +++ /dev/null @@ -1,30 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - // "github.com/cosmos/cosmos-sdk/client/flags" - // sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/ExocoreNetwork/exocore/x/withdraw/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(string) *cobra.Command { - // Group withdraw queries under a subcommand - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand() - // this line is used by starport scaffolding # 1 - - return cmd -} diff --git a/x/withdraw/client/cli/tx.go b/x/withdraw/client/cli/tx.go deleted file mode 100644 index ac1e77b6a..000000000 --- a/x/withdraw/client/cli/tx.go +++ /dev/null @@ -1,25 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/ExocoreNetwork/exocore/x/withdraw/types" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand() - return cmd -} diff --git a/x/withdraw/keeper/claim_withdraw.go b/x/withdraw/keeper/claim_withdraw.go deleted file mode 100644 index b1b6d5a8f..000000000 --- a/x/withdraw/keeper/claim_withdraw.go +++ /dev/null @@ -1,143 +0,0 @@ -package keeper - -import ( - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - "github.com/ExocoreNetwork/exocore/x/assets/types" - withdrawtype "github.com/ExocoreNetwork/exocore/x/withdraw/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common/hexutil" -) - -type WithdrawParams struct { - ClientChainLzID uint64 - Action types.CrossChainOpType - AssetsAddress []byte - WithdrawAddress []byte - OpAmount sdkmath.Int -} - -// func getWithdrawParamsFromEventLog(log *ethtypes.Log) (*WithdrawParams, error) { -// // check if action is withdraw -// var action types.CrossChainOpType -// var err error -// readStart := 0 -// readEnd := types.CrossChainActionLength -// r := bytes.NewReader(log.Data[readStart:readEnd]) -// err = binary.Read(r, binary.BigEndian, &action) -// if err != nil { -// return nil, errorsmod.Wrap(err, "error occurred when binary read action") -// } -// if action != types.WithdrawPrinciple { -// // not handle the actions that isn't withdraw -// return nil, nil -// } - -// //decode the action parameters -// readStart = readEnd -// readEnd += types.GeneralAssetsAddrLength -// r = bytes.NewReader(log.Data[readStart:readEnd]) -// var assetsAddress []byte -// err = binary.Read(r, binary.BigEndian, assetsAddress) -// if err != nil { -// return nil, errorsmod.Wrap(err, "error occurred when binary read assets address") -// } - -// readStart = readEnd -// readEnd += types.GeneralClientChainAddrLength -// r = bytes.NewReader(log.Data[readStart:readEnd]) -// var withdrawAddress []byte -// err = binary.Read(r, binary.BigEndian, withdrawAddress) -// if err != nil { -// return nil, errorsmod.Wrap(err, "error occurred when binary read assets address") -// } - -// readStart = readEnd -// readEnd += types.CrossChainOpAmountLength -// amount := sdkmath.NewIntFromBigInt(big.NewInt(0).SetBytes(log.Data[readStart:readEnd])) - -// var clientChainLzID uint64 -// r = bytes.NewReader(log.Topics[types.ClientChainLzIDIndexInTopics][:]) -// err = binary.Read(r, binary.BigEndian, &clientChainLzID) -// if err != nil { -// return nil, errorsmod.Wrap(err, "error occurred when binary read clientChainLzID from topic") -// } - -// return &WithdrawParams{ -// ClientChainLzID: clientChainLzID, -// Action: action, -// AssetsAddress: assetsAddress, -// WithdrawAddress: withdrawAddress, -// OpAmount: amount, -// }, nil -// } - -func getStakeIDAndAssetID(params *WithdrawParams) (stakeID string, assetID string) { - clientChainLzIDStr := hexutil.EncodeUint64(params.ClientChainLzID) - stakeID = strings.Join([]string{hexutil.Encode(params.WithdrawAddress), clientChainLzIDStr}, "_") - assetID = strings.Join([]string{hexutil.Encode(params.AssetsAddress), clientChainLzIDStr}, "_") - return -} - -// Be supported by precompiled way -// func (k Keeper) PostTxProcessing(ctx sdk.Context, msg core.Message, receipt *ethtypes.Receipt) error { -// //TODO check if contract address is valid layerZero relayer address -// //check if log address and topicId is valid -// params, err := k.GetParams(ctx) -// if err != nil { -// return err -// } -// //filter needed logs -// addresses := []common.Address{common.HexToAddress(params.ExoCoreLzAppAddress)} -// topics := [][]common.Hash{ -// {common.HexToHash(params.ExoCoreLzAppEventTopic)}, -// } -// needLogs := filters.FilterLogs(receipt.Logs, nil, nil, addresses, topics) -// if len(needLogs) == 0 { -// log.Println("the hook message doesn't have any event needed to handle") -// return nil -// } - -// for _, log := range needLogs { -// withdrawParams, err := getWithdrawParamsFromEventLog(log) -// if err != nil { -// return err -// } -// if withdrawParams != nil { -// err = k.Withdraw(ctx, withdrawParams) -// if err != nil { -// // todo: need to test if the changed storage state will be reverted if there is an error occurred -// return err -// } -// } -// } -// return nil -// } - -func (k Keeper) Withdraw(ctx sdk.Context, params *WithdrawParams) error { - // check event parameter then execute deposit operation - if params.OpAmount.IsNegative() { - return errorsmod.Wrap(withdrawtype.ErrWithdrawAmountIsNegative, fmt.Sprintf("the amount is:%s", params.OpAmount)) - } - stakeID, assetID := getStakeIDAndAssetID(params) - - // check if asset exist - if !k.assetsKeeper.IsStakingAsset(ctx, assetID) { - return errorsmod.Wrap(withdrawtype.ErrWithdrawAssetNotExist, fmt.Sprintf("the assetID is:%s", assetID)) - } - changeAmount := types.DeltaStakerSingleAsset{ - TotalDepositAmount: params.OpAmount.Neg(), - WithdrawableAmount: params.OpAmount.Neg(), - } - err := k.assetsKeeper.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount) - if err != nil { - return err - } - if err = k.assetsKeeper.UpdateStakingAssetTotalAmount(ctx, assetID, params.OpAmount.Neg()); err != nil { - return err - } - return nil -} diff --git a/x/withdraw/keeper/claim_withdraw_test.go b/x/withdraw/keeper/claim_withdraw_test.go deleted file mode 100644 index d454a2b8a..000000000 --- a/x/withdraw/keeper/claim_withdraw_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - "github.com/ExocoreNetwork/exocore/x/assets/types" - depositKeeper "github.com/ExocoreNetwork/exocore/x/deposit/keeper" - "github.com/ExocoreNetwork/exocore/x/withdraw/keeper" - withdrawtype "github.com/ExocoreNetwork/exocore/x/withdraw/types" - "github.com/ethereum/go-ethereum/common" -) - -func (suite *WithdrawTestSuite) TestClaimWithdrawRequest() { - usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") - usdcAddress := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") - event := &keeper.WithdrawParams{ - ClientChainLzID: 101, - Action: types.WithdrawPrinciple, - WithdrawAddress: suite.Address[:], - OpAmount: sdkmath.NewInt(90), - } - - depositEvent := &depositKeeper.DepositParams{ - ClientChainLzID: 101, - Action: types.Deposit, - StakerAddress: suite.Address[:], - OpAmount: sdkmath.NewInt(100), - } - - assets, err := suite.App.AssetsKeeper.GetAllStakingAssetsInfo(suite.Ctx) - suite.NoError(err) - suite.App.Logger().Info("the assets is:", "assets", assets) - - // deposit firstly - depositEvent.AssetsAddress = usdtAddress[:] - err = suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) - suite.NoError(err) - - // test the case that the withdraw asset hasn't registered - event.AssetsAddress = usdcAddress[:] - err = suite.App.WithdrawKeeper.Withdraw(suite.Ctx, event) - suite.ErrorContains(err, withdrawtype.ErrWithdrawAssetNotExist.Error()) - - stakerID, assetID := types.GetStakeIDAndAssetID(depositEvent.ClientChainLzID, depositEvent.StakerAddress, depositEvent.AssetsAddress) - info, err := suite.App.AssetsKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) - suite.NoError(err) - suite.Equal(types.StakerAssetInfo{ - TotalDepositAmount: depositEvent.OpAmount, - WithdrawableAmount: depositEvent.OpAmount, - WaitUnbondingAmount: sdkmath.NewInt(0), - }, *info) - // test the normal case - event.AssetsAddress = usdtAddress[:] - err = suite.App.WithdrawKeeper.Withdraw(suite.Ctx, event) - suite.NoError(err) - - // check state after withdraw - stakerID, assetID = types.GetStakeIDAndAssetID(event.ClientChainLzID, event.WithdrawAddress, event.AssetsAddress) - info, err = suite.App.AssetsKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) - suite.NoError(err) - suite.Equal(types.StakerAssetInfo{ - TotalDepositAmount: sdkmath.NewInt(10), - WithdrawableAmount: sdkmath.NewInt(10), - WaitUnbondingAmount: sdkmath.NewInt(0), - }, *info) - - assetInfo, err := suite.App.AssetsKeeper.GetStakingAssetInfo(suite.Ctx, assetID) - suite.NoError(err) - suite.Equal(assets[assetID].StakingTotalAmount.Add(depositEvent.OpAmount).Sub(event.OpAmount), assetInfo.StakingTotalAmount) -} diff --git a/x/withdraw/keeper/keeper.go b/x/withdraw/keeper/keeper.go deleted file mode 100644 index 7f9d1930f..000000000 --- a/x/withdraw/keeper/keeper.go +++ /dev/null @@ -1,42 +0,0 @@ -package keeper - -import ( - "fmt" - - restakingkeeper "github.com/ExocoreNetwork/exocore/x/assets/keeper" - depositkeeper "github.com/ExocoreNetwork/exocore/x/deposit/keeper" - "github.com/ExocoreNetwork/exocore/x/withdraw/types" - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type ( - Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - - // restaking keepers for asset status update - assetsKeeper restakingkeeper.Keeper - depositKeeper depositkeeper.Keeper - } -) - -func NewKeeper( - cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, - assetsKeeper restakingkeeper.Keeper, - depositKeeper depositkeeper.Keeper, -) Keeper { - return Keeper{ - cdc: cdc, - storeKey: storeKey, - assetsKeeper: assetsKeeper, - depositKeeper: depositKeeper, - } -} - -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} diff --git a/x/withdraw/keeper/setup_test.go b/x/withdraw/keeper/setup_test.go deleted file mode 100644 index fe9eb12e1..000000000 --- a/x/withdraw/keeper/setup_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/ExocoreNetwork/exocore/testutil" - - "github.com/stretchr/testify/suite" -) - -type WithdrawTestSuite struct { - testutil.BaseTestSuite -} - -var s *WithdrawTestSuite - -func TestKeeperTestSuite(t *testing.T) { - s = new(WithdrawTestSuite) - suite.Run(t, s) -} - -// SetupTest setup test environment, it uses`require.TestingT` to support both `testing.T` and `testing.B`. -func (suite *WithdrawTestSuite) SetupTest() { - suite.DoSetupTest() -} diff --git a/x/withdraw/module.go b/x/withdraw/module.go deleted file mode 100644 index 5b28f8ba2..000000000 --- a/x/withdraw/module.go +++ /dev/null @@ -1,122 +0,0 @@ -package withdraw - -import ( - // this line is used by starport scaffolding # 1 - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/ExocoreNetwork/exocore/x/withdraw/keeper" - - "github.com/ExocoreNetwork/exocore/x/withdraw/types" - - "github.com/ExocoreNetwork/exocore/x/withdraw/client/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -// AppModuleBasic implements the AppModuleBasic interface that defines the independent methods a Cosmos SDK module needs to implement. -type AppModuleBasic struct { - cdc codec.BinaryCodec -} - -func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} -} - -// Name returns the name of the module as a string -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec registers the amino codec for the module, which is used to marshal and unmarshal structs to/from []byte in order to persist them in the module's KVStore -func (AppModuleBasic) RegisterLegacyAminoCodec(_ *codec.LegacyAmino) {} - -// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message -func (a AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module -func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *runtime.ServeMux) {} - -// GetTxCmd returns the root Tx command for the module. The subcommands of this root command are used by end-users to generate new transactions containing messages defined in the module -func (a AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns the root query command for the module. The subcommands of this root command are used by end-users to generate new queries to the subset of the state defined by the module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(types.StoreKey) -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -func NewAppModule( - cdc codec.Codec, - keeper keeper.Keeper, -) AppModule { - return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), - keeper: keeper, - } -} - -// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries -func (am AppModule) RegisterServices(_ module.Configurator) { - // types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - // types.RegisterQueryServer(cfg.QueryServer(), am.keeper) -} - -// RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted) -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// // InitGenesis performs the module's genesis initialization. It returns no validator updates. -// func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { -// var genState types.GenesisState -// // Initialize global index to index in genesis state -// cdc.MustUnmarshalJSON(gs, &genState) - -// InitGenesis(ctx, am.keeper, genState) - -// return []abci.ValidatorUpdate{} -// } - -// // ExportGenesis returns the module's exported genesis state as raw JSON bytes. -// func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { -// genState := ExportGenesis(ctx, am.keeper) -// return cdc.MustMarshalJSON(genState) -// } - -// ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1 -func (AppModule) ConsensusVersion() uint64 { return 1 } - -// BeginBlock contains the logic that is automatically triggered at the beginning of each block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock contains the logic that is automatically triggered at the end of each block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/withdraw/types/errors.go b/x/withdraw/types/errors.go deleted file mode 100644 index 503ffe80f..000000000 --- a/x/withdraw/types/errors.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -// DONTCOVER - -import ( - errorsmod "cosmossdk.io/errors" -) - -// x/withdraw module sentinel errors -var ( - ErrSample = errorsmod.Register(ModuleName, 1100, "sample error") - ErrInvalidEvmAddressFormat = errorsmod.Register(ModuleName, 0, "the evm address format is error") - ErrInvalidLzUaTopicIDLength = errorsmod.Register(ModuleName, 1, "the LZUaTopicID length isn't equal to HashLength") - ErrNoParamsKey = errorsmod.Register(ModuleName, 2, "there is no stored key for params") - ErrWithdrawAmountIsNegative = errorsmod.Register(ModuleName, 3, "the withdraw amount is negative") - ErrWithdrawAssetNotExist = errorsmod.Register(ModuleName, 4, "the withdraw asset doesn't exist") -) diff --git a/x/withdraw/types/expected_keepers.go b/x/withdraw/types/expected_keepers.go deleted file mode 100644 index 6aa6e9778..000000000 --- a/x/withdraw/types/expected_keepers.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// AccountKeeper defines the expected account keeper used for simulations (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - // Methods imported from account should be defined here -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - // Methods imported from bank should be defined here -} diff --git a/x/withdraw/types/keys.go b/x/withdraw/types/keys.go deleted file mode 100644 index 4542e2e6d..000000000 --- a/x/withdraw/types/keys.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -const ( - // ModuleName defines the module name - ModuleName = "withdraw" - - // StoreKey defines the primary module store key - StoreKey = ModuleName - - // RouterKey defines the module's message routing key - RouterKey = ModuleName -) - -func KeyPrefix(p string) []byte { - return []byte(p) -} - -const ( - prefixParams = iota + 1 -) - -var ( - ParamsKey = []byte("WithdrawParams") - KeyPrefixParams = []byte{prefixParams} -)